max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,647 | #ifndef PYTHONIC_BUILTIN_OPEN_HPP
#define PYTHONIC_BUILTIN_OPEN_HPP
#include "pythonic/include/builtins/open.hpp"
#include "pythonic/types/file.hpp"
#include "pythonic/types/str.hpp"
#include "pythonic/utils/functor.hpp"
PYTHONIC_NS_BEGIN
namespace builtins
{
types::file open(types::str const &filename, types::str const &strmode)
{
return {filename, strmode};
}
}
PYTHONIC_NS_END
#endif
| 177 |
381 | <filename>jgiven-core/src/test/java/com/tngtech/jgiven/report/ReportGeneratorArgumentTest.java
package com.tngtech.jgiven.report;
import java.io.File;
import com.tngtech.jgiven.report.asciidoc.AsciiDocReportConfig;
import com.tngtech.jgiven.report.asciidoc.AsciiDocReportGenerator;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class ReportGeneratorArgumentTest {
@Test
public void testArgumentParsing() {
AsciiDocReportGenerator asciiReport = new AsciiDocReportGenerator();
asciiReport.setConfig( asciiReport.createReportConfig( "--sourceDir=source/dir", "--targetDir=target/dir" ) );
Assertions.assertThat( asciiReport.config.getSourceDir() ).isEqualTo( new File( "source/dir" ) );
Assertions.assertThat( asciiReport.config.getTargetDir() ).isEqualTo( new File( "target/dir" ) );
}
}
| 328 |
453 | <gh_stars>100-1000
/* Various stuff for the sparclet processor.
This file is in the public domain. */
#ifndef _MACHINE_SPARCLET_H_
#define _MACHINE_SPARCLET_H_
#ifdef __sparclet__
/* sparclet scan instruction */
extern __inline__ int
scan (int a, int b)
{
int res;
__asm__ ("scan %1,%2,%0" : "=r" (res) : "r" (a), "r" (b));
return res;
}
/* sparclet shuffle instruction */
extern __inline__ int
shuffle (int a, int b)
{
int res;
__asm__ ("shuffle %1,%2,%0" : "=r" (res) : "r" (a), "r" (b));
return res;
}
#endif /* __sparclet__ */
#endif /* _MACHINE_SPARCLET_H_ */
| 260 |
1,353 | /*
* Copyright (c) 2011, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.metadata.jpeg;
/**
* JPEG
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author last modified by $Author: haraldk$
* @version $Id: JPEG.java,v 1.0 11.02.11 15.51 haraldk Exp$
*/
public interface JPEG {
/** Start of Image segment marker (SOI). */
int SOI = 0xFFD8;
/** End of Image segment marker (EOI). */
int EOI = 0xFFD9;
/** Start of Scan segment marker (SOS). */
int SOS = 0xFFDA;
/** Define Quantization Tables segment marker (DQT). */
int DQT = 0xFFDB;
/** Define Huffman Tables segment marker (DHT). */
int DHT = 0xFFC4;
/** Comment (COM) */
int COM = 0xFFFE;
/** Define Number of Lines (DNL). */
int DNL = 0xFFDC;
/** Define Restart Interval (DRI). */
int DRI = 0xFFDD;
/** Define Hierarchical Progression (DHP). */
int DHP = 0xFFDE;
/** Expand reference components (EXP). */
int EXP = 0xFFDF;
/** Temporary use in arithmetic coding (TEM). */
int TEM = 0xFF01;
/** Define Define Arithmetic Coding conditioning (DAC). */
int DAC = 0xFFCC;
// App segment markers (APPn).
int APP0 = 0xFFE0;
int APP1 = 0xFFE1;
int APP2 = 0xFFE2;
int APP3 = 0xFFE3;
int APP4 = 0xFFE4;
int APP5 = 0xFFE5;
int APP6 = 0xFFE6;
int APP7 = 0xFFE7;
int APP8 = 0xFFE8;
int APP9 = 0xFFE9;
int APP10 = 0xFFEA;
int APP11 = 0xFFEB;
int APP12 = 0xFFEC;
int APP13 = 0xFFED;
int APP14 = 0xFFEE;
int APP15 = 0xFFEF;
// Start of Frame segment markers (SOFn).
/** SOF0: Baseline DCT, Huffman coding. */
int SOF0 = 0xFFC0;
/** SOF0: Extended DCT, Huffman coding. */
int SOF1 = 0xFFC1;
/** SOF2: Progressive DCT, Huffman coding. */
int SOF2 = 0xFFC2;
/** SOF3: Lossless sequential, Huffman coding. */
int SOF3 = 0xFFC3;
/** SOF5: Sequential DCT, differential Huffman coding. */
int SOF5 = 0xFFC5;
/** SOF6: Progressive DCT, differential Huffman coding. */
int SOF6 = 0xFFC6;
/** SOF7: Lossless, Differential Huffman coding. */
int SOF7 = 0xFFC7;
/** SOF9: Extended sequential DCT, arithmetic coding. */
int SOF9 = 0xFFC9;
/** SOF10: Progressive DCT, arithmetic coding. */
int SOF10 = 0xFFCA;
/** SOF11: Lossless sequential, arithmetic coding. */
int SOF11 = 0xFFCB;
/** SOF13: Sequential DCT, differential arithmetic coding. */
int SOF13 = 0xFFCD;
/** SOF14: Progressive DCT, differential arithmetic coding. */
int SOF14 = 0xFFCE;
/** SOF15: Lossless, differential arithmetic coding. */
int SOF15 = 0xFFCF;
// JPEG-LS markers
/** SOF55: JPEG-LS. */
int SOF55 = 0xFFF7; // NOTE: Equal to a normal SOF segment
int LSE = 0xFFF8; // JPEG-LS Preset Parameter marker
// TODO: Known/Important APPn marker identifiers
// "JFIF" APP0
// "JFXX" APP0
// "Exif" APP1
// "ICC_PROFILE" APP2
// "Adobe" APP14
// Possibly
// "http://ns.adobe.com/xap/1.0/" (XMP) APP1
// "Photoshop 3.0" (may contain IPTC) APP13
}
| 1,744 |
4,303 | #include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <set>
#include <string>
std::set<std::string> done;
void dump_header(const std::string &header) {
if (done.find(header) != done.end()) {
return;
}
done.insert(header);
if (header.find("runtime_internal") != std::string::npos) {
fprintf(stdout, "#error \"COMPILING_HALIDE_RUNTIME should never be defined for Halide.h\"\n");
return;
}
FILE *f = fopen(header.c_str(), "r");
if (f == nullptr) {
fprintf(stderr, "Could not open header %s.\n", header.c_str());
exit(1);
}
char line[1024];
const int line_len = sizeof(line);
const char include_str[] = "#include \"";
const int include_str_len = sizeof(include_str) - 1; // remove null terminator
while (fgets(line, line_len, f)) {
if (strncmp(line, include_str, include_str_len) == 0) {
char *sub_header = line + include_str_len;
for (int i = 0; i < line_len - include_str_len; i++) {
if (sub_header[i] == '"') {
sub_header[i] = 0;
}
}
size_t slash_pos = header.rfind('/');
std::string path;
if (slash_pos != std::string::npos) {
path = header.substr(0, slash_pos + 1);
}
dump_header(path + sub_header);
} else {
fputs(line, stdout);
}
}
fclose(f);
}
int main(int argc, char **files) {
if (argc < 3) {
fprintf(stderr, "Usage: %s LICENSE.txt [headers...]\n", files[0]);
exit(1);
}
fprintf(stdout, "/* Halide.h -- interface for the 'Halide' library.\n\n");
{
FILE *f = fopen(files[1], "r");
if (f == nullptr) {
fprintf(stderr, "Could not open %s.\n", files[1]);
exit(1);
}
char line[1024];
while (fgets(line, sizeof(line), f)) {
fprintf(stdout, " %s", line);
}
fclose(f);
}
fprintf(stdout, "\n*/\n\n");
fprintf(stdout, "#ifndef HALIDE_H\n");
fprintf(stdout, "#define HALIDE_H\n\n");
for (int i = 2; i < argc; i++) {
dump_header(files[i]);
}
fprintf(stdout, "\n");
fprintf(stdout,
"// Clean up macros used inside Halide headers\n"
"#undef user_assert\n"
"#undef user_error\n"
"#undef user_warning\n"
"#undef internal_error\n"
"#undef internal_assert\n"
"#undef halide_runtime_error\n"
"#endif // HALIDE_H\n");
return 0;
}
| 1,447 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/ScreenReaderCore.framework/ScreenReaderCore
*/
#import <ScreenReaderCore/ScreenReaderCore-Structs.h>
#import <ScreenReaderCore/XXUnknownSuperclass.h>
@interface SCRCStackQueue : XXUnknownSuperclass {
SCRCStackNode *_firstNode; // 4 = 0x4
SCRCStackNode *_lastNode; // 8 = 0x8
unsigned _count; // 12 = 0xc
}
@property(readonly, assign) unsigned count; // G=0x45ed; converted property
- (void)dealloc; // 0x3429
- (void)removeAllObjects; // 0x3469
- (void)pushArray:(id)array; // 0x4681
- (void)pushObject:(id)object; // 0x2159
- (id)popObject; // 0x119b9
- (id)popObjectRetained; // 0x4611
- (id)topObject; // 0x45fd
- (void)enqueueObject:(id)object; // 0x2149
- (id)dequeueObjectRetained; // 0x24f1
- (id)dequeueObject; // 0x119e1
// converted property getter: - (unsigned)count; // 0x45ed
- (id)description; // 0x11a09
- (id)objectEnumerator; // 0x4369
- (BOOL)isEmpty; // 0x2585
@end
| 395 |
325 | <gh_stars>100-1000
/**
* Copyright 2020 <NAME>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* <p>
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.github.btkelly.gandalf.checker;
import androidx.annotation.NonNull;
import io.github.btkelly.gandalf.models.Alert;
import io.github.btkelly.gandalf.models.AppVersionDetails;
import io.github.btkelly.gandalf.models.BootstrapException;
import io.github.btkelly.gandalf.models.OptionalUpdate;
import io.github.btkelly.gandalf.models.RequiredUpdate;
import io.github.btkelly.gandalf.utils.StringUtils;
/**
* Default implementation of {@link VersionChecker}.
*/
public class DefaultVersionChecker implements VersionChecker {
/**
* Checks provided {@link RequiredUpdate} against {@link AppVersionDetails} of the currently installed
* app.
*
* @param requiredUpdate current required version information
* @param appVersionDetails details about the current version of the install app
* @return {@code true} if app's version is less than the required version
*/
@Override
public boolean showRequiredUpdate(@NonNull final RequiredUpdate requiredUpdate, @NonNull final AppVersionDetails appVersionDetails) {
final String minimumVersionString = requiredUpdate.getMinimumVersion();
if (StringUtils.isBlank(minimumVersionString)) {
return false;
}
try {
final Integer minimumVersion = Integer.valueOf(minimumVersionString);
return appVersionDetails.getVersionCode() < minimumVersion;
} catch (NumberFormatException e) {
throw new BootstrapException("Invalid number format on RequiredUpdate version", e);
}
}
/**
* Checks provided {@link OptionalUpdate} against {@link AppVersionDetails} of the currently installed
* app.
*
* @param optionalUpdate current optional version information
* @param appVersionDetails details about the current version of the installed app
* @return {@code true} if app's version is behind the optional version
*/
@Override
public boolean showOptionalUpdate(@NonNull final OptionalUpdate optionalUpdate, @NonNull final AppVersionDetails appVersionDetails) {
final String optionalVersionString = optionalUpdate.getOptionalVersion();
if (StringUtils.isBlank(optionalVersionString)) {
return false;
}
try {
final Integer optionalVersionCode = Integer.valueOf(optionalVersionString);
return appVersionDetails.getVersionCode() < optionalVersionCode;
} catch (NumberFormatException e) {
throw new BootstrapException("Invalid number format on OptionalUpdate version", e);
}
}
/**
* Checks provided {@link Alert}.
*
* @param alert current alert information
* @return {@code true} if alert should block
*/
@Override
public boolean showAlert(@NonNull final Alert alert) {
final String message = alert.getMessage();
return !StringUtils.isBlank(message) && alert.isBlocking();
}
}
| 1,149 |
675 | #pragma once
#include <string>
#include "engine/core/base/echo_def.h"
namespace Echo
{
// remember call trace stack
i32 StackTrace(void **callstack, i32 maxStackDepth);
// get trace info
std::string StackTraceDesc(void **callstack, int maxStackDepth, int stackDepth, int skip = 1);
}
| 112 |
930 | package com.uwsoft.editor.view.ui.dialog;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import com.commons.UIDraggablePanel;
import com.kotcrab.vis.ui.widget.*;
import com.uwsoft.editor.Overlap2DFacade;
import com.uwsoft.editor.utils.StandardWidgetsFactory;
import java.util.HashSet;
import java.util.Set;
/**
* Created by azakhary on 8/1/2015.
*/
public class TagsDialog extends UIDraggablePanel {
public static final String prefix = "com.uwsoft.editor.view.ui.dialog.panels.TagsDialog";
public static final String LIST_CHANGED = prefix + ".LIST_CHANGED";
private Overlap2DFacade facade;
private VisTable mainTable;
private VisTable tagTable;
private TagItem.TagItemListener tagItemListener;
private Set<String> tags = new HashSet<>();
public TagsDialog() {
super("Tags");
addCloseButton();
facade = Overlap2DFacade.getInstance();
mainTable = new VisTable();
add(mainTable).padBottom(4);
tagItemListener = new TagItem.TagItemListener() {
@Override
public void removed(String tag) {
tags.remove(tag);
facade.sendNotification(LIST_CHANGED);
}
};
}
public void setEmpty() {
mainTable.clear();
VisLabel label = StandardWidgetsFactory.createLabel("No item selected");
label.setAlignment(Align.center);
mainTable.add(label).pad(10).width(278).center();
invalidateHeight();
}
private void addTag(String tag) {
tags.add(tag);
}
public void setTags(Set<String> tags) {
this.tags = tags;
}
public void updateView() {
mainTable.clear();
tagTable = new VisTable();
VisTable inputTable = new VisTable();
for(String tag: tags) {
tagTable.add(new TagItem(tag, tagItemListener)).pad(5).left().expandX().fillX();
tagTable.row();
}
VisTextField newTagField = StandardWidgetsFactory.createTextField();
VisTextButton createTagBtn = new VisTextButton("add");
inputTable.add(newTagField).width(200);
inputTable.add(createTagBtn).padLeft(5);
createTagBtn.addListener(new ClickListener() {
@Override
public void clicked (InputEvent event, float x, float y) {
String tag = newTagField.getText();
if(!tagExists(tag)) {
newTagField.setText("");
addTag(tag);
facade.sendNotification(LIST_CHANGED);
}
}
});
mainTable.add(tagTable).expandX().fillX();
mainTable.row();
mainTable.add(inputTable);
invalidateHeight();
}
public Set<String> getTags() {
return tags;
}
private boolean tagExists(String tag) {
return tags.contains(tag);
}
}
| 1,305 |
1,383 | <reponame>Benatti1991/chrono
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: <NAME>
// =============================================================================
//
// A simplified Marder driveline.
//
// =============================================================================
#ifndef MARDER_SIMPLE_DRIVELINE_H
#define MARDER_SIMPLE_DRIVELINE_H
#include "chrono_vehicle/tracked_vehicle/driveline/ChSimpleTrackDriveline.h"
#include "chrono_models/ChApiModels.h"
namespace chrono {
namespace vehicle {
namespace marder {
/// @addtogroup vehicle_models_marder
/// @{
/// Simple driveline model for the Marder vehicle (purely kinematic).
class CH_MODELS_API Marder_SimpleDriveline : public ChSimpleTrackDriveline {
public:
Marder_SimpleDriveline();
~Marder_SimpleDriveline() {}
/// Return the torque bias ratio for the differential.
/// This is a simple model of a Torsen limited-slip differential.
virtual double GetDifferentialMaxBias() const override { return m_diff_maxBias; }
private:
static const double m_diff_maxBias;
};
/// @} vehicle_models_marder
} // namespace marder
} // end namespace vehicle
} // end namespace chrono
#endif
| 463 |
4,474 | package com.lcodecore.tkrefreshlayout.processor;
/**
* Created by lcodecore on 2017/3/3.
*/
public interface IAnimOverScroll {
void animOverScrollTop(float vy, int computeTimes);
void animOverScrollBottom(float vy, int computeTimes);
}
| 83 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.azure.keyvault.cryptography.test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.fail;
import java.security.Provider;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.microsoft.azure.keyvault.cryptography.IAuthenticatedCryptoTransform;
import com.microsoft.azure.keyvault.cryptography.algorithms.Aes128CbcHmacSha256;
import com.microsoft.azure.keyvault.cryptography.algorithms.Aes192CbcHmacSha384;
import com.microsoft.azure.keyvault.cryptography.algorithms.Aes256CbcHmacSha512;
public class AesCbcHmacShaTest {
private Provider provider = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
setProvider(null);
}
@After
public void tearDown() throws Exception {
}
protected void setProvider(Provider provider) {
this.provider = null;
}
@Test
public void testAes128CbcHmacSha256() {
// Arrange: These values are taken from Appendix B of the JWE specification at
// https://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-40#appendix-B
byte[] key = {
(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f,
(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f
};
byte[] plaintext = {(byte) 0x41, (byte) 0x20, (byte) 0x63, (byte) 0x69, (byte) 0x70, (byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x20, (byte) 0x73, (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6d, (byte) 0x20,
(byte) 0x6d, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x20, (byte) 0x6e, (byte) 0x6f, (byte) 0x74, (byte) 0x20, (byte) 0x62, (byte) 0x65, (byte) 0x20, (byte) 0x72, (byte) 0x65, (byte) 0x71, (byte) 0x75,
(byte) 0x69, (byte) 0x72, (byte) 0x65, (byte) 0x64, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x62, (byte) 0x65, (byte) 0x20, (byte) 0x73, (byte) 0x65, (byte) 0x63, (byte) 0x72, (byte) 0x65,
(byte) 0x74, (byte) 0x2c, (byte) 0x20, (byte) 0x61, (byte) 0x6e, (byte) 0x64, (byte) 0x20, (byte) 0x69, (byte) 0x74, (byte) 0x20, (byte) 0x6d, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x20, (byte) 0x62,
(byte) 0x65, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x6c, (byte) 0x65, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x66, (byte) 0x61, (byte) 0x6c, (byte) 0x6c, (byte) 0x20, (byte) 0x69,
(byte) 0x6e, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x68, (byte) 0x61, (byte) 0x6e, (byte) 0x64, (byte) 0x73, (byte) 0x20, (byte) 0x6f, (byte) 0x66,
(byte) 0x20, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x65, (byte) 0x6e, (byte) 0x65, (byte) 0x6d, (byte) 0x79, (byte) 0x20, (byte) 0x77, (byte) 0x69, (byte) 0x74, (byte) 0x68, (byte) 0x6f,
(byte) 0x75, (byte) 0x74, (byte) 0x20, (byte) 0x69, (byte) 0x6e, (byte) 0x63, (byte) 0x6f, (byte) 0x6e, (byte) 0x76, (byte) 0x65, (byte) 0x6e, (byte) 0x69, (byte) 0x65, (byte) 0x6e, (byte) 0x63, (byte) 0x65
};
byte[] iv = {(byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04};
byte[] authData = {
(byte) 0x54, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x73, (byte) 0x65, (byte) 0x63, (byte) 0x6f, (byte) 0x6e, (byte) 0x64, (byte) 0x20, (byte) 0x70, (byte) 0x72, (byte) 0x69, (byte) 0x6e, (byte) 0x63,
(byte) 0x69, (byte) 0x70, (byte) 0x6c, (byte) 0x65, (byte) 0x20, (byte) 0x6f, (byte) 0x66, (byte) 0x20, (byte) 0x41, (byte) 0x75, (byte) 0x67, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x20,
(byte) 0x4b, (byte) 0x65, (byte) 0x72, (byte) 0x63, (byte) 0x6b, (byte) 0x68, (byte) 0x6f, (byte) 0x66, (byte) 0x66, (byte) 0x73
};
byte[] expected = {
(byte) 0xc8, (byte) 0x0e, (byte) 0xdf, (byte) 0xa3, (byte) 0x2d, (byte) 0xdf, (byte) 0x39, (byte) 0xd5, (byte) 0xef, (byte) 0x00, (byte) 0xc0, (byte) 0xb4, (byte) 0x68, (byte) 0x83, (byte) 0x42, (byte) 0x79,
(byte) 0xa2, (byte) 0xe4, (byte) 0x6a, (byte) 0x1b, (byte) 0x80, (byte) 0x49, (byte) 0xf7, (byte) 0x92, (byte) 0xf7, (byte) 0x6b, (byte) 0xfe, (byte) 0x54, (byte) 0xb9, (byte) 0x03, (byte) 0xa9, (byte) 0xc9,
(byte) 0xa9, (byte) 0x4a, (byte) 0xc9, (byte) 0xb4, (byte) 0x7a, (byte) 0xd2, (byte) 0x65, (byte) 0x5c, (byte) 0x5f, (byte) 0x10, (byte) 0xf9, (byte) 0xae, (byte) 0xf7, (byte) 0x14, (byte) 0x27, (byte) 0xe2,
(byte) 0xfc, (byte) 0x6f, (byte) 0x9b, (byte) 0x3f, (byte) 0x39, (byte) 0x9a, (byte) 0x22, (byte) 0x14, (byte) 0x89, (byte) 0xf1, (byte) 0x63, (byte) 0x62, (byte) 0xc7, (byte) 0x03, (byte) 0x23, (byte) 0x36,
(byte) 0x09, (byte) 0xd4, (byte) 0x5a, (byte) 0xc6, (byte) 0x98, (byte) 0x64, (byte) 0xe3, (byte) 0x32, (byte) 0x1c, (byte) 0xf8, (byte) 0x29, (byte) 0x35, (byte) 0xac, (byte) 0x40, (byte) 0x96, (byte) 0xc8,
(byte) 0x6e, (byte) 0x13, (byte) 0x33, (byte) 0x14, (byte) 0xc5, (byte) 0x40, (byte) 0x19, (byte) 0xe8, (byte) 0xca, (byte) 0x79, (byte) 0x80, (byte) 0xdf, (byte) 0xa4, (byte) 0xb9, (byte) 0xcf, (byte) 0x1b,
(byte) 0x38, (byte) 0x4c, (byte) 0x48, (byte) 0x6f, (byte) 0x3a, (byte) 0x54, (byte) 0xc5, (byte) 0x10, (byte) 0x78, (byte) 0x15, (byte) 0x8e, (byte) 0xe5, (byte) 0xd7, (byte) 0x9d, (byte) 0xe5, (byte) 0x9f,
(byte) 0xbd, (byte) 0x34, (byte) 0xd8, (byte) 0x48, (byte) 0xb3, (byte) 0xd6, (byte) 0x95, (byte) 0x50, (byte) 0xa6, (byte) 0x76, (byte) 0x46, (byte) 0x34, (byte) 0x44, (byte) 0x27, (byte) 0xad, (byte) 0xe5,
(byte) 0x4b, (byte) 0x88, (byte) 0x51, (byte) 0xff, (byte) 0xb5, (byte) 0x98, (byte) 0xf7, (byte) 0xf8, (byte) 0x00, (byte) 0x74, (byte) 0xb9, (byte) 0x47, (byte) 0x3c, (byte) 0x82, (byte) 0xe2, (byte) 0xdb
};
byte[] authTag = {(byte) 0x65, (byte) 0x2c, (byte) 0x3f, (byte) 0xa3, (byte) 0x6b, (byte) 0x0a, (byte) 0x7c, (byte) 0x5b, (byte) 0x32, (byte) 0x19, (byte) 0xfa, (byte) 0xb3, (byte) 0xa3, (byte) 0x0b, (byte) 0xc1, (byte) 0xc4};
Aes128CbcHmacSha256 algo = new Aes128CbcHmacSha256();
IAuthenticatedCryptoTransform transform = null;
byte[] encrypted = null;
byte[] tag = null;
try {
transform = (IAuthenticatedCryptoTransform) algo.CreateEncryptor(key, iv, authData, provider);
} catch (Exception e) {
fail(e.getMessage());
}
try {
encrypted = transform.doFinal(plaintext);
tag = transform.getTag();
assertArrayEquals(expected, encrypted);
assertArrayEquals(authTag, tag);
} catch (Exception e) {
fail(e.getMessage());
}
try {
transform = (IAuthenticatedCryptoTransform) algo.CreateDecryptor(key, iv, authData, authTag, provider);
} catch (Exception e) {
fail(e.getMessage());
}
byte[] decrypted = null;
try {
decrypted = transform.doFinal(encrypted);
tag = transform.getTag();
} catch (Exception e) {
fail(e.getMessage());
}
// Assert
assertArrayEquals(plaintext, decrypted);
assertArrayEquals(authTag, tag);
}
@Test
public void testAes192CbcHmacSha384() {
// Arrange: These values are taken from Appendix B of the JWE specification at
// https://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-40#appendix-B
byte[] key = {(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f,
(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f,
(byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27, (byte) 0x28, (byte) 0x29, (byte) 0x2a, (byte) 0x2b, (byte) 0x2c, (byte) 0x2d, (byte) 0x2e, (byte) 0x2f};
byte[] plaintext = {(byte) 0x41, (byte) 0x20, (byte) 0x63, (byte) 0x69, (byte) 0x70, (byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x20, (byte) 0x73, (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6d, (byte) 0x20,
(byte) 0x6d, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x20, (byte) 0x6e, (byte) 0x6f, (byte) 0x74, (byte) 0x20, (byte) 0x62, (byte) 0x65, (byte) 0x20, (byte) 0x72, (byte) 0x65, (byte) 0x71, (byte) 0x75,
(byte) 0x69, (byte) 0x72, (byte) 0x65, (byte) 0x64, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x62, (byte) 0x65, (byte) 0x20, (byte) 0x73, (byte) 0x65, (byte) 0x63, (byte) 0x72, (byte) 0x65,
(byte) 0x74, (byte) 0x2c, (byte) 0x20, (byte) 0x61, (byte) 0x6e, (byte) 0x64, (byte) 0x20, (byte) 0x69, (byte) 0x74, (byte) 0x20, (byte) 0x6d, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x20, (byte) 0x62,
(byte) 0x65, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x6c, (byte) 0x65, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x66, (byte) 0x61, (byte) 0x6c, (byte) 0x6c, (byte) 0x20, (byte) 0x69,
(byte) 0x6e, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x68, (byte) 0x61, (byte) 0x6e, (byte) 0x64, (byte) 0x73, (byte) 0x20, (byte) 0x6f, (byte) 0x66,
(byte) 0x20, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x65, (byte) 0x6e, (byte) 0x65, (byte) 0x6d, (byte) 0x79, (byte) 0x20, (byte) 0x77, (byte) 0x69, (byte) 0x74, (byte) 0x68, (byte) 0x6f,
(byte) 0x75, (byte) 0x74, (byte) 0x20, (byte) 0x69, (byte) 0x6e, (byte) 0x63, (byte) 0x6f, (byte) 0x6e, (byte) 0x76, (byte) 0x65, (byte) 0x6e, (byte) 0x69, (byte) 0x65, (byte) 0x6e, (byte) 0x63, (byte) 0x65};
byte[] iv = {(byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04};
byte[] authData = {(byte) 0x54, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x73, (byte) 0x65, (byte) 0x63, (byte) 0x6f, (byte) 0x6e, (byte) 0x64, (byte) 0x20, (byte) 0x70, (byte) 0x72, (byte) 0x69, (byte) 0x6e, (byte) 0x63,
(byte) 0x69, (byte) 0x70, (byte) 0x6c, (byte) 0x65, (byte) 0x20, (byte) 0x6f, (byte) 0x66, (byte) 0x20, (byte) 0x41, (byte) 0x75, (byte) 0x67, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x20,
(byte) 0x4b, (byte) 0x65, (byte) 0x72, (byte) 0x63, (byte) 0x6b, (byte) 0x68, (byte) 0x6f, (byte) 0x66, (byte) 0x66, (byte) 0x73};
byte[] expected = {(byte) 0xea, (byte) 0x65, (byte) 0xda, (byte) 0x6b, (byte) 0x59, (byte) 0xe6, (byte) 0x1e, (byte) 0xdb, (byte) 0x41, (byte) 0x9b, (byte) 0xe6, (byte) 0x2d, (byte) 0x19, (byte) 0x71, (byte) 0x2a, (byte) 0xe5,
(byte) 0xd3, (byte) 0x03, (byte) 0xee, (byte) 0xb5, (byte) 0x00, (byte) 0x52, (byte) 0xd0, (byte) 0xdf, (byte) 0xd6, (byte) 0x69, (byte) 0x7f, (byte) 0x77, (byte) 0x22, (byte) 0x4c, (byte) 0x8e, (byte) 0xdb,
(byte) 0x00, (byte) 0x0d, (byte) 0x27, (byte) 0x9b, (byte) 0xdc, (byte) 0x14, (byte) 0xc1, (byte) 0x07, (byte) 0x26, (byte) 0x54, (byte) 0xbd, (byte) 0x30, (byte) 0x94, (byte) 0x42, (byte) 0x30, (byte) 0xc6,
(byte) 0x57, (byte) 0xbe, (byte) 0xd4, (byte) 0xca, (byte) 0x0c, (byte) 0x9f, (byte) 0x4a, (byte) 0x84, (byte) 0x66, (byte) 0xf2, (byte) 0x2b, (byte) 0x22, (byte) 0x6d, (byte) 0x17, (byte) 0x46, (byte) 0x21,
(byte) 0x4b, (byte) 0xf8, (byte) 0xcf, (byte) 0xc2, (byte) 0x40, (byte) 0x0a, (byte) 0xdd, (byte) 0x9f, (byte) 0x51, (byte) 0x26, (byte) 0xe4, (byte) 0x79, (byte) 0x66, (byte) 0x3f, (byte) 0xc9, (byte) 0x0b,
(byte) 0x3b, (byte) 0xed, (byte) 0x78, (byte) 0x7a, (byte) 0x2f, (byte) 0x0f, (byte) 0xfc, (byte) 0xbf, (byte) 0x39, (byte) 0x04, (byte) 0xbe, (byte) 0x2a, (byte) 0x64, (byte) 0x1d, (byte) 0x5c, (byte) 0x21,
(byte) 0x05, (byte) 0xbf, (byte) 0xe5, (byte) 0x91, (byte) 0xba, (byte) 0xe2, (byte) 0x3b, (byte) 0x1d, (byte) 0x74, (byte) 0x49, (byte) 0xe5, (byte) 0x32, (byte) 0xee, (byte) 0xf6, (byte) 0x0a, (byte) 0x9a,
(byte) 0xc8, (byte) 0xbb, (byte) 0x6c, (byte) 0x6b, (byte) 0x01, (byte) 0xd3, (byte) 0x5d, (byte) 0x49, (byte) 0x78, (byte) 0x7b, (byte) 0xcd, (byte) 0x57, (byte) 0xef, (byte) 0x48, (byte) 0x49, (byte) 0x27,
(byte) 0xf2, (byte) 0x80, (byte) 0xad, (byte) 0xc9, (byte) 0x1a, (byte) 0xc0, (byte) 0xc4, (byte) 0xe7, (byte) 0x9c, (byte) 0x7b, (byte) 0x11, (byte) 0xef, (byte) 0xc6, (byte) 0x00, (byte) 0x54, (byte) 0xe3};
byte[] authTags = {(byte) 0x84, (byte) 0x90, (byte) 0xac, (byte) 0x0e, (byte) 0x58, (byte) 0x94, (byte) 0x9b, (byte) 0xfe, (byte) 0x51, (byte) 0x87, (byte) 0x5d, (byte) 0x73, (byte) 0x3f, (byte) 0x93, (byte) 0xac, (byte) 0x20,
(byte) 0x75, (byte) 0x16, (byte) 0x80, (byte) 0x39, (byte) 0xcc, (byte) 0xc7, (byte) 0x33, (byte) 0xd7};
Aes192CbcHmacSha384 algo = new Aes192CbcHmacSha384();
IAuthenticatedCryptoTransform transform = null;
byte[] encrypted = null;
byte[] tag = null;
try {
transform = (IAuthenticatedCryptoTransform) algo.CreateEncryptor(key, iv, authData, provider);
} catch (Exception e) {
fail(e.getMessage());
}
try {
encrypted = transform.doFinal(plaintext);
tag = transform.getTag();
assertArrayEquals(expected, encrypted);
assertArrayEquals(authTags, tag);
} catch (Exception e) {
fail(e.getMessage());
}
try {
transform = (IAuthenticatedCryptoTransform) algo.CreateDecryptor(key, iv, authData, authTags, provider);
} catch (Exception e) {
fail(e.getMessage());
}
byte[] decrypted = null;
try {
decrypted = transform.doFinal(encrypted);
tag = transform.getTag();
} catch (Exception e) {
fail(e.getMessage());
}
// Assert
assertArrayEquals(plaintext, decrypted);
assertArrayEquals(authTags, tag);
}
@Test
public void testAes256CbcHmacSha512() {
// Arrange: These values are taken from Appendix B of the JWE specification at
// https://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-40#appendix-B
byte[] key = {(byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c, (byte) 0x0d, (byte) 0x0e, (byte) 0x0f,
(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f,
(byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27, (byte) 0x28, (byte) 0x29, (byte) 0x2a, (byte) 0x2b, (byte) 0x2c, (byte) 0x2d, (byte) 0x2e, (byte) 0x2f,
(byte) 0x30, (byte) 0x31, (byte) 0x32, (byte) 0x33, (byte) 0x34, (byte) 0x35, (byte) 0x36, (byte) 0x37, (byte) 0x38, (byte) 0x39, (byte) 0x3a, (byte) 0x3b, (byte) 0x3c, (byte) 0x3d, (byte) 0x3e, (byte) 0x3f};
byte[] plaintext = {(byte) 0x41, (byte) 0x20, (byte) 0x63, (byte) 0x69, (byte) 0x70, (byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x20, (byte) 0x73, (byte) 0x79, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x6d, (byte) 0x20,
(byte) 0x6d, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x20, (byte) 0x6e, (byte) 0x6f, (byte) 0x74, (byte) 0x20, (byte) 0x62, (byte) 0x65, (byte) 0x20, (byte) 0x72, (byte) 0x65, (byte) 0x71, (byte) 0x75,
(byte) 0x69, (byte) 0x72, (byte) 0x65, (byte) 0x64, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x62, (byte) 0x65, (byte) 0x20, (byte) 0x73, (byte) 0x65, (byte) 0x63, (byte) 0x72, (byte) 0x65,
(byte) 0x74, (byte) 0x2c, (byte) 0x20, (byte) 0x61, (byte) 0x6e, (byte) 0x64, (byte) 0x20, (byte) 0x69, (byte) 0x74, (byte) 0x20, (byte) 0x6d, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x20, (byte) 0x62,
(byte) 0x65, (byte) 0x20, (byte) 0x61, (byte) 0x62, (byte) 0x6c, (byte) 0x65, (byte) 0x20, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x66, (byte) 0x61, (byte) 0x6c, (byte) 0x6c, (byte) 0x20, (byte) 0x69,
(byte) 0x6e, (byte) 0x74, (byte) 0x6f, (byte) 0x20, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x68, (byte) 0x61, (byte) 0x6e, (byte) 0x64, (byte) 0x73, (byte) 0x20, (byte) 0x6f, (byte) 0x66,
(byte) 0x20, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x65, (byte) 0x6e, (byte) 0x65, (byte) 0x6d, (byte) 0x79, (byte) 0x20, (byte) 0x77, (byte) 0x69, (byte) 0x74, (byte) 0x68, (byte) 0x6f,
(byte) 0x75, (byte) 0x74, (byte) 0x20, (byte) 0x69, (byte) 0x6e, (byte) 0x63, (byte) 0x6f, (byte) 0x6e, (byte) 0x76, (byte) 0x65, (byte) 0x6e, (byte) 0x69, (byte) 0x65, (byte) 0x6e, (byte) 0x63, (byte) 0x65};
byte[] iv = {(byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04};
byte[] authData = {(byte) 0x54, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x73, (byte) 0x65, (byte) 0x63, (byte) 0x6f, (byte) 0x6e, (byte) 0x64, (byte) 0x20, (byte) 0x70, (byte) 0x72, (byte) 0x69, (byte) 0x6e, (byte) 0x63,
(byte) 0x69, (byte) 0x70, (byte) 0x6c, (byte) 0x65, (byte) 0x20, (byte) 0x6f, (byte) 0x66, (byte) 0x20, (byte) 0x41, (byte) 0x75, (byte) 0x67, (byte) 0x75, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x20,
(byte) 0x4b, (byte) 0x65, (byte) 0x72, (byte) 0x63, (byte) 0x6b, (byte) 0x68, (byte) 0x6f, (byte) 0x66, (byte) 0x66, (byte) 0x73};
byte[] expected = {(byte) 0x4a, (byte) 0xff, (byte) 0xaa, (byte) 0xad, (byte) 0xb7, (byte) 0x8c, (byte) 0x31, (byte) 0xc5, (byte) 0xda, (byte) 0x4b, (byte) 0x1b, (byte) 0x59, (byte) 0x0d, (byte) 0x10, (byte) 0xff, (byte) 0xbd,
(byte) 0x3d, (byte) 0xd8, (byte) 0xd5, (byte) 0xd3, (byte) 0x02, (byte) 0x42, (byte) 0x35, (byte) 0x26, (byte) 0x91, (byte) 0x2d, (byte) 0xa0, (byte) 0x37, (byte) 0xec, (byte) 0xbc, (byte) 0xc7, (byte) 0xbd,
(byte) 0x82, (byte) 0x2c, (byte) 0x30, (byte) 0x1d, (byte) 0xd6, (byte) 0x7c, (byte) 0x37, (byte) 0x3b, (byte) 0xcc, (byte) 0xb5, (byte) 0x84, (byte) 0xad, (byte) 0x3e, (byte) 0x92, (byte) 0x79, (byte) 0xc2,
(byte) 0xe6, (byte) 0xd1, (byte) 0x2a, (byte) 0x13, (byte) 0x74, (byte) 0xb7, (byte) 0x7f, (byte) 0x07, (byte) 0x75, (byte) 0x53, (byte) 0xdf, (byte) 0x82, (byte) 0x94, (byte) 0x10, (byte) 0x44, (byte) 0x6b,
(byte) 0x36, (byte) 0xeb, (byte) 0xd9, (byte) 0x70, (byte) 0x66, (byte) 0x29, (byte) 0x6a, (byte) 0xe6, (byte) 0x42, (byte) 0x7e, (byte) 0xa7, (byte) 0x5c, (byte) 0x2e, (byte) 0x08, (byte) 0x46, (byte) 0xa1,
(byte) 0x1a, (byte) 0x09, (byte) 0xcc, (byte) 0xf5, (byte) 0x37, (byte) 0x0d, (byte) 0xc8, (byte) 0x0b, (byte) 0xfe, (byte) 0xcb, (byte) 0xad, (byte) 0x28, (byte) 0xc7, (byte) 0x3f, (byte) 0x09, (byte) 0xb3,
(byte) 0xa3, (byte) 0xb7, (byte) 0x5e, (byte) 0x66, (byte) 0x2a, (byte) 0x25, (byte) 0x94, (byte) 0x41, (byte) 0x0a, (byte) 0xe4, (byte) 0x96, (byte) 0xb2, (byte) 0xe2, (byte) 0xe6, (byte) 0x60, (byte) 0x9e,
(byte) 0x31, (byte) 0xe6, (byte) 0xe0, (byte) 0x2c, (byte) 0xc8, (byte) 0x37, (byte) 0xf0, (byte) 0x53, (byte) 0xd2, (byte) 0x1f, (byte) 0x37, (byte) 0xff, (byte) 0x4f, (byte) 0x51, (byte) 0x95, (byte) 0x0b,
(byte) 0xbe, (byte) 0x26, (byte) 0x38, (byte) 0xd0, (byte) 0x9d, (byte) 0xd7, (byte) 0xa4, (byte) 0x93, (byte) 0x09, (byte) 0x30, (byte) 0x80, (byte) 0x6d, (byte) 0x07, (byte) 0x03, (byte) 0xb1, (byte) 0xf6};
byte[] authTags = {(byte) 0x4d, (byte) 0xd3, (byte) 0xb4, (byte) 0xc0, (byte) 0x88, (byte) 0xa7, (byte) 0xf4, (byte) 0x5c, (byte) 0x21, (byte) 0x68, (byte) 0x39, (byte) 0x64, (byte) 0x5b, (byte) 0x20, (byte) 0x12, (byte) 0xbf,
(byte) 0x2e, (byte) 0x62, (byte) 0x69, (byte) 0xa8, (byte) 0xc5, (byte) 0x6a, (byte) 0x81, (byte) 0x6d, (byte) 0xbc, (byte) 0x1b, (byte) 0x26, (byte) 0x77, (byte) 0x61, (byte) 0x95, (byte) 0x5b, (byte) 0xc5};
Aes256CbcHmacSha512 algo = new Aes256CbcHmacSha512();
IAuthenticatedCryptoTransform transform = null;
byte[] encrypted = null;
byte[] tag = null;
try {
transform = (IAuthenticatedCryptoTransform) algo.CreateEncryptor(key, iv, authData, provider);
} catch (Exception e) {
fail(e.getMessage());
}
try {
encrypted = transform.doFinal(plaintext);
tag = transform.getTag();
assertArrayEquals(expected, encrypted);
assertArrayEquals(authTags, tag);
} catch (Exception e) {
fail(e.getMessage());
}
try {
transform = (IAuthenticatedCryptoTransform) algo.CreateDecryptor(key, iv, authData, authTags, provider);
} catch (Exception e) {
fail(e.getMessage());
}
byte[] decrypted = null;
try {
decrypted = transform.doFinal(encrypted);
tag = transform.getTag();
} catch (Exception e) {
fail(e.getMessage());
}
// Assert
assertArrayEquals(plaintext, decrypted);
assertArrayEquals(authTags, tag);
}
}
| 12,126 |
348 | <filename>docs/data/leg-t1/077/07704182.json
{"nom":"<NAME>","circ":"4ème circonscription","dpt":"Seine-et-Marne","inscrits":2424,"abs":1298,"votants":1126,"blancs":20,"nuls":6,"exp":1100,"res":[{"nuance":"LR","nom":"<NAME>","voix":372},{"nuance":"REM","nom":"M. <NAME>","voix":273},{"nuance":"FN","nom":"<NAME>","voix":244},{"nuance":"FI","nom":"Mme <NAME>","voix":102},{"nuance":"SOC","nom":"M. <NAME>","voix":46},{"nuance":"EXG","nom":"M. <NAME>","voix":18},{"nuance":"ECO","nom":"M. <NAME>","voix":18},{"nuance":"DLF","nom":"M. <NAME>","voix":15},{"nuance":"COM","nom":"M. <NAME>","voix":8},{"nuance":"DIV","nom":"Mme <NAME>","voix":4}]} | 265 |
574 | <reponame>gmarques33/android-junit5
package de.mannodermaus.app;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
class AndroidTest {
@Test
void test() {
InputStream is = getClass().getResourceAsStream("/com/android/tools/test_config.properties");
assertNotNull(is);
}
}
| 133 |
1,444 | <filename>Mage.Sets/src/mage/cards/p/PhantomSteed.java<gh_stars>1000+
package mage.cards.p;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.common.delayed.AtTheEndOfCombatDelayedTriggeredAbility;
import mage.abilities.common.delayed.OnLeaveReturnExiledToBattlefieldAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.CreateDelayedTriggeredAbilityEffect;
import mage.abilities.effects.common.ExileTargetEffect;
import mage.abilities.effects.common.ExileUntilSourceLeavesEffect;
import mage.abilities.keyword.FlashAbility;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import mage.game.ExileZone;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.game.permanent.token.EmptyToken;
import mage.target.TargetPermanent;
import mage.target.targetpointer.FixedTargets;
import mage.util.CardUtil;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* @author TheElk801
*/
public final class PhantomSteed extends CardImpl {
public PhantomSteed(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{U}");
this.subtype.add(SubType.HORSE);
this.subtype.add(SubType.ILLUSION);
this.power = new MageInt(4);
this.toughness = new MageInt(3);
// Flash
this.addAbility(FlashAbility.getInstance());
// When Phantom Steed enters the battlefield, exile another target creature you control until Phantom Steed leaves the battlefield.
Ability ability = new EntersBattlefieldTriggeredAbility(new ExileUntilSourceLeavesEffect("")
.setText("exile another target creature you control until Phantom Steed leaves the battlefield"));
ability.addTarget(new TargetPermanent(StaticFilters.FILTER_CONTROLLED_ANOTHER_CREATURE));
ability.addEffect(new CreateDelayedTriggeredAbilityEffect(new OnLeaveReturnExiledToBattlefieldAbility()));
this.addAbility(ability);
// Whenever Phantom Steed attacks, create a tapped and attacking token that's a copy of the exiled creature, except it's an Illusion in addition to its other types. Sacrifice that token at end of combat.
this.addAbility(new AttacksTriggeredAbility(new PhantomSteedEffect()));
}
private PhantomSteed(final PhantomSteed card) {
super(card);
}
@Override
public PhantomSteed copy() {
return new PhantomSteed(this);
}
}
class PhantomSteedEffect extends OneShotEffect {
PhantomSteedEffect() {
super(Outcome.Benefit);
staticText = "create a tapped and attacking token that's a copy of the exiled card, " +
"except it's an Illusion in addition to its other types. Sacrifice that token at end of combat";
}
private PhantomSteedEffect(final PhantomSteedEffect effect) {
super(effect);
}
@Override
public PhantomSteedEffect copy() {
return new PhantomSteedEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
ExileZone exileZone = game.getState().getExile().getExileZone(CardUtil.getExileZoneId(game, source));
if (exileZone == null || exileZone.isEmpty()) {
return false;
}
for (Card card : exileZone.getCards(game)) {
EmptyToken token = new EmptyToken();
CardUtil.copyTo(token).from(card, game);
token.addSubType(SubType.ILLUSION);
token.putOntoBattlefield(1, game, source, source.getControllerId(), true, true);
List<Permanent> permanents = token
.getLastAddedTokenIds()
.stream()
.map(game::getPermanent)
.filter(Objects::nonNull)
.collect(Collectors.toList());
game.addDelayedTriggeredAbility(new AtTheEndOfCombatDelayedTriggeredAbility(
new ExileTargetEffect("Sacrifice that token at end of combat")
.setTargetPointer(new FixedTargets(permanents, game))
), source);
}
return true;
}
}
| 1,659 |
713 | <filename>core/src/test/java/org/infinispan/util/ThreadLocalLeakTest.java
package org.infinispan.util;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertSame;
import java.io.File;
import java.lang.ref.Reference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import org.infinispan.Cache;
import org.infinispan.commons.test.CommonsTestingUtil;
import org.infinispan.commons.test.TestResourceTracker;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.AbstractInfinispanTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Tests whether certain cache set ups result in thread local leaks.
*
* @author <NAME>
* @since 5.3
*/
@Test(groups = "functional", testName = "util.ThreadLocalLeakTest")
public class ThreadLocalLeakTest extends AbstractInfinispanTest {
private static final Pattern THREAD_LOCAL_FILTER = Pattern.compile("org\\.infinispan\\..*");
// Ued to ignore the thread-local in our ConcurrentHashMap backport
private static final Set<String> ACCEPTED_THREAD_LOCALS = new HashSet<>(Arrays.asList());
private final ThreadLocal<ThreadLocalLeakTest> DUMMY_THREAD_LOCAL = ThreadLocal.withInitial(() -> this);
private String tmpDirectory;
@BeforeClass
protected void setUpTempDir() {
tmpDirectory = CommonsTestingUtil.tmpDirectory(this.getClass());
}
@AfterClass(alwaysRun = true)
protected void clearTempDir() {
org.infinispan.commons.util.Util.recursiveFileRemove(tmpDirectory);
new File(tmpDirectory).mkdirs();
}
public void testCheckThreadLocalLeaks() throws Exception {
// Perform the test in a new thread so we don't have any thread-locals from previous tests
fork(this::doCheckThreadLocalLeaks).get(30, TimeUnit.SECONDS);
}
private void doCheckThreadLocalLeaks() throws Exception {
TestResourceTracker.testThreadStarted(getTestName());
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.memory().maxCount(4096)
.locking().concurrencyLevel(2048)
.invocationBatching().enable()
.persistence().passivation(false)
.addSingleFileStore().shared(false).preload(true);
amendConfiguration(builder);
GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault();
globalBuilder.globalState().enable().persistentLocation(tmpDirectory);
CyclicBarrier barrier = new CyclicBarrier(2);
AtomicReference<Thread> putThread = new AtomicReference<>();
Future<Void> putFuture;
try (EmbeddedCacheManager cm = new DefaultCacheManager(globalBuilder.build())) {
cm.defineConfiguration("leak", builder.build());
final Cache<Object, Object> c = cm.getCache("leak");
c.put("key1", "value1");
putFuture = fork(() -> {
assertSame(this, DUMMY_THREAD_LOCAL.get());
putThread.set(Thread.currentThread());
Cache<Object, Object> c1 = cm.getCache("leak");
c1.put("key2", "value2");
c1 = null;
// Let the main thread know it can check for thread locals
barrier.await(10, TimeUnit.SECONDS);
// Wait for the main thread to finish the check
barrier.await(10, TimeUnit.SECONDS);
});
c.put("key3", "value3");
// Sync with the forked thread after cache.put() returns
barrier.await(10, TimeUnit.SECONDS);
}
// The cache manager is stopped and the forked thread is blocked after the operation
Map<Class<?>, Object> mainThreadLeaks = findThreadLocalLeaks(Thread.currentThread());
assertEquals(Collections.emptySet(), mainThreadLeaks.keySet());
Map<Class<?>, Object> forkThreadLeaks = findThreadLocalLeaks(putThread.get());
assertEquals(Collections.singleton(DUMMY_THREAD_LOCAL.getClass()), forkThreadLeaks.keySet());
// Let the put thread finish
barrier.await(10, TimeUnit.SECONDS);
// Check for any exceptions
putFuture.get(10, TimeUnit.SECONDS);
}
protected void amendConfiguration(ConfigurationBuilder builder) {
// To be overridden by subclasses
}
private Map<Class<?>, Object> findThreadLocalLeaks(Thread thread) throws Exception {
// Get a reference to the thread locals table of the current thread
Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
Object threadLocalTable = threadLocalsField.get(thread);
// Get a reference to the array holding the thread local variables inside the
// ThreadLocalMap of the current thread
Class<?> threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
Field tableField = threadLocalMapClass.getDeclaredField("table");
tableField.setAccessible(true);
Object table;
try {
table = tableField.get(threadLocalTable);
} catch (NullPointerException e) {
// Ignore
return null;
}
Class<?> entryClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap$Entry");
Field valueField = entryClass.getDeclaredField("value");
valueField.setAccessible(true);
Map<Class<?>, Object> threadLocals = new HashMap<>();
for (int i=0; i < Array.getLength(table); i++) {
// Each entry in the table array of ThreadLocalMap is an Entry object
// representing the thread local reference and its value
Reference<ThreadLocal<?>> entry = (Reference<ThreadLocal<?>>) Array.get(table, i);
if (entry != null) {
// Get a reference to the thread local object
ThreadLocal<?> threadLocal = entry.get();
Object value = valueField.get(entry);
if (threadLocal != null) {
if (filterThreadLocals(threadLocal, value) && !ACCEPTED_THREAD_LOCALS.contains(threadLocal.getClass().getCanonicalName())) {
log.error("Thread local leak: " + threadLocal);
threadLocals.put(threadLocal.getClass(), value);
}
} else {
log.warn("Thread local is not accessible, but it wasn't removed either: " + value);
}
}
}
return threadLocals;
}
private boolean filterThreadLocals(ThreadLocal<?> tl, Object value) {
String tlClassName = tl.getClass().getName();
String valueClassName = value != null ? value.getClass().getName() : "";
log.tracef("Checking thread-local %s = %s", tlClassName, valueClassName);
if (!THREAD_LOCAL_FILTER.matcher(tlClassName).find()
&& !THREAD_LOCAL_FILTER.matcher(valueClassName).find()) {
return false;
}
return !ACCEPTED_THREAD_LOCALS.contains(tlClassName) && !ACCEPTED_THREAD_LOCALS.contains(valueClassName);
}
}
| 2,718 |
1,405 | <reponame>jarekankowski/pegasus_spyware
package com.network.a;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.xmlpull.v1.XmlSerializer;
public final class a {
/* renamed from: a reason: collision with root package name */
private static final SimpleDateFormat f36a = new SimpleDateFormat("yyyyMMdd'T'HHmm00'Z'");
private static String b = null;
private static Double c = null;
public static Cursor a(ContentResolver contentResolver) {
return contentResolver.query(a(), new String[]{"title", "dtstart", "dtend", "allDay", "_id", "eventLocation", "description", "deleted"}, null, null, null);
}
public static Uri a() {
String str;
if (b != null) {
str = b;
} else {
if (b() > 2.1d) {
b = "content://com.android.calendar/events";
} else {
b = "content://calendar/events";
}
com.network.android.c.a.a.a("getEventCursor: " + b);
str = b;
}
return Uri.parse(str);
}
private static String a(Date date) {
if (date == null) {
return "";
}
f36a.setTimeZone(TimeZone.getTimeZone("GMT"));
return f36a.format(date);
}
public static void a(ContentResolver contentResolver, Handler handler, Context context) {
handler.post(new b(contentResolver, context));
}
public static void a(Cursor cursor, StringBuffer stringBuffer) {
boolean z = true;
String string = cursor.getString(0);
if (string == null) {
string = "";
}
Date date = new Date(cursor.getLong(1));
Date date2 = new Date(cursor.getLong(2));
if (cursor.getString(3).equals("0")) {
z = false;
}
Boolean valueOf = Boolean.valueOf(z);
String string2 = cursor.getString(5);
if (string2 == null) {
string2 = "";
}
String string3 = cursor.getString(6);
if (string3 == null) {
string3 = "";
}
String a2 = a(date);
String a3 = date2.getTime() == 0 ? a2 : a(date2);
String replaceAll = string.replaceAll("\n", "\\\\n");
stringBuffer.append("\r\nBEGIN:VCALENDAR\r\nPRODID:Android\r\nVERSION:2.0\r\nMETHOD:PUBLISH\r\nBEGIN:VEVENT");
stringBuffer.append("\r\nTITLE:" + replaceAll + "\r\nSUMMARY:" + replaceAll + "\r\nDESCRIPTION:" + string3.replaceAll("\n", "\\\\n") + "\r\nDTSTART:" + a2 + "\r\nDTEND:" + a3 + "\r\nALL-DAY:" + valueOf + "\r\nLOCATION:" + string2.replaceAll("\n", "\\\\n"));
stringBuffer.append("\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n");
}
public static void a(XmlSerializer xmlSerializer, Cursor cursor, StringBuffer stringBuffer, String str) {
String str2;
try {
String string = cursor.getString(4);
long j = cursor.getLong(1) / 1000;
a(cursor, stringBuffer);
if (j > 0) {
str2 = String.valueOf(j);
} else {
str2 = "0";
com.network.android.c.a.a.a("Bad Calendar: " + cursor.getPosition());
com.network.android.c.a.a.a(stringBuffer.toString());
}
a(xmlSerializer, str, string, stringBuffer.toString(), str2);
} catch (Throwable th) {
com.network.android.c.a.a.a("get sms Exception- " + th.getMessage(), th);
}
}
public static void a(XmlSerializer xmlSerializer, String str, String str2, String str3, String str4) {
xmlSerializer.startTag("", "calendarEntry");
xmlSerializer.attribute("", "recordId", str2);
xmlSerializer.attribute("", "timestamp", str4);
if (str != null) {
xmlSerializer.attribute("", "updateType", str);
}
if (str3 != null) {
xmlSerializer.cdsect(str3);
}
xmlSerializer.endTag("", "calendarEntry");
}
public static double b() {
if (c != null) {
return c.doubleValue();
}
String str = Build.VERSION.RELEASE;
com.network.android.c.a.a.a("Build.VERSION.RELEASE: " + str);
Double valueOf = Double.valueOf(Double.parseDouble(str.substring(0, str.indexOf(".") + 2)));
c = valueOf;
return valueOf.doubleValue();
}
}
| 2,080 |
6,989 | """
To ensure compatibility from Python ``2.7`` - ``3.x``, a module has been
created. Clearly there is huge need to use conforming syntax.
"""
import errno
import sys
import os
import re
import pkgutil
import warnings
import inspect
import subprocess
try:
import importlib
except ImportError:
pass
is_py3 = sys.version_info[0] >= 3
is_py35 = is_py3 and sys.version_info[1] >= 5
py_version = int(str(sys.version_info[0]) + str(sys.version_info[1]))
class DummyFile(object):
def __init__(self, loader, string):
self.loader = loader
self.string = string
def read(self):
return self.loader.get_source(self.string)
def close(self):
del self.loader
def find_module_py34(string, path=None, full_name=None, is_global_search=True):
spec = None
loader = None
for finder in sys.meta_path:
if is_global_search and finder != importlib.machinery.PathFinder:
p = None
else:
p = path
try:
find_spec = finder.find_spec
except AttributeError:
# These are old-school clases that still have a different API, just
# ignore those.
continue
spec = find_spec(string, p)
if spec is not None:
loader = spec.loader
if loader is None and not spec.has_location:
# This is a namespace package.
full_name = string if not path else full_name
implicit_ns_info = ImplicitNSInfo(full_name, spec.submodule_search_locations._path)
return None, implicit_ns_info, False
break
return find_module_py33(string, path, loader)
def find_module_py33(string, path=None, loader=None, full_name=None, is_global_search=True):
loader = loader or importlib.machinery.PathFinder.find_module(string, path)
if loader is None and path is None: # Fallback to find builtins
try:
with warnings.catch_warnings(record=True):
# Mute "DeprecationWarning: Use importlib.util.find_spec()
# instead." While we should replace that in the future, it's
# probably good to wait until we deprecate Python 3.3, since
# it was added in Python 3.4 and find_loader hasn't been
# removed in 3.6.
loader = importlib.find_loader(string)
except ValueError as e:
# See #491. Importlib might raise a ValueError, to avoid this, we
# just raise an ImportError to fix the issue.
raise ImportError("Originally " + repr(e))
if loader is None:
raise ImportError("Couldn't find a loader for {}".format(string))
try:
is_package = loader.is_package(string)
if is_package:
if hasattr(loader, 'path'):
module_path = os.path.dirname(loader.path)
else:
# At least zipimporter does not have path attribute
module_path = os.path.dirname(loader.get_filename(string))
if hasattr(loader, 'archive'):
module_file = DummyFile(loader, string)
else:
module_file = None
else:
module_path = loader.get_filename(string)
module_file = DummyFile(loader, string)
except AttributeError:
# ExtensionLoader has not attribute get_filename, instead it has a
# path attribute that we can use to retrieve the module path
try:
module_path = loader.path
module_file = DummyFile(loader, string)
except AttributeError:
module_path = string
module_file = None
finally:
is_package = False
if hasattr(loader, 'archive'):
module_path = loader.archive
return module_file, module_path, is_package
def find_module_pre_py34(string, path=None, full_name=None, is_global_search=True):
# This import is here, because in other places it will raise a
# DeprecationWarning.
import imp
try:
module_file, module_path, description = imp.find_module(string, path)
module_type = description[2]
return module_file, module_path, module_type is imp.PKG_DIRECTORY
except ImportError:
pass
if path is None:
path = sys.path
for item in path:
loader = pkgutil.get_importer(item)
if loader:
try:
loader = loader.find_module(string)
if loader:
is_package = loader.is_package(string)
is_archive = hasattr(loader, 'archive')
module_path = loader.get_filename(string)
if is_package:
module_path = os.path.dirname(module_path)
if is_archive:
module_path = loader.archive
file = None
if not is_package or is_archive:
file = DummyFile(loader, string)
return file, module_path, is_package
except ImportError:
pass
raise ImportError("No module named {}".format(string))
find_module = find_module_py34 if is_py3 else find_module_pre_py34
find_module.__doc__ = """
Provides information about a module.
This function isolates the differences in importing libraries introduced with
python 3.3 on; it gets a module name and optionally a path. It will return a
tuple containin an open file for the module (if not builtin), the filename
or the name of the module if it is a builtin one and a boolean indicating
if the module is contained in a package.
"""
def _iter_modules(paths, prefix=''):
# Copy of pkgutil.iter_modules adapted to work with namespaces
for path in paths:
importer = pkgutil.get_importer(path)
if not isinstance(importer, importlib.machinery.FileFinder):
# We're only modifying the case for FileFinder. All the other cases
# still need to be checked (like zip-importing). Do this by just
# calling the pkgutil version.
for mod_info in pkgutil.iter_modules([path], prefix):
yield mod_info
continue
# START COPY OF pkutils._iter_file_finder_modules.
if importer.path is None or not os.path.isdir(importer.path):
return
yielded = {}
try:
filenames = os.listdir(importer.path)
except OSError:
# ignore unreadable directories like import does
filenames = []
filenames.sort() # handle packages before same-named modules
for fn in filenames:
modname = inspect.getmodulename(fn)
if modname == '__init__' or modname in yielded:
continue
# jedi addition: Avoid traversing special directories
if fn.startswith('.') or fn == '__pycache__':
continue
path = os.path.join(importer.path, fn)
ispkg = False
if not modname and os.path.isdir(path) and '.' not in fn:
modname = fn
# A few jedi modifications: Don't check if there's an
# __init__.py
try:
os.listdir(path)
except OSError:
# ignore unreadable directories like import does
continue
ispkg = True
if modname and '.' not in modname:
yielded[modname] = 1
yield importer, prefix + modname, ispkg
# END COPY
iter_modules = _iter_modules if py_version >= 34 else pkgutil.iter_modules
class ImplicitNSInfo(object):
"""Stores information returned from an implicit namespace spec"""
def __init__(self, name, paths):
self.name = name
self.paths = paths
if is_py3:
all_suffixes = importlib.machinery.all_suffixes
else:
def all_suffixes():
# Is deprecated and raises a warning in Python 3.6.
import imp
return [suffix for suffix, _, _ in imp.get_suffixes()]
# unicode function
try:
unicode = unicode
except NameError:
unicode = str
# re-raise function
if is_py3:
def reraise(exception, traceback):
raise exception.with_traceback(traceback)
else:
eval(compile("""
def reraise(exception, traceback):
raise exception, None, traceback
""", 'blub', 'exec'))
reraise.__doc__ = """
Re-raise `exception` with a `traceback` object.
Usage::
reraise(Exception, sys.exc_info()[2])
"""
class Python3Method(object):
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype):
if obj is None:
return lambda *args, **kwargs: self.func(*args, **kwargs)
else:
return lambda *args, **kwargs: self.func(obj, *args, **kwargs)
def use_metaclass(meta, *bases):
""" Create a class with a metaclass. """
if not bases:
bases = (object,)
return meta("Py2CompatibilityMetaClass", bases, {})
try:
encoding = sys.stdout.encoding
if encoding is None:
encoding = 'utf-8'
except AttributeError:
encoding = 'ascii'
def u(string, errors='strict'):
"""Cast to unicode DAMMIT!
Written because Python2 repr always implicitly casts to a string, so we
have to cast back to a unicode (and we now that we always deal with valid
unicode, because we check that in the beginning).
"""
if isinstance(string, bytes):
return unicode(string, encoding='UTF-8', errors=errors)
return string
def cast_path(obj):
"""
Take a bytes or str path and cast it to unicode.
Apparently it is perfectly fine to pass both byte and unicode objects into
the sys.path. This probably means that byte paths are normal at other
places as well.
Since this just really complicates everything and Python 2.7 will be EOL
soon anyway, just go with always strings.
"""
return u(obj, errors='replace')
def force_unicode(obj):
# Intentionally don't mix those two up, because those two code paths might
# be different in the future (maybe windows?).
return cast_path(obj)
try:
import builtins # module name in python 3
except ImportError:
import __builtin__ as builtins # noqa: F401
import ast # noqa: F401
def literal_eval(string):
return ast.literal_eval(string)
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest # Python 2 # noqa: F401
try:
FileNotFoundError = FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
NotADirectoryError = NotADirectoryError
except NameError:
NotADirectoryError = IOError
try:
PermissionError = PermissionError
except NameError:
PermissionError = IOError
def no_unicode_pprint(dct):
"""
Python 2/3 dict __repr__ may be different, because of unicode differens
(with or without a `u` prefix). Normally in doctests we could use `pprint`
to sort dicts and check for equality, but here we have to write a separate
function to do that.
"""
import pprint
s = pprint.pformat(dct)
print(re.sub("u'", "'", s))
def print_to_stderr(*args):
if is_py3:
eval("print(*args, file=sys.stderr)")
else:
print >> sys.stderr, args
sys.stderr.flush()
def utf8_repr(func):
"""
``__repr__`` methods in Python 2 don't allow unicode objects to be
returned. Therefore cast them to utf-8 bytes in this decorator.
"""
def wrapper(self):
result = func(self)
if isinstance(result, unicode):
return result.encode('utf-8')
else:
return result
if is_py3:
return func
else:
return wrapper
if is_py3:
import queue
else:
import Queue as queue # noqa: F401
try:
# Attempt to load the C implementation of pickle on Python 2 as it is way
# faster.
import cPickle as pickle
except ImportError:
import pickle
if sys.version_info[:2] == (3, 3):
"""
Monkeypatch the unpickler in Python 3.3. This is needed, because the
argument `encoding='bytes'` is not supported in 3.3, but badly needed to
communicate with Python 2.
"""
class NewUnpickler(pickle._Unpickler):
dispatch = dict(pickle._Unpickler.dispatch)
def _decode_string(self, value):
# Used to allow strings from Python 2 to be decoded either as
# bytes or Unicode strings. This should be used only with the
# STRING, BINSTRING and SHORT_BINSTRING opcodes.
if self.encoding == "bytes":
return value
else:
return value.decode(self.encoding, self.errors)
def load_string(self):
data = self.readline()[:-1]
# Strip outermost quotes
if len(data) >= 2 and data[0] == data[-1] and data[0] in b'"\'':
data = data[1:-1]
else:
raise pickle.UnpicklingError("the STRING opcode argument must be quoted")
self.append(self._decode_string(pickle.codecs.escape_decode(data)[0]))
dispatch[pickle.STRING[0]] = load_string
def load_binstring(self):
# Deprecated BINSTRING uses signed 32-bit length
len, = pickle.struct.unpack('<i', self.read(4))
if len < 0:
raise pickle.UnpicklingError("BINSTRING pickle has negative byte count")
data = self.read(len)
self.append(self._decode_string(data))
dispatch[pickle.BINSTRING[0]] = load_binstring
def load_short_binstring(self):
len = self.read(1)[0]
data = self.read(len)
self.append(self._decode_string(data))
dispatch[pickle.SHORT_BINSTRING[0]] = load_short_binstring
def load(file, fix_imports=True, encoding="ASCII", errors="strict"):
return NewUnpickler(file, fix_imports=fix_imports,
encoding=encoding, errors=errors).load()
def loads(s, fix_imports=True, encoding="ASCII", errors="strict"):
if isinstance(s, str):
raise TypeError("Can't load pickle from unicode string")
file = pickle.io.BytesIO(s)
return NewUnpickler(file, fix_imports=fix_imports,
encoding=encoding, errors=errors).load()
pickle.Unpickler = NewUnpickler
pickle.load = load
pickle.loads = loads
def pickle_load(file):
try:
if is_py3:
return pickle.load(file, encoding='bytes')
return pickle.load(file)
# Python on Windows don't throw EOF errors for pipes. So reraise them with
# the correct type, which is caught upwards.
except OSError:
if sys.platform == 'win32':
raise EOFError()
raise
def pickle_dump(data, file, protocol):
try:
pickle.dump(data, file, protocol)
# On Python 3.3 flush throws sometimes an error even though the writing
# operation should be completed.
file.flush()
# Python on Windows don't throw EPIPE errors for pipes. So reraise them with
# the correct type and error number.
except OSError:
if sys.platform == 'win32':
raise IOError(errno.EPIPE, "Broken pipe")
raise
# Determine the highest protocol version compatible for a given list of Python
# versions.
def highest_pickle_protocol(python_versions):
protocol = 4
for version in python_versions:
if version[0] == 2:
# The minimum protocol version for the versions of Python that we
# support (2.7 and 3.3+) is 2.
return 2
if version[1] < 4:
protocol = 3
return protocol
try:
from inspect import Parameter
except ImportError:
class Parameter(object):
POSITIONAL_ONLY = object()
POSITIONAL_OR_KEYWORD = object()
VAR_POSITIONAL = object()
KEYWORD_ONLY = object()
VAR_KEYWORD = object()
class GeneralizedPopen(subprocess.Popen):
def __init__(self, *args, **kwargs):
if os.name == 'nt':
try:
# Was introduced in Python 3.7.
CREATE_NO_WINDOW = subprocess.CREATE_NO_WINDOW
except AttributeError:
CREATE_NO_WINDOW = 0x08000000
kwargs['creationflags'] = CREATE_NO_WINDOW
# The child process doesn't need file descriptors except 0, 1, 2.
# This is unix only.
kwargs['close_fds'] = 'posix' in sys.builtin_module_names
super(GeneralizedPopen, self).__init__(*args, **kwargs)
# shutil.which is not available on Python 2.7.
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode)
and not os.path.isdir(fn))
# If we're given a path with a directory part, look it up directly rather
# than referring to PATH directories. This includes checking relative to the
# current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
if sys.platform == "win32":
# The current directory takes precedence on Windows.
if os.curdir not in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
# If it does match, only test that one, otherwise we have to try
# others.
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
files = [cmd]
else:
files = [cmd + ext for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
normdir = os.path.normcase(dir)
if normdir not in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
| 8,089 |
975 | <reponame>parth-couture-ai/RecommenderSystems
#coding: utf-8
'''
Author: <NAME>
Contact: <EMAIL>
'''
import tensorflow as tf
import argparse
import numpy as np
import sys
import time
import math
from .utils import *
from .model import *
from .sampler import *
parser = argparse.ArgumentParser(description='Sequential or session-based recommendation')
parser.add_argument('--model', type=str, default='tcn', help='sequential model: rnn/tcn/transformer. (default: tcn)')
parser.add_argument('--batch_size', type=int, default=128, help='batch size (default: 128)')
parser.add_argument('--seq_len', type=int, default=20, help='max sequence length (default: 20)')
parser.add_argument('--dropout', type=float, default=0.2, help='dropout (default: 0.2)')
parser.add_argument('--l2_reg', type=float, default=0.0, help='regularization scale (default: 0.0)')
parser.add_argument('--clip', type=float, default=1., help='gradient clip (default: 1.)')
parser.add_argument('--epochs', type=int, default=20, help='upper epoch limit (default: 20)')
parser.add_argument('--lr', type=float, default=0.001, help='initial learning rate for Adam (default: 0.001)')
parser.add_argument('--emsize', type=int, default=100, help='dimension of item embedding (default: 100)')
parser.add_argument('--neg_size', type=int, default=1, help='size of negative samples (default: 10)')
parser.add_argument('--worker', type=int, default=10, help='number of sampling workers (default: 10)')
parser.add_argument('--nhid', type=int, default=100, help='number of hidden units (default: 100)')
parser.add_argument('--levels', type=int, default=3, help='# of levels (default: 3)')
parser.add_argument('--seed', type=int, default=1111, help='random seed (default: 1111)')
parser.add_argument('--loss', type=str, default='ns', help='type of loss: ns/sampled_sm/full_sm (default: ns)')
parser.add_argument('--data', type=str, default='gowalla', help='data set name (default: gowalla)')
parser.add_argument('--log_interval', type=int, default=1e2, help='log interval (default: 1e2)')
parser.add_argument('--eval_interval', type=int, default=1e3, help='eval/test interval (default: 1e3)')
# ****************************** unique arguments for rnn model. *******************************************************
# None
# ***************************** unique arguemnts for tcn model.
parser.add_argument('--ksize', type=int, default=3, help='kernel size (default: 100)')
# ****************************** unique arguments for transformer model. *************************************************
parser.add_argument('--num_blocks', type=int, default=3, help='num_blocks')
parser.add_argument('--num_heads', type=int, default=2, help='num_heads')
parser.add_argument('--pos_fixed', type=int, default=0, help='trainable positional embedding usually has better performance')
args = parser.parse_args()
tf.set_random_seed(args.seed)
train_data, val_data, test_data, n_items, n_users = data_generator(args)
train_sampler = Sampler(
data=train_data,
n_items=n_items,
n_users=n_users,
batch_size=args.batch_size,
max_len=args.seq_len,
neg_size=args.neg_size,
n_workers=args.worker,
neg_method='rand')
val_data = prepare_eval_test(val_data, batch_size=100, max_test_len= 20)
checkpoint_dir = '_'.join(['save', args.data, args.model, str(args.lr), str(args.l2_reg), str(args.emsize), str(args.dropout)])
print(args)
print ('#Item: ', n_items)
print ('#User: ', n_users)
model = NeuralSeqRecommender(args, n_items, n_users)
lr = args.lr
def evaluate(source, sess):
total_hit_k = 0.0
total_ndcg_k = 0.0
count = 0.0
for batch in source:
feed_dict = {model.inp: batch[1], model.dropout: 0.}
feed_dict[model.pos] = batch[2]
hit, ndcg, n_target = sess.run([model.hit_at_k, model.ndcg_at_k, model.num_target], feed_dict=feed_dict)
count += n_target
total_hit_k += hit
total_ndcg_k += ndcg
val_hit = total_hit_k / count
val_ndcg = total_ndcg_k / count
return [val_hit, val_ndcg]
def main():
global lr
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
init = tf.global_variables_initializer()
sess.run(init)
all_val_hit = [-1]
early_stop_cn = 0
step_count = 0
train_loss_l = 0.
start_time = time.time()
print('Start training...')
try:
while True:
cur_batch = train_sampler.next_batch()
inp = np.array(cur_batch[1])
feed_dict = {model.inp: inp, model.lr: lr, model.dropout: args.dropout}
feed_dict[model.pos] = np.array(cur_batch[2])
feed_dict[model.neg] = np.array(cur_batch[3])
_, train_loss = sess.run([model.train_op, model.loss], feed_dict=feed_dict)
train_loss_l += train_loss
step_count += 1
if step_count % args.log_interval == 0:
cur_loss = train_loss_l / args.log_interval
elapsed = time.time() - start_time
print('| Totol step {:10d} | lr {:02.5f} | ms/batch {:5.2f} | loss {:5.3f}'.format(
step_count, lr, elapsed * 1000 / args.log_interval, cur_loss))
sys.stdout.flush()
train_loss_l = 0.
start_time = time.time()
if step_count % args.eval_interval == 0:
val_hit, val_ndcg = evaluate(val_data, sess)
all_val_hit.append(val_hit)
print('-' * 90)
print('| End of step {:10d} | valid hit@20 {:8.5f} | valid ndcg@20 {:8.5f}'.format(
step_count, val_hit, val_ndcg))
print('=' * 90)
sys.stdout.flush()
if all_val_hit[-1] <= all_val_hit[-2]:
lr /= 2.
lr = max(lr, 1e-6)
early_stop_cn += 1
else:
early_stop_cn = 0
model.saver.save(sess, checkpoint_dir + '/model.ckpt')
if early_stop_cn == 3:
print('Validation hit decreases in three consecutive epochs. Stop Training!')
sys.stdout.flush()
break
start_time = time.time()
except Exception as e:
print(str(e))
train_sampler.close()
exit(1)
train_sampler.close()
print('Done')
if __name__ == '__main__':
if not os.path.exists(checkpoint_dir):
os.mkdir(checkpoint_dir)
main()
| 2,927 |
331 | <reponame>FreddieV4/DailyProgrammerChallenges<gh_stars>100-1000
#Solution by https://github.com/Ouss4
from math import ceil
year = int(input("Enter year: "))
print("Centry : {}".format(ceil(year/100)))
print("Leap Year: {}".format("Yes" if (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)) else "No"))
| 114 |
335 | <gh_stars>100-1000
{
"word": "Stepdaughter",
"definitions": [
"A daughter of one's husband or wife by a previous marriage."
],
"parts-of-speech": "Noun"
} | 74 |
4,812 | //===- NativeTypeArray.cpp - info about arrays ------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/Native/NativeTypeArray.h"
#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
#include "llvm/DebugInfo/PDB/Native/NativeTypeBuiltin.h"
#include "llvm/DebugInfo/PDB/Native/NativeTypeEnum.h"
using namespace llvm;
using namespace llvm::codeview;
using namespace llvm::pdb;
NativeTypeArray::NativeTypeArray(NativeSession &Session, SymIndexId Id,
codeview::TypeIndex TI,
codeview::ArrayRecord Record)
: NativeRawSymbol(Session, PDB_SymType::ArrayType, Id), Record(Record),
Index(TI) {}
NativeTypeArray::~NativeTypeArray() {}
void NativeTypeArray::dump(raw_ostream &OS, int Indent,
PdbSymbolIdField ShowIdFields,
PdbSymbolIdField RecurseIdFields) const {
NativeRawSymbol::dump(OS, Indent, ShowIdFields, RecurseIdFields);
dumpSymbolField(OS, "arrayIndexTypeId", getArrayIndexTypeId(), Indent);
dumpSymbolIdField(OS, "elementTypeId", getTypeId(), Indent, Session,
PdbSymbolIdField::Type, ShowIdFields, RecurseIdFields);
dumpSymbolIdField(OS, "lexicalParentId", 0, Indent, Session,
PdbSymbolIdField::LexicalParent, ShowIdFields,
RecurseIdFields);
dumpSymbolField(OS, "length", getLength(), Indent);
dumpSymbolField(OS, "count", getCount(), Indent);
dumpSymbolField(OS, "constType", isConstType(), Indent);
dumpSymbolField(OS, "unalignedType", isUnalignedType(), Indent);
dumpSymbolField(OS, "volatileType", isVolatileType(), Indent);
}
SymIndexId NativeTypeArray::getArrayIndexTypeId() const {
return Session.getSymbolCache().findSymbolByTypeIndex(Record.getIndexType());
}
bool NativeTypeArray::isConstType() const { return false; }
bool NativeTypeArray::isUnalignedType() const { return false; }
bool NativeTypeArray::isVolatileType() const { return false; }
uint32_t NativeTypeArray::getCount() const {
NativeRawSymbol &Element =
Session.getSymbolCache().getNativeSymbolById(getTypeId());
return getLength() / Element.getLength();
}
SymIndexId NativeTypeArray::getTypeId() const {
return Session.getSymbolCache().findSymbolByTypeIndex(
Record.getElementType());
}
uint64_t NativeTypeArray::getLength() const { return Record.Size; } | 979 |
3,513 | <reponame>jrekoske/jrekoske.github.io<gh_stars>1000+
/*
Copyright 2018 <NAME>
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
https://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.
*/
#include <assert.h>
#include "ascii.h"
#include "token_buffer.h"
#include "tokenizer.h"
#include "util.h"
struct GumboInternalCharacterToken {
GumboSourcePosition position;
GumboStringPiece original_text;
int c;
};
void gumbo_character_token_buffer_init(GumboCharacterTokenBuffer* buffer) {
buffer->data = NULL;
buffer->length = 0;
buffer->capacity = 0;
}
void gumbo_character_token_buffer_append (
const GumboToken* token,
GumboCharacterTokenBuffer* buffer
) {
assert(token->type == GUMBO_TOKEN_WHITESPACE
|| token->type == GUMBO_TOKEN_CHARACTER);
if (buffer->length == buffer->capacity) {
if (buffer->capacity == 0)
buffer->capacity = 10;
else
buffer->capacity *= 2;
size_t bytes = sizeof(*buffer->data) * buffer->capacity;
buffer->data = gumbo_realloc(buffer->data, bytes);
}
size_t index = buffer->length++;
buffer->data[index].position = token->position;
buffer->data[index].original_text = token->original_text;
buffer->data[index].c = token->v.character;
}
void gumbo_character_token_buffer_get (
const GumboCharacterTokenBuffer* buffer,
size_t index,
struct GumboInternalToken* output
) {
assert(index < buffer->length);
int c = buffer->data[index].c;
output->type = gumbo_ascii_isspace(c)?
GUMBO_TOKEN_WHITESPACE : GUMBO_TOKEN_CHARACTER;
output->position = buffer->data[index].position;
output->original_text = buffer->data[index].original_text;
output->v.character = c;
}
void gumbo_character_token_buffer_clear(GumboCharacterTokenBuffer* buffer) {
buffer->length = 0;
}
void gumbo_character_token_buffer_destroy(GumboCharacterTokenBuffer* buffer) {
gumbo_free(buffer->data);
buffer->data = NULL;
buffer->length = 0;
buffer->capacity = 0;
}
| 782 |
32,544 | package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@SpringBootApplication
public class AsyncApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
}
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(value = RuntimeException.class)
public ResponseEntity<Object> exception(RuntimeException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| 261 |
399 | <gh_stars>100-1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint:skip-file
import sys
sys.path.insert(0, "../../python")
import mxnet as mx
import numpy as np
from operator import itemgetter
def nce_loss(data, label, label_weight, embed_weight, vocab_size, num_hidden, num_label):
label_embed = mx.sym.Embedding(data = label, input_dim = vocab_size,
weight = embed_weight,
output_dim = num_hidden, name = 'label_embed')
data = mx.sym.Reshape(data = data, shape = (-1, 1, num_hidden))
pred = mx.sym.broadcast_mul(data, label_embed)
pred = mx.sym.sum(data = pred, axis = 2)
return mx.sym.LogisticRegressionOutput(data = pred,
label = label_weight)
def nce_loss_subwords(data, label, label_mask, label_weight, embed_weight, vocab_size, num_hidden, num_label):
"""NCE-Loss layer under subword-units input.
"""
# get subword-units embedding.
label_units_embed = mx.sym.Embedding(data = label,
input_dim = vocab_size,
weight = embed_weight,
output_dim = num_hidden)
# get valid subword-units embedding with the help of label_mask
# it's achieve by multiply zeros to useless units in order to handle variable-length input.
label_units_embed = mx.sym.broadcast_mul(lhs = label_units_embed,
rhs = label_mask,
name = 'label_units_embed')
# sum over them to get label word embedding.
label_embed = mx.sym.sum(label_units_embed, axis=2, name = 'label_embed')
# by boardcast_mul and sum you can get prediction scores in all num_label inputs,
# which is easy to feed into LogisticRegressionOutput and make your code more concise.
data = mx.sym.Reshape(data = data, shape = (-1, 1, num_hidden))
pred = mx.sym.broadcast_mul(data, label_embed)
pred = mx.sym.sum(data = pred, axis = 2)
return mx.sym.LogisticRegressionOutput(data = pred,
label = label_weight)
class NceAccuracy(mx.metric.EvalMetric):
def __init__(self):
super(NceAccuracy, self).__init__('nce-accuracy')
def update(self, labels, preds):
label_weight = labels[1].asnumpy()
preds = preds[0].asnumpy()
for i in range(preds.shape[0]):
if np.argmax(label_weight[i]) == np.argmax(preds[i]):
self.sum_metric += 1
self.num_inst += 1
class NceAuc(mx.metric.EvalMetric):
def __init__(self):
super(NceAuc, self).__init__('nce-auc')
def update(self, labels, preds):
label_weight = labels[1].asnumpy()
preds = preds[0].asnumpy()
tmp = []
for i in range(preds.shape[0]):
for j in range(preds.shape[1]):
tmp.append((label_weight[i][j], preds[i][j]))
tmp = sorted(tmp, key = itemgetter(1), reverse = True)
m = 0.0
n = 0.0
z = 0.0
k = 0
for a, b in tmp:
if a > 0.5:
m += 1.0
z += len(tmp) - k
else:
n += 1.0
k += 1
z -= m * (m + 1.0) / 2.0
z /= m
z /= n
self.sum_metric += z
self.num_inst += 1
class NceLSTMAuc(mx.metric.EvalMetric):
def __init__(self):
super(NceLSTMAuc, self).__init__('nce-lstm-auc')
def update(self, labels, preds):
preds = np.array([x.asnumpy() for x in preds])
preds = preds.reshape((preds.shape[0] * preds.shape[1], preds.shape[2]))
label_weight = labels[1].asnumpy()
label_weight = label_weight.transpose((1, 0, 2))
label_weight = label_weight.reshape((preds.shape[0], preds.shape[1]))
tmp = []
for i in range(preds.shape[0]):
for j in range(preds.shape[1]):
tmp.append((label_weight[i][j], preds[i][j]))
tmp = sorted(tmp, key = itemgetter(1), reverse = True)
m = 0.0
n = 0.0
z = 0.0
k = 0
for a, b in tmp:
if a > 0.5:
m += 1.0
z += len(tmp) - k
else:
n += 1.0
k += 1
z -= m * (m + 1.0) / 2.0
z /= m
z /= n
self.sum_metric += z
self.num_inst += 1
| 2,500 |
743 | <reponame>TheRakeshPurohit/flutter-embedded-linux<gh_stars>100-1000
// Copyright 2021 Sony Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux_embedded/vsync_waiter.h"
#include <cassert>
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/linux_embedded/logger.h"
namespace flutter {
VsyncWaiter::VsyncWaiter() : event_counter_(0) {}
void VsyncWaiter::NotifyWaitForVsync(intptr_t baton) {
std::lock_guard<std::mutex> lk(mutex_);
baton_ = baton;
event_counter_++;
}
void VsyncWaiter::NotifyVsync(FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterEngineProcTable* embedder_api,
uint64_t frame_start_time_nanos,
uint64_t frame_target_time_nanos) {
std::lock_guard<std::mutex> lk(mutex_);
if (event_counter_ > 0 && baton_ != 0) {
assert(event_counter_ == 1);
event_counter_--;
auto result = embedder_api->OnVsync(engine, baton_, frame_start_time_nanos,
frame_target_time_nanos);
if (result != kSuccess) {
ELINUX_LOG(ERROR) << "FlutterEngineOnVsync failed: batton = " << baton_;
}
}
}
} // namespace flutter
| 592 |
412 | /*******************************************************************\
Module: Statement List Type Helper
Author: <NAME>, <EMAIL>
\*******************************************************************/
/// \file
/// Statement List Type Helper
#ifndef CPROVER_STATEMENT_LIST_CONVERTERS_STATEMENT_LIST_TYPES_H
#define CPROVER_STATEMENT_LIST_CONVERTERS_STATEMENT_LIST_TYPES_H
#define STL_INT_WIDTH 16u
#define STL_DINT_WIDTH 32u
/// Creates a new type that resembles the 'Int' type of the Siemens PLC
/// languages.
/// \return The type object for 'Int'.
class signedbv_typet get_int_type();
/// Creates a new type that resembles the 'DInt' type of the Siemens PLC
/// languages.
/// \return The type object for 'DInt'.
class signedbv_typet get_dint_type();
/// Creates a new type that resembles the 'Real' type of the Siemens PLC
/// languages.
/// \return The type object for 'Real'.
class floatbv_typet get_real_type();
/// Creates a new type that resembles the 'Bool' type of the Siemens PLC
/// languages.
/// \return The type object for 'Bool'.
class bool_typet get_bool_type();
#endif // CPROVER_STATEMENT_LIST_CONVERTERS_STATEMENT_LIST_TYPES_H
| 354 |
14,668 | <reponame>zealoussnow/chromium<gh_stars>1000+
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.media_router;
import com.google.android.gms.cast.MediaInfo;
import com.google.android.gms.cast.MediaMetadata;
import com.google.android.gms.cast.MediaStatus;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* Wrapper layer that exposes a gms.cast.MediaStatus to native code.
* See also media/base/media_status.h.
*/
@JNINamespace("media_router")
public class MediaStatusBridge {
private MediaStatus mStatus;
public MediaStatusBridge(MediaStatus status) {
mStatus = status;
}
/**
* Gets the play state of the stream. Return values are defined as such:
* - PLAYER_STATE_UNKOWN = 0
* - PLAYER_STATE_IDLE = 1
* - PLAYER_STATE_PLAYING = 2
* - PLAYER_STATE_PAUSED = 3
* - PLAYER_STATE_BUFFERING = 4
* See https://developers.google.com/android/reference/com/google/android/gms/cast/MediaStatus
*/
@CalledByNative
public int playerState() {
return mStatus.getPlayerState();
}
/**
* Gets the idle reason. Only meaningful if we are in PLAYER_STATE_IDLE.
* - IDLE_REASON_NONE = 0
* - IDLE_REASON_FINISHED = 1
* - IDLE_REASON_CANCELED = 2
* - IDLE_REASON_INTERRUPTED = 3
* - IDLE_REASON_ERROR = 4
* See https://developers.google.com/android/reference/com/google/android/gms/cast/MediaStatus
*/
@CalledByNative
public int idleReason() {
return mStatus.getIdleReason();
}
/**
* The main title of the media. For example, in a MediaStatus representing
* a YouTube Cast session, this could be the title of the video.
*/
@CalledByNative
public String title() {
MediaInfo info = mStatus.getMediaInfo();
if (info == null) return "";
MediaMetadata metadata = info.getMetadata();
if (metadata == null) return "";
return metadata.getString(MediaMetadata.KEY_TITLE);
}
/**
* If this is true, the media can be played and paused.
*/
@CalledByNative
public boolean canPlayPause() {
return mStatus.isMediaCommandSupported(MediaStatus.COMMAND_PAUSE);
}
/**
* If this is true, the media can be muted and unmuted.
*/
@CalledByNative
public boolean canMute() {
return mStatus.isMediaCommandSupported(MediaStatus.COMMAND_TOGGLE_MUTE);
}
/**
* If this is true, the media's volume can be changed.
*/
@CalledByNative
public boolean canSetVolume() {
return mStatus.isMediaCommandSupported(MediaStatus.COMMAND_SET_VOLUME);
}
/**
* If this is true, the media's current playback position can be chaxnged.
*/
@CalledByNative
public boolean canSeek() {
return mStatus.isMediaCommandSupported(MediaStatus.COMMAND_SEEK);
}
/**
* Returns the stream's mute state.
*/
@CalledByNative
public boolean isMuted() {
return mStatus.isMute();
}
/**
* Current volume of the media, with 1 being the highest and 0 being the
* lowest/no sound. When |is_muted| is true, there should be no sound
* regardless of |volume|.
*/
@CalledByNative
public double volume() {
return mStatus.getStreamVolume();
}
/**
* The length of the media, in ms. A value of zero indicates that this is a media
* with no set duration (e.g. a live stream).
*/
@CalledByNative
public long duration() {
MediaInfo info = mStatus.getMediaInfo();
if (info == null) return 0;
return info.getStreamDuration();
}
/**
* Current playback position, in ms. Must be less than or equal to |duration|.
*/
@CalledByNative
public long currentTime() {
return mStatus.getStreamPosition();
}
}
| 1,541 |
493 | package com.jdh.microcraft.item;
import com.jdh.microcraft.gfx.Color;
import com.jdh.microcraft.item.resource.ItemIngot;
import com.jdh.microcraft.item.resource.ItemOre;
public class Metal {
public static final Metal GOLD =
new Metal("GOLD",4, 5,
441, Color.get(221, 331, 441, 553));
public static final Metal IRON =
new Metal("IRON", 6, 7,
444, Color.get(222, 333, 444, 555));
public static final Metal MITHRIL =
new Metal("MITH", 51, 52,
334, Color.get(222, 224, 335, 555));
public final String name;
public final int oreId, ingotId;
public final int baseColor, color;
public Metal(String name, int oreId, int ingotId, int baseColor, int color) {
this.name = name;
this.baseColor = baseColor;
this.color = color;
this.oreId = oreId;
this.ingotId = ingotId;
}
public ItemOre getOre() {
return (ItemOre) Item.ITEMS[this.oreId];
}
public ItemIngot getIngot() {
return (ItemIngot) Item.ITEMS[this.ingotId];
}
}
| 467 |
1,780 | <filename>core/src/platform/Linux/fonttool.cpp
#include "FontTool.hpp"
#include "utils.hpp"
#include "argh.h"
#include <codecvt>
#include <ft2build.h>
#include <iostream>
#include <locale>
#include <memory>
#include FT_FREETYPE_H
using NSFontTool::TypefaceLoader;
using NSFontTool::TypefaceProvider;
using NSFontTool::TextManager;
void usage(const std::string &cmd) {
std::cerr << "Usage: " << cmd << " <command> <params>" << std::endl << std::endl;
std::cerr << "Available commands:" << std::endl;
std::cerr << " buildCache <dir> [<dir2> ...] Build font cache from directories." << std::endl;
std::cerr << " dumpCache <cacheFile> Dump list of typefaces from cache file." << std::endl;
std::cerr << " outline <text> [<font name>] Export text outlines using prebuilt font cache." << std::endl;
std::cerr << " raster <text> [<font name>] [-s/--size=14] Raster text to image using prebuilt font cache." << std::endl;
std::cerr << std::endl << "For simplicity, cache file defaults to `.fontcache`, and image defaults to `out_<font name>.ppm`)" << std::endl;
std::cerr << std::endl;
}
int main(int argc, const char *argv[]) {
argh::parser cmdl(argc, argv);
if (cmdl.pos_args().size() < 3 || cmdl["h"] || cmdl["help"]) {
usage(cmdl[0]);
return 1;
}
if (cmdl[1] == "buildCache") {
TypefaceLoader *tl = TypefaceLoader::getInstance();
ASSERT(tl);
for (size_t i = 2; i < cmdl.size(); i++) {
tl->buildFontCacheFromDir(cmdl[i]);
}
bool res = tl->exportFontCache(".fontcache");
return res ? 0 : 1;
} else if (cmdl[1] == "dumpCache") {
std::string cacheFile = cmdl[2];
TypefaceLoader *tl = TypefaceLoader::getInstance();
ASSERT(tl);
if (!tl->importFontCache(cacheFile)) {
return 1;
}
tl->dumpFontCache();
return 0;
} else if (cmdl[1] == "outline") {
std::string text = cmdl[2];
std::string fontName = cmdl[3];
TypefaceLoader *tl = TypefaceLoader::getInstance();
ASSERT(tl);
if (!tl->importFontCache(".fontcache")) {
INFO("Please use `buildCache` to build font cache first.");
return 1;
}
tl->dumpFontCache();
TypefaceProvider *tp = TypefaceProvider::getInstance();
ASSERT(tp);
const std::vector<TypefaceProvider::Typeface *> &faces = tp->selectTypefaces(fontName);
TextManager tm;
for (size_t i = 0; i < faces.size(); i++) {
INFO("Using typeface: %s", faces[i]->psName.c_str());
tm.setFont(faces[i]->psName, 14);
ASSERT(tm.exportTextOutlines(text, 0, 0));
}
return 0;
} else if (cmdl[1] == "raster") {
std::string text = cmdl[2];
std::string fontName = cmdl[3];
long fontSize = 14;
cmdl({"-s", "--size"}) >> fontSize;
TypefaceLoader *tl = TypefaceLoader::getInstance();
ASSERT(tl);
if (!tl->importFontCache(".fontcache")) {
INFO("Please use `buildCache` to build font cache first.");
return 1;
}
tl->dumpFontCache();
TypefaceProvider *tp = TypefaceProvider::getInstance();
ASSERT(tp);
const std::vector<TypefaceProvider::Typeface *> &faces = tp->selectTypefaces(fontName);
TextManager tm;
for (size_t i = 0; i < faces.size(); i++) {
INFO("Using typeface: %s", faces[i]->psName.c_str());
tm.setFont(faces[i]->psName, fontSize);
ASSERT(tm.drawText(text, 0, 0));
}
return 0;
} else {
std::cerr << "Invalid command: " << cmdl[1] << std::endl << std::endl;
usage(cmdl[0]);
return 1;
}
return 0;
} | 1,444 |
496 | <filename>source/lexbor/core/in.h
/*
* Copyright (C) 2018 <NAME>
*
* Author: <NAME> <<EMAIL>>
*/
#ifndef LEXBOR_IN_H
#define LEXBOR_IN_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lexbor/core/base.h"
#include "lexbor/core/dobject.h"
typedef struct lexbor_in_node lexbor_in_node_t;
typedef int lexbor_in_opt_t;
enum lexbor_in_opt {
LEXBOR_IN_OPT_UNDEF = 0x00,
LEXBOR_IN_OPT_READONLY = 0x01,
LEXBOR_IN_OPT_DONE = 0x02,
LEXBOR_IN_OPT_FAKE = 0x04,
LEXBOR_IN_OPT_ALLOC = 0x08
};
typedef struct {
lexbor_dobject_t *nodes;
}
lexbor_in_t;
struct lexbor_in_node {
size_t offset;
lexbor_in_opt_t opt;
const lxb_char_t *begin;
const lxb_char_t *end;
const lxb_char_t *use;
lexbor_in_node_t *next;
lexbor_in_node_t *prev;
lexbor_in_t *incoming;
};
LXB_API lexbor_in_t *
lexbor_in_create(void);
LXB_API lxb_status_t
lexbor_in_init(lexbor_in_t *incoming, size_t chunk_size);
LXB_API void
lexbor_in_clean(lexbor_in_t *incoming);
LXB_API lexbor_in_t *
lexbor_in_destroy(lexbor_in_t *incoming, bool self_destroy);
LXB_API lexbor_in_node_t *
lexbor_in_node_make(lexbor_in_t *incoming, lexbor_in_node_t *last_node,
const lxb_char_t *buf, size_t buf_size);
LXB_API void
lexbor_in_node_clean(lexbor_in_node_t *node);
LXB_API lexbor_in_node_t *
lexbor_in_node_destroy(lexbor_in_t *incoming,
lexbor_in_node_t *node, bool self_destroy);
LXB_API lexbor_in_node_t *
lexbor_in_node_split(lexbor_in_node_t *node, const lxb_char_t *pos);
LXB_API lexbor_in_node_t *
lexbor_in_node_find(lexbor_in_node_t *node, const lxb_char_t *pos);
/**
* Get position by `offset`.
* If position outside of nodes return `begin` position of first node
* in nodes chain.
*/
LXB_API const lxb_char_t *
lexbor_in_node_pos_up(lexbor_in_node_t *node, lexbor_in_node_t **return_node,
const lxb_char_t *pos, size_t offset);
/**
* Get position by `offset`.
* If position outside of nodes return `end`
* position of last node in nodes chain.
*/
LXB_API const lxb_char_t *
lexbor_in_node_pos_down(lexbor_in_node_t *node, lexbor_in_node_t **return_node,
const lxb_char_t *pos, size_t offset);
/*
* Inline functions
*/
lxb_inline const lxb_char_t *
lexbor_in_node_begin(const lexbor_in_node_t *node)
{
return node->begin;
}
lxb_inline const lxb_char_t *
lexbor_in_node_end(const lexbor_in_node_t *node)
{
return node->end;
}
lxb_inline size_t
lexbor_in_node_offset(const lexbor_in_node_t *node)
{
return node->offset;
}
lxb_inline lexbor_in_node_t *
lexbor_in_node_next(const lexbor_in_node_t *node)
{
return node->next;
}
lxb_inline lexbor_in_node_t *
lexbor_in_node_prev(const lexbor_in_node_t *node)
{
return node->prev;
}
lxb_inline lexbor_in_t *
lexbor_in_node_in(const lexbor_in_node_t *node)
{
return node->incoming;
}
lxb_inline bool
lexbor_in_segment(const lexbor_in_node_t *node, const lxb_char_t *data)
{
return node->begin <= data && node->end >= data;
}
/*
* No inline functions for ABI.
*/
const lxb_char_t *
lexbor_in_node_begin_noi(const lexbor_in_node_t *node);
const lxb_char_t *
lexbor_in_node_end_noi(const lexbor_in_node_t *node);
size_t
lexbor_in_node_offset_noi(const lexbor_in_node_t *node);
lexbor_in_node_t *
lexbor_in_node_next_noi(const lexbor_in_node_t *node);
lexbor_in_node_t *
lexbor_in_node_prev_noi(const lexbor_in_node_t *node);
lexbor_in_t *
lexbor_in_node_in_noi(const lexbor_in_node_t *node);
bool
lexbor_in_segment_noi(const lexbor_in_node_t *node, const lxb_char_t *data);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* LEXBOR_IN_H */
| 1,759 |
732 | {
"year":"1 jaro|:count jaroj",
"y":"1 jaro|:count jaroj",
"month":"1 monato|:count monatoj",
"m":"1 monato|:count monatoj",
"week":"1 semajno|:count semajnoj",
"w":"1 semajno|:count semajnoj",
"day":"1 tago|:count tagoj",
"d":"1 tago|:count tagoj",
"hour":"1 horo|:count horoj",
"h":"1 horo|:count horoj",
"minute":"1 minuto|:count minutoj",
"min":"1 minuto|:count minutoj",
"second":"1 sekundo|:count sekundoj",
"s":"1 sekundo|:count sekundoj",
"ago":"antaŭ :time",
"from_now":"je :time",
"after":":time poste",
"before":":time antaŭe"
}
| 301 |
852 | #include "RecoEgamma/EgammaMCTools/interface/PhotonMCTruthFinder.h"
#include "RecoEgamma/EgammaMCTools/interface/PhotonMCTruth.h"
#include "RecoEgamma/EgammaMCTools/interface/ElectronMCTruth.h"
//
//
#include "SimDataFormats/CrossingFrame/interface/CrossingFrame.h"
#include "SimDataFormats/CrossingFrame/interface/MixCollection.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingParticleFwd.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingVertexContainer.h"
#include <algorithm>
PhotonMCTruthFinder::PhotonMCTruthFinder() {
//std::cout << " PhotonMCTruthFinder CTOR " << std::endl;
}
std::vector<PhotonMCTruth> PhotonMCTruthFinder::find(const std::vector<SimTrack>& theSimTracks,
const std::vector<SimVertex>& theSimVertices) {
// std::cout << " PhotonMCTruthFinder::find " << std::endl;
std::vector<PhotonMCTruth> result;
//const float pi = 3.141592653592;
//const float twopi=2*pi;
// Local variables
const int SINGLE = 1;
const int DOUBLE = 2;
const int PYTHIA = 3;
const int ELECTRON_FLAV = 1;
const int PIZERO_FLAV = 2;
const int PHOTON_FLAV = 3;
int ievtype = 0;
int ievflav = 0;
std::vector<SimTrack*> photonTracks;
std::vector<SimTrack> trkFromConversion;
std::vector<ElectronMCTruth> electronsFromConversions;
SimVertex primVtx;
fill(theSimTracks, theSimVertices);
// std::cout << " After fill " << theSimTracks.size() << " " << theSimVertices.size() << std::endl;
if (!theSimTracks.empty()) {
int iPV = -1;
int partType1 = 0;
int partType2 = 0;
std::vector<SimTrack>::const_iterator iFirstSimTk = theSimTracks.begin();
if (!(*iFirstSimTk).noVertex()) {
iPV = (*iFirstSimTk).vertIndex();
int vtxId = (*iFirstSimTk).vertIndex();
primVtx = theSimVertices[vtxId];
partType1 = (*iFirstSimTk).type();
// std::cout << " Primary vertex id " << iPV << " first track type " << (*iFirstSimTk).type() << std::endl;
} else {
//std::cout << " First track has no vertex " << std::endl;
}
math::XYZTLorentzVectorD primVtxPos(
primVtx.position().x(), primVtx.position().y(), primVtx.position().z(), primVtx.position().e());
// Look at a second track
iFirstSimTk++;
if (iFirstSimTk != theSimTracks.end()) {
if ((*iFirstSimTk).vertIndex() == iPV) {
partType2 = (*iFirstSimTk).type();
// std::cout << " second track type " << (*iFirstSimTk).type() << " vertex " << (*iFirstSimTk).vertIndex() << std::endl;
} else {
// std::cout << " Only one kine track from Primary Vertex " << std::endl;
}
}
//std::cout << " Loop over all particles " << std::endl;
int npv = 0;
//int iPho=0;
//int iPizero=0;
// theSimTracks.reset();
for (std::vector<SimTrack>::const_iterator iSimTk = theSimTracks.begin(); iSimTk != theSimTracks.end(); ++iSimTk) {
if ((*iSimTk).noVertex())
continue;
//int vertexId = (*iSimTk).vertIndex();
//SimVertex vertex = theSimVertices[vertexId];
// std::cout << " Particle type " << (*iSimTk).type() << " Sim Track ID " << (*iSimTk).trackId() << " momentum " << (*iSimTk).momentum() << " vertex position " << vertex.position() << " vertex index " << (*iSimTk).vertIndex() << std::endl;
if ((*iSimTk).vertIndex() == iPV) {
npv++;
if ((*iSimTk).type() == 22) {
// std::cout << " Found a primary photon with ID " << (*iSimTk).trackId() << " momentum " << (*iSimTk).momentum() << std::endl;
photonTracks.push_back(&(const_cast<SimTrack&>(*iSimTk)));
}
}
}
// std::cout << " There are " << npv << " particles originating in the PV " << std::endl;
if (npv >= 3) {
ievtype = PYTHIA;
} else if (npv == 1) {
if (std::abs(partType1) == 11) {
ievtype = SINGLE;
ievflav = ELECTRON_FLAV;
} else if (partType1 == 111) {
ievtype = SINGLE;
ievflav = PIZERO_FLAV;
} else if (partType1 == 22) {
ievtype = SINGLE;
ievflav = PHOTON_FLAV;
}
} else if (npv == 2) {
if (std::abs(partType1) == 11 && std::abs(partType2) == 11) {
ievtype = DOUBLE;
ievflav = ELECTRON_FLAV;
} else if (partType1 == 111 && partType2 == 111) {
ievtype = DOUBLE;
ievflav = PIZERO_FLAV;
} else if (partType1 == 22 && partType2 == 22) {
ievtype = DOUBLE;
ievflav = PHOTON_FLAV;
}
}
////// Look into converted photons
int isAconversion = 0;
int phoMotherType = -1;
int phoMotherVtxIndex = -1;
int phoMotherId = -1;
if (ievflav == PHOTON_FLAV || ievflav == PIZERO_FLAV || ievtype == PYTHIA) {
// std::cout << " It's a primary PHOTON or PIZERO or PYTHIA event with " << photonTracks.size() << " photons ievtype " << ievtype << " ievflav " << ievflav<< std::endl;
// for (std::vector<SimTrack*>::iterator iPhoTk = photonTracks.begin(); iPhoTk != photonTracks.end(); ++iPhoTk){
// std::cout << " All gamma found from PV " << (*iPhoTk)->momentum() << " photon track ID " << (*iPhoTk)->trackId() << " vertex index " << (*iPhoTk)->vertIndex() << std::endl;
// }
for (std::vector<SimTrack>::const_iterator iPhoTk = theSimTracks.begin(); iPhoTk != theSimTracks.end();
++iPhoTk) {
trkFromConversion.clear();
electronsFromConversions.clear();
if ((*iPhoTk).type() != 22)
continue;
int photonVertexIndex = (*iPhoTk).vertIndex();
int phoTrkId = (*iPhoTk).trackId();
//std::cout << " Looping on gamma looking for conversions " << (*iPhoTk).momentum() << " photon track ID " << (*iPhoTk).trackId() << std::endl;
// check who is his mother
SimVertex vertex = theSimVertices[photonVertexIndex];
phoMotherId = -1;
if (vertex.parentIndex() != -1) {
unsigned motherGeantId = vertex.parentIndex();
std::map<unsigned, unsigned>::iterator association = geantToIndex_.find(motherGeantId);
if (association != geantToIndex_.end())
phoMotherId = association->second;
phoMotherType = phoMotherId == -1 ? 0 : theSimTracks[phoMotherId].type();
if (phoMotherType == 111 || phoMotherType == 221 || phoMotherType == 331) {
//std::cout << " Parent to this vertex motherId " << phoMotherId << " mother type " << phoMotherType << " Sim track ID " << theSimTracks[phoMotherId].trackId() << std::endl;
//std::cout << " Son of a pizero or eta " << phoMotherType << std::endl;
}
}
for (std::vector<SimTrack>::const_iterator iEleTk = theSimTracks.begin(); iEleTk != theSimTracks.end();
++iEleTk) {
if ((*iEleTk).noVertex())
continue;
if ((*iEleTk).vertIndex() == iPV)
continue;
if (std::abs((*iEleTk).type()) != 11)
continue;
int vertexId = (*iEleTk).vertIndex();
SimVertex vertex = theSimVertices[vertexId];
int motherId = -1;
//std::cout << " Secondary from photons particle type " << (*iEleTk).type() << " trackId " << (*iEleTk).trackId() << " vertex ID " << vertexId << std::endl;
if (vertex.parentIndex() != -1) {
unsigned motherGeantId = vertex.parentIndex();
std::map<unsigned, unsigned>::iterator association = geantToIndex_.find(motherGeantId);
if (association != geantToIndex_.end())
motherId = association->second;
//int motherType = motherId == -1 ? 0 : theSimTracks[motherId].type();
//std::cout << " Parent to this vertex motherId " << motherId << " mother type " << motherType << " Sim track ID " << theSimTracks[motherId].trackId() << std::endl;
std::vector<CLHEP::Hep3Vector> bremPos;
std::vector<CLHEP::HepLorentzVector> pBrem;
std::vector<float> xBrem;
if (theSimTracks[motherId].trackId() == (*iPhoTk).trackId()) {
//std::cout << " Found the Mother Photon " << std::endl;
/// find truth about this electron and store it since it's from a converted photon
trkFromConversion.push_back((*iEleTk));
SimTrack trLast = (*iEleTk);
float remainingEnergy = trLast.momentum().e();
//HepLorentzVector primEleMom=(*iEleTk).momentum();
//HepLorentzVector motherMomentum=(*iEleTk).momentum();
math::XYZTLorentzVectorD primEleMom((*iEleTk).momentum().x(),
(*iEleTk).momentum().y(),
(*iEleTk).momentum().z(),
(*iEleTk).momentum().e());
math::XYZTLorentzVectorD motherMomentum(primEleMom);
unsigned int eleId = (*iEleTk).trackId();
int eleVtxIndex = (*iEleTk).vertIndex();
bremPos.clear();
pBrem.clear();
xBrem.clear();
for (std::vector<SimTrack>::const_iterator iSimTk = theSimTracks.begin(); iSimTk != theSimTracks.end();
++iSimTk) {
if ((*iSimTk).noVertex())
continue;
if ((*iSimTk).vertIndex() == iPV)
continue;
//std::cout << " (*iEleTk)->trackId() " << (*iEleTk).trackId() << " (*iEleTk)->vertIndex() "<< (*iEleTk).vertIndex() << " (*iSimTk).vertIndex() " << (*iSimTk).vertIndex() << " (*iSimTk).type() " << (*iSimTk).type() << " (*iSimTk).trackId() " << (*iSimTk).trackId() << std::endl;
int vertexId1 = (*iSimTk).vertIndex();
SimVertex vertex1 = theSimVertices[vertexId1];
int vertexId2 = trLast.vertIndex();
//SimVertex vertex2 = theSimVertices[vertexId2];
int motherId = -1;
if ((vertexId1 == vertexId2) && ((*iSimTk).type() == (*iEleTk).type()) && trLast.type() == 22) {
//std::cout << " Here a e/gamma brem vertex " << std::endl;
//std::cout << " Secondary from electron: particle1 type " << (*iSimTk).type() << " trackId " << (*iSimTk).trackId() << " vertex ID " << vertexId1 << " vertex position " << sqrt(vertex1.position().perp2()) << " parent index "<< vertex1.parentIndex() << std::endl;
//std::cout << " Secondary from electron: particle2 type " << trLast.type() << " trackId " << trLast.trackId() << " vertex ID " << vertexId2 << " vertex position " << sqrt(vertex2.position().perp2()) << " parent index " << vertex2.parentIndex() << std::endl;
//std::cout << " Electron pt " << sqrt((*iSimTk).momentum().perp2()) << " photon pt " << sqrt(trLast.momentum().perp2()) << " Mother electron pt " << sqrt(motherMomentum.perp2()) << std::endl;
//std::cout << " eleId " << eleId << std::endl;
float eLoss = remainingEnergy - ((*iSimTk).momentum() + trLast.momentum()).e();
//std::cout << " eLoss " << eLoss << std::endl;
if (vertex1.parentIndex() != -1) {
unsigned motherGeantId = vertex1.parentIndex();
std::map<unsigned, unsigned>::iterator association = geantToIndex_.find(motherGeantId);
if (association != geantToIndex_.end())
motherId = association->second;
//int motherType = motherId == -1 ? 0 : theSimTracks[motherId].type();
//std::cout << " Parent to this vertex motherId " << motherId << " mother type " << motherType << " Sim track ID " << theSimTracks[motherId].trackId() << std::endl;
if (theSimTracks[motherId].trackId() == eleId) {
//std::cout << " ***** Found the Initial Mother Electron **** theSimTracks[motherId].trackId() " << theSimTracks[motherId].trackId() << " eleId " << eleId << std::endl;
eleId = (*iSimTk).trackId();
remainingEnergy = (*iSimTk).momentum().e();
motherMomentum = (*iSimTk).momentum();
pBrem.push_back(CLHEP::HepLorentzVector(trLast.momentum().px(),
trLast.momentum().py(),
trLast.momentum().pz(),
trLast.momentum().e()));
bremPos.push_back(CLHEP::HepLorentzVector(vertex1.position().x(),
vertex1.position().y(),
vertex1.position().z(),
vertex1.position().t()));
xBrem.push_back(eLoss);
}
} else {
//std::cout << " This vertex has no parent tracks " << std::endl;
}
}
trLast = (*iSimTk);
} // End loop over all SimTracks
//std::cout << " Going to build the ElectronMCTruth for this electron from converted photon: pBrem size " << pBrem.size() << std::endl;
/// here fill the electron
CLHEP::HepLorentzVector tmpEleMom(primEleMom.px(), primEleMom.py(), primEleMom.pz(), primEleMom.e());
CLHEP::HepLorentzVector tmpVtxPos(primVtxPos.x(), primVtxPos.y(), primVtxPos.z(), primVtxPos.t());
electronsFromConversions.push_back(ElectronMCTruth(
tmpEleMom, eleVtxIndex, bremPos, pBrem, xBrem, tmpVtxPos, const_cast<SimTrack&>(*iEleTk)));
} //// Electron from conversion found
} else {
//std::cout << " This vertex has no parent tracks " << std::endl;
}
} // End of loop over the SimTracks
//std::cout << " DEBUG trkFromConversion.size() " << trkFromConversion.size() << " electronsFromConversions.size() " << electronsFromConversions.size() << std::endl;
math::XYZTLorentzVectorD motherVtxPosition(0., 0., 0., 0.);
CLHEP::HepLorentzVector phoMotherMom(0., 0., 0., 0.);
CLHEP::HepLorentzVector phoMotherVtx(0., 0., 0., 0.);
if (phoMotherId >= 0) {
phoMotherVtxIndex = theSimTracks[phoMotherId].vertIndex();
SimVertex motherVtx = theSimVertices[phoMotherVtxIndex];
motherVtxPosition = math::XYZTLorentzVectorD(
motherVtx.position().x(), motherVtx.position().y(), motherVtx.position().z(), motherVtx.position().e());
phoMotherMom.setPx(theSimTracks[phoMotherId].momentum().x());
phoMotherMom.setPy(theSimTracks[phoMotherId].momentum().y());
phoMotherMom.setPz(theSimTracks[phoMotherId].momentum().z());
phoMotherMom.setE(theSimTracks[phoMotherId].momentum().t());
// std::cout << " PhotonMCTruthFinder mother " << phoMotherId << " type " << phoMotherType << " Momentum" << phoMotherMom.et() << std::endl;
phoMotherVtx.setX(motherVtxPosition.x());
phoMotherVtx.setY(motherVtxPosition.y());
phoMotherVtx.setZ(motherVtxPosition.z());
phoMotherVtx.setT(motherVtxPosition.t());
}
if (!electronsFromConversions.empty()) {
// if ( trkFromConversion.size() > 0 ) {
isAconversion = 1;
//std::cout << " CONVERTED photon " << "\n";
//int convVtxId = trkFromConversion[0].vertIndex();
int convVtxId = electronsFromConversions[0].vertexInd();
SimVertex convVtx = theSimVertices[convVtxId];
// CLHEP::HepLorentzVector vtxPosition = convVtx.position();
math::XYZTLorentzVectorD vtxPosition(
convVtx.position().x(), convVtx.position().y(), convVtx.position().z(), convVtx.position().e());
//result.push_back( PhotonMCTruth(isAconversion, (*iPhoTk).momentum(), photonVertexIndex, phoTrkId, vtxPosition, primVtx.position(), trkFromConversion ));
CLHEP::HepLorentzVector tmpPhoMom((*iPhoTk).momentum().px(),
(*iPhoTk).momentum().py(),
(*iPhoTk).momentum().pz(),
(*iPhoTk).momentum().e());
CLHEP::HepLorentzVector tmpVertex(vtxPosition.x(), vtxPosition.y(), vtxPosition.z(), vtxPosition.t());
CLHEP::HepLorentzVector tmpPrimVtx(primVtxPos.x(), primVtxPos.y(), primVtxPos.z(), primVtxPos.t());
result.push_back(PhotonMCTruth(isAconversion,
tmpPhoMom,
photonVertexIndex,
phoTrkId,
phoMotherType,
phoMotherMom,
phoMotherVtx,
tmpVertex,
tmpPrimVtx,
electronsFromConversions));
} else {
isAconversion = 0;
//std::cout << " UNCONVERTED photon " << "\n";
CLHEP::HepLorentzVector vtxPosition(0., 0., 0., 0.);
CLHEP::HepLorentzVector tmpPhoMom((*iPhoTk).momentum().px(),
(*iPhoTk).momentum().py(),
(*iPhoTk).momentum().pz(),
(*iPhoTk).momentum().e());
CLHEP::HepLorentzVector tmpPrimVtx(primVtxPos.x(), primVtxPos.y(), primVtxPos.z(), primVtxPos.t());
// result.push_back( PhotonMCTruth(isAconversion, (*iPhoTk).momentum(), photonVertexIndex, phoTrkId, vtxPosition, primVtx.position(), trkFromConversion ));
result.push_back(PhotonMCTruth(isAconversion,
tmpPhoMom,
photonVertexIndex,
phoTrkId,
phoMotherType,
phoMotherMom,
phoMotherVtx,
vtxPosition,
tmpPrimVtx,
electronsFromConversions));
}
} // End loop over the primary photons
} // Event with one or two photons
//std::cout << " PhotonMCTruthFinder photon size " << result.size() << std::endl;
}
return result;
}
void PhotonMCTruthFinder::fill(const std::vector<SimTrack>& simTracks, const std::vector<SimVertex>& simVertices) {
// std::cout << " PhotonMCTruthFinder::fill " << std::endl;
// Watch out there ! A SimVertex is in mm (stupid),
unsigned nVtx = simVertices.size();
unsigned nTks = simTracks.size();
// std::cout << " PhotonMCTruthFinder::fill " << nVtx << " " << nTks << std::endl;
// Empty event, do nothin'
if (nVtx == 0)
return;
// create a map associating geant particle id and position in the
// event SimTrack vector
for (unsigned it = 0; it < nTks; ++it) {
geantToIndex_[simTracks[it].trackId()] = it;
// std::cout << " PhotonMCTruthFinder::fill it " << it << " simTracks[it].trackId() " << simTracks[it].trackId() << std::endl;
}
}
| 9,723 |
637 | /*
* The MIT License
*
* Copyright 2014 <NAME>.
*
* 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.
*/
package jenkins.model;
import hudson.Functions;
import hudson.Util;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeFalse;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
public class RunIdMigratorTest {
@Rule public TemporaryFolder tmp = new TemporaryFolder();
/** Ensures that legacy timestamps are interpreted in a predictable time zone. */
@BeforeClass public static void timezone() {
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
}
// TODO could use LoggerRule only if it were extracted to an independent library
@BeforeClass public static void logging() {
RunIdMigrator.LOGGER.setLevel(Level.ALL);
Handler handler = new ConsoleHandler();
handler.setLevel(Level.ALL);
RunIdMigrator.LOGGER.addHandler(handler);
}
private RunIdMigrator migrator;
private File dir;
@Before public void init() {
migrator = new RunIdMigrator();
dir = tmp.getRoot();
}
@Test public void newJob() throws Exception {
migrator.created(dir);
assertEquals("{legacyIds=''}", summarize());
assertEquals(0, migrator.findNumber("whatever"));
migrator.delete(dir, "1");
migrator = new RunIdMigrator();
assertFalse(migrator.migrate(dir, null));
assertEquals("{legacyIds=''}", summarize());
}
@Test public void legacy() throws Exception {
assumeFalse("Symlinks don't work well on Windows", Functions.isWindows());
write("2014-01-02_03-04-05/build.xml", "<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <number>99</number>\n <otherstuff>ok</otherstuff>\n</run>");
link("99", "2014-01-02_03-04-05");
link("lastFailedBuild", "-1");
link("lastSuccessfulBuild", "99");
assertEquals("{2014-01-02_03-04-05={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <number>99</number>\n <otherstuff>ok</otherstuff>\n</run>'}, 99=→2014-01-02_03-04-05, lastFailedBuild=→-1, lastSuccessfulBuild=→99}", summarize());
assertTrue(migrator.migrate(dir, null));
assertEquals("{99={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <id>2014-01-02_03-04-05</id>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>'}, lastFailedBuild=→-1, lastSuccessfulBuild=→99, legacyIds='2014-01-02_03-04-05 99\n'}", summarize());
assertEquals(99, migrator.findNumber("2014-01-02_03-04-05"));
migrator = new RunIdMigrator();
assertFalse(migrator.migrate(dir, null));
assertEquals(99, migrator.findNumber("2014-01-02_03-04-05"));
migrator.delete(dir, "2014-01-02_03-04-05");
FileUtils.deleteDirectory(new File(dir, "99"));
new File(dir, "lastSuccessfulBuild").delete();
assertEquals("{lastFailedBuild=→-1, legacyIds=''}", summarize());
}
@Test public void reRunMigration() throws Exception {
assumeFalse("Symlinks don't work well on Windows", Functions.isWindows());
write("2014-01-02_03-04-04/build.xml", "<run>\n <number>98</number>\n</run>");
link("98", "2014-01-02_03-04-04");
write("99/build.xml", "<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>");
link("lastFailedBuild", "-1");
link("lastSuccessfulBuild", "99");
assertEquals("{2014-01-02_03-04-04={build.xml='<run>\n <number>98</number>\n</run>'}, 98=→2014-01-02_03-04-04, 99={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>'}, lastFailedBuild=→-1, lastSuccessfulBuild=→99}", summarize());
assertTrue(migrator.migrate(dir, null));
assertEquals("{98={build.xml='<run>\n <id>2014-01-02_03-04-04</id>\n <timestamp>1388649844000</timestamp>\n</run>'}, 99={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>'}, lastFailedBuild=→-1, lastSuccessfulBuild=→99, legacyIds='2014-01-02_03-04-04 98\n'}", summarize());
}
@Test public void reverseImmediately() throws Exception {
assumeFalse("Symlinks don't work well on Windows", Functions.isWindows());
File root = dir;
dir = new File(dir, "jobs/somefolder/jobs/someproject/promotions/OK/builds");
write("99/build.xml", "<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <id>2014-01-02_03-04-05</id>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>");
link("lastFailedBuild", "-1");
link("lastSuccessfulBuild", "99");
write("legacyIds", "2014-01-02_03-04-05 99\n");
assertEquals("{99={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <id>2014-01-02_03-04-05</id>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>'}, lastFailedBuild=→-1, lastSuccessfulBuild=→99, legacyIds='2014-01-02_03-04-05 99\n'}", summarize());
RunIdMigrator.main(root.getAbsolutePath());
assertEquals("{2014-01-02_03-04-05={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <number>99</number>\n <otherstuff>ok</otherstuff>\n</run>'}, 99=→2014-01-02_03-04-05, lastFailedBuild=→-1, lastSuccessfulBuild=→99}", summarize());
}
@Test public void reverseAfterNewBuilds() throws Exception {
assumeFalse("Symlinks don't work well on Windows", Functions.isWindows());
File root = dir;
dir = new File(dir, "jobs/someproject/modules/test$test/builds");
write("1/build.xml", "<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>");
write("legacyIds", "");
assertEquals("{1={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>'}, legacyIds=''}", summarize());
RunIdMigrator.main(root.getAbsolutePath());
assertEquals("{1=→2014-01-02_03-04-05, 2014-01-02_03-04-05={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <number>1</number>\n <otherstuff>ok</otherstuff>\n</run>'}}", summarize());
}
@Test public void reverseMatrixAfterNewBuilds() throws Exception {
assumeFalse("Symlinks don't work well on Windows", Functions.isWindows());
File root = dir;
dir = new File(dir, "jobs/someproject/Environment=prod/builds");
write("1/build.xml", "<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>");
write("legacyIds", "");
assertEquals("{1={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>'}, legacyIds=''}", summarize());
RunIdMigrator.main(root.getAbsolutePath());
assertEquals("{1=→2014-01-02_03-04-05, 2014-01-02_03-04-05={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <number>1</number>\n <otherstuff>ok</otherstuff>\n</run>'}}", summarize());
}
@Test public void reverseMavenAfterNewBuilds() throws Exception {
assumeFalse("Symlinks don't work well on Windows", Functions.isWindows());
File root = dir;
dir = new File(dir, "jobs/someproject/test$test/builds");
write("1/build.xml", "<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>");
write("legacyIds", "");
assertEquals("{1={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <timestamp>1388649845000</timestamp>\n <otherstuff>ok</otherstuff>\n</run>'}, legacyIds=''}", summarize());
RunIdMigrator.main(root.getAbsolutePath());
assertEquals("{1=→2014-01-02_03-04-05, 2014-01-02_03-04-05={build.xml='<?xml version='1.0' encoding='UTF-8'?>\n<run>\n <stuff>ok</stuff>\n <number>1</number>\n <otherstuff>ok</otherstuff>\n</run>'}}", summarize());
}
// TODO test sane recovery from various error conditions
private void write(String file, String text) throws Exception {
FileUtils.write(new File(dir, file), text);
}
private void link(String symlink, String dest) throws Exception {
Util.createSymlink(dir, dest, symlink, new StreamTaskListener(System.out, Charset.defaultCharset()));
}
private String summarize() throws Exception {
return summarize(dir);
}
private static String summarize(File dir) throws Exception {
File[] kids = dir.listFiles();
Map<String,String> m = new TreeMap<String,String>();
for (File kid : kids) {
String notation;
String symlink = Util.resolveSymlink(kid);
if (symlink != null) {
notation = "→" + symlink;
} else if (kid.isFile()) {
notation = "'" + FileUtils.readFileToString(kid) + "'";
} else if (kid.isDirectory()) {
notation = summarize(kid);
} else {
notation = "?";
}
m.put(kid.getName(), notation);
}
return m.toString();
}
@Test public void move() throws Exception {
File src = tmp.newFile();
File dest = new File(tmp.getRoot(), "dest");
RunIdMigrator.move(src, dest);
File dest2 = tmp.newFile();
try {
RunIdMigrator.move(dest, dest2);
fail();
} catch (IOException x) {
System.err.println("Got expected move exception: " + x);
}
}
}
| 4,736 |
907 | package org.jbox2d.testbed.tests;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.EdgeShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.testbed.framework.TestbedTest;
public class EdgeTest extends TestbedTest {
@Override
public void initTest(boolean deserialized) {
{
Body ground = getGroundBody();
Vec2 v1 = new Vec2(-10.0f, 0.0f), v2 = new Vec2(-7.0f, -2.0f), v3 = new Vec2(-4.0f, 0.0f);
Vec2 v4 = new Vec2(0.0f, 0.0f), v5 = new Vec2(4.0f, 0.0f), v6 = new Vec2(7.0f, 2.0f), v7 =
new Vec2(10.0f, 0.0f);
EdgeShape shape = new EdgeShape();
shape.set(v1, v2);
shape.m_hasVertex3 = true;
shape.m_vertex3.set(v3);
ground.createFixture(shape, 0.0f);
shape.set(v2, v3);
shape.m_hasVertex0 = true;
shape.m_hasVertex3 = true;
shape.m_vertex0.set(v1);
shape.m_vertex3.set(v4);
ground.createFixture(shape, 0.0f);
shape.set(v3, v4);
shape.m_hasVertex0 = true;
shape.m_hasVertex3 = true;
shape.m_vertex0.set(v2);
shape.m_vertex3.set(v5);
ground.createFixture(shape, 0.0f);
shape.set(v4, v5);
shape.m_hasVertex0 = true;
shape.m_hasVertex3 = true;
shape.m_vertex0.set(v3);
shape.m_vertex3.set(v6);
ground.createFixture(shape, 0.0f);
shape.set(v5, v6);
shape.m_hasVertex0 = true;
shape.m_hasVertex3 = true;
shape.m_vertex0.set(v4);
shape.m_vertex3.set(v7);
ground.createFixture(shape, 0.0f);
shape.set(v6, v7);
shape.m_hasVertex0 = true;
shape.m_vertex0.set(v5);
ground.createFixture(shape, 0.0f);
}
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(-0.5f, 0.6f);
bd.allowSleep = false;
Body body = m_world.createBody(bd);
CircleShape shape = new CircleShape();
shape.m_radius = 0.5f;
body.createFixture(shape, 1.0f);
}
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(1.0f, 0.6f);
bd.allowSleep = false;
Body body = m_world.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.5f, 0.5f);
body.createFixture(shape, 1.0f);
}
}
@Override
public String getTestName() {
return "Edge Test";
}
}
| 1,269 |
3,631 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.testcoverage.regression;
import org.assertj.core.api.Assertions;
import org.drools.testcoverage.common.KieSessionTest;
import org.drools.testcoverage.common.model.Message;
import org.drools.testcoverage.common.util.*;
import org.junit.Test;
import org.junit.runners.Parameterized;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class GlobalOnLHSTest extends KieSessionTest {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalOnLHSTest.class);
private static final String DRL_FILE = "bz1019473.drl";
public GlobalOnLHSTest(final KieBaseTestConfiguration kieBaseTestConfiguration,
final KieSessionTestConfiguration kieSessionTestConfiguration) {
super(kieBaseTestConfiguration, kieSessionTestConfiguration);
}
@Parameterized.Parameters(name = "{1}" + " (from " + "{0}" + ")")
public static Collection<Object[]> getParameters() {
return TestParametersUtil.getKieBaseAndStatefulKieSessionConfigurations();
}
@Test
public void testNPEOnMutableGlobal() throws Exception {
KieSession ksession = session.getStateful();
List<String> context = new ArrayList<String>();
ksession.setGlobal("context", context);
ksession.setGlobal("LOGGER", LOGGER);
FactHandle b = ksession.insert( new Message( "b" ) );
ksession.delete(b);
int fired = ksession.fireAllRules(1);
Assertions.assertThat(fired).isEqualTo(0);
ksession.dispose();
}
@Override
protected Resource[] createResources() {
return KieUtil.createResources(DRL_FILE, GlobalOnLHSTest.class);
}
}
| 850 |
911 | <reponame>buketkonuk/pythondotorg
import datetime
from django.utils import timezone
from django.test import TestCase
from ..utils import (
seconds_resolution, minutes_resolution, timedelta_nice_repr, timedelta_parse,
)
class EventsUtilsTests(TestCase):
def test_seconds_resolution(self):
now = timezone.now()
t = seconds_resolution(now)
self.assertEqual(t.microsecond, 0)
def test_minutes_resolution(self):
now = timezone.now()
t = minutes_resolution(now)
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 0)
def test_timedelta_nice_repr(self):
tests = [
(dict(days=1, hours=2, minutes=3, seconds=4), (),
'1 day, 2 hours, 3 minutes, 4 seconds'),
(dict(days=1, seconds=1), ('minimal',), '1d, 1s'),
(dict(days=1), (), '1 day'),
(dict(days=0), (), '0 seconds'),
(dict(seconds=1), (), '1 second'),
(dict(seconds=10), (), '10 seconds'),
(dict(seconds=30), (), '30 seconds'),
(dict(seconds=60), (), '1 minute'),
(dict(seconds=150), (), '2 minutes, 30 seconds'),
(dict(seconds=1800), (), '30 minutes'),
(dict(seconds=3600), (), '1 hour'),
(dict(seconds=3601), (), '1 hour, 1 second'),
(dict(seconds=3601), (), '1 hour, 1 second'),
(dict(seconds=19800), (), '5 hours, 30 minutes'),
(dict(seconds=91800), (), '1 day, 1 hour, 30 minutes'),
(dict(seconds=302400), (), '3 days, 12 hours'),
(dict(seconds=0), ('minimal',), '0s'),
(dict(seconds=0), ('short',), '0 sec'),
(dict(seconds=0), ('long',), '0 seconds'),
]
for timedelta, arguments, expected in tests:
with self.subTest(timedelta=timedelta, arguments=arguments):
self.assertEqual(
timedelta_nice_repr(datetime.timedelta(**timedelta), *arguments),
expected
)
self.assertRaises(TypeError, timedelta_nice_repr, '')
def test_timedelta_parse(self):
tests = [
('1 day', datetime.timedelta(1)),
('2 days', datetime.timedelta(2)),
('1 d', datetime.timedelta(1)),
('1 hour', datetime.timedelta(0, 3600)),
('1 hours', datetime.timedelta(0, 3600)),
('1 hr', datetime.timedelta(0, 3600)),
('1 hrs', datetime.timedelta(0, 3600)),
('1h', datetime.timedelta(0, 3600)),
('1wk', datetime.timedelta(7)),
('1 week', datetime.timedelta(7)),
('1 weeks', datetime.timedelta(7)),
('2 weeks', datetime.timedelta(14)),
('1 sec', datetime.timedelta(0, 1)),
('1 secs', datetime.timedelta(0, 1)),
('1 s', datetime.timedelta(0, 1)),
('1 second', datetime.timedelta(0, 1)),
('1 seconds', datetime.timedelta(0, 1)),
('1 minute', datetime.timedelta(0, 60)),
('1 min', datetime.timedelta(0, 60)),
('1 m', datetime.timedelta(0, 60)),
('1 minutes', datetime.timedelta(0, 60)),
('1 mins', datetime.timedelta(0, 60)),
('1.5 days', datetime.timedelta(1, 43200)),
('3 weeks', datetime.timedelta(21)),
('4.2 hours', datetime.timedelta(0, 15120)),
('.5 hours', datetime.timedelta(0, 1800)),
('1 hour, 5 mins', datetime.timedelta(0, 3900)),
('-2 days', datetime.timedelta(-2)),
('-1 day 0:00:01', datetime.timedelta(-1, 1)),
('-1 day, -1:01:01', datetime.timedelta(-2, 82739)),
('-1 weeks, 2 days, -3 hours, 4 minutes, -5 seconds',
datetime.timedelta(-5, 11045)),
('0 seconds', datetime.timedelta(0)),
('0 days', datetime.timedelta(0)),
('0 weeks', datetime.timedelta(0)),
]
for string, timedelta in tests:
with self.subTest(string=string):
self.assertEqual(timedelta_parse(string), timedelta)
def test_timedelta_parse_invalid(self):
tests = [
('2 ws', TypeError),
('2 ds', TypeError),
('2 hs', TypeError),
('2 ms', TypeError),
('2 aa', TypeError),
('', TypeError),
(' hours', TypeError),
]
for string, exception in tests:
with self.subTest(string=string):
self.assertRaises(exception, timedelta_parse, string)
| 2,299 |
5,169 | {
"name": "ObjectiveHAL",
"version": "1.0.0",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"homepage": "https://github.com/ObjectiveHAL/ObjectiveHAL",
"summary": "Objective-C implementation of the JSON Hypertext Application Language.",
"authors": {
"<NAME>": "<EMAIL>",
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/ObjectiveHAL/ObjectiveHAL.git",
"tag": "1.0.0"
},
"platforms": {
"ios": "6.1"
},
"source_files": [
"ObjectiveHAL",
"ObjectiveHAL/**/*.{h,m}"
],
"public_header_files": "ObjectiveHAL/*.h",
"requires_arc": true,
"dependencies": {
"CSURITemplate": [
],
"AFNetworking": [
"~> 1.3"
]
},
"frameworks": [
"Security",
"SystemConfiguration",
"MobileCoreServices",
"CoreGraphics"
]
}
| 367 |
445 | from matplotlib import docstring, transforms
from matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox,
DrawingArea, TextArea, VPacker)
from matplotlib.patches import (Rectangle, Ellipse, ArrowStyle,
FancyArrowPatch, PathPatch)
from matplotlib.text import TextPath
__all__ = ['AnchoredDrawingArea', 'AnchoredAuxTransformBox',
'AnchoredEllipse', 'AnchoredSizeBar', 'AnchoredDirectionArrows']
class AnchoredDrawingArea(AnchoredOffsetbox):
@docstring.dedent
def __init__(self, width, height, xdescent, ydescent,
loc, pad=0.4, borderpad=0.5, prop=None, frameon=True,
**kwargs):
"""
An anchored container with a fixed size and fillable DrawingArea.
Artists added to the *drawing_area* will have their coordinates
interpreted as pixels. Any transformations set on the artists will be
overridden.
Parameters
----------
width, height : int or float
width and height of the container, in pixels.
xdescent, ydescent : int or float
descent of the container in the x- and y- direction, in pixels.
loc : int
Location of this artist. Valid location codes are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10
pad : int or float, optional
Padding around the child objects, in fraction of the font
size. Defaults to 0.4.
borderpad : int or float, optional
Border padding, in fraction of the font size.
Defaults to 0.5.
prop : `matplotlib.font_manager.FontProperties`, optional
Font property used as a reference for paddings.
frameon : bool, optional
If True, draw a box around this artists. Defaults to True.
**kwargs :
Keyworded arguments to pass to
:class:`matplotlib.offsetbox.AnchoredOffsetbox`.
Attributes
----------
drawing_area : `matplotlib.offsetbox.DrawingArea`
A container for artists to display.
Examples
--------
To display blue and red circles of different sizes in the upper right
of an axes *ax*:
>>> ada = AnchoredDrawingArea(20, 20, 0, 0,
... loc='upper right', frameon=False)
>>> ada.drawing_area.add_artist(Circle((10, 10), 10, fc="b"))
>>> ada.drawing_area.add_artist(Circle((30, 10), 5, fc="r"))
>>> ax.add_artist(ada)
"""
self.da = DrawingArea(width, height, xdescent, ydescent)
self.drawing_area = self.da
super().__init__(
loc, pad=pad, borderpad=borderpad, child=self.da, prop=None,
frameon=frameon, **kwargs
)
class AnchoredAuxTransformBox(AnchoredOffsetbox):
@docstring.dedent
def __init__(self, transform, loc,
pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs):
"""
An anchored container with transformed coordinates.
Artists added to the *drawing_area* are scaled according to the
coordinates of the transformation used. The dimensions of this artist
will scale to contain the artists added.
Parameters
----------
transform : `matplotlib.transforms.Transform`
The transformation object for the coordinate system in use, i.e.,
:attr:`matplotlib.axes.Axes.transData`.
loc : int
Location of this artist. Valid location codes are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10
pad : int or float, optional
Padding around the child objects, in fraction of the font
size. Defaults to 0.4.
borderpad : int or float, optional
Border padding, in fraction of the font size.
Defaults to 0.5.
prop : `matplotlib.font_manager.FontProperties`, optional
Font property used as a reference for paddings.
frameon : bool, optional
If True, draw a box around this artists. Defaults to True.
**kwargs :
Keyworded arguments to pass to
:class:`matplotlib.offsetbox.AnchoredOffsetbox`.
Attributes
----------
drawing_area : `matplotlib.offsetbox.AuxTransformBox`
A container for artists to display.
Examples
--------
To display an ellipse in the upper left, with a width of 0.1 and
height of 0.4 in data coordinates:
>>> box = AnchoredAuxTransformBox(ax.transData, loc='upper left')
>>> el = Ellipse((0,0), width=0.1, height=0.4, angle=30)
>>> box.drawing_area.add_artist(el)
>>> ax.add_artist(box)
"""
self.drawing_area = AuxTransformBox(transform)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=self.drawing_area,
prop=prop,
frameon=frameon,
**kwargs)
class AnchoredEllipse(AnchoredOffsetbox):
@docstring.dedent
def __init__(self, transform, width, height, angle, loc,
pad=0.1, borderpad=0.1, prop=None, frameon=True, **kwargs):
"""
Draw an anchored ellipse of a given size.
Parameters
----------
transform : `matplotlib.transforms.Transform`
The transformation object for the coordinate system in use, i.e.,
:attr:`matplotlib.axes.Axes.transData`.
width, height : int or float
Width and height of the ellipse, given in coordinates of
*transform*.
angle : int or float
Rotation of the ellipse, in degrees, anti-clockwise.
loc : int
Location of this size bar. Valid location codes are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10
pad : int or float, optional
Padding around the ellipse, in fraction of the font size. Defaults
to 0.1.
borderpad : int or float, optional
Border padding, in fraction of the font size. Defaults to 0.1.
frameon : bool, optional
If True, draw a box around the ellipse. Defaults to True.
prop : `matplotlib.font_manager.FontProperties`, optional
Font property used as a reference for paddings.
**kwargs :
Keyworded arguments to pass to
:class:`matplotlib.offsetbox.AnchoredOffsetbox`.
Attributes
----------
ellipse : `matplotlib.patches.Ellipse`
Ellipse patch drawn.
"""
self._box = AuxTransformBox(transform)
self.ellipse = Ellipse((0, 0), width, height, angle)
self._box.add_artist(self.ellipse)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=self._box,
prop=prop,
frameon=frameon, **kwargs)
class AnchoredSizeBar(AnchoredOffsetbox):
@docstring.dedent
def __init__(self, transform, size, label, loc,
pad=0.1, borderpad=0.1, sep=2,
frameon=True, size_vertical=0, color='black',
label_top=False, fontproperties=None, fill_bar=None,
**kwargs):
"""
Draw a horizontal scale bar with a center-aligned label underneath.
Parameters
----------
transform : `matplotlib.transforms.Transform`
The transformation object for the coordinate system in use, i.e.,
:attr:`matplotlib.axes.Axes.transData`.
size : int or float
Horizontal length of the size bar, given in coordinates of
*transform*.
label : str
Label to display.
loc : int
Location of this size bar. Valid location codes are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10
pad : int or float, optional
Padding around the label and size bar, in fraction of the font
size. Defaults to 0.1.
borderpad : int or float, optional
Border padding, in fraction of the font size.
Defaults to 0.1.
sep : int or float, optional
Separation between the label and the size bar, in points.
Defaults to 2.
frameon : bool, optional
If True, draw a box around the horizontal bar and label.
Defaults to True.
size_vertical : int or float, optional
Vertical length of the size bar, given in coordinates of
*transform*. Defaults to 0.
color : str, optional
Color for the size bar and label.
Defaults to black.
label_top : bool, optional
If True, the label will be over the size bar.
Defaults to False.
fontproperties : `matplotlib.font_manager.FontProperties`, optional
Font properties for the label text.
fill_bar : bool, optional
If True and if size_vertical is nonzero, the size bar will
be filled in with the color specified by the size bar.
Defaults to True if `size_vertical` is greater than
zero and False otherwise.
**kwargs :
Keyworded arguments to pass to
:class:`matplotlib.offsetbox.AnchoredOffsetbox`.
Attributes
----------
size_bar : `matplotlib.offsetbox.AuxTransformBox`
Container for the size bar.
txt_label : `matplotlib.offsetbox.TextArea`
Container for the label of the size bar.
Notes
-----
If *prop* is passed as a keyworded argument, but *fontproperties* is
not, then *prop* is be assumed to be the intended *fontproperties*.
Using both *prop* and *fontproperties* is not supported.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from mpl_toolkits.axes_grid1.anchored_artists import (
... AnchoredSizeBar)
>>> fig, ax = plt.subplots()
>>> ax.imshow(np.random.random((10,10)))
>>> bar = AnchoredSizeBar(ax.transData, 3, '3 data units', 4)
>>> ax.add_artist(bar)
>>> fig.show()
Using all the optional parameters
>>> import matplotlib.font_manager as fm
>>> fontprops = fm.FontProperties(size=14, family='monospace')
>>> bar = AnchoredSizeBar(ax.transData, 3, '3 units', 4, pad=0.5,
... sep=5, borderpad=0.5, frameon=False,
... size_vertical=0.5, color='white',
... fontproperties=fontprops)
"""
if fill_bar is None:
fill_bar = size_vertical > 0
self.size_bar = AuxTransformBox(transform)
self.size_bar.add_artist(Rectangle((0, 0), size, size_vertical,
fill=fill_bar, facecolor=color,
edgecolor=color))
if fontproperties is None and 'prop' in kwargs:
fontproperties = kwargs.pop('prop')
if fontproperties is None:
textprops = {'color': color}
else:
textprops = {'color': color, 'fontproperties': fontproperties}
self.txt_label = TextArea(
label,
minimumdescent=False,
textprops=textprops)
if label_top:
_box_children = [self.txt_label, self.size_bar]
else:
_box_children = [self.size_bar, self.txt_label]
self._box = VPacker(children=_box_children,
align="center",
pad=0, sep=sep)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=self._box,
prop=fontproperties,
frameon=frameon, **kwargs)
class AnchoredDirectionArrows(AnchoredOffsetbox):
@docstring.dedent
def __init__(self, transform, label_x, label_y, length=0.15,
fontsize=0.08, loc=2, angle=0, aspect_ratio=1, pad=0.4,
borderpad=0.4, frameon=False, color='w', alpha=1,
sep_x=0.01, sep_y=0, fontproperties=None, back_length=0.15,
head_width=10, head_length=15, tail_width=2,
text_props=None, arrow_props=None,
**kwargs):
"""
Draw two perpendicular arrows to indicate directions.
Parameters
----------
transform : `matplotlib.transforms.Transform`
The transformation object for the coordinate system in use, i.e.,
:attr:`matplotlib.axes.Axes.transAxes`.
label_x, label_y : string
Label text for the x and y arrows
length : int or float, optional
Length of the arrow, given in coordinates of
*transform*.
Defaults to 0.15.
fontsize : int, optional
Size of label strings, given in coordinates of *transform*.
Defaults to 0.08.
loc : int, optional
Location of the direction arrows. Valid location codes are::
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10
Defaults to 2.
angle : int or float, optional
The angle of the arrows in degrees.
Defaults to 0.
aspect_ratio : int or float, optional
The ratio of the length of arrow_x and arrow_y.
Negative numbers can be used to change the direction.
Defaults to 1.
pad : int or float, optional
Padding around the labels and arrows, in fraction of the font
size. Defaults to 0.4.
borderpad : int or float, optional
Border padding, in fraction of the font size.
Defaults to 0.4.
frameon : bool, optional
If True, draw a box around the arrows and labels.
Defaults to False.
color : str, optional
Color for the arrows and labels.
Defaults to white.
alpha : int or float, optional
Alpha values of the arrows and labels
Defaults to 1.
sep_x, sep_y : int or float, optional
Separation between the arrows and labels in coordinates of
*transform*. Defaults to 0.01 and 0.
fontproperties : `matplotlib.font_manager.FontProperties`, optional
Font properties for the label text.
back_length : float, optional
Fraction of the arrow behind the arrow crossing.
Defaults to 0.15.
head_width : int or float, optional
Width of arrow head, sent to ArrowStyle.
Defaults to 10.
head_length : int or float, optional
Length of arrow head, sent to ArrowStyle.
Defaults to 15.
tail_width : int or float, optional
Width of arrow tail, sent to ArrowStyle.
Defaults to 2.
text_props, arrow_props : dict
Properties of the text and arrows, passed to
:class:`matplotlib.text.TextPath` and
`matplotlib.patches.FancyArrowPatch`
**kwargs :
Keyworded arguments to pass to
:class:`matplotlib.offsetbox.AnchoredOffsetbox`.
Attributes
----------
arrow_x, arrow_y : `matplotlib.patches.FancyArrowPatch`
Arrow x and y
text_path_x, text_path_y : `matplotlib.text.TextPath`
Path for arrow labels
p_x, p_y : `matplotlib.patches.PathPatch`
Patch for arrow labels
box : `matplotlib.offsetbox.AuxTransformBox`
Container for the arrows and labels.
Notes
-----
If *prop* is passed as a keyword argument, but *fontproperties* is
not, then *prop* is be assumed to be the intended *fontproperties*.
Using both *prop* and *fontproperties* is not supported.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from mpl_toolkits.axes_grid1.anchored_artists import (
... AnchoredDirectionArrows)
>>> fig, ax = plt.subplots()
>>> ax.imshow(np.random.random((10,10)))
>>> arrows = AnchoredDirectionArrows(ax.transAxes, '111', '110')
>>> ax.add_artist(arrows)
>>> fig.show()
Using several of the optional parameters, creating downward pointing
arrow and high contrast text labels.
>>> import matplotlib.font_manager as fm
>>> fontprops = fm.FontProperties(family='monospace')
>>> arrows = AnchoredDirectionArrows(ax.transAxes, 'East', 'South',
... loc='lower left', color='k',
... aspect_ratio=-1, sep_x=0.02,
... sep_y=-0.01,
... text_props={'ec':'w', 'fc':'k'},
... fontproperties=fontprops)
"""
if arrow_props is None:
arrow_props = {}
if text_props is None:
text_props = {}
arrowstyle = ArrowStyle("Simple",
head_width=head_width,
head_length=head_length,
tail_width=tail_width)
if fontproperties is None and 'prop' in kwargs:
fontproperties = kwargs.pop('prop')
if 'color' not in arrow_props:
arrow_props['color'] = color
if 'alpha' not in arrow_props:
arrow_props['alpha'] = alpha
if 'color' not in text_props:
text_props['color'] = color
if 'alpha' not in text_props:
text_props['alpha'] = alpha
t_start = transform
t_end = t_start + transforms.Affine2D().rotate_deg(angle)
self.box = AuxTransformBox(t_end)
length_x = length
length_y = length*aspect_ratio
self.arrow_x = FancyArrowPatch(
(0, back_length*length_y),
(length_x, back_length*length_y),
arrowstyle=arrowstyle,
shrinkA=0.0,
shrinkB=0.0,
**arrow_props)
self.arrow_y = FancyArrowPatch(
(back_length*length_x, 0),
(back_length*length_x, length_y),
arrowstyle=arrowstyle,
shrinkA=0.0,
shrinkB=0.0,
**arrow_props)
self.box.add_artist(self.arrow_x)
self.box.add_artist(self.arrow_y)
text_path_x = TextPath((
length_x+sep_x, back_length*length_y+sep_y), label_x,
size=fontsize, prop=fontproperties)
self.p_x = PathPatch(text_path_x, transform=t_start, **text_props)
self.box.add_artist(self.p_x)
text_path_y = TextPath((
length_x*back_length+sep_x, length_y*(1-back_length)+sep_y),
label_y, size=fontsize, prop=fontproperties)
self.p_y = PathPatch(text_path_y, **text_props)
self.box.add_artist(self.p_y)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=self.box,
frameon=frameon, **kwargs)
| 10,332 |
488 | import pydiffvg
import torch
import skimage
import numpy as np
import matplotlib.pyplot as plt
# Use GPU if available
pydiffvg.set_use_gpu(torch.cuda.is_available())
canvas_width, canvas_height = 256, 256
num_control_points = torch.tensor([1])
points = torch.tensor([[ 50.0, 30.0], # base
[125.0, 400.0], # control point
[170.0, 30.0]]) # base
path = pydiffvg.Path(num_control_points = num_control_points,
points = points,
stroke_width = torch.tensor([30.0]),
is_closed = False,
use_distance_approx = False)
shapes = [path]
path_group = pydiffvg.ShapeGroup(shape_ids = torch.tensor([0]),
fill_color = None,
stroke_color = torch.tensor([0.5, 0.5, 0.5, 0.5]))
shape_groups = [path_group]
scene_args = pydiffvg.RenderFunction.serialize_scene(\
canvas_width, canvas_height, shapes, shape_groups,
output_type = pydiffvg.OutputType.sdf)
render = pydiffvg.RenderFunction.apply
img = render(256, # width
256, # height
1, # num_samples_x
1, # num_samples_y
0, # seed
None, # background_image
*scene_args)
img /= 256.0
cm = plt.get_cmap('viridis')
img = cm(img.squeeze())
pydiffvg.imwrite(img, 'results/quadratic_distance_approx/ref_sdf.png')
scene_args = pydiffvg.RenderFunction.serialize_scene(\
canvas_width, canvas_height, shapes, shape_groups)
img = render(256, # width
256, # height
2, # num_samples_x
2, # num_samples_y
0, # seed
None, # background_image
*scene_args)
pydiffvg.imwrite(img, 'results/quadratic_distance_approx/ref_color.png')
shapes[0].use_distance_approx = True
scene_args = pydiffvg.RenderFunction.serialize_scene(\
canvas_width, canvas_height, shapes, shape_groups,
output_type = pydiffvg.OutputType.sdf)
img = render(256, # width
256, # height
1, # num_samples_x
1, # num_samples_y
0, # seed
None, # background_image
*scene_args)
img /= 256.0
img = cm(img.squeeze())
pydiffvg.imwrite(img, 'results/quadratic_distance_approx/approx_sdf.png')
scene_args = pydiffvg.RenderFunction.serialize_scene(\
canvas_width, canvas_height, shapes, shape_groups)
img = render(256, # width
256, # height
2, # num_samples_x
2, # num_samples_y
0, # seed
None, # background_image
*scene_args)
pydiffvg.imwrite(img, 'results/quadratic_distance_approx/approx_color.png') | 1,355 |
370 | <filename>worldedit-bukkit/adapters/adapter-1_18/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/fawe/v1_18_R1/PaperweightStarlightRelighterFactory.java
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1;
import com.fastasyncworldedit.core.extent.processor.lighting.NullRelighter;
import com.fastasyncworldedit.core.extent.processor.lighting.RelightMode;
import com.fastasyncworldedit.core.extent.processor.lighting.Relighter;
import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory;
import com.fastasyncworldedit.core.queue.IQueueChunk;
import com.fastasyncworldedit.core.queue.IQueueExtent;
import com.sk89q.worldedit.world.World;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld;
import javax.annotation.Nonnull;
public class PaperweightStarlightRelighterFactory implements RelighterFactory {
@Override
public @Nonnull
Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) {
org.bukkit.World w = Bukkit.getWorld(world.getName());
if (w == null) {
return NullRelighter.INSTANCE;
}
return new PaperweightStarlightRelighter(((CraftWorld) w).getHandle(), queue);
}
}
| 463 |
679 | <filename>main/sfx2/source/bastyp/frmhtmlw.cxx
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifndef _INETDEF_HXX
#include <svl/inetdef.hxx>
#endif
#include "svtools/htmlkywd.hxx"
//!(dv) #include <chaos2/cntapi.hxx>
#include <rtl/tencinfo.h>
#include <unotools/configmgr.hxx>
#include "svl/urihelper.hxx"
#include <tools/datetime.hxx>
#include <sfx2/frmhtmlw.hxx>
#include <sfx2/evntconf.hxx>
#include <sfx2/frame.hxx>
#include <sfx2/app.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/docfile.hxx>
#include "sfx2/sfxresid.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/sfx.hrc>
#include "bastyp.hrc"
#include <comphelper/string.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/script/XTypeConverter.hpp>
#include <com/sun/star/document/XDocumentProperties.hpp>
// -----------------------------------------------------------------------
using namespace ::com::sun::star;
static sal_Char __READONLY_DATA sHTML_SC_yes[] = "YES";
static sal_Char __READONLY_DATA sHTML_SC_no[] = "NO";
static sal_Char __READONLY_DATA sHTML_SC_auto[] = "AUTO";
static sal_Char __READONLY_DATA sHTML_MIME_text_html[] = "text/html; charset=";
/* not used anymore?
static HTMLOutEvent __FAR_DATA aFrameSetEventTable[] =
{
{ sHTML_O_SDonload, sHTML_O_onload, SFX_EVENT_OPENDOC },
{ sHTML_O_SDonunload, sHTML_O_onunload, SFX_EVENT_PREPARECLOSEDOC },
{ sHTML_O_SDonfocus, sHTML_O_onfocus, SFX_EVENT_ACTIVATEDOC },
{ sHTML_O_SDonblur, sHTML_O_onblur, SFX_EVENT_DEACTIVATEDOC },
{ 0, 0, 0 }
};
*/
#if defined(UNX)
const sal_Char SfxFrameHTMLWriter::sNewLine[] = "\012";
#else
const sal_Char __FAR_DATA SfxFrameHTMLWriter::sNewLine[] = "\015\012";
#endif
void SfxFrameHTMLWriter::OutMeta( SvStream& rStrm,
const sal_Char *pIndent,
const String& rName,
const String& rContent, sal_Bool bHTTPEquiv,
rtl_TextEncoding eDestEnc,
String *pNonConvertableChars )
{
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
ByteString sOut( '<' );
(((sOut += OOO_STRING_SVTOOLS_HTML_meta) += ' ')
+= (bHTTPEquiv ? OOO_STRING_SVTOOLS_HTML_O_httpequiv : OOO_STRING_SVTOOLS_HTML_O_name)) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rName, eDestEnc, pNonConvertableChars );
((sOut = "\" ") += OOO_STRING_SVTOOLS_HTML_O_content) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rContent, eDestEnc, pNonConvertableChars ) << "\">";
}
void SfxFrameHTMLWriter::Out_DocInfo( SvStream& rStrm, const String& rBaseURL,
const uno::Reference<document::XDocumentProperties> & i_xDocProps,
const sal_Char *pIndent,
rtl_TextEncoding eDestEnc,
String *pNonConvertableChars )
{
const sal_Char *pCharSet =
rtl_getBestMimeCharsetFromTextEncoding( eDestEnc );
if( pCharSet )
{
String aContentType = String::CreateFromAscii( sHTML_MIME_text_html );
aContentType.AppendAscii( pCharSet );
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_content_type, aContentType, sal_True,
eDestEnc, pNonConvertableChars );
}
// Titel (auch wenn er leer ist)
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
HTMLOutFuncs::Out_AsciiTag( rStrm, OOO_STRING_SVTOOLS_HTML_title );
if( i_xDocProps.is() )
{
const String& rTitle = i_xDocProps->getTitle();
if( rTitle.Len() )
HTMLOutFuncs::Out_String( rStrm, rTitle, eDestEnc, pNonConvertableChars );
}
HTMLOutFuncs::Out_AsciiTag( rStrm, OOO_STRING_SVTOOLS_HTML_title, sal_False );
// Target-Frame
if( i_xDocProps.is() )
{
const String& rTarget = i_xDocProps->getDefaultTarget();
if( rTarget.Len() )
{
rStrm << sNewLine;
if( pIndent )
rStrm << pIndent;
ByteString sOut( '<' );
(((sOut += OOO_STRING_SVTOOLS_HTML_base) += ' ') += OOO_STRING_SVTOOLS_HTML_O_target) += "=\"";
rStrm << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rStrm, rTarget, eDestEnc, pNonConvertableChars )
<< "\">";
}
}
// Who we are
String sGenerator( SfxResId( STR_HTML_GENERATOR ) );
sGenerator.SearchAndReplaceAscii( "%1", String( DEFINE_CONST_UNICODE( TOOLS_INETDEF_OS ) ) );
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_generator, sGenerator, sal_False, eDestEnc, pNonConvertableChars );
if( i_xDocProps.is() )
{
// Reload
if( (i_xDocProps->getAutoloadSecs() != 0) ||
!i_xDocProps->getAutoloadURL().equalsAscii("") )
{
String sContent = String::CreateFromInt32(
i_xDocProps->getAutoloadSecs() );
const String &rReloadURL = i_xDocProps->getAutoloadURL();
if( rReloadURL.Len() )
{
sContent.AppendAscii( ";URL=" );
sContent += String(
URIHelper::simpleNormalizedMakeRelative(
rBaseURL, rReloadURL));
}
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_refresh, sContent, sal_True,
eDestEnc, pNonConvertableChars );
}
// Author
const String& rAuthor = i_xDocProps->getAuthor();
if( rAuthor.Len() )
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_author, rAuthor, sal_False,
eDestEnc, pNonConvertableChars );
// created
::util::DateTime uDT = i_xDocProps->getCreationDate();
Date aD(uDT.Day, uDT.Month, uDT.Year);
Time aT(uDT.Hours, uDT.Minutes, uDT.Seconds, uDT.HundredthSeconds);
String sOut = String::CreateFromInt32(aD.GetDate());
sOut += ';';
sOut += String::CreateFromInt32(aT.GetTime());
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_created, sOut, sal_False,
eDestEnc, pNonConvertableChars );
// changedby
const String& rChangedBy = i_xDocProps->getModifiedBy();
if( rChangedBy.Len() )
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_changedby, rChangedBy, sal_False,
eDestEnc, pNonConvertableChars );
// changed
uDT = i_xDocProps->getModificationDate();
Date aD2(uDT.Day, uDT.Month, uDT.Year);
Time aT2(uDT.Hours, uDT.Minutes, uDT.Seconds, uDT.HundredthSeconds);
sOut = String::CreateFromInt32(aD2.GetDate());
sOut += ';';
sOut += String::CreateFromInt32(aT2.GetTime());
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_changed, sOut, sal_False,
eDestEnc, pNonConvertableChars );
// Subject
const String& rTheme = i_xDocProps->getSubject();
if( rTheme.Len() )
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_classification, rTheme, sal_False,
eDestEnc, pNonConvertableChars );
// Description
const String& rComment = i_xDocProps->getDescription();
if( rComment.Len() )
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_description, rComment, sal_False,
eDestEnc, pNonConvertableChars);
// Keywords
String Keywords = ::comphelper::string::convertCommaSeparated(
i_xDocProps->getKeywords());
if( Keywords.Len() )
OutMeta( rStrm, pIndent, OOO_STRING_SVTOOLS_HTML_META_keywords, Keywords, sal_False,
eDestEnc, pNonConvertableChars);
uno::Reference < script::XTypeConverter > xConverter(
::comphelper::getProcessServiceFactory()->createInstance(
::rtl::OUString::createFromAscii("com.sun.star.script.Converter")),
uno::UNO_QUERY_THROW );
uno::Reference<beans::XPropertySet> xUserDefinedProps(
i_xDocProps->getUserDefinedProperties(), uno::UNO_QUERY_THROW);
DBG_ASSERT(xUserDefinedProps.is(), "UserDefinedProperties is null");
uno::Reference<beans::XPropertySetInfo> xPropInfo =
xUserDefinedProps->getPropertySetInfo();
DBG_ASSERT(xPropInfo.is(), "UserDefinedProperties Info is null");
uno::Sequence<beans::Property> props = xPropInfo->getProperties();
for (sal_Int32 i = 0; i < props.getLength(); ++i) {
try {
::rtl::OUString name = props[i].Name;
::rtl::OUString str;
uno::Any aStr = xConverter->convertToSimpleType(
xUserDefinedProps->getPropertyValue(name),
uno::TypeClass_STRING);
aStr >>= str;
String valstr(str);
valstr.EraseTrailingChars();
OutMeta( rStrm, pIndent, name, valstr, sal_False,
eDestEnc, pNonConvertableChars );
} catch (uno::Exception &) {
// may happen with concurrent modification...
DBG_WARNING("SfxFrameHTMLWriter::Out_DocInfo: exception");
}
}
}
}
/*
void SfxFrameHTMLWriter::OutHeader( rtl_TextEncoding eDestEnc )
{
// <HTML>
// <HEAD>
// <TITLE>Titel</TITLE>
// </HEAD>
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_html ) << sNewLine;
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head );
Out_DocInfo( Strm(), &pDoc->GetDocInfo(), "\t", eDestEnc );
Strm() << sNewLine;
HTMLOutFuncs::Out_AsciiTag( Strm(), sHTML_head, sal_False ) << sNewLine;
//! OutScript(); // Hier fehlen noch die Scripten im Header
}
*/
void SfxFrameHTMLWriter::Out_FrameDescriptor(
SvStream& rOut, const String& rBaseURL, const uno::Reference < beans::XPropertySet >& xSet,
rtl_TextEncoding eDestEnc, String *pNonConvertableChars )
{
try
{
ByteString sOut;
::rtl::OUString aStr;
uno::Any aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameURL") );
if ( (aAny >>= aStr) && aStr.getLength() )
{
String aURL = INetURLObject( aStr ).GetMainURL( INetURLObject::DECODE_TO_IURI );
if( aURL.Len() )
{
aURL = URIHelper::simpleNormalizedMakeRelative(
rBaseURL, aURL );
((sOut += ' ') += OOO_STRING_SVTOOLS_HTML_O_src) += "=\"";
rOut << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rOut, aURL, eDestEnc, pNonConvertableChars );
sOut = '\"';
}
}
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameName") );
if ( (aAny >>= aStr) && aStr.getLength() )
{
((sOut += ' ') += OOO_STRING_SVTOOLS_HTML_O_name) += "=\"";
rOut << sOut.GetBuffer();
HTMLOutFuncs::Out_String( rOut, aStr, eDestEnc, pNonConvertableChars );
sOut = '\"';
}
sal_Int32 nVal = SIZE_NOT_SET;
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameMarginWidth") );
if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )
(((sOut += ' ') += OOO_STRING_SVTOOLS_HTML_O_marginwidth) += '=') += ByteString::CreateFromInt32( nVal );
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameMarginHeight") );
if ( (aAny >>= nVal) && nVal != SIZE_NOT_SET )
(((sOut += ' ') += OOO_STRING_SVTOOLS_HTML_O_marginheight) += '=') += ByteString::CreateFromInt32( nVal );
sal_Bool bVal = sal_True;
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsAutoScroll") );
if ( (aAny >>= bVal) && !bVal )
{
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsScrollingMode") );
if ( aAny >>= bVal )
{
const sal_Char *pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;
(((sOut += ' ') += OOO_STRING_SVTOOLS_HTML_O_scrolling) += '=') += pStr;
}
}
// frame border (MS+Netscape-Erweiterung)
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsAutoBorder") );
if ( (aAny >>= bVal) && !bVal )
{
aAny = xSet->getPropertyValue( ::rtl::OUString::createFromAscii("FrameIsBorder") );
if ( aAny >>= bVal )
{
const char* pStr = bVal ? sHTML_SC_yes : sHTML_SC_no;
(((sOut += ' ') += OOO_STRING_SVTOOLS_HTML_O_frameborder) += '=') += pStr;
}
}
// TODO/LATER: currently not supported attributes
// resize
//if( !pFrame->IsResizable() )
// (sOut += ' ') += sHTML_O_noresize;
//
//if ( pFrame->GetWallpaper() )
//{
// ((sOut += ' ') += sHTML_O_bordercolor) += '=';
// rOut << sOut.GetBuffer();
// HTMLOutFuncs::Out_Color( rOut, pFrame->GetWallpaper()->GetColor(), eDestEnc );
//}
//else
rOut << sOut.GetBuffer();
}
catch ( uno::Exception& )
{
}
}
String SfxFrameHTMLWriter::CreateURL( SfxFrame* pFrame )
{
String aRet;
SfxObjectShell* pShell = pFrame->GetCurrentDocument();
if( !aRet.Len() && pShell )
{
aRet = pShell->GetMedium()->GetName();
//!(dv) CntAnchor::ToPresentationURL( aRet );
}
return aRet;
}
| 6,426 |
624 | #!/usr/bin/python
# This script creates a clone of a remote repository in local memory,
# then adds a single file and pushes the result back.
#
# Example usage:
# python examples/memoryrepo.py git+ssh://github.com/jelmer/testrepo
import stat
import sys
from dulwich import porcelain
from dulwich.objects import Blob
from dulwich.repo import MemoryRepo
local_repo = MemoryRepo()
local_repo.refs.set_symbolic_ref(b'HEAD', b'refs/heads/master')
print(local_repo.refs.as_dict())
porcelain.fetch(local_repo, sys.argv[1])
local_repo['refs/heads/master'] = local_repo['refs/remotes/origin/master']
last_tree = local_repo[local_repo['HEAD'].tree]
new_blob = Blob.from_string(b'Some contents')
local_repo.object_store.add_object(new_blob)
last_tree.add(b'test', stat.S_IFREG, new_blob.id)
local_repo.object_store.add_object(last_tree)
local_repo.do_commit(
message=b'Add a file called \'test\'',
ref=b'refs/heads/master',
tree=last_tree.id)
porcelain.push(local_repo, sys.argv[1], 'master')
| 390 |
8,980 | {"articles":[{"id":"AB1C61AC-02EF-46A4-A16C-AD65A4D6289F","datePosted":"2020-05-03T08:00:34-07:00","expirationDate":"2020-06-23T17:22:28-07:00","localizations":{"eng":{"id":"10096D7C-06AB-4036-9387-3A65141AC350","summaryComponents":[{"flexibleSpacer":0.3960468521,"id":"9BF051B6-8879-409D-B6F6-54D1F4C7E7CC","modifiers":{"horizontalSizeClass":"regular"},"type":"flexibleSpacer"},{"flexibleSpacer":0.8701171875,"id":"87EC13ED-30CB-4904-BFC2-3E531FBDC398","modifiers":{"horizontalSizeClass":"compact"},"type":"flexibleSpacer"},{"id":"A70C63EC-3740-49AB-9DDA-E6B57BE9840E","title":"Ready. Set. Code.","modifiers":{"alignment":"centered","weight":"semibold","textStyle":"largeTitle","color":{"type":"custom","custom":{"lightColor":"#FFFFFF","darkColor":"#FFFFFF"}}},"type":"title"},{"id":"283B015F-0EFF-438F-9BAF-4AB459BC9B43","type":"fixedSpacer","fixedSpacer":20},{"id":"BCCA3547-97ED-4154-B2A1-A12A327E0603","modifiers":{"color":{"type":"custom","custom":{"lightColor":"#FFFFFF","darkColor":"#FFFFFF"}},"alignment":"centered"},"type":"text","text":"Starting June 22, WWDC20 takes off. Get ready for the first global, all-online WWDC by turning on your notifications to get all the latest news, with updates for events and sessions. More announcements to come in June."},{"fullBleedBackgroundImage":"https://devimages-cdn.apple.com/wwdc-services/images/wwdc20/v3-EFE0FCBF-4265-46D6-BBCD-85314EF768CE/BG-WWDCTab-Landscape.heic","id":"C7F45573-EE74-4389-BB62-F9D7F0A0ACFB","modifiers":{"horizontalSizeClass":"regular"},"type":"fullBleedBackgroundImage"},{"fullBleedBackgroundImage":"https://devimages-cdn.apple.com/wwdc-services/images/wwdc20/v3-EFE0FCBF-4265-46D6-BBCD-85314EF768CE/BG-WWDCTab-Portrait.heic","id":"A8FC229F-17D0-4588-9219-0EEBE436395A","modifiers":{"horizontalSizeClass":"compact"},"type":"fullBleedBackgroundImage"}],"detailComponents":[]}},"shareURL":"https://developer.apple.com/news/?id=gtopy09y","permalinkKey":"gtopy09y","webDisplaySetting":"summaryDetail"}],"filename":"event.json","updated":"2020-05-20T20:33:19+00:00","imageStore":{"path":"https://devimages-cdn.apple.com/wwdc-services/articles/images","variants":[64,128,256,512,1024,2048,2732],"extension":"jpeg"}} | 796 |
746 | package in.srain.cube.views.loadmore;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
/**
* @author huqiu.lhq
*/
public class LoadMoreListViewContainer extends LoadMoreContainerBase {
private ListView mListView;
public LoadMoreListViewContainer(Context context) {
super(context);
}
public LoadMoreListViewContainer(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void addFooterView(View view) {
mListView.addFooterView(view);
}
@Override
protected void removeFooterView(View view) {
mListView.removeFooterView(view);
}
@Override
protected AbsListView retrieveAbsListView() {
mListView = (ListView) getChildAt(0);
return mListView;
}
}
| 326 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.gradle.javaee.web;
import org.netbeans.modules.gradle.api.NbGradleProject;
import org.netbeans.modules.gradle.javaee.api.GradleWebProject;
import java.util.Collection;
import java.util.Collections;
import org.netbeans.api.project.Project;
import org.netbeans.modules.web.common.spi.ProjectWebRootProvider;
import org.netbeans.spi.project.ProjectServiceProvider;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
/**
*
* @author <NAME>
*/
@ProjectServiceProvider( service = ProjectWebRootProvider.class, projectType = NbGradleProject.GRADLE_PLUGIN_TYPE + "/war")
public class WebProjectWebRootProvider implements ProjectWebRootProvider{
final Project project;
public WebProjectWebRootProvider(Project project) {
this.project = project;
}
@Override
public FileObject getWebRoot(FileObject file) {
return getDefaultWebRoot();
}
@Override
public Collection<FileObject> getWebRoots() {
FileObject webRoot = getDefaultWebRoot();
return webRoot != null ? Collections.singleton(webRoot) : Collections.<FileObject>emptySet();
}
FileObject getDefaultWebRoot() {
GradleWebProject wp = GradleWebProject.get(project);
return wp != null ? FileUtil.toFileObject(wp.getWebAppDir()) : null;
}
}
| 667 |
14,668 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/android/autofill/card_name_fix_flow_view_android.h"
#include "chrome/android/chrome_jni_headers/AutofillNameFixFlowBridge_jni.h"
#include "chrome/browser/android/resource_mapper.h"
#include "components/autofill/core/browser/ui/payments/card_name_fix_flow_controller.h"
#include "components/autofill/core/browser/ui/payments/card_name_fix_flow_view.h"
#include "content/public/browser/web_contents.h"
#include "ui/android/view_android.h"
#include "ui/android/window_android.h"
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace autofill {
CardNameFixFlowViewAndroid::CardNameFixFlowViewAndroid(
CardNameFixFlowController* controller,
content::WebContents* web_contents)
: controller_(controller), web_contents_(web_contents) {}
void CardNameFixFlowViewAndroid::OnUserAccept(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
const JavaParamRef<jstring>& name) {
controller_->OnNameAccepted(
base::android::ConvertJavaStringToUTF16(env, name));
}
void CardNameFixFlowViewAndroid::PromptDismissed(
JNIEnv* env,
const JavaParamRef<jobject>& obj) {
delete this;
}
void CardNameFixFlowViewAndroid::Show() {
auto java_object = GetOrCreateJavaObject();
if (!java_object)
return;
java_object_.Reset(java_object);
JNIEnv* env = base::android::AttachCurrentThread();
ui::ViewAndroid* view_android = web_contents_->GetNativeView();
Java_AutofillNameFixFlowBridge_show(
env, java_object_, view_android->GetWindowAndroid()->GetJavaObject());
}
void CardNameFixFlowViewAndroid::ControllerGone() {
controller_ = nullptr;
JNIEnv* env = base::android::AttachCurrentThread();
if (java_object_internal_) {
// Don't create an object just for dismiss.
Java_AutofillNameFixFlowBridge_dismiss(env, java_object_internal_);
}
}
CardNameFixFlowViewAndroid::~CardNameFixFlowViewAndroid() {
if (controller_)
controller_->OnConfirmNameDialogClosed();
}
base::android::ScopedJavaGlobalRef<jobject>
CardNameFixFlowViewAndroid::GetOrCreateJavaObject() {
if (java_object_internal_)
return java_object_internal_;
if (web_contents_->GetNativeView() == nullptr ||
web_contents_->GetNativeView()->GetWindowAndroid() == nullptr)
return nullptr; // No window attached (yet or anymore).
JNIEnv* env = base::android::AttachCurrentThread();
ui::ViewAndroid* view_android = web_contents_->GetNativeView();
ScopedJavaLocalRef<jstring> dialog_title =
base::android::ConvertUTF16ToJavaString(env, controller_->GetTitleText());
ScopedJavaLocalRef<jstring> inferred_name =
base::android::ConvertUTF16ToJavaString(
env, controller_->GetInferredCardholderName());
ScopedJavaLocalRef<jstring> confirm = base::android::ConvertUTF16ToJavaString(
env, controller_->GetSaveButtonLabel());
return java_object_internal_ = Java_AutofillNameFixFlowBridge_create(
env, reinterpret_cast<intptr_t>(this), dialog_title, inferred_name,
confirm,
ResourceMapper::MapToJavaDrawableId(controller_->GetIconId()),
view_android->GetWindowAndroid()->GetJavaObject());
}
} // namespace autofill
| 1,167 |
679 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
/*
* Created on 2005
* by <NAME>
*/
package com.sun.star.tooling.DirtyTags;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class DirtyTagWrapCheck {
static String line="";
public static void main(String[] args) {
try {
File fi = new File("D:\\Testfiles\\KID_helpcontent.sdf");//Copy of
FileReader fr = new FileReader(fi);
BufferedReader br = new BufferedReader(fr);
int readCounter=0;
int missCounter=0;
int lineErrorCounter=0;
while((line=br.readLine())!=null){
readCounter++;
String [] split = line.split("\t");
if(split.length<15){
lineErrorCounter++;
continue;
}
String string = split[10];
String wrapped = DirtyTagWrapper.wrapString(string);
String unwrapped=DirtyTagWrapper.unwrapString(wrapped);
if(!string.equals(unwrapped)){
missCounter++;
System.out.println(""+readCounter+"\n"+string+"\n"+unwrapped+"\n"+wrapped+"\n");
}
}
System.out.println("Fertig "+readCounter+" "+missCounter+" "+lineErrorCounter);
} catch (FileNotFoundException e) {
//
e.printStackTrace();
} catch (IOException e) {
//
e.printStackTrace();
} catch (DirtyTagWrapper.TagWrapperException e) {
System.out.println(e.getMessage()+"\n"+line+"\n");
}
}
}
| 1,093 |
362 | // Copyright (c) 2018-2020, <NAME>. For more information see 'LICENSE'
#include "WindowSDL2.h"
#include "framework/Vulkan/VulkanSurface.h"
#include "stl/Containers/Singleton.h"
#ifdef FG_ENABLE_SDL2
# include "SDL_syswm.h"
namespace FGC
{
namespace {
struct SDL2Instance
{
uint refCounter = 0;
bool initialized = false;
};
}
/*
=================================================
constructor
=================================================
*/
WindowSDL2::WindowSDL2 () :
_window{ null },
_wndID{ 0 }
{
for (auto& state : _keyStates) {
state = EKeyAction(~0u);
}
}
/*
=================================================
destructor
=================================================
*/
WindowSDL2::~WindowSDL2 ()
{
Destroy();
}
/*
=================================================
Create
=================================================
*/
bool WindowSDL2::Create (uint2 surfaceSize, NtStringView title)
{
CHECK_ERR( not _window );
auto& inst = *Singleton<SDL2Instance>();
if ( not inst.initialized )
{
CHECK( SDL_Init( SDL_INIT_EVERYTHING ) == 0 );
inst.initialized = true;
}
++inst.refCounter;
//const int count = SDL_GetNumVideoDisplays();
//const int disp_idx= 0;
//SDL_Rect area = {};
//CHECK( SDL_GetDisplayUsableBounds( disp_idx, OUT &area ));
//const int2 pos = int2(area.x + area.w/2 - surfaceSize.x/2, area.y + area.h/2 - surfaceSize.y/2);
const uint flags = int(SDL_WINDOW_ALLOW_HIGHDPI) | int(SDL_WINDOW_RESIZABLE);
CHECK_ERR( (_window = SDL_CreateWindow( title.c_str(),
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
surfaceSize.x, surfaceSize.y,
flags )) != null );
_wndID = SDL_GetWindowID( _window );
SDL_SetWindowData( _window, "fg", this );
return true;
}
/*
=================================================
AddListener
=================================================
*/
void WindowSDL2::AddListener (IWindowEventListener *listener)
{
ASSERT( listener );
_listeners.insert( listener );
}
/*
=================================================
RemoveListener
=================================================
*/
void WindowSDL2::RemoveListener (IWindowEventListener *listener)
{
ASSERT( listener );
_listeners.erase( listener );
}
/*
=================================================
Update
=================================================
*/
bool WindowSDL2::Update ()
{
const auto OnKeyEvent = [this] (bool down, SDL_Scancode scancode)
{
auto& state = _keyStates[ scancode ];
if ( down ) {
if ( state == EKeyAction::Down or state == EKeyAction::Pressed )
state = EKeyAction::Pressed;
else
state = EKeyAction::Down;
}else
state = EKeyAction::Up;
for (auto& active : _activeKeys)
{
// skip duplicates
if ( active.first == scancode )
{
if ( state == EKeyAction::Up )
active.second = state;
return;
}
}
_activeKeys.push_back({ scancode, state });
};
//---------------------------------------------------------------------------
if ( not _window )
return false;
SDL_Event ev;
while ( SDL_PollEvent( OUT &ev ))
{
// check for events from different window
bool other_wnd = false;
switch ( ev.type )
{
case SDL_WINDOWEVENT : other_wnd = (ev.window.windowID != _wndID); break;
case SDL_KEYDOWN :
case SDL_KEYUP : other_wnd = (ev.key.windowID != _wndID); break;
case SDL_TEXTEDITING : other_wnd = (ev.edit.windowID != _wndID); break;
case SDL_TEXTINPUT : other_wnd = (ev.text.windowID != _wndID); break;
case SDL_MOUSEMOTION : other_wnd = (ev.motion.windowID != _wndID); break;
case SDL_MOUSEBUTTONDOWN :
case SDL_MOUSEBUTTONUP : other_wnd = (ev.button.windowID != _wndID); break;
case SDL_MOUSEWHEEL : other_wnd = (ev.wheel.windowID != _wndID); break;
}
if ( other_wnd )
{
SDL_PushEvent( &ev );
return true;
}
switch ( ev.type )
{
case SDL_QUIT :
case SDL_APP_TERMINATING :
Quit();
return false;
case SDL_APP_WILLENTERBACKGROUND :
break;
case SDL_APP_DIDENTERBACKGROUND :
break;
case SDL_APP_WILLENTERFOREGROUND :
break;
case SDL_APP_DIDENTERFOREGROUND :
break;
case SDL_MOUSEMOTION :
{
float2 pos = { float(ev.motion.x), float(ev.motion.y) };
for (auto& listener : _listeners) {
listener->OnMouseMove( pos );
}
break;
}
case SDL_MOUSEBUTTONDOWN :
case SDL_MOUSEBUTTONUP :
{
OnKeyEvent( ev.type == SDL_MOUSEBUTTONDOWN, SDL_Scancode(SDL_NUM_SCANCODES + ev.button.button) );
break;
}
case SDL_MOUSEWHEEL :
{
break;
}
case SDL_KEYDOWN :
case SDL_KEYUP :
{
OnKeyEvent( ev.type == SDL_KEYDOWN, ev.key.keysym.scancode );
break;
}
case SDL_WINDOWEVENT :
{
switch ( ev.window.event )
{
case SDL_WINDOWEVENT_SHOWN :
{
break;
}
case SDL_WINDOWEVENT_HIDDEN :
{
break;
}
case SDL_WINDOWEVENT_RESIZED :
//case SDL_WINDOWEVENT_MOVED :
//case SDL_WINDOWEVENT_SIZE_CHANGED :
{
if ( _window )
{
int2 size;
SDL_GetWindowSize( _window, OUT &size.x, OUT &size.y );
for (auto& listener : _listeners) {
listener->OnResize( uint2(size) );
}
}
break;
}
case SDL_WINDOWEVENT_CLOSE :
{
Quit();
return false;
}
}
break;
}
}
}
for (auto key_iter = _activeKeys.begin(); key_iter != _activeKeys.end();)
{
StringView key_name = _MapKey( key_iter->first );
EKeyAction& action = key_iter->second;
if ( key_name.size() )
{
for (auto& listener : _listeners) {
listener->OnKey( key_name, action );
}
}
BEGIN_ENUM_CHECKS();
switch ( action ) {
case EKeyAction::Up : key_iter = _activeKeys.erase( key_iter ); break;
case EKeyAction::Down : action = EKeyAction::Pressed; break;
case EKeyAction::Pressed : ++key_iter; break;
}
END_ENUM_CHECKS();
}
if ( not _window )
return false;
for (auto& listener : _listeners) {
listener->OnUpdate();
}
return true;
}
/*
=================================================
Quit
=================================================
*/
void WindowSDL2::Quit ()
{
Destroy();
}
/*
=================================================
Destroy
=================================================
*/
void WindowSDL2::Destroy ()
{
for (auto& listener : _listeners) {
listener->OnDestroy();
}
if ( _window )
{
SDL_DestroyWindow( _window );
_window = null;
_wndID = 0;
auto& inst = *Singleton<SDL2Instance>();
if ( --inst.refCounter == 0 and inst.initialized )
{
SDL_Quit();
inst.initialized = false;
}
}
}
/*
=================================================
SetTitle
=================================================
*/
void WindowSDL2::SetTitle (NtStringView value)
{
CHECK_ERRV( _window );
SDL_SetWindowTitle( _window, value.c_str() );
}
/*
=================================================
SetSize
=================================================
*/
void WindowSDL2::SetSize (const uint2 &value)
{
CHECK_ERRV( _window );
SDL_SetWindowSize( _window, int(value.x), int(value.y) );
}
/*
=================================================
SetPosition
=================================================
*/
void WindowSDL2::SetPosition (const int2 &value)
{
CHECK_ERRV( _window );
SDL_SetWindowPosition( _window, value.x, value.y );
}
/*
=================================================
GetSize
=================================================
*/
uint2 WindowSDL2::GetSize () const
{
CHECK_ERR( _window );
int2 size;
SDL_GetWindowSize( _window, OUT &size.x, OUT &size.y );
return uint2(size);
}
/*
=================================================
_MapKey
=================================================
*/
StringView WindowSDL2::_MapKey (SDL_Scancode code)
{
switch ( int(code) )
{
case SDL_SCANCODE_BACKSPACE : return "backspace";
case SDL_SCANCODE_TAB : return "tab";
case SDL_SCANCODE_CLEAR : return "clear";
case SDL_SCANCODE_RETURN : return "enter";
case SDL_SCANCODE_LCTRL : return "l-ctrl";
case SDL_SCANCODE_RCTRL : return "r-ctrl";
case SDL_SCANCODE_LALT : return "l-alt";
case SDL_SCANCODE_RALT : return "r-alt";
case SDL_SCANCODE_PAUSE : return "pause";
case SDL_SCANCODE_CAPSLOCK : return "caps lock";
case SDL_SCANCODE_ESCAPE : return "escape";
case SDL_SCANCODE_SPACE : return "space";
case SDL_SCANCODE_PAGEUP : return "page up";
case SDL_SCANCODE_PAGEDOWN : return "page down";
case SDL_SCANCODE_END : return "end";
case SDL_SCANCODE_HOME : return "home";
case SDL_SCANCODE_LEFT : return "arrow left";
case SDL_SCANCODE_UP : return "arrow up";
case SDL_SCANCODE_RIGHT : return "arrow right";
case SDL_SCANCODE_DOWN : return "arrow down";
case SDL_SCANCODE_PRINTSCREEN : return "print screen";
case SDL_SCANCODE_INSERT : return "insert";
case SDL_SCANCODE_DELETE : return "delete";
case SDL_SCANCODE_0 : return "0";
case SDL_SCANCODE_1 : return "1";
case SDL_SCANCODE_2 : return "2";
case SDL_SCANCODE_3 : return "3";
case SDL_SCANCODE_4 : return "4";
case SDL_SCANCODE_5 : return "5";
case SDL_SCANCODE_6 : return "6";
case SDL_SCANCODE_7 : return "7";
case SDL_SCANCODE_8 : return "8";
case SDL_SCANCODE_9 : return "9";
case SDL_SCANCODE_A : return "A";
case SDL_SCANCODE_B : return "B";
case SDL_SCANCODE_C : return "C";
case SDL_SCANCODE_D : return "D";
case SDL_SCANCODE_E : return "E";
case SDL_SCANCODE_F : return "F";
case SDL_SCANCODE_G : return "G";
case SDL_SCANCODE_H : return "H";
case SDL_SCANCODE_I : return "I";
case SDL_SCANCODE_J : return "J";
case SDL_SCANCODE_K : return "K";
case SDL_SCANCODE_L : return "L";
case SDL_SCANCODE_M : return "M";
case SDL_SCANCODE_N : return "N";
case SDL_SCANCODE_O : return "O";
case SDL_SCANCODE_P : return "P";
case SDL_SCANCODE_Q : return "Q";
case SDL_SCANCODE_R : return "R";
case SDL_SCANCODE_S : return "S";
case SDL_SCANCODE_T : return "T";
case SDL_SCANCODE_U : return "U";
case SDL_SCANCODE_V : return "V";
case SDL_SCANCODE_W : return "W";
case SDL_SCANCODE_X : return "X";
case SDL_SCANCODE_Y : return "Y";
case SDL_SCANCODE_Z : return "Z";
case SDL_SCANCODE_KP_ENTER : return "numpad enter";
case SDL_SCANCODE_KP_0 : return "numpad 0";
case SDL_SCANCODE_KP_1 : return "numpad 1";
case SDL_SCANCODE_KP_2 : return "numpad 2";
case SDL_SCANCODE_KP_3 : return "numpad 3";
case SDL_SCANCODE_KP_4 : return "numpad 4";
case SDL_SCANCODE_KP_5 : return "numpad 5";
case SDL_SCANCODE_KP_6 : return "numpad 6";
case SDL_SCANCODE_KP_7 : return "numpad 7";
case SDL_SCANCODE_KP_8 : return "numpad 8";
case SDL_SCANCODE_KP_9 : return "numpad 9";
case SDL_SCANCODE_KP_MULTIPLY : return "numpad *";
case SDL_SCANCODE_KP_PLUS : return "numpad +";
case SDL_SCANCODE_SEPARATOR : return "numpad sep";
case SDL_SCANCODE_KP_MINUS : return "numpad -";
case SDL_SCANCODE_KP_PERIOD : return "numpad .";
case SDL_SCANCODE_KP_DIVIDE : return "numpad /";
case SDL_SCANCODE_KP_EQUALS : return "numpad =";
case SDL_SCANCODE_KP_COMMA : return "numpad ,";
case SDL_SCANCODE_F1 : return "F1";
case SDL_SCANCODE_F2 : return "F2";
case SDL_SCANCODE_F3 : return "F3";
case SDL_SCANCODE_F4 : return "F4";
case SDL_SCANCODE_F5 : return "F5";
case SDL_SCANCODE_F6 : return "F6";
case SDL_SCANCODE_F7 : return "F7";
case SDL_SCANCODE_F8 : return "F8";
case SDL_SCANCODE_F9 : return "F9";
case SDL_SCANCODE_F10 : return "F10";
case SDL_SCANCODE_F11 : return "F11";
case SDL_SCANCODE_F12 : return "F12";
case SDL_SCANCODE_NUMLOCKCLEAR : return "num lock";
case SDL_SCANCODE_SCROLLLOCK : return "scroll lock";
case SDL_SCANCODE_SEMICOLON : return ";";
case SDL_SCANCODE_EQUALS : return "=";
case SDL_SCANCODE_COMMA : return ",";
case SDL_SCANCODE_MINUS : return "-";
case SDL_SCANCODE_PERIOD : return ".";
case SDL_SCANCODE_BACKSLASH : return "/";
case SDL_SCANCODE_GRAVE : return "~";
case SDL_SCANCODE_LEFTBRACKET : return "[";
case SDL_SCANCODE_SLASH : return "\\";
case SDL_SCANCODE_RIGHTBRACKET : return "]";
case SDL_SCANCODE_APOSTROPHE : return "'";
case SDL_NUM_SCANCODES + 1 : return "left mb";
case SDL_NUM_SCANCODES + 2 : return "right mb";
case SDL_NUM_SCANCODES + 3 : return "middle mb";
case SDL_NUM_SCANCODES + 4 : return "mouse btn 4";
case SDL_NUM_SCANCODES + 5 : return "mouse btn 5";
case SDL_NUM_SCANCODES + 6 : return "mouse btn 6";
case SDL_NUM_SCANCODES + 7 : return "mouse btn 7";
case SDL_NUM_SCANCODES + 8 : return "mouse btn 8";
}
return "";
}
/*
=================================================
GetVulkanSurface
=================================================
*/
UniquePtr<IVulkanSurface> WindowSDL2::GetVulkanSurface () const
{
#ifdef FG_ENABLE_VULKAN
return UniquePtr<IVulkanSurface>{new VulkanSurface( _window )};
#else
return {};
#endif
}
/*
=================================================
GetPlatformHandle
=================================================
*/
void* WindowSDL2::GetPlatformHandle () const
{
if ( not _window )
return null;
SDL_SysWMinfo info = {};
SDL_VERSION( OUT &info.version );
CHECK_ERR( SDL_GetWindowWMInfo( _window, OUT &info ) == SDL_TRUE );
switch ( info.subsystem )
{
#ifdef PLATFORM_ANDROID
case SDL_SYSWM_ANDROID :
return info.info.android.window;
#endif
#ifdef PLATFORM_WINDOWS
case SDL_SYSWM_WINDOWS :
return info.info.win.window;
#endif
}
return null;
}
//-----------------------------------------------------------------------------
# ifdef FG_ENABLE_VULKAN
/*
=================================================
VulkanSurface
=================================================
*/
WindowSDL2::VulkanSurface::VulkanSurface (SDL_Window *wnd) :
_window{wnd}, _extensions{FGC::VulkanSurface::GetRequiredExtensions()}
{}
/*
=================================================
Create
=================================================
*/
IVulkanSurface::SurfaceVk_t WindowSDL2::VulkanSurface::Create (InstanceVk_t instance) const
{
SDL_SysWMinfo info = {};
SDL_VERSION( OUT &info.version );
CHECK_ERR( SDL_GetWindowWMInfo( _window, OUT &info ) == SDL_TRUE );
switch ( info.subsystem )
{
case SDL_SYSWM_X11 :
return Zero; // TODO
case SDL_SYSWM_WAYLAND :
return Zero; // TODO
case SDL_SYSWM_MIR :
return Zero; // TODO
# if defined(VK_USE_PLATFORM_ANDROID_KHR)
case SDL_SYSWM_ANDROID :
return BitCast<SurfaceVk_t>( FGC::VulkanSurface::CreateAndroidSurface( instance, info.info.android.window ));
# endif
# if defined(PLATFORM_WINDOWS) or defined(VK_USE_PLATFORM_WIN32_KHR)
case SDL_SYSWM_WINDOWS :
return BitCast<SurfaceVk_t>( FGC::VulkanSurface::CreateWin32Surface( instance, info.info.win.hinstance, info.info.win.window ));
# endif
}
RETURN_ERR( "current subsystem type is not supported!" );
}
# endif // FG_ENABLE_VULKAN
} // FGC
#endif // FG_ENABLE_SDL2
| 6,772 |
1,373 | # Copyright (c) 2020 PaddlePaddle 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.
"""Classification task."""
from knover.core.task import Task
from knover.data.classification_reader import ClassificationReader
from knover.tasks import register_task
@register_task("Classification")
class Classification(Task):
"""Define classification task."""
@classmethod
def add_cmdline_args(cls, parser):
"""Add cmdline arguments."""
group = ClassificationReader.add_cmdline_args(parser)
group.add_argument("--num_classes", type=int, default=2,
help="The num classes in classification task.")
return group
def __init__(self, args):
super(Classification, self).__init__(args)
self.reader = ClassificationReader(args)
self.num_classes = args.num_classes
return
def merge_metrics_and_statistics(self, outputs, part_outputs):
"""Merge two evaulation output.
Args:
outputs: Original outputs which contains metrics and statistics.
part_outputs: New outputs which contains metrics and statistics.
Returns:
Return merged output which contains metrics and statistics.
"""
if outputs is None:
return part_outputs
if part_outputs is None:
return outputs
batch_size = outputs.pop("batch_size")
part_batch_size = part_outputs.pop("batch_size")
new_outputs = {
"batch_size": batch_size + part_batch_size,
}
for k in outputs:
if k.startswith("stat_"):
new_outputs[k] = outputs[k] + part_outputs[k]
else:
new_outputs[k] = (
outputs[k] * batch_size + part_outputs[k] * part_batch_size
) / new_outputs["batch_size"]
return new_outputs
def get_metrics(self, outputs):
"""Get metrics."""
if outputs is None:
raise ValueError("metrics is None")
outputs = dict(outputs)
# pop statistics
outputs.pop("batch_size", None)
if self.num_classes == 2:
tp = outputs.pop("stat_tp")
fp = outputs.pop("stat_fp")
tn = outputs.pop("stat_tn")
fn = outputs.pop("stat_fn")
outputs["precision"] = tp / (tp + fp + 1e-10)
outputs["recall"] = tp / (tp + fn + 1e-10)
outputs["f1"] = (2 * outputs["precision"] * outputs["recall"]) \
/ (outputs["precision"] + outputs["recall"] + 1e-10)
return outputs
def _post_process_infer_output(self, predictions):
"""Post-process inference output."""
predictions = [{"data_id": data_id.tolist()[0], "score": score.tolist()[1]}
for data_id, score in zip(predictions["data_id"], predictions["scores"])]
return predictions
| 1,416 |
317 | #ifndef __AIXMLElement__
#define __AIXMLElement__
/*
* Name: AIXMLNodeRef.h
* $Revision: 1 $
* Author:
* Date:
* Purpose: Adobe Illustrator XML node suite.
*
* ADOBE SYSTEMS INCORPORATED
* Copyright 1986-2007 Adobe Systems Incorporated.
* All rights reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute this file
* in accordance with the terms of the Adobe license agreement
* accompanying it. If you have received this file from a source other
* than Adobe, then your use, modification, or distribution of it
* requires the prior written permission of Adobe.
*
*/
/*******************************************************************************
**
** Imports
**
**/
#ifndef __AITypes__
#include "AITypes.h"
#endif
#ifndef __AIEntry__
#include "AIEntry.h"
#endif
#ifndef __AIDict__
#include "AIDictionary.h"
#endif
#ifndef __AIArray__
#include "AIArray.h"
#endif
#include "AIHeaderBegin.h"
/** @file AIXMLElement.h */
/*******************************************************************************
**
** Suite name and version
**
**/
#define kAIXMLNodeSuite "AI XML Node Suite"
#define kAIXMLNodeSuiteVersion5 AIAPI_VERSION(5)
#define kAIXMLNodeSuiteVersion kAIXMLNodeSuiteVersion5
#define kAIXMLNodeVersion kAIXMLNodeSuiteVersion
#define kAIXMLDocumentSuite "AI XML Document Suite"
#define kAIXMLDocumentSuiteVersion4 AIAPI_VERSION(4)
#define kAIXMLDocumentSuiteVersion kAIXMLDocumentSuiteVersion4
#define kAIXMLDocumentVersion kAIXMLDocumentSuiteVersion
#define kAIXMLElementSuite "AI XML Element Suite"
#define kAIXMLElementSuiteVersion4 AIAPI_VERSION(4)
#define kAIXMLElementSuiteVersion kAIXMLElementSuiteVersion4
#define kAIXMLElementVersion kAIXMLElementSuiteVersion
#define kAIXMLNodeListSuite "AI XML Node List Suite"
#define kAIXMLNodeListSuiteVersion3 AIAPI_VERSION(3)
#define kAIXMLNodeListSuiteVersion kAIXMLNodeListSuiteVersion3
#define kAIXMLNodeListVersion kAIXMLNodeListSuiteVersion
#define kAIXMLNamedNodeMapSuite "AI XML Named Node Map Suite"
#define kAIXMLNamedNodeMapSuiteVersion4 AIAPI_VERSION(4)
#define kAIXMLNamedNodeMapSuiteVersion kAIXMLNamedNodeMapSuiteVersion4
#define kAIXMLNamedNodeMapVersion kAIXMLNamedNodeMapSuiteVersion
/*******************************************************************************
**
** Constants
**
**/
/** @ingroup Errors
See \c #AIXMLElementSuite, \c #AIXMLNodeListSuite.*/
#define kAIXMLIndexSizeErr 'xInd'
/** @ingroup Errors
See \c #AIXMLElementSuite */
#define kAIXMLDOMStringSizeErr 'xDSt'
/** @ingroup Errors
See \c #AIXMLDocumentSuite */
#define kAIXMLHierarchyRequestErr 'xHer'
/** @ingroup Errors
See \c #AIXMLDocumentSuite */
#define kAIXMLWrongDocumentErr 'xDoc'
/** @ingroup Errors
See \c #AIXMLElementSuite, \c #AIXMLDocumentSuite */
#define kAIXMLInvalidCharacterErr 'xChr'
/** @ingroup Errors
See \c #AIXMLDocumentSuite */
#define kAIXMLNoDataAllowedErr 'x!dt'
/** @ingroup Errors
See \c #AIXMLDocumentSuite */
#define kAIXMLNoModifyAllowedErr 'x!mo'
/** @ingroup Errors
See \c #AIXMLDocumentSuite */
#define kAIXMLNotFoundErr 'x!fd'
/** @ingroup Errors
See \c #AIXMLDocumentSuite */
#define kAIXMLNotSupportedErr 'x!sp'
/** @ingroup Errors
See \c #AIXMLElementSuite */
#define kAIXMLInUseAttributeErr 'xInU'
/*******************************************************************************
**
** Types
**
**/
/** Opaque reference to an XML node list. Access with \c #AIXMLNodeListSuite */
typedef struct _AIXMLNodeList *AIXMLNodeListRef;
/** Opaque reference to an XML named node map. Access with \c #AIXMLNamedNodeMapSuite */
typedef struct _AIXMLNamedNodeMap *AIXMLNamedNodeMapRef;
/** Opaque reference to an XML name. See \c #AIXMLNodeSuite::NameFromString(),
\c #AIXMLNodeSuite::SetNodeName(). */
typedef struct _AIXMLName *AIXMLName;
/** An abstract name that can be converted to or from a
simple C string or Unicode string. See \c #AIXMLNodeSuite. */
typedef AIEntryRef AIXMLString; // entry of type string.
/** XML node type, an \c #AIXMLNodeTypeValue. See \c #AIXMLNodeSuite::GetNodeType(),
\c #AIXMLDocumentSuite*/
typedef ai::int32 AIXMLNodeType;
/** Possible values for \c #AIXMLNodeType. */
enum AIXMLNodeTypeValue {
kAIXMLUnknownNode,
/** Element. See \c #AIXMLDocumentSuite::CreateElement() */
kAIXMLElementNode,
/** Attribute. See \c #AIXMLDocumentSuite::CreateAttribute() */
kAIXMLAttributeNode,
/** Text. See \c #AIXMLDocumentSuite::CreateTextNode() */
kAIXMLTextNode,
/** CData section. See \c #AIXMLDocumentSuite::CreateCDATASection() */
kAIXMLCDATASectionNode,
/** Comment. See \c #AIXMLDocumentSuite::CreateComment() */
kAIXMLCommentNode,
/** Not supported */
kAIXMLEntityReferenceNode,
/** Not supported */
kAIXMLEntityNode,
/** Not supported */
kAIXMLProcessingInstructionNode,
/** Not supported */
kAIXMLDocumentNode,
/** Not supported */
kAIXMLDocumentTypeNode,
/** Not supported */
kAIXMLDocumentFragmentNode,
/** Not supported */
kAIXMLNotationNode
};
/*******************************************************************************
**
** Notifier
**
**/
/** @ingroup Notifiers
Sent when an operation requiring update of metadata is about to occur.
For example, sent before any file format is called or written.
Register for this if you need to keep metadata current.
If you add any function that assumes the metadata is current
(for a metadata browser, for example), send this notifier.
@see \c #AIXMLDocumentSuite
*/
#define kAIMetadataSyncNotifier "AI Metadata Sync Notifier"
/*******************************************************************************
**
** Suites
**
**/
// ------ AIXMLNodeSuite -------------------------
/** @ingroup Suites
This suite allows you to create and manipulate XML nodes.
The XML node suite provides an approximate implementation of the
XML Level 1 DOM interface for nodes. See
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html#ID-1950641247
\li Acquire this suite using \c #SPBasicSuite::AcquireSuite() with the constants
\c #kAIXMLNodeSuite and \c #kAIXMLNodeVersion.
The values of "NodeName", "NodeValue", and "Attributes" vary according to
the node type as follows:
<table>
<tr><td> </td><td>NodeName </td><td>NodeValue </td><td>Attributes</td></tr>
<tr><td>Element </td><td>tag name </td><td>null </td><td>NamedNodeMap</td></tr>
<tr><td>Attr </td><td>attribute name </td><td>attribute value </td><td>null</td></tr>
<tr><td>Text </td><td>\#text </td><td>text value </td><td>null</td></tr>
<tr><td>CDATASection </td><td>\#cdata-section </td><td>CDATA contents </td><td>null</td></tr>
<tr><td>Comment </td><td>\#comment </td><td>comment string </td><td>null</td></tr>
<tr><td>EntityReference </td><td>entity ref name </td><td>null </td><td>null</td></tr>
<tr><td>Entity </td><td>entity name </td><td>null </td><td>null</td></tr>
<tr><td>P.Instruction </td><td>target name </td><td>content </td><td>null</td></tr>
<tr><td>Document </td><td>\#document </td><td>null </td><td>null</td></tr>
<tr><td>DocumentType </td><td>document type name </td><td>null </td><td>null</td></tr>
<tr><td>DocumentFrag </td><td>\#document-fragment </td><td>null </td><td>null</td></tr>
<tr><td>Notation </td><td>notation name </td><td>null </td><td>null</td></tr>
</table>
*/
typedef struct {
// -- nodes --
/** Increments the reference count for an XML node.
When you create a node, the initial count is 1.
Use \c #Release() to decrement the count.
(Note that this function returns a numeric value, not an error code.)
@param node The XML node reference.
@return The current reference count.
*/
AIAPI ai::int32 (*AddRef) (AIXMLNodeRef node);
/** Decrements the reference count for an XML node, and
frees the memory when the reference count is 0.
When you create a node, the initial count is 1.
Use \c #AddRef() to increment the count.
(Note that this function returns a numeric value, not an error code.)
@param node The XML node reference.
@return The current reference count.
*/
AIAPI ai::int32 (*Release) (AIXMLNodeRef node);
/** Creates an exact duplicate of an XML node. performing a deep copy.
@param src The source node.
@param dst [out] A buffer in which to return the new node.
*/
AIAPI AIErr (*Clone) (AIXMLNodeRef src, AIXMLNodeRef* dst );
/** Copies the contents of an XML node into another existing node.
@param node The node whose contents are replaced.
@param src The source node.
*/
AIAPI AIErr (*Copy) (AIXMLNodeRef node, AIXMLNodeRef src);
/** Retrieves the type of an XML node.
@param node The XML node reference.
@param type [out] A buffer in which to return the type constant.
*/
AIAPI AIErr (*GetNodeType)(AIXMLNodeRef node, AIXMLNodeType *type);
/** Retrieves the name of an XML node.
@param node The XML node reference.
@param name [out] A buffer in which to return the name.
*/
AIAPI AIErr (*GetNodeName)(AIXMLNodeRef node, AIXMLName *name);
/** Sets the name of an XML node.
@param node The XML node reference.
@param name The new name.
*/
AIAPI AIErr (*SetNodeName)(AIXMLNodeRef node, AIXMLName name);
/** Retrieves the value of an XML node.
@param node The XML node reference.
@param value [out] A buffer in which to return the value.
*/
AIAPI AIErr (*GetNodeValue)(AIXMLNodeRef node, AIXMLString *value);
/** Sets the value of an XML node.
@param node The XML node reference.
@param name The new value.
*/
AIAPI AIErr (*SetNodeValue)(AIXMLNodeRef node, AIXMLString value);
/** Retrieves a node list containing the child nodes of an XML node.
@param node The XML node reference.
@param nodes [out] A buffer in which to return the node list.
*/
AIAPI AIErr (*GetChildNodes)(AIXMLNodeRef node, AIXMLNodeListRef *nodes);
/** Retrieves a named node map containing the attributes associated
with an XML node.
@param node The XML node reference.
@param attributes [out] A buffer in which to return the node map.
*/
AIAPI AIErr (*GetAttributes)(AIXMLNodeRef node, AIXMLNamedNodeMapRef *attributes);
/** Inserts a new child node in an XML node.
@param node The XML node reference for the parent node.
@param newchild The new child node.
@param refchild An existing child node before which to insert the new child,
or \c NULL to insert the new child at the end of the child list.
*/
AIAPI AIErr (*InsertBefore)(AIXMLNodeRef node, AIXMLNodeRef newchild, AIXMLNodeRef refchild);
/** Replaces one child of an XML node with another child node.
@param node The XML node reference for the parent node.
@param newchild The new child node.
@param oldchild An existing child node to replace.
*/
AIAPI AIErr (*ReplaceChild)(AIXMLNodeRef node, AIXMLNodeRef newchild, AIXMLNodeRef oldchild);
/** Removes a child node from an XML node.
@param node The XML node reference for the parent node.
@param oldchild An existing child node to remove.
*/
AIAPI AIErr (*RemoveChild)(AIXMLNodeRef node, AIXMLNodeRef oldchild);
/** Appends a new child node to the child list of an XML node.
@param node The XML node reference for the parent node.
@param newchild The new child node.
*/
AIAPI AIErr (*AppendChild)(AIXMLNodeRef node, AIXMLNodeRef newchild);
/** Reports whether an XML node has any children.
@param node The XML node reference.
@param haschildren [out] A buffer in which to return true if the node has children.
*/
AIAPI AIErr (*HasChildNodes)(AIXMLNodeRef node, AIBoolean *haschildren);
// -- names --
/** Converts a C string to an XML node name.
(Note that this function returns an XML name value, not an error code,)
@param string The C string.
@return The XML name.
*/
AIAPI AIXMLName (*NameFromString) (const char* string);
/** Converts an XML name to a C string.
(Note that this function returns a string value, not an error code,)
@param name The XML name.
@return The C string.
*/
AIAPI const char* (*StringFromName) (AIXMLName name);
/** Converts a Unicode string to an XML node name.
(Note that this function returns an XML name value, not an error code,)
@param string The Unicode string.
@return The XML name.
*/
AIAPI AIXMLName (*NameFromUnicodeString) (const ai::UnicodeString& string);
/** Converts an XML name to a Unicode string.
@param name The XML name.
@param string [out] A buffer in which to return the Unicode string.
*/
AIAPI AIErr (*UnicodeStringFromName) (AIXMLName name, ai::UnicodeString& string);
// -- private data --
/** @deprecated. Obsolete, do not use. */
AIAPI AIErr (*GetData) (AIXMLNodeRef node, AIDictKey key, AIEntryRef *value);
/** @deprecated. Obsolete, do not use. */
AIAPI AIErr (*SetData) (AIXMLNodeRef node, AIDictKey key, AIEntryRef value);
/** @deprecated. Obsolete, do not use. */
AIAPI AIErr (*RemoveData) (AIXMLNodeRef node, AIDictKey key);
// -- utilities --
/** Compares two XML nodes for equality. Nodes are equal if they have
the same type, name, and value, and if they each have the same
attributes with the same values. They are deeply
equal if their sequences of child nodes are also equal.
When comparing values, the function converts them to real
numbers if possible, and otherwise compares the strings.
@param node1 The first node.
@param node2 The second node.
@param deep True to perform a deep comparison.
@param result [out] A buffer in which to return true (non-zero) if the nodes are equal.
@note This is not a part of the XML DOM specification.
*/
AIAPI AIErr (*Compare) (AIXMLNodeRef node1, AIXMLNodeRef node2, AIBoolean deep, ai::int32 *result);
} AIXMLNodeSuite;
// ------ AIXMLDocumentSuite -------------------------
/** @ingroup Suites
An Illustrator document can store an XML document element in its dictionary.
This suite allows you to create and access the XML document and its
contained metadata element.
When an Illustrator document is exported to SVG, the metadata element
is written to the SVG file. Before writing the file, Illustrator sends
the \c #kAIMetadataSyncNotifier to ensure that the metadata is updated.
When Illustrator reads an SVG file, the metadata in the SVG becomes
the document metadata element.
This suite provides an approximate implementation of the
XML Level 1 DOM interface for documents. See
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html#i-Document
\li Acquire this suite using \c #SPBasicSuite::AcquireSuite() with the constants
\c #kAIXMLDocumentSuite and \c #kAIXMLDocumentVersion.
*/
typedef struct {
/** Retrieves the XML document for the current Illustrator document, creating
one if none exists.
@param element [out] A buffer in which to return the XML document element.
@note This is not a part of the XML DOM specification.
*/
AIAPI AIErr (*GetDocumentElement)(AIXMLNodeRef *element);
/** Retrieves the metadata element from the XML document for the current
Illustrator document, creating one if none exists.
@param element [out] A buffer in which to return the metadata element.
@note This is not a part of the XML DOM specification.
*/
AIAPI AIErr (*GetDocumentMetadata)(AIXMLNodeRef *element);
/** Creates a new metadata element.
@param name The element name.
@param element [out] A buffer in which to return the new element.
*/
AIAPI AIErr (*CreateElement)(AIXMLName name, AIXMLNodeRef *element);
/** Creates a new metadata attribute.
@param name The attribute name.
@param value The attribute value.
@param attribute [out] A buffer in which to return the new attribute.
*/
AIAPI AIErr (*CreateAttribute)(AIXMLName name, AIXMLString value, AIXMLNodeRef *attribute);
/** Creates a new metadata text node.
@param string The text string.
@param text [out] A buffer in which to return the new text node.
*/
AIAPI AIErr (*CreateTextNode)(AIXMLString string, AIXMLNodeRef *text);
/** Creates a new metadata comment node.
@param string The comment string.
@param comment [out] A buffer in which to return the new comment node.
*/
AIAPI AIErr (*CreateComment)(AIXMLString string, AIXMLNodeRef *comment);
/** Creates a new metadata CDATA node.
@param string The CDATA string.
@param cdata [out] A buffer in which to return the new CDATA node.
*/
AIAPI AIErr (*CreateCDATASection)(AIXMLString string, AIXMLNodeRef *cdata);
/** Retrieves XML elements at or under a node that match a name pattern.
The matching elements are determined by a pre-order traversal.
@param node A node at any level of the XML tree.
@param name The name pattern to match. The special name "*" matches all elements.
@param count [in, out] On input, the maximum number of matches to return.
On return, the number of array elements actually filled.
@param [in, out] An array of nodes of size \c count, in which to return matching
nodes.
@note This implementation differs from the XML DOM specification.
*/
AIAPI AIErr (*GetElementsByTagName)(AIXMLNodeRef node, AIXMLName name, ai::int32 *count, AIXMLNodeRef *match);
} AIXMLDocumentSuite;
// ------ AIXMLElementSuite -------------------------
/** @ingroup Suites
This suite allows you to access XML metadata attributes.
This suite provides an approximate implementation of the
XML Level 1 DOM interface for elements. See
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html#ID-745549614
\li Acquire this suite using \c #SPBasicSuite::AcquireSuite() with the constants
\c #kAIXMLElementSuite and \c #kAIXMLElementVersion.
*/
typedef struct {
// -- attributes --
/** Retrieves the value of an XML node's named attribute.
@param element The node.
@param name The attribute name.
@param value [out] A buffer in which to return the value.
*/
AIAPI AIErr (*GetAttribute)(AIXMLNodeRef element, AIXMLName name, AIXMLString *value);
/** Sets the value of an XML node's named attribute.
@param element The node.
@param name The attribute name.
@param value The new value.
*/
AIAPI AIErr (*SetAttribute)(AIXMLNodeRef element, AIXMLName name, AIXMLString value);
/** Removes a named attribute associated with an XML node.
@param element The node.
@param name The attribute name.
*/
AIAPI AIErr (*RemoveAttribute)(AIXMLNodeRef element, AIXMLName name);
} AIXMLElementSuite;
// ------ AIXMLNodeListSuite -------------------------
/** @ingroup Suites
This suite allows you to iterate through and manage lists of XML nodes.
This suite provides an approximate implementation of the
XML Level 1 DOM interface for node lists. See
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html#ID-536297177
\li Acquire this suite using \c #SPBasicSuite::AcquireSuite() with the constants
\c #kAIXMLNodeListSuite and \c #kAIXMLNodeListVersion.
*/
typedef struct {
/** Retrieves the number of items in a node list. Use with \c #GetItem()
to iterate through a list.
@param nodes The XML node list.
@param length [out] A buffer in which to return the number of items.
*/
AIAPI AIErr (*GetLength)(AIXMLNodeListRef nodes, ai::int32 *length);
/** Retrieves an XML node from a node list by position index. Use with \c #GetLength()
to iterate through a list.
@param nodes The XML node list.
@param index The 0-based position index.
@param node [out] A buffer in which to return the node.
*/
AIAPI AIErr (*GetItem)(AIXMLNodeListRef nodes, ai::int32 index, AIXMLNodeRef *node);
// -- utilities --
/** Swaps XML nodes between two node lists.
@param list1 The first XML node list.
@param list2 The second XML node list.
@param position1 The 0-based position index of the node in the first list to move
to \c position2 in the second list.
@param position2 The 0-based position index of the node in the second list to move
to \c position1 in the first list.
@note This is not a part of the XML DOM specification. */
AIAPI AIErr (*SwapNodes) (AIXMLNodeListRef list1, AIXMLNodeListRef list2, ai::int32 position1, ai::int32 position2);
} AIXMLNodeListSuite;
// ------ AIXMLNamedNodeMapSuite -------------------------
/** @ingroup Suites
This suite allows you to access XML named node maps.
This suite provides an approximate implementation of the
XML Level 1 DOM interface for named node maps. See
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html#ID-1780488922
\li Acquire this suite using \c #SPBasicSuite::AcquireSuite() with the constants
\c #kAIXMLNamedNodeMapSuite and \c #kAIXMLNamedNodeMapSuiteVersion.
*/
typedef struct {
/** Retrieves the size of a named node map. Use with \c #GetItem() to iterate
through items in the map.
@param map The node map.
@param length [out] A buffer in which to return the number of nodes.
*/
AIAPI AIErr (*GetLength)(AIXMLNamedNodeMapRef map, ai::int32 *length);
/** Retrieves an XML node from a node map by position index. Use with \c #GetLength()
to iterate through a map.
@param map The node map.
@param index The 0-based position index.
@param node [out] A buffer in which to return the node.
*/
AIAPI AIErr (*GetItem)(AIXMLNamedNodeMapRef map, ai::int32 index, AIXMLNodeRef *node);
/** Retrieves a node by name from a node map.
@param map The node map.
@param name The node name.
@param node [out] A buffer in which to return the node.
*/
AIAPI AIErr (*GetNamedItem)(AIXMLNamedNodeMapRef map, AIXMLName name, AIXMLNodeRef *node);
/** Adds a named node to a node map, replacing it if it is already included.
@param map The node map.
@param name The node name.
*/
AIAPI AIErr (*SetNamedItem)(AIXMLNamedNodeMapRef map, AIXMLNodeRef node);
/** Removes a named node from a node map. There is no error if the node
was not in the map.
@param map The node map.
@param name The node name.
*/
AIAPI AIErr (*RemoveNamedItem)(AIXMLNamedNodeMapRef map, AIXMLNodeRef node);
} AIXMLNamedNodeMapSuite;
#include "AIHeaderEnd.h"
#endif
| 7,530 |
1,738 | <filename>dev/Code/Sandbox/Editor/AI/GenerateSpawners.cpp
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "GenerateSpawners.h"
#include "IEntitySystem.h"
#include "IScriptSystem.h"
namespace
{
QString Tabs(int n)
{
QString tabs;
for (int i = 0; i < n; i++)
{
tabs += '\t';
}
return tabs;
}
inline const char* to_str(float val)
{
static char temp[32];
sprintf_s(temp, "%g", val);
return temp;
}
}
static bool ShouldGenerateSpawner(IEntityClass* pClass)
{
const QString startPath = "Scripts/Entities/AI/";
// things that we're not smart enough to skip
const QString exceptionClasses[] = {
"AIAlertness",
"AIAnchor",
"SmartObjectCondition"
};
QString filename = pClass->GetScriptFile();
QString classname = pClass->GetName();
// check the path name is right
if (filename.isEmpty())
{
return false;
}
if (filename.length() < startPath.length())
{
return false;
}
if (filename.left(startPath.length()) != startPath)
{
return false;
}
for (int i = 0; i < sizeof(exceptionClasses) / sizeof(*exceptionClasses); i++)
{
if (classname == exceptionClasses[i])
{
return false;
}
}
// check the table has properties (a good filter)
SmartScriptTable pTable;
gEnv->pScriptSystem->GetGlobalValue(pClass->GetName(), pTable);
if (!pTable)
{
return false;
}
if (!pTable->HaveValue("Properties"))
{
return false;
}
return true;
}
static bool OutputFile(const QString& name, const QString& data)
{
FILE* f = nullptr;
azfopen(&f, name.toUtf8().data(), "wt");
if (!f)
{
CryLogAlways("Unable to open file %s", name.toUtf8().data());
return false;
}
fwrite(data.toUtf8().data(), data.toUtf8().length(), 1, f);
fclose(f);
return true;
}
static bool GenerateEntityForSpawner(IEntityClass* pClass)
{
QString os;
os += QString("<Entity Name=\"Spawn") + pClass->GetName() + "\" Script=\"Scripts/Entities/AISpawners/Spawn" + pClass->GetName() + ".lua\"/>\n";
return OutputFile((Path::GetEditingGameDataFolder() + "\\Entities\\Spawn" + pClass->GetName() + ".ent").c_str(), os);
}
static void CloneTable(QString& os, SmartScriptTable from, const char* table, int tabs)
{
SmartScriptTable tbl;
from->GetValue(table, tbl);
if (!tbl)
{
return;
}
os += Tabs(tabs) + table + " =\n"
+ Tabs(tabs) + "{\n";
IScriptTable::Iterator iter = tbl->BeginIteration();
while (tbl->MoveNext(iter))
{
if (!iter.sKey)
{
continue;
}
switch (iter.value.type)
{
case ANY_TSTRING:
os += Tabs(tabs + 1) + iter.sKey + " = \"" + iter.value.str + "\",\n";
break;
case ANY_TNUMBER:
os += Tabs(tabs + 1) + iter.sKey + " = " + to_str(iter.value.number) + ",\n";
break;
case ANY_TTABLE:
CloneTable(os, tbl, iter.sKey, tabs + 1);
break;
}
}
tbl->EndIteration(iter);
os += Tabs(tabs) + "},\n";
}
static bool GenerateLuaForSpawner(IEntityClass* pClass)
{
QString os;
SmartScriptTable entityTable;
gEnv->pScriptSystem->GetGlobalValue(pClass->GetName(), entityTable);
os += "-- AUTOMATICALLY GENERATED CODE\n";
os += "-- use sandbox (AI/Generate Spawner Scripts) to regenerate this file\n";
os += QString("Script.ReloadScript(\"") + pClass->GetScriptFile() + "\")\n";
os += QString("Spawn") + pClass->GetName() + " =\n";
os += "{\n";
os += "\tspawnedEntity = nil,\n";
CloneTable(os, entityTable, "Properties", 1);
CloneTable(os, entityTable, "PropertiesInstance", 1);
os += "}\n";
os += QString("Spawn") + pClass->GetName() + ".Properties.SpawnedEntityName = \"\"\n";
// get event information
std::set<QString> inputEvents, outputEvents;
std::map<QString, QString> eventTypes;
SmartScriptTable eventsTable;
entityTable->GetValue("FlowEvents", eventsTable);
if (!!eventsTable)
{
SmartScriptTable inputs, outputs;
eventsTable->GetValue("Inputs", inputs);
eventsTable->GetValue("Outputs", outputs);
if (!!inputs)
{
IScriptTable::Iterator iter = inputs->BeginIteration();
while (inputs->MoveNext(iter))
{
if (!iter.sKey || iter.value.type != ANY_TTABLE)
{
continue;
}
const char* type;
if (iter.value.table->GetAt(2, type))
{
eventTypes[iter.sKey] = type;
inputEvents.insert(iter.sKey);
}
}
inputs->EndIteration(iter);
}
if (!!outputs)
{
IScriptTable::Iterator iter = outputs->BeginIteration();
while (outputs->MoveNext(iter))
{
if (!iter.sKey || iter.value.type != ANY_TSTRING)
{
continue;
}
eventTypes[iter.sKey] = iter.value.str;
outputEvents.insert(iter.sKey);
}
outputs->EndIteration(iter);
}
}
// boiler plate (almost) code
os += QString("function Spawn") + pClass->GetName() + ":Event_Spawn(sender,params)\n"
+ "\tlocal params = {\n"
+ "\t\tclass = \"" + pClass->GetName() + "\",\n"
+ "\t\tposition = self:GetPos(),\n"
+ "\t\torientation = self:GetDirectionVector(1),\n"
+ "\t\tscale = self:GetScale(),\n"
+ "\t\tproperties = self.Properties,\n"
+ "\t\tpropertiesInstance = self.PropertiesInstance,\n"
+ "\t}\n"
+ "\tif self.Properties.SpawnedEntityName ~= \"\" then\n"
+ "\t\tparams.name = self.Properties.SpawnedEntityName\n"
+ "\telse\n"
+ "\t\tparams.name = self:GetName()\n"
+ "\tend\n"
+ "\tlocal ent = System.SpawnEntity(params)\n"
+ "\tif ent then\n"
+ "\t\tself.spawnedEntity = ent.id\n"
+ "\t\tif not ent.Events then ent.Events = {} end\n"
+ "\t\tlocal evts = ent.Events\n";
for (std::set<QString>::const_iterator iter = outputEvents.begin(); iter != outputEvents.end(); ++iter)
{
// setup event munging...
os += QString("\t\tif not evts.") + *iter + " then evts." + *iter + " = {} end\n"
+ "\t\ttable.insert(evts." + *iter + ", {self.id, \"" + *iter + "\"})\n";
}
os += QString("\tend\n")
+ "\tBroadcastEvent(self, \"Spawned\")\n"
+ "end\n"
+ "function Spawn" + pClass->GetName() + ":OnReset()\n"
+ "\tif self.spawnedEntity then\n"
+ "\t\tSystem.RemoveEntity(self.spawnedEntity)\n"
+ "\t\tself.spawnedEntity = nil\n"
+ "\tend\n"
+ "end\n"
+ "function Spawn" + pClass->GetName() + ":GetFlowgraphForwardingEntity()\n"
+ "\treturn self.spawnedEntity\n"
+ "end\n"
+ "function Spawn" + pClass->GetName() + ":Event_Spawned()\n"
+ "\tBroadcastEvent(self, \"Spawned\")\n"
+ "end\n";
// output the event information
for (std::map<QString, QString>::const_iterator iter = eventTypes.begin(); iter != eventTypes.end(); ++iter)
{
os += QString("function Spawn") + pClass->GetName() + ":Event_" + iter->first + "(sender, param)\n";
if (outputEvents.find(iter->first) != outputEvents.end())
{
os += QString("\tif sender and sender.id == self.spawnedEntity then BroadcastEvent(self, \"") + iter->first + "\") end\n";
}
if (inputEvents.find(iter->first) != inputEvents.end())
{
os += QString("\tif self.spawnedEntity and ((not sender) or (self.spawnedEntity ~= sender.id)) then\n")
+ "\t\tlocal ent = System.GetEntity(self.spawnedEntity)\n"
+ "\t\tif ent and ent ~= sender then\n"
+ "\t\t\tself.Handle_" + iter->first + "(ent, sender, param)\n"
+ "\t\tend\n"
+ "\tend\n";
}
if (iter->first == "OnDeath" || iter->first == "Die")
{
os += "\tif sender and sender.id == self.spawnedEntity then self.spawnedEntity = nil end\n";
}
os += "end\n";
}
os += QString("Spawn") + pClass->GetName() + ".FlowEvents =\n"
+ "{\n"
+ "\tInputs = \n"
+ "\t{\n"
+ "\t\tSpawn = { Spawn" + pClass->GetName() + ".Event_Spawn, \"bool\" },\n";
for (std::set<QString>::const_iterator iter = inputEvents.begin(); iter != inputEvents.end(); ++iter)
{
os += QString("\t\t") + *iter + " = { Spawn" + pClass->GetName() + ".Event_" + *iter + ", \"" + eventTypes[*iter] + "\" },\n";
}
os += QString("\t},\n")
+ "\tOutputs = \n"
+ "\t{\n"
+ "\t\tSpawned = \"bool\",\n";
for (std::set<QString>::const_iterator iter = outputEvents.begin(); iter != outputEvents.end(); ++iter)
{
os += QString("\t\t") + *iter + " = \"" + eventTypes[*iter] + "\",\n";
}
os += QString("\t}\n")
+ "}\n";
for (std::set<QString>::const_iterator iter = inputEvents.begin(); iter != inputEvents.end(); ++iter)
{
os += QString("Spawn") + pClass->GetName() + ".Handle_" + *iter + " = " + pClass->GetName() + ".FlowEvents.Inputs." + *iter + "[1]\n";
}
return OutputFile((Path::GetEditingGameDataFolder() + "\\Scripts\\Entities\\AISpawners\\Spawn" + pClass->GetName() + ".lua").c_str(), os);
}
static bool GenerateSpawner(IEntityClass* pClass)
{
GenerateEntityForSpawner(pClass);
return GenerateLuaForSpawner(pClass);
}
void GenerateSpawners()
{
if (!gEnv->pEntitySystem)
{
return;
}
// iterate over all entity classes, and try to find those that are spawning AI's
IEntityClass* pClass;
IEntityClassRegistry* pReg = gEnv->pEntitySystem->GetClassRegistry();
for (pReg->IteratorMoveFirst(); pClass = pReg->IteratorNext(); )
{
if (ShouldGenerateSpawner(pClass))
{
if (!GenerateSpawner(pClass))
{
CryLogAlways("Couldn't generate spawner for %s", pClass->GetName());
}
}
}
}
| 5,004 |
1,756 | /* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_libmailcore_SMTPSendWithDataOperation */
#ifndef _Included_com_libmailcore_SMTPSendWithDataOperation
#define _Included_com_libmailcore_SMTPSendWithDataOperation
#ifdef __cplusplus
extern "C" {
#endif
#undef com_libmailcore_SMTPSendWithDataOperation_serialVersionUID
#define com_libmailcore_SMTPSendWithDataOperation_serialVersionUID 1LL
#ifdef __cplusplus
}
#endif
#endif
| 156 |
435 | package org.uma.jmetal.algorithm.multiobjective.moead;
import org.uma.jmetal.algorithm.multiobjective.moead.util.MOEADUtils;
import org.uma.jmetal.operator.crossover.CrossoverOperator;
import org.uma.jmetal.operator.crossover.impl.DifferentialEvolutionCrossover;
import org.uma.jmetal.operator.mutation.MutationOperator;
import org.uma.jmetal.problem.Problem;
import org.uma.jmetal.solution.doublesolution.DoubleSolution;
import org.uma.jmetal.util.errorchecking.JMetalException;
import org.uma.jmetal.util.pseudorandom.JMetalRandom;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Class implementing the MOEA/D-STM algorithm described in : <NAME>, <NAME>, <NAME>, <NAME> and
* <NAME>, "Stable Matching-Based Selection in Evolutionary Multiobjective Optimization", IEEE
* Transactions on Evolutionary Computation, 18(6): 909-923, 2014. DOI: 10.1109/TEVC.2013.2293776
*
* @author <NAME>
* @version 1.0
*/
@SuppressWarnings("serial")
public class MOEADSTM extends AbstractMOEAD<DoubleSolution> {
protected DifferentialEvolutionCrossover differentialEvolutionCrossover;
protected DoubleSolution[] savedValues;
protected double[] utility;
protected int[] frequency;
JMetalRandom randomGenerator;
public MOEADSTM(Problem<DoubleSolution> problem, int populationSize, int resultPopulationSize,
int maxEvaluations,
MutationOperator<DoubleSolution> mutation, CrossoverOperator<DoubleSolution> crossover,
FunctionType functionType, String dataDirectory, double neighborhoodSelectionProbability,
int maximumNumberOfReplacedSolutions, int neighborSize) {
super(problem, populationSize, resultPopulationSize, maxEvaluations, crossover, mutation,
functionType,
dataDirectory, neighborhoodSelectionProbability, maximumNumberOfReplacedSolutions,
neighborSize);
differentialEvolutionCrossover = (DifferentialEvolutionCrossover) crossoverOperator;
savedValues = new DoubleSolution[populationSize];
utility = new double[populationSize];
frequency = new int[populationSize];
for (int i = 0; i < utility.length; i++) {
utility[i] = 1.0;
frequency[i] = 0;
}
randomGenerator = JMetalRandom.getInstance();
}
@Override
public void run() {
initializePopulation();
initializeUniformWeight();
initializeNeighborhood();
idealPoint.update(population);
nadirPoint.update(population);
int generation = 0;
evaluations = populationSize;
do {
int[] permutation = new int[populationSize];
MOEADUtils.randomPermutation(permutation, populationSize);
offspringPopulation.clear();
for (int i = 0; i < populationSize; i++) {
int subProblemId = permutation[i];
frequency[subProblemId]++;
NeighborType neighborType = chooseNeighborType();
List<DoubleSolution> parents = parentSelection(subProblemId, neighborType);
differentialEvolutionCrossover.setCurrentSolution(population.get(subProblemId));
List<DoubleSolution> children = differentialEvolutionCrossover.execute(parents);
DoubleSolution child = children.get(0);
mutationOperator.execute(child);
problem.evaluate(child);
evaluations++;
idealPoint.update(population);
nadirPoint.update(population);
updateNeighborhood(child, subProblemId, neighborType);
offspringPopulation.add(child);
}
// Combine the parent and the current offspring populations
jointPopulation.clear();
jointPopulation.addAll(population);
jointPopulation.addAll(offspringPopulation);
// selection process
stmSelection();
generation++;
if (generation % 30 == 0) {
utilityFunction();
}
} while (evaluations < maxEvaluations);
}
protected void initializePopulation() {
population = new ArrayList<>(populationSize);
offspringPopulation = new ArrayList<>(populationSize);
jointPopulation = new ArrayList<>(populationSize);
for (int i = 0; i < populationSize; i++) {
DoubleSolution newSolution = (DoubleSolution) problem.createSolution();
problem.evaluate(newSolution);
population.add(newSolution);
savedValues[i] = (DoubleSolution) newSolution.copy();
}
}
@Override
public List<DoubleSolution> getResult() {
return population;
}
public void utilityFunction() throws JMetalException {
double f1, f2, uti, delta;
for (int n = 0; n < populationSize; n++) {
f1 = fitnessFunction(population.get(n), lambda[n]);
f2 = fitnessFunction(savedValues[n], lambda[n]);
delta = f2 - f1;
if (delta > 0.001) {
utility[n] = 1.0;
} else {
uti = (0.95 + (0.05 * delta / 0.001)) * utility[n];
utility[n] = uti < 1.0 ? uti : 1.0;
}
savedValues[n] = (DoubleSolution) population.get(n).copy();
}
}
public List<Integer> tourSelection(int depth) {
List<Integer> selected = new ArrayList<Integer>();
List<Integer> candidate = new ArrayList<Integer>();
for (int k = 0; k < problem.getNumberOfObjectives(); k++) {
// WARNING! HERE YOU HAVE TO USE THE WEIGHT PROVIDED BY QINGFU Et AL
// (NOT SORTED!!!!)
selected.add(k);
}
for (int n = problem.getNumberOfObjectives(); n < populationSize; n++) {
// set of unselected weights
candidate.add(n);
}
while (selected.size() < (int) (populationSize / 5.0)) {
int best_idd = (int) (randomGenerator.nextDouble() * candidate.size());
int i2;
int best_sub = candidate.get(best_idd);
int s2;
for (int i = 1; i < depth; i++) {
i2 = (int) (randomGenerator.nextDouble() * candidate.size());
s2 = candidate.get(i2);
if (utility[s2] > utility[best_sub]) {
best_idd = i2;
best_sub = s2;
}
}
selected.add(best_sub);
candidate.remove(best_idd);
}
return selected;
}
/**
* Select the next parent population, based on the stable matching criteria
*/
public void stmSelection() {
int[] idx = new int[populationSize];
double[] nicheCount = new double[populationSize];
int[][] solPref = new int[jointPopulation.size()][];
double[][] solMatrix = new double[jointPopulation.size()][];
double[][] distMatrix = new double[jointPopulation.size()][];
double[][] fitnessMatrix = new double[jointPopulation.size()][];
for (int i = 0; i < jointPopulation.size(); i++) {
solPref[i] = new int[populationSize];
solMatrix[i] = new double[populationSize];
distMatrix[i] = new double[populationSize];
fitnessMatrix[i] = new double[populationSize];
}
int[][] subpPref = new int[populationSize][];
double[][] subpMatrix = new double[populationSize][];
for (int i = 0; i < populationSize; i++) {
subpPref[i] = new int[jointPopulation.size()];
subpMatrix[i] = new double[jointPopulation.size()];
}
// Calculate the preference values of solution matrix
for (int i = 0; i < jointPopulation.size(); i++) {
int minIndex = 0;
for (int j = 0; j < populationSize; j++) {
fitnessMatrix[i][j] = fitnessFunction(jointPopulation.get(i), lambda[j]);
distMatrix[i][j] = calculateDistance2(jointPopulation.get(i), lambda[j]);
if (distMatrix[i][j] < distMatrix[i][minIndex]) {
minIndex = j;
}
}
nicheCount[minIndex] = nicheCount[minIndex] + 1;
}
// calculate the preference values of subproblem matrix and solution matrix
for (int i = 0; i < jointPopulation.size(); i++) {
for (int j = 0; j < populationSize; j++) {
subpMatrix[j][i] = fitnessFunction(jointPopulation.get(i), lambda[j]);
solMatrix[i][j] = distMatrix[i][j] + nicheCount[j];
}
}
// sort the preference value matrix to get the preference rank matrix
for (int i = 0; i < populationSize; i++) {
for (int j = 0; j < jointPopulation.size(); j++) {
subpPref[i][j] = j;
}
MOEADUtils.quickSort(subpMatrix[i], subpPref[i], 0, jointPopulation.size() - 1);
}
for (int i = 0; i < jointPopulation.size(); i++) {
for (int j = 0; j < populationSize; j++) {
solPref[i][j] = j;
}
MOEADUtils.quickSort(solMatrix[i], solPref[i], 0, populationSize - 1);
}
idx = stableMatching(subpPref, solPref, populationSize, jointPopulation.size());
population.clear();
for (int i = 0; i < populationSize; i++) {
population.add(i, jointPopulation.get(idx[i]));
}
}
/**
* Return the stable matching between 'subproblems' and 'solutions' ('subproblems' propose first).
* It is worth noting that the number of solutions is larger than that of the subproblems.
*/
public int[] stableMatching(int[][] manPref, int[][] womanPref, int menSize, int womenSize) {
// Indicates the mating status
int[] statusMan = new int[menSize];
int[] statusWoman = new int[womenSize];
final int NOT_ENGAGED = -1;
for (int i = 0; i < womenSize; i++) {
statusWoman[i] = NOT_ENGAGED;
}
// List of men that are not currently engaged.
LinkedList<Integer> freeMen = new LinkedList<Integer>();
for (int i = 0; i < menSize; i++) {
freeMen.add(i);
}
// next[i] is the next woman to whom i has not yet proposed.
int[] next = new int[womenSize];
while (!freeMen.isEmpty()) {
int m = freeMen.remove();
int w = manPref[m][next[m]];
next[m]++;
if (statusWoman[w] == NOT_ENGAGED) {
statusMan[m] = w;
statusWoman[w] = m;
} else {
int m1 = statusWoman[w];
if (prefers(m, m1, womanPref[w], menSize)) {
statusMan[m] = w;
statusWoman[w] = m;
freeMen.add(m1);
} else {
freeMen.add(m);
}
}
}
return statusMan;
}
/**
* Returns true in case that a given woman prefers x to y.
*/
public boolean prefers(int x, int y, int[] womanPref, int size) {
for (int i = 0; i < size; i++) {
int pref = womanPref[i];
if (pref == x) {
return true;
}
if (pref == y) {
return false;
}
}
// this should never happen.
System.out.println("Error in womanPref list!");
return false;
}
/**
* Calculate the perpendicular distance between the solution and reference line
*/
public double calculateDistance(DoubleSolution individual, double[] lambda) {
double scale;
double distance;
double[] vecInd = new double[problem.getNumberOfObjectives()];
double[] vecProj = new double[problem.getNumberOfObjectives()];
// vecInd has been normalized to the range [0,1]
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
vecInd[i] = (individual.objectives()[i] - idealPoint.getValue(i)) /
(nadirPoint.getValue(i) - idealPoint.getValue(i));
}
scale = innerproduct(vecInd, lambda) / innerproduct(lambda, lambda);
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
vecProj[i] = vecInd[i] - scale * lambda[i];
}
distance = norm_vector(vecProj);
return distance;
}
/**
* Calculate the perpendicular distance between the solution and reference line
*/
public double calculateDistance2(DoubleSolution individual, double[] lambda) {
double distance;
double distanceSum = 0.0;
double[] vecInd = new double[problem.getNumberOfObjectives()];
double[] normalizedObj = new double[problem.getNumberOfObjectives()];
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
distanceSum += individual.objectives()[i];
}
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
normalizedObj[i] = individual.objectives()[i] / distanceSum;
}
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
vecInd[i] = normalizedObj[i] - lambda[i];
}
distance = norm_vector(vecInd);
return distance;
}
/**
* Calculate the norm of the vector
*/
public double norm_vector(double[] z) {
double sum = 0;
for (int i = 0; i < problem.getNumberOfObjectives(); i++) {
sum += z[i] * z[i];
}
return Math.sqrt(sum);
}
/**
* Calculate the dot product of two vectors
*/
public double innerproduct(double[] vec1, double[] vec2) {
double sum = 0;
for (int i = 0; i < vec1.length; i++) {
sum += vec1[i] * vec2[i];
}
return sum;
}
@Override
public String getName() {
return "MOEADSTM";
}
@Override
public String getDescription() {
return "Multi-Objective Evolutionary Algorithm based on Decomposition. Version with Stable Matching Model";
}
}
| 4,787 |
1,025 | <filename>CodeXL/Components/ShaderAnalyzer/AMDTKernelAnalyzer/src/kaProjectSettingsExtension.cpp
//------------------------------ kaProjectSettingsExtension.h ------------------------------
// TinyXml:
#include <tinyxml.h>
// QT:
#include <QtWidgets>
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTApplicationComponents/Include/acFunctions.h>
// AMDTApplicationFramework:
#include <AMDTApplicationFramework/Include/afCSSSettings.h>
#include <AMDTApplicationFramework/Include/afGlobalVariablesManager.h>
#include <AMDTApplicationFramework/Include/afMainAppWindow.h>
// Local:
#include <AMDTKernelAnalyzer/src/kaApplicationCommands.h>
#include <AMDTKernelAnalyzer/src/kaBuildToolbar.h>
#include <AMDTKernelAnalyzer/src/kaProjectDataManager.h>
#include <AMDTKernelAnalyzer/src/kaProjectSettingsExtension.h>
#include <AMDTKernelAnalyzer/Include/kaStringConstants.h>
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::kaProjectSettingsExtension
// Description: Constructor
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
kaProjectSettingsExtension::kaProjectSettingsExtension() : m_pMacrosLineEdit(nullptr)
{
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::~gdProjectSettingsExtension
// Description: Destructor
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
kaProjectSettingsExtension::~kaProjectSettingsExtension()
{
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::initialize
// Description: Create the widget that is reading the debug setting for the debugger
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
void kaProjectSettingsExtension::Initialize()
{
m_pGridLayout = new QGridLayout(this);
m_pGridLayout->setContentsMargins(0, 0, 0, 0);
GenerateOptionsTable();
m_pGridWidget = new QWidget;
m_pGridWidget->setLayout(m_pGridLayout);
// Create the command text control:
m_pCommandTextEdit = new QTextEdit;
bool rc = kaProjectSettingsExtensionBase::connect(m_pCommandTextEdit, SIGNAL(textChanged()), this, SLOT(OnCommandTextChanged()));
GT_ASSERT(rc);
rc = kaProjectSettingsExtensionBase::connect(&KA_PROJECT_DATA_MGR_INSTANCE, SIGNAL(BuildOptionsChanged()), this, SLOT(OnCommandTextChanged()));
GT_ASSERT(rc);
kaApplicationCommands::instance().SetCommandTextEdit(m_pCommandTextEdit);
QString dummyText = "first \n second \n third\n forth";
QRect commandLineTextRect = QFontMetrics(m_pCommandTextEdit->font()).boundingRect(dummyText);
m_pCommandTextEdit->resize(-1, commandLineTextRect.height());
QLabel* pInfoLabel = new QLabel(KA_STR_optionsDialogEditCaption);
pInfoLabel->setStyleSheet(AF_STR_captionLabelStyleSheet);
// Create the main layout and add the controls to it:
QVBoxLayout* pMainLayout = new QVBoxLayout;
pMainLayout->addWidget(m_pGridWidget);
pMainLayout->addStretch();
QVBoxLayout* pBottomLayout = new QVBoxLayout;
pBottomLayout->addWidget(pInfoLabel, 0, Qt::AlignBottom);
pBottomLayout->addWidget(m_pCommandTextEdit, 1, Qt::AlignBottom);
pBottomLayout->setContentsMargins(0, 0, 0, 0);
pMainLayout->addLayout(pBottomLayout);
m_pCommandTextEdit->setStyleSheet(AF_STR_grayBorderWhiteBackgroundTE);
setLayout(pMainLayout);
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::ExtensionXMLString
// Description: Return the extension string
// Return Val: gtString&
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
gtString kaProjectSettingsExtension::ExtensionXMLString()
{
gtString retVal = KA_STR_projectSettingExtensionName;
return retVal;
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::extensionDisplayName
// Description: Return the display name for the extension
// Return Val: gtString
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
gtString kaProjectSettingsExtension::ExtensionTreePathAsString()
{
gtString retVal = KA_STR_projectSettingExtensionDisplayName;
return retVal;
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::getXMLSettingsString
// Description: Get the current debugger project settings as XML string
// Arguments: gtASCIIString& projectAsXMLString
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
bool kaProjectSettingsExtension::GetXMLSettingsString(gtString& projectAsXMLString)
{
bool retVal = false;
projectAsXMLString.appendFormattedString(L"<%ls>", ExtensionXMLString().asCharArray());
retVal = KA_PROJECT_DATA_MGR_INSTANCE.getXMLSettingsString(projectAsXMLString);
projectAsXMLString.appendFormattedString(L"</%ls>", ExtensionXMLString().asCharArray());
return retVal;
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::setSettingsFromXMLString
// Description: Get the project settings from the XML string
// Arguments: const gtASCIIString& projectAsXMLString
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
bool kaProjectSettingsExtension::SetSettingsFromXMLString(const gtString& projectAsXMLString)
{
bool retVal = false;
TiXmlNode* pKANode = new TiXmlElement(ExtensionXMLString().asASCIICharArray());
QString projectAsQtXML = acGTStringToQString(projectAsXMLString);
QByteArray projectAsQtXMLAsUTF8 = projectAsQtXML.toUtf8();
pKANode->Parse(projectAsQtXMLAsUTF8.data(), 0, TIXML_DEFAULT_ENCODING);
gtString kaNodeTitle;
kaNodeTitle.fromASCIIString(pKANode->Value());
if (ExtensionXMLString() == kaNodeTitle.asCharArray())
{
retVal = KA_PROJECT_DATA_MGR_INSTANCE.setSettingsFromXMLString(projectAsXMLString, pKANode);
if (retVal)
{
m_originalBuildOptions = KA_PROJECT_DATA_MGR_INSTANCE.BuildOptions();
}
}
QString macrosStr = KA_PROJECT_DATA_MGR_INSTANCE.KernelMacros();
GT_IF_WITH_ASSERT(nullptr != m_pMacrosLineEdit)
{
m_pMacrosLineEdit->setText(macrosStr);
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::SaveCurrentSettings
// Description: Get the current project settings from the controls, and store into
// the current project properties
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
bool kaProjectSettingsExtension::SaveCurrentSettings()
{
bool retVal = true;
// Save the command text value to the toolbar in the none VS mode
// and to the data manager:
auto pActiveProgram = KA_PROJECT_DATA_MGR_INSTANCE.GetActiveProgram();
if (pActiveProgram != nullptr && pActiveProgram->GetBuildType() != kaProgramDX)
{
// Save the text for next time we'll need the original text:
m_originalBuildOptions = m_pCommandTextEdit->toPlainText();
KA_PROJECT_DATA_MGR_INSTANCE.SetKernelBuildOptions(m_originalBuildOptions);
kaApplicationCommands::instance().SetToolbarBuildOptions(m_originalBuildOptions);
}
// set macros to project data
GT_IF_WITH_ASSERT(nullptr != m_pMacrosLineEdit)
{
KA_PROJECT_DATA_MGR_INSTANCE.SetKernelMacros(m_pMacrosLineEdit->text());
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::RestoreDefaultProjectSettings
// Description: Restore default project settings
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
void kaProjectSettingsExtension::RestoreDefaultProjectSettings()
{
if (nullptr != m_pCommandTextEdit)
{
m_pCommandTextEdit->setPlainText("");
}
m_originalBuildOptions.clear();
// Restore the data manager information, it will restore the edit box data:
KA_PROJECT_DATA_MGR_INSTANCE.setBuildOptions("");
KA_PROJECT_DATA_MGR_INSTANCE.SetShaderBuildOptions("");
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::AreSettingsValid
// Description: Check if the current settings are valid
// Arguments: gtString& invalidMessageStr
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
bool kaProjectSettingsExtension::AreSettingsValid(gtString& invalidMessageStr)
{
GT_UNREFERENCED_PARAMETER(invalidMessageStr);
// No project setting page at this stage for this extension
bool retVal = true;
return retVal;
}
// ---------------------------------------------------------------------------
// Name: kaProjectSettingsExtension::RestoreCurrentSettings
// Description: Load the current settings to the displayed widgets
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 5/8/2013
// ---------------------------------------------------------------------------
bool kaProjectSettingsExtension::RestoreCurrentSettings()
{
bool retVal = true;
// Restore the data manager information, it will restore the edit box data:
kaProgram* pActiveProgram = KA_PROJECT_DATA_MGR_INSTANCE.GetActiveProgram();
// restore the toolbar information:
if (pActiveProgram != nullptr && pActiveProgram->GetBuildType() == kaProgramCL)
{
KA_PROJECT_DATA_MGR_INSTANCE.setBuildOptions(m_originalBuildOptions);
kaApplicationCommands::instance().SetToolbarBuildOptions(m_originalBuildOptions);
}
return retVal;
}
// ---------------------------------------------------------------------------
void kaProjectSettingsExtension::GenerateOptionsTable()
{
// Create the first section:
QLabel* pGeneralLabel = new QLabel(KA_STR_optionsDialogGeneralSection);
pGeneralLabel->setStyleSheet(AF_STR_captionLabelStyleSheetMain);
m_pGridLayout->addWidget(pGeneralLabel, 1, 0, 1, 2);
kaProjectSettingFlagData* pDataFlag = AddTextEditOption(m_pGridLayout, KA_STR_optionsDialogPredefinedText, KA_STR_optionsDialogPredefinedTextTooltip);
m_pMacrosLineEdit = qobject_cast<QLineEdit*>(pDataFlag->m_pWidget);
AddTextEditOption(m_pGridLayout, KA_STR_optionsDialogAdditionalText, KA_STR_optionsDialogAdditionalTextTooltip);
AddComboBoxOption(m_pGridLayout, KA_STR_optionsDialogOpenCLFormatCombo, KA_STR_optionsDialogOpenCLFormatComboTooltip, kaProjectSettingFlagData::KA_FLAG_TYPE_COMBO_BOX_JOINED);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogDisableWarningCheck, KA_STR_optionsDialogDisableWarningCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogTreatAsErrorCheck, KA_STR_optionsDialogTreatAsErrorCheckTooltip);
// Create the second section:
QLabel* pOptimizeLabel = new QLabel(KA_STR_optionsDialogOptimizationSection);
pOptimizeLabel->setStyleSheet(AF_STR_captionLabelStyleSheet);
int numRows = m_pGridLayout->rowCount();
m_pGridLayout->addWidget(pOptimizeLabel, numRows, 0, 1, 2);
AddComboBoxOption(m_pGridLayout, KA_STR_optionsDialogOptimizationCombo, "");
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogTreatDoubleCheck, KA_STR_optionsDialogTreatDoubleCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogFlushCheck, KA_STR_optionsDialogFlushCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogCompilerAssumesCheck, KA_STR_optionsDialogCompilerAssumesCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogEnableMADCheck, KA_STR_optionsDialogEnableMADCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogIgnoreSignednessCheck, KA_STR_optionsDialogIgnoreSignednessCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogAllowUnsafeCheck, KA_STR_optionsDialogAllowUnsafeCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogAssumeNaNCheck, KA_STR_optionsDialogAssumeNaNCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogAggressiveMathCheck, KA_STR_optionsDialogAggressiveMathCheckTooltip);
AddCheckBoxOption(m_pGridLayout, KA_STR_optionsDialogCorrectlyRoundCheck, KA_STR_optionsDialogCorrectlyRoundCheckTooltip);
}
void kaProjectSettingsExtension::UpdateProjectDataManagerWithTBOptions(const QString& value, QStringList& optionsList)
{
GT_UNREFERENCED_PARAMETER(optionsList);
auto pActiveProgram = KA_PROJECT_DATA_MGR_INSTANCE.GetActiveProgram();
if (m_isBasicBuildOption && pActiveProgram != nullptr && kaProgramDX != pActiveProgram->GetBuildType())
{
KA_PROJECT_DATA_MGR_INSTANCE.setBuildOptions(value);
}
}
void kaProjectSettingsExtension::UpdateProjectDataManagerWithTBOptions(const QString& value)
{
// If just updating the text make sure that the project manager text is also updated and it will also update the
// second text box in the second setting page
QString oldCommands = KA_PROJECT_DATA_MGR_INSTANCE.BuildOptions();
if (oldCommands != value)
{
KA_PROJECT_DATA_MGR_INSTANCE.setBuildOptions(value);
}
}
| 4,421 |
620 | //
// PiwigoAlbumData.h
// piwigo
//
// Created by <NAME> on 1/24/15.
// Copyright (c) 2015 bakercrew. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "PiwigoImageData.h"
typedef enum {
ImageListOrderId,
ImageListOrderFileName,
ImageListOrderName,
ImageListOrderDate
} ImageListOrder;
@class ImageUpload;
@interface PiwigoAlbumData : NSObject
@property (nonatomic, assign) NSInteger albumId;
@property (nonatomic, assign) NSInteger parentAlbumId;
@property (nonatomic, strong) NSArray *upperCategories;
@property (nonatomic, assign) NSInteger nearestUpperCategory;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *comment;
@property (nonatomic, assign) CGFloat globalRank;
@property (nonatomic, assign) NSInteger numberOfImages;
@property (nonatomic, assign) NSInteger numberOfSubAlbumImages;
@property (nonatomic, assign) NSInteger numberOfSubCategories;
@property (nonatomic, assign) NSInteger albumThumbnailId;
@property (nonatomic, strong) NSString *albumThumbnailUrl;
@property (nonatomic, strong) NSDate *dateLast;
@property (nonatomic, strong) UIImage *categoryImage;
@property (nonatomic, readonly) NSArray *imageList;
-(void)addImages:(NSArray*)images;
-(void)removeImage:(PiwigoImageData*)image;
-(void)loadCategoryImageDataChunkForProgress:(void (^)(NSInteger onPage, NSInteger outOf))progress
OnCompletion:(void (^)(BOOL completed))completion;
-(void)loadAllCategoryImageDataForProgress:(void (^)(NSInteger onPage, NSInteger outOf))progress
OnCompletion:(void (^)(BOOL completed))completion;
-(void)updateCacheWithImageUploadInfo:(ImageUpload*)imageUpload;
-(NSInteger)getDepthOfCategory;
-(BOOL)containsUpperCategory:(NSInteger)category;
@end
| 556 |
1,853 | #define INSIGHTS_USE_TEMPLATE
#include <cstddef>
#include <type_traits>
namespace details {
template<class T>
struct remove_reference { typedef T type; };
template<class T>
struct remove_reference<T&> { typedef T type; };
template<class T>
struct remove_reference<T&&> { typedef T type; };
template<class T, size_t N = 0>
struct extent
{
static constexpr size_t value = N;
static_assert(N != 0, "Arrays only");
};
template<class T, size_t I>
struct extent<T[I], 0>
{
static constexpr size_t value = I;
static_assert(I != 0, "Arrays only");
};
} // namespace details
#define ARRAY_SIZE(var_x) \
details::extent<typename details::remove_reference< \
decltype(var_x)>::type>::value
class B
{
};
class E{};
template<typename T>
class S : public B
{
};
template<typename T>
class Y : public S<T>, public E
{
};
void test()
{
int buffer[16]{};
const auto& xx = ARRAY_SIZE(buffer);
S<int> s;
Y<double> y;
}
int main(){}
| 421 |
1,484 | <reponame>dspalmer99/anchore-engine<filename>tests/data/test_data_env/feeds/vulnerabilities/ol:7/2017-07-28T01:09:14.566549.json
[{"Vulnerability": {"Severity": "High", "NamespaceName": "oracle:7", "FixedIn": [{"VersionFormat": "rpm", "NamespaceName": "oracle:7", "Version": "0:3.8.13-118.19.3.el7uek", "Name": "kernel-uek-debug"}, {"VersionFormat": "rpm", "NamespaceName": "oracle:7", "Version": "0:3.8.13-118.19.3.el7uek", "Name": "kernel-uek-devel"}, {"VersionFormat": "rpm", "NamespaceName": "oracle:7", "Version": "0:3.8.13-118.19.3.el7uek", "Name": "kernel-uek-debug-devel"}, {"VersionFormat": "rpm", "NamespaceName": "oracle:7", "Version": "0:3.8.13-118.19.3.el7uek", "Name": "kernel-uek-doc"}, {"VersionFormat": "rpm", "NamespaceName": "oracle:7", "Version": "0:3.8.13-118.19.3.el7uek", "Name": "kernel-uek-firmware"}, {"VersionFormat": "rpm", "NamespaceName": "oracle:7", "Version": "0:3.8.13-118.19.3.el7uek", "Name": "kernel-uek"}, {"VersionFormat": "rpm", "NamespaceName": "oracle:7", "Version": "0:0.4.5-3.el7", "Name": "dtrace-modules-3.8.13-118.19.3.el7uek"}], "Link": "http://linux.oracle.com/errata/ELSA-2017-3596.html", "Description": " kernel-uek [3.8.13-118.19.3] - posix_acl: Clear SGID bit when setting file permissions (Jan Kara) [Orabug: 25507344] {CVE-2016-7097} {CVE-2016-7097} ", "Name": "ELSA-2017-3596"}}] | 572 |
347 | package org.ovirt.engine.core.common.action;
import java.io.Serializable;
import org.ovirt.engine.core.compat.Guid;
public class RemoveUnregisteredEntityParameters extends ActionParametersBase implements Serializable {
private static final long serialVersionUID = -149288206548640151L;
private Guid storagePoolId;
private Guid storageDomainId;
private Guid entityId;
public RemoveUnregisteredEntityParameters() {
this(Guid.Empty, Guid.Empty, Guid.Empty);
}
public RemoveUnregisteredEntityParameters(Guid entityId, Guid storageDomainId, Guid storagePoolId) {
this.setEntityId(entityId);
this.setStorageDomainId(storageDomainId);
this.setStoragePoolId(storagePoolId);
}
public Guid getStoragePoolId() {
return storagePoolId;
}
public void setStoragePoolId(Guid storagePoolId) {
this.storagePoolId = storagePoolId;
}
public Guid getStorageDomainId() {
return storageDomainId;
}
public void setStorageDomainId(Guid storageDomainId) {
this.storageDomainId = storageDomainId;
}
public Guid getEntityId() {
return entityId;
}
public void setEntityId(Guid entityId) {
this.entityId = entityId;
}
}
| 448 |
2,695 | // Copyright (C) 2013 Massachusetts Institute of Technology, Lincoln Laboratory
// License: Boost Software License See LICENSE.txt for the full license.
// Authors: <NAME> (<EMAIL>)
#ifndef MIT_LL_TOTAL_WoRD_FEATURE_EXTRACTOR_H_
#define MIT_LL_TOTAL_WoRD_FEATURE_EXTRACTOR_H_
#include <map>
#include "word_morphology_feature_extractor.h"
#include <dlib/statistics.h>
#include <dlib/vectorstream.h>
#include <dlib/hash.h>
namespace mitie
{
class total_word_feature_extractor
{
/*!
WHAT THIS OBJECT REPRESENTS
This is a tool for turning a word into a short and dense vector which
describes what kind of places in text a word can appear. This is done
using both word morphology and general distributional word features. Or in
other words, this object is basically a combination of the
word_morphology_feature_extractor along with a general table mapping words
to descriptive feature vectors (generally created from some CCA based
distributional feature thing).
THREAD SAFETY
Note that this object uses mutable internal scratch space. Therefore, it is
unsafe for two threads to touch the same instance of this object at a time
without mutex locking it first.
!*/
inline static std::string convert_numbers (
const std::string& str_
)
{
std::string str(str_);
for (unsigned long i = 0; i < str.size(); ++i)
{
if ('0' <= str[i] && str[i] <= '9')
str[i] = '#';
}
return str;
}
public:
total_word_feature_extractor() : fingerprint(0), non_morph_feats(0) {}
total_word_feature_extractor(
const std::map<std::string, dlib::matrix<float,0,1> >& word_vectors,
const word_morphology_feature_extractor& morph_fe_
) :
morph_fe(morph_fe_)
{
DLIB_CASSERT(word_vectors.size() != 0, "Invalid arguments");
std::map<std::string, dlib::matrix<float,0,1> >::const_iterator i;
i = word_vectors.begin();
non_morph_feats = i->second.size() + 1; // plus one for the OOV indicator
// now figure out how to relatively scale the word_vectors and morph features.
dlib::running_stats<double> rs_word, rs_morph;
dlib::matrix<float,0,1> feats;
for (; i != word_vectors.end(); ++i)
{
morph_fe.get_feature_vector(i->first, feats);
rs_morph.add(mean(abs(feats)));
rs_word.add(mean(abs(i->second)));
}
// scale the morphological features so they have an average feature value of 1.
morph_fe.premultiply_vectors_by(1/rs_morph.mean());
// We also want to scale the word vectors to have an average feature value of 1.
const double scale = 1/rs_word.mean();
// Now go though all the words again and compute the complete feature vectors for
// each and store that into total_word_vectors.
for (i = word_vectors.begin(); i != word_vectors.end(); ++i)
{
morph_fe.get_feature_vector(i->first, feats);
total_word_vectors[i->first] = join_cols(join_cols(dlib::zeros_matrix<float>(1,1), scale*i->second), feats);
}
// finally, don't forget to set the fingerprint to something
compute_fingerprint();
}
dlib::uint64 get_fingerprint(
) const { return fingerprint; }
/*!
ensures
- returns a 64bit ID number that uniquely identifies this object instance.
The ID is computed based on the state of this object, so any copy of it
that has the same state will have the same fingerprint ID number. This
is useful since down stream models that have been trained to use a
specific total_word_feature_extractor instance can record the fingerprint
of the total_word_feature_extractor they used and use that fingerprint ID
to verify that the same total_word_feature_extractor is being used later
on.
!*/
void get_feature_vector(
const std::string& word_,
dlib::matrix<float,0,1>& feats
) const
/*!
ensures
- #feats == a dense vector describing the given word
- #feats.size() == get_num_dimensions()
!*/
{
const std::string word = convert_numbers(word_);
std::map<std::string, dlib::matrix<float,0,1> >::const_iterator i;
i = total_word_vectors.find(word);
if (i != total_word_vectors.end())
{
feats = i->second;
return;
}
if (get_num_dimensions() == 0)
{
feats.set_size(0);
return;
}
morph_fe.get_feature_vector(word, temp);
feats = join_cols(dlib::zeros_matrix<float>(non_morph_feats,1), temp);
// This is an indicator feature used to model the fact that this word is
// outside our dictionary.
feats(0) = 1;
}
unsigned long get_num_dimensions(
) const
/*!
ensures
- returns the dimensionality of the feature vectors produced by this
object.
!*/
{
return non_morph_feats + morph_fe.get_num_dimensions();
}
unsigned long get_num_words_in_dictionary (
) const
{
return total_word_vectors.size();
}
std::vector<std::string> get_words_in_dictionary (
) const
{
std::vector<std::string> temp;
temp.reserve(total_word_vectors.size());
std::map<std::string, dlib::matrix<float,0,1> >::const_iterator i;
for (i = total_word_vectors.begin(); i != total_word_vectors.end(); ++i)
{
temp.push_back(i->first);
}
return temp;
}
friend void serialize(const total_word_feature_extractor& item, std::ostream& out)
{
int version = 2;
dlib::serialize(version, out);
dlib::serialize(item.fingerprint, out);
dlib::serialize(item.non_morph_feats, out);
dlib::serialize(item.total_word_vectors, out);
serialize(item.morph_fe, out);
}
friend void deserialize(total_word_feature_extractor& item, std::istream& in)
{
int version = 0;
dlib::deserialize(version, in);
if (version != 2)
throw dlib::serialization_error("Unexpected version found while deserializing total_word_feature_extractor.");
dlib::deserialize(item.fingerprint, in);
dlib::deserialize(item.non_morph_feats, in);
dlib::deserialize(item.total_word_vectors, in);
deserialize(item.morph_fe, in);
}
private:
void compute_fingerprint()
{
std::vector<char> buf;
dlib::vectorstream sout(buf);
sout << "fingerprint";
dlib::serialize(non_morph_feats, sout);
dlib::serialize(total_word_vectors, sout);
serialize(morph_fe, sout);
fingerprint = dlib::murmur_hash3_128bit(&buf[0], buf.size()).first;
}
dlib::uint64 fingerprint;
long non_morph_feats;
std::map<std::string, dlib::matrix<float,0,1> > total_word_vectors;
word_morphology_feature_extractor morph_fe;
// This object does not logically contribute to the state of this object. It is
// just here to avoid reallocating it over and over in get_feature_vector().
mutable dlib::matrix<float,0,1> temp;
};
}
#endif // MIT_LL_TOTAL_WoRD_FEATURE_EXTRACTOR_H_
| 3,874 |
634 | <gh_stars>100-1000
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.util.io.zip;
import java.util.Date;
public class DosTime {
private DosTime() {
}
/*
* Converts DOS time to Java time (number of milliseconds since epoch).
*/
public static long dosToJavaTime(long dtime) {
Date d = new Date((int)(((dtime >> 25) & 0x7f) + 80), (int)(((dtime >> 21) & 0x0f) - 1), (int)((dtime >> 16) & 0x1f),
(int)((dtime >> 11) & 0x1f), (int)((dtime >> 5) & 0x3f), (int)((dtime << 1) & 0x3e));
return d.getTime();
}
/*
* Converts Java time to DOS time.
*/
public static long javaToDosTime(long time) {
Date d = new Date(time);
int year = d.getYear() + 1900;
if (year < 1980) {
return (1 << 21) | (1 << 16);
}
return (year - 1980) << 25 |
(d.getMonth() + 1) << 21 |
d.getDate() << 16 |
d.getHours() << 11 |
d.getMinutes() << 5 |
d.getSeconds() >> 1;
}
}
| 610 |
1,178 | <reponame>leozz37/makani
# Copyright 2020 Makani Technologies LLC
#
# 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.
"""Indicators for network status."""
import collections
from makani.analysis.checks import check_range
from makani.avionics.common import cvt
from makani.avionics.network import aio_node
from makani.control import system_params
from makani.control import system_types
from makani.gs.monitor2.apps.layout import indicator
from makani.gs.monitor2.apps.layout import stoplights
from makani.gs.monitor2.apps.plugins import common
from makani.lib.python import c_helpers
_TETHER_NODE_FLAGS_HELPER = c_helpers.EnumHelper('TetherNodeFlag', cvt)
_AIO_NODE_HELPER = c_helpers.EnumHelper('AioNode', aio_node)
_SYSTEM_PARAMS = system_params.GetSystemParams().contents
_WING_TMS570_NODES = common.WingTms570Nodes()
class BaseTetherNodeStatusIndicator(indicator.BaseAttributeIndicator):
"""Base indicator class for individual node status."""
def __init__(self, name, node_name):
node_id = _AIO_NODE_HELPER.Value(node_name)
super(BaseTetherNodeStatusIndicator, self).__init__([
('filtered', 'merge_tether_down', 'node_status[%d]' % node_id),
('filtered', 'merge_tether_down',
'node_status_valid[%d]' % node_id),
], name)
def _IsValidInput(self, node_status, valid):
return valid
class BaseTetherAllNodeStatusIndicator(indicator.BaseAttributeIndicator):
"""Base indicator class for aggregated node status."""
def __init__(self, name):
super(BaseTetherAllNodeStatusIndicator, self).__init__([
('filtered', 'merge_tether_down', 'node_status'),
('filtered', 'merge_tether_down', 'node_status_valid'),
], name)
class BaseTetherNodeStatusFieldIndicator(BaseTetherNodeStatusIndicator):
def __init__(self, name, node_name, node_field):
super(BaseTetherNodeStatusFieldIndicator, self).__init__(
name, node_name)
self._node_field = node_field
@indicator.ReturnIfInputInvalid('--', stoplights.STOPLIGHT_UNAVAILABLE)
def _Filter(self, node_status, valid):
value = getattr(node_status, self._node_field)
return '% 4.1f' % value, stoplights.STOPLIGHT_NORMAL
class TetherNodeTempIndicator(BaseTetherNodeStatusFieldIndicator):
def __init__(self, name, node_name):
super(TetherNodeTempIndicator, self).__init__(
name, node_name, 'board_temp')
class TetherNodeHumidityIndicator(BaseTetherNodeStatusFieldIndicator):
def __init__(self, name, node_name):
super(TetherNodeHumidityIndicator, self).__init__(
name, node_name, 'board_humidity')
class BaseTetherNodeStatusFlagsIndicator(BaseTetherNodeStatusIndicator):
def __init__(self, name, node_name, node_flags):
super(BaseTetherNodeStatusFlagsIndicator, self).__init__(
name, node_name)
self._node_flags = node_flags
def _ActivatedFlags(self, node_status):
flags = node_status.flags
activated_flags = set()
for flag_name in self._node_flags:
if flags & _TETHER_NODE_FLAGS_HELPER.Value(flag_name):
activated_flags.add(flag_name)
return activated_flags
class TetherNodeNetworkIndicator(BaseTetherNodeStatusFlagsIndicator):
"""Show network status for individual node from the TetherDown."""
def __init__(self, name, node_name, enabled=True):
super(TetherNodeNetworkIndicator, self).__init__(
name, node_name, ['NetworkAGood', 'NetworkBGood'])
# If not `enabled`, the indicator always shows grey. We allow this
# scenario so that the indicators can still take a grid cell for the
# purpose of alignment in the status layout.
self._enabled = enabled
def _IsValidInput(self, node_status, valid):
return valid and self._enabled
@indicator.ReturnIfInputInvalid(
'A: -- B: -- ', stoplights.STOPLIGHT_UNAVAILABLE)
def _Filter(self, node_status, valid):
activated_flags = self._ActivatedFlags(node_status)
network_labels = ['A', 'B']
chars_per_network = 6
total_links = len(network_labels)
outputs = []
for idx, flag in enumerate(self._node_flags):
text = '%s: ' % network_labels[idx]
if flag in activated_flags:
text += 'Up'.ljust(chars_per_network)
else:
text += 'Down'.ljust(chars_per_network)
outputs.append(text)
total_up_links = len(activated_flags)
if not total_up_links:
stoplight = stoplights.STOPLIGHT_ERROR
elif total_up_links < total_links:
stoplight = stoplights.STOPLIGHT_WARNING
else:
stoplight = stoplights.STOPLIGHT_NORMAL
return ' '.join(outputs), stoplight
class TetherNodeFailureIndicator(BaseTetherNodeStatusFlagsIndicator):
def __init__(self, name, node_name):
super(TetherNodeFailureIndicator, self).__init__(
name, node_name, ['SelfTestFailure', 'AnyWarning', 'AnyError'])
@indicator.ReturnIfInputInvalid('--', stoplights.STOPLIGHT_UNAVAILABLE)
def _Filter(self, node_status, valid):
activated_flags = self._ActivatedFlags(node_status)
failures = []
warnings = []
for flag_name in ['SelfTestFailure', 'AnyError']:
if flag_name in activated_flags:
failures.append(flag_name)
for flag_name in ['AnyWarning']:
if flag_name in activated_flags:
warnings.append(flag_name)
reports = failures + warnings
text = ', '.join(reports) if reports else 'No Failures'
if failures:
stoplight = stoplights.STOPLIGHT_ERROR
elif warnings:
stoplight = stoplights.STOPLIGHT_WARNING
else:
stoplight = stoplights.STOPLIGHT_NORMAL
return text, stoplight
class TetherNodePowerIndicator(BaseTetherNodeStatusFlagsIndicator):
def __init__(self, name, node_name):
super(TetherNodePowerIndicator, self).__init__(
name, node_name, ['PowerGood'])
@indicator.ReturnIfInputInvalid('--', stoplights.STOPLIGHT_UNAVAILABLE)
def _Filter(self, node_status, valid):
activated_flags = self._ActivatedFlags(node_status)
if activated_flags:
text = 'Power Bad'
stoplight = stoplights.STOPLIGHT_ERROR
else:
text = 'Power Good'
stoplight = stoplights.STOPLIGHT_NORMAL
return text, stoplight
class BaseNodeStatusSummary(BaseTetherAllNodeStatusIndicator):
"""Summary indicator for node status."""
def __init__(self, name, field, normal_ranges, warning_ranges, char_limit):
super(BaseNodeStatusSummary, self).__init__(name)
self._normal_ranges = check_range.BuildRanges(normal_ranges)
self._warning_ranges = check_range.BuildRanges(warning_ranges)
self._char_limit = char_limit
self._field = field
def _SetMaxStatusValue(self, node_name, status_value, max_status_value,
node_with_max_value, category):
if status_value > max_status_value[category]:
max_status_value[category] = status_value
node_with_max_value[category] = node_name
def _DisplaySummary(self, max_status_value, node_with_max_value, category,
nodes, char_limit):
if node_with_max_value[category] is None:
return '--'
text = 'Max: %.0f (%s)' % (
max_status_value[category], node_with_max_value[category])
if nodes:
char_limit -= len(text) + 3
catalog = common.TimeCycle(
[n for n in nodes if n != node_with_max_value[category]],
char_limit, ',')
text += ' | ' + catalog
return text
def _Filter(self, node_status, valid):
status_values = {}
warnings = set()
errors = set()
any_value = False
max_status_value = {t: float('-inf')
for t in ['error', 'warning', 'normal']}
node_with_max_value = {t: None for t in ['error', 'warning', 'normal']}
for node_name in _WING_TMS570_NODES:
aio_node_id = _AIO_NODE_HELPER.Value(node_name)
if valid[aio_node_id]:
any_value = True
status_value = getattr(node_status[aio_node_id], self._field)
status_values[node_name] = status_value
if status_value not in self._normal_ranges:
if status_value not in self._warning_ranges:
errors.add(node_name)
self._SetMaxStatusValue(node_name, status_value, max_status_value,
node_with_max_value, 'error')
else:
warnings.add(node_name)
self._SetMaxStatusValue(node_name, status_value, max_status_value,
node_with_max_value, 'warning')
else:
self._SetMaxStatusValue(node_name, status_value, max_status_value,
node_with_max_value, 'normal')
if not any_value:
text = '--'
stoplight = stoplights.STOPLIGHT_UNAVAILABLE
elif errors:
text = self._DisplaySummary(
max_status_value, node_with_max_value, 'error', errors,
self._char_limit)
stoplight = stoplights.STOPLIGHT_ERROR
elif warnings:
text = self._DisplaySummary(
max_status_value, node_with_max_value, 'warning', warnings,
self._char_limit)
stoplight = stoplights.STOPLIGHT_WARNING
else:
text = self._DisplaySummary(max_status_value, node_with_max_value,
'normal', None, self._char_limit)
stoplight = stoplights.STOPLIGHT_NORMAL
return text, stoplight
class TetherMaxBoardTemperature(BaseNodeStatusSummary):
"""Indicator for board temperature."""
def __init__(self, name, normal_ranges, warning_ranges, char_limit):
super(TetherMaxBoardTemperature, self).__init__(
name, 'board_temp', normal_ranges, warning_ranges, char_limit)
class TetherMaxBoardHumidity(BaseNodeStatusSummary):
"""Indicator for board humidity."""
def __init__(self, name, normal_ranges, warning_ranges, char_limit):
super(TetherMaxBoardHumidity, self).__init__(
name, 'board_humidity', normal_ranges, warning_ranges, char_limit)
class BaseNodeStatusFlagsSummary(BaseTetherAllNodeStatusIndicator):
"""Summary indicator for node status."""
_MAX_CHARS = 20
def __init__(self, name, flag_names, normal_if_set, is_error,
merge_flags=True, nodes_to_exclude=None):
super(BaseNodeStatusFlagsSummary, self).__init__(name)
self._flag_names = flag_names
self._normal_if_set = normal_if_set
self._is_error = is_error
self._merge_flags = merge_flags
self._nodes_to_exclude = nodes_to_exclude
def _Filter(self, node_status, valid):
if self._merge_flags:
bad_nodes = set()
else:
bad_nodes = collections.defaultdict(list)
error = False
warning = False
any_value = False
for node_name in _WING_TMS570_NODES:
if self._nodes_to_exclude and node_name in self._nodes_to_exclude:
continue
aio_node_id = _AIO_NODE_HELPER.Value(node_name)
if valid[aio_node_id]:
any_value = True
flags = node_status[aio_node_id].flags
num_caught = 0
for flag_name in self._flag_names:
if (bool(flags & _TETHER_NODE_FLAGS_HELPER.Value(flag_name)) !=
self._normal_if_set):
num_caught += 1
if self._merge_flags:
bad_nodes.add(node_name)
else:
bad_nodes[flag_name].append(node_name)
if self._is_error is None:
if num_caught == len(self._flag_names):
error = True
elif num_caught:
warning = True
elif self._is_error:
error |= bool(num_caught)
else:
warning |= bool(num_caught)
if not any_value:
stoplight = stoplights.STOPLIGHT_UNAVAILABLE
elif error:
stoplight = stoplights.STOPLIGHT_ERROR
elif warning:
stoplight = stoplights.STOPLIGHT_WARNING
else:
stoplight = stoplights.STOPLIGHT_NORMAL
if bad_nodes:
if self._merge_flags:
return common.TimeCycle(sorted(bad_nodes), self._MAX_CHARS), stoplight
else:
return self._ShowDetailedReport(bad_nodes), stoplight
elif any_value:
return 'Normal', stoplight
else:
return '--', stoplight
def _ShowDetailedReport(self, bad_nodes):
lines = [
flag + ': ' + common.TimeCycle(bad_nodes[flag], self._MAX_CHARS)
for flag in sorted(bad_nodes)]
return '\n'.join(lines)
class TetherNodePowerSummary(BaseNodeStatusFlagsSummary):
def __init__(self, name):
super(TetherNodePowerSummary, self).__init__(
'Power', ['PowerGood'], normal_if_set=False, is_error=True)
class TetherNodeNetworkSummary(BaseNodeStatusFlagsSummary):
def __init__(self, name):
super(TetherNodeNetworkSummary, self).__init__(
'Network', ['NetworkAGood', 'NetworkBGood'],
normal_if_set=True, is_error=None, merge_flags=False,
nodes_to_exclude=common.NETWORK_STATUS_NODES_TO_EXCLUDE)
def _ShowDetailedReport(self, bad_nodes):
keys = {'NetworkAGood': 'A', 'NetworkBGood': 'B'}
lines = [
keys[flag] + ': ' +
common.TimeCycle(bad_nodes[flag], self._MAX_CHARS)
for flag in sorted(bad_nodes)]
return '\n'.join(lines)
class TetherNodeSelfTestSummary(BaseNodeStatusFlagsSummary):
def __init__(self, name):
super(TetherNodeSelfTestSummary, self).__init__(
'Self Test', ['SelfTestFailure'], normal_if_set=False, is_error=True)
class TetherNodeErrorSummary(BaseNodeStatusFlagsSummary):
def __init__(self, name):
nodes_to_exclude = []
if _SYSTEM_PARAMS.wing_serial == system_types.kWingSerial01:
# Eliminate MVLV from error reporting since 4 of its temperature sensors
# are not reliable due to common mode noise in Gin configuration (SN01)
nodes_to_exclude = ['Mvlv']
super(TetherNodeErrorSummary, self).__init__(
'Error', ['AnyError'], normal_if_set=False, is_error=True,
nodes_to_exclude=nodes_to_exclude)
class TetherNodeWarningSummary(BaseNodeStatusFlagsSummary):
def __init__(self, name):
super(TetherNodeWarningSummary, self).__init__(
'Warning', ['AnyWarning'], normal_if_set=False, is_error=False)
| 5,741 |
3,189 | <filename>bp/src/PrivateHeaders/CoreSimulator/NSString-SIMCPUType.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
@import Foundation;
@interface NSString (SIMCPUType)
+ (id)sim_stringForCPUType:(int)arg1;
- (int)sim_cpuType;
@end
| 128 |
1,115 | """ Testing for util.py """
import pathlib
from unittest import mock
import pytest
from quilt3 import util
# Constants
TEST_YAML = """
# This is an arbitrary comment solely for the purposes of testing.
c: the speed of light
d: a programming language that almost mattered
# Another arbitrary comment.
e: a not-so-hip MC from a relatively unknown nightclub # do you like cats?
"""
# Code
def test_write_yaml(tmpdir):
fname = tmpdir / 'some_file.yml'
util.write_yaml({'testing': 'foo'}, fname)
assert fname.read_text('utf-8') == 'testing: foo\n'
util.write_yaml({'testing': 'bar'}, fname, keep_backup=True)
fnames = [name for name in tmpdir.listdir() if name.basename.startswith('some_file')]
assert len(fnames) == 2
fname2 = max(fnames, key=lambda x: len(x.basename)) # backup name is longer
assert fname2.read_text('utf-8') == 'testing: foo\n'
assert fname.read_text('utf-8') == 'testing: bar\n'
def test_read_yaml(tmpdir):
# Read a string
parsed_string = util.read_yaml(TEST_YAML)
fname = tmpdir / 'test_read_yaml.yml'
util.write_yaml(parsed_string, fname)
# Read file descriptor..
with fname.open('r') as f:
parsed_file = util.read_yaml(f)
assert parsed_file == parsed_string
# Read Path object
parsed_path_obj = util.read_yaml(pathlib.Path(fname))
assert parsed_string == parsed_path_obj
def test_read_yaml_exec_flaw(capfd):
# We don't execute anything remote, but someone could give a bad build.yml..
with pytest.raises(util.QuiltException) as exc_info:
util.read_yaml("""!!python/object/apply:os.system\nargs: ['echo arbitrary code execution!']""")
assert "could not determine a constructor for the tag" in str(exc_info.value)
def test_validate_url():
with pytest.raises(util.QuiltException, match='Port must be a number'):
util.validate_url('http://foo:bar')
with pytest.raises(util.QuiltException, match='Requires at least scheme and host'):
util.validate_url('blah')
@pytest.mark.parametrize(
'env_val, expected_val',
(
(None, None),
('', None),
('1', 1),
('10', 10),
('20', 20),
)
)
def test_get_pos_int_from_env(env_val, expected_val):
var_name = 'ENV_VAR_NAME'
with mock.patch.dict('os.environ', {} if env_val is None else {var_name: env_val}, clear=True):
assert util.get_pos_int_from_env(var_name) == expected_val
@pytest.mark.parametrize('env_val', ('blah', '-3', '0'))
def test_get_pos_int_from_env_error(env_val):
var_name = 'ENV_VAR_NAME'
with mock.patch.dict('os.environ', {} if env_val is None else {var_name: env_val}, clear=True):
with pytest.raises(ValueError) as e:
util.get_pos_int_from_env(var_name)
assert f'{var_name} must be a positive integer' == str(e.value)
| 1,163 |
634 | """
Simple styling used for matplotlib figures
"""
from matplotlib import pyplot as plt
# Configuration settings to help visibility on small screen / prints
plt.rcParams['xtick.labelsize'] = 20
plt.rcParams['ytick.labelsize'] = 20
plt.rcParams['figure.titlesize'] = 15
plt.rcParams['font.size'] = 20
plt.rcParams['axes.labelsize'] = 20
plt.rcParams['axes.facecolor'] = 'none'
plt.rcParams['legend.fontsize'] = 18
plt.rcParams['lines.linewidth'] = 3
plt.rcParams['figure.figsize'] = [.8 * 6.4, .8 * 4.8]
plt.rcParams['legend.frameon'] = False
plt.rcParams['legend.columnspacing'] = 1.8
plt.rcParams['legend.handlelength'] = 1.5
plt.rcParams['legend.handletextpad'] = 0.5
# Utility functions
def light_axis():
"Hide the top and right spines"
ax = plt.gca()
for s in ('top', 'right'):
ax.spines[s].set_visible(False)
plt.xticks(())
plt.yticks(())
plt.subplots_adjust(left=.01, bottom=.01, top=.99, right=.99)
def no_axis():
plt.axis('off')
plt.subplots_adjust(left=.0, bottom=.0, top=1, right=1)
| 445 |
4,962 | <filename>byte-buddy-dep/src/test/java/net/bytebuddy/matcher/VisibilityMatcherTest.java
package net.bytebuddy.matcher;
import net.bytebuddy.description.ByteCodeElement;
import net.bytebuddy.description.type.TypeDescription;
import org.junit.Test;
import org.mockito.Mock;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;
public class VisibilityMatcherTest extends AbstractElementMatcherTest<VisibilityMatcher<?>> {
@Mock
private TypeDescription typeDescription;
@Mock
private ByteCodeElement byteCodeElement;
@SuppressWarnings("unchecked")
public VisibilityMatcherTest() {
super((Class<? extends VisibilityMatcher<?>>) (Object) VisibilityMatcher.class, "isVisibleTo");
}
@Test
public void testMatch() throws Exception {
when(byteCodeElement.isVisibleTo(typeDescription)).thenReturn(true);
assertThat(new VisibilityMatcher<ByteCodeElement>(typeDescription).matches(byteCodeElement), is(true));
verify(byteCodeElement).isVisibleTo(typeDescription);
verifyNoMoreInteractions(byteCodeElement);
verifyZeroInteractions(typeDescription);
}
@Test
public void testNoMatch() throws Exception {
when(byteCodeElement.isVisibleTo(typeDescription)).thenReturn(false);
assertThat(new VisibilityMatcher<ByteCodeElement>(typeDescription).matches(byteCodeElement), is(false));
verify(byteCodeElement).isVisibleTo(typeDescription);
verifyNoMoreInteractions(byteCodeElement);
verifyZeroInteractions(typeDescription);
}
}
| 552 |
335 | <gh_stars>100-1000
{
"word": "Exploration",
"definitions": [
"The action of exploring an unfamiliar area.",
"The action of searching an area for natural resources.",
"Thorough examination of a subject."
],
"parts-of-speech": "Noun"
} | 104 |
4,879 | <reponame>kudlav/organicmaps
package com.mapswithme.maps.base;
public interface NoConnectionListener
{
void onNoConnectionError();
}
| 43 |
1,346 | <reponame>disrupted/Trakttv.bundle
from oem_framework.models.core.base import BaseMapping, BaseMedia, Model
from oem_framework.models.core.registry import ModelRegistry
| 54 |
766 | <reponame>data-man/libfsm<gh_stars>100-1000
/* generated */
#include "class.h"
static const struct range ranges[] = {
{ 0x0000UL, 0x0040UL },
{ 0x005BUL, 0x0060UL },
{ 0x007BUL, 0x00A9UL },
{ 0x00ABUL, 0x00B9UL },
{ 0x00BBUL, 0x00BFUL },
{ 0x00D7UL, 0x00D7UL },
{ 0x00F7UL, 0x00F7UL },
{ 0x02B9UL, 0x02DFUL },
{ 0x02E5UL, 0x02E9UL },
{ 0x02ECUL, 0x02FFUL },
{ 0x0374UL, 0x0374UL },
{ 0x037EUL, 0x037EUL },
{ 0x0385UL, 0x0385UL },
{ 0x0387UL, 0x0387UL },
{ 0x0605UL, 0x0605UL },
{ 0x060CUL, 0x060CUL },
{ 0x061BUL, 0x061BUL },
{ 0x061FUL, 0x061FUL },
{ 0x0640UL, 0x0640UL },
{ 0x06DDUL, 0x06DDUL },
{ 0x08E2UL, 0x08E2UL },
{ 0x0964UL, 0x0965UL },
{ 0x0E3FUL, 0x0E3FUL },
{ 0x0FD5UL, 0x0FD8UL },
{ 0x10FBUL, 0x10FBUL },
{ 0x16EBUL, 0x16EDUL },
{ 0x1735UL, 0x1736UL },
{ 0x1802UL, 0x1803UL },
{ 0x1805UL, 0x1805UL },
{ 0x1CD3UL, 0x1CD3UL },
{ 0x1CE1UL, 0x1CE1UL },
{ 0x1CE9UL, 0x1CECUL },
{ 0x1CEEUL, 0x1CF3UL },
{ 0x1CF5UL, 0x1CF7UL },
{ 0x1CFAUL, 0x1CFAUL },
{ 0x2000UL, 0x200BUL },
{ 0x200EUL, 0x2064UL },
{ 0x2066UL, 0x2070UL },
{ 0x2074UL, 0x207EUL },
{ 0x2080UL, 0x208EUL },
{ 0x20A0UL, 0x20C0UL },
{ 0x2100UL, 0x2125UL },
{ 0x2127UL, 0x2129UL },
{ 0x212CUL, 0x2131UL },
{ 0x2133UL, 0x214DUL },
{ 0x214FUL, 0x215FUL },
{ 0x2189UL, 0x218BUL },
{ 0x2190UL, 0x2426UL },
{ 0x2440UL, 0x244AUL },
{ 0x2460UL, 0x27FFUL },
{ 0x2900UL, 0x2B73UL },
{ 0x2B76UL, 0x2B95UL },
{ 0x2B97UL, 0x2BFFUL },
{ 0x2E00UL, 0x2E5DUL },
{ 0x2FF0UL, 0x2FFBUL },
{ 0x3000UL, 0x3004UL },
{ 0x3006UL, 0x3006UL },
{ 0x3008UL, 0x3020UL },
{ 0x3030UL, 0x3037UL },
{ 0x303CUL, 0x303FUL },
{ 0x309BUL, 0x309CUL },
{ 0x30A0UL, 0x30A0UL },
{ 0x30FBUL, 0x30FCUL },
{ 0x3190UL, 0x319FUL },
{ 0x31C0UL, 0x31E3UL },
{ 0x3220UL, 0x325FUL },
{ 0x327FUL, 0x32CFUL },
{ 0x32FFUL, 0x32FFUL },
{ 0x3358UL, 0x33FFUL },
{ 0x4DC0UL, 0x4DFFUL },
{ 0xA700UL, 0xA721UL },
{ 0xA788UL, 0xA78AUL },
{ 0xA830UL, 0xA839UL },
{ 0xA92EUL, 0xA92EUL },
{ 0xA9CFUL, 0xA9CFUL },
{ 0xAB5BUL, 0xAB5BUL },
{ 0xAB6AUL, 0xAB6BUL },
{ 0xFD3EUL, 0xFD3FUL },
{ 0xFE10UL, 0xFE19UL },
{ 0xFE30UL, 0xFE52UL },
{ 0xFE54UL, 0xFE66UL },
{ 0xFE68UL, 0xFE6BUL },
{ 0xFEFFUL, 0xFEFFUL },
{ 0xFF01UL, 0xFF20UL },
{ 0xFF3BUL, 0xFF40UL },
{ 0xFF5BUL, 0xFF65UL },
{ 0xFF70UL, 0xFF70UL },
{ 0xFF9EUL, 0xFF9FUL },
{ 0xFFE0UL, 0xFFE6UL },
{ 0xFFE8UL, 0xFFEEUL },
{ 0xFFF9UL, 0xFFFDUL },
{ 0x10100UL, 0x10102UL },
{ 0x10107UL, 0x10133UL },
{ 0x10137UL, 0x1013FUL },
{ 0x10190UL, 0x1019CUL },
{ 0x101D0UL, 0x101FCUL },
{ 0x102E1UL, 0x102FBUL },
{ 0x1BCA0UL, 0x1BCA3UL },
{ 0x1CF50UL, 0x1CFC3UL },
{ 0x1D000UL, 0x1D0F5UL },
{ 0x1D100UL, 0x1D126UL },
{ 0x1D129UL, 0x1D166UL },
{ 0x1D16AUL, 0x1D17AUL },
{ 0x1D183UL, 0x1D184UL },
{ 0x1D18CUL, 0x1D1A9UL },
{ 0x1D1AEUL, 0x1D1EAUL },
{ 0x1D2E0UL, 0x1D2F3UL },
{ 0x1D300UL, 0x1D356UL },
{ 0x1D360UL, 0x1D378UL },
{ 0x1D400UL, 0x1D454UL },
{ 0x1D456UL, 0x1D49CUL },
{ 0x1D49EUL, 0x1D49FUL },
{ 0x1D4A2UL, 0x1D4A2UL },
{ 0x1D4A5UL, 0x1D4A6UL },
{ 0x1D4A9UL, 0x1D4ACUL },
{ 0x1D4AEUL, 0x1D4B9UL },
{ 0x1D4BBUL, 0x1D4BBUL },
{ 0x1D4BDUL, 0x1D4C3UL },
{ 0x1D4C5UL, 0x1D505UL },
{ 0x1D507UL, 0x1D50AUL },
{ 0x1D50DUL, 0x1D514UL },
{ 0x1D516UL, 0x1D51CUL },
{ 0x1D51EUL, 0x1D539UL },
{ 0x1D53BUL, 0x1D53EUL },
{ 0x1D540UL, 0x1D544UL },
{ 0x1D546UL, 0x1D546UL },
{ 0x1D54AUL, 0x1D550UL },
{ 0x1D552UL, 0x1D6A5UL },
{ 0x1D6A8UL, 0x1D7CBUL },
{ 0x1D7CEUL, 0x1D7FFUL },
{ 0x1EC71UL, 0x1ECB4UL },
{ 0x1ED01UL, 0x1ED3DUL },
{ 0x1F000UL, 0x1F02BUL },
{ 0x1F030UL, 0x1F093UL },
{ 0x1F0A0UL, 0x1F0AEUL },
{ 0x1F0B1UL, 0x1F0BFUL },
{ 0x1F0C1UL, 0x1F0CFUL },
{ 0x1F0D1UL, 0x1F0F5UL },
{ 0x1F100UL, 0x1F1ADUL },
{ 0x1F1E6UL, 0x1F1FFUL },
{ 0x1F201UL, 0x1F202UL },
{ 0x1F210UL, 0x1F23BUL },
{ 0x1F240UL, 0x1F248UL },
{ 0x1F250UL, 0x1F251UL },
{ 0x1F260UL, 0x1F265UL },
{ 0x1F300UL, 0x1F6D7UL },
{ 0x1F6DDUL, 0x1F6ECUL },
{ 0x1F6F0UL, 0x1F6FCUL },
{ 0x1F700UL, 0x1F773UL },
{ 0x1F780UL, 0x1F7D8UL },
{ 0x1F7E0UL, 0x1F7EBUL },
{ 0x1F7F0UL, 0x1F7F0UL },
{ 0x1F800UL, 0x1F80BUL },
{ 0x1F810UL, 0x1F847UL },
{ 0x1F850UL, 0x1F859UL },
{ 0x1F860UL, 0x1F887UL },
{ 0x1F890UL, 0x1F8ADUL },
{ 0x1F8B0UL, 0x1F8B1UL },
{ 0x1F900UL, 0x1FA53UL },
{ 0x1FA60UL, 0x1FA6DUL },
{ 0x1FA70UL, 0x1FA74UL },
{ 0x1FA78UL, 0x1FA7CUL },
{ 0x1FA80UL, 0x1FA86UL },
{ 0x1FA90UL, 0x1FAACUL },
{ 0x1FAB0UL, 0x1FABAUL },
{ 0x1FAC0UL, 0x1FAC5UL },
{ 0x1FAD0UL, 0x1FAD9UL },
{ 0x1FAE0UL, 0x1FAE7UL },
{ 0x1FAF0UL, 0x1FAF6UL },
{ 0x1FB00UL, 0x1FB92UL },
{ 0x1FB94UL, 0x1FBCAUL },
{ 0x1FBF0UL, 0x1FBF9UL },
{ 0xE0001UL, 0xE0001UL },
{ 0xE0020UL, 0xE007FUL }
};
const struct class utf8_Common = {
ranges,
sizeof ranges / sizeof *ranges
};
| 3,015 |
1,133 | /**
*
* PixelFlow | Copyright (C) 2016 <NAME> - http://thomasdiewald.com
*
* A Processing/Java library for high performance GPU-Computing (GLSL).
* MIT License: https://opensource.org/licenses/MIT
*
*/
package OpticalFlow.OpticalFlow_ExportPFM.Demo_OpticalFlowMovie_PFM;
import java.io.File;
import java.io.IOException;
import com.jogamp.opengl.GL2;
import com.thomasdiewald.pixelflow.java.DwPixelFlow;
import com.thomasdiewald.pixelflow.java.dwgl.DwGLTexture;
import com.thomasdiewald.pixelflow.java.imageprocessing.DwOpticalFlow;
import com.thomasdiewald.pixelflow.java.imageprocessing.filter.DwFilter;
import com.thomasdiewald.pixelflow.java.utils.DwFrameCapture;
import com.thomasdiewald.pixelflow.java.utils.DwPortableFloatMap;
import processing.core.*;
import processing.opengl.PGraphics2D;
import processing.video.Movie;
public class Demo_OpticalFlowMovie_PFM extends PApplet {
//
// Optical flow computed based on image sequence of a Movie.
//
// The resulting velocity-textures gets exported as PFM-files.
//
int viewport_w = 1280;
int viewport_h = 720;
int viewport_x = 230;
int viewport_y = 0;
DwPixelFlow context;
DwOpticalFlow opticalflow;
PGraphics2D pg_oflow;
boolean APPLY_GRAYSCALE = false;
boolean APPLY_BILATERAL = true;
// buffer for the movie-image
PGraphics2D pg_movie_a, pg_movie_b;
Movie movie;
public void settings() {
size(viewport_w, viewport_h, P2D);
smooth(8);
}
public void setup() {
surface.setLocation(viewport_x, viewport_y);
// main library context
context = new DwPixelFlow(this);
context.print();
context.printGL();
// opticalflow
opticalflow = new DwOpticalFlow(context, width, height);
// some flow parameters
opticalflow.param.blur_flow = 5;
opticalflow.param.blur_input = 10;
opticalflow.param.temporal_smoothing = 0.50f;
opticalflow.param.flow_scale = 50;
opticalflow.param.threshold = 1.0f; // flow vector length threshold
opticalflow.param.display_mode = 0;
// render target
pg_oflow = (PGraphics2D) createGraphics(width, height, P2D);
pg_oflow.smooth(8);
// movie file is not contained in the library release
// to keep the file size small. please use one of your own videos instead.
movie = new Movie(this, "examples/data/Pulp_Fiction_Dance_Scene.mp4");
movie.loop();
movie.frameRate(24);
frameRate(160);
}
void resize(Movie movie){
int mw = movie.width;
int mh = movie.height;
if(pg_movie_a == null || pg_movie_a.width != mw || pg_movie_a.height != mh){
pg_movie_a = (PGraphics2D) createGraphics(mw, mh, P2D);
pg_movie_a.smooth(0);
pg_movie_b = (PGraphics2D) createGraphics(mw, mh, P2D);
pg_movie_b.smooth(0);
pg_oflow = (PGraphics2D) createGraphics(mw, mh, P2D);
pg_oflow.smooth(0);
System.out.println("resized optical flow frames: "+mw+", "+mh);
}
}
// int frameCount_movie = 0;
public void draw() {
if(movie.available()){
movie.read();
resize(movie);
// frameCount_movie++;
// float ratio_frameCount = frameCount_movie / (float)frameCount;
// float ratio_frameRate = movie.frameRate / (float)frameRate;
// System.out.println(frameCount_movie+", "+frameCount+", "+ratio_frameCount);
// System.out.println(movie.frameRate+", "+frameRate+", "+ratio_frameRate);
// put onto gl buffer
pg_movie_a.beginDraw();
pg_movie_a.blendMode(REPLACE);
pg_movie_a.image(movie, 0, 0);
pg_movie_a.endDraw();
// apply filters (not necessary)
if(APPLY_GRAYSCALE){
DwFilter.get(context).luminance.apply(pg_movie_a, pg_movie_a);
}
if(APPLY_BILATERAL){
DwFilter.get(context).bilateral.apply(pg_movie_a, pg_movie_b, 5, 0.10f, 4);
swapCamBuffer();
}
// compute Optical Flow
opticalflow.update(pg_movie_a);
// write PFM
if(pmf_write_sequence_enabled && frameCount % pmf_write_every_nth_frame == 0){
writePFM(opticalflow.frameCurr.velocity);
}
// render Optical Flow
pg_oflow.beginDraw();
pg_oflow.clear();
pg_oflow.endDraw();
// opticalflow visualizations
// 1) velocity is displayed as dense, colored shading
if(mousePressed && mouseButton == RIGHT) opticalflow.renderVelocityShading(pg_oflow);
// 2) velocity is displayed as vectors
// display_mode = 0 --> lines, along the velocity direction
// display_mode = 1 --> lines, normal to the velocity direction
opticalflow.param.display_mode = (mousePressed && mouseButton == CENTER) ? 1 : 0;
opticalflow.renderVelocityStreams(pg_oflow, Math.round(pmf_scale * 4));
// original dimensions
int screen_w = width;
int screen_h = height;
int movie_w = pg_movie_a.width;
int movie_h = pg_movie_a.height;
// compute scale factor for display
float scalex = screen_w / (float) movie_w;
float scaley = screen_h / (float) movie_h;
float scale = Math.min(scalex, scaley);
// compute position and size, to fit images into screen
int dw = (int) (movie_w * scale);
int dh = (int) (movie_h * scale);
int dx = (int) (-dw/2f + screen_w/2f);
int dy = (int) (-dh/2f + screen_h/2f);
// display movie, and optical flow vectors on top
background(0);
image(pg_movie_a, dx, dy, dw, dh);
image(pg_oflow , dx, dy, dw, dh);
}
// info
String txt_fps = String.format(getClass().getName()+ " [size %d/%d] [frame %d] [fps %6.2f]", pg_oflow.width, pg_oflow.height, opticalflow.UPDATE_STEP, frameRate);
surface.setTitle(txt_fps);
}
void swapCamBuffer(){
PGraphics2D tmp = pg_movie_a;
pg_movie_a = pg_movie_b;
pg_movie_b = tmp;
}
public void keyReleased(){
if(key == '1') APPLY_GRAYSCALE = !APPLY_GRAYSCALE;
if(key == '2') APPLY_BILATERAL = !APPLY_BILATERAL;
if(key == 'w') writePFM(opticalflow.frameCurr.velocity);
if(key == 'e') pmf_write_sequence_enabled = !pmf_write_sequence_enabled;
}
// PFM EXPORT SETTINGS
boolean pmf_write_sequence_enabled = !true;
int pmf_write_every_nth_frame = 1;
float pmf_scale = 2;
boolean pmf_debug_check = false;
boolean normalize_velocities = true;
// PMF write/reader
DwPortableFloatMap pfm_w = new DwPortableFloatMap();
DwPortableFloatMap pfm_r = new DwPortableFloatMap();
// used to create filenames for the PFM sequence
DwFrameCapture fcapture;
// texture, for down-sampling before writing the pmf-file.
// TODO: better down-sampling if necessary
DwGLTexture tex_small = new DwGLTexture();
/**
*
* Writes a PFM-File (Color, 3 x 32bit float) based on the given DwGLTexture.
*
* PFM ... Portable Float Map
*
*/
public void writePFM(DwGLTexture tex){
// compute smaller texture dimensions
int w = (int) Math.ceil(tex.w / pmf_scale);
int h = (int) Math.ceil(tex.h / pmf_scale);
// prepare smaller texture for quicker transfer and export
tex_small.resize(context, GL2.GL_RGB32F, w, h, GL2.GL_RGB, GL2.GL_FLOAT, GL2.GL_LINEAR, 3, 4, null);
// copy original velocity-texture to a smaller one, GPU
DwFilter.get(context).copy.apply(tex, tex_small);
// read velocity-texture from GPU memory to our local memory
pfm_w.float_array = tex_small.getFloatTextureData(pfm_w.float_array);
// optionally do some post-process, CPU
if(normalize_velocities){
normalizeVelocities(pfm_w.float_array, w, h);
}
// write PMF file
try {
// DwFrameCapture is only used here for creating a filename
if(fcapture == null){
fcapture = new DwFrameCapture(this, "examples/");
}
// create unique filename
File filename = fcapture.createFilename(String.format("%d_%d", w, h), "pfm");
// write file
pfm_w.write(filename, pfm_w.float_array, w, h);
System.out.println("pfm-file: "+filename.getAbsolutePath());
// optionally check data
if(pmf_debug_check){
pfm_r.read(filename);
pfm_r.debugPrint();
pfm_r.debugCompare(pfm_w);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* normalizes the velocity vectors and saves the magnitude in the blue channel.
* r ... velocity x [-1, +1]
* g ... velocity y [-1, +1]
* b ... velocity mag [ 0, Float.MAX_VALUE]
*
*/
public void normalizeVelocities(float[] rgb, int w, int h){
int num_pixel = w * h;
for(int i = 0, pi = 0; i < num_pixel; i++, pi += 3){
float x = rgb[pi + 0];
float y = rgb[pi + 1];
float mag = (float) Math.sqrt(x*x + y*y);
rgb[pi + 0] = x / mag;
rgb[pi + 1] = y / mag;
rgb[pi + 2] = mag;
}
}
public static void main(String args[]) {
PApplet.main(new String[] { Demo_OpticalFlowMovie_PFM.class.getName() });
}
} | 3,961 |
994 | /*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
FxTypes.h
Abstract:
This defines the memory tags for the frameworks objects
Author:
Revision History:
--*/
#ifndef _FXTYPES_H
#define _FXTYPES_H
//
// Might be expanded to a ULONG if we need the storage
//
typedef USHORT WDFTYPE;
enum FX_OBJECT_TYPES_BASE {
FX_TYPES_BASE = 0x1000,
FX_TYPES_PACKAGES_BASE = 0x1100,
FX_TYPES_IO_TARGET_BASE = 0x1200,
FX_ABSTRACT_TYPES_BASE = 0x1300,
FX_TYPES_DMA_BASE = 0x1400,
FX_TYPES_INTERFACES_BASE = 0x1500,
};
enum FX_OBJECT_TYPES {
// Use Hex numbers since this the kd default dump value
FX_TYPE_OBJECT = FX_TYPES_BASE+0x0,
FX_TYPE_DRIVER = FX_TYPES_BASE+0x1,
FX_TYPE_DEVICE = FX_TYPES_BASE+0x2,
FX_TYPE_QUEUE = FX_TYPES_BASE+0x3,
FX_TYPE_WMI_PROVIDER = FX_TYPES_BASE+0x4,
// can be reused = FX_TYPES_BASE+0x5,
FX_TYPE_REG_KEY = FX_TYPES_BASE+0x6,
FX_TYPE_STRING = FX_TYPES_BASE+0x7,
FX_TYPE_REQUEST = FX_TYPES_BASE+0x8,
FX_TYPE_LOOKASIDE = FX_TYPES_BASE+0x9,
IFX_TYPE_MEMORY = FX_TYPES_BASE+0xA,
FX_TYPE_IRPQUEUE = FX_TYPES_BASE+0xB,
FX_TYPE_USEROBJECT = FX_TYPES_BASE+0xC,
// can be reused FX_TYPES_BASE+0xD,
FX_TYPE_COLLECTION = FX_TYPES_BASE+0xE,
// can be reused = FX_TYPES_BASE+0x11,
FX_TYPE_VERIFIERLOCK = FX_TYPES_BASE+0x12,
FX_TYPE_SYSTEMTHREAD = FX_TYPES_BASE+0x13,
FX_TYPE_MP_DEVICE = FX_TYPES_BASE+0x14,
FX_TYPE_DPC = FX_TYPES_BASE+0x15,
FX_TYPE_RESOURCE_IO = FX_TYPES_BASE+0x16,
FX_TYPE_RESOURCE_CM = FX_TYPES_BASE+0x17,
FX_TYPE_FILEOBJECT = FX_TYPES_BASE+0x18,
// can be reused = FX_TYPES_BASE+0x19,
// can be reused = FX_TYPES_BASE+0x20,
FX_TYPE_RELATED_DEVICE = FX_TYPES_BASE+0x21,
FX_TYPE_MEMORY_PREALLOCATED = FX_TYPES_BASE+0x22,
FX_TYPE_WAIT_LOCK = FX_TYPES_BASE+0x23,
FX_TYPE_SPIN_LOCK = FX_TYPES_BASE+0x24,
FX_TYPE_WORKITEM = FX_TYPES_BASE+0x25,
FX_TYPE_CLEANUPLIST = FX_TYPES_BASE+0x26,
FX_TYPE_INTERRUPT = FX_TYPES_BASE+0x27,
FX_TYPE_TIMER = FX_TYPES_BASE+0x28,
FX_TYPE_CHILD_LIST = FX_TYPES_BASE+0x29,
FX_TYPE_DEVICE_BASE = FX_TYPES_BASE+0x30,
FX_TYPE_SYSTEMWORKITEM = FX_TYPES_BASE+0x31,
FX_TYPE_REQUEST_MEMORY = FX_TYPES_BASE+0x32,
FX_TYPE_DISPOSELIST = FX_TYPES_BASE+0x33,
FX_TYPE_WMI_INSTANCE = FX_TYPES_BASE+0x34,
FX_TYPE_IO_RES_LIST = FX_TYPES_BASE+0x35,
FX_TYPE_CM_RES_LIST = FX_TYPES_BASE+0x36,
FX_TYPE_IO_RES_REQ_LIST = FX_TYPES_BASE+0x37,
FX_TYPE_COMPANION_TARGET = FX_TYPES_BASE+0x38,
FX_TYPE_COMPANION = FX_TYPES_BASE+0x39,
FX_TYPE_TASK_QUEUE = FX_TYPES_BASE+0x40,
FX_TYPE_PACKAGE_IO = FX_TYPES_PACKAGES_BASE+0x0,
FX_TYPE_PACKAGE_FDO = FX_TYPES_PACKAGES_BASE+0x1,
FX_TYPE_PACKAGE_PDO = FX_TYPES_PACKAGES_BASE+0x2,
FX_TYPE_WMI_IRP_HANDLER = FX_TYPES_PACKAGES_BASE+0x3,
FX_TYPE_PACKAGE_GENERAL = FX_TYPES_PACKAGES_BASE+0x4,
FX_TYPE_DEFAULT_IRP_HANDLER = FX_TYPES_PACKAGES_BASE+0x5,
FX_TYPE_WMI_TRACING_IRP_HANDLER = FX_TYPES_PACKAGES_BASE+0x6,
FX_TYPE_IO_TARGET = FX_TYPES_IO_TARGET_BASE+0x0,
FX_TYPE_IO_TARGET_REMOTE = FX_TYPES_IO_TARGET_BASE+0x1,
FX_TYPE_IO_TARGET_USB_DEVICE = FX_TYPES_IO_TARGET_BASE+0x2,
FX_TYPE_IO_TARGET_USB_PIPE = FX_TYPES_IO_TARGET_BASE+0x3,
FX_TYPE_USB_INTERFACE = FX_TYPES_IO_TARGET_BASE+0x4,
FX_TYPE_IO_TARGET_SELF = FX_TYPES_IO_TARGET_BASE+0x5,
FX_TYPE_DMA_ENABLER = FX_TYPES_DMA_BASE+0x0,
FX_TYPE_DMA_TRANSACTION = FX_TYPES_DMA_BASE+0x1,
FX_TYPE_COMMON_BUFFER = FX_TYPES_DMA_BASE+0x2,
// Interfaces
FX_TYPE_IASSOCIATE = FX_TYPES_INTERFACES_BASE+0x01,
// unused
FX_TYPE_IHASCALLBACKS = FX_TYPES_INTERFACES_BASE+0x03,
// unused = FX_TYPES_INTERFACES_BASE+0x04,
FX_TYPE_NONE = 0xFFFF,
};
// begin_wpp config
// CUSTOM_TYPE(FX_OBJECT_TYPES, ItemEnum(FX_OBJECT_TYPES));
// end_wpp
#endif // _FXTYPES_H
| 2,786 |
1,975 | <reponame>r3yn0ld4/omaha
// Copyright 2007-2010 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.
// ========================================================================
//
// ApplicationUsageData unit tests
#include "omaha/base/reg_key.h"
#include "omaha/base/user_info.h"
#include "omaha/base/utils.h"
#include "omaha/base/vistautil.h"
#include "omaha/testing/unit_test.h"
#include "omaha/goopdate/application_usage_data.h"
namespace omaha {
const TCHAR kAppDidRunValueName[] = _T("dr");
const TCHAR kHKCUClientStateKeyName[] =
_T("HKCU\\Software\\") SHORT_COMPANY_NAME _T("\\") PRODUCT_NAME
_T("\\ClientState\\{6ACB7D4D-E5BA-48b0-85FE-A4051500A1BD}");
const TCHAR kMachineClientState[] =
_T("HKLM\\Software\\") SHORT_COMPANY_NAME _T("\\") PRODUCT_NAME
_T("\\ClientState\\{6ACB7D4D-E5BA-48b0-85FE-A4051500A1BD}");
const TCHAR kLowIntegrityIEHKCU[] =
_T("HKCU\\Software\\Microsoft\\Internet Explorer\\")
_T("InternetRegistry\\REGISTRY\\USER\\");
const TCHAR kAppGuid[] = _T("{6ACB7D4D-E5BA-48b0-85FE-A4051500A1BD}");
const TCHAR kRelativeClientState[] =
_T("Software\\") SHORT_COMPANY_NAME _T("\\") PRODUCT_NAME
_T("\\ClientState\\{6ACB7D4D-E5BA-48b0-85FE-A4051500A1BD}");
// TODO(omaha): Expected and actual are reversed throughout this file. Fix.
class ApplicationUsageDataTest : public testing::Test {
protected:
virtual void SetUp() {
CString sid;
ASSERT_SUCCEEDED(user_info::GetProcessUser(NULL, NULL, &sid));
low_integrity_key_name_ = AppendRegKeyPath(kLowIntegrityIEHKCU,
sid,
kRelativeClientState);
TearDown();
}
virtual void TearDown() {
RegKey::DeleteKey(kHKCUClientStateKeyName);
RegKey::DeleteKey(kMachineClientState);
RegKey::DeleteKey(low_integrity_key_name_);
}
void CreateMachineDidRunValue(bool value) {
if (!vista_util::IsUserAdmin()) {
return;
}
RegKey key;
ASSERT_SUCCEEDED(key.Create(kMachineClientState));
ASSERT_SUCCEEDED(key.SetValue(kAppDidRunValueName,
value == true ? _T("1") : _T("0")));
}
void CreateMachineDidRunDwordValue(bool value) {
if (!vista_util::IsUserAdmin()) {
return;
}
RegKey key;
DWORD new_value = (value == true ? 1 : 0);
ASSERT_SUCCEEDED(key.Create(kMachineClientState));
ASSERT_SUCCEEDED(key.SetValue(kAppDidRunValueName, new_value));
}
bool MachineDidRunValueExists() {
if (!vista_util::IsUserAdmin()) {
return true;
}
RegKey key;
if (FAILED(key.Open(kMachineClientState))) {
return false;
}
CString did_run_str(_T("0"));
if (FAILED(key.GetValue(kAppDidRunValueName, &did_run_str))) {
return false;
}
return true;
}
void DeleteMachineDidRunValue() {
if (!vista_util::IsUserAdmin()) {
return;
}
ASSERT_SUCCEEDED(RegKey::DeleteValue(kMachineClientState,
kAppDidRunValueName));
}
void CheckMachineDidRunValue(bool expected) {
if (!vista_util::IsUserAdmin()) {
return;
}
RegKey key;
ASSERT_SUCCEEDED(key.Open(kMachineClientState));
CString did_run_str(_T("0"));
ASSERT_SUCCEEDED(key.GetValue(kAppDidRunValueName, &did_run_str));
bool value = (did_run_str == _T("1")) ? true : false;
ASSERT_EQ(value, expected);
}
void CreateUserDidRunValue(bool value) {
RegKey key;
ASSERT_SUCCEEDED(key.Create(kHKCUClientStateKeyName));
ASSERT_SUCCEEDED(key.SetValue(kAppDidRunValueName,
(value == true) ? _T("1") : _T("0")));
}
void CreateUserDidRunDwordValue(bool value) {
RegKey key;
DWORD new_value = (value == true ? 1 : 0);
ASSERT_SUCCEEDED(key.Create(kHKCUClientStateKeyName));
ASSERT_SUCCEEDED(key.SetValue(kAppDidRunValueName, new_value));
}
void DeleteUserDidRunValue() {
ASSERT_SUCCEEDED(RegKey::DeleteValue(kHKCUClientStateKeyName,
kAppDidRunValueName));
}
void CheckUserDidRunValue(bool expected) {
RegKey key;
ASSERT_SUCCEEDED(key.Open(kHKCUClientStateKeyName));
CString did_run_str(_T("0"));
ASSERT_SUCCEEDED(key.GetValue(kAppDidRunValueName, &did_run_str));
bool value = (did_run_str == _T("1")) ? true : false;
ASSERT_EQ(value, expected);
}
bool UserDidRunValueExists() {
RegKey key;
if (FAILED(key.Open(kHKCUClientStateKeyName))) {
return false;
}
CString did_run_str(_T("0"));
if (FAILED(key.GetValue(kAppDidRunValueName, &did_run_str))) {
return false;
}
return true;
}
void CreateLowIntegrityUserDidRunValue(bool value) {
RegKey key;
ASSERT_SUCCEEDED(key.Create(low_integrity_key_name_));
ASSERT_SUCCEEDED(key.SetValue(kAppDidRunValueName,
(value == true) ? _T("1") : _T("0")));
}
void CreateLowIntegrityUserDidRunDwordValue(bool value) {
RegKey key;
DWORD new_value = (value == true ? 1 : 0);
ASSERT_SUCCEEDED(key.Create(low_integrity_key_name_));
ASSERT_SUCCEEDED(key.SetValue(kAppDidRunValueName, new_value));
}
void DeleteLowIntegrityUserDidRunValue() {
ASSERT_SUCCEEDED(RegKey::DeleteValue(low_integrity_key_name_,
kAppDidRunValueName));
}
void CheckLowIntegrityUserDidRunValue(bool expected) {
RegKey key;
ASSERT_SUCCEEDED(key.Open(low_integrity_key_name_));
CString did_run_str(_T("0"));
ASSERT_SUCCEEDED(key.GetValue(kAppDidRunValueName, &did_run_str));
bool value = (did_run_str == _T("1")) ? true : false;
ASSERT_EQ(value, expected);
}
bool LowIntegrityUserDidRunValueExists() {
RegKey key;
if (FAILED(key.Open(low_integrity_key_name_))) {
return false;
}
CString did_run_str(_T("0"));
if (FAILED(key.GetValue(kAppDidRunValueName, &did_run_str))) {
return false;
}
return true;
}
// This method takes in machine_did_run, user_did_run and
// low_user_did_run as int's. The idea is that the test tries to simulate
// all of these values as being not-present, and if present then true or
// false.
// -1 indicates non-presense, 1 indicates true, and 0 false. The caller
// then loops over all these values to capture testing all the permutations.
void TestUserAndMachineDidRun(int machine_did_run,
int user_did_run,
int low_user_did_run,
bool expected_exists,
bool expected_did_run,
int is_vista) {
ApplicationUsageData data(true, is_vista ? true : false);
// Set up the registry for the test.
if (machine_did_run != -1) {
CreateMachineDidRunValue((machine_did_run == 1) ? true: false);
}
if (user_did_run != -1) {
CreateUserDidRunValue((user_did_run == 1) ? true: false);
}
if (low_user_did_run != -1) {
CreateLowIntegrityUserDidRunValue((low_user_did_run == 1) ? true: false);
}
// Perform the test.
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), expected_exists);
ASSERT_EQ(data.did_run(), expected_did_run);
// Check the return values.
if (machine_did_run == -1) {
ASSERT_FALSE(MachineDidRunValueExists());
} else {
CheckMachineDidRunValue((machine_did_run == 1) ? true: false);
}
if (user_did_run == -1) {
ASSERT_FALSE(UserDidRunValueExists());
} else {
CheckUserDidRunValue((user_did_run == 1) ? true: false);
}
if (low_user_did_run == -1) {
ASSERT_FALSE(LowIntegrityUserDidRunValueExists());
} else {
CheckLowIntegrityUserDidRunValue((low_user_did_run == 1) ? true: false);
}
}
void TestUserAndMachineDidRunPostProcess(int machine_did_run,
int user_did_run,
int low_user_did_run,
bool expected_exists,
int is_vista) {
ApplicationUsageData data(true, is_vista ? true : false);
// Setup the registry for the test.
if (machine_did_run != -1) {
CreateMachineDidRunValue((machine_did_run == 1) ? true: false);
}
if (user_did_run != -1) {
CreateUserDidRunValue((user_did_run == 1) ? true: false);
}
if (low_user_did_run != -1) {
CreateLowIntegrityUserDidRunValue((low_user_did_run == 1) ? true: false);
}
// Run the test.
ASSERT_SUCCEEDED(data.ResetDidRun(kAppGuid));
if (user_did_run == -1) {
ASSERT_FALSE(UserDidRunValueExists());
} else {
CheckUserDidRunValue(false);
}
if (low_user_did_run == -1) {
ASSERT_FALSE(LowIntegrityUserDidRunValueExists());
} else {
if (is_vista) {
CheckLowIntegrityUserDidRunValue(false);
} else {
CheckLowIntegrityUserDidRunValue((low_user_did_run == 1) ? true: false);
}
}
if (machine_did_run == -1) {
ASSERT_FALSE(MachineDidRunValueExists());
} else {
if (user_did_run != -1 || (is_vista && low_user_did_run != -1)) {
// This means that the user keys exists for this application
// we should have delete the machine key.
ASSERT_EQ(MachineDidRunValueExists(), false);
} else {
CheckMachineDidRunValue(false);
}
}
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), expected_exists);
ASSERT_EQ(data.did_run(), false);
}
void UserTestDidRunPreProcess(int user_did_run,
int low_user_did_run,
int is_vista,
bool expected_exists,
bool expected_did_run) {
ApplicationUsageData data(false, is_vista ? true : false);
// Set up the registry for the test.
CreateMachineDidRunValue(true);
if (user_did_run != -1) {
CreateUserDidRunValue((user_did_run == 1) ? true: false);
}
if (low_user_did_run != -1) {
CreateLowIntegrityUserDidRunValue((low_user_did_run == 1) ? true: false);
}
// Perform the test.
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), expected_exists);
ASSERT_EQ(data.did_run(), expected_did_run);
// The machine value should not have changed from what we set it to.
CheckMachineDidRunValue(true);
if (user_did_run == -1) {
// If we did not create the user value it should not exist.
ASSERT_FALSE(UserDidRunValueExists());
}
if (low_user_did_run == -1) {
// If we did not create the low integrity user value it should not exist.
ASSERT_FALSE(LowIntegrityUserDidRunValueExists());
}
}
void UserTestDidRunPostProcess(int user_did_run,
int low_user_did_run,
int is_vista) {
// Create a user ApplicationUsageData class.
ApplicationUsageData data(false, is_vista ? true : false);
// This should not affect the test.
CreateMachineDidRunValue(true);
if (user_did_run != -1) {
CreateUserDidRunValue((user_did_run == 1) ? true: false);
}
if (low_user_did_run != -1) {
CreateLowIntegrityUserDidRunValue((low_user_did_run == 1) ? true: false);
}
ASSERT_SUCCEEDED(data.ResetDidRun(kAppGuid));
// The machine did run shold never get affected.
CheckMachineDidRunValue(true);
if (user_did_run == -1) {
ASSERT_FALSE(UserDidRunValueExists());
} else {
// In all cases if the HKCU did run is set, it should get cleared.
CheckUserDidRunValue(false);
}
if (low_user_did_run == -1) {
ASSERT_FALSE(LowIntegrityUserDidRunValueExists());
} else {
// In case of vista, the low integrity user value should get reset.
CheckLowIntegrityUserDidRunValue(is_vista ? false :
(low_user_did_run == 1) ? true : false);
}
}
private:
CString low_integrity_key_name_;
};
TEST_F(ApplicationUsageDataTest, ReadDidRunUser1) {
ApplicationUsageData data(true, false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), false);
ASSERT_EQ(data.did_run(), false);
// Test with false user value.
CreateUserDidRunValue(false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), true);
ASSERT_EQ(data.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ReadDwordDidRunUser1) {
ApplicationUsageData data(true, false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), false);
ASSERT_EQ(data.did_run(), false);
// Test with false user value.
CreateUserDidRunDwordValue(false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), true);
ASSERT_EQ(data.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ReadDidRunUser2) {
// Test with true user value.
ApplicationUsageData data1(true, false);
CreateUserDidRunValue(true);
ASSERT_SUCCEEDED(data1.ReadDidRun(kAppGuid));
ASSERT_EQ(data1.exists(), true);
ASSERT_EQ(data1.did_run(), true);
}
TEST_F(ApplicationUsageDataTest, ReadDwordDidRunUser2) {
// Test with true user value.
ApplicationUsageData data1(true, false);
CreateUserDidRunDwordValue(true);
ASSERT_SUCCEEDED(data1.ReadDidRun(kAppGuid));
ASSERT_EQ(data1.exists(), true);
ASSERT_EQ(data1.did_run(), true);
}
TEST_F(ApplicationUsageDataTest, ReadDidRunUser3) {
// low integrity user = false, vista
ApplicationUsageData data2(true, true);
CreateLowIntegrityUserDidRunValue(false);
ASSERT_SUCCEEDED(data2.ReadDidRun(kAppGuid));
ASSERT_EQ(data2.exists(), true);
ASSERT_EQ(data2.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ReadDwordDidRunUser3) {
// low integrity user = false, vista
ApplicationUsageData data2(true, true);
CreateLowIntegrityUserDidRunDwordValue(false);
ASSERT_SUCCEEDED(data2.ReadDidRun(kAppGuid));
ASSERT_EQ(data2.exists(), true);
ASSERT_EQ(data2.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ReadDidRunUser4) {
// low integrity user = true, vista
ApplicationUsageData data2(true, true);
CreateLowIntegrityUserDidRunValue(true);
ASSERT_SUCCEEDED(data2.ReadDidRun(kAppGuid));
ASSERT_EQ(data2.exists(), true);
ASSERT_EQ(data2.did_run(), true);
}
TEST_F(ApplicationUsageDataTest, ReadDwordDidRunUser4) {
// low integrity user = true, vista
ApplicationUsageData data2(true, true);
CreateLowIntegrityUserDidRunDwordValue(true);
ASSERT_SUCCEEDED(data2.ReadDidRun(kAppGuid));
ASSERT_EQ(data2.exists(), true);
ASSERT_EQ(data2.did_run(), true);
}
TEST_F(ApplicationUsageDataTest, ReadDidRunUser5) {
// low integrity user = true, not vista
ApplicationUsageData data2(true, false);
CreateLowIntegrityUserDidRunValue(true);
ASSERT_SUCCEEDED(data2.ReadDidRun(kAppGuid));
ASSERT_EQ(data2.exists(), false);
ASSERT_EQ(data2.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ReadDwordDidRunUser5) {
// low integrity user = true, not vista
ApplicationUsageData data2(true, false);
CreateLowIntegrityUserDidRunDwordValue(true);
ASSERT_SUCCEEDED(data2.ReadDidRun(kAppGuid));
ASSERT_EQ(data2.exists(), false);
ASSERT_EQ(data2.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ReadDidRunMachine1) {
if (!vista_util::IsUserAdmin()) {
return;
}
ApplicationUsageData data(true, true);
// create machine application key and test
CreateMachineDidRunValue(false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), true);
ASSERT_EQ(data.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ReadDwordDidRunMachine1) {
if (!vista_util::IsUserAdmin()) {
return;
}
ApplicationUsageData data(true, true);
// create machine application key and test
CreateMachineDidRunDwordValue(false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), true);
ASSERT_EQ(data.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ReadDidRunMachine2) {
if (!vista_util::IsUserAdmin()) {
return;
}
ApplicationUsageData data1(true, true);
CreateMachineDidRunValue(true);
ASSERT_SUCCEEDED(data1.ReadDidRun(kAppGuid));
ASSERT_EQ(data1.exists(), true);
ASSERT_EQ(data1.did_run(), true);
}
TEST_F(ApplicationUsageDataTest, ReadDwordDidRunMachine2) {
if (!vista_util::IsUserAdmin()) {
return;
}
ApplicationUsageData data1(true, true);
CreateMachineDidRunDwordValue(true);
ASSERT_SUCCEEDED(data1.ReadDidRun(kAppGuid));
ASSERT_EQ(data1.exists(), true);
ASSERT_EQ(data1.did_run(), true);
}
TEST_F(ApplicationUsageDataTest, ReadDidRunBoth1) {
if (!vista_util::IsUserAdmin()) {
return;
}
// We try all combinations of machine, user and low integrity user
// registry value for did run. -1 indicates the value does not exist
// 1 indicates true and 0 indicates false.
for (int vista = 0; vista < 2; ++vista) {
for (int machine = -1; machine < 2; ++machine) {
for (int user = -1; user < 2; ++user) {
for (int lowuser = -1; lowuser < 2; ++lowuser) {
bool expected_did_run = false;
bool expected_exists = false;
if (machine > -1 || user > -1 || (vista && lowuser > -1)) {
expected_exists = true;
}
if (machine > 0 || user > 0 || (vista && lowuser > 0)) {
expected_did_run = true;
}
TestUserAndMachineDidRun(machine, user, lowuser,
expected_exists,
expected_did_run,
vista);
TearDown();
}
}
}
}
}
TEST_F(ApplicationUsageDataTest, ResetDidRunUser1) {
ApplicationUsageData data(true, true);
// create user application key and test
CreateUserDidRunValue(false);
ASSERT_SUCCEEDED(data.ResetDidRun(kAppGuid));
CheckUserDidRunValue(false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), true);
ASSERT_EQ(data.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ResetDidRunUser2) {
ApplicationUsageData data1(true, true);
CreateUserDidRunValue(true);
ASSERT_SUCCEEDED(data1.ResetDidRun(kAppGuid));
CheckUserDidRunValue(false);
ASSERT_SUCCEEDED(data1.ReadDidRun(kAppGuid));
ASSERT_EQ(data1.exists(), true);
ASSERT_EQ(data1.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ResetDidRunUser3) {
ApplicationUsageData data(true, true);
// create user application key and test
CreateUserDidRunDwordValue(false);
ASSERT_SUCCEEDED(data.ResetDidRun(kAppGuid));
CheckUserDidRunValue(false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), true);
ASSERT_EQ(data.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ResetDidRunUser4) {
ApplicationUsageData data1(true, true);
CreateUserDidRunDwordValue(true);
ASSERT_SUCCEEDED(data1.ResetDidRun(kAppGuid));
CheckUserDidRunValue(false);
ASSERT_SUCCEEDED(data1.ReadDidRun(kAppGuid));
ASSERT_EQ(data1.exists(), true);
ASSERT_EQ(data1.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ResetDidRunMachine1) {
if (!vista_util::IsUserAdmin()) {
return;
}
ApplicationUsageData data(true, true);
CreateMachineDidRunValue(false);
ASSERT_SUCCEEDED(data.ResetDidRun(kAppGuid));
CheckMachineDidRunValue(false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), true);
ASSERT_EQ(data.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ResetDidRunMachine2) {
if (!vista_util::IsUserAdmin()) {
return;
}
ApplicationUsageData data1(true, true);
CreateMachineDidRunValue(true);
ASSERT_SUCCEEDED(data1.ResetDidRun(kAppGuid));
CheckMachineDidRunValue(false);
ASSERT_SUCCEEDED(data1.ReadDidRun(kAppGuid));
ASSERT_EQ(data1.exists(), true);
ASSERT_EQ(data1.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ResetDidRunMachine3) {
if (!vista_util::IsUserAdmin()) {
return;
}
ApplicationUsageData data(true, true);
CreateMachineDidRunDwordValue(false);
ASSERT_SUCCEEDED(data.ResetDidRun(kAppGuid));
CheckMachineDidRunValue(false);
ASSERT_SUCCEEDED(data.ReadDidRun(kAppGuid));
ASSERT_EQ(data.exists(), true);
ASSERT_EQ(data.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ResetDidRunMachine4) {
if (!vista_util::IsUserAdmin()) {
return;
}
ApplicationUsageData data1(true, true);
CreateMachineDidRunDwordValue(true);
ASSERT_SUCCEEDED(data1.ResetDidRun(kAppGuid));
CheckMachineDidRunValue(false);
ASSERT_SUCCEEDED(data1.ReadDidRun(kAppGuid));
ASSERT_EQ(data1.exists(), true);
ASSERT_EQ(data1.did_run(), false);
}
TEST_F(ApplicationUsageDataTest, ResetDidRunBoth) {
if (!vista_util::IsUserAdmin()) {
return;
}
// We try all combinations of machine, user and low integrity user
// registry value for did run. -1 indicates the value does not exist
// 1 indicates true and 0 indicates false.
for (int vista = 0; vista < 2; ++vista) {
for (int machine = -1; machine < 2; ++machine) {
for (int user = -1; user < 2; ++user) {
for (int lowuser = -1; lowuser < 2; ++lowuser) {
bool expected_exists = false;
if (machine > -1 || user > -1 || (vista && lowuser > -1)) {
expected_exists = true;
}
TestUserAndMachineDidRunPostProcess(machine, user, lowuser,
expected_exists,
vista);
TearDown();
}
}
}
}
}
TEST_F(ApplicationUsageDataTest, UserReadDidRunUser) {
for (int vista = 0; vista < 2; ++vista) {
for (int user = -1; user < 2; ++user) {
for (int lowuser = -1; lowuser < 2; ++lowuser) {
bool expected_exists = false;
bool expected_did_run = false;
if (user != -1 || (vista && lowuser != -1)) {
expected_exists = true;
}
if (user > 0 || (vista && lowuser > 0)) {
expected_did_run = true;
}
UserTestDidRunPreProcess(user, lowuser, vista, expected_exists,
expected_did_run);
TearDown();
}
}
}
}
TEST_F(ApplicationUsageDataTest, UserResetDidRunUser1) {
for (int vista = 0; vista < 2; ++vista) {
for (int user = -1; user < 2; ++user) {
for (int lowuser = -1; lowuser < 2; ++lowuser) {
UserTestDidRunPostProcess(user, lowuser, vista);
TearDown();
}
}
}
}
} // namespace omaha
| 9,866 |
348 | <filename>docs/data/leg-t1/058/05801232.json
{"nom":"Saint-Benin-d'Azy","circ":"1ère circonscription","dpt":"Nièvre","inscrits":946,"abs":426,"votants":520,"blancs":13,"nuls":1,"exp":506,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":213},{"nuance":"FN","nom":"Mme <NAME>","voix":84},{"nuance":"UDI","nom":"M. <NAME>","voix":52},{"nuance":"FI","nom":"Mme <NAME>","voix":48},{"nuance":"SOC","nom":"M. <NAME>","voix":32},{"nuance":"DVD","nom":"Mme <NAME>","voix":19},{"nuance":"ECO","nom":"Mme <NAME>","voix":16},{"nuance":"COM","nom":"<NAME>","voix":15},{"nuance":"DLF","nom":"M. <NAME>","voix":12},{"nuance":"DIV","nom":"Mme <NAME>","voix":4},{"nuance":"RDG","nom":"M. <NAME>","voix":3},{"nuance":"DVD","nom":"M. <NAME>","voix":2},{"nuance":"EXG","nom":"Mme <NAME>","voix":2},{"nuance":"ECO","nom":"M. <NAME>","voix":2},{"nuance":"DIV","nom":"M. <NAME>","voix":2}]} | 359 |
1,664 | <reponame>liupengpop/ambari<filename>ambari-server/src/main/java/org/apache/ambari/server/controller/ViewInstanceRequest.java<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.server.controller;
import java.util.Map;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.UriInfo;
import org.apache.ambari.server.api.services.views.ViewInstanceService;
import org.apache.ambari.server.controller.internal.ViewInstanceResourceProvider;
import org.apache.ambari.view.ClusterType;
import io.swagger.annotations.ApiModelProperty;
/**
* Request body schema for endpoint {@link ViewInstanceService#createService(String, HttpHeaders, UriInfo, String, String, String)}
*/
public class ViewInstanceRequest implements ApiModel{
private final ViewInstanceRequestInfo viewInstanceRequestInfo;
/**
* @param viewInstanceRequestInfo {@link ViewInstanceRequestInfo}
*/
public ViewInstanceRequest(ViewInstanceRequestInfo viewInstanceRequestInfo) {
this.viewInstanceRequestInfo = viewInstanceRequestInfo;
}
/**
* Returns wrapper class for view instance information
* @return {@link #viewInstanceRequestInfo}
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.VIEW_INSTANCE_INFO)
public ViewInstanceRequestInfo getViewInstanceInfo() {
return viewInstanceRequestInfo;
}
/**
* static class that wraps all view instance information
*/
public static class ViewInstanceRequestInfo {
protected final String viewName;
protected final String version;
protected final String instanceName;
private final String label;
private final String description;
private final boolean visible;
private final String iconPath;
private final String icon64Path;
private final Map<String, String> properties;
private final Map<String, String> instanceData;
private final Integer clusterHandle;
private final ClusterType clusterType;
/**
*
* @param viewName view name
* @param version view version
* @param instanceName instance name
* @param label view label
* @param description view description
* @param visible visibility for view
* @param iconPath icon path
* @param icon64Path icon64 path
* @param properties properties
* @param instanceData instance data
* @param clusterHandle cluster handle
* @param clusterType cluster type (local|remote|none)
*/
public ViewInstanceRequestInfo(String viewName, String version, String instanceName, String label, String description,
boolean visible, String iconPath, String icon64Path, Map<String, String> properties,
Map<String, String> instanceData, Integer clusterHandle, ClusterType clusterType) {
this.viewName = viewName;
this.version = version;
this.instanceName = instanceName;
this.label = label;
this.description = description;
this.visible = visible;
this.iconPath = iconPath;
this.icon64Path = icon64Path;
this.properties = properties;
this.instanceData = instanceData;
this.clusterHandle = clusterHandle;
this.clusterType = clusterType;
}
/**
* Returns view name
* @return view name
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.VIEW_NAME_PROPERTY_ID, hidden = true)
public String getViewName() {
return viewName;
}
/**
* Returns view version
* @return view version
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.VERSION_PROPERTY_ID, hidden = true)
public String getVersion() {
return version;
}
/**
* Returns instance name
* @return instance name
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.INSTANCE_NAME_PROPERTY_ID, hidden = true)
public String getInstanceName() {
return instanceName;
}
/**
* Returns view label
* @return view label
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.LABEL_PROPERTY_ID)
public String getLabel() {
return label;
}
/**
* Returns view description
* @return view description
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.DESCRIPTION_PROPERTY_ID)
public String getDescription() {
return description;
}
/**
* Returns visibility for view
* @return visibility for view
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.VISIBLE_PROPERTY_ID)
public boolean isVisible() {
return visible;
}
/**
* Returns icon path
* @return icon path
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.ICON_PATH_PROPERTY_ID)
public String getIconPath() {
return iconPath;
}
/**
* Returns icon64 patch
* @return icon64 path
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.ICON64_PATH_PROPERTY_ID)
public String getIcon64Path() {
return icon64Path;
}
/**
* Returns all view properties
* @return view properties
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.PROPERTIES_PROPERTY_ID)
public Map<String, String> getProperties() {
return properties;
}
/**
* Returns instance data
* @return instance data
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.INSTANCE_DATA_PROPERTY_ID)
public Map<String, String> getInstanceData() {
return instanceData;
}
/**
* Returns cluster handle
* @return cluster handle
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.CLUSTER_HANDLE_PROPERTY_ID)
public Integer getClusterHandle() {
return clusterHandle;
}
/**
* Returns cluster type {@link ClusterType}
* @return cluster type
*/
@ApiModelProperty(name = ViewInstanceResourceProvider.CLUSTER_TYPE_PROPERTY_ID)
public ClusterType getClusterType() {
return clusterType;
}
}
}
| 2,310 |
2,151 | <filename>third_party/feed/src/src/test/java/com/google/android/libraries/feed/api/scope/FeedStreamScopeTest.java<gh_stars>1000+
// Copyright 2018 The Feed Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.feed.api.scope;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.MockitoAnnotations.initMocks;
import android.app.Activity;
import android.content.Context;
import com.google.android.libraries.feed.api.actionmanager.ActionManager;
import com.google.android.libraries.feed.api.actionparser.ActionParser;
import com.google.android.libraries.feed.api.common.ThreadUtils;
import com.google.android.libraries.feed.api.modelprovider.ModelProviderFactory;
import com.google.android.libraries.feed.api.scope.FeedStreamScope.Builder;
import com.google.android.libraries.feed.api.sessionmanager.SessionManager;
import com.google.android.libraries.feed.api.stream.Stream;
import com.google.android.libraries.feed.common.concurrent.MainThreadRunner;
import com.google.android.libraries.feed.common.testing.FakeClock;
import com.google.android.libraries.feed.common.time.Clock;
import com.google.android.libraries.feed.common.time.TimingUtils;
import com.google.android.libraries.feed.feedprotocoladapter.FeedProtocolAdapter;
import com.google.android.libraries.feed.host.action.ActionApi;
import com.google.android.libraries.feed.host.config.Configuration;
import com.google.android.libraries.feed.host.config.DebugBehavior;
import com.google.android.libraries.feed.host.imageloader.ImageLoaderApi;
import com.google.android.libraries.feed.host.logging.LoggingApi;
import com.google.android.libraries.feed.host.stream.CardConfiguration;
import com.google.android.libraries.feed.host.stream.StreamConfiguration;
import com.google.android.libraries.feed.piet.host.CustomElementProvider;
import com.google.android.libraries.feed.piet.host.HostBindingProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
/** Tests for {@link FeedStreamScope}. */
@RunWith(RobolectricTestRunner.class)
public class FeedStreamScopeTest {
// Mocks for required fields
@Mock private ActionApi actionApi;
@Mock private ImageLoaderApi imageLoaderApi;
@Mock private LoggingApi loggingApi;
// Mocks for optional fields
@Mock private FeedProtocolAdapter protocolAdapter;
@Mock private SessionManager sessionManager;
@Mock private ActionParser actionParser;
@Mock private Stream stream;
@Mock private StreamConfiguration streamConfiguration;
@Mock private CardConfiguration cardConfiguration;
@Mock private ModelProviderFactory modelProviderFactory;
@Mock private CustomElementProvider customElementProvider;
@Mock private ActionManager actionManager;
@Mock private Configuration config;
private Context context;
private MainThreadRunner mainThreadRunner;
private ThreadUtils threadUtils;
private TimingUtils timingUtils;
private Clock clock;
@Before
public void setUp() {
initMocks(this);
context = Robolectric.setupActivity(Activity.class);
mainThreadRunner = new MainThreadRunner();
threadUtils = new ThreadUtils();
timingUtils = new TimingUtils();
clock = new FakeClock();
}
@Test
public void testBasicBuild() {
FeedStreamScope streamScope =
new Builder(
context,
actionApi,
imageLoaderApi,
loggingApi,
protocolAdapter,
sessionManager,
threadUtils,
timingUtils,
mainThreadRunner,
clock,
DebugBehavior.VERBOSE,
streamConfiguration,
cardConfiguration,
actionManager,
config)
.build();
assertThat(streamScope.getStream()).isNotNull();
assertThat(streamScope.getModelProviderFactory()).isNotNull();
}
@Test
public void testComplexBuild() {
FeedStreamScope streamScope =
new Builder(
context,
actionApi,
imageLoaderApi,
loggingApi,
protocolAdapter,
sessionManager,
threadUtils,
timingUtils,
mainThreadRunner,
clock,
DebugBehavior.VERBOSE,
streamConfiguration,
cardConfiguration,
actionManager,
config)
.setActionParser(actionParser)
.setStream(stream)
.setModelProviderFactory(modelProviderFactory)
.setCustomElementProvider(customElementProvider)
.setHostBindingProvider(new HostBindingProvider())
.build();
assertThat(streamScope.getStream()).isEqualTo(stream);
assertThat(streamScope.getModelProviderFactory()).isEqualTo(modelProviderFactory);
}
}
| 2,015 |
511 | #!/usr/bin/python
###########################################################################
#
# Copyright (c) 2017 The Chromium Authors. All rights reserved.
# Copyright 2017 Samsung Electronics 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.
#
###########################################################################
from __future__ import print_function
from operator import itemgetter
import os
import sys
import time
import glob
import optparse
cycleIdDict = dict()
workIdDict = dict()
beginDict = dict()
endDict = dict()
cycleGap = 0
temporalId = 1000
parserDirPath = "scripts"
ftraceLogs = []
class TraceItem:
def __init__(self):
self.taskname = "null"
self.pid = "0"
self.tgid = "0"
self.core = "[000]"
self.flags = "...1"
self.timestamp = "0"
self.function_type = "null"
self.pair_type = "B"
self.message = "0"
def extractTime(self, line):
self.timestamp = line.strip('[]').replace(':', '.')
return self.timestamp
def extractPid(self, line):
self.pid = line.strip(':')
return self.pid
def extractPairType(self, line):
self.pair_type = line.split('|')[0].upper()
return self.pair_type
def extractMsg(self, line):
self.message = (line.split('|'))[1]
return self.message
def composeSchedLine(self):
self.function_type = "sched_switch"
line = "%s-%s %s %s %s: %s: %s" % (
self.taskname, self.pid, self.core, self.flags, self.timestamp,
self.function_type, self.message)
return line
def composeNormalLine(self):
self.function_type = "tracing_mark_write"
line = "%s-%s %s %s %s: %s: %s|%s|%s" % (self.taskname, self.pid,
self.core, self.flags, self.timestamp,
self.function_type, self.pair_type, self.pid, self.message)
return line
def composeLine(self):
if self.pair_type == 'S':
line = self.composeSchedLine()
else:
line = self.composeNormalLine()
return line
def addLineToFtraceLogs(self, line):
ftraceLogs.append(line)
return
def writeFtraceLogs(options):
with open(options.outputFile, "wb") as output:
for line in ftraceLogs:
if (options.verbose == True):
print(line)
output.write(line + "\n")
return True
def translateTinyaraLogs(options):
item = TraceItem()
filename = os.path.join(options.inputFile)
with open(filename, "r") as rawLogs:
for line in rawLogs:
if (line.isspace()):
continue
lineList = line.strip().split(None, 2)
time = item.extractTime(lineList[0])
pid = item.extractPid(lineList[1])
pair_type = item.extractPairType(lineList[2])
msg = item.extractMsg(lineList[2])
translatedLine = item.composeLine()
if (options.verbose == True):
print(translatedLine)
item.addLineToFtraceLogs(translatedLine)
return True
def get_os_cmd(cmdARGS):
fd_popen = subprocess.Popen(cmdARGS.split(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ready = select.select([fd_popen.stdout, fd_popen.stderr],
[], [fd_popen.stdout, fd_popen.stderr])
if fd_popen.stdout in ready[0]:
out = os.read(fd_popen.stdout.fileno(), 4096)
return out
else:
return False
def makeHtml(options):
htmlfile = options.outputFile.replace(options.outputExt, '.html')
if os.name == 'nt':
os.system("%s/ttrace.py --from-text-file=%s -o %s\n"
% (parserDirPath, options.outputFile, htmlfile))
else:
os.system("./%s/ttrace.py --from-text-file=%s -o %s\n"
% (parserDirPath, options.outputFile, htmlfile))
return True
def findAddr(filename, target):
with open(filename, "r") as sysmap:
for line in sysmap:
if line.isspace():
continue
if target in line:
return line.strip().split()[0]
return False
def main():
usage = "Usage: %prog [options]"
desc = "Example: %prog -i logs.txt -o ttrace_dump"
parser = optparse.OptionParser(usage=usage, description=desc)
parser.add_option('-i', '--input', dest='inputFile',
default=None,
metavar='FILENAME',
help="Parsed text file only, Not support dumpped file, "
"[default:%default]")
parser.add_option('-d', '--dump', dest='dump',
default=None,
metavar='MODELNAME',
help="Dump trace buffer and generate html report, "
"[default:%default]")
parser.add_option('-o', '--output', dest='outputFile',
default=None,
metavar='FILENAME',
help="Output file that html report saved, "
"[default:%default]")
parser.add_option('-v', '--verbose', dest='verbose',
action="store_true",
default=False,
help="Generate verbose output, "
"[default:%default]")
options, arg = parser.parse_args()
options.curDir = os.path.dirname(os.path.abspath(sys.argv[0]))
if (options.inputFile == None and options.dump == None):
print("Please specify reading from file or dump")
exit()
if (options.inputFile != None and options.dump != None):
print("Please choose just one option for reading logs")
exit()
if (options.dump != None):
if (options.dump != "artik051" and options.dump != "artik053"):
print("%s is not supported" % (options.dump))
print("T-trace dump supports artik051, artik053")
exit()
os.system("./%s/ttrace_tinyaraDump.py -t %s -o %s\n" \
% (parserDirPath, options.dump, "dump.bin"))
options.inputFile = "%s/dump.trace" % (options.curDir)
if (options.inputFile != None):
# Check inputFile existance,
if not os.access(options.inputFile, os.F_OK | os.R_OK):
print("ERROR: " + "Can not read " + options.inputFile)
return
print("Input file: " + options.inputFile)
options.inputFolder = os.path.split(options.inputFile)[0]
options.inputFilenameExt = os.path.split(options.inputFile)[1]
options.inputFileName = \
os.path.splitext(options.inputFilenameExt)[0]
if (options.outputFile != None):
options.outputFolder = os.path.split(options.outputFile)[0]
options.outputFileName = os.path.split(options.outputFile)[1]
if not os.access(options.outputFolder, os.F_OK | os.W_OK):
os.mkdir(options.outputFolder)
else:
if (options.inputFile != None):
options.outputFolder = options.inputFolder
options.outputFileName = options.inputFileName
else:
options.outputFolder = options.curDir
options.outputFileName = "report"
options.outputExt = ".ftrace"
options.outputFilenameExt = options.outputFileName + options.outputExt
options.outputFile = \
os.path.join(options.outputFolder, options.outputFilenameExt)
print("output file will be saved at %s" % (options.outputFile))
translateTinyaraLogs(options)
writeFtraceLogs(options)
makeHtml(options)
if __name__ == '__main__':
main()
| 3,754 |
852 | #ifndef GaussianZBeamSpotFilter_h
#define GaussianZBeamSpotFilter_h
// Filter to select events with a gaussian Z beam spot shape
// narrower than the original one
// system include files
// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDFilter.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
class GaussianZBeamSpotFilter : public edm::EDFilter {
public:
explicit GaussianZBeamSpotFilter(const edm::ParameterSet&);
~GaussianZBeamSpotFilter() override;
private:
bool filter(edm::Event&, const edm::EventSetup&) override;
// ----------member data ---------------------------
edm::InputTag src_;
double baseSZ_;
double baseZ0_;
double newSZ_;
double newZ0_;
};
#endif
| 300 |
9,717 | <gh_stars>1000+
{
"url": "https://github.com/hubro/tree-sitter-yang",
"rev": "8e9d175982afcefa3dac8ca20d40d1643accd2bd",
"date": "2021-07-29T23:07:25+02:00",
"path": "/nix/store/ark7nssjv3jzy1kw9anlma7li5k9zpnb-tree-sitter-yang",
"sha256": "044q9fikaxnrcrnfwc7cfjnwdg6v7jb6rg7mj556iryv0bkv48s1",
"fetchLFS": false,
"fetchSubmodules": false,
"deepClone": false,
"leaveDotGit": false
}
| 215 |
460 | <gh_stars>100-1000
#define ICE_P(x) (sizeof(int) == sizeof(*(1 ? ((void*)((x) * 0l)) : (int*)1)))
int is_a_constant = ICE_P(4);
int is_not_a_constant = ICE_P(is_a_constant);
| 85 |
352 | #include "Atm_controller.hpp"
const char Atm_controller::relOps[8] = "0=!<>-+";
Atm_controller& Atm_controller::begin( bool initialState /* = false */ ) {
// clang-format off
const static state_t state_table[] PROGMEM = {
/* ON_ENTER ON_LOOP ON_EXIT EVT_ON EVT_OFF EVT_INPUT ELSE */
/* OFF */ ENT_OFF, -1, -1, ON, -1, OFF, -1,
/* ON */ ENT_ON, -1, -1, -1, OFF, ON, -1,
};
// clang-format on
Machine::begin( state_table, ELSE );
last_state = -1;
state( initialState ? ON : OFF );
indicator = -1;
return *this;
}
int Atm_controller::event( int id ) {
switch ( id ) {
case EVT_ON:
return eval_all();
case EVT_OFF:
return !eval_all();
}
return 0;
}
void Atm_controller::action( int id ) {
switch ( id ) {
case ENT_OFF:
connector[last_state == current ? ON_INPUT_FALSE : ON_CHANGE_FALSE].push( state() );
if ( indicator > -1 ) digitalWrite( indicator, !LOW != !indicatorActiveLow );
last_state = current;
return;
case ENT_ON:
if ( last_state != -1 ) connector[( last_state == current ) ? ON_INPUT_TRUE : ON_CHANGE_TRUE].push( state() );
if ( indicator > -1 ) digitalWrite( indicator, !HIGH != !indicatorActiveLow );
last_state = current;
return;
}
}
bool Atm_controller::eval_one( atm_connector& connector ) {
switch ( connector.relOp() ) {
case atm_connector::REL_EQ:
return connector.pull() == connector.event;
case atm_connector::REL_NEQ:
return connector.pull() != connector.event;
case atm_connector::REL_LT:
return connector.pull() < connector.event;
case atm_connector::REL_GT:
return connector.pull() > connector.event;
case atm_connector::REL_LTE:
return connector.pull() <= connector.event;
case atm_connector::REL_GTE:
return connector.pull() >= connector.event;
}
return connector.pull();
}
bool Atm_controller::eval_all() {
bool r = eval_one( operand[0] );
for ( uint8_t i = 1; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
if ( operand[i].mode() ) {
switch ( operand[i].logOp() ) {
case atm_connector::LOG_AND:
r = r && eval_one( operand[i] );
break;
case atm_connector::LOG_OR:
r = r || eval_one( operand[i] );
break;
case atm_connector::LOG_XOR:
r = !r != !eval_one( operand[i] );
break;
}
}
}
return r;
}
Atm_controller& Atm_controller::led( int led, bool activeLow /* = false */ ) {
indicator = led;
indicatorActiveLow = activeLow;
pinMode( indicator, OUTPUT );
return *this;
}
Atm_controller& Atm_controller::onChange( bool status, atm_cb_push_t callback, int idx /* = 0 */ ) {
connector[status ? ON_CHANGE_TRUE : ON_CHANGE_FALSE].set( callback, idx );
return *this;
}
Atm_controller& Atm_controller::onChange( bool status, Machine& machine, int event /* = 0 */ ) {
connector[status ? ON_CHANGE_TRUE : ON_CHANGE_FALSE].set( &machine, event );
return *this;
}
Atm_controller& Atm_controller::onChange( atm_cb_push_t callback, int idx /* = 0 */ ) {
connector[ON_CHANGE_TRUE].set( callback, idx );
connector[ON_CHANGE_FALSE].set( callback, idx );
return *this;
}
Atm_controller& Atm_controller::onChange( Machine& machine, int event /* = 0 */ ) {
connector[ON_CHANGE_TRUE].set( &machine, event );
connector[ON_CHANGE_FALSE].set( &machine, event );
return *this;
}
Atm_controller& Atm_controller::onInput( bool status, atm_cb_push_t callback, int idx /* = 0 */ ) {
connector[status ? ON_INPUT_TRUE : ON_INPUT_FALSE].set( callback, idx );
return *this;
}
Atm_controller& Atm_controller::onInput( bool status, Machine& machine, int event /* = 0 */ ) {
connector[status ? ON_INPUT_TRUE : ON_INPUT_FALSE].set( &machine, event );
return *this;
}
Atm_controller& Atm_controller::IF( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
return OP( atm_connector::LOG_AND, machine, relOp, match );
}
Atm_controller& Atm_controller::IF( atm_cb_pull_t callback, int idx /* = 0 */ ) {
return OP( atm_connector::LOG_AND, callback, idx );
}
Atm_controller& Atm_controller::AND( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
return OP( atm_connector::LOG_AND, machine, relOp, match );
}
Atm_controller& Atm_controller::AND( atm_cb_pull_t callback, int idx /* = 0 */ ) {
return OP( atm_connector::LOG_AND, callback, idx );
}
Atm_controller& Atm_controller::OR( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
return OP( atm_connector::LOG_OR, machine, relOp, match );
}
Atm_controller& Atm_controller::OR( atm_cb_pull_t callback, int idx /* = 0 */ ) {
return OP( atm_connector::LOG_OR, callback, idx );
}
Atm_controller& Atm_controller::XOR( Machine& machine, char relOp /* = '>' */, int match /* = 0 */ ) {
return OP( atm_connector::LOG_XOR, machine, relOp, match );
}
Atm_controller& Atm_controller::XOR( atm_cb_pull_t callback, int idx /* = 0 */ ) {
return OP( atm_connector::LOG_XOR, callback, idx );
}
Atm_controller& Atm_controller::OP( char logOp, Machine& machine, char relOp, int match ) {
for ( uint8_t i = 0; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
if ( operand[i].mode() == atm_connector::MODE_NULL ) { // Pick the first free slot
operand[i].set( &machine, match, logOp, (int)( strchr( relOps, relOp ) - relOps ) );
break;
}
}
return *this;
}
Atm_controller& Atm_controller::OP( char logOp, atm_cb_pull_t callback, int idx ) {
for ( uint8_t i = 0; i < ATM_CONDITION_OPERAND_MAX; i++ ) {
if ( operand[i].mode() == atm_connector::MODE_NULL ) { // Pick the first free slot
operand[i].set( callback, idx );
break;
}
}
return *this;
}
Atm_controller& Atm_controller::trace( Stream& stream ) {
Machine::setTrace( &stream, atm_serial_debug::trace, "CONTROLLER\0EVT_ON\0EVT_OFF\0EVT_INPUT\0ELSE\0OFF\0ON" );
return *this;
}
| 2,461 |
460 | <gh_stars>100-1000
/*
* Copyright 2015-2018 Red Hat, Inc, and individual contributors.
*
* 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.mycorp;
import java.util.Collections;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
* The customized resources should be made available under the "context-root/api" JAX-RS servlet context. The test case
* add this resource selectively.
*/
@ApplicationPath("/api/v1")
public class CustomApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
return Collections.singleton(Resource.class);
}
}
| 336 |
689 | <filename>test/gtest/ucp/test_ucp_tls.cc<gh_stars>100-1000
/**
* Copyright (C) Mellanox Technologies Ltd. 2001-2021. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#include "ucp_test.h"
#include <ucp/core/ucp_context.h>
class test_ucp_tl : public test_ucp_context {
};
UCS_TEST_P(test_ucp_tl, check_ucp_tl, "SELF_NUM_DEVICES?=50")
{
create_entity();
EXPECT_GE((sender().ucph())->num_tls, 50);
}
UCP_INSTANTIATE_TEST_CASE_TLS(test_ucp_tl, self, "self");
| 220 |
335 | <filename>G/Geothermal_adjective.json
{
"word": "Geothermal",
"definitions": [
"Relating to or produced by the internal heat of the earth."
],
"parts-of-speech": "Adjective"
} | 80 |
3,194 | /**
* Copyright (c) 2011-2021, <NAME> 詹波 (<EMAIL>).
*
* 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.jfinal.template.expr.ast;
import com.jfinal.template.TemplateException;
import com.jfinal.template.expr.ast.SharedMethodKit.SharedMethodInfo;
import com.jfinal.template.stat.Location;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
/**
* SharedMethod
*
* 用法:
* engine.addSharedMethod(new StrKit());
* engine.addSharedStaticMethod(MyKit.class);
*
* #if (notBlank(para))
* ....
* #end
*
* 上面代码中的 notBlank 方法来自 StrKit
*/
public class SharedMethod extends Expr {
private SharedMethodKit sharedMethodKit;
private String methodName;
private ExprList exprList;
public SharedMethod(SharedMethodKit sharedMethodKit, String methodName, ExprList exprList, Location location) {
if (MethodKit.isForbiddenMethod(methodName)) {
throw new ParseException("Forbidden method: " + methodName, location);
}
this.sharedMethodKit = sharedMethodKit;
this.methodName = methodName;
this.exprList = exprList;
this.location = location;
}
public Object eval(Scope scope) {
Object[] argValues = exprList.evalExprList(scope);
try {
SharedMethodInfo sharedMethodInfo = sharedMethodKit.getSharedMethodInfo(methodName, argValues);
if (sharedMethodInfo != null) {
return sharedMethodInfo.invoke(argValues);
} else {
// ShareMethod 相当于是固定的静态的方法,不支持 null safe,null safe 只支持具有动态特征的用法
throw new TemplateException(Method.buildMethodNotFoundSignature("Shared method not found: ", methodName, argValues), location);
}
} catch (TemplateException | ParseException e) {
throw e;
} catch (Exception e) {
throw new TemplateException(e.getMessage(), location, e);
}
}
}
| 882 |
3,274 | package com.ql.util.express.test;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import org.junit.Assert;
import org.junit.Test;
public class PreloadExpressTest {
@Test
public void preloadExpress() throws Exception {
ExpressRunner runner = new ExpressRunner();
runner.loadMutilExpress(null,
"function add(int a, int b){return a+b;} \n" +
"function sub(int a, int b){return a-b;}");
DefaultContext<String, Object> context = new DefaultContext<String, Object>();
context.put("m", 1);
context.put("n", 1);
Object object = runner.execute("add(m,n)+sub(2,-2)", context, null, true, false);
System.out.println(object);
Assert.assertTrue((Integer)object==6);
}
}
| 335 |
13,006 | /*******************************************************************************
* Copyright (c) 2015-2019 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.autodiff.loss;
/**
* The LossReduce enum specifies how (or if) the values of a loss function should be reduced to a single value.
* See the javadoc comments on the individual enumeration constants for details.
*
* @author <NAME>
*/
public enum LossReduce {
/**
* No reduction. In most cases, output is the same shape as the predictions/labels.<br>
* Weights (if any) are applied<br>
* Example Input: 2d input array with mean squared error loss.<br>
* Example Output: squaredDifference(predictions,labels), with same shape as input/labels<br>
*/
NONE,
/**
* Weigted sum across all loss values, returning a scalar.<br>
*/
SUM,
/**
* Weighted mean: sum(weights * perOutputLoss) / sum(weights) - gives a single scalar output<br>
* Example: 2d input, mean squared error<br>
* Output: squared_error_per_ex = weights * squaredDifference(predictions,labels)<br>
* output = sum(squared_error_per_ex) / sum(weights)<br>
* <br>
* NOTE: if weights array is not provided, then weights default to 1.0 for all entries - and hence
* MEAN_BY_WEIGHT is equivalent to MEAN_BY_NONZERO_WEIGHT_COUNT
*/
MEAN_BY_WEIGHT,
/**
* Weighted mean: sum(weights * perOutputLoss) / count(weights != 0)<br>
* Example: 2d input, mean squared error loss.<br>
* Output: squared_error_per_ex = weights * squaredDifference(predictions,labels)<br>
* output = sum(squared_error_per_ex) / count(weights != 0)<br>
*
* NOTE: if weights array is not provided, then weights default to scalar 1.0 and hence MEAN_BY_NONZERO_WEIGHT_COUNT
* is equivalent to MEAN_BY_WEIGHT
*/
MEAN_BY_NONZERO_WEIGHT_COUNT
}
| 820 |
1,136 | <filename>utils/__init__.py
from .calculate_score import get_score
from .optimizer import get_optimizer | 32 |
534 | package mekanism.common.upgrade;
import mekanism.common.inventory.slot.BinInventorySlot;
public class BinUpgradeData implements IUpgradeData {
public final boolean redstone;
public final BinInventorySlot binSlot;
public BinUpgradeData(boolean redstone, BinInventorySlot binSlot) {
this.redstone = redstone;
this.binSlot = binSlot;
}
} | 125 |
12,718 | /*===---- mmintrin.h - Implementation of MMX intrinsics on PowerPC ---------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===-----------------------------------------------------------------------===
*/
/* Implemented from the specification included in the Intel C++ Compiler
User Guide and Reference, version 9.0. */
#ifndef NO_WARN_X86_INTRINSICS
/* This header file is to help porting code using Intel intrinsics
explicitly from x86_64 to powerpc64/powerpc64le.
Since PowerPC target doesn't support native 64-bit vector type, we
typedef __m64 to 64-bit unsigned long long in MMX intrinsics, which
works well for _si64 and some _pi32 operations.
For _pi16 and _pi8 operations, it's better to transfer __m64 into
128-bit PowerPC vector first. Power8 introduced direct register
move instructions which helps for more efficient implementation.
It's user's responsibility to determine if the results of such port
are acceptable or further changes are needed. Please note that much
code using Intel intrinsics CAN BE REWRITTEN in more portable and
efficient standard C or GNU C extensions with 64-bit scalar
operations, or 128-bit SSE/Altivec operations, which are more
recommended. */
#error \
"Please read comment above. Use -DNO_WARN_X86_INTRINSICS to disable this error."
#endif
#ifndef _MMINTRIN_H_INCLUDED
#define _MMINTRIN_H_INCLUDED
#if defined(__linux__) && defined(__ppc64__)
#include <altivec.h>
/* The Intel API is flexible enough that we must allow aliasing with other
vector types, and their scalar components. */
typedef __attribute__((__aligned__(8))) unsigned long long __m64;
typedef __attribute__((__aligned__(8))) union {
__m64 as_m64;
char as_char[8];
signed char as_signed_char[8];
short as_short[4];
int as_int[2];
long long as_long_long;
float as_float[2];
double as_double;
} __m64_union;
/* Empty the multimedia state. */
extern __inline void
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_empty(void) {
/* nothing to do on PowerPC. */
}
extern __inline void
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_empty(void) {
/* nothing to do on PowerPC. */
}
/* Convert I to a __m64 object. The integer is zero-extended to 64-bits. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cvtsi32_si64(int __i) {
return (__m64)(unsigned int)__i;
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_from_int(int __i) {
return _mm_cvtsi32_si64(__i);
}
/* Convert the lower 32 bits of the __m64 object into an integer. */
extern __inline int
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cvtsi64_si32(__m64 __i) {
return ((int)__i);
}
extern __inline int
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_to_int(__m64 __i) {
return _mm_cvtsi64_si32(__i);
}
/* Convert I to a __m64 object. */
/* Intel intrinsic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_from_int64(long long __i) {
return (__m64)__i;
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cvtsi64_m64(long long __i) {
return (__m64)__i;
}
/* Microsoft intrinsic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cvtsi64x_si64(long long __i) {
return (__m64)__i;
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_set_pi64x(long long __i) {
return (__m64)__i;
}
/* Convert the __m64 object to a 64bit integer. */
/* Intel intrinsic. */
extern __inline long long
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_to_int64(__m64 __i) {
return (long long)__i;
}
extern __inline long long
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cvtm64_si64(__m64 __i) {
return (long long)__i;
}
/* Microsoft intrinsic. */
extern __inline long long
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cvtsi64_si64x(__m64 __i) {
return (long long)__i;
}
#ifdef _ARCH_PWR8
/* Pack the four 16-bit values from M1 into the lower four 8-bit values of
the result, and the four 16-bit values from M2 into the upper four 8-bit
values of the result, all with signed saturation. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_packs_pi16(__m64 __m1, __m64 __m2) {
__vector signed short vm1;
__vector signed char vresult;
vm1 = (__vector signed short)(__vector unsigned long long)
#ifdef __LITTLE_ENDIAN__
{__m1, __m2};
#else
{__m2, __m1};
#endif
vresult = vec_packs(vm1, vm1);
return (__m64)((__vector long long)vresult)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_packsswb(__m64 __m1, __m64 __m2) {
return _mm_packs_pi16(__m1, __m2);
}
/* Pack the two 32-bit values from M1 in to the lower two 16-bit values of
the result, and the two 32-bit values from M2 into the upper two 16-bit
values of the result, all with signed saturation. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_packs_pi32(__m64 __m1, __m64 __m2) {
__vector signed int vm1;
__vector signed short vresult;
vm1 = (__vector signed int)(__vector unsigned long long)
#ifdef __LITTLE_ENDIAN__
{__m1, __m2};
#else
{__m2, __m1};
#endif
vresult = vec_packs(vm1, vm1);
return (__m64)((__vector long long)vresult)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_packssdw(__m64 __m1, __m64 __m2) {
return _mm_packs_pi32(__m1, __m2);
}
/* Pack the four 16-bit values from M1 into the lower four 8-bit values of
the result, and the four 16-bit values from M2 into the upper four 8-bit
values of the result, all with unsigned saturation. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_packs_pu16(__m64 __m1, __m64 __m2) {
__vector unsigned char r;
__vector signed short vm1 = (__vector signed short)(__vector long long)
#ifdef __LITTLE_ENDIAN__
{__m1, __m2};
#else
{__m2, __m1};
#endif
const __vector signed short __zero = {0};
__vector __bool short __select = vec_cmplt(vm1, __zero);
r = vec_packs((__vector unsigned short)vm1, (__vector unsigned short)vm1);
__vector __bool char packsel = vec_pack(__select, __select);
r = vec_sel(r, (const __vector unsigned char)__zero, packsel);
return (__m64)((__vector long long)r)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_packuswb(__m64 __m1, __m64 __m2) {
return _mm_packs_pu16(__m1, __m2);
}
#endif /* end ARCH_PWR8 */
/* Interleave the four 8-bit values from the high half of M1 with the four
8-bit values from the high half of M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_unpackhi_pi8(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector unsigned char a, b, c;
a = (__vector unsigned char)vec_splats(__m1);
b = (__vector unsigned char)vec_splats(__m2);
c = vec_mergel(a, b);
return (__m64)((__vector long long)c)[1];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_char[0] = m1.as_char[4];
res.as_char[1] = m2.as_char[4];
res.as_char[2] = m1.as_char[5];
res.as_char[3] = m2.as_char[5];
res.as_char[4] = m1.as_char[6];
res.as_char[5] = m2.as_char[6];
res.as_char[6] = m1.as_char[7];
res.as_char[7] = m2.as_char[7];
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_punpckhbw(__m64 __m1, __m64 __m2) {
return _mm_unpackhi_pi8(__m1, __m2);
}
/* Interleave the two 16-bit values from the high half of M1 with the two
16-bit values from the high half of M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_unpackhi_pi16(__m64 __m1, __m64 __m2) {
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_short[0] = m1.as_short[2];
res.as_short[1] = m2.as_short[2];
res.as_short[2] = m1.as_short[3];
res.as_short[3] = m2.as_short[3];
return (__m64)res.as_m64;
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_punpckhwd(__m64 __m1, __m64 __m2) {
return _mm_unpackhi_pi16(__m1, __m2);
}
/* Interleave the 32-bit value from the high half of M1 with the 32-bit
value from the high half of M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_unpackhi_pi32(__m64 __m1, __m64 __m2) {
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_int[0] = m1.as_int[1];
res.as_int[1] = m2.as_int[1];
return (__m64)res.as_m64;
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_punpckhdq(__m64 __m1, __m64 __m2) {
return _mm_unpackhi_pi32(__m1, __m2);
}
/* Interleave the four 8-bit values from the low half of M1 with the four
8-bit values from the low half of M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_unpacklo_pi8(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector unsigned char a, b, c;
a = (__vector unsigned char)vec_splats(__m1);
b = (__vector unsigned char)vec_splats(__m2);
c = vec_mergel(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_char[0] = m1.as_char[0];
res.as_char[1] = m2.as_char[0];
res.as_char[2] = m1.as_char[1];
res.as_char[3] = m2.as_char[1];
res.as_char[4] = m1.as_char[2];
res.as_char[5] = m2.as_char[2];
res.as_char[6] = m1.as_char[3];
res.as_char[7] = m2.as_char[3];
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_punpcklbw(__m64 __m1, __m64 __m2) {
return _mm_unpacklo_pi8(__m1, __m2);
}
/* Interleave the two 16-bit values from the low half of M1 with the two
16-bit values from the low half of M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_unpacklo_pi16(__m64 __m1, __m64 __m2) {
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_short[0] = m1.as_short[0];
res.as_short[1] = m2.as_short[0];
res.as_short[2] = m1.as_short[1];
res.as_short[3] = m2.as_short[1];
return (__m64)res.as_m64;
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_punpcklwd(__m64 __m1, __m64 __m2) {
return _mm_unpacklo_pi16(__m1, __m2);
}
/* Interleave the 32-bit value from the low half of M1 with the 32-bit
value from the low half of M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_unpacklo_pi32(__m64 __m1, __m64 __m2) {
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_int[0] = m1.as_int[0];
res.as_int[1] = m2.as_int[0];
return (__m64)res.as_m64;
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_punpckldq(__m64 __m1, __m64 __m2) {
return _mm_unpacklo_pi32(__m1, __m2);
}
/* Add the 8-bit values in M1 to the 8-bit values in M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_add_pi8(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector signed char a, b, c;
a = (__vector signed char)vec_splats(__m1);
b = (__vector signed char)vec_splats(__m2);
c = vec_add(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_char[0] = m1.as_char[0] + m2.as_char[0];
res.as_char[1] = m1.as_char[1] + m2.as_char[1];
res.as_char[2] = m1.as_char[2] + m2.as_char[2];
res.as_char[3] = m1.as_char[3] + m2.as_char[3];
res.as_char[4] = m1.as_char[4] + m2.as_char[4];
res.as_char[5] = m1.as_char[5] + m2.as_char[5];
res.as_char[6] = m1.as_char[6] + m2.as_char[6];
res.as_char[7] = m1.as_char[7] + m2.as_char[7];
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_paddb(__m64 __m1, __m64 __m2) {
return _mm_add_pi8(__m1, __m2);
}
/* Add the 16-bit values in M1 to the 16-bit values in M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_add_pi16(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector signed short a, b, c;
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
c = vec_add(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_short[0] = m1.as_short[0] + m2.as_short[0];
res.as_short[1] = m1.as_short[1] + m2.as_short[1];
res.as_short[2] = m1.as_short[2] + m2.as_short[2];
res.as_short[3] = m1.as_short[3] + m2.as_short[3];
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_paddw(__m64 __m1, __m64 __m2) {
return _mm_add_pi16(__m1, __m2);
}
/* Add the 32-bit values in M1 to the 32-bit values in M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_add_pi32(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR9
__vector signed int a, b, c;
a = (__vector signed int)vec_splats(__m1);
b = (__vector signed int)vec_splats(__m2);
c = vec_add(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_int[0] = m1.as_int[0] + m2.as_int[0];
res.as_int[1] = m1.as_int[1] + m2.as_int[1];
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_paddd(__m64 __m1, __m64 __m2) {
return _mm_add_pi32(__m1, __m2);
}
/* Subtract the 8-bit values in M2 from the 8-bit values in M1. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sub_pi8(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector signed char a, b, c;
a = (__vector signed char)vec_splats(__m1);
b = (__vector signed char)vec_splats(__m2);
c = vec_sub(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_char[0] = m1.as_char[0] - m2.as_char[0];
res.as_char[1] = m1.as_char[1] - m2.as_char[1];
res.as_char[2] = m1.as_char[2] - m2.as_char[2];
res.as_char[3] = m1.as_char[3] - m2.as_char[3];
res.as_char[4] = m1.as_char[4] - m2.as_char[4];
res.as_char[5] = m1.as_char[5] - m2.as_char[5];
res.as_char[6] = m1.as_char[6] - m2.as_char[6];
res.as_char[7] = m1.as_char[7] - m2.as_char[7];
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psubb(__m64 __m1, __m64 __m2) {
return _mm_sub_pi8(__m1, __m2);
}
/* Subtract the 16-bit values in M2 from the 16-bit values in M1. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sub_pi16(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector signed short a, b, c;
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
c = vec_sub(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_short[0] = m1.as_short[0] - m2.as_short[0];
res.as_short[1] = m1.as_short[1] - m2.as_short[1];
res.as_short[2] = m1.as_short[2] - m2.as_short[2];
res.as_short[3] = m1.as_short[3] - m2.as_short[3];
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psubw(__m64 __m1, __m64 __m2) {
return _mm_sub_pi16(__m1, __m2);
}
/* Subtract the 32-bit values in M2 from the 32-bit values in M1. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sub_pi32(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR9
__vector signed int a, b, c;
a = (__vector signed int)vec_splats(__m1);
b = (__vector signed int)vec_splats(__m2);
c = vec_sub(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_int[0] = m1.as_int[0] - m2.as_int[0];
res.as_int[1] = m1.as_int[1] - m2.as_int[1];
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psubd(__m64 __m1, __m64 __m2) {
return _mm_sub_pi32(__m1, __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_add_si64(__m64 __m1, __m64 __m2) {
return (__m1 + __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sub_si64(__m64 __m1, __m64 __m2) {
return (__m1 - __m2);
}
/* Shift the 64-bit value in M left by COUNT. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sll_si64(__m64 __m, __m64 __count) {
return (__m << __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psllq(__m64 __m, __m64 __count) {
return _mm_sll_si64(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_slli_si64(__m64 __m, const int __count) {
return (__m << __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psllqi(__m64 __m, const int __count) {
return _mm_slli_si64(__m, __count);
}
/* Shift the 64-bit value in M left by COUNT; shift in zeros. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_srl_si64(__m64 __m, __m64 __count) {
return (__m >> __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psrlq(__m64 __m, __m64 __count) {
return _mm_srl_si64(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_srli_si64(__m64 __m, const int __count) {
return (__m >> __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psrlqi(__m64 __m, const int __count) {
return _mm_srli_si64(__m, __count);
}
/* Bit-wise AND the 64-bit values in M1 and M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_and_si64(__m64 __m1, __m64 __m2) {
return (__m1 & __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pand(__m64 __m1, __m64 __m2) {
return _mm_and_si64(__m1, __m2);
}
/* Bit-wise complement the 64-bit value in M1 and bit-wise AND it with the
64-bit value in M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_andnot_si64(__m64 __m1, __m64 __m2) {
return (~__m1 & __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pandn(__m64 __m1, __m64 __m2) {
return _mm_andnot_si64(__m1, __m2);
}
/* Bit-wise inclusive OR the 64-bit values in M1 and M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_or_si64(__m64 __m1, __m64 __m2) {
return (__m1 | __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_por(__m64 __m1, __m64 __m2) {
return _mm_or_si64(__m1, __m2);
}
/* Bit-wise exclusive OR the 64-bit values in M1 and M2. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_xor_si64(__m64 __m1, __m64 __m2) {
return (__m1 ^ __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pxor(__m64 __m1, __m64 __m2) {
return _mm_xor_si64(__m1, __m2);
}
/* Creates a 64-bit zero. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_setzero_si64(void) {
return (__m64)0;
}
/* Compare eight 8-bit values. The result of the comparison is 0xFF if the
test is true and zero if false. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cmpeq_pi8(__m64 __m1, __m64 __m2) {
#if defined(_ARCH_PWR6) && defined(__powerpc64__)
__m64 res;
__asm__("cmpb %0,%1,%2;\n" : "=r"(res) : "r"(__m1), "r"(__m2) :);
return (res);
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_char[0] = (m1.as_char[0] == m2.as_char[0]) ? -1 : 0;
res.as_char[1] = (m1.as_char[1] == m2.as_char[1]) ? -1 : 0;
res.as_char[2] = (m1.as_char[2] == m2.as_char[2]) ? -1 : 0;
res.as_char[3] = (m1.as_char[3] == m2.as_char[3]) ? -1 : 0;
res.as_char[4] = (m1.as_char[4] == m2.as_char[4]) ? -1 : 0;
res.as_char[5] = (m1.as_char[5] == m2.as_char[5]) ? -1 : 0;
res.as_char[6] = (m1.as_char[6] == m2.as_char[6]) ? -1 : 0;
res.as_char[7] = (m1.as_char[7] == m2.as_char[7]) ? -1 : 0;
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pcmpeqb(__m64 __m1, __m64 __m2) {
return _mm_cmpeq_pi8(__m1, __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cmpgt_pi8(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector signed char a, b, c;
a = (__vector signed char)vec_splats(__m1);
b = (__vector signed char)vec_splats(__m2);
c = (__vector signed char)vec_cmpgt(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_char[0] = (m1.as_char[0] > m2.as_char[0]) ? -1 : 0;
res.as_char[1] = (m1.as_char[1] > m2.as_char[1]) ? -1 : 0;
res.as_char[2] = (m1.as_char[2] > m2.as_char[2]) ? -1 : 0;
res.as_char[3] = (m1.as_char[3] > m2.as_char[3]) ? -1 : 0;
res.as_char[4] = (m1.as_char[4] > m2.as_char[4]) ? -1 : 0;
res.as_char[5] = (m1.as_char[5] > m2.as_char[5]) ? -1 : 0;
res.as_char[6] = (m1.as_char[6] > m2.as_char[6]) ? -1 : 0;
res.as_char[7] = (m1.as_char[7] > m2.as_char[7]) ? -1 : 0;
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pcmpgtb(__m64 __m1, __m64 __m2) {
return _mm_cmpgt_pi8(__m1, __m2);
}
/* Compare four 16-bit values. The result of the comparison is 0xFFFF if
the test is true and zero if false. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cmpeq_pi16(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector signed short a, b, c;
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
c = (__vector signed short)vec_cmpeq(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_short[0] = (m1.as_short[0] == m2.as_short[0]) ? -1 : 0;
res.as_short[1] = (m1.as_short[1] == m2.as_short[1]) ? -1 : 0;
res.as_short[2] = (m1.as_short[2] == m2.as_short[2]) ? -1 : 0;
res.as_short[3] = (m1.as_short[3] == m2.as_short[3]) ? -1 : 0;
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pcmpeqw(__m64 __m1, __m64 __m2) {
return _mm_cmpeq_pi16(__m1, __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cmpgt_pi16(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR8
__vector signed short a, b, c;
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
c = (__vector signed short)vec_cmpgt(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_short[0] = (m1.as_short[0] > m2.as_short[0]) ? -1 : 0;
res.as_short[1] = (m1.as_short[1] > m2.as_short[1]) ? -1 : 0;
res.as_short[2] = (m1.as_short[2] > m2.as_short[2]) ? -1 : 0;
res.as_short[3] = (m1.as_short[3] > m2.as_short[3]) ? -1 : 0;
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pcmpgtw(__m64 __m1, __m64 __m2) {
return _mm_cmpgt_pi16(__m1, __m2);
}
/* Compare two 32-bit values. The result of the comparison is 0xFFFFFFFF if
the test is true and zero if false. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cmpeq_pi32(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR9
__vector signed int a, b, c;
a = (__vector signed int)vec_splats(__m1);
b = (__vector signed int)vec_splats(__m2);
c = (__vector signed int)vec_cmpeq(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_int[0] = (m1.as_int[0] == m2.as_int[0]) ? -1 : 0;
res.as_int[1] = (m1.as_int[1] == m2.as_int[1]) ? -1 : 0;
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pcmpeqd(__m64 __m1, __m64 __m2) {
return _mm_cmpeq_pi32(__m1, __m2);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_cmpgt_pi32(__m64 __m1, __m64 __m2) {
#if _ARCH_PWR9
__vector signed int a, b, c;
a = (__vector signed int)vec_splats(__m1);
b = (__vector signed int)vec_splats(__m2);
c = (__vector signed int)vec_cmpgt(a, b);
return (__m64)((__vector long long)c)[0];
#else
__m64_union m1, m2, res;
m1.as_m64 = __m1;
m2.as_m64 = __m2;
res.as_int[0] = (m1.as_int[0] > m2.as_int[0]) ? -1 : 0;
res.as_int[1] = (m1.as_int[1] > m2.as_int[1]) ? -1 : 0;
return (__m64)res.as_m64;
#endif
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pcmpgtd(__m64 __m1, __m64 __m2) {
return _mm_cmpgt_pi32(__m1, __m2);
}
#if _ARCH_PWR8
/* Add the 8-bit values in M1 to the 8-bit values in M2 using signed
saturated arithmetic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_adds_pi8(__m64 __m1, __m64 __m2) {
__vector signed char a, b, c;
a = (__vector signed char)vec_splats(__m1);
b = (__vector signed char)vec_splats(__m2);
c = vec_adds(a, b);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_paddsb(__m64 __m1, __m64 __m2) {
return _mm_adds_pi8(__m1, __m2);
}
/* Add the 16-bit values in M1 to the 16-bit values in M2 using signed
saturated arithmetic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_adds_pi16(__m64 __m1, __m64 __m2) {
__vector signed short a, b, c;
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
c = vec_adds(a, b);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_paddsw(__m64 __m1, __m64 __m2) {
return _mm_adds_pi16(__m1, __m2);
}
/* Add the 8-bit values in M1 to the 8-bit values in M2 using unsigned
saturated arithmetic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_adds_pu8(__m64 __m1, __m64 __m2) {
__vector unsigned char a, b, c;
a = (__vector unsigned char)vec_splats(__m1);
b = (__vector unsigned char)vec_splats(__m2);
c = vec_adds(a, b);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_paddusb(__m64 __m1, __m64 __m2) {
return _mm_adds_pu8(__m1, __m2);
}
/* Add the 16-bit values in M1 to the 16-bit values in M2 using unsigned
saturated arithmetic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_adds_pu16(__m64 __m1, __m64 __m2) {
__vector unsigned short a, b, c;
a = (__vector unsigned short)vec_splats(__m1);
b = (__vector unsigned short)vec_splats(__m2);
c = vec_adds(a, b);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_paddusw(__m64 __m1, __m64 __m2) {
return _mm_adds_pu16(__m1, __m2);
}
/* Subtract the 8-bit values in M2 from the 8-bit values in M1 using signed
saturating arithmetic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_subs_pi8(__m64 __m1, __m64 __m2) {
__vector signed char a, b, c;
a = (__vector signed char)vec_splats(__m1);
b = (__vector signed char)vec_splats(__m2);
c = vec_subs(a, b);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psubsb(__m64 __m1, __m64 __m2) {
return _mm_subs_pi8(__m1, __m2);
}
/* Subtract the 16-bit values in M2 from the 16-bit values in M1 using
signed saturating arithmetic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_subs_pi16(__m64 __m1, __m64 __m2) {
__vector signed short a, b, c;
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
c = vec_subs(a, b);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psubsw(__m64 __m1, __m64 __m2) {
return _mm_subs_pi16(__m1, __m2);
}
/* Subtract the 8-bit values in M2 from the 8-bit values in M1 using
unsigned saturating arithmetic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_subs_pu8(__m64 __m1, __m64 __m2) {
__vector unsigned char a, b, c;
a = (__vector unsigned char)vec_splats(__m1);
b = (__vector unsigned char)vec_splats(__m2);
c = vec_subs(a, b);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psubusb(__m64 __m1, __m64 __m2) {
return _mm_subs_pu8(__m1, __m2);
}
/* Subtract the 16-bit values in M2 from the 16-bit values in M1 using
unsigned saturating arithmetic. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_subs_pu16(__m64 __m1, __m64 __m2) {
__vector unsigned short a, b, c;
a = (__vector unsigned short)vec_splats(__m1);
b = (__vector unsigned short)vec_splats(__m2);
c = vec_subs(a, b);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psubusw(__m64 __m1, __m64 __m2) {
return _mm_subs_pu16(__m1, __m2);
}
/* Multiply four 16-bit values in M1 by four 16-bit values in M2 producing
four 32-bit intermediate results, which are then summed by pairs to
produce two 32-bit results. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_madd_pi16(__m64 __m1, __m64 __m2) {
__vector signed short a, b;
__vector signed int c;
__vector signed int zero = {0, 0, 0, 0};
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
c = vec_vmsumshm(a, b, zero);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pmaddwd(__m64 __m1, __m64 __m2) {
return _mm_madd_pi16(__m1, __m2);
}
/* Multiply four signed 16-bit values in M1 by four signed 16-bit values in
M2 and produce the high 16 bits of the 32-bit results. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_mulhi_pi16(__m64 __m1, __m64 __m2) {
__vector signed short a, b;
__vector signed short c;
__vector signed int w0, w1;
__vector unsigned char xform1 = {
#ifdef __LITTLE_ENDIAN__
0x02, 0x03, 0x12, 0x13, 0x06, 0x07, 0x16, 0x17, 0x0A,
0x0B, 0x1A, 0x1B, 0x0E, 0x0F, 0x1E, 0x1F
#else
0x00, 0x01, 0x10, 0x11, 0x04, 0x05, 0x14, 0x15, 0x00,
0x01, 0x10, 0x11, 0x04, 0x05, 0x14, 0x15
#endif
};
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
w0 = vec_vmulesh(a, b);
w1 = vec_vmulosh(a, b);
c = (__vector signed short)vec_perm(w0, w1, xform1);
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pmulhw(__m64 __m1, __m64 __m2) {
return _mm_mulhi_pi16(__m1, __m2);
}
/* Multiply four 16-bit values in M1 by four 16-bit values in M2 and produce
the low 16 bits of the results. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_mullo_pi16(__m64 __m1, __m64 __m2) {
__vector signed short a, b, c;
a = (__vector signed short)vec_splats(__m1);
b = (__vector signed short)vec_splats(__m2);
c = a * b;
return (__m64)((__vector long long)c)[0];
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pmullw(__m64 __m1, __m64 __m2) {
return _mm_mullo_pi16(__m1, __m2);
}
/* Shift four 16-bit values in M left by COUNT. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sll_pi16(__m64 __m, __m64 __count) {
__vector signed short m, r;
__vector unsigned short c;
if (__count <= 15) {
m = (__vector signed short)vec_splats(__m);
c = (__vector unsigned short)vec_splats((unsigned short)__count);
r = vec_sl(m, (__vector unsigned short)c);
return (__m64)((__vector long long)r)[0];
} else
return (0);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psllw(__m64 __m, __m64 __count) {
return _mm_sll_pi16(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_slli_pi16(__m64 __m, int __count) {
/* Promote int to long then invoke mm_sll_pi16. */
return _mm_sll_pi16(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psllwi(__m64 __m, int __count) {
return _mm_slli_pi16(__m, __count);
}
/* Shift two 32-bit values in M left by COUNT. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sll_pi32(__m64 __m, __m64 __count) {
__m64_union m, res;
m.as_m64 = __m;
res.as_int[0] = m.as_int[0] << __count;
res.as_int[1] = m.as_int[1] << __count;
return (res.as_m64);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pslld(__m64 __m, __m64 __count) {
return _mm_sll_pi32(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_slli_pi32(__m64 __m, int __count) {
/* Promote int to long then invoke mm_sll_pi32. */
return _mm_sll_pi32(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_pslldi(__m64 __m, int __count) {
return _mm_slli_pi32(__m, __count);
}
/* Shift four 16-bit values in M right by COUNT; shift in the sign bit. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sra_pi16(__m64 __m, __m64 __count) {
__vector signed short m, r;
__vector unsigned short c;
if (__count <= 15) {
m = (__vector signed short)vec_splats(__m);
c = (__vector unsigned short)vec_splats((unsigned short)__count);
r = vec_sra(m, (__vector unsigned short)c);
return (__m64)((__vector long long)r)[0];
} else
return (0);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psraw(__m64 __m, __m64 __count) {
return _mm_sra_pi16(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_srai_pi16(__m64 __m, int __count) {
/* Promote int to long then invoke mm_sra_pi32. */
return _mm_sra_pi16(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psrawi(__m64 __m, int __count) {
return _mm_srai_pi16(__m, __count);
}
/* Shift two 32-bit values in M right by COUNT; shift in the sign bit. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_sra_pi32(__m64 __m, __m64 __count) {
__m64_union m, res;
m.as_m64 = __m;
res.as_int[0] = m.as_int[0] >> __count;
res.as_int[1] = m.as_int[1] >> __count;
return (res.as_m64);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psrad(__m64 __m, __m64 __count) {
return _mm_sra_pi32(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_srai_pi32(__m64 __m, int __count) {
/* Promote int to long then invoke mm_sra_pi32. */
return _mm_sra_pi32(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psradi(__m64 __m, int __count) {
return _mm_srai_pi32(__m, __count);
}
/* Shift four 16-bit values in M right by COUNT; shift in zeros. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_srl_pi16(__m64 __m, __m64 __count) {
__vector unsigned short m, r;
__vector unsigned short c;
if (__count <= 15) {
m = (__vector unsigned short)vec_splats(__m);
c = (__vector unsigned short)vec_splats((unsigned short)__count);
r = vec_sr(m, (__vector unsigned short)c);
return (__m64)((__vector long long)r)[0];
} else
return (0);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psrlw(__m64 __m, __m64 __count) {
return _mm_srl_pi16(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_srli_pi16(__m64 __m, int __count) {
/* Promote int to long then invoke mm_sra_pi32. */
return _mm_srl_pi16(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psrlwi(__m64 __m, int __count) {
return _mm_srli_pi16(__m, __count);
}
/* Shift two 32-bit values in M right by COUNT; shift in zeros. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_srl_pi32(__m64 __m, __m64 __count) {
__m64_union m, res;
m.as_m64 = __m;
res.as_int[0] = (unsigned int)m.as_int[0] >> __count;
res.as_int[1] = (unsigned int)m.as_int[1] >> __count;
return (res.as_m64);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psrld(__m64 __m, __m64 __count) {
return _mm_srl_pi32(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_srli_pi32(__m64 __m, int __count) {
/* Promote int to long then invoke mm_srl_pi32. */
return _mm_srl_pi32(__m, __count);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_m_psrldi(__m64 __m, int __count) {
return _mm_srli_pi32(__m, __count);
}
#endif /* _ARCH_PWR8 */
/* Creates a vector of two 32-bit values; I0 is least significant. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_set_pi32(int __i1, int __i0) {
__m64_union res;
res.as_int[0] = __i0;
res.as_int[1] = __i1;
return (res.as_m64);
}
/* Creates a vector of four 16-bit values; W0 is least significant. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_set_pi16(short __w3, short __w2, short __w1, short __w0) {
__m64_union res;
res.as_short[0] = __w0;
res.as_short[1] = __w1;
res.as_short[2] = __w2;
res.as_short[3] = __w3;
return (res.as_m64);
}
/* Creates a vector of eight 8-bit values; B0 is least significant. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_set_pi8(char __b7, char __b6, char __b5, char __b4, char __b3,
char __b2, char __b1, char __b0) {
__m64_union res;
res.as_char[0] = __b0;
res.as_char[1] = __b1;
res.as_char[2] = __b2;
res.as_char[3] = __b3;
res.as_char[4] = __b4;
res.as_char[5] = __b5;
res.as_char[6] = __b6;
res.as_char[7] = __b7;
return (res.as_m64);
}
/* Similar, but with the arguments in reverse order. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_setr_pi32(int __i0, int __i1) {
__m64_union res;
res.as_int[0] = __i0;
res.as_int[1] = __i1;
return (res.as_m64);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_setr_pi16(short __w0, short __w1, short __w2, short __w3) {
return _mm_set_pi16(__w3, __w2, __w1, __w0);
}
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_setr_pi8(char __b0, char __b1, char __b2, char __b3, char __b4,
char __b5, char __b6, char __b7) {
return _mm_set_pi8(__b7, __b6, __b5, __b4, __b3, __b2, __b1, __b0);
}
/* Creates a vector of two 32-bit values, both elements containing I. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_set1_pi32(int __i) {
__m64_union res;
res.as_int[0] = __i;
res.as_int[1] = __i;
return (res.as_m64);
}
/* Creates a vector of four 16-bit values, all elements containing W. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_set1_pi16(short __w) {
#if _ARCH_PWR9
__vector signed short w;
w = (__vector signed short)vec_splats(__w);
return (__m64)((__vector long long)w)[0];
#else
__m64_union res;
res.as_short[0] = __w;
res.as_short[1] = __w;
res.as_short[2] = __w;
res.as_short[3] = __w;
return (res.as_m64);
#endif
}
/* Creates a vector of eight 8-bit values, all elements containing B. */
extern __inline __m64
__attribute__((__gnu_inline__, __always_inline__, __artificial__))
_mm_set1_pi8(signed char __b) {
#if _ARCH_PWR8
__vector signed char b;
b = (__vector signed char)vec_splats(__b);
return (__m64)((__vector long long)b)[0];
#else
__m64_union res;
res.as_char[0] = __b;
res.as_char[1] = __b;
res.as_char[2] = __b;
res.as_char[3] = __b;
res.as_char[4] = __b;
res.as_char[5] = __b;
res.as_char[6] = __b;
res.as_char[7] = __b;
return (res.as_m64);
#endif
}
#else
#include_next <mmintrin.h>
#endif /* defined(__linux__) && defined(__ppc64__) */
#endif /* _MMINTRIN_H_INCLUDED */
| 19,653 |
675 | <reponame>blico/intellij
/*
* Copyright 2017 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.idea.blaze.base.projectview.section.sections;
import com.google.idea.blaze.base.projectview.parser.ParseContext;
import com.google.idea.blaze.base.projectview.parser.ProjectViewParser;
import com.google.idea.blaze.base.projectview.section.ScalarSection;
import com.google.idea.blaze.base.projectview.section.ScalarSectionParser;
import com.google.idea.blaze.base.projectview.section.SectionKey;
import com.google.idea.blaze.base.projectview.section.SectionParser;
import javax.annotation.Nullable;
/** Allows the user to tune the maximum number of targets in each blaze build shard. */
public class TargetShardSizeSection {
public static final SectionKey<Integer, ScalarSection<Integer>> KEY =
SectionKey.of("target_shard_size");
public static final SectionParser PARSER = new TargetShardSizeSectionParser();
private static class TargetShardSizeSectionParser extends ScalarSectionParser<Integer> {
TargetShardSizeSectionParser() {
super(KEY, ':');
}
@Nullable
@Override
protected Integer parseItem(ProjectViewParser parser, ParseContext parseContext, String rest) {
try {
return Integer.parseInt(rest);
} catch (NumberFormatException e) {
parseContext.addError(
String.format("Invalid shard size '%s': Shard size must be an integer", rest));
return null;
}
}
@Override
protected void printItem(StringBuilder sb, Integer value) {
sb.append(value.toString());
}
@Override
public ItemType getItemType() {
return ItemType.Other;
}
@Override
public String quickDocs() {
return "Sets the maximum number of targets per shard, when sharding build invocations during "
+ "sync. Only relevant if 'shard_sync: true' is also set";
}
}
}
| 788 |
22,426 | <gh_stars>1000+
from .hashtable import *
from .separate_chaining_hashtable import *
from .word_pattern import *
from .is_isomorphic import *
from .is_anagram import *
from .longest_palindromic_subsequence import *
| 69 |
3,252 | # Copyright (c) Facebook, Inc. and its affiliates.
__all__ = ["BaseTrainer"]
from .base_trainer import BaseTrainer
| 36 |
2,151 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GPU_IPC_SERVICE_GPU_MEMORY_BUFFER_FACTORY_IO_SURFACE_H_
#define GPU_IPC_SERVICE_GPU_MEMORY_BUFFER_FACTORY_IO_SURFACE_H_
#include <utility>
#include <IOSurface/IOSurface.h>
#include "base/containers/hash_tables.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/lock.h"
#include "gpu/command_buffer/service/image_factory.h"
#include "gpu/ipc/service/gpu_ipc_service_export.h"
#include "gpu/ipc/service/gpu_memory_buffer_factory.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gfx/mac/io_surface.h"
namespace gl {
class GLImage;
}
namespace gpu {
class GPU_IPC_SERVICE_EXPORT GpuMemoryBufferFactoryIOSurface
: public GpuMemoryBufferFactory,
public ImageFactory {
public:
GpuMemoryBufferFactoryIOSurface();
~GpuMemoryBufferFactoryIOSurface() override;
// Overridden from GpuMemoryBufferFactory:
gfx::GpuMemoryBufferHandle CreateGpuMemoryBuffer(
gfx::GpuMemoryBufferId id,
const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
int client_id,
SurfaceHandle surface_handle) override;
void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
int client_id) override;
ImageFactory* AsImageFactory() override;
// Overridden from ImageFactory:
scoped_refptr<gl::GLImage> CreateImageForGpuMemoryBuffer(
const gfx::GpuMemoryBufferHandle& handle,
const gfx::Size& size,
gfx::BufferFormat format,
unsigned internalformat,
int client_id,
SurfaceHandle surface_handle) override;
scoped_refptr<gl::GLImage> CreateAnonymousImage(const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
unsigned internalformat,
bool* is_cleared) override;
unsigned RequiredTextureType() override;
bool SupportsFormatRGB() override;
private:
typedef std::pair<gfx::IOSurfaceId, int> IOSurfaceMapKey;
typedef base::hash_map<IOSurfaceMapKey, base::ScopedCFTypeRef<IOSurfaceRef>>
IOSurfaceMap;
// TODO(reveman): Remove |io_surfaces_| and allow IOSurface backed GMBs to be
// used with any GPU process by passing a mach_port to CreateImageCHROMIUM.
IOSurfaceMap io_surfaces_;
base::Lock io_surfaces_lock_;
// Assign unique ids to anonymous images to differentiate in memory dumps.
int next_anonymous_image_id_ = 1;
DISALLOW_COPY_AND_ASSIGN(GpuMemoryBufferFactoryIOSurface);
};
} // namespace gpu
#endif // GPU_IPC_SERVICE_GPU_MEMORY_BUFFER_FACTORY_IO_SURFACE_H_
| 1,220 |
416 | <filename>contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/GameplayKit.framework/Versions/A/Headers/GKGoal.h<gh_stars>100-1000
//
// GKGoal.h
// GameLogic
//
// Copyright © 2015 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "GameplayKitBase.h"
NS_ASSUME_NONNULL_BEGIN
@class GKAgent, GKPath, GKObstacle;
/**
* Defines a spatial directive.
* The various goals cause force to be applied to agents to try to achieve said goal.
*/
GK_BASE_AVAILABILITY @interface GKGoal : NSObject <NSCopying>
/**
* Creates a goal to move toward the agent
* @param agent the agent to seek
*/
+ (instancetype)goalToSeekAgent:(GKAgent *)agent;
/**
* Creates a goal to move away from the agent
* @param agent the agent to flee from
*/
+ (instancetype)goalToFleeAgent:(GKAgent *)agent;
/**
* Creates a goal to avoid colliding with a group of agents without taking into account those agents' momentum
* @param maxPredictionTime how far ahead in the future, in seconds, should we look for potential collisions
*/
+ (instancetype)goalToAvoidObstacles:(NSArray<GKObstacle *> *)obstacles maxPredictionTime:(NSTimeInterval)maxPredictionTime;
/**
* Creates a goal to avoid colliding with a group of agents taking into account those agent's momentum
* @param timeBeforeCollisionToAvoid how far ahead in the future, in seconds, should we look for potential collisions
*/
+ (instancetype)goalToAvoidAgents:(NSArray<GKAgent *> *)agents maxPredictionTime:(NSTimeInterval)maxPredictionTime;
/**
* Creates a goal that tries to repel this agent away from the other agents and attempts to prevent overlap
* @param maxDistance the distance between agents before repelling happens
* @param maxAngle the angle, in radians, between this agent's foward and the vector toward the other agent before the repelling happens
*/
+ (instancetype)goalToSeparateFromAgents:(NSArray<GKAgent *> *)agents maxDistance:(float)maxDistance maxAngle:(float)maxAngle;
/**
* Creates a goal to align this agent's orientation with the average orientation of the group of agents.
* @param maxDistance the distance between agents before alignment happens
* @param maxAngle the angle, in radians, between this agent's foward and the vector toward the other agent before alignment happens
*/
+ (instancetype)goalToAlignWithAgents:(NSArray<GKAgent *> *)agents maxDistance:(float)maxDistance maxAngle:(float)maxAngle;
/**
* Creates a goal to seek the average position of the group of agents.
* @param maxDistance the distance between agents before cohesion happens
* @param maxAngle the angle between this agent's foward and the vector toward the other agent before cohesion happens
*/
+ (instancetype)goalToCohereWithAgents:(NSArray<GKAgent *> *)agents maxDistance:(float)maxDistance maxAngle:(float)maxAngle;
/**
* Creates a goal that attempts to change our momentum to reach the target speed
* @param targetSpeed the target speed
*/
+ (instancetype)goalToReachTargetSpeed:(float)targetSpeed;
/**
* Creates a goal that will make the agent appear to wander, aimlessly moving forward and turning randomly
* @param deltaTime how much time, in seconds, has elapsed since the last simulation step
* @param speed the speed at which to wander
*/
+ (instancetype)goalToWander:(float)speed;
/**
* Creates a goal that will attempt to intercept another target agent taking into account that agent's momentum
* @param target agent to intercept
* @param maxPredictionTime how far ahead in the future, in seconds, should we look for potential intercepts
*/
+ (instancetype)goalToInterceptAgent:(GKAgent *)target maxPredictionTime:(NSTimeInterval)maxPredictionTime;
/**
* Creates a goal that will attempt to follow the given path
* @param path the path to follow
* @param maxPredictionTime how far ahead in the future, in seconds, should we look for potential intercepts
* @param forward direction to follow the path. forward = NO is reverse
*/
+ (instancetype)goalToFollowPath:(GKPath *)path maxPredictionTime:(NSTimeInterval)maxPredictionTime forward:(BOOL)forward;
/**
* Creates a goal that will attempt to stay on the given path
* @param path the path to follow
* @param maxPredictionTime how far ahead in the future, in seconds, should we look for potential intercepts
*/
+ (instancetype)goalToStayOnPath:(GKPath *)path maxPredictionTime:(NSTimeInterval)maxPredictionTime;
@end
NS_ASSUME_NONNULL_END
| 1,247 |
5,169 | <gh_stars>1000+
{
"name": "Log4swift",
"version": "0.9.0",
"summary": "A looging library written in swift.",
"description": " Log4swift is a logging library similar in philosophy to log4j.\n It is meant to be :\n\n * very simple to use for simple cases\n * extensively configurable for less simple cases\n * taking advantage of the swift 2 language\n\n It is still a work in progress : fully functinnal, but missing the ability to read configuration from a file.\n",
"homepage": "http://github.com/jduquennoy/Log4swift",
"license": {
"type": "LGPL v3",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"platforms": {
"osx": "10.10"
},
"source": {
"git": "https://github.com/jduquennoy/Log4swift.git",
"tag": "versions/0.9.0"
},
"source_files": [
"Log4swift",
"Log4swift/**/*.{swift}"
],
"exclude_files": "Classes/Exclude",
"public_header_files": "Log4swift/log4swift.h"
}
| 480 |
892 | <filename>advisories/unreviewed/2022/04/GHSA-9fvr-m6jg-h4hx/GHSA-9fvr-m6jg-h4hx.json<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-9fvr-m6jg-h4hx",
"modified": "2022-04-22T00:00:58Z",
"published": "2022-04-15T00:00:42Z",
"aliases": [
"CVE-2022-22182"
],
"details": "A Cross-site Scripting (XSS) vulnerability in Juniper Networks Junos OS J-Web allows an attacker to construct a URL that when visited by another user enables the attacker to execute commands with the target's permissions, including an administrator. This issue affects: Juniper Networks Junos OS 12.3 versions prior to 12.3R12-S19; 15.1 versions prior to 15.1R7-S10; 18.3 versions prior to 18.3R3-S5; 18.4 versions prior to 18.4R2-S10, 18.4R3-S9; 19.1 versions prior to 19.1R2-S3, 19.1R3-S6; 19.2 versions prior to 19.2R1-S8, 19.2R3-S3; 19.3 versions prior to 19.3R2-S6, 19.3R3-S3; 19.4 versions prior to 19.4R3-S5; 20.1 versions prior to 20.1R3-S2; 20.2 versions prior to 20.2R3-S2; 20.3 versions prior to 20.3R3; 20.4 versions prior to 20.4R2-S2, 20.4R3; 21.1 versions prior to 21.1R1-S1, 21.1R2; 21.2 versions prior to 21.2R1-S1, 21.2R2.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-22182"
},
{
"type": "WEB",
"url": "https://kb.juniper.net/JSA69519"
}
],
"database_specific": {
"cwe_ids": [
"CWE-79"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 761 |
2,389 | <filename>util/src/main/java/io/kubernetes/client/util/Streams.java
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
public class Streams {
public static final int BUFFER_SIZE = 4096;
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
}
public static String toString(Reader reader) throws IOException {
StringBuilder out = new StringBuilder(BUFFER_SIZE);
char[] buffer = new char[BUFFER_SIZE];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
out.append(buffer, 0, charsRead);
}
return out.toString();
}
public static void readFully(InputStream in, byte[] bytes) throws IOException {
int total = 0;
int len = bytes.length;
while (total < len) {
int result = in.read(bytes, total, len - total);
if (result == -1) {
break;
}
total += result;
}
}
}
| 570 |
2,941 | <gh_stars>1000+
package com.amazonaws.cdk.examples;
import software.amazon.awscdk.core.*;
import software.amazon.awscdk.services.ec2.Vpc;
import software.amazon.awscdk.services.ec2.VpcProps;
import software.amazon.awscdk.services.ecs.Cluster;
import software.amazon.awscdk.services.ecs.ClusterProps;
import software.amazon.awscdk.services.ecs.ContainerImage;
import software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateService;
import software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedFargateServiceProps;
import software.amazon.awscdk.services.ecs.patterns.NetworkLoadBalancedTaskImageOptions;
public class ECSFargateLoadBalancedStack extends Stack {
public ECSFargateLoadBalancedStack(final Construct parent, final String id) {
this(parent, id, null);
}
public ECSFargateLoadBalancedStack(final Construct parent, final String id, final StackProps props) {
super(parent, id, props);
// Create VPC with a AZ limit of two.
Vpc vpc = new Vpc(this, "MyVpc", VpcProps.builder().maxAzs(2).build());
// Create the ECS Service
Cluster cluster = new Cluster(this, "Ec2Cluster", ClusterProps.builder().vpc(vpc).build());
// Use the ECS Network Load Balanced Fargate Service construct to create a ECS service
NetworkLoadBalancedFargateService fargateService = new NetworkLoadBalancedFargateService(
this,
"FargateService",
NetworkLoadBalancedFargateServiceProps.builder()
.cluster(cluster)
.taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.build())
.build());
}
}
| 743 |
1,830 | <reponame>thirteen13Floor/zeebe
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.1. You may not use this file
* except in compliance with the Zeebe Community License 1.1.
*/
package io.camunda.zeebe.gateway.query.impl;
import io.camunda.zeebe.gateway.impl.broker.request.BrokerRequest;
import io.camunda.zeebe.gateway.impl.broker.response.BrokerResponse;
import io.camunda.zeebe.protocol.impl.encoding.ExecuteQueryRequest;
import io.camunda.zeebe.protocol.impl.encoding.ExecuteQueryResponse;
import io.camunda.zeebe.protocol.record.ExecuteQueryResponseDecoder;
import io.camunda.zeebe.protocol.record.ValueType;
import io.camunda.zeebe.transport.RequestType;
import io.camunda.zeebe.util.buffer.BufferWriter;
import org.agrona.DirectBuffer;
import org.agrona.MutableDirectBuffer;
public final class BrokerExecuteQuery extends BrokerRequest<String> {
private final ExecuteQueryRequest request = new ExecuteQueryRequest();
private final ExecuteQueryResponse response = new ExecuteQueryResponse();
public BrokerExecuteQuery() {
super(ExecuteQueryResponseDecoder.SCHEMA_ID, ExecuteQueryResponseDecoder.TEMPLATE_ID);
}
public void setKey(final long key) {
request.setKey(key);
}
public void setValueType(final ValueType valueType) {
request.setValueType(valueType);
}
@Override
public int getPartitionId() {
return request.getPartitionId();
}
@Override
public void setPartitionId(final int partitionId) {
request.setPartitionId(partitionId);
}
@Override
public boolean addressesSpecificPartition() {
return true;
}
@Override
public boolean requiresPartitionId() {
return true;
}
/** @return null to avoid writing any serialized value */
@Override
public BufferWriter getRequestWriter() {
return null;
}
@Override
protected void setSerializedValue(final DirectBuffer buffer) {
throw new UnsupportedOperationException();
}
@Override
protected void wrapResponse(final DirectBuffer buffer) {
response.wrap(buffer, 0, buffer.capacity());
}
@Override
protected BrokerResponse<String> readResponse() {
return new BrokerResponse<>(
response.getBpmnProcessId(), request.getPartitionId(), request.getKey());
}
@Override
protected String toResponseDto(final DirectBuffer buffer) {
throw new UnsupportedOperationException();
}
@Override
public String getType() {
return "Query#" + request.getValueType();
}
@Override
public RequestType getRequestType() {
return RequestType.QUERY;
}
@Override
public int getLength() {
return request.getLength();
}
@Override
public void write(final MutableDirectBuffer buffer, final int offset) {
request.write(buffer, offset);
}
}
| 900 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.