max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,822 | // Copyright (c) 2016 <NAME>
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <hpx/config/export_definitions.hpp>
#if defined(HPX_PROCESS_EXPORTS)
# define HPX_PROCESS_EXPORT HPX_SYMBOL_EXPORT
#else
# define HPX_PROCESS_EXPORT HPX_SYMBOL_IMPORT
#endif
| 172 |
1,056 | <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
*
* 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.spellchecker;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.modules.spellchecker.spi.dictionary.Dictionary;
import org.netbeans.modules.spellchecker.spi.dictionary.ValidityType;
/**
*
* @author <NAME>
*/
public class CompoundDictionary implements Dictionary {
private static final Logger LOGGER = Logger.getLogger(CompoundDictionary.class.getName());
private Dictionary[] delegates;
private CompoundDictionary(Dictionary... delegates) {
this.delegates = delegates.clone();
}
public static Dictionary create(Dictionary... delegates) {
return new CompoundDictionary(delegates);
}
public ValidityType validateWord(CharSequence word) {
ValidityType result = ValidityType.INVALID;
for (Dictionary d : delegates) {
ValidityType thisResult = d.validateWord(word);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "validating word \"{0}\" using dictionary {1}, result: {2}", new Object[] {word, d.toString(), thisResult});
}
if (thisResult == ValidityType.VALID || thisResult == ValidityType.BLACKLISTED) {
return thisResult;
}
if (thisResult == ValidityType.PREFIX_OF_VALID && result == ValidityType.INVALID) {
result = ValidityType.PREFIX_OF_VALID;
}
}
return result;
}
public List<String> findValidWordsForPrefix(CharSequence word) {
List<String> result = new LinkedList<String>();
for (Dictionary d : delegates) {
result.addAll(d.findValidWordsForPrefix(word));
}
return result;
}
public List<String> findProposals(CharSequence word) {
List<String> result = new LinkedList<String>();
for (Dictionary d : delegates) {
result.addAll(d.findProposals(word));
}
return result;
}
}
| 1,111 |
1,900 | <gh_stars>1000+
/*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ehcache.impl.persistence;
import org.ehcache.CachePersistenceException;
import org.ehcache.core.spi.service.LocalPersistenceService;
import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import static org.ehcache.impl.internal.util.FileExistenceMatchers.containsCacheDirectory;
import static org.ehcache.impl.internal.util.FileExistenceMatchers.isLocked;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
public class DefaultLocalPersistenceServiceTest {
@Rule
public final TemporaryFolder folder = new TemporaryFolder();
private File testFolder;
@Before
public void setup() throws IOException {
testFolder = folder.newFolder("testFolder");
}
@Test
public void testFailsIfDirectoryExistsButNotWritable() throws IOException {
assumeTrue(testFolder.setWritable(false));
try {
try {
final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(testFolder));
service.start(null);
fail("Expected IllegalArgumentException");
} catch(IllegalArgumentException e) {
assertThat(e.getMessage(), equalTo("Location isn't writable: " + testFolder.getAbsolutePath()));
}
} finally {
testFolder.setWritable(true);
}
}
@Test
public void testFailsIfFileExistsButIsNotDirectory() throws IOException {
File f = folder.newFile("testFailsIfFileExistsButIsNotDirectory");
try {
final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(f));
service.start(null);
fail("Expected IllegalArgumentException");
} catch(IllegalArgumentException e) {
assertThat(e.getMessage(), equalTo("Location is not a directory: " + f.getAbsolutePath()));
}
}
@Test
public void testFailsIfDirectoryDoesNotExistsAndIsNotCreated() throws IOException {
assumeTrue(testFolder.setWritable(false));
try {
File f = new File(testFolder, "notallowed");
try {
final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(f));
service.start(null);
fail("Expected IllegalArgumentException");
} catch(IllegalArgumentException e) {
assertThat(e.getMessage(), equalTo("Directory couldn't be created: " + f.getAbsolutePath()));
}
} finally {
testFolder.setWritable(true);
}
}
@Test
public void testLocksDirectoryAndUnlocks() throws IOException {
final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(testFolder));
service.start(null);
assertThat(service.getLockFile().exists(), is(true));
service.stop();
assertThat(service.getLockFile().exists(), is(false));
}
@Test
public void testPhysicalDestroy() throws IOException, CachePersistenceException {
final File f = folder.newFolder("testPhysicalDestroy");
final DefaultLocalPersistenceService service = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(f));
service.start(null);
assertThat(service.getLockFile().exists(), is(true));
assertThat(f, isLocked());
LocalPersistenceService.SafeSpaceIdentifier id = service.createSafeSpaceIdentifier("test", "test");
service.createSafeSpace(id);
assertThat(f, containsCacheDirectory("test", "test"));
// try to destroy the physical space without the logical id
LocalPersistenceService.SafeSpaceIdentifier newId = service.createSafeSpaceIdentifier("test", "test");
service.destroySafeSpace(newId, false);
assertThat(f, not(containsCacheDirectory("test", "test")));
service.stop();
assertThat(f, not(isLocked()));
}
@Test
public void testExclusiveLock() throws IOException {
DefaultLocalPersistenceService service1 = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(testFolder));
DefaultLocalPersistenceService service2 = new DefaultLocalPersistenceService(new DefaultPersistenceConfiguration(testFolder));
service1.start(null);
// We should not be able to lock the same directory twice
// And we should receive a meaningful exception about it
RuntimeException thrown = assertThrows(RuntimeException.class, () -> service2.start(null));
assertThat(thrown, hasProperty("message", is("Persistence directory already locked by this process: " + testFolder.getAbsolutePath())));
}
}
| 1,685 |
4,002 | package me.zeroX150.cornos.features.module.impl.render;
import me.zeroX150.cornos.Cornos;
import me.zeroX150.cornos.etc.config.MConfNum;
import me.zeroX150.cornos.etc.helper.Renderer;
import me.zeroX150.cornos.features.module.Module;
import me.zeroX150.cornos.features.module.ModuleType;
import me.zeroX150.cornos.features.module.impl.external.Hud;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.gui.screen.ingame.InventoryScreen;
import net.minecraft.client.util.Window;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.math.Vec3d;
import org.lwjgl.opengl.GL11;
import java.awt.*;
public class TargetHUD extends Module {
public static LivingEntity current = null;
MConfNum trackDistance = new MConfNum("trackDistance", 20.0, 100, 3, "distance to show the info modal");
int distLatest = -1;
public TargetHUD() {
super("TargetHUD", "Shows info about the nearest player", ModuleType.RENDER);
this.mconf.add(trackDistance);
}
@Override
public void onExecute() {
Vec3d pos = Cornos.minecraft.player.getPos();
PlayerEntity closestSoFar = null;
for (Entity entity : Cornos.minecraft.world.getEntities()) {
if (entity.getUuid().equals(Cornos.minecraft.player.getUuid()))
continue;
if (entity instanceof PlayerEntity) {
Vec3d ep = entity.getPos();
double dist = pos.distanceTo(ep);
if (dist > trackDistance.getValue())
continue;
if (closestSoFar == null || dist < closestSoFar.getPos().distanceTo(pos)) {
closestSoFar = (PlayerEntity) entity;
distLatest = (int) dist;
}
}
}
current = closestSoFar;
super.onExecute();
}
@Override
public void onDisable() {
current = null;
super.onDisable();
}
@Override
public String getContext() {
return current == null ? "" : current.getEntityName();
}
@Override
public void onHudRender(MatrixStack ms, float td) {
if (current != null) {
Window w = Cornos.minecraft.getWindow();
int w1 = w.getScaledWidth() / 2;
int h = w.getScaledHeight() / 2;
int width = 120;
int height = 42;
int x1 = w1 + 5;
int x2 = x1 + width;
int y1 = h + 5;
int y2 = y1 + height;
double innerCompScale = 1;
String uname = current.getEntityName();
current.setCustomName(Text.of("DoNotRenderThisUsernameISwearToGod")); // it works but im not proud
DrawableHelper.fill(ms, x1, y1, x2, y2, new Color(20, 20, 20, 100).getRGB());
Renderer.renderLineScreen(new Vec3d(x1, y1, 0), new Vec3d(x2, y1, 0), Hud.themeColor.getColor(), 2);
Renderer.renderLineScreen(new Vec3d(x2, y1, 0), new Vec3d(x2, y2, 0), Hud.themeColor.getColor(), 2);
Renderer.renderLineScreen(new Vec3d(x2, y2, 0), new Vec3d(x1, y2, 0), Hud.themeColor.getColor(), 2);
Renderer.renderLineScreen(new Vec3d(x1, y2, 0), new Vec3d(x1, y1, 0), Hud.themeColor.getColor(), 2);
InventoryScreen.drawEntity(x1 + 10, y1 + 38, 18, (float) -(w1 / 10), (float) -(h / 10), current);
DrawableHelper.drawCenteredString(ms, Cornos.minecraft.textRenderer, uname, x1 + (width / 2), y1 + 2,
0xFFFFFF);
GL11.glScaled(innerCompScale, innerCompScale, innerCompScale);
Cornos.minecraft.textRenderer.draw(ms, "Distance: " + distLatest,
(float) ((x1 + 10 + 7 + 4) / innerCompScale), (float) ((y1 + 11) / innerCompScale),
Color.WHITE.getRGB());
Cornos.minecraft.textRenderer.draw(ms,
"Health: " + ((int) Math.floor(current.getHealth())) + " / "
+ ((int) Math.floor(current.getMaxHealth())),
(float) ((x1 + 10 + 7 + 4) / innerCompScale), (float) ((y1 + 11 + 10) / innerCompScale),
Color.WHITE.getRGB());
String winLoseState;
Color c = Color.WHITE;
if (current.getHealth() > Cornos.minecraft.player.getHealth()) {
winLoseState = "Losing";
c = new Color(196, 48, 48);
} else if (current.getHealth() == Cornos.minecraft.player.getHealth()) {
winLoseState = "Stalemate";
} else {
winLoseState = "Winning";
c = new Color(35, 231, 100);
}
Cornos.minecraft.textRenderer.draw(ms, winLoseState, (float) ((x1 + 10 + 7 + 4) / innerCompScale),
(float) ((y1 + 11 + 20) / innerCompScale), c.getRGB());
GL11.glScaled(1 / innerCompScale, 1 / innerCompScale, 1 / innerCompScale);
current.setCustomName(null);
}
super.onHudRender(ms, td);
}
}
| 2,400 |
1,444 | <filename>Mage.Sets/src/mage/cards/e/EurekaMoment.java
package mage.cards.e;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.effects.common.PutCardFromHandOntoBattlefieldEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.StaticFilters;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class EurekaMoment extends CardImpl {
public EurekaMoment(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{G}{U}");
// Draw two cards. You may put a land card from your hand onto the battlefield.
this.getSpellAbility().addEffect(new DrawCardSourceControllerEffect(2));
this.getSpellAbility().addEffect(new PutCardFromHandOntoBattlefieldEffect(StaticFilters.FILTER_CARD_LAND_A));
}
private EurekaMoment(final EurekaMoment card) {
super(card);
}
@Override
public EurekaMoment copy() {
return new EurekaMoment(this);
}
}
| 383 |
1,178 | /*
* 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.
*/
#include "avionics/firmware/monitors/analog.h"
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include "avionics/firmware/cpu/adc.h"
#include "common/macros.h"
#define ADC_MODULE 1
static float ConvertToVoltage(const AnalogMonitor *mon, int16_t in) {
return (float)in * mon->volts_per_count - mon->offset;
}
static uint32_t ComputeVoltageFlags(const AnalogMonitor *mon, float in) {
if (in >= mon->max) {
return kAnalogFlagOverVoltage;
} else if (in <= mon->min) {
return kAnalogFlagUnderVoltage;
} else {
return 0x0;
}
}
static uint32_t ComputeLogicLowFlags(int16_t in) {
return (in < ADC_LOGIC_LOW) ? kAnalogFlagAsserted : 0x0;
}
static uint32_t ComputeLogicHighFlags(int16_t in) {
return (in > ADC_LOGIC_HIGH) ? kAnalogFlagAsserted : 0x0;
}
static uint32_t ComputePortDetectFlags(int16_t in) {
// ADC measures ~2.3v when detected, ~1.6v when not detected.
int16_t high = (int16_t)(1.95f * ADC_MAX_VALUE / ADC_MAX_VOLTAGE);
return (in > high) ? kAnalogFlagAsserted : 0x0;
}
static uint32_t ComputeFlags(const AnalogMonitor *mon, int16_t raw,
float value) {
switch (mon->type) {
case kAnalogTypeVoltage:
return ComputeVoltageFlags(mon, value);
case kAnalogTypeLogicLow:
return ComputeLogicLowFlags(raw);
case kAnalogTypeLogicHigh:
return ComputeLogicHighFlags(raw);
case kAnalogTypePortDetect:
return ComputePortDetectFlags(raw);
default:
return 0x0;
}
}
void AnalogMonitorInit(void) {
AdcInit(ADC_MODULE);
}
bool AnalogMonitorPoll(const AnalogMonitors *config,
AnalogOutputFunction output_function) {
// If no valid configuration exists, return true to advance to next monitor.
if (config == NULL || config->num_devices <= 0) {
return true;
}
int16_t adc[ADC_CHANNELS];
assert(output_function != NULL);
if (AdcPollGroup1(ADC_MODULE, config->channel_mask, ARRAYSIZE(adc), adc)) {
for (int32_t i = 0; i < config->num_devices; ++i) {
const AnalogMonitor *mon = &config->device[i];
int16_t raw = adc[mon->channel];
float value = ConvertToVoltage(mon, raw);
output_function(mon, value, ComputeFlags(mon, raw, value));
}
return true;
}
return false;
}
| 1,085 |
2,845 | <gh_stars>1000+
#pragma once
#include "PJON.h"
#include "strategies/LocalUDP/LocalUDP.h"
#define PJONLocalUDP PJON<LocalUDP>
| 60 |
1,779 | //
// Copyright 2020 Google 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.
//
#ifndef THIRD_PARTY_ZETASQL_ZETASQL_BASE_NET_PUBLIC_SUFFIX_H_
#define THIRD_PARTY_ZETASQL_ZETASQL_BASE_NET_PUBLIC_SUFFIX_H_
// This file abstracts public suffix methods which has a different
// implementation in the open source version. Methods are documented here as a
// convenience.
#include "zetasql/base/net/public_suffix_oss.h"
namespace zetasql::internal {
//
// GetPublicSuffix()
//
// Extract the public suffix from the given name, using the latest public
// suffix data. Returns the entire string if it is a public suffix. Returns the
// empty string when the name does not contain a public suffix. Examples:
// "www.berkeley.edu" -> "edu"
// "www.clavering.essex.sch.uk" -> "essex.sch.uk"
// "sch.uk" -> ""
// The name must be normalized (lower-cased, Punycoded) before calling this
// method. Use zetasql::internal::ToASCII to normalize the name. The returned
// absl::string_view will live as long as the input absl::string_view lives.
//
// absl::string_view GetPublicSuffix(absl::string_view name);
//
// GetTopPrivateDomain()
//
// Extract the top private domain from the given name, using the latest public
// suffix data. Returns the entire string if it is a top private domain.
// Returns the empty string when the name does not contain a top private
// domain. Examples:
// "www.google.com" -> "google.com"
// "www.google.co.uk" -> "google.co.uk"
// "co.uk" -> ""
// The name must be normalized (lower-cased, Punycoded) before calling this
// method. Use zetasql::internal::ToASCII to normalize the name. The returned
// absl::string_view will live as long as the input absl::string_view lives.
//
// absl::string_view GetTopPrivateDomain(absl::string_view name);
} // namespace zetasql::internal
#endif // THIRD_PARTY_ZETASQL_ZETASQL_BASE_NET_PUBLIC_SUFFIX_H_
| 790 |
350 | /*
* Copyright 2020 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.
*/
package com.google.android.accessibility.brailleime.translate;
import static com.google.android.accessibility.brailleime.translate.BrailleTranslateUtils.NUMERIC;
import android.content.res.Resources;
import com.google.android.accessibility.brailleime.BrailleCharacter;
import com.google.android.accessibility.brailleime.R;
/** Utils for translation of UEB Braille. */
public class BrailleTranslateUtilsUeb {
public static final BrailleCharacter CAPITALIZE = new BrailleCharacter(6);
public static final BrailleCharacter LETTER_A = new BrailleCharacter(1);
public static final BrailleCharacter LETTER_B = new BrailleCharacter(1, 2);
public static final BrailleCharacter LETTER_C = new BrailleCharacter(1, 4);
public static final BrailleCharacter LETTER_D = new BrailleCharacter(1, 4, 5);
/**
* Return a brief announcement text that represents the given {@link BrailleCharacter}, in case
* such an announcement is appropriate. This is useful for certain prefixes that do not have a
* stand-alone translation, but are important enough that the user would appreciate an audial
* description of it.
*/
public static String getTextToSpeak(Resources resources, BrailleCharacter brailleCharacter) {
String textToSpeak = "";
if (brailleCharacter.equals(CAPITALIZE)) {
textToSpeak = resources.getString(R.string.capitalize_announcement);
} else if (brailleCharacter.equals(NUMERIC)) {
textToSpeak = resources.getString(R.string.number_announcement);
}
return textToSpeak;
}
private BrailleTranslateUtilsUeb() {}
}
| 621 |
2,453 | <reponame>haozhiyu1990/XVim2<gh_stars>1000+
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <objc/NSObject.h>
@interface IDEExplorationContext : NSObject
{
}
// Remaining properties
@property(readonly) int explorationType; // @dynamic explorationType;
@end
| 129 |
4,050 | /*
* Copyright 2011 LinkedIn Corp.
*
* 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 azkaban.security.commons;
import azkaban.Constants.JobProperties;
import azkaban.utils.Props;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.log4j.Logger;
public class SecurityUtils {
// Secure Hadoop proxy user params
public static final String ENABLE_PROXYING = "azkaban.should.proxy"; // boolean
public static final String PROXY_KEYTAB_LOCATION = "proxy.keytab.location";
public static final String PROXY_USER = "proxy.user";
public static final String OBTAIN_BINARY_TOKEN = "obtain.binary.token";
public static final String MAPREDUCE_JOB_CREDENTIALS_BINARY =
"mapreduce.job.credentials.binary";
private static UserGroupInformation loginUser = null;
/**
* Create a proxied user based on the explicit user name, taking other parameters necessary from
* properties file.
*/
public static synchronized UserGroupInformation getProxiedUser(
final String toProxy, final Properties prop, final Logger log, final Configuration conf)
throws IOException {
if (conf == null) {
throw new IllegalArgumentException("conf can't be null");
}
UserGroupInformation.setConfiguration(conf);
if (toProxy == null) {
throw new IllegalArgumentException("toProxy can't be null");
}
if (loginUser == null) {
log.info("No login user. Creating login user");
final String keytab = verifySecureProperty(prop, PROXY_KEYTAB_LOCATION, log);
final String proxyUser = verifySecureProperty(prop, PROXY_USER, log);
UserGroupInformation.loginUserFromKeytab(proxyUser, keytab);
loginUser = UserGroupInformation.getLoginUser();
log.info("Logged in with user " + loginUser);
} else {
log.info("loginUser (" + loginUser + ") already created, refreshing tgt.");
loginUser.checkTGTAndReloginFromKeytab();
}
return UserGroupInformation.createProxyUser(toProxy, loginUser);
}
/**
* Create a proxied user, taking all parameters, including which user to proxy from provided
* Properties.
*/
public static UserGroupInformation getProxiedUser(final Properties prop,
final Logger log, final Configuration conf) throws IOException {
final String toProxy = verifySecureProperty(prop, JobProperties.USER_TO_PROXY, log);
final UserGroupInformation user = getProxiedUser(toProxy, prop, log, conf);
if (user == null) {
throw new IOException(
"Proxy as any user in unsecured grid is not supported!"
+ prop.toString());
}
log.info("created proxy user for " + user.getUserName() + user.toString());
return user;
}
public static String verifySecureProperty(final Properties properties, final String s,
final Logger l) throws IOException {
final String value = properties.getProperty(s);
if (value == null) {
throw new IOException(s
+ " not set in properties. Cannot use secure proxy");
}
l.info("Secure proxy configuration: Property " + s + " = " + value);
return value;
}
public static boolean shouldProxy(final Properties prop) {
final String shouldProxy = prop.getProperty(ENABLE_PROXYING);
return shouldProxy != null && shouldProxy.equals("true");
}
public static synchronized void prefetchToken(final File tokenFile,
final Props p, final Logger logger) throws InterruptedException,
IOException {
final Configuration conf = new Configuration();
logger.info("Getting proxy user for " + p.getString(JobProperties.USER_TO_PROXY));
logger.info("Getting proxy user for " + p.toString());
getProxiedUser(p.toProperties(), logger, conf).doAs(
new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
getToken(p);
return null;
}
private void getToken(final Props p) throws InterruptedException,
IOException {
final String shouldPrefetch = p.getString(OBTAIN_BINARY_TOKEN);
if (shouldPrefetch != null && shouldPrefetch.equals("true")) {
logger.info("Pre-fetching token");
logger.info("Pre-fetching fs token");
final FileSystem fs = FileSystem.get(conf);
final Token<?> fsToken =
fs.getDelegationToken(p.getString(JobProperties.USER_TO_PROXY));
logger.info("Created token: " + fsToken.toString());
final Job job =
new Job(conf, "totally phony, extremely fake, not real job");
final JobConf jc = new JobConf(conf);
final JobClient jobClient = new JobClient(jc);
logger.info("Pre-fetching job token: Got new JobClient: " + jc);
final Token<DelegationTokenIdentifier> mrdt =
jobClient.getDelegationToken(new Text("hi"));
logger.info("Created token: " + mrdt.toString());
job.getCredentials().addToken(new Text("howdy"), mrdt);
job.getCredentials().addToken(fsToken.getService(), fsToken);
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream(tokenFile);
dos = new DataOutputStream(fos);
job.getCredentials().writeTokenStorageToStream(dos);
} finally {
if (dos != null) {
dos.close();
}
if (fos != null) {
fos.close();
}
}
logger.info("Loading hadoop tokens into "
+ tokenFile.getAbsolutePath());
p.put("HadoopTokenFileLoc", tokenFile.getAbsolutePath());
} else {
logger.info("Not pre-fetching token");
}
}
});
}
}
| 2,632 |
18,012 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.protocol.tri.stream;
import org.apache.dubbo.rpc.TriRpcStatus;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.util.concurrent.Future;
import java.net.SocketAddress;
/**
* Stream is a bi-directional channel that manipulates the data flow between peers. Inbound data
* from remote peer is acquired by {@link Listener}. Outbound data to remote peer is sent directly
* by {@link Stream}. Backpressure is supported by {@link #request(int)}.
*/
public interface Stream {
/**
* Register a {@link Listener} to receive inbound data from remote peer.
*/
interface Listener {
/**
* Callback when receive message. Note this method may be called many times if is a
* streaming .
*
* @param message message received from remote peer
*/
void onMessage(byte[] message);
/**
* Callback when receive cancel signal.
*
* @param status the cancel status
*/
void onCancelByRemote(TriRpcStatus status);
}
/**
* Send headers to remote peer.
*
* @param headers headers to send to remote peer
* @return future to callback when send headers is done
*/
Future<?> sendHeader(Http2Headers headers);
/**
* Cancel by this peer.
*
* @param status cancel status to send to remote peer
* @return future to callback when cancel is done
*/
Future<?> cancelByLocal(TriRpcStatus status);
/**
* Get remote peer address.
*
* @return socket address of remote peer
*/
SocketAddress remoteAddress();
/**
* Request n message from remote peer.
*
* @param n number of message
*/
void request(int n);
}
| 843 |
839 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.jaxrs.client.logging;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.List;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.ext.logging.AbstractLoggingInterceptor;
import org.apache.cxf.ext.logging.LoggingFeature;
import org.apache.cxf.ext.logging.event.EventType;
import org.apache.cxf.ext.logging.event.LogEvent;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.transport.local.LocalTransportFactory;
import org.junit.Assert;
import org.junit.Test;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.core.Is.is;
public class RESTLoggingTest {
private static final String SERVICE_URI = "local://testrest";
private static final String SERVICE_URI_BINARY = "local://testrestbin";
@Test
public void testSlf4j() throws IOException {
LoggingFeature loggingFeature = new LoggingFeature();
Server server = createService(SERVICE_URI, new TestServiceRest(), loggingFeature);
server.start();
WebClient client = createClient(SERVICE_URI, loggingFeature);
String result = client.get(String.class);
server.destroy();
Assert.assertEquals("test1", result);
}
@Test
public void testBinary() throws IOException, InterruptedException {
LoggingFeature loggingFeature = new LoggingFeature();
TestEventSender sender = new TestEventSender();
loggingFeature.setSender(sender);
loggingFeature.setLogBinary(true);
Server server = createService(SERVICE_URI_BINARY, new TestServiceRestBinary(), loggingFeature);
server.start();
WebClient client = createClient(SERVICE_URI_BINARY, loggingFeature);
client.get(InputStream.class).close();
client.close();
List<LogEvent> events = sender.getEvents();
await().until(() -> events.size(), is(4));
server.stop();
server.destroy();
Assert.assertEquals(4, events.size());
assertContentLogged(events.get(0));
assertContentLogged(events.get(1));
assertContentLogged(events.get(2));
assertContentLogged(events.get(3));
}
@Test
public void testNonBinary() throws IOException, InterruptedException {
LoggingFeature loggingFeature = new LoggingFeature();
TestEventSender sender = new TestEventSender();
loggingFeature.setSender(sender);
Server server = createService(SERVICE_URI_BINARY, new TestServiceRestBinary(), loggingFeature);
server.start();
WebClient client = createClient(SERVICE_URI_BINARY, loggingFeature);
client.get(InputStream.class).close();
client.close();
List<LogEvent> events = sender.getEvents();
await().until(() -> events.size(), is(4));
server.stop();
server.destroy();
Assert.assertEquals(4, events.size());
assertContentLogged(events.get(0));
assertContentLogged(events.get(1));
assertContentNotLogged(events.get(2));
assertContentNotLogged(events.get(3));
}
@Test
public void testEvents() throws MalformedURLException {
LoggingFeature loggingFeature = new LoggingFeature();
loggingFeature.setLogBinary(true);
TestEventSender sender = new TestEventSender();
loggingFeature.setSender(sender);
Server server = createService(SERVICE_URI, new TestServiceRest(), loggingFeature);
server.start();
WebClient client = createClient(SERVICE_URI, loggingFeature);
String result = client.get(String.class);
Assert.assertEquals("test1", result);
List<LogEvent> events = sender.getEvents();
await().until(() -> events.size(), is(4));
server.stop();
server.destroy();
Assert.assertEquals(4, events.size());
checkRequestOut(events.get(0));
checkRequestIn(events.get(1));
checkResponseOut(events.get(2));
checkResponseIn(events.get(3));
}
private void assertContentLogged(LogEvent event) {
Assert.assertNotEquals(AbstractLoggingInterceptor.CONTENT_SUPPRESSED, event.getPayload());
}
private void assertContentNotLogged(LogEvent event) {
Assert.assertEquals(AbstractLoggingInterceptor.CONTENT_SUPPRESSED, event.getPayload());
}
private WebClient createClient(String serviceURI, LoggingFeature loggingFeature) {
JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
bean.setAddress(serviceURI);
bean.setFeatures(Collections.singletonList(loggingFeature));
bean.setTransportId(LocalTransportFactory.TRANSPORT_ID);
return bean.createWebClient().path("test1");
}
private Server createService(String serviceURI, Object serviceImpl, LoggingFeature loggingFeature) {
JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
factory.setAddress(serviceURI);
factory.setFeatures(Collections.singletonList(loggingFeature));
factory.setServiceBean(serviceImpl);
factory.setTransportId(LocalTransportFactory.TRANSPORT_ID);
return factory.create();
}
private void checkRequestOut(LogEvent requestOut) {
Assert.assertEquals(SERVICE_URI + "/test1", requestOut.getAddress());
Assert.assertNull(requestOut.getContentType());
Assert.assertEquals(EventType.REQ_OUT, requestOut.getType());
Assert.assertNull(requestOut.getEncoding());
Assert.assertNotNull(requestOut.getExchangeId());
Assert.assertEquals("GET", requestOut.getHttpMethod());
Assert.assertNotNull(requestOut.getMessageId());
Assert.assertEquals("", requestOut.getPayload());
}
private void checkRequestIn(LogEvent requestIn) {
Assert.assertEquals(SERVICE_URI + "/test1", requestIn.getAddress());
Assert.assertNull(requestIn.getContentType());
Assert.assertEquals(EventType.REQ_IN, requestIn.getType());
Assert.assertNull(requestIn.getEncoding());
Assert.assertNotNull(requestIn.getExchangeId());
Assert.assertEquals("GET", requestIn.getHttpMethod());
Assert.assertNotNull(requestIn.getMessageId());
}
private void checkResponseOut(LogEvent responseOut) {
// Not yet available
Assert.assertEquals(SERVICE_URI + "/test1", responseOut.getAddress());
Assert.assertEquals("application/octet-stream", responseOut.getContentType());
Assert.assertEquals(EventType.RESP_OUT, responseOut.getType());
Assert.assertNull(responseOut.getEncoding());
Assert.assertNotNull(responseOut.getExchangeId());
// Not yet available
Assert.assertNull(responseOut.getHttpMethod());
Assert.assertNotNull(responseOut.getMessageId());
Assert.assertEquals("test1", responseOut.getPayload());
}
private void checkResponseIn(LogEvent responseIn) {
// Not yet available
Assert.assertEquals(SERVICE_URI + "/test1", responseIn.getAddress());
Assert.assertEquals("application/octet-stream", responseIn.getContentType());
Assert.assertEquals(EventType.RESP_IN, responseIn.getType());
Assert.assertNotNull(responseIn.getExchangeId());
// Not yet available
Assert.assertNull(responseIn.getHttpMethod());
Assert.assertNotNull(responseIn.getMessageId());
Assert.assertEquals("test1", responseIn.getPayload());
}
}
| 3,091 |
8,664 | <gh_stars>1000+
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
//#include <roapi.h>
#include "activation.h"
#include <winstring.h>
#include "RoParameterizedIID.h"
namespace Js
{
class DelayLoadWinRtString : public DelayLoadLibrary
{
private:
// WinRTString specific functions
typedef HRESULT FNCWindowsCreateString(const WCHAR *, UINT32, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING *);
typedef FNCWindowsCreateString* PFNCWindowsCreateString;
PFNCWindowsCreateString m_pfnWindowsCreateString;
typedef HRESULT FNCWindowsCreateStringReference(const WCHAR *, UINT32, HSTRING_HEADER *, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING *);
typedef FNCWindowsCreateStringReference* PFNCWindowsCreateStringReference;
PFNCWindowsCreateStringReference m_pfnWindowsCreateStringReference;
typedef PCWSTR FNCWindowsGetStringRawBuffer(HSTRING, UINT32*);
typedef FNCWindowsGetStringRawBuffer* PFNCWindowsGetStringRawBuffer;
PFNCWindowsGetStringRawBuffer m_pfWindowsGetStringRawBuffer;
typedef HRESULT FNCWindowsDeleteString(HSTRING);
typedef FNCWindowsDeleteString* PFNCWindowsDeleteString;
PFNCWindowsDeleteString m_pfnWindowsDeleteString;
typedef HRESULT FNCWindowsCompareStringOrdinal(HSTRING,HSTRING,INT32*);
typedef FNCWindowsCompareStringOrdinal* PFNCWindowsCompareStringOrdinal;
PFNCWindowsCompareStringOrdinal m_pfnWindowsCompareStringOrdinal;
typedef HRESULT FNCWindowsDuplicateString(HSTRING, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING*);
typedef FNCWindowsDuplicateString* PFNCWindowsDuplicateString;
PFNCWindowsDuplicateString m_pfnWindowsDuplicateString;
public:
DelayLoadWinRtString() : DelayLoadLibrary(),
m_pfnWindowsCreateString(NULL),
m_pfWindowsGetStringRawBuffer(NULL),
m_pfnWindowsDeleteString(NULL),
m_pfnWindowsCreateStringReference(NULL),
m_pfnWindowsDuplicateString(NULL),
m_pfnWindowsCompareStringOrdinal(NULL) { }
virtual ~DelayLoadWinRtString() { }
LPCTSTR GetLibraryName() const { return _u("api-ms-win-core-winrt-string-l1-1-0.dll"); }
virtual HRESULT WindowsCreateString(_In_reads_opt_(length) const WCHAR * sourceString, UINT32 length, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING * string);
virtual HRESULT WindowsCreateStringReference(_In_reads_opt_(length + 1) const WCHAR * sourceString, UINT32 length, _Out_ HSTRING_HEADER * header, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING * string);
virtual HRESULT WindowsDeleteString(_In_opt_ HSTRING string);
virtual PCWSTR WindowsGetStringRawBuffer(_In_opt_ HSTRING string, _Out_opt_ UINT32 * length);
virtual HRESULT WindowsCompareStringOrdinal(_In_opt_ HSTRING string1, _In_opt_ HSTRING string2, _Out_ INT32 * result);
virtual HRESULT WindowsDuplicateString(_In_opt_ HSTRING original, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING * newString);
};
#ifdef INTL_WINGLOB
class DelayLoadWindowsGlobalization sealed : public DelayLoadWinRtString
{
private:
// DelayLoadWindowsGlobalization specific functions
typedef HRESULT FNCWDllGetActivationFactory(HSTRING clsid, IActivationFactory** factory);
typedef FNCWDllGetActivationFactory* PFNCWDllGetActivationFactory;
PFNCWDllGetActivationFactory m_pfnFNCWDllGetActivationFactory;
Js::DelayLoadWinRtString *winRTStringLibrary;
bool winRTStringsPresent;
bool hasGlobalizationDllLoaded;
public:
DelayLoadWindowsGlobalization() : DelayLoadWinRtString(),
m_pfnFNCWDllGetActivationFactory(nullptr),
winRTStringLibrary(nullptr),
winRTStringsPresent(false),
hasGlobalizationDllLoaded(false) { }
virtual ~DelayLoadWindowsGlobalization() { }
LPCTSTR GetLibraryName() const
{
return _u("windows.globalization.dll");
}
LPCTSTR GetWin7LibraryName() const
{
return _u("jsIntl.dll");
}
void Ensure(Js::DelayLoadWinRtString *winRTStringLibrary);
HRESULT DllGetActivationFactory(__in HSTRING activatibleClassId, __out IActivationFactory** factory);
bool HasGlobalizationDllLoaded();
HRESULT WindowsCreateString(_In_reads_opt_(length) const WCHAR * sourceString, UINT32 length, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING * string) override;
HRESULT WindowsCreateStringReference(_In_reads_opt_(length+1) const WCHAR * sourceString, UINT32 length, _Out_ HSTRING_HEADER * header, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING * string) override;
HRESULT WindowsDeleteString(_In_opt_ HSTRING string) override;
PCWSTR WindowsGetStringRawBuffer(_In_opt_ HSTRING string, _Out_opt_ UINT32 * length) override;
HRESULT WindowsCompareStringOrdinal(_In_opt_ HSTRING string1, _In_opt_ HSTRING string2, _Out_ INT32 * result) override;
HRESULT WindowsDuplicateString(_In_opt_ HSTRING original, _Outptr_result_maybenull_ _Result_nullonfailure_ HSTRING *newString) override;
};
#endif
class DelayLoadWinRtFoundation sealed : public DelayLoadLibrary
{
private:
// DelayLoadWindowsFoundation specific functions
typedef HRESULT FNCWRoGetActivationFactory(HSTRING clsid, REFIID iid, IActivationFactory** factory);
typedef FNCWRoGetActivationFactory* PFNCWRoGetActivationFactory;
PFNCWRoGetActivationFactory m_pfnFNCWRoGetActivationFactory;
public:
DelayLoadWinRtFoundation() : DelayLoadLibrary(),
m_pfnFNCWRoGetActivationFactory(nullptr) { }
virtual ~DelayLoadWinRtFoundation() { }
LPCTSTR GetLibraryName() const { return _u("api-ms-win-core-winrt-l1-1-0.dll"); }
HRESULT RoGetActivationFactory(
__in HSTRING activatibleClassId,
__in REFIID iid,
__out IActivationFactory** factory);
};
class DelayLoadWinCoreProcessThreads sealed : public DelayLoadLibrary
{
private:
// LoadWinCoreMemory specific functions
typedef BOOL FNCGetProcessInformation(HANDLE, PROCESS_INFORMATION_CLASS, PVOID, SIZE_T);
typedef FNCGetProcessInformation* PFNCGetProcessInformation;
PFNCGetProcessInformation m_pfnGetProcessInformation;
public:
DelayLoadWinCoreProcessThreads() :
DelayLoadLibrary(),
m_pfnGetProcessInformation(nullptr)
{
}
LPCTSTR GetLibraryName() const { return _u("api-ms-win-core-processthreads-l1-1-3.dll"); }
BOOL GetProcessInformation(
__in HANDLE hProcess,
__in PROCESS_INFORMATION_CLASS ProcessInformationClass,
__out_bcount(nLength) PVOID lpBuffer,
__in SIZE_T nLength
);
};
}
| 2,786 |
1,338 | /*
* Copyright 2006, 2011, <NAME> <<EMAIL>>.
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "CurrentColor.h"
#include <stdio.h>
#include <OS.h>
#include "ui_defines.h"
CurrentColor::CurrentColor()
: Observable(),
fColor(kBlack)
{
}
CurrentColor::~CurrentColor()
{
}
void
CurrentColor::SetColor(rgb_color color)
{
if ((uint32&)fColor == (uint32&)color)
return;
fColor = color;
Notify();
}
| 171 |
742 | package org.support.project.knowledge.control;
import java.util.ArrayList;
import java.util.List;
import org.support.project.common.util.HtmlUtils;
import org.support.project.common.util.StringUtils;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.knowledge.config.AppConfig;
import org.support.project.knowledge.config.LocaleTextReader;
import org.support.project.knowledge.config.SystemConfig;
import org.support.project.knowledge.dao.KnowledgeFilesDao;
import org.support.project.knowledge.dao.TagsDao;
import org.support.project.knowledge.entity.DraftKnowledgesEntity;
import org.support.project.knowledge.entity.KnowledgeFilesEntity;
import org.support.project.knowledge.entity.KnowledgesEntity;
import org.support.project.knowledge.entity.TagsEntity;
import org.support.project.knowledge.entity.TemplateMastersEntity;
import org.support.project.knowledge.logic.KnowledgeLogic;
import org.support.project.knowledge.logic.TargetLogic;
import org.support.project.knowledge.logic.TemplateLogic;
import org.support.project.knowledge.logic.UploadedFileLogic;
import org.support.project.knowledge.vo.UploadFile;
import org.support.project.web.bean.LabelValue;
import org.support.project.web.dao.SystemConfigsDao;
import org.support.project.web.entity.SystemConfigsEntity;
@DI(instance = Instance.Prototype)
public class KnowledgeControlBase extends Control {
private static final String MARKDOWN_SAMPLE = "/org/support/project/knowledge/markdown/sample_markdown.md";
protected String setViewParam() {
List<LabelValue> paramsArray = new ArrayList<>();
paramsArray.add(new LabelValue("offset", getParamWithDefault("offset", "")));
paramsArray.add(new LabelValue("keyword", getParamWithDefault("keyword", "")));
paramsArray.add(new LabelValue("tag", getParamWithDefault("tag", "")));
paramsArray.add(new LabelValue("tagNames", getParamWithDefault("tagNames", "")));
paramsArray.add(new LabelValue("group", getParamWithDefault("group", "")));
paramsArray.add(new LabelValue("groupNames", getParamWithDefault("groupNames", "")));
paramsArray.add(new LabelValue("user", getParamWithDefault("user", "")));
paramsArray.add(new LabelValue("creators", getParamWithDefault("creators", "")));
String[] templates = getParam("template", String[].class);
if (templates != null) {
for (String template : templates) {
paramsArray.add(new LabelValue("template", template));
}
}
StringBuilder params = new StringBuilder();
boolean append = false;
for (LabelValue labelValue : paramsArray) {
if (StringUtils.isNotEmpty(labelValue.getValue())) {
if (!append) {
params.append('?');
append = true;
} else {
params.append('&');
}
params.append(HtmlUtils.escapeHTML(labelValue.getLabel()))
.append("=")
.append(HtmlUtils.escapeHTML(labelValue.getValue()));
}
}
setAttribute("params", params.toString());
return params.toString();
}
protected void setAttributeForEditPage() {
List<TagsEntity> tagitems = TagsDao.get().selectAll();
setAttribute("tagitems", tagitems);
List<TemplateMastersEntity> templates = TemplateLogic.get().selectAll();
setAttribute("templates", templates);
SystemConfigsEntity config = SystemConfigsDao.get().selectOnKey(SystemConfig.UPLOAD_MAX_MB_SIZE, AppConfig.get().getSystemName());
if (config != null) {
setAttribute("uploadMaxMBSize", config.getConfigValue());
} else {
setAttribute("uploadMaxMBSize", "10"); // default
}
String markdown = LocaleTextReader.get().read(MARKDOWN_SAMPLE, getLocale());
setAttribute("markdown", markdown);
}
/**
* 下書きの情報をセットする
* 下書き一覧と、Knowledgeの編集画面の2つから呼び出されるため共通化
* @param draft
*/
protected void setDraftInfo(DraftKnowledgesEntity draft) {
List<UploadFile> files = new ArrayList<UploadFile>();
// 下書きにのみ紐づくファイルがあれば取得
List<UploadFile> draftFiles = new ArrayList<UploadFile>();
List<KnowledgeFilesEntity> filesEntities = KnowledgeFilesDao.get().selectOnDraftId(draft.getDraftId());
for (KnowledgeFilesEntity entity : filesEntities) {
if (entity.getCommentNo() == null || entity.getCommentNo() == 0) {
draftFiles.add(UploadedFileLogic.get().convUploadFile(getRequest().getContextPath(), entity));
}
}
if (draft.getKnowledgeId() != null && draft.getKnowledgeId() > 0) {
// ナレッジに紐付いた下書きであれば、Knowledgeの編集権限をチェックする
KnowledgesEntity knowledge = KnowledgeLogic.get().select(draft.getKnowledgeId(), getLoginedUser());
if (knowledge == null) {
addMsgWarn("knowledge.draft.view.msg.not.editor");
}
// ナレッジに紐づく添付ファイルを取得
List<UploadFile> knowledgeFiles = UploadedFileLogic.get().selectOnKnowledgeIdWithoutCommentFiles(
draft.getKnowledgeId(), getRequest().getContextPath());
files.addAll(knowledgeFiles);
} else {
draft.setKnowledgeId(null);
}
setAttributeOnProperty(draft);
files.addAll(draftFiles);
setAttribute("files", files);
// 表示するグループを取得
String[] targets = draft.getAccesses().split(",");
List<LabelValue> viewers = TargetLogic.get().selectTargets(targets);
setAttribute("groups", viewers);
// 共同編集者
String[] editordids = draft.getEditors().split(",");
List<LabelValue> editors = TargetLogic.get().selectTargets(editordids);
setAttribute("editors", editors);
}
}
| 2,502 |
998 | // Copyright 2021 Phyronnaz
#pragma once
#if 0
#include "CoreMinimal.h"
#include "FastNoise/VoxelFastNoise.h"
#include "VoxelGenerators/VoxelGeneratorHelpers.h"
#include "VoxelGeneratorExample.generated.h"
UCLASS(Blueprintable)
class UVoxelGeneratorExample : public UVoxelGenerator
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Generator")
float NoiseHeight = 10.f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Generator")
int32 Seed = 1337;
//~ Begin UVoxelGenerator Interface
virtual TVoxelSharedRef<FVoxelGeneratorInstance> GetInstance() override;
//~ End UVoxelGenerator Interface
};
class FVoxelGeneratorExampleInstance : public TVoxelGeneratorInstanceHelper<FVoxelGeneratorExampleInstance, UVoxelGeneratorExample>
{
public:
using Super = TVoxelGeneratorInstanceHelper<FVoxelGeneratorExampleInstance, UVoxelGeneratorExample>;
explicit FVoxelGeneratorExampleInstance(const UVoxelGeneratorExample& MyGenerator);
//~ Begin FVoxelGeneratorInstance Interface
virtual void Init(const FVoxelGeneratorInit& InitStruct) override;
v_flt GetValueImpl(v_flt X, v_flt Y, v_flt Z, int32 LOD, const FVoxelItemStack& Items) const;
FVoxelMaterial GetMaterialImpl(v_flt X, v_flt Y, v_flt Z, int32 LOD, const FVoxelItemStack& Items) const;
TVoxelRange<v_flt> GetValueRangeImpl(const FVoxelIntBox& Bounds, int32 LOD, const FVoxelItemStack& Items) const;
virtual FVector GetUpVector(v_flt X, v_flt Y, v_flt Z) const override final;
//~ End FVoxelGeneratorInstance Interface
private:
const float NoiseHeight;
const int32 Seed;
FVoxelFastNoise Noise;
};
#endif | 637 |
460 | /**
* Copyright 2015-2017 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 org.wildfly.swarm.jca;
import java.util.HashMap;
import java.util.Map;
import org.wildfly.swarm.config.JCA;
import org.wildfly.swarm.config.jca.ArchiveValidation;
import org.wildfly.swarm.config.jca.BeanValidation;
import org.wildfly.swarm.config.jca.BootstrapContext;
import org.wildfly.swarm.config.jca.CachedConnectionManager;
import org.wildfly.swarm.config.jca.LongRunningThreads;
import org.wildfly.swarm.config.jca.ShortRunningThreads;
import org.wildfly.swarm.config.jca.Workmanager;
import org.wildfly.swarm.spi.api.Fraction;
import org.wildfly.swarm.spi.api.annotations.MarshalDMR;
import org.wildfly.swarm.spi.api.annotations.WildFlyExtension;
/**
* @author <NAME>
*/
@WildFlyExtension(module = "org.jboss.as.connector", classname = "org.jboss.as.connector.subsystems.jca.JcaExtension")
@MarshalDMR
public class JCAFraction extends JCA<JCAFraction> implements Fraction<JCAFraction> {
private static final String DEFAULT = "default";
public static JCAFraction createDefaultFraction() {
return new JCAFraction().applyDefaults();
}
public JCAFraction applyDefaults() {
Map<Object, Object> keepAlive = new HashMap<>();
keepAlive.put("time", 10L);
keepAlive.put("unit", "SECONDS");
archiveValidation(new ArchiveValidation()
.enabled(true)
.failOnError(true)
.failOnWarn(false))
.beanValidation(new BeanValidation()
.enabled(true))
.workmanager(new Workmanager(DEFAULT)
.name(DEFAULT)
.shortRunningThreads(new ShortRunningThreads(DEFAULT)
.coreThreads(50)
.queueLength(50)
.maxThreads(50)
.keepaliveTime(keepAlive))
.longRunningThreads(new LongRunningThreads(DEFAULT)
.coreThreads(50)
.queueLength(50)
.maxThreads(50)
.keepaliveTime(keepAlive)))
.bootstrapContext(new BootstrapContext(DEFAULT)
.workmanager(DEFAULT)
.name(DEFAULT))
.cachedConnectionManager(new CachedConnectionManager().install(true));
return this;
}
}
| 1,771 |
4,071 | <gh_stars>1000+
// Mutex for batching module
//
#pragma once
#include <condition_variable>
#include <mutex>
namespace blaze {
namespace batching {
// A class that wraps around the std::mutex implementation
class mutex : public std::mutex {
public:
mutex() {}
void lock() { std::mutex::lock(); }
bool try_lock() {
return std::mutex::try_lock();
};
void unlock() { std::mutex::unlock(); }
};
class mutex_lock : public std::unique_lock<std::mutex> {
public:
mutex_lock(class mutex& m) : std::unique_lock<std::mutex>(m) {}
mutex_lock(class mutex& m, std::try_to_lock_t t)
: std::unique_lock<std::mutex>(m, t) {}
mutex_lock(mutex_lock&& ml) noexcept
: std::unique_lock<std::mutex>(std::move(ml)) {}
~mutex_lock() {}
};
// Catch bug where variable name is omitted, e.g. mutex_lock (mu);
#define mutex_lock(x) static_assert(0, "mutex_lock_decl_missing_var_name");
using std::condition_variable;
/// 0 timeout; 1 notified
inline int WaitForMilliseconds(mutex_lock* mu,
condition_variable* cv, uint64_t ms) {
std::cv_status s = cv->wait_for(*mu, std::chrono::milliseconds(ms));
return (s == std::cv_status::timeout) ? 0 : 1;
}
} // namespace batching
} // namespace blaze
| 487 |
14,668 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/page_load_metrics/common/test/page_load_metrics_test_util.h"
#include "components/page_load_metrics/common/page_load_metrics_util.h"
using page_load_metrics::OptionalMin;
void PopulateRequiredTimingFields(
page_load_metrics::mojom::PageLoadTiming* inout_timing) {
if (inout_timing->paint_timing->first_meaningful_paint &&
!inout_timing->paint_timing->first_contentful_paint) {
inout_timing->paint_timing->first_contentful_paint =
inout_timing->paint_timing->first_meaningful_paint;
}
if ((inout_timing->paint_timing->first_image_paint ||
inout_timing->paint_timing->first_contentful_paint) &&
!inout_timing->paint_timing->first_paint) {
inout_timing->paint_timing->first_paint =
OptionalMin(inout_timing->paint_timing->first_image_paint,
inout_timing->paint_timing->first_contentful_paint);
}
if (inout_timing->paint_timing->first_paint &&
!inout_timing->paint_timing->first_eligible_to_paint) {
inout_timing->paint_timing->first_eligible_to_paint =
inout_timing->paint_timing->first_paint;
}
if (inout_timing->document_timing->load_event_start &&
!inout_timing->document_timing->dom_content_loaded_event_start) {
inout_timing->document_timing->dom_content_loaded_event_start =
inout_timing->document_timing->load_event_start;
}
if (inout_timing->document_timing->dom_content_loaded_event_start &&
!inout_timing->parse_timing->parse_stop) {
inout_timing->parse_timing->parse_stop =
inout_timing->document_timing->dom_content_loaded_event_start;
}
if (inout_timing->parse_timing->parse_stop &&
!inout_timing->parse_timing->parse_start) {
inout_timing->parse_timing->parse_start =
inout_timing->parse_timing->parse_stop;
}
if (inout_timing->parse_timing->parse_start &&
!inout_timing->response_start) {
inout_timing->response_start = inout_timing->parse_timing->parse_start;
}
if (inout_timing->parse_timing->parse_start) {
if (!inout_timing->parse_timing->parse_blocked_on_script_load_duration)
inout_timing->parse_timing->parse_blocked_on_script_load_duration =
base::TimeDelta();
if (!inout_timing->parse_timing
->parse_blocked_on_script_execution_duration) {
inout_timing->parse_timing->parse_blocked_on_script_execution_duration =
base::TimeDelta();
}
if (!inout_timing->parse_timing
->parse_blocked_on_script_load_from_document_write_duration) {
inout_timing->parse_timing
->parse_blocked_on_script_load_from_document_write_duration =
base::TimeDelta();
}
if (!inout_timing->parse_timing
->parse_blocked_on_script_execution_from_document_write_duration) {
inout_timing->parse_timing
->parse_blocked_on_script_execution_from_document_write_duration =
base::TimeDelta();
}
}
}
// Sets the experimental LCP values to be equal to the non-experimental
// counterparts.
void PopulateExperimentalLCP(page_load_metrics::mojom::PaintTimingPtr& timing) {
timing->experimental_largest_contentful_paint =
timing->largest_contentful_paint->Clone();
}
page_load_metrics::mojom::ResourceDataUpdatePtr CreateResource(
bool was_cached,
int64_t delta_bytes,
int64_t encoded_body_length,
int64_t decoded_body_length,
bool is_complete) {
auto resource_data_update =
page_load_metrics::mojom::ResourceDataUpdate::New();
resource_data_update->cache_type =
was_cached ? page_load_metrics::mojom::CacheType::kHttp
: page_load_metrics::mojom::CacheType::kNotCached;
resource_data_update->delta_bytes = delta_bytes;
resource_data_update->received_data_length = delta_bytes;
resource_data_update->encoded_body_length = encoded_body_length;
resource_data_update->decoded_body_length = decoded_body_length;
resource_data_update->is_complete = is_complete;
return resource_data_update;
}
std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr>
GetSampleResourceDataUpdateForTesting(int64_t resource_size) {
// Prepare 3 resources of varying configurations.
std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr> resources;
// Cached resource.
resources.push_back(CreateResource(true /* was_cached */, 0 /* delta_bytes */,
resource_size /* encoded_body_length */,
resource_size /* decoded_body_length */,
true /* is_complete */));
// Uncached resource.
resources.push_back(CreateResource(
false /* was_cached */, resource_size /* delta_bytes */,
resource_size /* encoded_body_length */,
resource_size /* decoded_body_length */, true /* is_complete */));
// Uncached, unfinished, resource.
resources.push_back(
CreateResource(false /* was_cached */, resource_size /* delta_bytes */,
0 /* encoded_body_length */, 0 /* decoded_body_length */,
false /* is_complete */));
return resources;
}
| 2,151 |
310 | {
"name": "22-802",
"description": "A digital multimeter.",
"url": "https://www.amazon.com/POCKET-RANGING-DIGITAL-MULTIMETER-22-802/dp/B00A3VAB1E"
} | 71 |
9,724 | <gh_stars>1000+
/* poppler-link-extractor-private.h: qt interface to poppler
* Copyright (C) 2007, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _POPPLER_ANNOTATION_PRIVATE_H_
#define _POPPLER_ANNOTATION_PRIVATE_H_
#include "poppler-annotation.h"
namespace Poppler
{
class AnnotationPrivate
{
public:
AnnotationPrivate();
virtual ~AnnotationPrivate();
/* properties: contents related */
QString author;
QString contents;
QString uniqueName;
QDateTime modDate; // before or equal to currentDateTime()
QDateTime creationDate; // before or equal to modifyDate
/* properties: look/interaction related */
int flags;
QRectF boundary;
QLinkedList< Annotation::Revision > revisions;
};
}
#endif
| 499 |
407 | package com.alibaba.tesla.appmanager.server.repository;
import com.alibaba.tesla.appmanager.server.repository.condition.RtComponentInstanceHistoryQueryCondition;
import com.alibaba.tesla.appmanager.server.repository.domain.RtComponentInstanceHistoryDO;
import java.util.List;
public interface RtComponentInstanceHistoryRepository {
long countByCondition(RtComponentInstanceHistoryQueryCondition condition);
int deleteByCondition(RtComponentInstanceHistoryQueryCondition condition);
int insert(RtComponentInstanceHistoryDO record);
List<RtComponentInstanceHistoryDO> selectByCondition(RtComponentInstanceHistoryQueryCondition condition);
RtComponentInstanceHistoryDO getLatestByCondition(RtComponentInstanceHistoryQueryCondition condition);
int updateByCondition(RtComponentInstanceHistoryDO record, RtComponentInstanceHistoryQueryCondition condition);
int deleteExpiredRecords(String componentInstanceId, int instanceKeepDays);
} | 247 |
1,359 | <gh_stars>1000+
package com.kalessil.phpStorm.phpInspectionsEA.inspectors.languageConstructions;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.lang.psi.resolve.types.PhpType;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.ifs.utils.ExpressionCostEstimateUtil;
import com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor;
import com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpInspection;
import com.kalessil.phpStorm.phpInspectionsEA.openApi.PhpLanguageLevel;
import com.kalessil.phpStorm.phpInspectionsEA.utils.*;
import org.jetbrains.annotations.NotNull;
/*
* This file is part of the Php Inspections (EA Extended) package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
public class UnsupportedStringOffsetOperationsInspector extends BasePhpInspection {
private static final String messageOffset = "Could provoke a PHP Fatal error (cannot use string offset as an array).";
private static final String messagePush = "Could provoke a PHP Fatal error ([] operator not supported for strings).";
@NotNull
@Override
public String getShortName() {
return "UnsupportedStringOffsetOperationsInspection";
}
@NotNull
@Override
public String getDisplayName() {
return "Unsupported string offset operations";
}
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new BasePhpElementVisitor() {
@Override
public void visitPhpArrayAccessExpression(@NotNull ArrayAccessExpression expression) {
final Project project = holder.getProject();
if (PhpLanguageLevel.get(project).atLeast(PhpLanguageLevel.PHP710)) {
PsiElement target = null;
String message = null;
boolean isTargetContext = false;
/* context identification phase */
final PsiElement candidate = expression.getValue();
if (
candidate instanceof Variable ||
candidate instanceof FieldReference ||
candidate instanceof ArrayAccessExpression
) {
/* false-positives: pushing to pre-defined globals */
PsiElement possiblyValue = candidate;
while (possiblyValue instanceof ArrayAccessExpression) {
possiblyValue = ((ArrayAccessExpression) possiblyValue).getValue();
}
if (possiblyValue instanceof Variable) {
final String variableName = ((Variable) possiblyValue).getName();
if (ExpressionCostEstimateUtil.predefinedVars.contains(variableName)) {
return;
}
}
final PsiElement parent = expression.getParent();
/* case 1: unsupported casting to array */
if (parent instanceof ArrayAccessExpression) {
message = messageOffset;
target = parent;
while (target.getParent() instanceof ArrayAccessExpression) {
target = target.getParent();
}
PsiElement context = target.getParent();
if (context instanceof AssignmentExpression) {
isTargetContext = ((AssignmentExpression) context).getValue() != target;
} else if (OpenapiTypesUtil.is(context, PhpElementTypes.ARRAY_VALUE)) {
final PsiElement array = context.getParent();
if ((context = array.getParent()) instanceof AssignmentExpression) {
isTargetContext = ((AssignmentExpression) context).getValue() != array;
}
}
}
/* case 2: array push operator is not supported by strings */
else {
final ArrayIndex index = expression.getIndex();
if (index == null || index.getValue() == null) {
final PsiElement context = expression.getParent();
if (context instanceof AssignmentExpression) {
message = messagePush;
target = expression;
isTargetContext = ((AssignmentExpression) context).getValue() != expression;
}
}
}
}
/* type verification and reporting phase */
if (isTargetContext && ExpressionSemanticUtil.getScope(target) != null) {
final PhpType resolved = OpenapiResolveUtil.resolveType((PhpTypedElement) candidate, project);
if (resolved != null) {
final boolean isTarget = resolved.filterUnknown().getTypes().stream().anyMatch(type -> Types.getType(type).equals(Types.strString));
if (isTarget) {
holder.registerProblem(
target,
MessagesPresentationUtil.prefixWithEa(message),
ProblemHighlightType.GENERIC_ERROR
);
}
}
}
}
}
};
}
}
| 3,185 |
329 | //
// DMToolbarButton.h
// DotMail
//
// Created by <NAME> on 6/28/13.
// Copyright (c) 2013 CodaFi Inc. All rights reserved.
//
@interface DMToolbarButton : NSButton
- (instancetype)initWithImage:(NSImage *)image;
- (RACSignal *)rac_selectionSignal;
@end
@interface DMBadgedToolbarButton : DMToolbarButton
- (void)setBadgeCount:(NSUInteger)count;
@end
| 139 |
2,219 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/test/fontconfig_util_linux.h"
#include <fontconfig/fontconfig.h>
#include <memory>
#include "base/base_paths.h"
#include "base/check.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
namespace base {
void SetUpFontconfig() {
FilePath dir_module;
CHECK(PathService::Get(DIR_MODULE, &dir_module));
std::unique_ptr<Environment> env(Environment::Create());
CHECK(env->SetVar("FONTCONFIG_SYSROOT", dir_module.value().c_str()));
}
} // namespace base
| 239 |
1,275 | <reponame>ananthdurai/pinot
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.broker.requesthandler;
import com.google.common.collect.ImmutableSet;
import org.apache.pinot.common.request.BrokerRequest;
import org.apache.pinot.common.request.PinotQuery;
import org.apache.pinot.pql.parsers.Pql2Compiler;
import org.apache.pinot.segment.spi.AggregationFunctionType;
import org.apache.pinot.sql.parsers.CalciteSqlParser;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DistinctCountRewriteTest {
private static final Pql2Compiler PQL_COMPILER = new Pql2Compiler();
@Test
@Deprecated
public void testPql() {
String pql = "SELECT distinctCount(col1) FROM myTable";
BrokerRequest brokerRequest = PQL_COMPILER.compileToBrokerRequest(pql);
BaseBrokerRequestHandler.handleSegmentPartitionedDistinctCountOverride(brokerRequest,
ImmutableSet.of("col2", "col3"));
Assert.assertEquals(brokerRequest.getAggregationsInfo().get(0).getAggregationType().toUpperCase(),
AggregationFunctionType.DISTINCTCOUNT.name());
BaseBrokerRequestHandler.handleSegmentPartitionedDistinctCountOverride(brokerRequest,
ImmutableSet.of("col2", "col3", "col1"));
Assert.assertEquals(brokerRequest.getAggregationsInfo().get(0).getAggregationType().toUpperCase(),
AggregationFunctionType.SEGMENTPARTITIONEDDISTINCTCOUNT.name());
}
@Test
public void testSql() {
String sql = "SELECT distinctCount(col1) FROM myTable";
PinotQuery pinotQuery = CalciteSqlParser.compileToPinotQuery(sql);
BaseBrokerRequestHandler.handleSegmentPartitionedDistinctCountOverride(pinotQuery, ImmutableSet.of("col2", "col3"));
Assert.assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(),
AggregationFunctionType.DISTINCTCOUNT.name());
BaseBrokerRequestHandler.handleSegmentPartitionedDistinctCountOverride(pinotQuery,
ImmutableSet.of("col1", "col2", "col3"));
Assert.assertEquals(pinotQuery.getSelectList().get(0).getFunctionCall().getOperator(),
AggregationFunctionType.SEGMENTPARTITIONEDDISTINCTCOUNT.name());
}
}
| 949 |
852 | <gh_stars>100-1000
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
#include "DataFormats/PatCandidates/interface/Electron.h"
#include "PhysicsTools/SelectorUtils/interface/VersionedIdProducer.h"
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/ESProducer.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "CommonTools/UtilAlgos/interface/ObjectSelector.h"
#include "CommonTools/UtilAlgos/interface/EventSetupInitTrait.h"
#include "RecoEgamma/ElectronIdentification/plugins/ElectronIDSelector.h"
#include "RecoEgamma/ElectronIdentification/plugins/ElectronIDSelectorCutBased.h"
typedef VersionedIdProducer<reco::GsfElectronPtr> VersionedGsfElectronIdProducer;
DEFINE_FWK_MODULE(VersionedGsfElectronIdProducer);
typedef VersionedIdProducer<pat::ElectronPtr> VersionedPatElectronIdProducer;
DEFINE_FWK_MODULE(VersionedPatElectronIdProducer);
typedef ElectronIDSelector<ElectronIDSelectorCutBased> EleIdCutBasedSel;
#include "RecoEgamma/ElectronIdentification/plugins/ElectronIDExternalProducer.h"
typedef ElectronIDExternalProducer<ElectronIDSelectorCutBased> EleIdCutBasedExtProducer;
DEFINE_FWK_MODULE(EleIdCutBasedExtProducer);
typedef ObjectSelector<EleIdCutBasedSel, reco::GsfElectronCollection> EleIdCutBased;
DEFINE_FWK_MODULE(EleIdCutBased);
#include "RecoEgamma/EgammaTools/interface/MVAValueMapProducer.h"
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
#include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h"
typedef MVAValueMapProducer<reco::GsfElectron> ElectronMVAValueMapProducer;
DEFINE_FWK_MODULE(ElectronMVAValueMapProducer);
#include "RecoEgamma/ElectronIdentification/interface/ElectronMVAEstimatorRun2.h"
DEFINE_EDM_PLUGIN(AnyMVAEstimatorRun2Factory, ElectronMVAEstimatorRun2, "ElectronMVAEstimatorRun2");
| 692 |
335 | <filename>I/Indicative_noun.json
{
"word": "Indicative",
"definitions": [
"A verb in the indicative mood.",
"The indicative mood."
],
"parts-of-speech": "Noun"
} | 85 |
2,151 | #!/usr/bin/python2
#
# Copyright 2016 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.
"""Archive corpus file into zip and generate .d depfile.
Invoked by GN from fuzzer_test.gni.
"""
from __future__ import print_function
import argparse
import os
import sys
import warnings
import zipfile
def main():
parser = argparse.ArgumentParser(description="Generate fuzzer config.")
parser.add_argument('corpus_directories', metavar='corpus_dir', type=str,
nargs='+')
parser.add_argument('--output', metavar='output_archive_name.zip',
required=True)
args = parser.parse_args()
corpus_files = []
for directory in args.corpus_directories:
if not os.path.exists(directory):
raise Exception('The given seed_corpus directory (%s) does not exist.' %
directory)
for (dirpath, _, filenames) in os.walk(directory):
for filename in filenames:
full_filename = os.path.join(dirpath, filename)
corpus_files.append(full_filename)
with zipfile.ZipFile(args.output, 'w') as z:
# Turn warnings into errors to interrupt the build: crbug.com/653920.
with warnings.catch_warnings():
warnings.simplefilter("error")
for i, corpus_file in enumerate(corpus_files):
# To avoid duplication of filenames inside the archive, use numbers.
arcname = '%016d' % i
z.write(corpus_file, arcname)
if __name__ == '__main__':
main()
| 579 |
634 | <reponame>halotroop2288/consulo<filename>modules/base/compiler-impl/src/main/java/com/intellij/packaging/impl/elements/LibraryElementType.java
/*
* 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.
*/
package com.intellij.packaging.impl.elements;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.elements.ComplexPackagingElementType;
import com.intellij.packaging.elements.CompositePackagingElement;
import com.intellij.packaging.ui.ArtifactEditorContext;
import com.intellij.util.containers.ContainerUtil;
import consulo.ui.image.Image;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
/**
* @author nik
*/
public class LibraryElementType extends ComplexPackagingElementType<LibraryPackagingElement> {
public static LibraryElementType getInstance() {
return getInstance(LibraryElementType.class);
}
public LibraryElementType() {
super("library", CompilerBundle.message("element.type.name.library.files"));
}
@Nonnull
@Override
public Image getIcon() {
return AllIcons.Nodes.PpLib;
}
@Override
public boolean isAvailableForAdd(@Nonnull ArtifactEditorContext context, @Nonnull Artifact artifact) {
return !getAllLibraries(context).isEmpty();
}
@Nonnull
public List<? extends LibraryPackagingElement> chooseAndCreate(@Nonnull ArtifactEditorContext context, @Nonnull Artifact artifact,
@Nonnull CompositePackagingElement<?> parent) {
final List<Library> selected = context.chooseLibraries(ProjectBundle.message("dialog.title.packaging.choose.library"));
final List<LibraryPackagingElement> elements = new ArrayList<LibraryPackagingElement>();
for (Library library : selected) {
elements.add(new LibraryPackagingElement(library.getTable().getTableLevel(), library.getName(), null));
}
return elements;
}
private static List<Library> getAllLibraries(ArtifactEditorContext context) {
List<Library> libraries = new ArrayList<Library>();
ContainerUtil.addAll(libraries, LibraryTablesRegistrar.getInstance().getLibraryTable().getLibraries());
ContainerUtil.addAll(libraries, LibraryTablesRegistrar.getInstance().getLibraryTable(context.getProject()).getLibraries());
return libraries;
}
@Nonnull
public LibraryPackagingElement createEmpty(@Nonnull Project project) {
return new LibraryPackagingElement();
}
@Override
public String getShowContentActionText() {
return "Show Library Files";
}
}
| 1,059 |
6,098 | <reponame>vishalbelsare/h2o-3<gh_stars>1000+
package water.k8s;
import water.H2O;
import java.util.Collection;
public class H2OApp {
public static void main(String[] args) {
if (H2O.checkUnsupportedJava())
System.exit(1);
if (H2OCluster.isRunningOnKubernetes()) {
Collection<String> nodeIPs = H2OCluster.resolveNodeIPs();
KubernetesEmbeddedConfig config = new KubernetesEmbeddedConfig(nodeIPs);
H2O.setEmbeddedH2OConfig(config);
}
water.H2OApp.start(args, System.getProperty("user.dir"));
}
}
| 274 |
966 | <filename>moe/optimal_learning/cpp/gpp_hyperparameter_optimization_demo.cpp
/*!
\file gpp_hyperparameter_optimization_demo.cpp
\rst
``moe/optimal_learning/cpp/gpp_hyperparameter_optimization_demo.cpp``
This is a demo for the model selection (via hyperparameter optimization) capability
present in this project. These capabilities live in
gpp_model_selection.
In gpp_expected_improvement_demo, we choose the hyperparameters arbitrarily. Here,
we will walk through an example of how one would select hyperparameters for a given
class of covariance function; here, SquareExponential will do. This demo supports:
1. User-specified training data
2. Randomly generated training data (more automatic)
More details on the second case:
1. Choose a set of hyperparameters randomly: source covariance
2. Build a fake\* training set by drawing from a GP with source covariance, at randomly
chosen locations
\* By defining OL_USER_INPUTS to 1, you can specify your own input data.
3. Choose a new random set of hyperparameters and run hyperparameter optimization
a. Show log likelihood using the optimized hyperparameters AND the source hyperparameters
b. observe that with larger training sets, the optimized hyperparameters converge
to the source values; but in smaller sets other optima may exist
Further notes about [newton] optimization performance and robustness are spread throughout the
demo code, placed near the function call/object construction that they are relevant to.
Please read and understand gpp_expected_improvement_demo.cpp before going through
this example. In addition, understanding gpp_model_selection.hpp's
file comments (as well as cpp for devs) is prerequisite.
\endrst*/
#include <cstdio>
#include <vector>
#include <boost/random/uniform_real.hpp> // NOLINT(build/include_order)
#include "gpp_common.hpp"
#include "gpp_covariance.hpp"
#include "gpp_domain.hpp"
#include "gpp_logging.hpp"
#include "gpp_math.hpp"
#include "gpp_model_selection.hpp"
#include "gpp_optimizer_parameters.hpp"
#include "gpp_random.hpp"
#include "gpp_test_utils.hpp"
#define OL_USER_INPUTS 0
using namespace optimal_learning; // NOLINT, i'm lazy in this file which has no external linkage anyway
int main() {
using DomainType = TensorProductDomain;
using HyperparameterDomainType = TensorProductDomain;
// here we set some configurable parameters
// feel free to change them (and recompile) as you explore
// comments next to each parameter will indicate its purpose and domain
// the "spatial" dimension, aka the number of independent (experiment) parameters
// i.e., this is the dimension of the points in points_sampled
static const int dim = 3; // > 0
// number of points that we have already sampled; i.e., size of the training set
static const int num_sampled = 100; // >= 0
// observe that as num_sampled increases, the optimal set of hyperparameters (via optimization) will approach
// the set used to generate the input data (in the case of generating inputs randomly from a GP). Don't try overly
// large values or it will be slow; for reference 500 samples takes ~2-3 min on my laptop whereas 100 samples takes ~1s
// the log likelihoods will also decrease in value since by adding more samples, we are more greatly restricting the GP
// into ever-narrower sets of likely realizations
UniformRandomGenerator uniform_generator(314); // repeatable results
// construct with (base_seed, thread_id) to generate a 'random' seed
// specifies the domain of each independent variable in (min, max) pairs
// set appropriately for user-specified inputs
// mostly irrelevant for randomly generated inputs
std::vector<ClosedInterval> domain_bounds = {
{-1.5, 2.3}, // first dimension
{0.1, 3.1}, // second dimension
{1.7, 2.9}}; // third dimension
DomainType domain(domain_bounds.data(), dim);
// now we allocate point sets; ALL POINTS MUST LIE INSIDE THE DOMAIN!
std::vector<double> points_sampled(num_sampled*dim);
std::vector<double> points_sampled_value(num_sampled);
// default to 0 noise
std::vector<double> noise_variance(num_sampled, 0.0); // each entry must be >= 0.0
// choosing too much noise makes little sense: cannot make useful predicitions if data
// is drowned out by noise
// choosing 0 noise is dangerous for large problems; the covariance matrix becomes very
// ill-conditioned, and adding noise caps the maximum condition number at roughly
// 1.0/min(noise_variance)
// covariance selection
using CovarianceClass = SquareExponential; // see gpp_covariance.hpp for other options
// arbitrary hyperparameters used to generate data
std::vector<double> hyperparameters_original(1 + dim);
CovarianceClass covariance_original(dim, 1.0, 1.0);
// CovarianceClass provides SetHyperparameters, GetHyperparameters to read/modify
// hyperparameters later on
// Generate hyperparameters randomly
boost::uniform_real<double> uniform_double_for_hyperparameter(0.5, 1.5);
FillRandomCovarianceHyperparameters(uniform_double_for_hyperparameter, &uniform_generator,
&hyperparameters_original, &covariance_original);
std::vector<ClosedInterval> hyperparameter_domain_bounds(covariance_original.GetNumberOfHyperparameters(), {1.0e-10, 1.0e10});
HyperparameterDomainType hyperparameter_domain(hyperparameter_domain_bounds.data(),
covariance_original.GetNumberOfHyperparameters());
// now fill data
#if OL_USER_INPUTS == 1
// if you prefer, insert your own data here
// requirements aka variables that must be set:
// noise variance, num_sampled values: defaulted to 0; need to set this for larger data sets to deal with conditioning
// points_sampled, num_sampled*dim values: the locations of already-sampled points; must be INSIDE the domain
// points_sampled_value, num_sampled values: the function values at the already-sampled points
// covariance_perturbed: a CovarianceClass object constructed with perturbed (from covariance_original) hyperparameters;
// must have decltype(covariance_perturbed) == decltype(covariance_original) for hyperparameter opt to make any sense
// NOTE: the GP is 0-mean, so shift your points_sampled_value entries accordingly
// e.g., if the samples are from a function with mean M, subtract it out
#else
// generate GP inputs randomly
// set noise
std::fill(noise_variance.begin(), noise_variance.end(), 1.0e-1); // arbitrary choice
// use latin hypercube sampling to get a reasonable distribution of training point locations
domain.GenerateUniformPointsInDomain(num_sampled, &uniform_generator, points_sampled.data());
// build an empty GP: since num_sampled (last arg) is 0, none of the data arrays will be used here
GaussianProcess gp_generator(covariance_original, points_sampled.data(), points_sampled_value.data(),
noise_variance.data(), dim, 0);
// fill the GP with randomly generated data
FillRandomGaussianProcess(points_sampled.data(), noise_variance.data(), dim, num_sampled,
points_sampled_value.data(), &gp_generator);
// choose a random initial guess reasonably far away from hyperparameters_original
// to find some optima (see WARNING2 below), it may be necessary to start with hyperparameters smaller than the originals or
// of similar magnitude
std::vector<double> hyperparameters_perturbed(covariance_original.GetNumberOfHyperparameters());
CovarianceClass covariance_perturbed(dim, 1.0, 1.0);
boost::uniform_real<double> uniform_double_for_wrong_hyperparameter(5.0, 12.0);
FillRandomCovarianceHyperparameters(uniform_double_for_wrong_hyperparameter, &uniform_generator,
&hyperparameters_perturbed, &covariance_perturbed);
#endif
// log likelihood type selection
using LogLikelihoodEvaluator = LogMarginalLikelihoodEvaluator;
// log likelihood evaluator object
LogLikelihoodEvaluator log_marginal_eval(points_sampled.data(), points_sampled_value.data(),
noise_variance.data(), dim, num_sampled);
int total_newton_errors = 0; // number of newton runs that failed due to singular hessians
int newton_max_num_steps = 500; // max number of newton steps
double gamma_newton = 1.05; // newton diagonal dominance scale-down factor (see newton docs for details)
double pre_mult_newton = 1.0e-1; // newton diagonal dominance scaling factor (see newton docs for details)
double max_relative_change_newton = 1.0;
double tolerance_newton = 1.0e-11;
NewtonParameters newton_parameters(1, newton_max_num_steps, gamma_newton, pre_mult_newton,
max_relative_change_newton, tolerance_newton);
// call newton to optimize hyperparameters
// in general if this takes the full hyperparameter_max_num_steps iterations, something went wrong
// newton's solution:
std::vector<double> new_newton_hyperparameters(covariance_original.GetNumberOfHyperparameters());
printf(OL_ANSI_COLOR_CYAN "ORIGINAL HYPERPARMETERS:\n" OL_ANSI_COLOR_RESET);
printf("Original Hyperparameters:\n");
PrintMatrix(hyperparameters_original.data(), 1, covariance_original.GetNumberOfHyperparameters());
printf(OL_ANSI_COLOR_CYAN "NEWTON OPTIMIZED HYPERPARAMETERS:\n" OL_ANSI_COLOR_RESET);
// run newton optimization
total_newton_errors += NewtonHyperparameterOptimization(log_marginal_eval, covariance_perturbed,
newton_parameters, hyperparameter_domain,
new_newton_hyperparameters.data());
// WARNING: the gradient of log marginal appears to go to 0 as you move toward infinity. if you do not start
// close enough to an optima or have overly aggressive diagonal dominance settings, newton will skip miss everything
// going on locally and shoot out to these solutions.
// Having hyperparameters = 1.0e10 is nonsense, and usually this problem is further signaled by a log marginal likelihood
// that is POSITIVE (impossible since p \in [0,1], so log(p) \in (-\infty, 0])
// Long-term, we should solve this problem by multistarting newton. Additionally there will be some kind of "quick kill"
// mechanism needed--when newton is wandering down the wrong path (or to an already-known solution?) we should detect it
// and kill it quickly to keep cost low.
// For now, just play around with different initial conditions or more conservative gamam settings.
// WARNING2: for small num_sampled, it often appears that the solution becomes independent of one or more hyperparameters.
// e.g., in 2D, we'd have an optimal "ridge." Finding this robustly requires starting near it, so the random choice of
// initial conditions can fail horribly in general.
// WARNING3: if you choose large values of num_sampled (like 300), this can be quite slow; about 5min on my computer
// sometimes the reason is that machine prescision prevents us from reaching the cutoff criterion:
// norm_gradient_likelihood <= 1.0e-13 in NewtonHyperparameterOptimization() in gpp_model_selection...cpp
// So you may need to relax this to 1.0e-10 or something so that we aren't just spinning wheels at almost-converged but
// unable to actually move anywhere.
printf("Result of newton:\n");
PrintMatrix(new_newton_hyperparameters.data(), 1, covariance_original.GetNumberOfHyperparameters());
if (total_newton_errors > 0) {
printf("WARNING: %d newton runs exited due to singular Hessian matrices.\n", total_newton_errors);
}
printf(OL_ANSI_COLOR_CYAN "LOG LIKELIHOOD + GRADIENT AT NEWTON OPTIMIZED FINAL HYPERPARAMS:\n" OL_ANSI_COLOR_RESET);
CovarianceClass covariance_final(dim, new_newton_hyperparameters[0], new_newton_hyperparameters.data() + 1);
typename LogLikelihoodEvaluator::StateType log_marginal_state_newton_optimized_hyper(log_marginal_eval,
covariance_final);
double newton_log_marginal_opt = log_marginal_eval.ComputeLogLikelihood(log_marginal_state_newton_optimized_hyper);
printf("newton optimized log marginal likelihood = %.18E\n", newton_log_marginal_opt);
std::vector<double> grad_log_marginal_opt(covariance_final.GetNumberOfHyperparameters());
log_marginal_eval.ComputeGradLogLikelihood(&log_marginal_state_newton_optimized_hyper,
grad_log_marginal_opt.data());
printf("grad log likelihood: ");
PrintMatrix(grad_log_marginal_opt.data(), 1, covariance_final.GetNumberOfHyperparameters());
printf(OL_ANSI_COLOR_CYAN "LOG LIKELIHOOD + GRADIENT AT ORIGINAL HYPERPARAMS:\n" OL_ANSI_COLOR_RESET);
typename LogLikelihoodEvaluator::StateType log_marginal_state_original_hyper(log_marginal_eval,
covariance_original);
double original_log_marginal = log_marginal_eval.ComputeLogLikelihood(log_marginal_state_original_hyper);
printf("original log marginal likelihood = %.18E\n", original_log_marginal);
std::vector<double> original_grad_log_marginal(covariance_original.GetNumberOfHyperparameters());
log_marginal_eval.ComputeGradLogLikelihood(&log_marginal_state_original_hyper,
original_grad_log_marginal.data());
printf("grad log likelihood: ");
PrintMatrix(original_grad_log_marginal.data(), 1, covariance_original.GetNumberOfHyperparameters());
return 0;
} // end main
| 4,465 |
2,592 | <reponame>gregorburger/glad
from glad.lang.common.loader import BaseLoader
from glad.lang.c.loader import LOAD_OPENGL_DLL, LOAD_OPENGL_DLL_H, LOAD_OPENGL_GLAPI_H
_GLX_LOADER = \
LOAD_OPENGL_DLL % {'pre':'static', 'init':'open_glx',
'proc':'get_proc', 'terminate':'close_glx'} + '''
int gladLoadGLX(Display *dpy, int screen) {
int status = 0;
if(open_glx()) {
status = gladLoadGLXLoader((GLADloadproc)get_proc, dpy, screen);
}
return status;
}
void gladUnloadGLX(void) {
close_glx();
}
'''
_GLX_HEADER_START = '''
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
'''
#include <glad/glad.h>
_WGL_HEADER_MID = '''
#ifndef __glad_glxext_h_
#ifdef __glxext_h_
#error GLX header already included, remove this include, glad already provides it
#endif
#define __glad_glxext_h_
#define __glxext_h_
#ifndef APIENTRY
#define APIENTRY
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef void* (* GLADloadproc)(const char *name);
''' + LOAD_OPENGL_GLAPI_H
_GLX_HEADER_LOADER = '''
GLAPI int gladLoadGLX(Display *dpy, int screen);
GLAPI void gladUnloadGLX(void);
''' + LOAD_OPENGL_DLL_H
_GLX_HEADER_END = '''
#ifdef __cplusplus
}
#endif
#endif
'''
_GLX_HAS_EXT = '''
static Display *GLADGLXDisplay = 0;
static int GLADGLXscreen = 0;
static int get_exts(void) {
return 1;
}
static void free_exts(void) {
return;
}
static int has_ext(const char *ext) {
const char *terminator;
const char *loc;
const char *extensions;
if(!GLAD_GLX_VERSION_1_1)
return 0;
extensions = glXQueryExtensionsString(GLADGLXDisplay, GLADGLXscreen);
if(extensions == NULL || ext == NULL)
return 0;
while(1) {
loc = strstr(extensions, ext);
if(loc == NULL)
break;
terminator = loc + strlen(ext);
if((loc == extensions || *(loc - 1) == ' ') &&
(*terminator == ' ' || *terminator == '\\0'))
{
return 1;
}
extensions = terminator;
}
return 0;
}
'''
class GLXCLoader(BaseLoader):
def write(self, fobj):
if not self.disabled:
fobj.write(_GLX_LOADER)
def write_begin_load(self, fobj):
fobj.write('\tglXQueryVersion = (PFNGLXQUERYVERSIONPROC)load("glXQueryVersion");\n')
fobj.write('\tif(glXQueryVersion == NULL) return 0;\n')
def write_end_load(self, fobj):
fobj.write('\treturn 1;\n')
def write_find_core(self, fobj):
fobj.write('\tint major = 0, minor = 0;\n')
fobj.write('\tif(dpy == 0 && GLADGLXDisplay == 0) {\n')
fobj.write('\t\tdpy = XOpenDisplay(0);\n')
fobj.write('\t\tscreen = XScreenNumberOfScreen(XDefaultScreenOfDisplay(dpy));\n')
fobj.write('\t} else if(dpy == 0) {\n')
fobj.write('\t\tdpy = GLADGLXDisplay;\n')
fobj.write('\t\tscreen = GLADGLXscreen;\n')
fobj.write('\t}\n')
fobj.write('\tglXQueryVersion(dpy, &major, &minor);\n')
fobj.write('\tGLADGLXDisplay = dpy;\n')
fobj.write('\tGLADGLXscreen = screen;\n')
def write_has_ext(self, fobj):
fobj.write(_GLX_HAS_EXT)
def write_header(self, fobj):
fobj.write(_GLX_HEADER_START)
if self.local_files:
fobj.write('#include "glad.h"\n')
else:
fobj.write('#include <glad/glad.h>\n')
fobj.write(_WGL_HEADER_MID)
if not self.disabled:
fobj.write(_GLX_HEADER_LOADER)
def write_header_end(self, fobj):
fobj.write(_GLX_HEADER_END)
| 1,752 |
788 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.usergrid.persistence.core.guicyfig;
import java.lang.annotation.Annotation;
import org.safehaus.guicyfig.Bypass;
import org.safehaus.guicyfig.Env;
import org.safehaus.guicyfig.GuicyFig;
import org.safehaus.guicyfig.Option;
public class SetConfigTestBypass {
/**
* Set the value bypass on the guicyfig
* @param guicyFig
* @param methodName
* @param valueToSet
*/
public static void setValueByPass(final GuicyFig guicyFig, final String methodName, final String valueToSet){
guicyFig.setBypass( new TestByPass( methodName, valueToSet ) );
}
/**
* Test bypass that sets all environments to use the timeout of 1 second
*/
public static final class TestByPass implements Bypass {
private Option[] options;
public TestByPass( final String methodName, final String value ) {
options = new Option[] { new TestOption( methodName, value ) };
}
@Override
public Option[] options() {
return options;
}
@Override
public Env[] environments() {
return new Env[] { Env.ALL, Env.UNIT };
}
@Override
public Class<? extends Annotation> annotationType() {
return Bypass.class;
}
}
/**
* TestOption
*/
public static final class TestOption implements Option {
private final String methodName;
private final String valueToReturn;
public TestOption( final String methodName, final String valueToReturn ) {
this.methodName = methodName;
this.valueToReturn = valueToReturn;
}
@Override
public Class<? extends Annotation> annotationType() {
return Bypass.class;
}
@Override
public String method() {
return methodName;
}
@Override
public String override() {
return valueToReturn;
}
}
}
| 1,016 |
534 | package mekanism.common.content.network.transmitter;
import javax.annotation.Nonnull;
import mekanism.api.tier.AlloyTier;
import mekanism.api.tier.ITier;
import mekanism.common.upgrade.transmitter.TransmitterUpgradeData;
public interface IUpgradeableTransmitter<DATA extends TransmitterUpgradeData> {
DATA getUpgradeData();
boolean dataTypeMatches(@Nonnull TransmitterUpgradeData data);
void parseUpgradeData(@Nonnull DATA data);
ITier getTier();
default boolean canUpgrade(AlloyTier alloyTier) {
return alloyTier.getBaseTier().ordinal() == getTier().getBaseTier().ordinal() + 1;
}
} | 199 |
2,406 | <reponame>pazamelin/openvino
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "legacy/transformations/convert_opset1_to_legacy/convert_pad_to_pad_ie.hpp"
#include <memory>
#include <vector>
#include <ngraph/opsets/opset1.hpp>
#include <ngraph/rt_info.hpp>
#include <ngraph/pattern/op/wrap_type.hpp>
NGRAPH_RTTI_DEFINITION(ngraph::pass::ConvertPadToLegacyMatcher, "ConvertPadToLegacyMatcher", 0);
ngraph::pass::ConvertPadToLegacyMatcher::ConvertPadToLegacyMatcher() {
auto m_pad = ngraph::pattern::wrap_type<ngraph::opset1::Pad>(pattern::has_static_shape());
ngraph::matcher_pass_callback callback = [](pattern::Matcher& m) {
auto pad = std::dynamic_pointer_cast<ngraph::opset1::Pad> (m.get_match_root());
if (!pad) {
return false;
}
auto pad_ie = std::make_shared<ngraph::op::PadIE>(pad);
pad_ie->set_friendly_name(pad->get_friendly_name());
ngraph::copy_runtime_info(pad, pad_ie);
ngraph::replace_node(pad, pad_ie);
return true;
};
auto m = std::make_shared<ngraph::pattern::Matcher>(m_pad, "ConvertPadToLegacy");
this->register_matcher(m, callback);
}
| 508 |
394 | //-------------------------------------------------------------------------------------
// UVAtlas - SymmetricMatrix.hpp
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkID=512686
//-------------------------------------------------------------------------------------
#pragma once
namespace Isochart
{
#ifdef UVATLAS_USE_EIGEN
template<class TYPE>
class CSymmetricMatrix
{
public:
using value_type = TYPE;
_Success_(return)
static bool
GetEigen(
size_t dwDimension,
_In_reads_(dwDimension* dwDimension) const value_type* pMatrix,
_Out_writes_(dwMaxRange) value_type* pEigenValue,
_Out_writes_(dwDimension* dwMaxRange) value_type* pEigenVector,
size_t dwMaxRange,
float epsilon = 1e-10f)
{
// Check arguments.
if (!pMatrix || !pEigenValue || !pEigenVector)
return false;
if (dwDimension < dwMaxRange
|| dwMaxRange == 0
|| dwDimension == 0)
{
return false;
}
using EigenMatrix = Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>;
Eigen::Map<const EigenMatrix> matrix(pMatrix, static_cast<long>(dwDimension), static_cast<long>(dwDimension));
Eigen::Map<EigenMatrix> eigenvalues(pEigenValue, static_cast<long>(dwMaxRange), 1);
Eigen::Map<EigenMatrix> eigenvectors(pEigenVector, static_cast<long>(dwDimension), static_cast<long>(dwMaxRange));
// If we don't want every eigenvalue, try solving with Spectra first.
if (dwMaxRange < dwDimension)
{
try
{
constexpr int maxIterations = 1000; // Spectra's default
// Construct matrix operation object using the wrapper class DenseSymMatProd.
Spectra::DenseSymMatProd<value_type> op(matrix);
// Construct eigen solver object, requesting the largest dwMaxRange eigenvalues
Spectra::SymEigsSolver< Spectra::DenseSymMatProd<value_type> > eigs(
op,
static_cast<int>(dwMaxRange),
// Convergence speed, higher is faster with more memory usage, recommended to be at least 2x nev, must be <= dimension.
static_cast<int>(std::min(dwMaxRange * 2, dwDimension))
);
eigs.init();
auto const numConverged = eigs.compute(
Spectra::SortRule::LargestAlge, // Sort by descending eigenvalues.
maxIterations,
epsilon
);
if (numConverged >= static_cast<int>(dwMaxRange) && eigs.info() == Spectra::CompInfo::Successful)
{
eigenvalues = eigs.eigenvalues();
eigenvectors = eigs.eigenvectors();
return true;
}
else
{
DPF(0, "Spectra::SymEigsSolver failed with info() == %d, numConverged == %d, dwDimension == %d, dwMaxRange == %d", eigs.info(), numConverged, dwDimension, dwMaxRange);
}
}
catch (const std::exception& ex)
{
DPF(0, "Spectra::SymEigsSolver threw an exception with what() == \"%s\", dwDimension == %d, dwMaxRange == %d", ex.what(), dwDimension, dwMaxRange);
}
}
// Otherwise, fallback to Eigen built-in solver.
const Eigen::SelfAdjointEigenSolver<EigenMatrix> eigenSolver(matrix);
if (eigenSolver.info() == Eigen::ComputationInfo::Success)
{
// We want the eigenvalues in descending order, Eigen produces them in increasing order.
eigenvalues = eigenSolver.eigenvalues().reverse().head(static_cast<long>(dwMaxRange));
eigenvectors = eigenSolver.eigenvectors().rowwise().reverse().leftCols(static_cast<long>(dwMaxRange));
return true;
}
else
{
DPF(0, "Eigen::SelfAdjointEigenSolver failed with info() == %d", eigenSolver.info());
}
return false;
}
};
#else // !UVATLAS_USE_EIGEN
// This file implement the algorithm in "Numerical Recipes in Fortan 77,
// The Art of Scientific Computing Second Edition", Section 11.1 ~ 11.3
// http://www.library.cornell.edu/nr/bookfpdf/f11-1.pdf
// http://www.library.cornell.edu/nr/bookfpdf/f11-2.pdf
// http://www.library.cornell.edu/nr/bookfpdf/f11-3.pdf
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdouble-promotion"
#endif
template<class TYPE>
class CSymmetricMatrix
{
public:
using value_type = TYPE;
private:
static inline value_type VectorDot(
const value_type v1[],
const value_type v2[],
size_t dwDimension)
{
value_type result = 0;
for (size_t ii = 0; ii < dwDimension; ii++)
{
result += v1[ii] * v2[ii];
}
return result;
}
static inline void VectorScale(
value_type v[],
value_type scale,
size_t dwDimension)
{
assert(std::isfinite(double(scale)));
for (size_t ii = 0; ii < dwDimension; ii++)
{
v[ii] *= scale;
}
}
static inline void VectorZero(
value_type v[],
size_t dwDimension)
{
memset(v, 0, dwDimension * sizeof(value_type));
}
static inline void VectorAssign(
value_type dest[],
const value_type src[],
size_t dwDimension)
{
memcpy(dest, src, dwDimension * sizeof(value_type));
}
public:
_Success_(return)
static bool
GetEigen(
size_t dwDimension,
_In_reads_(dwDimension * dwDimension) const value_type* pMatrix,
_Out_writes_(dwMaxRange) value_type* pEigenValue,
_Out_writes_(dwDimension * dwMaxRange) value_type* pEigenVector,
size_t dwMaxRange,
value_type epsilon = 1.0e-6f)
{
// 1. check argument
if (!pMatrix || !pEigenValue || !pEigenVector)
return false;
if (dwDimension < dwMaxRange
|| dwMaxRange == 0
|| dwDimension == 0)
{
return false;
}
// 2. allocate memory resouce
std::unique_ptr<value_type[]> tmp(new (std::nothrow) value_type[(dwDimension * dwDimension) + (4 * dwDimension)]);
if (!tmp)
return false;
value_type* pInitialMatrix = tmp.get(); // dwDimension * dwDimension
value_type* pSubDiagVec = pInitialMatrix + (dwDimension * dwDimension); // dwDimension
value_type* pU = pSubDiagVec + dwDimension; // dwDimension
value_type* pP = pU + dwDimension; // dwDimension
value_type* pValues = pP + dwDimension; // dwDimension
std::unique_ptr<value_type * []> rowHeader(new (std::nothrow) value_type * [dwDimension]);
if (!rowHeader)
return false;
value_type** pRowHeader = rowHeader.get();
VectorZero(pSubDiagVec, dwDimension);
VectorAssign(pInitialMatrix, pMatrix, dwDimension * dwDimension);
for (size_t i = 0; i < dwDimension; i++)
{
pRowHeader[i] = pInitialMatrix + i * dwDimension;
}
// 3. Using Householder method to reduction to tridiagonal matrix
// 3.1 Prepare u vector of first iteration.
memcpy(pU, pRowHeader[dwDimension - 1], dwDimension * sizeof(value_type));
for (size_t i = dwDimension - 1; i > 0; i--)
{
value_type total = 0;
value_type h = 0;
for (size_t j = 0; j < i; j++)
{
total += static_cast<value_type>(fabs(pU[j]));
}
if (total < epsilon)
{
// prepare u of next iteration, skip this step
pU[i] = 0;
for (size_t j = 0; j < i; j++)
{
pU[j] = pRowHeader[i - 1][j];
pRowHeader[i][j] = 0;
pRowHeader[j][i] = 0;
}
}
else
{
value_type scale = 1.0f / total;
VectorScale(pU, scale, i);
h = VectorDot(pU, pU, i);
//value_type shift = pValues[i - 1];
auto g = (pU[i - 1] < 0) ? value_type(-IsochartSqrt(h)) : value_type(IsochartSqrt(h));
pSubDiagVec[i] = -(total * g); // i element of sub-diagonal vector
h += pU[i - 1] * g; // h = |u|*|u|/2
pU[i - 1] += g; // u(i-1) = u(i-1) + |g|
VectorZero(pP, i);
// compute p = A * u / H, Used property of symmetric Matrix
for (size_t j = 0; j < i; j++)
{
pRowHeader[j][i] = pU[j];
pP[j] += pRowHeader[j][j] * pU[j];
for (size_t k = 0; k < j; k++)
{
pP[j] += pRowHeader[j][k] * pU[k];
pP[k] += pRowHeader[j][k] * pU[j];
}
}
VectorScale(pP, 1.0f / h, i);
// compute K = u'* p / (2*H)
value_type up = VectorDot(pU, pP, i);
value_type K = up / (h + h);
// compute q = p - K * u, store q into p for p will not be used
// any more.
for (size_t j = 0; j < i; j++)
{
pP[j] -= K * pU[j];
}
// compute A` = A - q * u' - u * q', only need to compute lower
// triangle
for (size_t j = 0; j < i; j++)
{
for (size_t k = j; k < i; k++)
{
pRowHeader[k][j] -= (pP[k] * pU[j] + pP[j] * pU[k]);
if (fabs(pRowHeader[k][j]) < epsilon)
{
pRowHeader[k][j] = 0;
}
}
}
// prepare u vector for next iteration
for (size_t j = 0; j < i; j++)
{
pU[j] = pRowHeader[i - 1][j];
pRowHeader[i][j] = 0.0;
}
}
// After i iteration, pU[i] will never used in u vector, so store H of
// this iteration in it.
pU[i] = h;
}
// Q = P(0) * P(1) * p(2) * * * p(n-1)
// Q(n-1) = P(n-1)
// Q(n-2) = P(n-2) * Q(n-1)
// ......
// Q(0) = Q = P(0) * Q(1)
// Here used :
//P*Q = ( 1 - u* u'/H)Q
//= Q - u * u' * Q / H ( 2n*n multiplication )
//= Q - (u/H) * (u' * Q); ( n*n +n multiplication )
for (size_t i = 0; i < dwDimension - 1; i++)
{
pValues[i] = pRowHeader[i][i];
pRowHeader[i][i] = 1.0;
size_t currentDim = i + 1;
if (fabs(pU[currentDim]) > epsilon)
{
//Q - (u/H) * (u' * Q); ( n*n +n multiplication )
for (size_t j = 0; j < currentDim; j++)
{
value_type delta = 0.0;
for (size_t k = 0; k < currentDim; k++)
{
delta += pRowHeader[k][j] * pRowHeader[k][currentDim];
}
for (size_t k = 0; k <= i; k++)
{
pRowHeader[k][j] -=
delta *
pRowHeader[k][currentDim]
/ pU[currentDim];
}
}
}
for (size_t k = 0; k <= i; k++)
{
pRowHeader[k][currentDim] = 0;
}
}
pValues[dwDimension - 1] = pRowHeader[dwDimension - 1][dwDimension - 1];
pRowHeader[dwDimension - 1][dwDimension - 1] = 1;
VectorZero(pRowHeader[dwDimension - 1], dwDimension - 1);
// 2. Symmetric tridiagonal QL algorithm.
// 2.1 For Convience, renumber the element of subdiagal vector
memmove(
pSubDiagVec, pSubDiagVec + 1,
(dwDimension - 1) * sizeof(value_type));
pSubDiagVec[dwDimension - 1] = 0;
value_type shift = 0;
value_type maxv = 0;
// 2.2 QL iteration Algorithm.
for (size_t j = 0; j < dwDimension; j++)
{
// 2.2.1 Find a small subdiagonal element to split the matrix
auto temp = value_type(fabs(pValues[j]) + fabs(pSubDiagVec[j]));
if (maxv < temp)
{
maxv = temp;
}
// Iteration to zero the subdiagal item e[j]
for (;;)
{
size_t n;
for (n = j; n < dwDimension; n++)
{
if (fabs(pSubDiagVec[n]) <= epsilon * maxv)
{
break;
}
}
// e[j] already equals to 0, get eigenvalue d[j] by adding back
// shift value.
if (n == j)
{
pValues[j] = pValues[j] + shift;
pSubDiagVec[j] = 0.0;
break;
}
// A plane rotation as Original OL, followed by n-j-2 Given rotations to
// restore tridiagonal form
else
{
// Estimate the shift value by comptuing the eigenvalues of leading
// 2-dimension matrix. Usually, we get 2 eigenvalues, use the one
// close to pValues[j]
value_type a = 1;
value_type b = -(pValues[j] + pValues[j + 1]);
value_type c =
pValues[j] * pValues[j + 1]
- pSubDiagVec[j] * pSubDiagVec[j];
auto bc = value_type(IsochartSqrt(b * b - 4 * a * c));
value_type ks = (-b + bc) / 2;
value_type ks1 = (-b - bc) / 2;
if (fabs(pValues[j] - ks) >
fabs(pValues[j] - ks1))
{
ks = ks1;
}
// Shift original matrix.
for (size_t k = j; k < dwDimension; k++)
{
pValues[k] -= ks;
}
// Record the totoal shift value.
shift = shift + ks;
value_type extra;
value_type lastqq;
value_type lastpp;
value_type lastpq;
value_type lastC;
value_type lastS;
// "Jacobi Rotation" at P(n-1, n)
// C = d(n) / (d(n)^2 + e(n-1)^2)
// S = e(n-1) / (d(n)^2 + e(n-1)^2)
auto tt = value_type(IsochartSqrt(
pValues[n] * pValues[n] +
pSubDiagVec[n - 1] * pSubDiagVec[n - 1]));
lastC = pValues[n] / tt;
lastS = pSubDiagVec[n - 1] / tt;
lastqq =
lastS * lastS * pValues[n - 1]
+ lastC * lastC * pValues[n]
+ 2 * lastS * lastC * pSubDiagVec[n - 1];
lastpp =
lastS * lastS * pValues[n]
+ lastC * lastC * pValues[n - 1]
- 2 * lastS * lastC * pSubDiagVec[n - 1];
lastpq =
(lastC * lastC - lastS * lastS) * pSubDiagVec[n - 1]
+ lastS * lastC * (pValues[n - 1] - pValues[n]);
// Because d[n-1], e[n-1] will continue to be changed in next
// step, only change d[n] here
pValues[n] = value_type(lastqq);
// Multiply current rotoation matrix to the finial orthogonal matrix,
//which stores the eigenvectors
for (size_t l = 0; l < dwDimension; l++)
{
value_type tempItem = pRowHeader[l][n];
pRowHeader[l][n] = value_type(
lastS * pRowHeader[l][n - 1]
+ lastC * tempItem);
pRowHeader[l][n - 1] = value_type(
lastC * pRowHeader[l][n - 1]
- lastS * tempItem);
}
// If need restore tridiagonal form
if (n > j + 1)
{
// Each step, generate a Given rotation matrix to decrease
// the "extra" item.
// Each step, e[next+1] and d[next+1] can be decided.
// Each step, compute a new "extra" value.
extra = lastS * pSubDiagVec[n - 2];
assert(n > 1);
size_t next;
for (size_t k = n - 1; k > j; k--)
{
next = k - 1;
pSubDiagVec[next] = value_type(lastC * pSubDiagVec[next]);
tt = value_type(IsochartSqrt(lastpq * lastpq + extra * extra));
lastC = lastpq / tt;
lastS = extra / tt;
pSubDiagVec[next + 1] = value_type(lastC * lastpq + lastS * extra);
pValues[next + 1] = value_type(
lastS * lastS * pValues[next]
+ lastC * lastC * lastpp
+ 2 * lastS * lastC * pSubDiagVec[next]);
lastpq =
(lastC * lastC - lastS * lastS) * pSubDiagVec[next]
+ lastS * lastC * (pValues[next] - lastpp);
lastpp =
lastS * lastS * lastpp
+ lastC * lastC * pValues[next]
- 2 * lastS * lastC * pSubDiagVec[next];
if (next > 0)
extra = lastS * pSubDiagVec[next - 1];
for (size_t l = 0; l < dwDimension; l++)
{
value_type tempItem = pRowHeader[l][next + 1];
pRowHeader[l][next + 1] = value_type(
lastS * pRowHeader[l][next]
+ lastC * tempItem);
pRowHeader[l][next] = value_type(
lastC * pRowHeader[l][next]
- lastS * tempItem);
}
}
}
// Last step.
pValues[j] = value_type(lastpp);
pSubDiagVec[j] = value_type(lastpq);
if (n < dwDimension)
{
pSubDiagVec[n] = 0.0;
}
}
}
}
// Sort eigenvalues and corresponding vectors.
for (size_t i = 0; i < dwDimension - 1; i++)
{
for (size_t j = i + 1; j < dwDimension; j++)
{
if (pValues[j] > pValues[i])
{
std::swap(pValues[i], pValues[j]);
for (size_t k = 0; k < dwDimension; k++)
{
std::swap(pRowHeader[k][i], pRowHeader[k][j]);
}
}
}
}
// Export the selected eigen values and vectors
for (size_t i = 0; i < dwMaxRange; i++)
{
pEigenValue[i] = pValues[i];
for (size_t j = 0; j < dwDimension; j++)
{
pEigenVector[i * dwDimension + j] = pRowHeader[j][i];
}
}
return true;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif
}
| 14,693 |
513 | /*
** C data arithmetic.
** Copyright (C) 2005-2017 <NAME>. See Copyright Notice in luajit.h
*/
#ifndef _LJ_CARITH_H
#define _LJ_CARITH_H
#include "lj_obj.h"
#if LJ_HASFFI
LJ_FUNC int lj_carith_op(lua_State *L, MMS mm);
#if LJ_32 && LJ_HASJIT
LJ_FUNC int64_t lj_carith_mul64(int64_t x, int64_t k);
#endif
LJ_FUNC uint64_t lj_carith_divu64(uint64_t a, uint64_t b);
LJ_FUNC int64_t lj_carith_divi64(int64_t a, int64_t b);
LJ_FUNC uint64_t lj_carith_modu64(uint64_t a, uint64_t b);
LJ_FUNC int64_t lj_carith_modi64(int64_t a, int64_t b);
LJ_FUNC uint64_t lj_carith_powu64(uint64_t x, uint64_t k);
LJ_FUNC int64_t lj_carith_powi64(int64_t x, int64_t k);
#endif
#endif
| 359 |
476 | <filename>test/test_statistics.py
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import warnings
from itertools import product
import math
import random
import pytest
from asv.util import inf
import asv.statistics as statistics
try:
import numpy as np
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
try:
from scipy import integrate, special, stats
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
try:
from rpy2 import robjects
HAS_RPY2 = True
except ImportError:
HAS_RPY2 = False
@pytest.mark.skipif(not HAS_NUMPY, reason="Requires numpy")
def test_compute_stats():
np.random.seed(1)
assert statistics.compute_stats([], 1) == (None, None)
assert statistics.compute_stats([15.0], 1) == (
15.0, {'ci_99_a': -inf, 'ci_99_b': inf,
'number': 1, 'q_25': 15.0, 'q_75': 15.0, 'repeat': 1})
for nsamples, true_mean in product([10, 50, 250], [0, 0.3, 0.6]):
samples = np.random.randn(nsamples) + true_mean
result, stats = statistics.compute_stats(samples, 42)
assert stats['repeat'] == len(samples)
assert stats['number'] == 42
assert np.allclose(stats['q_25'], np.percentile(samples, 25))
assert np.allclose(stats['q_75'], np.percentile(samples, 75))
assert np.allclose(result, np.median(samples))
ci = stats['ci_99_a'], stats['ci_99_b']
assert ci[0] <= true_mean <= ci[1]
w = 12.0 * np.std(samples) / np.sqrt(len(samples))
assert ci[1] - ci[0] < w
err = statistics.get_err(result, stats)
iqr = np.percentile(samples, 75) - np.percentile(samples, 25)
assert np.allclose(err, iqr/2)
@pytest.mark.skipif(not HAS_NUMPY, reason="Requires numpy")
def test_is_different():
np.random.seed(1)
# Smoke test is_different
for true_mean, n, significant in [(0.01, 10, False), (0.05, 100, True), (0.1, 10, True)]:
samples_a = 0 + 0.1 * np.random.rand(n)
samples_b = true_mean + 0.1 * np.random.rand(n)
result_a, stats_a = statistics.compute_stats(samples_a, 1)
result_b, stats_b = statistics.compute_stats(samples_b, 1)
assert statistics.is_different(None, None, stats_a, stats_b) == significant
assert statistics.is_different(samples_a, samples_b, stats_a, stats_b) == significant
def _check_ci(estimator, sampler, nsamples=300):
"""
Check whether confidence behaves as advertized.
Draw random samples from a distribution and check how often the
true value (assumed 0) falls in the estimated CI.
Parameters
----------
ci_estimator : callable(samples, alpha)
Estimator returning ``(m, (a, b))`` for coverage alpha,
for the estimate ``m`` and CI ``(a, b)``
sampler : callable(size)
Draw samples from a distribution with zero value for the true
location parameter.
nsamples : int, optional
Number of samples to draw
Yields
------
size, alpha, alpha_got
"""
alphas = [0.5, 0.1, 0.01]
sizes = [2, 5, 10, 30, 100]
for size, alpha in product(sizes, alphas):
samples = []
for k in range(nsamples):
z = sampler(size)
m, ci = estimator(z, alpha)
a, b = ci
assert a <= m <= b
samples.append(a <= 0 <= b)
alpha_got = 1 - sum(samples) / len(samples)
yield size, alpha, alpha_got
@pytest.mark.skipif(not HAS_NUMPY, reason="Requires numpy")
def test_quantile_ci():
# Test the confidence intervals
scale = 2.5
def sample_exp(size):
z = np.random.exponential(scale, size=size)
z *= 2 * np.random.randint(0, 2, size=len(z)) - 1
return z
def sample_normal(size):
return np.random.normal(0, scale, size=size)
np.random.seed(1)
for sampler in [sample_exp, sample_normal]:
cis = _check_ci(lambda z, alpha: statistics.quantile_ci(z, 0.5, alpha),
sampler, nsamples=300)
atol = 5/300
for size, alpha, alpha_got in cis:
if size < 20:
assert 0 <= alpha_got <= 1.2*alpha
else:
assert 0.5*alpha - atol <= alpha_got <= 1.1*alpha + atol
def test_quantile_ci_small():
# Small samples should give infinite ci
for n in range(1, 7):
sample = list(range(n))
m, ci = statistics.quantile_ci(sample, 0.5, 0.99)
assert ci[0] == -inf
assert ci[1] == inf
def test_quantile_ci_r():
# Compare to R
x = [-2.47946614, -1.49595963, -1.02812482, -0.76592323, -0.09452743, 0.10732743,
0.27798342, 0.50173779, 0.57829823, 0.60474948, 0.94695675, 1.20159789]
# quantile(x, type=7, prob=p)
q_20_e = -0.9756845
q_50_e = 0.1926554
q_80_e = 0.5994592
# asht::quantileTest(x, prob=p, conf.level=0.8)$conf.int
ci_20_80_e = [-2.47946614, -0.09452743]
ci_50_80_e = [-0.7659232, 0.5782982]
ci_80_80_e = [0.5017378, 1.2015979,]
q_20, ci_20_80 = statistics.quantile_ci(x, 0.2, 0.8)
q_50, ci_50_80 = statistics.quantile_ci(x, 0.5, 0.8)
q_80, ci_80_80 = statistics.quantile_ci(x, 0.8, 0.8)
assert q_20 == pytest.approx(q_20_e)
assert q_50 == pytest.approx(q_50_e)
assert q_80 == pytest.approx(q_80_e)
assert ci_20_80 == pytest.approx(ci_20_80_e, abs=1e-4)
assert ci_50_80 == pytest.approx(ci_50_80_e, abs=1e-4)
assert ci_80_80 == pytest.approx(ci_80_80_e, abs=1e-4)
@pytest.mark.skipif(not HAS_NUMPY, reason="Requires numpy")
def test_quantile():
np.random.seed(1)
x = np.random.randn(50)
for q in np.linspace(0, 1, 300):
expected = np.percentile(x, 100 * q)
got = statistics.quantile(x.tolist(), q)
assert np.allclose(got, expected), q
@pytest.mark.skipif(not HAS_SCIPY, reason="Requires scipy")
def test_lgamma():
x = np.arange(1, 5000)
expected = special.gammaln(x)
got = np.vectorize(statistics.lgamma)(x)
assert np.allclose(got, expected, rtol=1e-12, atol=0)
assert np.isnan(statistics.lgamma(1.2))
@pytest.mark.skipif(not HAS_SCIPY, reason="Requires scipy")
def test_binom_pmf():
p = np.linspace(0, 1, 7)
k = np.arange(0, 40, 5)[:,None]
n = np.arange(0, 40, 5)[:,None,None]
expected = stats.binom.pmf(k, n, p)
got = np.vectorize(statistics.binom_pmf)(n, k, p)
assert np.allclose(got, expected, rtol=1e-12, atol=0)
@pytest.mark.skipif(not HAS_NUMPY, reason="Requires numpy")
def test_laplace_posterior_ci():
# Test the LaplacePosterior confidence intervals
scale = 2.5
def get_z_exp(size):
"""Samples from noise distribution assumed in LaplacePosterior"""
z = np.random.exponential(scale, size=size)
z *= 2 * np.random.randint(0, 2, size=len(z)) - 1
return z
def get_z_normal(size):
"""Samples from noise distribution not assumed in LaplacePosterior"""
z = np.random.normal(0, scale, size=size)
return z
np.random.seed(41)
def estimator(z, alpha):
c = statistics.LaplacePosterior(z.tolist())
a, b = c.ppf(alpha/2), c.ppf(1 - alpha/2)
a = min(c.mle, a) # force MLE inside CI
b = max(c.mle, b)
return c.mle, (a, b)
for sampler in [get_z_exp, get_z_normal]:
cis = _check_ci(estimator, sampler, nsamples=300)
atol = 5/300
for size, alpha, alpha_got in cis:
if sampler == get_z_exp:
# Result should be ok for the assumed distribution
rtol = 0.25
else:
# For other distributions, order of magnitude should match
rtol = 2.0
assert np.allclose(alpha_got, alpha, atol=atol, rtol=rtol)
def test_laplace_posterior_basic():
# Test the LaplacePosterior mle/cdf/ppf
# even
y = [1, 2, 3, 4, 5, 6][::-1]
c = statistics.LaplacePosterior(y)
assert abs(c.mle - 3.5) < 1e-8
# odd
y = [1, 2, 3, 4, 5][::-1]
c = statistics.LaplacePosterior(y)
assert abs(c.mle - 3) < 1e-8
# check pdf vs cdf
sx = 200
dx = 1.0/sx
cdf = 0
for jx in range(-10*sx, 10*sx):
cdf += c.pdf(dx*jx) * dx
got = c.cdf(dx*jx)
assert abs(cdf - got) < 3e-3
assert abs(cdf - 1.0) < 1e-3
# large input (must not cause overflows)
y = list(range(500))
c = statistics.LaplacePosterior(y)
assert abs(c.mle - 249.5) < 1e-8
assert abs(c.cdf(249.5) - 0.5) < 1e-8
# check cdf sanity
assert c.cdf(float('inf')) == 1.0
assert c.cdf(-float('inf')) == 0.0
assert abs(c.cdf(-1e9) - 0) < 1e-6
assert abs(c.cdf(1e9) - 1) < 1e-6
# check ppf
for p in [0.0, 1e-3, 0.01, 0.1, 0.5, 0.9, 0.99, 0.999, 1.0]:
assert abs(c.cdf(c.ppf(p)) - p) < 1e-3
t = c.ppf(1.1)
assert t != t
# check zero variance
y = [1, 1, 1, 1, 1]
c = statistics.LaplacePosterior(y)
assert c.mle == 1
assert c.pdf(1 - 1e-5) == 0
assert c.pdf(1 + 1e-5) == 0
assert c.cdf(1 - 1e-5) == 0
assert c.cdf(1 + 1e-5) == 1.0
assert c.ppf(1.0) == 1.0
# one item
y = [1]
c = statistics.LaplacePosterior(y)
assert c.cdf(1 - 1e-5) == 0
assert c.cdf(1 + 1e-5) == 1.0
# zero items
with pytest.raises(ValueError):
statistics.LaplacePosterior([])
@pytest.mark.skipif(not HAS_SCIPY, reason="Requires scipy")
def test_laplace_posterior_cdf():
# Test the LaplacePosterior cdf vs pdf
np.random.seed(1)
y = np.random.randn(15).tolist()
c = statistics.LaplacePosterior(y)
num_cdf = lambda t: integrate.quad(c.pdf, -np.inf, t, limit=1000)[0]
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=integrate.IntegrationWarning)
for t in np.linspace(-5, 5, 70):
x = c.cdf(t)
assert abs(x - num_cdf(t)) < 1e-5
assert abs(c.ppf(x) - t) < 1e-5
def test_mann_whitney_u_cdf():
memo = {}
def check_table(m, tbl):
for u, row in enumerate(tbl):
for nx, p in enumerate(row):
n = nx + 1
if p is None:
continue
p2 = statistics.mann_whitney_u_cdf(m, n, u, memo=memo)
assert p2 == pytest.approx(p, abs=1e-3, rel=0), (m, n, u, p2, p)
# Tables from Mann & Whitney, Ann. Math. Statist. 18, 50 (1947).
tbl = [[.250, .100, .050],
[.500, .200, .100],
[.750, .400, .200],
[None, .600, .350],
[None, None, .500],
[None, None, .650]]
check_table(3, tbl)
tbl = [[.200, .067, .028, .014],
[.400, .133, .057, .029],
[.600, .267, .114, .057],
[None, .400, .200, .100],
[None, .600, .314, .171],
[None, None, .429, .243],
[None, None, .571, .343],
[None, None, None, .443],
[None, None, None, .557]]
check_table(4, tbl)
tbl = [[.167, .047, .018, .008, .004],
[.333, .095, .036, .016, .008],
[.500, .190, .071, .032, .016],
[.667, .286, .125, .056, .028],
[None, .429, .196, .095, .048],
[None, .571, .286, .143, .075],
[None, None, .393, .206, .111],
[None, None, .500, .278, .155],
[None, None, .607, .365, .210],
[None, None, None, .452, .274],
[None, None, None, .548, .345],
[None, None, None, None, .421],
[None, None, None, None, .500],
[None, None, None, None, .579]]
check_table(5, tbl)
@pytest.mark.skipif(not HAS_SCIPY, reason="Requires scipy")
def test_mann_whitney_u_scipy():
# Scipy only has the large-sample limit...
def check(x, y):
u0, p0 = stats.mannwhitneyu(x, y, alternative='two-sided', use_continuity=False)
u, p = statistics.mann_whitney_u(x.tolist(), y.tolist(), method='normal')
assert u == u0
assert p == pytest.approx(p0, rel=1e-9, abs=0)
u, p = statistics.mann_whitney_u(x.tolist(), y.tolist(), method='exact')
assert u == u0
assert p == pytest.approx(p0, rel=5e-2, abs=5e-3)
u, p = statistics.mann_whitney_u(x.tolist(), y.tolist())
assert u == u0
assert p == pytest.approx(p0, rel=5e-2, abs=5e-3)
np.random.seed(1)
x = np.random.randn(22)
y = np.random.randn(23)
check(x, y)
check(x, y + 0.5)
check(x, y - 2.5)
def test_mann_whitney_u_basic():
# wilcox.test(a, b, exact=TRUE)
a = [1, 2, 3, 4]
b = [0.9, 1.1, 0.7]
u, p = statistics.mann_whitney_u(a, b, method='exact')
assert u == 11
assert p == pytest.approx(0.11428571428571428, abs=0, rel=1e-10)
a = [1, 2]
b = [1.5]
u, p = statistics.mann_whitney_u(a, b, method='exact')
assert u == 1
assert p == 1.0
a = [1, 2]
b = [2.5]
u, p = statistics.mann_whitney_u(a, b, method='exact')
assert u == 0
assert p == pytest.approx(2/3, abs=0, rel=1e-10)
@pytest.mark.skipif(not HAS_RPY2, reason="Requires rpy2")
def test_mann_whitney_u_R():
random.seed(1)
a = list(range(30))
b = [x + 0.1 for x in a]
random.shuffle(a)
random.shuffle(b)
wilcox_test = robjects.r('wilcox.test')
for m in range(1, len(a) + 1):
for n in range(1, len(b) + 1):
u, p = statistics.mann_whitney_u(a[:m], b[:n])
r = wilcox_test(robjects.FloatVector(a[:m]),
robjects.FloatVector(b[:n]))
if max(m, n) <= 20:
err = 1e-10 # exact method
else:
# normal approximation
if min(m, n) < 3:
err = 0.4
elif min(m, n) < 10:
err = 0.1
else:
err = 0.05
assert u == r.rx('statistic')[0][0]
assert p == pytest.approx(r.rx('p.value')[0][0], abs=0, rel=err)
def test_binom():
for n in range(10):
for k in range(10):
p = statistics.binom(n, k)
if 0 <= k <= n:
p2 = math.factorial(n) / math.factorial(k) / math.factorial(n - k)
else:
p2 = 0
assert p == p2
| 7,219 |
396 | <filename>resonance_audio/utils/planar_interleaved_conversion.cc
/*
Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Prevent Visual Studio from complaining about std::copy_n.
#if defined(_WIN32)
#define _SCL_SECURE_NO_WARNINGS
#endif
#include "utils/planar_interleaved_conversion.h"
#include "base/constants_and_types.h"
#include "base/logging.h"
#include "base/simd_utils.h"
#include "utils/sample_type_conversion.h"
namespace vraudio {
namespace {
template <typename InputType, typename OutputType>
void ConvertInterleavedToPlanarTemplated(
InputType interleaved_buffer, size_t num_input_frames,
size_t num_input_channels, size_t input_offset_frames,
const std::vector<size_t>* channel_map, OutputType output_buffer,
size_t num_output_frames, size_t num_output_channels,
size_t output_offset_frames, size_t num_frames_to_copy) {
DCHECK_GE(num_input_frames, input_offset_frames);
const size_t max_num_input_frames = num_input_frames - input_offset_frames;
DCHECK_GE(num_output_frames, output_offset_frames);
const size_t max_num_output_frames = num_output_frames - output_offset_frames;
DCHECK_GE(max_num_input_frames, num_frames_to_copy);
DCHECK_GE(max_num_output_frames, num_frames_to_copy);
if (channel_map == nullptr) {
DCHECK_EQ(num_input_channels, num_output_channels);
} else {
DCHECK_GE(channel_map->size(), num_output_channels);
}
InputType interleaved_buffer_with_offset =
interleaved_buffer + input_offset_frames * num_input_channels;
if (num_input_channels == kNumStereoChannels &&
num_output_channels == kNumStereoChannels) {
if (channel_map == nullptr) {
DeinterleaveStereo(num_frames_to_copy, interleaved_buffer_with_offset,
&output_buffer[0][output_offset_frames],
&output_buffer[1][output_offset_frames]);
} else {
DCHECK_LT((*channel_map)[0], kNumStereoChannels);
DCHECK_LT((*channel_map)[1], kNumStereoChannels);
DeinterleaveStereo(
num_input_frames, interleaved_buffer_with_offset,
&output_buffer[(*channel_map)[0]][output_offset_frames],
&output_buffer[(*channel_map)[1]][output_offset_frames]);
}
} else {
for (size_t channel_idx = 0; channel_idx < num_output_channels;
++channel_idx) {
const size_t input_channel =
channel_map != nullptr ? (*channel_map)[channel_idx] : channel_idx;
DCHECK_LT(input_channel, num_input_channels);
InputType input_ptr = &interleaved_buffer_with_offset[input_channel];
float* output_ptr = &output_buffer[channel_idx][output_offset_frames];
for (size_t frame = 0; frame < num_frames_to_copy; ++frame) {
ConvertSampleToFloatFormat(*input_ptr, output_ptr);
input_ptr += num_input_channels;
++output_ptr;
}
}
}
}
template <typename PlanarInputType, typename PlanarOutputType>
void ConvertPlanarToPlanarTemplated(
PlanarInputType input, size_t num_input_frames, size_t num_input_channels,
size_t input_offset_frames, const std::vector<size_t>* channel_map,
PlanarOutputType planar_output_ptrs, size_t num_output_frames,
size_t num_output_channels, size_t output_offset_frames,
size_t num_frames_convert_and_copy) {
DCHECK_GE(num_input_frames, input_offset_frames);
const size_t max_num_input_frames = num_input_frames - input_offset_frames;
DCHECK_GE(num_output_frames, output_offset_frames);
const size_t max_num_output_frames = num_output_frames - output_offset_frames;
DCHECK_GE(max_num_input_frames, num_frames_convert_and_copy);
DCHECK_GE(max_num_output_frames, num_frames_convert_and_copy);
if (channel_map == nullptr) {
DCHECK_EQ(num_input_channels, num_output_channels);
} else {
DCHECK_GE(channel_map->size(), num_output_channels);
}
for (size_t channel = 0; channel < num_output_channels; ++channel) {
const size_t input_channel =
channel_map != nullptr ? (*channel_map)[channel] : channel;
DCHECK_LT(input_channel, num_input_channels);
ConvertPlanarSamples(num_frames_convert_and_copy,
&input[input_channel][input_offset_frames],
&planar_output_ptrs[channel][output_offset_frames]);
}
}
template <typename PlanarInputType, typename InterleavedOutputType>
void ConvertPlanarToInterleavedTemplated(
PlanarInputType input, size_t num_input_frames, size_t num_input_channels,
size_t input_offset_frames, InterleavedOutputType interleaved_output_ptr,
size_t num_output_frames, size_t num_output_channels,
size_t output_offset_frames, size_t num_frames_convert_and_copy) {
DCHECK(interleaved_output_ptr);
DCHECK_GE(num_input_frames, input_offset_frames);
const size_t max_num_input_frames = num_input_frames - input_offset_frames;
DCHECK_GE(num_output_frames, output_offset_frames);
const size_t max_num_output_frames = num_output_frames - output_offset_frames;
DCHECK_GE(max_num_input_frames, num_frames_convert_and_copy);
DCHECK_GE(max_num_output_frames, num_frames_convert_and_copy);
DCHECK_EQ(num_input_channels, num_output_channels);
InterleavedOutputType interleaved_output_ptr_with_offset =
interleaved_output_ptr + output_offset_frames * num_output_channels;
if (num_input_channels == kNumStereoChannels &&
num_output_channels == kNumStereoChannels) {
const float* left_ptr = &input[0][input_offset_frames];
const float* right_ptr = &input[1][input_offset_frames];
InterleaveStereo(num_frames_convert_and_copy, left_ptr, right_ptr,
interleaved_output_ptr_with_offset);
} else {
for (size_t channel = 0; channel < num_output_channels; ++channel) {
const float* input_channel_ptr = &input[channel][input_offset_frames];
size_t interleaved_index = channel;
for (size_t frame = 0; frame < num_frames_convert_and_copy; ++frame) {
ConvertSampleFromFloatFormat(
input_channel_ptr[frame],
&interleaved_output_ptr_with_offset[interleaved_index]);
interleaved_index += num_output_channels;
}
}
}
}
} // namespace
void PlanarFromInterleaved(const float* interleaved_buffer,
size_t num_input_frames, size_t num_input_channels,
const std::vector<float*>& planar_buffer_ptr,
size_t num_output_frames) {
DCHECK(interleaved_buffer);
DCHECK_GT(planar_buffer_ptr.size(), 0);
const size_t num_frames_to_copy =
std::min(num_input_frames, num_output_frames);
ConvertInterleavedToPlanarTemplated<const float*, float* const*>(
interleaved_buffer, num_input_frames, num_input_channels,
0 /* input_offset_frames */, nullptr /* channel_map*/,
planar_buffer_ptr.data(), num_output_frames, planar_buffer_ptr.size(),
0 /* output_offset_frames */, num_frames_to_copy);
}
void PlanarFromInterleaved(const int16* interleaved_buffer,
size_t num_input_frames, size_t num_input_channels,
const std::vector<float*>& planar_buffer_ptr,
size_t num_output_frames) {
DCHECK(interleaved_buffer);
DCHECK_GT(planar_buffer_ptr.size(), 0);
const size_t num_frames_to_copy =
std::min(num_input_frames, num_output_frames);
ConvertInterleavedToPlanarTemplated<const int16*, float* const*>(
interleaved_buffer, num_input_frames, num_input_channels,
0 /* input_offset_frames */, nullptr /* channel_map*/,
planar_buffer_ptr.data(), num_output_frames, planar_buffer_ptr.size(),
0 /* output_offset_frames */, num_frames_to_copy);
}
void FillAudioBuffer(const float* interleaved_buffer, size_t num_input_frames,
size_t num_input_channels, AudioBuffer* output) {
DCHECK(interleaved_buffer);
DCHECK(output);
const size_t num_frames_to_copy =
std::min(num_input_frames, output->num_frames());
ConvertInterleavedToPlanarTemplated<const float*, AudioBuffer&>(
interleaved_buffer, num_input_frames, num_input_channels,
0 /* input_offset_frames */, nullptr /* channel_map*/, *output,
output->num_frames(), output->num_channels(),
0 /* output_offset_frames */, num_frames_to_copy);
}
void FillAudioBuffer(const int16* interleaved_buffer, size_t num_input_frames,
size_t num_input_channels, AudioBuffer* output) {
DCHECK(interleaved_buffer);
DCHECK(output);
const size_t num_frames_to_copy =
std::min(num_input_frames, output->num_frames());
ConvertInterleavedToPlanarTemplated<const int16*, AudioBuffer&>(
interleaved_buffer, num_input_frames, num_input_channels,
0 /* input_offset_frames */, nullptr /* channel_map*/, *output,
output->num_frames(), output->num_channels(),
0 /* output_offset_frames */, num_frames_to_copy);
}
void FillAudioBuffer(const std::vector<float>& interleaved_buffer,
size_t num_input_channels, AudioBuffer* output) {
DCHECK(output);
DCHECK_EQ(interleaved_buffer.size() % num_input_channels, 0);
const size_t num_frames_to_copy = std::min(
interleaved_buffer.size() / num_input_channels, output->num_frames());
FillAudioBuffer(&interleaved_buffer[0], num_frames_to_copy,
num_input_channels, output);
}
void FillAudioBuffer(const std::vector<int16>& interleaved_buffer,
size_t num_input_channels, AudioBuffer* output) {
DCHECK(output);
DCHECK_EQ(interleaved_buffer.size() % num_input_channels, 0);
const size_t num_frames_to_copy = std::min(
interleaved_buffer.size() / num_input_channels, output->num_frames());
FillAudioBuffer(&interleaved_buffer[0], num_frames_to_copy,
num_input_channels, output);
}
void FillAudioBuffer(const float* const* planar_ptrs, size_t num_input_frames,
size_t num_input_channels, AudioBuffer* output) {
DCHECK(planar_ptrs);
DCHECK(output);
const size_t num_frames_to_copy =
std::min(num_input_frames, output->num_frames());
ConvertPlanarToPlanarTemplated<const float* const*, AudioBuffer&>(
planar_ptrs, num_input_frames, num_input_channels,
0 /* input_offset_frames */, nullptr /* channel_map*/, *output,
output->num_frames(), output->num_channels(),
0 /* output_offset_frames */, num_frames_to_copy);
}
void FillAudioBuffer(const int16* const* planar_ptrs, size_t num_input_frames,
size_t num_input_channels, AudioBuffer* output) {
DCHECK(planar_ptrs);
DCHECK(output);
const size_t num_frames_to_copy =
std::min(num_input_frames, output->num_frames());
ConvertPlanarToPlanarTemplated<const int16* const*, AudioBuffer&>(
planar_ptrs, num_input_frames, num_input_channels,
0 /* input_offset_frames */, nullptr /* channel_map*/, *output,
output->num_frames(), output->num_channels(),
0 /* output_offset_frames */, num_frames_to_copy);
}
void FillAudioBufferWithOffset(const float* interleaved_buffer,
size_t num_input_frames,
size_t num_input_channels,
size_t input_frame_offset,
size_t output_frame_offset,
size_t num_frames_to_copy, AudioBuffer* output) {
DCHECK(interleaved_buffer);
DCHECK(output);
ConvertInterleavedToPlanarTemplated<const float*, AudioBuffer&>(
interleaved_buffer, num_input_frames, num_input_channels,
input_frame_offset, nullptr /* channel_map*/, *output,
output->num_frames(), output->num_channels(), output_frame_offset,
num_frames_to_copy);
}
void FillAudioBufferWithOffset(const int16* interleaved_buffer,
size_t num_input_frames,
size_t num_input_channels,
size_t input_frame_offset,
size_t output_frame_offset,
size_t num_frames_to_copy, AudioBuffer* output) {
DCHECK(interleaved_buffer);
DCHECK(output);
ConvertInterleavedToPlanarTemplated<const int16*, AudioBuffer&>(
interleaved_buffer, num_input_frames, num_input_channels,
input_frame_offset, nullptr /* channel_map*/, *output,
output->num_frames(), output->num_channels(), output_frame_offset,
num_frames_to_copy);
}
void FillAudioBufferWithOffset(const float* const* planar_ptrs,
size_t num_input_frames,
size_t num_input_channels,
size_t input_frame_offset,
size_t output_frame_offset,
size_t num_frames_to_copy, AudioBuffer* output) {
DCHECK(planar_ptrs);
DCHECK(output);
ConvertPlanarToPlanarTemplated<const float* const*, AudioBuffer&>(
planar_ptrs, num_input_frames, num_input_channels, input_frame_offset,
nullptr /* channel_map*/, *output, output->num_frames(),
output->num_channels(), output_frame_offset, num_frames_to_copy);
}
void FillAudioBufferWithOffset(const int16* const* planar_ptrs,
size_t num_input_frames,
size_t num_input_channels,
size_t input_frame_offset,
size_t output_frame_offset,
size_t num_frames_to_copy, AudioBuffer* output) {
DCHECK(planar_ptrs);
DCHECK(output);
ConvertPlanarToPlanarTemplated<const int16* const*, AudioBuffer&>(
planar_ptrs, num_input_frames, num_input_channels, input_frame_offset,
nullptr /* channel_map*/, *output, output->num_frames(),
output->num_channels(), output_frame_offset, num_frames_to_copy);
}
void FillAudioBufferWithChannelRemapping(const int16* interleaved_buffer,
size_t num_input_frames,
size_t num_input_channels,
const std::vector<size_t>& channel_map,
AudioBuffer* output) {
DCHECK(interleaved_buffer);
DCHECK(output);
const size_t num_frames_to_copy =
std::min(num_input_frames, output->num_frames());
ConvertInterleavedToPlanarTemplated<const int16*, AudioBuffer&>(
interleaved_buffer, num_input_frames, num_input_channels,
0 /*input_frame_offset*/, &channel_map, *output, output->num_frames(),
output->num_channels(), 0 /*output_frame_offset*/, num_frames_to_copy);
}
void FillAudioBufferWithChannelRemapping(const float* interleaved_buffer,
size_t num_input_frames,
size_t num_input_channels,
const std::vector<size_t>& channel_map,
AudioBuffer* output) {
DCHECK(interleaved_buffer);
DCHECK(output);
const size_t num_frames_to_copy =
std::min(num_input_frames, output->num_frames());
ConvertInterleavedToPlanarTemplated<const float*, AudioBuffer&>(
interleaved_buffer, num_input_frames, num_input_channels,
0 /*input_frame_offset*/, &channel_map, *output, output->num_frames(),
output->num_channels(), 0 /*output_frame_offset*/, num_frames_to_copy);
}
void FillAudioBufferWithChannelRemapping(const float* const* planar_ptrs,
size_t num_input_frames,
size_t num_input_channels,
const std::vector<size_t>& channel_map,
AudioBuffer* output) {
DCHECK(planar_ptrs);
DCHECK(output);
const size_t num_frames_to_copy =
std::min(num_input_frames, output->num_frames());
ConvertPlanarToPlanarTemplated<const float* const*, AudioBuffer&>(
planar_ptrs, num_input_frames, num_input_channels,
0 /*input_offset_frames*/, &channel_map, *output, output->num_frames(),
output->num_channels(), 0 /* output_offset_frames*/, num_frames_to_copy);
}
void FillAudioBufferWithChannelRemapping(const int16* const* planar_ptr,
size_t num_input_frames,
size_t num_input_channels,
const std::vector<size_t>& channel_map,
AudioBuffer* output) {
DCHECK(planar_ptr);
DCHECK(output);
const size_t num_frames_to_copy =
std::min(num_input_frames, output->num_frames());
ConvertPlanarToPlanarTemplated<const int16* const*, AudioBuffer&>(
planar_ptr, num_input_frames, num_input_channels,
0 /*input_offset_frames*/, &channel_map, *output, output->num_frames(),
output->num_channels(), 0 /* output_offset_frames*/, num_frames_to_copy);
}
void FillExternalBuffer(const AudioBuffer& input, std::vector<float>* output) {
DCHECK(output);
output->resize(input.num_frames() * input.num_channels());
FillExternalBuffer(input, output->data(), input.num_frames(),
input.num_channels());
}
void FillExternalBuffer(const AudioBuffer& input, std::vector<int16>* output) {
DCHECK(output);
output->resize(input.num_frames() * input.num_channels());
FillExternalBuffer(input, output->data(), input.num_frames(),
input.num_channels());
}
void FillExternalBuffer(const AudioBuffer& input,
int16* const* planar_output_ptrs,
size_t num_output_frames, size_t num_output_channels) {
ConvertPlanarToPlanarTemplated<const AudioBuffer&, int16* const*>(
input, input.num_frames(), input.num_channels(),
0 /*input_offset_frames*/, nullptr /* channel_map*/, planar_output_ptrs,
num_output_frames, num_output_channels, 0 /* output_offset_frames*/,
num_output_frames);
}
void FillExternalBuffer(const AudioBuffer& input,
float* const* planar_output_ptrs,
size_t num_output_frames, size_t num_output_channels) {
ConvertPlanarToPlanarTemplated<const AudioBuffer&, float* const*>(
input, input.num_frames(), input.num_channels(),
0 /*input_offset_frames*/, nullptr /* channel_map*/, planar_output_ptrs,
num_output_frames, num_output_channels, 0 /* output_offset_frames*/,
num_output_frames);
}
void FillExternalBuffer(const AudioBuffer& input,
int16* interleaved_output_buffer,
size_t num_output_frames, size_t num_output_channels) {
ConvertPlanarToInterleavedTemplated<const AudioBuffer&, int16*>(
input, input.num_frames(), input.num_channels(),
0 /*input_offset_frames*/, interleaved_output_buffer, num_output_frames,
num_output_channels, 0 /* output_offset_frames*/, num_output_frames);
}
void FillExternalBuffer(const AudioBuffer& input,
float* interleaved_output_buffer,
size_t num_output_frames, size_t num_output_channels) {
ConvertPlanarToInterleavedTemplated<const AudioBuffer&, float*>(
input, input.num_frames(), input.num_channels(),
0 /*input_offset_frames*/, interleaved_output_buffer, num_output_frames,
num_output_channels, 0 /* output_offset_frames*/, num_output_frames);
}
void FillExternalBufferWithOffset(const AudioBuffer& input,
size_t input_offset_frames,
int16* const* planar_output_ptrs,
size_t num_output_frames,
size_t num_output_channels,
size_t output_offset_frames,
size_t num_frames_convert_and_copy) {
ConvertPlanarToPlanarTemplated<const AudioBuffer&, int16* const*>(
input, input.num_frames(), input.num_channels(), input_offset_frames,
nullptr /* channel_map */, planar_output_ptrs, num_output_frames,
num_output_channels, output_offset_frames, num_frames_convert_and_copy);
}
void FillExternalBufferWithOffset(const AudioBuffer& input,
size_t input_offset_frames,
float* const* planar_output_ptrs,
size_t num_output_frames,
size_t num_output_channels,
size_t output_offset_frames,
size_t num_frames_convert_and_copy) {
ConvertPlanarToPlanarTemplated<const AudioBuffer&, float* const*>(
input, input.num_frames(), input.num_channels(), input_offset_frames,
nullptr /* channel_map */, planar_output_ptrs, num_output_frames,
num_output_channels, output_offset_frames, num_frames_convert_and_copy);
}
void FillExternalBufferWithOffset(const AudioBuffer& input,
size_t input_offset_frames,
int16* interleaved_output_buffer,
size_t num_output_frames,
size_t num_output_channels,
size_t output_offset_frames,
size_t num_frames_convert_and_copy) {
ConvertPlanarToInterleavedTemplated<const AudioBuffer&, int16*>(
input, input.num_frames(), input.num_channels(), input_offset_frames,
interleaved_output_buffer, num_output_frames, num_output_channels,
output_offset_frames, num_frames_convert_and_copy);
}
void FillExternalBufferWithOffset(const AudioBuffer& input,
size_t input_offset_frames,
float* interleaved_output_buffer,
size_t num_output_frames,
size_t num_output_channels,
size_t output_offset_frames,
size_t num_frames_convert_and_copy) {
ConvertPlanarToInterleavedTemplated<const AudioBuffer&, float*>(
input, input.num_frames(), input.num_channels(), input_offset_frames,
interleaved_output_buffer, num_output_frames, num_output_channels,
output_offset_frames, num_frames_convert_and_copy);
}
void GetRawChannelDataPointersFromAudioBuffer(
AudioBuffer* audio_buffer, std::vector<float*>* channel_ptr_vector) {
DCHECK(audio_buffer);
DCHECK(channel_ptr_vector);
DCHECK_EQ(audio_buffer->num_channels(), channel_ptr_vector->size());
for (size_t i = 0; i < audio_buffer->num_channels(); ++i) {
(*channel_ptr_vector)[i] = &(*audio_buffer)[i][0];
}
}
void GetRawChannelDataPointersFromAudioBuffer(
const AudioBuffer& audio_buffer,
std::vector<const float*>* channel_ptr_vector) {
DCHECK(channel_ptr_vector);
DCHECK_EQ(audio_buffer.num_channels(), channel_ptr_vector->size());
for (size_t i = 0; i < audio_buffer.num_channels(); ++i) {
(*channel_ptr_vector)[i] = &audio_buffer[i][0];
}
}
} // namespace vraudio
| 10,316 |
473 | /*
* defines the entry point for the cac card. Only used by cac.c anc
* vcard_emul_type.c
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*/
#ifndef CAC_H
#define CAC_H 1
#include "vcard.h"
#include "vreader.h"
#define CAC_GET_PROPERTIES 0x56
#define CAC_GET_ACR 0x4c
#define CAC_READ_BUFFER 0x52
#define CAC_UPDATE_BUFFER 0x58
#define CAC_SIGN_DECRYPT 0x42
#define CAC_GET_CERTIFICATE 0x36
/*
* Initialize the cac card. This is the only public function in this file. All
* the rest are connected through function pointers.
*/
VCardStatus cac_card_init(VReader *reader, VCard *card, const char *params,
unsigned char * const *cert, int cert_len[],
VCardKey *key[] /* adopt the keys*/,
int cert_count);
/* not yet implemented */
VCardStatus cac_is_cac_card(VReader *reader);
#endif
| 371 |
852 | <reponame>ckamtsikis/cmssw
package detidGenerator;
/**
* <p>Used to convert the det id to a 32 bits word</p>
* @author <NAME>
* @version 1.0
**/
/*
Revision 1.3 2006/08/31 15:24:29 gbaulieu
The TOBCS are directly in the TOB
Correction on the Stereo flag
Revision 1.2 2006/08/30 15:21:12 gbaulieu
Add the TOB analyzer
Revision 1.1 2006/06/28 11:42:24 gbaulieu
First import of the sources
Revision 1.1 2006/02/08 15:03:00 baulieu
Add the convertion to 32 bits for the TOB
*/
public class TOBDetIdConverter extends DetIdConverter{
private int layer;
private int frontBack;
private int rod;
private int moduleNumber;
private int stereo;
/// two bits would be enough, but we could use the number "0" as a wildcard
private final short layerStartBit = 14;
private final short rod_fw_bwStartBit = 12;
private final short rodStartBit = 5;
private final short detStartBit = 2;
private final short sterStartBit = 0;
/// two bits would be enough, but we could use the number "0" as a wildcard
private final short layerMask = 0x7;
private final short rod_fw_bwMask = 0x3;
private final short rodMask = 0x7F;
private final short detMask = 0x7;
private final short sterMask = 0x3;
public TOBDetIdConverter(int l, int fb, int r, int mn, int s){
super(1, 5);
layer = l;
frontBack = fb;
rod = r;
moduleNumber = mn;
stereo = s;
}
public TOBDetIdConverter(String detID) throws Exception{
super(1,5);
try{
String[] val = detID.split("\\.");
if(val.length!=7)
throw new Exception("The detID has an invalid format");
else{
layer = Integer.parseInt(val[2]);
frontBack = Integer.parseInt(val[3]);
rod = Integer.parseInt(val[4]);
moduleNumber = Integer.parseInt(val[5]);
stereo = Integer.parseInt(val[6]);
}
}
catch(NumberFormatException e){
throw new Exception("TOBDetIdConverter : \n"+e.getMessage());
}
}
public TOBDetIdConverter(int detID) throws Exception{
super(detID);
layer = getLayer();
frontBack = getFrontBack();
rod = getRod();
moduleNumber = getModNumber();
stereo = getStereo();
}
public int compact(){
super.compact();
id |= (layer&layerMask)<<layerStartBit |
(frontBack&rod_fw_bwMask)<<rod_fw_bwStartBit |
(rod&rodMask)<<rodStartBit |
(moduleNumber&detMask)<<detStartBit |
(stereo&sterMask)<<sterStartBit;
return id;
}
public int getLayer(){
return (id>>layerStartBit)&layerMask;
}
public int getFrontBack(){
return (id>>rod_fw_bwStartBit)&rod_fw_bwMask;
}
public int getRod(){
return (id>>rodStartBit)&rodMask;
}
public int getModNumber(){
return (id>>detStartBit)&detMask;
}
public int getStereo(){
return (id>>sterStartBit)&sterMask;
}
public String toString(){
return "TOB"+
((getFrontBack()==2)?"+":"-")+
" Layer "+getLayer()+" "+
" Rod "+getRod()+
" module "+getModNumber()+
((getStereo()==1)?" Stereo":(getStereo()==0?" Mono":" Glued"));
}
public static void main(String args[]){
try{
//System.out.println(args[0]);
//TECDetIdConverter d = new TECDetIdConverter(args[0]);
TOBDetIdConverter d = new TOBDetIdConverter(Integer.parseInt(args[0]));
System.out.println("Det ID : "+d.compact());
System.out.println("Module : "+d.getDetector()+
" - "+d.getSubDetector()+
" - "+d.getLayer()+
" - "+d.getFrontBack()+
" - "+d.getRod()+
" - "+d.getModNumber()+
" - "+d.getStereo()
);
System.out.println(d);
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
| 1,572 |
12,278 | # -*- coding: utf-8 -*-
# © 2019 and later: Unicode, Inc. and others.
# License & terms of use: http://www.unicode.org/copyright.html#License
data = {
"cldrVersion": "35.1",
"aliases": {
"ars": "ar_SA",
"az_AZ": "az_Latn_AZ",
"bs_BA": "bs_Latn_BA",
"en_NH": "en_VU",
"en_RH": "en_ZW",
"ff_CM": "ff_Latn_CM",
"ff_GN": "ff_Latn_GN",
"ff_MR": "ff_Latn_MR",
"ff_SN": "ff_Latn_SN",
"in": "id",
"in_ID": "id_ID",
"iw": "he",
"iw_IL": "he_IL",
"mo": "ro",
"no_NO": "nb_NO",
"no_NO_NY": "nn_NO",
"no": "nb",
"pa_IN": "pa_Guru_IN",
"pa_PK": "pa_Arab_PK",
"sh": "sr_Latn",
"sh_BA": "sr_Latn_BA",
"sh_CS": "sr_Latn_RS",
"sh_YU": "sr_Latn_RS",
"shi_MA": "shi_Tfng_MA",
"sr_BA": "sr_Cyrl_BA",
"sr_CS": "sr_Cyrl_RS",
"sr_ME": "sr_Latn_ME",
"sr_RS": "sr_Cyrl_RS",
"sr_XK": "sr_Cyrl_XK",
"sr_YU": "sr_Cyrl_RS",
"sr_Cyrl_YU": "sr_Cyrl_RS",
"sr_Cyrl_CS": "sr_Cyrl_RS",
"sr_Latn_YU": "sr_Latn_RS",
"sr_Latn_CS": "sr_Latn_RS",
"tl": "fil",
"tl_PH": "fil_PH",
"uz_AF": "uz_Arab_AF",
"uz_UZ": "uz_Latn_UZ",
"vai_LR": "vai_Vaii_LR",
"yue_CN": "yue_Hans_CN",
"yue_HK": "yue_Hant_HK",
"zh_CN": "zh_Hans_CN",
"zh_HK": "zh_Hant_HK",
"zh_MO": "zh_Hant_MO",
"zh_SG": "zh_Hans_SG",
"zh_TW": "zh_Hant_TW"
},
"parents": {
"ff_Adlm": "root",
"en_CM": "en_001",
"so_Arab": "root",
"en_KY": "en_001",
"en_TC": "en_001",
"yue_Hans": "root",
"en_CX": "en_001",
"es_EC": "es_419",
"es_US": "es_419",
"byn_Latn": "root",
"en_CY": "en_001",
"en_LC": "en_001",
"en_TK": "en_001",
"tg_Arab": "root",
"es_UY": "es_419",
"ky_Latn": "root",
"en_TO": "en_001",
"en_TT": "en_001",
"en_DE": "en_150",
"es_MX": "es_419",
"en_TV": "en_001",
"en_DG": "en_001",
"pt_ST": "pt_PT",
"en_DM": "en_001",
"en_LR": "en_001",
"en_TZ": "en_001",
"en_LS": "en_001",
"en_DK": "en_150",
"blt_Latn": "root",
"es_VE": "es_419",
"es_NI": "es_419",
"sd_Khoj": "root",
"pt_AO": "pt_PT",
"en_UG": "en_001",
"yo_Arab": "root",
"dje_Arab": "root",
"en_MG": "en_001",
"en_MO": "en_001",
"en_MU": "en_001",
"en_MS": "en_001",
"en_MT": "en_001",
"shi_Latn": "root",
"es_BR": "es_419",
"en_AU": "en_001",
"en_ZM": "en_001",
"en_AT": "en_150",
"es_BZ": "es_419",
"uz_Arab": "root",
"az_Cyrl": "root",
"es_SV": "es_419",
"en_ZW": "en_001",
"en_JE": "en_001",
"en_BB": "en_001",
"sd_Deva": "root",
"pa_Arab": "root",
"en_RW": "en_001",
"es_CO": "es_419",
"en_JM": "en_001",
"en_BE": "en_150",
"dyo_Arab": "root",
"es_CL": "es_419",
"en_BM": "en_001",
"en_SC": "en_001",
"es_CR": "es_419",
"en_150": "en_001",
"en_BS": "en_001",
"en_SD": "en_001",
"pt_GQ": "pt_PT",
"en_SB": "en_001",
"es_CU": "es_419",
"en_SG": "en_001",
"uz_Cyrl": "root",
"en_BW": "en_001",
"en_SH": "en_001",
"en_SE": "en_150",
"pt_GW": "pt_PT",
"ky_Arab": "root",
"en_BZ": "en_001",
"en_SL": "en_001",
"en_SI": "en_150",
"ff_Arab": "root",
"en_KE": "en_001",
"bm_Nkoo": "root",
"en_CC": "en_001",
"en_SS": "en_001",
"iu_Latn": "root",
"en_CA": "en_001",
"en_KI": "en_001",
"es_DO": "es_419",
"en_SX": "en_001",
"en_CH": "en_150",
"en_KN": "en_001",
"en_CK": "en_001",
"ml_Arab": "root",
"en_SZ": "en_001",
"pt_FR": "pt_PT",
"ug_Cyrl": "root",
"en_GY": "en_001",
"en_PH": "en_001",
"en_PG": "en_001",
"en_PK": "en_001",
"cu_Glag": "root",
"en_PN": "en_001",
"kk_Arab": "root",
"en_HK": "en_001",
"zh_Hant": "root",
"en_PW": "en_001",
"es_AR": "es_419",
"pt_MZ": "pt_PT",
"sd_Sind": "root",
"en_Shaw": "root",
"en_IE": "en_001",
"ms_Arab": "root",
"en_IM": "en_001",
"en_IN": "en_001",
"es_BO": "es_419",
"en_IL": "en_001",
"en_AI": "en_001",
"az_Arab": "root",
"en_AG": "en_001",
"en_IO": "en_001",
"en_ZA": "en_001",
"en_MY": "en_001",
"en_ER": "en_001",
"en_VC": "en_001",
"mn_Mong": "root",
"vai_Latn": "root",
"en_MW": "en_001",
"pt_LU": "pt_PT",
"bs_Cyrl": "root",
"en_VG": "en_001",
"en_NA": "en_001",
"en_NF": "en_001",
"en_NG": "en_001",
"ha_Arab": "root",
"en_NL": "en_150",
"zh_Hant_MO": "zh_Hant_HK",
"en_VU": "en_001",
"en_FJ": "en_001",
"en_NR": "en_001",
"en_FK": "en_001",
"es_GT": "es_419",
"en_FI": "en_150",
"ku_Arab": "root",
"pt_MO": "pt_PT",
"en_FM": "en_001",
"en_NU": "en_001",
"en_NZ": "en_001",
"pt_CH": "pt_PT",
"en_Dsrt": "root",
"es_PE": "es_419",
"es_PA": "es_419",
"pt_CV": "pt_PT",
"wo_Arab": "root",
"en_WS": "en_001",
"en_GD": "en_001",
"en_GB": "en_001",
"es_HN": "es_419",
"pt_TL": "pt_PT",
"en_GG": "en_001",
"en_GH": "en_001",
"es_PR": "es_419",
"sw_Arab": "root",
"en_GI": "en_001",
"sr_Latn": "root",
"en_GM": "en_001",
"es_PY": "es_419"
}
}
| 4,031 |
3,495 | <filename>build/chip/java/write_build_config.py
#!/usr/bin/env python
# Copyright (c) 2021 Project CHIP 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.
"""
Writes a JSON file containing build configuration information.
See build/chip/java/tests/expected_output/* for example build configuration
files.
"""
import json
import optparse
import os
import sys
def LoadBuildConfigs(paths):
build_configs = []
for path in paths:
with open(path, 'r') as file:
build_configs.append(json.load(file))
return build_configs
def ParseGnList(value):
if not value:
return []
if value.startswith('[') and value.endswith(']'):
gn_list = value.strip("[]").replace(
"\"", "").replace(" ", "").split(",")
if not gn_list[0]:
return []
else:
return gn_list
def GetAllDependentJars(deps_configs_data):
configs_to_process = deps_configs_data
deps_jars = set()
while configs_to_process:
deps_config = configs_to_process.pop()
child_configs = LoadBuildConfigs(
deps_config['deps_info']['deps_configs'])
deps_jars.add(deps_config['deps_info']['jar_path'])
configs_to_process += child_configs
return deps_jars
def main(argv):
parser = optparse.OptionParser()
parser.add_option('--build-config', help='Path to build_config output')
parser.add_option('--deps-configs',
help='GN-list of dependent build_config files')
parser.add_option('--jar-path', help='Path to the .jar')
options, args = parser.parse_args(argv)
deps_configs_list = ParseGnList(options.deps_configs)
deps_configs_data = LoadBuildConfigs(deps_configs_list)
deps_jars_set = GetAllDependentJars(deps_configs_data)
config = {
"deps_info": {
"name": os.path.basename(options.build_config),
"jar_path": options.jar_path,
# List of configs depended on by this config. Not recursive.
"deps_configs": deps_configs_list,
# List of all jars needed by all dependencies of this config (recursive).
"deps_jars": list(deps_jars_set)
}
}
with open(options.build_config, 'w') as file:
json.dump(config, file)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| 1,131 |
763 | package org.batfish.common.util.serialization.guava;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ser.std.StdDelegatingSerializer;
import com.fasterxml.jackson.databind.util.Converter;
import com.google.common.collect.RangeSet;
import javax.annotation.Nonnull;
/** Custom serializer for {@link RangeSet} */
public final class RangeSetSerializer extends StdDelegatingSerializer {
public RangeSetSerializer(@Nonnull JavaType type) {
super(new RangeSetSerializerConverter(type));
}
@Override
protected @Nonnull StdDelegatingSerializer withDelegate(
Converter<Object, ?> converter, JavaType delegateType, JsonSerializer<?> delegateSerializer) {
return this;
}
}
| 260 |
47,529 | <gh_stars>1000+
/*
* Copyright (c) 2016-present, RxJava 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 io.reactivex.rxjava3.internal.operators.observable;
import static org.mockito.Mockito.*;
import org.junit.*;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.internal.util.ExceptionHelper;
import io.reactivex.rxjava3.testsupport.TestHelper;
public class ObservableFinallyTest extends RxJavaTest {
private Action aAction0;
private Observer<String> observer;
// mocking has to be unchecked, unfortunately
@Before
public void before() {
aAction0 = mock(Action.class);
observer = TestHelper.mockObserver();
}
private void checkActionCalled(Observable<String> input) {
input.doAfterTerminate(aAction0).subscribe(observer);
try {
verify(aAction0, times(1)).run();
} catch (Throwable e) {
throw ExceptionHelper.wrapOrThrow(e);
}
}
@Test
public void finallyCalledOnComplete() {
checkActionCalled(Observable.fromArray("1", "2", "3"));
}
@Test
public void finallyCalledOnError() {
checkActionCalled(Observable.<String> error(new RuntimeException("expected")));
}
}
| 615 |
1,334 | <reponame>jordanm88/Django-CRM<gh_stars>1000+
from drf_yasg import openapi
organization_params_in_header = openapi.Parameter(
"org", openapi.IN_HEADER, required=True, type=openapi.TYPE_INTEGER
)
organization_params = [
organization_params_in_header,
]
event_list_get_params = [
organization_params_in_header,
openapi.Parameter("name", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter("created_by", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter("assigned_users", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter(
"date_of_meeting",
openapi.IN_QUERY,
type=openapi.FORMAT_DATE,
example="2021-01-01",
),
]
event_detail_post_params = [
organization_params_in_header,
openapi.Parameter(
"event_attachment",
openapi.IN_QUERY,
type=openapi.TYPE_FILE,
),
openapi.Parameter("comment", openapi.IN_QUERY, type=openapi.TYPE_STRING),
]
event_create_post_params = [
organization_params_in_header,
openapi.Parameter(
"name", openapi.IN_QUERY, required=True, type=openapi.TYPE_STRING
),
openapi.Parameter(
"event_type",
openapi.IN_QUERY,
type=openapi.TYPE_STRING,
required=True,
enum=["Recurring", "Non-Recurring"],
),
openapi.Parameter(
"contacts",
openapi.IN_QUERY,
type=openapi.TYPE_STRING,
required=True,
),
openapi.Parameter(
"start_date", openapi.IN_QUERY, type=openapi.FORMAT_DATE, example="2021-01-01"
),
openapi.Parameter(
"start_time", openapi.IN_QUERY, type=openapi.FORMAT_DATETIME, example="13:01:01"
),
openapi.Parameter(
"end_date", openapi.IN_QUERY, type=openapi.FORMAT_DATE, example="2021-01-01"
),
openapi.Parameter(
"end_time", openapi.IN_QUERY, type=openapi.FORMAT_DATETIME, example="13:01:01"
),
openapi.Parameter(
"teams",
openapi.IN_QUERY,
type=openapi.TYPE_STRING,
),
openapi.Parameter("assigned_to", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter("description", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter("recurring_days", openapi.IN_QUERY, type=openapi.TYPE_STRING),
]
event_comment_edit_params = [
organization_params_in_header,
openapi.Parameter("comment", openapi.IN_QUERY, type=openapi.TYPE_STRING),
]
| 1,083 |
1,350 | <reponame>Shashi-rk/azure-sdk-for-java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.desktopvirtualization.models;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
/** Resource collection API of PrivateEndpointConnections. */
public interface PrivateEndpointConnections {
/**
* List private endpoint connections associated with hostpool.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param hostPoolName The name of the host pool within the specified resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of private endpoint connection associated with the specified storage account.
*/
PagedIterable<PrivateEndpointConnectionWithSystemData> listByHostPool(
String resourceGroupName, String hostPoolName);
/**
* List private endpoint connections associated with hostpool.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param hostPoolName The name of the host pool within the specified resource group.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of private endpoint connection associated with the specified storage account.
*/
PagedIterable<PrivateEndpointConnectionWithSystemData> listByHostPool(
String resourceGroupName, String hostPoolName, Context context);
/**
* Get a private endpoint connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param hostPoolName The name of the host pool within the specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a private endpoint connection.
*/
PrivateEndpointConnectionWithSystemData getByHostPool(
String resourceGroupName, String hostPoolName, String privateEndpointConnectionName);
/**
* Get a private endpoint connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param hostPoolName The name of the host pool within the specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a private endpoint connection.
*/
Response<PrivateEndpointConnectionWithSystemData> getByHostPoolWithResponse(
String resourceGroupName, String hostPoolName, String privateEndpointConnectionName, Context context);
/**
* Remove a connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param hostPoolName The name of the host pool within the specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
void deleteByHostPool(String resourceGroupName, String hostPoolName, String privateEndpointConnectionName);
/**
* Remove a connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param hostPoolName The name of the host pool within the specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
Response<Void> deleteByHostPoolWithResponse(
String resourceGroupName, String hostPoolName, String privateEndpointConnectionName, Context context);
/**
* Approve or reject a private endpoint connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param hostPoolName The name of the host pool within the specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param connection Object containing the updated connection.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
PrivateEndpointConnectionWithSystemData updateByHostPool(
String resourceGroupName,
String hostPoolName,
String privateEndpointConnectionName,
PrivateEndpointConnection connection);
/**
* Approve or reject a private endpoint connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param hostPoolName The name of the host pool within the specified resource group.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param connection Object containing the updated connection.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
Response<PrivateEndpointConnectionWithSystemData> updateByHostPoolWithResponse(
String resourceGroupName,
String hostPoolName,
String privateEndpointConnectionName,
PrivateEndpointConnection connection,
Context context);
/**
* List private endpoint connections.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of private endpoint connection associated with the specified storage account.
*/
PagedIterable<PrivateEndpointConnectionWithSystemData> listByWorkspace(
String resourceGroupName, String workspaceName);
/**
* List private endpoint connections.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return list of private endpoint connection associated with the specified storage account.
*/
PagedIterable<PrivateEndpointConnectionWithSystemData> listByWorkspace(
String resourceGroupName, String workspaceName, Context context);
/**
* Get a private endpoint connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a private endpoint connection.
*/
PrivateEndpointConnectionWithSystemData getByWorkspace(
String resourceGroupName, String workspaceName, String privateEndpointConnectionName);
/**
* Get a private endpoint connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a private endpoint connection.
*/
Response<PrivateEndpointConnectionWithSystemData> getByWorkspaceWithResponse(
String resourceGroupName, String workspaceName, String privateEndpointConnectionName, Context context);
/**
* Remove a connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
void deleteByWorkspace(String resourceGroupName, String workspaceName, String privateEndpointConnectionName);
/**
* Remove a connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
Response<Void> deleteByWorkspaceWithResponse(
String resourceGroupName, String workspaceName, String privateEndpointConnectionName, Context context);
/**
* Approve or reject a private endpoint connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param connection Object containing the updated connection.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
PrivateEndpointConnectionWithSystemData updateByWorkspace(
String resourceGroupName,
String workspaceName,
String privateEndpointConnectionName,
PrivateEndpointConnection connection);
/**
* Approve or reject a private endpoint connection.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param workspaceName The name of the workspace.
* @param privateEndpointConnectionName The name of the private endpoint connection associated with the Azure
* resource.
* @param connection Object containing the updated connection.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the Private Endpoint Connection resource.
*/
Response<PrivateEndpointConnectionWithSystemData> updateByWorkspaceWithResponse(
String resourceGroupName,
String workspaceName,
String privateEndpointConnectionName,
PrivateEndpointConnection connection,
Context context);
}
| 4,167 |
432 | <filename>sys/gnu/vfs/ext2fs/ext2_extern.h
/*
* modified for EXT2FS support in Lites 1.1
*
* Aug 1995, <NAME> (<EMAIL>)
* University of Utah, Department of Computer Science
*/
/*-
* Copyright (c) 1991, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)ffs_extern.h 8.3 (Berkeley) 4/16/94
* $FreeBSD: src/sys/gnu/ext2fs/ext2_extern.h,v 1.22.6.1 2000/11/05 19:17:40 bde Exp $
*/
#ifndef _VFS_GNU_EXT2FS_EXT2_EXTERN_H_
#define _VFS_GNU_EXT2FS_EXT2_EXTERN_H_
struct ext2_dinode;
struct ext2_inode;
struct inode;
struct mount;
struct vfsconf;
struct vnode;
struct indir;
struct statfs;
struct sockaddr;
int ext2_alloc (struct inode *,
daddr_t, daddr_t, int, struct ucred *, daddr_t *);
int ext2_balloc (struct inode *,
daddr_t, int, struct ucred *, struct buf **, int);
int ext2_blkatoff (struct vnode *, off_t, char **, struct buf **);
void ext2_blkfree (struct inode *, daddr_t, long);
daddr_t ext2_blkpref (struct inode *, daddr_t, int, daddr_t *, daddr_t);
int ext2_bmap (struct vop_bmap_args *);
int ext2_reallocblks (struct vop_reallocblks_args *);
int ext2_reclaim (struct vop_reclaim_args *);
void ext2_setblock (struct ext2_sb_info *, u_char *, daddr_t);
int ext2_truncate (struct vnode *, off_t, int, struct ucred *);
int ext2_update (struct vnode *, int);
int ext2_valloc (struct vnode *, int, struct ucred *, struct vnode **);
int ext2_vfree (struct vnode *, ino_t, int);
int ext2_lookup (struct vop_old_lookup_args *);
int ext2_readdir (struct vop_readdir_args *);
void ext2_print_dinode (struct ext2_dinode *);
void ext2_print_inode (struct inode *);
int ext2_direnter (struct inode *,
struct vnode *, struct componentname *);
int ext2_dirremove (struct vnode *, struct componentname *);
int ext2_dirrewrite (struct inode *,
struct inode *, struct componentname *);
int ext2_dirempty (struct inode *, ino_t, struct ucred *);
int ext2_checkpath (struct inode *, struct inode *, struct ucred *);
struct ext2_group_desc *get_group_desc (struct mount *,
unsigned int, struct buf **);
int ext2_group_sparse (int group);
void ext2_discard_prealloc (struct inode *);
int ext2_inactive (struct vop_inactive_args *);
int ext2_new_block (struct mount *mp, unsigned long goal,
u_int32_t *prealloc_count,
u_int32_t *prealloc_block);
ino_t ext2_new_inode (const struct inode *dir, int mode);
unsigned long ext2_count_free (struct buf *map, unsigned int numchars);
void ext2_free_blocks (struct mount *mp, unsigned long block,
unsigned long count);
void ext2_free_inode (struct inode *inode);
void ext2_ei2di (struct ext2_inode *ei, struct ext2_dinode *di);
void ext2_di2ei (struct ext2_dinode *di, struct ext2_inode *ei);
void mark_buffer_dirty (struct buf *bh);
int ext2_getlbns(struct vnode *, ext2_daddr_t, struct indir *, int *);
void ext2_itimes(struct vnode *vp);
struct vnode *ext2_ihashget(cdev_t, ino_t);
int ext2_ihashins(struct inode *);
void ext2_ihashrem(struct inode *);
void ext2_dirbad(struct inode *, doff_t, char *);
int ext2_check_export(struct mount *, struct sockaddr *, int *,
struct ucred **);
int ext2_vinit(struct mount *, struct vnode **);
int ext2_vnoperate(struct vop_generic_args *);
int ext2_vnoperatefifo(struct vop_generic_args *);
int ext2_vnoperatespec(struct vop_generic_args *);
int ext2_uninit(struct vfsconf *);
void ext2_ihashinit(void);
struct vnode *ext2_ihashlookup(cdev_t dev, ino_t inum);
int ext2_ihashcheck(cdev_t dev, ino_t inum);
int ext2_check_descriptors(struct ext2_sb_info *sb);
int ext2_statfs(struct mount *mp, struct statfs *sbp, struct ucred *cred);
/*
* This macro allows the ufs code to distinguish between an EXT2 and a
* non-ext2(FFS/LFS) vnode.
*/
#define IS_EXT2_VNODE(vp) (vp->v_mount->mnt_stat.f_type == MOUNT_EXT2FS)
#endif /* !_VFS_GNU_EXT2FS_EXT2_EXTERN_H_ */
| 1,995 |
844 | from __future__ import absolute_import, division, print_function
import gzip
from datashape import discover, dshape
from collections import Iterator
from toolz import partial, concat
import uuid
import os
from ..compatibility import unicode
from ..chunks import chunks
from ..drop import drop
from ..temp import Temp
from ..append import append
from ..convert import convert
from ..resource import resource
class TextFile(object):
canonical_extension = 'txt'
def __init__(self, path, **kwargs):
self.path = path
@property
def open(self):
if self.path.split(os.path.extsep)[-1] == 'gz':
return gzip.open
else:
return open
@convert.register(Iterator, (TextFile, Temp(TextFile)), cost=0.1)
def textfile_to_iterator(data, **kwargs):
with data.open(data.path) as f:
for line in f:
yield line
@convert.register(Iterator, chunks(TextFile), cost=0.1)
def chunks_textfile_to_iterator(data, **kwargs):
return concat(map(partial(convert, Iterator), data))
@discover.register((TextFile, Temp(TextFile)))
def discover_textfile(data, **kwargs):
return dshape('var * string')
@append.register((Temp(TextFile), TextFile), Iterator)
def append_iterator_to_textfile(target, source, **kwargs):
with target.open(target.path, 'a') as f:
for item in source:
f.write(unicode(item))
f.write('\n') # TODO: detect OS-level newline character
return target
@append.register(TextFile, object)
def append_anything_to_textfile(target, source, **kwargs):
return append(target, convert(Iterator, source, **kwargs), **kwargs)
@convert.register(Temp(TextFile), Iterator)
def iterator_to_temp_textfile(seq, **kwargs):
fn = str(uuid.uuid1())
txt = Temp(TextFile)(fn)
return append(txt, seq, **kwargs)
@resource.register('.+\.(txt|log)(.gz)?')
def resource_sas(uri, **kwargs):
return TextFile(uri)
@drop.register(TextFile)
def drop_textfile(data, **kwargs):
os.remove(data.path)
| 753 |
640 |
typedef unsigned char uint8_t;
void do_something( uint8_t param1, uint8_t param2)
{
}
void main()
{
do_something( 20 * 0.45 , 0.5 * 40);
}
| 71 |
777 | <reponame>google-ar/chromium
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_SHOWCASE_COMMON_COORDINATOR_H_
#define IOS_SHOWCASE_COMMON_COORDINATOR_H_
#import <Foundation/Foundation.h>
// This protocol is the common interface to the simple non-production
// coordinators that will initialize, set up and present production view
// controllers, usually with completely mocked data.
@protocol Coordinator<NSObject>
// The base view controller used to present the view controller that this
// coordinator drives.
@property(nonatomic, weak) UIViewController* baseViewController;
// Typically, this initializes a view controller, sets it up and presents it.
- (void)start;
@end
#endif // IOS_SHOWCASE_COMMON_COORDINATOR_H_
| 251 |
3,976 | <reponame>YAMLONG/Deformable-ConvNets
import resnet_v1_101_deeplab
import resnet_v1_101_deeplab_dcn
| 50 |
743 | package pl.allegro.tech.hermes.consumers.consumer.sender.http.headers;
import pl.allegro.tech.hermes.api.EndpointAddress;
public interface BatchHttpHeadersProvider {
HttpRequestHeaders getHeaders(EndpointAddress address);
}
| 76 |
337 | <filename>j2k/testData/fileOrElement/detectProperties/FieldUsagesInFactoryMethods.java
class C {
final int myArg1;
int myArg2;
int myArg3;
C(int arg1, int arg2, int arg3) {
this(arg1);
myArg2 = arg2;
myArg3 = arg3;
}
C(int arg1, int arg2) {
this(arg1);
myArg2 = arg2;
myArg3 = 0;
}
C(int arg1) {
myArg1 = arg1;
myArg2 = 0;
myArg3 = 0;
}
int getArg1() {
return myArg1;
}
int getArg2() {
return myArg2;
}
int getArg3() {
return myArg3;
}
}
| 262 |
575 | <reponame>Ron423c/chromium
// 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 <cstdint>
#include <string>
#include "base/base_paths.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/check_op.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/notreached.h"
#include "base/optional.h"
#include "base/path_service.h"
#include "base/process/process.h"
#include "base/run_loop.h"
#include "base/synchronization/lock.h"
#include "base/test/bind.h"
#include "base/test/multiprocess_test.h"
#include "base/test/task_environment.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "build/build_config.h"
#include "mojo/core/core.h"
#include "mojo/core/node_controller.h"
#include "mojo/core/test/mojo_test_base.h"
#include "mojo/public/c/system/invitation.h"
#include "mojo/public/cpp/platform/named_platform_channel.h"
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/system/invitation.h"
#include "mojo/public/cpp/system/platform_handle.h"
namespace mojo {
namespace core {
namespace {
enum class TransportType {
kChannel,
kChannelServer,
};
const char kSecondaryChannelHandleSwitch[] = "test-secondary-channel-handle";
class InvitationTest : public test::MojoTestBase {
public:
InvitationTest() = default;
~InvitationTest() override = default;
protected:
static base::Process LaunchChildTestClient(
const std::string& test_client_name,
MojoHandle* primordial_pipes,
size_t num_primordial_pipes,
TransportType transport_type,
MojoSendInvitationFlags send_flags,
MojoProcessErrorHandler error_handler = nullptr,
uintptr_t error_handler_context = 0,
base::CommandLine* custom_command_line = nullptr,
base::LaunchOptions* custom_launch_options = nullptr);
static void SendInvitationToClient(
PlatformHandle endpoint_handle,
base::ProcessHandle process,
MojoHandle* primordial_pipes,
size_t num_primordial_pipes,
TransportType transport_type,
MojoSendInvitationFlags flags,
MojoProcessErrorHandler error_handler,
uintptr_t error_handler_context,
base::StringPiece isolated_invitation_name);
private:
base::test::TaskEnvironment task_environment_;
DISALLOW_COPY_AND_ASSIGN(InvitationTest);
};
void PrepareToPassRemoteEndpoint(PlatformChannel* channel,
base::LaunchOptions* options,
base::CommandLine* command_line,
base::StringPiece switch_name = {}) {
std::string value;
#if defined(OS_FUCHSIA)
channel->PrepareToPassRemoteEndpoint(&options->handles_to_transfer, &value);
#elif defined(OS_MAC)
channel->PrepareToPassRemoteEndpoint(&options->mach_ports_for_rendezvous,
&value);
#elif defined(OS_POSIX)
channel->PrepareToPassRemoteEndpoint(&options->fds_to_remap, &value);
#elif defined(OS_WIN)
channel->PrepareToPassRemoteEndpoint(&options->handles_to_inherit, &value);
#else
#error "Platform not yet supported."
#endif
if (switch_name.empty())
switch_name = PlatformChannel::kHandleSwitch;
command_line->AppendSwitchASCII(switch_name.as_string(), value);
}
TEST_F(InvitationTest, Create) {
MojoHandle invitation;
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateInvitation(nullptr, &invitation));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
MojoCreateInvitationOptions options;
options.struct_size = sizeof(options);
options.flags = MOJO_CREATE_INVITATION_FLAG_NONE;
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateInvitation(&options, &invitation));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
}
TEST_F(InvitationTest, InvalidArguments) {
MojoHandle invitation;
MojoCreateInvitationOptions invalid_create_options;
invalid_create_options.struct_size = 0;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoCreateInvitation(&invalid_create_options, &invitation));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoCreateInvitation(nullptr, nullptr));
// We need a valid invitation handle to exercise some of the other invalid
// argument cases below.
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateInvitation(nullptr, &invitation));
MojoHandle pipe;
MojoAttachMessagePipeToInvitationOptions invalid_attach_options;
invalid_attach_options.struct_size = 0;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoAttachMessagePipeToInvitation(MOJO_HANDLE_INVALID, "x", 1,
nullptr, &pipe));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoAttachMessagePipeToInvitation(invitation, "x", 1,
&invalid_attach_options, &pipe));
EXPECT_EQ(
MOJO_RESULT_INVALID_ARGUMENT,
MojoAttachMessagePipeToInvitation(invitation, "x", 1, nullptr, nullptr));
MojoExtractMessagePipeFromInvitationOptions invalid_extract_options;
invalid_extract_options.struct_size = 0;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoExtractMessagePipeFromInvitation(MOJO_HANDLE_INVALID, "x", 1,
nullptr, &pipe));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoExtractMessagePipeFromInvitation(
invitation, "x", 1, &invalid_extract_options, &pipe));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoExtractMessagePipeFromInvitation(invitation, "x", 1, nullptr,
nullptr));
PlatformChannel channel;
MojoPlatformHandle endpoint_handle;
endpoint_handle.struct_size = sizeof(endpoint_handle);
PlatformHandle::ToMojoPlatformHandle(
channel.TakeLocalEndpoint().TakePlatformHandle(), &endpoint_handle);
ASSERT_NE(endpoint_handle.type, MOJO_PLATFORM_HANDLE_TYPE_INVALID);
MojoInvitationTransportEndpoint valid_endpoint;
valid_endpoint.struct_size = sizeof(valid_endpoint);
valid_endpoint.type = MOJO_INVITATION_TRANSPORT_TYPE_CHANNEL;
valid_endpoint.num_platform_handles = 1;
valid_endpoint.platform_handles = &endpoint_handle;
MojoSendInvitationOptions invalid_send_options;
invalid_send_options.struct_size = 0;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoSendInvitation(MOJO_HANDLE_INVALID, nullptr, &valid_endpoint,
nullptr, 0, nullptr));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoSendInvitation(invitation, nullptr, &valid_endpoint, nullptr, 0,
&invalid_send_options));
MojoInvitationTransportEndpoint invalid_endpoint;
invalid_endpoint.struct_size = 0;
invalid_endpoint.type = MOJO_INVITATION_TRANSPORT_TYPE_CHANNEL;
invalid_endpoint.num_platform_handles = 1;
invalid_endpoint.platform_handles = &endpoint_handle;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoSendInvitation(invitation, nullptr, &invalid_endpoint, nullptr,
0, nullptr));
invalid_endpoint.struct_size = sizeof(invalid_endpoint);
invalid_endpoint.num_platform_handles = 0;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoSendInvitation(invitation, nullptr, &invalid_endpoint, nullptr,
0, nullptr));
MojoPlatformHandle invalid_platform_handle;
invalid_platform_handle.struct_size = 0;
invalid_endpoint.num_platform_handles = 1;
invalid_endpoint.platform_handles = &invalid_platform_handle;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoSendInvitation(invitation, nullptr, &invalid_endpoint, nullptr,
0, nullptr));
invalid_platform_handle.struct_size = sizeof(invalid_platform_handle);
invalid_platform_handle.type = MOJO_PLATFORM_HANDLE_TYPE_INVALID;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoSendInvitation(invitation, nullptr, &invalid_endpoint, nullptr,
0, nullptr));
invalid_endpoint.num_platform_handles = 1;
invalid_endpoint.platform_handles = nullptr;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoSendInvitation(invitation, nullptr, &invalid_endpoint, nullptr,
0, nullptr));
MojoHandle accepted_invitation;
MojoAcceptInvitationOptions invalid_accept_options;
invalid_accept_options.struct_size = 0;
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoAcceptInvitation(nullptr, nullptr, &accepted_invitation));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoAcceptInvitation(&valid_endpoint, &invalid_accept_options,
&accepted_invitation));
EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
MojoAcceptInvitation(&valid_endpoint, nullptr, nullptr));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
}
TEST_F(InvitationTest, AttachAndExtractLocally) {
MojoHandle invitation;
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateInvitation(nullptr, &invitation));
MojoHandle pipe0 = MOJO_HANDLE_INVALID;
EXPECT_EQ(MOJO_RESULT_OK, MojoAttachMessagePipeToInvitation(
invitation, "x", 1, nullptr, &pipe0));
EXPECT_NE(MOJO_HANDLE_INVALID, pipe0);
MojoHandle pipe1 = MOJO_HANDLE_INVALID;
EXPECT_EQ(MOJO_RESULT_OK, MojoExtractMessagePipeFromInvitation(
invitation, "x", 1, nullptr, &pipe1));
EXPECT_NE(MOJO_HANDLE_INVALID, pipe1);
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
// Should be able to communicate over the pipe.
const std::string kMessage = "RSVP LOL";
WriteMessage(pipe0, kMessage);
EXPECT_EQ(kMessage, ReadMessage(pipe1));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(pipe0));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(pipe1));
}
TEST_F(InvitationTest, ClosedInvitationClosesAttachments) {
MojoHandle invitation;
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateInvitation(nullptr, &invitation));
MojoHandle pipe = MOJO_HANDLE_INVALID;
EXPECT_EQ(MOJO_RESULT_OK, MojoAttachMessagePipeToInvitation(
invitation, "x", 1, nullptr, &pipe));
EXPECT_NE(MOJO_HANDLE_INVALID, pipe);
// Closing the invitation should close |pipe|'s peer.
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(pipe));
}
TEST_F(InvitationTest, AttachNameInUse) {
MojoHandle invitation;
EXPECT_EQ(MOJO_RESULT_OK, MojoCreateInvitation(nullptr, &invitation));
MojoHandle pipe0 = MOJO_HANDLE_INVALID;
EXPECT_EQ(MOJO_RESULT_OK, MojoAttachMessagePipeToInvitation(
invitation, "x", 1, nullptr, &pipe0));
EXPECT_NE(MOJO_HANDLE_INVALID, pipe0);
MojoHandle pipe1 = MOJO_HANDLE_INVALID;
EXPECT_EQ(
MOJO_RESULT_ALREADY_EXISTS,
MojoAttachMessagePipeToInvitation(invitation, "x", 1, nullptr, &pipe1));
EXPECT_EQ(MOJO_HANDLE_INVALID, pipe1);
EXPECT_EQ(MOJO_RESULT_OK, MojoAttachMessagePipeToInvitation(
invitation, "y", 1, nullptr, &pipe1));
EXPECT_NE(MOJO_HANDLE_INVALID, pipe1);
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(pipe0));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(pipe1));
}
// static
base::Process InvitationTest::LaunchChildTestClient(
const std::string& test_client_name,
MojoHandle* primordial_pipes,
size_t num_primordial_pipes,
TransportType transport_type,
MojoSendInvitationFlags send_flags,
MojoProcessErrorHandler error_handler,
uintptr_t error_handler_context,
base::CommandLine* custom_command_line,
base::LaunchOptions* custom_launch_options) {
base::CommandLine default_command_line =
base::GetMultiProcessTestChildBaseCommandLine();
base::CommandLine& command_line =
custom_command_line ? *custom_command_line : default_command_line;
base::LaunchOptions default_launch_options;
base::LaunchOptions& launch_options =
custom_launch_options ? *custom_launch_options : default_launch_options;
#if defined(OS_WIN)
launch_options.start_hidden = true;
#endif
#if !defined(OS_FUCHSIA)
base::Optional<NamedPlatformChannel> named_channel;
#endif
base::Optional<PlatformChannel> channel;
PlatformHandle local_endpoint_handle;
if (transport_type == TransportType::kChannel) {
channel.emplace();
PrepareToPassRemoteEndpoint(&channel.value(), &launch_options,
&command_line);
local_endpoint_handle = channel->TakeLocalEndpoint().TakePlatformHandle();
} else {
#if !defined(OS_FUCHSIA)
NamedPlatformChannel::Options named_channel_options;
#if !defined(OS_WIN)
CHECK(base::PathService::Get(base::DIR_TEMP,
&named_channel_options.socket_dir));
#endif
named_channel.emplace(named_channel_options);
named_channel->PassServerNameOnCommandLine(&command_line);
local_endpoint_handle =
named_channel->TakeServerEndpoint().TakePlatformHandle();
#else // !defined(OS_FUCHSIA)
NOTREACHED() << "Named pipe support does not exist for Mojo on Fuchsia.";
#endif // !defined(OS_FUCHSIA)
}
base::Process child_process = base::SpawnMultiProcessTestChild(
test_client_name, command_line, launch_options);
if (channel)
channel->RemoteProcessLaunchAttempted();
SendInvitationToClient(std::move(local_endpoint_handle),
child_process.Handle(), primordial_pipes,
num_primordial_pipes, transport_type, send_flags,
error_handler, error_handler_context, "");
return child_process;
}
// static
void InvitationTest::SendInvitationToClient(
PlatformHandle endpoint_handle,
base::ProcessHandle process,
MojoHandle* primordial_pipes,
size_t num_primordial_pipes,
TransportType transport_type,
MojoSendInvitationFlags flags,
MojoProcessErrorHandler error_handler,
uintptr_t error_handler_context,
base::StringPiece isolated_invitation_name) {
MojoPlatformHandle handle;
PlatformHandle::ToMojoPlatformHandle(std::move(endpoint_handle), &handle);
CHECK_NE(handle.type, MOJO_PLATFORM_HANDLE_TYPE_INVALID);
MojoHandle invitation;
CHECK_EQ(MOJO_RESULT_OK, MojoCreateInvitation(nullptr, &invitation));
for (uint32_t name = 0; name < num_primordial_pipes; ++name) {
CHECK_EQ(MOJO_RESULT_OK,
MojoAttachMessagePipeToInvitation(invitation, &name, 4, nullptr,
&primordial_pipes[name]));
}
MojoPlatformProcessHandle process_handle;
process_handle.struct_size = sizeof(process_handle);
#if defined(OS_WIN)
process_handle.value =
static_cast<uint64_t>(reinterpret_cast<uintptr_t>(process));
#else
process_handle.value = static_cast<uint64_t>(process);
#endif
MojoInvitationTransportEndpoint transport_endpoint;
transport_endpoint.struct_size = sizeof(transport_endpoint);
if (transport_type == TransportType::kChannel)
transport_endpoint.type = MOJO_INVITATION_TRANSPORT_TYPE_CHANNEL;
else
transport_endpoint.type = MOJO_INVITATION_TRANSPORT_TYPE_CHANNEL_SERVER;
transport_endpoint.num_platform_handles = 1;
transport_endpoint.platform_handles = &handle;
MojoSendInvitationOptions options;
options.struct_size = sizeof(options);
options.flags = flags;
if (flags & MOJO_SEND_INVITATION_FLAG_ISOLATED) {
options.isolated_connection_name = isolated_invitation_name.data();
options.isolated_connection_name_length =
static_cast<uint32_t>(isolated_invitation_name.size());
}
CHECK_EQ(MOJO_RESULT_OK,
MojoSendInvitation(invitation, &process_handle, &transport_endpoint,
error_handler, error_handler_context, &options));
}
class TestClientBase : public InvitationTest {
public:
static MojoHandle AcceptInvitation(MojoAcceptInvitationFlags flags,
base::StringPiece switch_name = {}) {
const auto& command_line = *base::CommandLine::ForCurrentProcess();
PlatformChannelEndpoint channel_endpoint;
#if !defined(OS_FUCHSIA)
channel_endpoint = NamedPlatformChannel::ConnectToServer(command_line);
#endif
if (!channel_endpoint.is_valid()) {
if (switch_name.empty()) {
channel_endpoint =
PlatformChannel::RecoverPassedEndpointFromCommandLine(command_line);
} else {
channel_endpoint = PlatformChannel::RecoverPassedEndpointFromString(
command_line.GetSwitchValueASCII(switch_name));
}
}
MojoPlatformHandle endpoint_handle;
PlatformHandle::ToMojoPlatformHandle(channel_endpoint.TakePlatformHandle(),
&endpoint_handle);
CHECK_NE(endpoint_handle.type, MOJO_PLATFORM_HANDLE_TYPE_INVALID);
MojoInvitationTransportEndpoint transport_endpoint;
transport_endpoint.struct_size = sizeof(transport_endpoint);
transport_endpoint.type = MOJO_INVITATION_TRANSPORT_TYPE_CHANNEL;
transport_endpoint.num_platform_handles = 1;
transport_endpoint.platform_handles = &endpoint_handle;
MojoAcceptInvitationOptions options;
options.struct_size = sizeof(options);
options.flags = flags;
MojoHandle invitation;
CHECK_EQ(MOJO_RESULT_OK,
MojoAcceptInvitation(&transport_endpoint, &options, &invitation));
return invitation;
}
private:
DISALLOW_COPY_AND_ASSIGN(TestClientBase);
};
#define DEFINE_TEST_CLIENT(name) \
class name##Impl : public TestClientBase { \
public: \
static void Run(); \
}; \
MULTIPROCESS_TEST_MAIN(name) { \
name##Impl::Run(); \
return 0; \
} \
void name##Impl::Run()
const std::string kTestMessage1 = "i am the pusher robot";
const std::string kTestMessage2 = "i push the messages down the pipe";
const std::string kTestMessage3 = "i am the shover robot";
const std::string kTestMessage4 = "i shove the messages down the pipe";
TEST_F(InvitationTest, SendInvitation) {
MojoHandle primordial_pipe;
base::Process child_process = LaunchChildTestClient(
"SendInvitationClient", &primordial_pipe, 1, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_NONE);
WriteMessage(primordial_pipe, kTestMessage1);
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE));
EXPECT_EQ(kTestMessage3, ReadMessage(primordial_pipe));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
DEFINE_TEST_CLIENT(SendInvitationClient) {
MojoHandle primordial_pipe;
MojoHandle invitation = AcceptInvitation(MOJO_ACCEPT_INVITATION_FLAG_NONE);
const uint32_t pipe_name = 0;
ASSERT_EQ(MOJO_RESULT_OK,
MojoExtractMessagePipeFromInvitation(invitation, &pipe_name, 4,
nullptr, &primordial_pipe));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE);
ASSERT_EQ(kTestMessage1, ReadMessage(primordial_pipe));
WriteMessage(primordial_pipe, kTestMessage3);
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
}
TEST_F(InvitationTest, SendInvitationMultiplePipes) {
MojoHandle pipes[2];
base::Process child_process = LaunchChildTestClient(
"SendInvitationMultiplePipesClient", pipes, 2, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_NONE);
WriteMessage(pipes[0], kTestMessage1);
WriteMessage(pipes[1], kTestMessage2);
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(pipes[0], MOJO_HANDLE_SIGNAL_READABLE));
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(pipes[1], MOJO_HANDLE_SIGNAL_READABLE));
EXPECT_EQ(kTestMessage3, ReadMessage(pipes[0]));
EXPECT_EQ(kTestMessage4, ReadMessage(pipes[1]));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(pipes[0]));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(pipes[1]));
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
DEFINE_TEST_CLIENT(SendInvitationMultiplePipesClient) {
MojoHandle pipes[2];
MojoHandle invitation = AcceptInvitation(MOJO_ACCEPT_INVITATION_FLAG_NONE);
const uint32_t pipe_names[] = {0, 1};
ASSERT_EQ(MOJO_RESULT_OK,
MojoExtractMessagePipeFromInvitation(invitation, &pipe_names[0], 4,
nullptr, &pipes[0]));
ASSERT_EQ(MOJO_RESULT_OK,
MojoExtractMessagePipeFromInvitation(invitation, &pipe_names[1], 4,
nullptr, &pipes[1]));
WaitForSignals(pipes[0], MOJO_HANDLE_SIGNAL_READABLE);
WaitForSignals(pipes[1], MOJO_HANDLE_SIGNAL_READABLE);
ASSERT_EQ(kTestMessage1, ReadMessage(pipes[0]));
ASSERT_EQ(kTestMessage2, ReadMessage(pipes[1]));
WriteMessage(pipes[0], kTestMessage3);
WriteMessage(pipes[1], kTestMessage4);
WaitForSignals(pipes[0], MOJO_HANDLE_SIGNAL_PEER_CLOSED);
WaitForSignals(pipes[1], MOJO_HANDLE_SIGNAL_PEER_CLOSED);
}
#if !defined(OS_FUCHSIA)
TEST_F(InvitationTest, SendInvitationWithServer) {
MojoHandle primordial_pipe;
base::Process child_process = LaunchChildTestClient(
"SendInvitationWithServerClient", &primordial_pipe, 1,
TransportType::kChannelServer, MOJO_SEND_INVITATION_FLAG_NONE);
WriteMessage(primordial_pipe, kTestMessage1);
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE));
EXPECT_EQ(kTestMessage3, ReadMessage(primordial_pipe));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
DEFINE_TEST_CLIENT(SendInvitationWithServerClient) {
MojoHandle primordial_pipe;
MojoHandle invitation = AcceptInvitation(MOJO_ACCEPT_INVITATION_FLAG_NONE);
const uint32_t pipe_name = 0;
ASSERT_EQ(MOJO_RESULT_OK,
MojoExtractMessagePipeFromInvitation(invitation, &pipe_name, 4,
nullptr, &primordial_pipe));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE);
ASSERT_EQ(kTestMessage1, ReadMessage(primordial_pipe));
WriteMessage(primordial_pipe, kTestMessage3);
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
}
#endif // !defined(OS_FUCHSIA)
const char kErrorMessage[] = "ur bad :(";
const char kDisconnectMessage[] = "go away plz";
class RemoteProcessState {
public:
RemoteProcessState()
: callback_task_runner_(base::SequencedTaskRunnerHandle::Get()) {}
~RemoteProcessState() = default;
bool disconnected() {
base::AutoLock lock(lock_);
return disconnected_;
}
void set_error_callback(base::RepeatingClosure callback) {
error_callback_ = std::move(callback);
}
void set_expected_error_message(const std::string& expected) {
expected_error_message_ = expected;
}
void NotifyError(const std::string& error_message, bool disconnected) {
base::AutoLock lock(lock_);
CHECK(!disconnected_);
EXPECT_NE(error_message.find(expected_error_message_), std::string::npos);
disconnected_ = disconnected;
++call_count_;
if (error_callback_)
callback_task_runner_->PostTask(FROM_HERE, error_callback_);
}
private:
const scoped_refptr<base::SequencedTaskRunner> callback_task_runner_;
base::Lock lock_;
int call_count_ = 0;
bool disconnected_ = false;
std::string expected_error_message_;
base::RepeatingClosure error_callback_;
DISALLOW_COPY_AND_ASSIGN(RemoteProcessState);
};
void TestProcessErrorHandler(uintptr_t context,
const MojoProcessErrorDetails* details) {
auto* state = reinterpret_cast<RemoteProcessState*>(context);
std::string error_message;
if (details->error_message) {
error_message =
std::string(details->error_message, details->error_message_length - 1);
}
state->NotifyError(error_message,
details->flags & MOJO_PROCESS_ERROR_FLAG_DISCONNECTED);
}
TEST_F(InvitationTest, ProcessErrors) {
RemoteProcessState process_state;
MojoHandle pipe;
base::Process child_process = LaunchChildTestClient(
"ProcessErrorsClient", &pipe, 1, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_NONE, &TestProcessErrorHandler,
reinterpret_cast<uintptr_t>(&process_state));
MojoMessageHandle message;
WaitForSignals(pipe, MOJO_HANDLE_SIGNAL_READABLE);
EXPECT_EQ(MOJO_RESULT_OK, MojoReadMessage(pipe, nullptr, &message));
base::RunLoop error_loop;
process_state.set_error_callback(error_loop.QuitClosure());
// Report this message as "bad". This should cause the error handler to be
// invoked and the RunLoop to be quit.
process_state.set_expected_error_message(kErrorMessage);
EXPECT_EQ(MOJO_RESULT_OK,
MojoNotifyBadMessage(message, kErrorMessage, sizeof(kErrorMessage),
nullptr));
error_loop.Run();
EXPECT_EQ(MOJO_RESULT_OK, MojoDestroyMessage(message));
// Now tell the child it can exit, and wait for it to disconnect.
base::RunLoop disconnect_loop;
process_state.set_error_callback(disconnect_loop.QuitClosure());
process_state.set_expected_error_message(std::string());
WriteMessage(pipe, kDisconnectMessage);
disconnect_loop.Run();
EXPECT_TRUE(process_state.disconnected());
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
DEFINE_TEST_CLIENT(ProcessErrorsClient) {
MojoHandle pipe;
MojoHandle invitation = AcceptInvitation(MOJO_ACCEPT_INVITATION_FLAG_NONE);
const uint32_t pipe_name = 0;
ASSERT_EQ(MOJO_RESULT_OK, MojoExtractMessagePipeFromInvitation(
invitation, &pipe_name, 4, nullptr, &pipe));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
// Send a message. Contents are irrelevant, the test process is just going to
// flag it as a bad.
WriteMessage(pipe, "doesn't matter");
// Wait for our goodbye before exiting.
WaitForSignals(pipe, MOJO_HANDLE_SIGNAL_READABLE);
EXPECT_EQ(kDisconnectMessage, ReadMessage(pipe));
}
TEST_F(InvitationTest, Reinvitation) {
// The gist of this test is that a process should be able to accept an
// invitation, lose its connection to the process network, and then accept a
// new invitation to re-establish communication.
// We pass an extra PlatformChannel endpoint to the child process which it
// will use to accept a secondary invitation after we sever its first
// connection.
PlatformChannel secondary_channel;
auto command_line = base::GetMultiProcessTestChildBaseCommandLine();
base::LaunchOptions launch_options;
PrepareToPassRemoteEndpoint(&secondary_channel, &launch_options,
&command_line, kSecondaryChannelHandleSwitch);
MojoHandle pipe;
base::Process child_process = LaunchChildTestClient(
"ReinvitationClient", &pipe, 1, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_NONE, nullptr, 0, &command_line,
&launch_options);
secondary_channel.RemoteProcessLaunchAttempted();
// Synchronize end-to-end communication first to ensure the process connection
// is fully established.
WriteMessage(pipe, kTestMessage1);
EXPECT_EQ(kTestMessage2, ReadMessage(pipe));
// Force-disconnect the child process.
Core::Get()->GetNodeController()->ForceDisconnectProcessForTesting(
child_process.Pid());
// The above disconnection should force pipe closure eventually.
WaitForSignals(pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
MojoClose(pipe);
// Now use our secondary channel to send a new invitation to the same process.
// It should be able to accept the new invitation and re-establish
// communication.
mojo::OutgoingInvitation new_invitation;
auto new_pipe = new_invitation.AttachMessagePipe(0);
mojo::OutgoingInvitation::Send(std::move(new_invitation),
child_process.Handle(),
secondary_channel.TakeLocalEndpoint());
WriteMessage(new_pipe.get().value(), kTestMessage3);
EXPECT_EQ(kTestMessage4, ReadMessage(new_pipe.get().value()));
WriteMessage(new_pipe.get().value(), kDisconnectMessage);
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
DEFINE_TEST_CLIENT(ReinvitationClient) {
MojoHandle pipe;
MojoHandle invitation = AcceptInvitation(MOJO_ACCEPT_INVITATION_FLAG_NONE);
const uint32_t pipe_name = 0;
ASSERT_EQ(MOJO_RESULT_OK, MojoExtractMessagePipeFromInvitation(
invitation, &pipe_name, 4, nullptr, &pipe));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
EXPECT_EQ(kTestMessage1, ReadMessage(pipe));
WriteMessage(pipe, kTestMessage2);
// Wait for the pipe to break due to forced process disconnection.
WaitForSignals(pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
MojoClose(pipe);
// Now grab the secondary channel and accept a new invitation from it.
PlatformChannelEndpoint new_endpoint =
PlatformChannel::RecoverPassedEndpointFromString(
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
kSecondaryChannelHandleSwitch));
auto secondary_invitation =
mojo::IncomingInvitation::Accept(std::move(new_endpoint));
auto new_pipe = secondary_invitation.ExtractMessagePipe(0);
// Ensure that the new connection is working end-to-end.
EXPECT_EQ(kTestMessage3, ReadMessage(new_pipe.get().value()));
WriteMessage(new_pipe.get().value(), kTestMessage4);
EXPECT_EQ(kDisconnectMessage, ReadMessage(new_pipe.get().value()));
}
TEST_F(InvitationTest, SendIsolatedInvitation) {
MojoHandle primordial_pipe;
base::Process child_process = LaunchChildTestClient(
"SendIsolatedInvitationClient", &primordial_pipe, 1,
TransportType::kChannel, MOJO_SEND_INVITATION_FLAG_ISOLATED);
WriteMessage(primordial_pipe, kTestMessage1);
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE));
EXPECT_EQ(kTestMessage3, ReadMessage(primordial_pipe));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
DEFINE_TEST_CLIENT(SendIsolatedInvitationClient) {
MojoHandle primordial_pipe;
MojoHandle invitation =
AcceptInvitation(MOJO_ACCEPT_INVITATION_FLAG_ISOLATED);
const uint32_t pipe_name = 0;
ASSERT_EQ(MOJO_RESULT_OK,
MojoExtractMessagePipeFromInvitation(invitation, &pipe_name, 4,
nullptr, &primordial_pipe));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE);
ASSERT_EQ(kTestMessage1, ReadMessage(primordial_pipe));
WriteMessage(primordial_pipe, kTestMessage3);
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
}
TEST_F(InvitationTest, SendMultipleIsolatedInvitations) {
// We send a secondary transport to the client process so we can send a second
// isolated invitation.
base::CommandLine command_line =
base::GetMultiProcessTestChildBaseCommandLine();
PlatformChannel secondary_transport;
base::LaunchOptions options;
PrepareToPassRemoteEndpoint(&secondary_transport, &options, &command_line,
kSecondaryChannelHandleSwitch);
MojoHandle primordial_pipe;
base::Process child_process = LaunchChildTestClient(
"SendMultipleIsolatedInvitationsClient", &primordial_pipe, 1,
TransportType::kChannel, MOJO_SEND_INVITATION_FLAG_ISOLATED, nullptr, 0,
&command_line, &options);
secondary_transport.RemoteProcessLaunchAttempted();
WriteMessage(primordial_pipe, kTestMessage1);
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE));
EXPECT_EQ(kTestMessage3, ReadMessage(primordial_pipe));
// Send another invitation over our seconary pipe. This should trample the
// original connection, breaking the first pipe.
MojoHandle new_pipe;
SendInvitationToClient(
secondary_transport.TakeLocalEndpoint().TakePlatformHandle(),
child_process.Handle(), &new_pipe, 1, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_ISOLATED, nullptr, 0, "");
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
// And the new pipe should be working.
WriteMessage(new_pipe, kTestMessage1);
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(new_pipe, MOJO_HANDLE_SIGNAL_READABLE));
EXPECT_EQ(kTestMessage3, ReadMessage(new_pipe));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(new_pipe));
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
DEFINE_TEST_CLIENT(SendMultipleIsolatedInvitationsClient) {
MojoHandle primordial_pipe;
MojoHandle invitation =
AcceptInvitation(MOJO_ACCEPT_INVITATION_FLAG_ISOLATED);
const uint32_t pipe_name = 0;
ASSERT_EQ(MOJO_RESULT_OK,
MojoExtractMessagePipeFromInvitation(invitation, &pipe_name, 4,
nullptr, &primordial_pipe));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE);
ASSERT_EQ(kTestMessage1, ReadMessage(primordial_pipe));
WriteMessage(primordial_pipe, kTestMessage3);
// The above pipe should get closed once we accept a new invitation.
invitation = AcceptInvitation(MOJO_ACCEPT_INVITATION_FLAG_ISOLATED,
kSecondaryChannelHandleSwitch);
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
primordial_pipe = MOJO_HANDLE_INVALID;
ASSERT_EQ(MOJO_RESULT_OK,
MojoExtractMessagePipeFromInvitation(invitation, &pipe_name, 4,
nullptr, &primordial_pipe));
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(invitation));
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_READABLE);
ASSERT_EQ(kTestMessage1, ReadMessage(primordial_pipe));
WriteMessage(primordial_pipe, kTestMessage3);
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
ASSERT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
}
TEST_F(InvitationTest, SendIsolatedInvitationWithDuplicateName) {
PlatformChannel channel1;
PlatformChannel channel2;
MojoHandle pipe0, pipe1;
const char kConnectionName[] = "there can be only one!";
SendInvitationToClient(
channel1.TakeLocalEndpoint().TakePlatformHandle(),
base::kNullProcessHandle, &pipe0, 1, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_ISOLATED, nullptr, 0, kConnectionName);
// Send another invitation with the same connection name. |pipe0| should be
// disconnected as the first invitation's connection is torn down.
SendInvitationToClient(
channel2.TakeLocalEndpoint().TakePlatformHandle(),
base::kNullProcessHandle, &pipe1, 1, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_ISOLATED, nullptr, 0, kConnectionName);
WaitForSignals(pipe0, MOJO_HANDLE_SIGNAL_PEER_CLOSED);
}
TEST_F(InvitationTest, SendIsolatedInvitationToSelf) {
PlatformChannel channel;
MojoHandle pipe0, pipe1;
SendInvitationToClient(channel.TakeLocalEndpoint().TakePlatformHandle(),
base::kNullProcessHandle, &pipe0, 1,
TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_ISOLATED, nullptr, 0, "");
SendInvitationToClient(channel.TakeRemoteEndpoint().TakePlatformHandle(),
base::kNullProcessHandle, &pipe1, 1,
TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_ISOLATED, nullptr, 0, "");
WriteMessage(pipe0, kTestMessage1);
EXPECT_EQ(kTestMessage1, ReadMessage(pipe1));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(pipe0));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(pipe1));
}
TEST_F(InvitationTest, BrokenInvitationTransportBreaksAttachedPipe) {
MojoHandle primordial_pipe;
base::Process child_process = LaunchChildTestClient(
"BrokenTransportClient", &primordial_pipe, 1, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_NONE);
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
TEST_F(InvitationTest, BrokenIsolatedInvitationTransportBreaksAttachedPipe) {
MojoHandle primordial_pipe;
base::Process child_process = LaunchChildTestClient(
"BrokenTransportClient", &primordial_pipe, 1, TransportType::kChannel,
MOJO_SEND_INVITATION_FLAG_ISOLATED);
EXPECT_EQ(MOJO_RESULT_OK,
WaitForSignals(primordial_pipe, MOJO_HANDLE_SIGNAL_PEER_CLOSED));
EXPECT_EQ(MOJO_RESULT_OK, MojoClose(primordial_pipe));
int wait_result = -1;
base::WaitForMultiprocessTestChildExit(
child_process, TestTimeouts::action_timeout(), &wait_result);
child_process.Close();
EXPECT_EQ(0, wait_result);
}
DEFINE_TEST_CLIENT(BrokenTransportClient) {
// No-op. Exit immediately without accepting any invitation.
}
} // namespace
} // namespace core
} // namespace mojo
| 15,419 |
3,690 | <reponame>corkiwang1122/LeetCode
#include <cstddef>
#include <cstdlib>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode dummy(0), *tail = &dummy;
for (div_t sum{0, 0}; sum.quot || l1 || l2; tail = tail->next) {
if (l1) { sum.quot += l1->val; l1 = l1->next; }
if (l2) { sum.quot += l2->val; l2 = l2->next; }
sum = div(sum.quot, 10);
tail->next = new ListNode(sum.rem);
}
return dummy.next;
}
};
| 317 |
1,157 | /*
* Copyright (c) 2020 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-10-11
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#define MXS_MODULE_NAME "commentfilter"
#include <maxscale/ccdefs.hh>
#include "commentconfig.hh"
namespace comment
{
namespace config = mxs::config;
config::Specification specification(MXS_MODULE_NAME, config::Specification::FILTER);
config::ParamString inject(
&specification,
"inject",
"This string is injected as a comment before the statement. If the string "
"contains $IP, it will be replaced with the IP of the client.",
config::ParamString::Quotes::REQUIRED);
}
CommentConfig::CommentConfig(const std::string& name)
: mxs::config::Configuration(name, &comment::specification)
{
add_native(&CommentConfig::inject, &comment::inject);
}
//static
void CommentConfig::populate(MXS_MODULE& info)
{
info.specification = &comment::specification;
}
| 366 |
6,192 | # -*- coding:utf-8 -*-
"""
Author:
zanshuxun, <EMAIL>
Reference:
[1] <NAME>, <NAME>, <NAME>. An Input-aware Factorization Machine for Sparse Prediction[C]//IJCAI. 2019: 1466-1472.
(https://www.ijcai.org/Proceedings/2019/0203.pdf)
"""
import tensorflow as tf
from tensorflow.python.keras.layers import Lambda
from ..feature_column import build_input_features, get_linear_logit, input_from_feature_columns, SparseFeat, \
VarLenSparseFeat
from ..layers.core import PredictionLayer, DNN
from ..layers.interaction import FM
from ..layers.utils import concat_func, add_func, combined_dnn_input, softmax
def IFM(linear_feature_columns, dnn_feature_columns, dnn_hidden_units=(256, 128, 64),
l2_reg_linear=0.00001, l2_reg_embedding=0.00001, l2_reg_dnn=0, seed=1024, dnn_dropout=0,
dnn_activation='relu', dnn_use_bn=False, task='binary'):
"""Instantiates the IFM Network architecture.
:param linear_feature_columns: An iterable containing all the features used by linear part of the model.
:param dnn_feature_columns: An iterable containing all the features used by deep part of the model.
:param dnn_hidden_units: list,list of positive integer or empty list, the layer number and units in each layer of DNN
:param l2_reg_linear: float. L2 regularizer strength applied to linear part
:param l2_reg_embedding: float. L2 regularizer strength applied to embedding vector
:param l2_reg_dnn: float. L2 regularizer strength applied to DNN
:param seed: integer ,to use as random seed.
:param dnn_dropout: float in [0,1), the probability we will drop out a given DNN coordinate.
:param dnn_activation: Activation function to use in DNN
:param dnn_use_bn: bool. Whether use BatchNormalization before activation or not in DNN
:param task: str, ``"binary"`` for binary logloss or ``"regression"`` for regression loss
:return: A Keras model instance.
"""
if not len(dnn_hidden_units) > 0:
raise ValueError("dnn_hidden_units is null!")
features = build_input_features(
linear_feature_columns + dnn_feature_columns)
sparse_feat_num = len(list(filter(lambda x: isinstance(x, SparseFeat) or isinstance(x, VarLenSparseFeat),
dnn_feature_columns)))
inputs_list = list(features.values())
sparse_embedding_list, _ = input_from_feature_columns(features, dnn_feature_columns,
l2_reg_embedding, seed)
if not len(sparse_embedding_list) > 0:
raise ValueError("there are no sparse features")
dnn_input = combined_dnn_input(sparse_embedding_list, [])
dnn_output = DNN(dnn_hidden_units, dnn_activation, l2_reg_dnn, dnn_dropout, dnn_use_bn, seed=seed)(dnn_input)
# here, dnn_output is the m'_{x}
dnn_output = tf.keras.layers.Dense(
sparse_feat_num, use_bias=False, kernel_initializer=tf.keras.initializers.glorot_normal(seed=seed))(dnn_output)
# input_aware_factor m_{x,i}
input_aware_factor = Lambda(lambda x: tf.cast(tf.shape(x)[-1], tf.float32) * softmax(x, dim=1))(dnn_output)
linear_logit = get_linear_logit(features, linear_feature_columns, seed=seed, prefix='linear',
l2_reg=l2_reg_linear, sparse_feat_refine_weight=input_aware_factor)
fm_input = concat_func(sparse_embedding_list, axis=1)
refined_fm_input = Lambda(lambda x: x[0] * tf.expand_dims(x[1], axis=-1))(
[fm_input, input_aware_factor])
fm_logit = FM()(refined_fm_input)
final_logit = add_func([linear_logit, fm_logit])
output = PredictionLayer(task)(final_logit)
model = tf.keras.models.Model(inputs=inputs_list, outputs=output)
return model
| 1,487 |
5,316 | <reponame>pgliaskovitis/aerosolve
package com.airbnb.aerosolve.core.transforms;
import com.airbnb.aerosolve.core.FeatureVector;
import com.airbnb.aerosolve.core.util.TransformUtil;
import com.airbnb.aerosolve.core.util.Util;
import com.typesafe.config.Config;
import java.util.Map;
import java.util.Map.Entry;
/**
* Buckets float features and places them in a new float column.
*/
public class BucketFloatTransform implements Transform {
private String fieldName1;
private double bucket;
private String outputName;
@Override
public void configure(Config config, String key) {
fieldName1 = config.getString(key + ".field1");
bucket = config.getDouble(key + ".bucket");
outputName = config.getString(key + ".output");
}
@Override
public void doTransform(FeatureVector featureVector) {
Map<String, Map<String, Double>> floatFeatures = featureVector.getFloatFeatures();
if (floatFeatures == null) {
return;
}
Map<String, Double> feature1 = floatFeatures.get(fieldName1);
if (feature1 == null || feature1.isEmpty()) {
return;
}
Map<String, Double> output = Util.getOrCreateFloatFeature(outputName, floatFeatures);
for (Entry<String, Double> feature : feature1.entrySet()) {
Double dbl = TransformUtil.quantize(feature.getValue(), bucket);
Double newVal = feature.getValue() - dbl;
String name = feature.getKey() + '[' + bucket + "]=" + dbl;
output.put(name, newVal);
}
}
}
| 501 |
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.api.debugger.providers;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.netbeans.spi.debugger.ui.BreakpointType;
/**
*
* @author <NAME>
*/
@BreakpointType.Registration(displayName="Test")
public class TestBreakpointType extends BreakpointType {
public static Object ACTION_OBJECT = new Object();
public static Set<TestBreakpointType> INSTANCES = new HashSet<TestBreakpointType>();
public TestBreakpointType() {
INSTANCES.add(this);
}
@Override
public JComponent getCustomizer() {
return new JPanel();
}
@Override
public String getCategoryDisplayName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isDefault() {
throw new UnsupportedOperationException("Not supported yet.");
}
@BreakpointType.Registration(displayName="Test2")
public static BreakpointType getTest2BreakpointType() {
return new BreakpointType() {
@Override
public String getCategoryDisplayName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public JComponent getCustomizer() {
return new JPanel();
}
@Override
public boolean isDefault() {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
}
| 792 |
2,151 | <filename>src/chromium/cc/paint/draw_image.cc
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/paint/draw_image.h"
namespace cc {
namespace {
// Helper funciton to extract a scale from the matrix. Returns true on success
// and false on failure.
bool ExtractScale(const SkMatrix& matrix, SkSize* scale) {
*scale = SkSize::Make(matrix.getScaleX(), matrix.getScaleY());
if (matrix.getType() & SkMatrix::kAffine_Mask) {
if (!matrix.decomposeScale(scale)) {
scale->set(1, 1);
return false;
}
}
return true;
}
} // namespace
DrawImage::DrawImage()
: src_rect_(SkIRect::MakeXYWH(0, 0, 0, 0)),
filter_quality_(kNone_SkFilterQuality),
scale_(SkSize::Make(1.f, 1.f)),
matrix_is_decomposable_(true) {}
DrawImage::DrawImage(PaintImage image,
const SkIRect& src_rect,
SkFilterQuality filter_quality,
const SkMatrix& matrix,
base::Optional<size_t> frame_index,
const base::Optional<gfx::ColorSpace>& color_space)
: paint_image_(std::move(image)),
src_rect_(src_rect),
filter_quality_(filter_quality),
frame_index_(frame_index),
target_color_space_(color_space) {
matrix_is_decomposable_ = ExtractScale(matrix, &scale_);
}
DrawImage::DrawImage(const DrawImage& other,
float scale_adjustment,
size_t frame_index,
const gfx::ColorSpace& color_space)
: paint_image_(other.paint_image_),
src_rect_(other.src_rect_),
filter_quality_(other.filter_quality_),
scale_(SkSize::Make(other.scale_.width() * scale_adjustment,
other.scale_.height() * scale_adjustment)),
matrix_is_decomposable_(other.matrix_is_decomposable_),
frame_index_(frame_index),
target_color_space_(color_space) {}
DrawImage::DrawImage(const DrawImage& other) = default;
DrawImage::DrawImage(DrawImage&& other) = default;
DrawImage::~DrawImage() = default;
DrawImage& DrawImage::operator=(DrawImage&& other) = default;
DrawImage& DrawImage::operator=(const DrawImage& other) = default;
bool DrawImage::operator==(const DrawImage& other) const {
return paint_image_ == other.paint_image_ && src_rect_ == other.src_rect_ &&
filter_quality_ == other.filter_quality_ && scale_ == other.scale_ &&
matrix_is_decomposable_ == other.matrix_is_decomposable_ &&
target_color_space_ == other.target_color_space_;
}
} // namespace cc
| 1,082 |
635 | <reponame>Qautry/AAChartCore<filename>app/src/main/java/com/example/anan/AAChartCore/AAChartCoreLib/AAOptionsModel/AAOptions.java
package com.example.anan.AAChartCore.AAChartCoreLib.AAOptionsModel;
public class AAOptions {
public AAChart chart;
public AATitle title;
public AASubtitle subtitle;
public AAXAxis xAxis;
public AAYAxis yAxis;
public AAXAxis[] xAxisArray;
public AAYAxis[] yAxisArray;
public AATooltip tooltip;
public AAPlotOptions plotOptions;
public Object[] series;
public AALegend legend;
public AAPane pane;
public Object[] colors;
public AACredits credits;
public AALang defaultOptions;
public Boolean touchEventEnabled;
public AAOptions chart(AAChart prop) {
chart = prop;
return this;
}
public AAOptions title(AATitle prop) {
title = prop;
return this;
}
public AAOptions subtitle(AASubtitle prop) {
subtitle = prop;
return this;
}
public AAOptions xAxis(AAXAxis prop) {
xAxis = prop;
return this;
}
public AAOptions yAxis(AAYAxis prop) {
yAxis = prop;
return this;
}
public AAOptions xAxisArray(AAXAxis[] prop) {
xAxisArray = prop;
return this;
}
public AAOptions yAxisArray(AAYAxis[] prop) {
yAxisArray = prop;
return this;
}
public AAOptions tooltip(AATooltip prop) {
tooltip = prop;
return this;
}
public AAOptions plotOptions(AAPlotOptions prop) {
plotOptions = prop;
return this;
}
public AAOptions series(Object[] prop) {
series = prop;
return this;
}
public AAOptions legend(AALegend prop) {
legend = prop;
return this;
}
public AAOptions pane(AAPane prop) {
pane = prop;
return this;
}
public AAOptions colors(Object[] prop) {
colors = prop;
return this;
}
public AAOptions credits(AACredits prop) {
credits = prop;
return this;
}
public AAOptions defaultOptions(AALang prop) {
defaultOptions = prop;
return this;
}
public AAOptions touchEventEnabled(Boolean prop) {
touchEventEnabled = prop;
return this;
}
public AAOptions() {
AACredits aaCredits = new AACredits();
aaCredits.enabled = false;
this.credits = aaCredits;
}
}
| 1,042 |
952 | <gh_stars>100-1000
{
"version": "1.23",
"description": "File archiver for manipulation with '.tar.*' files.",
"homepage": "http://www.mingw.org/wiki/msys",
"license": "GPL-2.0-only",
"depends": "gzip",
"url": [
"https://downloads.sourceforge.net/project/mingw/MSYS/Base/tar/tar-1.23-1/tar-1.23-1-msys-1.0.13-bin.tar.lzma",
"https://downloads.sourceforge.net/project/mingw/MSYS/Base/msys-core/msys-1.0.18-1/msysCORE-1.0.18-1-msys-1.0.18-bin.tar.lzma",
"https://downloads.sourceforge.net/project/mingw/MSYS/Base/libiconv/libiconv-1.14-1/libiconv-1.14-1-msys-1.0.17-dll-2.tar.lzma",
"https://downloads.sourceforge.net/project/mingw/MSYS/Base/gettext/gettext-0.18.1.1-1/libintl-0.18.1.1-1-msys-1.0.17-dll-8.tar.lzma",
"https://downloads.sourceforge.net/project/mingw/MSYS/Base/regex/regex-1.20090805-2/libregex-1.20090805-2-msys-1.0.13-dll-1.tar.lzma"
],
"hash": [
"sha1:1791b71ad8573612049a8a4821d93e870fb2ae38",
"sha1:36d52ca7066eb6ad0da68c6f31214416f4c9dcec",
"sha1:056d16bfb7a91c3e3b1acf8adb20edea6fceecdd",
"sha1:4000b935a5bc30b4c757fde69d27716fa3c2c269",
"sha1:d95faa144cf06625b3932a8e84ed1a6ab6bbe644"
],
"bin": "bin\\tar.exe"
}
| 712 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/EDCollection.h>
__attribute__((visibility("hidden")))
@interface EDMergedCellCollection : EDCollection {
}
- (unsigned)addObject:(id)object; // 0xf5631
- (void)insertObject:(id)object atIndex:(unsigned)index; // 0x25c011
- (id)referenceContainingRow:(int)row column:(int)column; // 0xf8c35
@end
| 153 |
1,030 | <filename>client/manifest_util.cc
// Copyright (c) 2012-2013 NetEase Youdao Inc. and other heX contributors. All
// rights reserved. Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
#include "manifest_util.h"
#include "default_values.h"
#include "util.h"
#include "hex_shared_win.h"
#include <algorithm>
#include <string>
namespace hexclient {
#define MANIFEST_MEMBER(key) key##_(GET_DEFAULT_VALUE(##key##))
#define MANIFEST_ROOT_RETRIEVE(key, type) \
key##_ = root_.get(#key, ##key##_).as##type##()
#define MANIFEST_FORM_RETRIEVE(key, type) \
form_##key##_ = form.get(#key, form_##key##_).as##type##()
#define MANIFEST_BROWSER_RETRIEVE(key, type) \
browser_##key##_ = browser.get(#key, browser_##key##_).as##type##()
#define MANIFEST_CORRECT_VALUE(key, value, condition) if (condition) { \
##key##_ = value;\
}
#define MANIFEST_PARSE() Json::Reader reader; \
Json::Features::strictMode(); \
if (!reader.parse(json_content_, root_)) { \
error_messages_ = reader.getFormattedErrorMessages(); \
return false; \
}
ManifestUtil::ManifestUtil()
: error_messages_(""),
MANIFEST_MEMBER(first_page),
MANIFEST_MEMBER(application_title),
MANIFEST_MEMBER(version),
MANIFEST_MEMBER(locale),
MANIFEST_MEMBER(multiple_process),
MANIFEST_MEMBER(user_agent),
MANIFEST_MEMBER(launch_node_in_all_pages),
MANIFEST_MEMBER(launch_node_in_background),
MANIFEST_MEMBER(load_node_manually),
MANIFEST_MEMBER(disable_async_node_apis),
MANIFEST_MEMBER(cache_path),
MANIFEST_MEMBER(remote_debugging_port),
MANIFEST_MEMBER(disable_debug_log),
MANIFEST_MEMBER(quit_after_main_window_closed),
MANIFEST_MEMBER(npapi_plugin_directory),
MANIFEST_MEMBER(disable_ime_composition),
MANIFEST_MEMBER(form_style),
MANIFEST_MEMBER(form_plain),
MANIFEST_MEMBER(form_system_buttons),
MANIFEST_MEMBER(form_transmission_color),
MANIFEST_MEMBER(form_transparent_browser),
MANIFEST_MEMBER(form_fixed),
MANIFEST_MEMBER(form_disable_form_apis),
MANIFEST_MEMBER(form_opacity),
MANIFEST_MEMBER(form_hook_system_command),
MANIFEST_MEMBER(form_launch_state),
MANIFEST_MEMBER(form_launch_width),
MANIFEST_MEMBER(form_launch_height),
MANIFEST_MEMBER(form_launch_x),
MANIFEST_MEMBER(form_launch_y),
MANIFEST_MEMBER(form_min_width),
MANIFEST_MEMBER(form_min_height),
MANIFEST_MEMBER(form_max_width),
MANIFEST_MEMBER(form_max_height),
MANIFEST_MEMBER(form_border_width),
MANIFEST_MEMBER(browser_no_proxy_server),
MANIFEST_MEMBER(browser_winhttp_proxy_resolver),
MANIFEST_MEMBER(browser_disable_gpu),
MANIFEST_MEMBER(browser_web_security_disabled),
MANIFEST_MEMBER(browser_disable_3d_apis),
MANIFEST_MEMBER(browser_disable_databases),
MANIFEST_MEMBER(browser_disable_experimental_webgl),
MANIFEST_MEMBER(browser_disable_file_system),
MANIFEST_MEMBER(browser_disable_geolocation),
MANIFEST_MEMBER(browser_disable_gpu_process_prelaunch),
MANIFEST_MEMBER(browser_disable_java),
MANIFEST_MEMBER(browser_disable_javascript),
MANIFEST_MEMBER(browser_disable_javascript_i18n_api),
MANIFEST_MEMBER(browser_disable_local_storage),
MANIFEST_MEMBER(browser_disable_logging),
MANIFEST_MEMBER(browser_disable_plugins),
MANIFEST_MEMBER(browser_disable_renderer_accessibility),
MANIFEST_MEMBER(browser_disable_session_storage),
MANIFEST_MEMBER(browser_disable_speech_input),
MANIFEST_MEMBER(browser_disable_web_sockets),
MANIFEST_MEMBER(browser_in_process_gpu),
MANIFEST_MEMBER(browser_in_process_plugins),
MANIFEST_MEMBER(browser_file_access_from_file_urls_allowed),
MANIFEST_MEMBER(browser_universal_access_from_file_urls_allowed) {
file_name_ = hexclient::GetFullPathInExecutionDirectory("manifest.json",
true);
}
ManifestUtil::~ManifestUtil() {
}
bool ManifestUtil::Parse() {
MANIFEST_PARSE();
MANIFEST_ROOT_RETRIEVE(first_page, String);
MANIFEST_ROOT_RETRIEVE(application_title, String);
MANIFEST_ROOT_RETRIEVE(version, String);
MANIFEST_ROOT_RETRIEVE(locale, String);
MANIFEST_ROOT_RETRIEVE(multiple_process, Bool);
MANIFEST_ROOT_RETRIEVE(user_agent, String);
MANIFEST_ROOT_RETRIEVE(launch_node_in_all_pages, Bool);
MANIFEST_ROOT_RETRIEVE(launch_node_in_background, Bool);
MANIFEST_ROOT_RETRIEVE(load_node_manually, Bool);
MANIFEST_ROOT_RETRIEVE(disable_async_node_apis, Bool);
MANIFEST_ROOT_RETRIEVE(cache_path, String);
MANIFEST_ROOT_RETRIEVE(remote_debugging_port, Int);
MANIFEST_ROOT_RETRIEVE(disable_debug_log, Bool);
MANIFEST_ROOT_RETRIEVE(quit_after_main_window_closed, Bool);
MANIFEST_ROOT_RETRIEVE(npapi_plugin_directory, String);
MANIFEST_ROOT_RETRIEVE(disable_ime_composition, Bool);
Json::Value form = root_["form"];
std::string form_style_str = form.get("style", "standard").asString();
std::transform(form_style_str.begin(),
form_style_str.end(),
form_style_str.begin(),
tolower);
if (form_style_str == "standard") {
form_style_ = STANDARD;
} else if (form_style_str == "captionless") {
form_style_ = CAPTIONLESS;
} else if (form_style_str == "desktop_widget") {
form_style_ = DESKTOP_WIDGET;
}
MANIFEST_FORM_RETRIEVE(plain, Bool);
MANIFEST_FORM_RETRIEVE(system_buttons, Bool);
Json::Value transmission_color_value = form.get("transmission_color", "none");
std::string transmission_color_string = transmission_color_value.asString();
int transmission_color_integer = hex::NONE;
std::transform(transmission_color_string.begin(),
transmission_color_string.end(),
transmission_color_string.begin(),
tolower);
if (transmission_color_string != "none") {
if (transmission_color_string == "full") {
transmission_color_integer = hex::FULL;
} else if ((transmission_color_string.size() != 4 &&
transmission_color_string.size() != 7) ||
(transmission_color_string.at(0) != '#')) {
transmission_color_string = "none";
} else {
transmission_color_string = transmission_color_string.substr(1);
if (transmission_color_string.size() == 3) {
std::string tmp = transmission_color_string;
transmission_color_string.insert(0, tmp, 0, 1);
transmission_color_string.insert(2, tmp, 1, 1);
transmission_color_string.insert(4, tmp, 2, 1);
}
char* stop_string;
transmission_color_integer =
strtol(transmission_color_string.c_str(), &stop_string, 16);
if (strcmp(stop_string, "")) {
transmission_color_string = "none";
}
}
if (transmission_color_string == "none") {
transmission_color_integer = -1;
}
form_transmission_color_ = transmission_color_integer;
}
MANIFEST_CORRECT_VALUE(form_transmission_color, NONE,
form_style_ == STANDARD);
MANIFEST_FORM_RETRIEVE(transparent_browser, Bool);
form_adjusted_transparent_browser_ = form_transparent_browser_;
MANIFEST_CORRECT_VALUE(form_adjusted_transparent_browser, false,
form_transmission_color_ != NONE || !IsAeroGlassEnabled());
/*MANIFEST_CORRECT_VALUE(form_transparent_browser, false,
form_transmission_color_ != NONE || !IsAeroGlassEnabled());*/
MANIFEST_FORM_RETRIEVE(fixed, Bool);
/*MANIFEST_CORRECT_VALUE(form_plain, true,
form_style_ == DESKTOP_WIDGET || form_transmission_color_ != NONE);*/
MANIFEST_CORRECT_VALUE(form_plain, false, form_style_ == STANDARD);
MANIFEST_CORRECT_VALUE(form_fixed, form_plain_,
form_style_ != STANDARD && form_transparent_browser_ &&
(form_transmission_color_ == NONE && IsAeroGlassEnabled()));
MANIFEST_CORRECT_VALUE(form_opacity, NONE, form_transmission_color_ != NONE);
MANIFEST_CORRECT_VALUE(form_system_buttons, false,
!form_transparent_browser_ ||
(form_transmission_color_ != NONE || !IsAeroGlassEnabled()));
/*MANIFEST_CORRECT_VALUE(form_borderless, true, form_embed_into_desktop_);
MANIFEST_CORRECT_VALUE(form_transparent_browser, false,
!IsAeroGlassEnabled());
MANIFEST_CORRECT_VALUE(form_no_system_animation, false,
!IsAeroGlassEnabled());
MANIFEST_CORRECT_VALUE(form_no_system_shadow, true,
form_embed_into_desktop_ ||
form_transmission_color_ != -1 ||
form_fully_transmission_);
MANIFEST_CORRECT_VALUE(form_no_system_animation, true,
form_embed_into_desktop_);
MANIFEST_CORRECT_VALUE(form_hide_in_taskbar, true, form_embed_into_desktop_);
MANIFEST_CORRECT_VALUE(form_no_system_animation, false, !form_borderless_);
MANIFEST_CORRECT_VALUE(form_transparent_browser, false,
form_transmission_color_ != -1 || form_embed_into_desktop_);
MANIFEST_CORRECT_VALUE(form_transmission_color, NONE,
form_embed_into_desktop_);
MANIFEST_CORRECT_VALUE(form_no_system_shadow, false, !form_borderless_);*/
MANIFEST_FORM_RETRIEVE(disable_form_apis, Bool);
Json::Value opacityValue = form.get("opacity", "none");
if (opacityValue.isInt()) {
int o = opacityValue.asInt();
if (o >= 0 && o <= 255) {
form_opacity_ = o;
//form_no_system_animation_ = false;
} else {
form_opacity_ = NONE;
}
} else {
form_opacity_ = NONE;
}
//MANIFEST_CORRECT_VALUE(form_opacity, NONE, form_style_ == DESKTOP_WIDGET);
//MANIFEST_CORRECT_VALUE(form_no_system_animation, false, form_opacity_ != NONE);
MANIFEST_FORM_RETRIEVE(hook_system_command, Bool);
//MANIFEST_FORM_RETRIEVE(hide_in_taskbar, Bool);
//MANIFEST_CORRECT_VALUE(form_hide_in_taskbar, false, !form_borderless_);
std::string launchStateStr = form.get("launch_state", "normal").asString();
std::transform(launchStateStr.begin(),
launchStateStr.end(),
launchStateStr.begin(),
tolower);
if (launchStateStr == "maximized") {
form_launch_state_ = MAXIMIZED;
} else if (launchStateStr == "minimized") {
form_launch_state_ = MINIMIZED;
} else if (launchStateStr == "fullscreen") {
form_launch_state_ = FULLSCREEN;
} else if (launchStateStr == "normal") {
form_launch_state_ = NORMAL;
} else if (launchStateStr == "hidden") {
form_launch_state_ = HIDDEN;
} else {
form_launch_state_ = hex::NORMAL;
}
std::string launchWidthStr =
form.get("launch_width", "system_default").asString();
std::transform(launchWidthStr.begin(),
launchWidthStr.end(),
launchWidthStr.begin(),
tolower);
if (launchWidthStr == "system_default") {
form_launch_width_ = SYSTEMDEFAULT;
} else {
MANIFEST_FORM_RETRIEVE(launch_width, Int);
}
std::string launchHeightStr =
form.get("launch_height", "system_default").asString();
std::transform(launchHeightStr.begin(),
launchHeightStr.end(),
launchHeightStr.begin(),
tolower);
if (launchHeightStr == "system_default") {
form_launch_height_ = SYSTEMDEFAULT;
} else {
MANIFEST_FORM_RETRIEVE(launch_height, Int);
}
std::string form_launch_x =
form.get("launch_x", form_launch_x_).asString();
std::transform(form_launch_x.begin(),
form_launch_x.end(),
form_launch_x.begin(),
tolower);
if (form_launch_x == "system_default") {
form_launch_x_ = SYSTEMDEFAULT;
} else if (form_launch_x == "parent_centered") {
form_launch_x_ = PARENTCENTERED;
} else if (form_launch_x == "screen_centered") {
form_launch_x_ = SCREENCENTERED;
} else if (form.get("launch_left", form_launch_x_).isInt()) {
MANIFEST_FORM_RETRIEVE(launch_x, Int);
}
std::string form_launch_y =
form.get("launch_y", form_launch_y_).asString();
std::transform(form_launch_y.begin(),
form_launch_y.end(),
form_launch_y.begin(),
tolower);
if (form_launch_y == "system_default") {
form_launch_y_ = SYSTEMDEFAULT;
} else if (form_launch_y == "parent_centered") {
form_launch_y_ = PARENTCENTERED;
} else if (form_launch_y == "screen_centered") {
form_launch_y_ = SCREENCENTERED;
} else if (form.get("launch_top", form_launch_y_).isInt()) {
MANIFEST_FORM_RETRIEVE(launch_y, Int);
}
MANIFEST_FORM_RETRIEVE(min_width, Int);
MANIFEST_FORM_RETRIEVE(min_height, Int);
MANIFEST_FORM_RETRIEVE(max_width, Int);
MANIFEST_FORM_RETRIEVE(max_height, Int);
MANIFEST_FORM_RETRIEVE(border_width, Int);
MANIFEST_CORRECT_VALUE(form_border_width, 0, form_border_width_ < 0);
Json::Value browser = root_["browser"];
MANIFEST_BROWSER_RETRIEVE(no_proxy_server, Bool);
MANIFEST_BROWSER_RETRIEVE(winhttp_proxy_resolver, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_gpu, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_3d_apis, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_databases, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_experimental_webgl, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_file_system, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_geolocation, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_gpu_process_prelaunch, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_java, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_javascript, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_javascript_i18n_api, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_local_storage, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_logging, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_plugins, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_renderer_accessibility, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_session_storage, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_speech_input, Bool);
MANIFEST_BROWSER_RETRIEVE(disable_web_sockets, Bool);
MANIFEST_BROWSER_RETRIEVE(in_process_gpu, Bool);
MANIFEST_BROWSER_RETRIEVE(in_process_plugins, Bool);
MANIFEST_BROWSER_RETRIEVE(web_security_disabled, Bool);
MANIFEST_BROWSER_RETRIEVE(file_access_from_file_urls_allowed, Bool);
MANIFEST_BROWSER_RETRIEVE(universal_access_from_file_urls_allowed, Bool);
return true;
}
bool ManifestUtil::UpdateWithJson(std::string json_content) {
json_content_ = json_content;
MANIFEST_PARSE();
return true;
}
} // namespace hexclient
| 6,299 |
657 | <reponame>danielgrieve/Elixir-Slack<gh_stars>100-1000
{
"desc": "Renames a channel.",
"args": {
"channel": {
"type" : "channel",
"required" : true,
"desc" : "Channel to rename"
},
"name": {
"required" : true,
"desc" : "New name for channel."
}
},
"errors": {
"channel_not_found" : "Value passed for `channel` was invalid.",
"not_in_channel" : "Caller is not a member of the channel.",
"not_authorized" : "Caller cannot rename this channel",
"invalid_name" : "New name is invalid",
"name_taken" : "New channel name is taken"
}
}
| 245 |
1,040 | <filename>ui/GoForFlight/MultiStatusHandler.h
#ifndef MULTI_STATUS_HANDLER_HPP
#define MULTI_STATUS_HANDLER_HPP
#include <wx/settings.h>
#include <string.h>
#include <vector>
#include <iostream>
#include "StatusHandler.h"
#define NUM_TYPES 3
enum ComputerType { LOCAL = 0, GPS = 1, CAM = 2 };
class MultiStatusHandler : public StatusHandler {
public:
MultiStatusHandler(std::string prepend_str = "") : StatusHandler(prepend_str) {
lbl_labels_.resize(NUM_TYPES);
for (int i = 0; i < NUM_TYPES; i++) {
lbl_labels_[i] = NULL;
}
lbl_values_.resize(NUM_TYPES);
for (int i = 0; i < NUM_TYPES; i++) {
lbl_values_[i] = NULL;
}
status_array_.resize(NUM_TYPES);
for (int i = 0; i < NUM_TYPES; i++) {
status_array_[i] = false;
}
last_utime_.resize(NUM_TYPES);
for (int i = 0; i < NUM_TYPES; i++) {
last_utime_[i] = -1;
}
timeout_array_.resize(NUM_TYPES);
for (int i = 0; i < NUM_TYPES; i++) {
timeout_array_[i] = false;
}
label_text_.resize(NUM_TYPES);
for (int i = 0; i < NUM_TYPES; i++) {
label_text_[i] = "";
}
}
~MultiStatusHandler() {}
void AddLabel(ComputerType type, wxStaticText *label, wxStaticText *value) {
lbl_labels_[type] = label;
lbl_values_[type] = value;
}
void SetStatus(ComputerType type, bool value, long utime) {
status_array_[type] = value;
if (lbl_labels_[type] != NULL) {
lbl_labels_[type]->SetForegroundColour(GetColour(value));
}
if (lbl_values_[type] != NULL) {
lbl_values_[type]->SetForegroundColour(GetColour(value));
}
last_utime_[type] = utime;
}
bool GetStatus(ComputerType type) {
return status_array_[type];
}
void SetText(ComputerType type, std::string text) {
label_text_[type] = text;
if (lbl_values_[type] != NULL) {
lbl_values_[type]->SetLabel(text);
}
}
void SetTimeout(ComputerType type, bool timeout) {
timeout_array_[type] = timeout;
if (GetStatus(type) == true && timeout_array_[type]) {
std::string text = label_text_[type] + " (timeout)";
SetStatus(type, false, last_utime_[type]);
if (lbl_values_[type] != NULL) {
lbl_values_[type]->SetLabel(text);
}
}
}
std::string GetText(ComputerType type) {
std::string str = "";
if (lbl_values_[type] != NULL) {
str = std::string(lbl_values_[type]->GetLabel());
}
return str;
}
bool GetStatus() {
for (auto status : status_array_) {
if (status == false) {
return false;
}
}
return true;
}
void Update() {
CheckTime();
StatusHandler::SetText(GetStatusString(GetStatus()));
SetColour(GetColour(GetStatus()));
for (int i = 0; i < NUM_TYPES; i++) {
if (lbl_labels_[i] != NULL) {
lbl_labels_[i]->SetForegroundColour(GetColour(status_array_[i]));
}
if (lbl_values_[i] != NULL) {
lbl_values_[i]->SetForegroundColour(GetColour(status_array_[i]));
}
}
}
void CheckTime() {
StatusHandler::CheckTime();
for (int i = 0; i < NUM_TYPES; i++) {
if (abs(last_utime_[i] - StatusHandler::GetTimestampNow()) > timeout_threshold_) {
SetTimeout(ComputerType(i), true);
} else {
SetTimeout(ComputerType(i), false);
}
}
}
protected:
ComputerType GetIndexFromChannelName(std::string channel_name) {
if (channel_name.find("gps") != std::string::npos) {
return GPS;
} else if (channel_name.find("cam") != std::string::npos) {
return CAM;
} else {
return LOCAL;
}
}
private:
std::vector<wxStaticText*> lbl_labels_;
std::vector<wxStaticText*> lbl_values_;
std::vector<bool> status_array_;
std::vector<long> last_utime_;
std::vector<bool> timeout_array_;
std::vector<std::string> label_text_;
};
#endif // LOG_SIZE_HANDLER_HPP
| 2,651 |
931 | <reponame>jahnvisrivastava100/CompetitiveProgrammingQuestionBank
/*
Given a Binary Tree with all unique values and two nodes value n1 and n2. The task is to find the lowest common ancestor
of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them is present.
*/
#include <bits/stdc++.h>
using namespace std;
// Tree Node
struct Node
{
int data;
Node *left;
Node *right;
};
Node *lca(Node *root, int n1, int n2);
Node *newNode(int val)
{
Node *temp = new Node;
temp->data = val;
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node *buildTree(string str)
{
if (str.length() == 0 || str[0] == 'N')
return NULL;
vector<string> ip;
istringstream iss(str);
for (string str; iss >> str;)
ip.push_back(str);
Node *root = newNode(stoi(ip[0]));
queue<Node *> queue;
queue.push(root);
int i = 1;
while (!queue.empty() && i < ip.size())
{
Node *currNode = queue.front();
queue.pop();
string currVal = ip[i];
if (currVal != "N")
{
currNode->left = newNode(stoi(currVal));
queue.push(currNode->left);
}
i++;
if (i >= ip.size())
break;
currVal = ip[i];
if (currVal != "N")
{
currNode->right = newNode(stoi(currVal));
queue.push(currNode->right);
}
i++;
}
return root;
}
void printInorder(Node *root)
{
if (!root)
return;
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int a, b;
scanf("%d %d ", &a, &b);
string s;
getline(cin, s);
Node *root = buildTree(s);
cout << lca(root, a, b)->data << endl;
}
return 0;
}
Node *lca(Node *root, int n1, int n2)
{
//Your code here
Node *lnode, *rnode;
if (!root)
return NULL;
if (root->data == n1 || root->data == n2)
{
return root;
}
lnode = lca(root->left, n1, n2);
rnode = lca(root->right, n1, n2);
if (lnode && rnode)
{
return root;
}
return (lnode != NULL) ? lnode : rnode;
}
| 1,102 |
348 | <filename>docs/data/leg-t2/067/06705438.json<gh_stars>100-1000
{"nom":"Schaeffersheim","circ":"5ème circonscription","dpt":"Bas-Rhin","inscrits":674,"abs":394,"votants":280,"blancs":11,"nuls":3,"exp":266,"res":[{"nuance":"LR","nom":"<NAME>","voix":167},{"nuance":"REG","nom":"<NAME>","voix":99}]} | 122 |
372 | <filename>graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/autoconfigure/editor/graphiql/GraphiQLAutoConfiguration.java
package graphql.kickstart.autoconfigure.editor.graphiql;
import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.REACTIVE;
import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;;
/**
* @author <NAME>
* @author <NAME>
*/
@Configuration
@ConditionalOnProperty(value = "graphql.graphiql.enabled", havingValue = "true")
@EnableConfigurationProperties(GraphiQLProperties.class)
public class GraphiQLAutoConfiguration {
@Bean(name = "graphiQLController")
@ConditionalOnWebApplication(type = SERVLET)
ServletGraphiQLController servletGraphiQLController(GraphiQLProperties properties) {
return new ServletGraphiQLController(properties);
}
@Bean(name = "graphiQLController")
@ConditionalOnMissingBean(ServletGraphiQLController.class)
@ConditionalOnWebApplication(type = REACTIVE)
ReactiveGraphiQLController reactiveGraphiQLController(GraphiQLProperties properties) {
return new ReactiveGraphiQLController(properties);
}
@Bean
@ConditionalOnWebApplication(type = REACTIVE)
@ConditionalOnExpression("'${graphql.graphiql.cdn.enabled:false}' == 'false'")
public RouterFunction<ServerResponse> graphiqlStaticFilesRouter() {
return RouterFunctions.resources(
"/vendor/graphiql/**", new ClassPathResource("static/vendor/graphiql/"));
}
@Configuration
@EnableWebMvc
@ConditionalOnWebApplication(type = SERVLET)
@ConditionalOnExpression("'${graphql.graphiql.cdn.enabled:false}' == 'false'")
public static class GraphiQLWebMvcResourceConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/vendor/graphiql/**")
.addResourceLocations(new ClassPathResource("static/vendor/graphiql/"));
}
}
}
| 898 |
1,011 | #ifndef __TweakBarParameters_h__
#define __TweakBarParameters_h__
#include "SPlisHSPlasH/Common.h"
#include "extern/AntTweakBar/include/AntTweakBar.h"
#include <vector>
#include "ParameterObject.h"
#ifdef USE_DOUBLE
#define TW_TYPE_REAL TW_TYPE_DOUBLE
#define TW_TYPE_DIR3R TW_TYPE_DIR3D
#else
#define TW_TYPE_REAL TW_TYPE_FLOAT
#define TW_TYPE_DIR3R TW_TYPE_DIR3F
#endif
namespace SPH
{
class TweakBarParameters
{
public:
typedef std::pair<GenParam::ParameterObject*, unsigned int> ParameterIndex;
static void createParameterGUI(TwBar *tweakBar);
static void createParameterObjectGUI(TwBar *tweakBar, GenParam::ParameterObject *paramObj);
static void TW_CALL setParameterValue(const void *value, void *clientData);
static void TW_CALL getParameterValue(void *value, void *clientData);
static void TW_CALL setTimeStepSizeCB(const void *value, void *clientData);
static void TW_CALL getTimeStepSizeCB(void *value, void *clientData);
static void cleanup();
protected:
static std::vector<std::unique_ptr<ParameterIndex>> m_params;
static std::vector<std::string> m_objectNames;
};
}
#endif | 399 |
367 | /*
* Copyright (C) 2017 skydoves
*
* 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.skydoves.processor;
import static javax.lang.model.element.Modifier.PUBLIC;
import androidx.annotation.Nullable;
import com.skydoves.preferenceroom.PreferenceChangedListener;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;
import java.util.List;
import javax.lang.model.element.Modifier;
@SuppressWarnings("WeakerAccess")
public class PreferenceChangeListenerGenerator {
private final PreferenceKeyField keyField;
public static final String CHANGED_LISTENER_POSTFIX = "OnChangedListener";
public static final String CHANGED_ABSTRACT_METHOD = "onChanged";
public PreferenceChangeListenerGenerator(PreferenceKeyField keyField) {
this.keyField = keyField;
}
public TypeSpec generateInterface() {
TypeSpec.Builder builder =
TypeSpec.interfaceBuilder(getClazzName())
.addModifiers(PUBLIC)
.addSuperinterface(PreferenceChangedListener.class)
.addMethod(getOnChangedSpec());
return builder.build();
}
public FieldSpec generateField(String className) {
return FieldSpec.builder(
ParameterizedTypeName.get(ClassName.get(List.class), getInterfaceType(className)),
getFieldName(),
Modifier.PRIVATE)
.addAnnotation(Nullable.class)
.initializer("new ArrayList()")
.build();
}
private MethodSpec getOnChangedSpec() {
return MethodSpec.methodBuilder("onChanged")
.addParameter(
ParameterSpec.builder(keyField.typeName, keyField.keyName.toLowerCase()).build())
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.build();
}
public String getClazzName() {
return StringUtils.toUpperCamel(keyField.keyName) + CHANGED_LISTENER_POSTFIX;
}
private String getFieldName() {
return keyField.keyName + CHANGED_LISTENER_POSTFIX;
}
public ClassName getInterfaceType(String className) {
return ClassName.get(keyField.packageName + "." + className, getClazzName());
}
}
| 936 |
569 | // Author: <NAME> <<EMAIL>>
#ifndef wyhash_version_alpha
#define wyhash_version_alpha
#include <stdint.h>
#include <string.h>
#if defined(_MSC_VER) && defined(_M_X64)
#include <intrin.h>
#pragma intrinsic(_umul128)
#endif
#if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__clang__)
#define _likely_(x) __builtin_expect(x, 1)
#define _unlikely_(x) __builtin_expect(x, 0)
#else
#define _likely_(x) (x)
#define _unlikely_(x) (x)
#endif
const uint64_t _wyp[2] = { 0xa0761d6478bd642full, 0xe7037ed1a0b428dbull};
static inline uint64_t _wyrotr(uint64_t v, unsigned k) { return (v >> k) | (v << (64 - k));}
static inline uint64_t _wymum(uint64_t A, uint64_t B) {
#ifdef UNOFFICIAL_WYHASH_32BIT
uint64_t hh = (A >> 32) * (B >> 32), hl = (A >> 32) * (unsigned)B, lh = (unsigned)A * (B >> 32), ll = (uint64_t)(unsigned)A * (unsigned)B;
return _wyrotr(hl, 32) ^ _wyrotr(lh, 32) ^ hh ^ ll;
#else
#ifdef __SIZEOF_INT128__
__uint128_t r = A; r *= B; return (r >> 64) ^ r;
#elif defined(_MSC_VER) && defined(_M_X64)
A = _umul128(A, B, &B); return A ^ B;
#else
uint64_t ha = A >> 32, hb = B >> 32, la = (uint32_t)A, lb = (uint32_t)B, hi, lo;
uint64_t rh = ha * hb, rm0 = ha * lb, rm1 = hb * la, rl = la * lb, t = rl + (rm0 << 32), c = t < rl;
lo = t + (rm1 << 32); c += lo < t; hi = rh + (rm0 >> 32) + (rm1 >> 32) + c;
return hi ^ lo;
#endif
#endif
}
static inline uint64_t _wymix(uint64_t A, uint64_t B) {
#ifdef UNOFFICIAL_WYHASH_CONDOM
return (A ^ B) ^ _wymum(A, B);
#else
return _wymum(A, B);
#endif
}
static inline uint64_t wyhash64(uint64_t A, uint64_t B) { return _wymum(_wymum(A ^ *_wyp, B ^ _wyp[1]), *_wyp);}
static inline uint64_t wyrand(uint64_t *seed) { *seed += *_wyp; return _wymum(*seed ^ _wyp[1], *seed);}
static inline double wy2u01(uint64_t r) { const double _wynorm = 1.0 / (1ull << 52); return (r >> 12) * _wynorm;}
static inline double wy2gau(uint64_t r) { const double _wynorm = 1.0 / (1ull << 20); return ((r & 0x1fffff) + ((r >> 21) & 0x1fffff) + ((r >> 42) & 0x1fffff)) * _wynorm - 3.0;}
#ifndef WYHASH_LITTLE_ENDIAN
#if defined(_WIN32) || defined(__LITTLE_ENDIAN__) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define WYHASH_LITTLE_ENDIAN 1
#elif defined(__BIG_ENDIAN__) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
#define WYHASH_LITTLE_ENDIAN 0
#endif
#endif
#if (WYHASH_LITTLE_ENDIAN)
static inline uint64_t _wyr8(const uint8_t *p) { uint64_t v; memcpy(&v, p, 8); return v;}
static inline uint64_t _wyr4(const uint8_t *p) { unsigned v; memcpy(&v, p, 4); return v;}
#else
#if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__clang__)
static inline uint64_t _wyr8(const uint8_t *p) { uint64_t v; memcpy(&v, p, 8); return __builtin_bswap64(v);}
static inline uint64_t _wyr4(const uint8_t *p) { unsigned v; memcpy(&v, p, 4); return __builtin_bswap32(v);}
#elif defined(_MSC_VER)
static inline uint64_t _wyr8(const uint8_t *p) { uint64_t v; memcpy(&v, p, 8); return _byteswap_uint64(v);}
static inline uint64_t _wyr4(const uint8_t *p) { unsigned v; memcpy(&v, p, 4); return _byteswap_ulong(v);}
#endif
#endif
static inline uint64_t _wyr3(const uint8_t *p, unsigned k) { return (((uint64_t)p[0]) << 16) | (((uint64_t)p[k >> 1]) << 8) | p[k - 1];}
static inline uint64_t FastestHash(const void *key, size_t len, uint64_t seed) {
const uint8_t *p = (const uint8_t *)key;
return _likely_(len >= 4) ? (_wyr4(p) + _wyr4(p + len - 4)) * (_wyr4(p + (len >> 1) - 2) ^ seed) : (_likely_(len) ? _wyr3(p, len) * (*_wyp ^ seed) : seed);
}
static inline uint64_t _wyhash(const void *key, uint64_t len, uint64_t seed, const uint64_t secret[2]) {
const uint8_t *p = (const uint8_t *)key; uint64_t i = len; seed ^= secret[1];
if (_likely_(i <= 64)) {
finalization:
if(_likely_(i<=8)) {
if(_likely_(i>=4)) return _wymix(_wyr4(p) ^ *secret, _wyr4(p + i - 4) ^ seed);
else if (_likely_(i)) return _wymix(_wyr3(p, i) ^ *secret, seed);
else return _wymum(*secret, seed);
}
else if(_likely_(i <= 16)) return _wymix(_wyr8(p) ^ *secret, _wyr8(p + i - 8) ^ seed);
else{ seed = _wymix(_wyr8(p) ^ *secret, _wyr8(p + 8) ^ seed); i -= 16; p += 16; goto finalization;}
}
uint64_t see1 = _wyrotr(seed,16), see2 = _wyrotr(seed,32), see3 = _wyrotr(seed,48);
for (; i > 64; i -= 64, p += 64) {
seed = _wymix(_wyr8(p) ^ *secret, _wyr8(p + 8) ^ seed);
see1 = _wymix(_wyr8(p + 16) ^ *secret, _wyr8(p + 24) ^ see1);
see2 = _wymix(_wyr8(p + 32) ^ *secret, _wyr8(p + 40) ^ see2);
see3 = _wymix(_wyr8(p + 48) ^ *secret, _wyr8(p + 56) ^ see3);
}
seed ^= see1 ^ see2 ^ see3;
goto finalization;
}
static inline uint64_t wyhash(const void *key, uint64_t len, uint64_t seed, const uint64_t secret[2]) { return _wymum(_wyhash(key, len, seed, secret) ^ len, *secret);}
static inline void make_secret(uint64_t seed, uint64_t secret[2]) {
uint8_t c[] = {15, 23, 27, 29, 30, 39, 43, 45, 46, 51, 53, 54, 57, 58, 60, 71, 75, 77, 78, 83, 85, 86, 89, 90, 92, 99, 101, 102, 105, 106, 108, 113, 114, 116, 120, 135, 139, 141, 142, 147, 149, 150, 153, 154, 156, 163, 165, 166, 169, 170, 172, 177, 178, 180, 184, 195, 197, 198, 201, 202, 204, 209, 210, 212, 216, 225, 226, 228, 232, 240 };
for (size_t i = 0; i < 2; i++) {
uint8_t ok;
do {
ok = 1; secret[i] = 0;
for (size_t j = 0; j < 64; j += 8) secret[i] |= ((uint64_t)c[wyrand(&seed) % sizeof(c)]) << j;
if (secret[i] % 2 == 0) { ok = 0; continue; }
for (size_t j = 0; j < i; j++)
#if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__clang__)
if (__builtin_popcountll(secret[i] ^ secret[j]) != 32) {
ok = 0;
break;
}
#elif defined(_MSC_VER)
if (_mm_popcnt_u64(secret[i] ^ secret[j]) != 32) {
ok = 0;
break;
}
#endif
if (!ok||secret[i]%2==0) continue;
for (uint64_t j = 3; j < 0x100000000ull; j += 2) if (secret[i] % j == 0) { ok = 0; break;}
} while (!ok);
}
}
/*
typedef struct wyhash_context {
uint64_t secret[6];
uint64_t seed, see1, see2, see3;
uint8_t buffer[64];
uint8_t left; // always in [0, 64]
int loop;
uint64_t total;
} wyhash_context_t;
static inline void wyhash_init(wyhash_context_t *const __restrict ctx,
const uint64_t seed, const uint64_t secret[5]) {
memcpy(ctx->secret, secret, sizeof(ctx->secret));
ctx->seed = seed ^ secret[4];
ctx->see1 = ctx->seed;
ctx->see2 = ctx->seed;
ctx->see3 = ctx->seed;
ctx->left = 0;
ctx->total = 0;
ctx->loop = 0;
}
static inline uint64_t _wyhash_loop(wyhash_context_t *const __restrict ctx,
const uint8_t *p, const uint64_t len) {
uint64_t i = len;
ctx->loop |= (i > 64);
for (; i > 64; i -= 64, p += 64) {
ctx->seed = _wymix(_wyr8(p) ^ ctx->secret[0], _wyr8(p + 8) ^ ctx->seed);
ctx->see1 = _wymix(_wyr8(p + 16) ^ ctx->secret[1], _wyr8(p + 24) ^ ctx->see1);
ctx->see2 = _wymix(_wyr8(p + 32) ^ ctx->secret[2], _wyr8(p + 40) ^ ctx->see2);
ctx->see3 = _wymix(_wyr8(p + 48) ^ ctx->secret[3], _wyr8(p + 56) ^ ctx->see3);
}
return len - i;
}
static inline void wyhash_update(wyhash_context_t *const __restrict ctx,
const void *const key, uint64_t len) {
ctx->total += len; // overflow for total length is ok
const uint8_t *p = (const uint8_t *)key;
uint8_t slots = 64 - ctx->left; // assert left <= 64
slots = len <= slots ? len : slots;
memcpy(ctx->buffer + ctx->left, p, slots);
p += slots;
len -= slots;
ctx->left += slots;
ctx->left -= _wyhash_loop(ctx, ctx->buffer, ctx->left + (len > 0));
const uint64_t consumed = _wyhash_loop(ctx, p, len);
p += consumed;
len -= consumed; // assert len <= 64
ctx->left = ctx->left > len ? ctx->left : (uint8_t)len;
memcpy(ctx->buffer, p, len);
}
static inline uint64_t wyhash_final(wyhash_context_t *const __restrict ctx) {
if (_likely_(ctx->loop)) ctx->seed ^= ctx->see1 ^ ctx->see2 ^ ctx->see3;
return _wymum(_wyhash(ctx->buffer, ctx->left, ctx->seed ^ ctx->secret[4],
ctx->secret) ^
ctx->total,
ctx->secret[4]);
}
*/
#endif
| 3,610 |
305 | //===-- Benchmark ---------------------------------------------------------===//
//
// 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 "LibcMemoryBenchmarkMain.h"
#include "JSON.h"
#include "LibcBenchmark.h"
#include "LibcMemoryBenchmark.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
namespace llvm {
namespace libc_benchmarks {
static cl::opt<std::string>
Configuration("conf", cl::desc("Specify configuration filename"),
cl::value_desc("filename"), cl::init(""));
static cl::opt<std::string> Output("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
extern std::unique_ptr<BenchmarkRunner>
getRunner(const StudyConfiguration &Conf);
void Main() {
#ifndef NDEBUG
static_assert(
false,
"For reproducibility benchmarks should not be compiled in DEBUG mode.");
#endif
checkRequirements();
ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
MemoryBuffer::getFileOrSTDIN(Configuration);
if (!MB)
report_fatal_error(
Twine("Could not open configuration file: ").concat(Configuration));
auto ErrorOrStudy = ParseJsonStudy((*MB)->getBuffer());
if (!ErrorOrStudy)
report_fatal_error(ErrorOrStudy.takeError());
const auto StudyPrototype = *ErrorOrStudy;
Study S;
S.Host = HostState::get();
S.Options = StudyPrototype.Options;
S.Configuration = StudyPrototype.Configuration;
const auto Runs = S.Configuration.Runs;
const auto &SR = S.Configuration.Size;
std::unique_ptr<BenchmarkRunner> Runner = getRunner(S.Configuration);
const size_t TotalSteps =
Runner->getFunctionNames().size() * Runs * ((SR.To - SR.From) / SR.Step);
size_t Steps = 0;
for (auto FunctionName : Runner->getFunctionNames()) {
FunctionMeasurements FM;
FM.Name = std::string(FunctionName);
for (size_t Run = 0; Run < Runs; ++Run) {
for (uint32_t Size = SR.From; Size <= SR.To; Size += SR.Step) {
const auto Result = Runner->benchmark(S.Options, FunctionName, Size);
Measurement Measurement;
Measurement.Runtime = Result.BestGuess;
Measurement.Size = Size;
FM.Measurements.push_back(Measurement);
outs() << format("%3d%% run: %2d / %2d size: %5d ",
(Steps * 100 / TotalSteps), Run, Runs, Size)
<< FunctionName
<< " \r";
++Steps;
}
}
S.Functions.push_back(std::move(FM));
}
std::error_code EC;
raw_fd_ostream FOS(Output, EC);
if (EC)
report_fatal_error(Twine("Could not open file: ")
.concat(EC.message())
.concat(", ")
.concat(Output));
json::OStream JOS(FOS);
SerializeToJson(S, JOS);
}
} // namespace libc_benchmarks
} // namespace llvm
int main(int argc, char **argv) {
llvm::cl::ParseCommandLineOptions(argc, argv);
llvm::libc_benchmarks::Main();
return EXIT_SUCCESS;
}
| 1,368 |
1,056 | <filename>enterprise/j2ee.ejbcore/src/org/netbeans/modules/j2ee/ejbcore/ui/logicalview/entries/CallEjbCodeGenerator.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
*
* 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.j2ee.ejbcore.ui.logicalview.entries;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.swing.text.JTextComponent;
import org.netbeans.api.java.source.CompilationController;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.api.java.source.TreeUtilities;
import org.netbeans.api.project.FileOwnerQuery;
import org.netbeans.api.project.Project;
import org.netbeans.modules.j2ee.api.ejbjar.EnterpriseReferenceContainer;
import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
import org.netbeans.modules.j2ee.deployment.devmodules.api.InstanceRemovedException;
import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eePlatform;
import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
import org.netbeans.modules.javaee.specs.support.api.EjbSupport;
import org.netbeans.spi.editor.codegen.CodeGenerator;
import org.openide.filesystems.FileObject;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.Lookup;
/**
* Provide action for calling another EJB
* @author <NAME>
* @author <NAME>
*/
public class CallEjbCodeGenerator implements CodeGenerator {
private FileObject srcFile;
private TypeElement beanClass;
public static class Factory implements CodeGenerator.Factory {
public List<? extends CodeGenerator> create(Lookup context) {
ArrayList<CodeGenerator> ret = new ArrayList<CodeGenerator>();
JTextComponent component = context.lookup(JTextComponent.class);
CompilationController controller = context.lookup(CompilationController.class);
TreePath path = context.lookup(TreePath.class);
path = path != null ? SendEmailCodeGenerator.getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, path) : null;
if (component == null || controller == null || path == null)
return ret;
try {
controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
Element elem = controller.getTrees().getElement(path);
if (elem != null) {
CallEjbCodeGenerator gen = createCallEjbAction(component, controller, elem);
if (gen != null)
ret.add(gen);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return ret;
}
}
static CallEjbCodeGenerator createCallEjbAction(JTextComponent component, CompilationController cc, Element el) throws IOException {
if (el.getKind() != ElementKind.CLASS)
return null;
TypeElement typeElement = (TypeElement)el;
if (!isEnable(cc.getFileObject(), typeElement)) {
return null;
}
return new CallEjbCodeGenerator(cc.getFileObject(), typeElement);
}
public CallEjbCodeGenerator(FileObject srcFile, TypeElement beanClass) {
this.srcFile = srcFile;
this.beanClass = beanClass;
}
public void invoke() {
try {
CallEjbDialog callEjbDialog = new CallEjbDialog();
callEjbDialog.open(srcFile, beanClass.getQualifiedName().toString(), NbBundle.getMessage(CallEjbCodeGenerator.class, "LBL_CallEjbActionTitle")); //NOI18N
} catch (IOException ioe) {
Exceptions.printStackTrace(ioe);
}
}
public String getDisplayName() {
return NbBundle.getMessage(CallEjbCodeGenerator.class, "LBL_CallEjbAction");
}
private static boolean isEnable(FileObject srcFile, TypeElement typeElement) {
Project project = FileOwnerQuery.getOwner(srcFile);
if (project == null) {
return false;
}
J2eeModuleProvider j2eeModuleProvider = project.getLookup ().lookup (J2eeModuleProvider.class);
if (j2eeModuleProvider != null) {
if (project.getLookup().lookup(EnterpriseReferenceContainer.class) == null) {
return false;
}
String serverInstanceId = j2eeModuleProvider.getServerInstanceID();
if (serverInstanceId == null) {
return true;
}
J2eePlatform platform = null;
try {
platform = Deployment.getDefault().getServerInstance(serverInstanceId).getJ2eePlatform();
} catch (InstanceRemovedException ex) {
Logger.getLogger(CallEjbCodeGenerator.class.getName()).log(Level.FINE, null, ex);
}
if (platform == null) {
return true;
}
if (!EjbSupport.getInstance(platform).isEjb31LiteSupported(platform)
&& !platform.getSupportedTypes().contains(J2eeModule.Type.EJB)) {
return false;
}
} else {
return false;
}
return ElementKind.INTERFACE != typeElement.getKind();
}
}
| 2,486 |
2,161 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.flink;
import org.apache.flink.table.types.logical.DayTimeIntervalType;
import org.apache.flink.table.types.logical.DistinctType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.LogicalTypeVisitor;
import org.apache.flink.table.types.logical.NullType;
import org.apache.flink.table.types.logical.RawType;
import org.apache.flink.table.types.logical.StructuredType;
import org.apache.flink.table.types.logical.SymbolType;
import org.apache.flink.table.types.logical.YearMonthIntervalType;
import org.apache.flink.table.types.logical.ZonedTimestampType;
public abstract class FlinkTypeVisitor<T> implements LogicalTypeVisitor<T> {
// ------------------------- Unsupported types ------------------------------
@Override
public T visit(ZonedTimestampType zonedTimestampType) {
throw new UnsupportedOperationException("Unsupported ZonedTimestampType.");
}
@Override
public T visit(YearMonthIntervalType yearMonthIntervalType) {
throw new UnsupportedOperationException("Unsupported YearMonthIntervalType.");
}
@Override
public T visit(DayTimeIntervalType dayTimeIntervalType) {
throw new UnsupportedOperationException("Unsupported DayTimeIntervalType.");
}
@Override
public T visit(DistinctType distinctType) {
throw new UnsupportedOperationException("Unsupported DistinctType.");
}
@Override
public T visit(StructuredType structuredType) {
throw new UnsupportedOperationException("Unsupported StructuredType.");
}
@Override
public T visit(NullType nullType) {
throw new UnsupportedOperationException("Unsupported NullType.");
}
@Override
public T visit(RawType<?> rawType) {
throw new UnsupportedOperationException("Unsupported RawType.");
}
@Override
public T visit(SymbolType<?> symbolType) {
throw new UnsupportedOperationException("Unsupported SymbolType.");
}
@Override
public T visit(LogicalType other) {
throw new UnsupportedOperationException("Unsupported type: " + other);
}
}
| 814 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-7589-4cgq-4p68",
"modified": "2022-05-13T01:49:40Z",
"published": "2022-05-13T01:49:40Z",
"aliases": [
"CVE-2018-12893"
],
"details": "An issue was discovered in Xen through 4.10.x. One of the fixes in XSA-260 added some safety checks to help prevent Xen livelocking with debug exceptions. Unfortunately, due to an oversight, at least one of these safety checks can be triggered by a guest. A malicious PV guest can crash Xen, leading to a Denial of Service. All Xen systems which have applied the XSA-260 fix are vulnerable. Only x86 systems are vulnerable. ARM systems are not vulnerable. Only x86 PV guests can exploit the vulnerability. x86 HVM and PVH guests cannot exploit the vulnerability. An attacker needs to be able to control hardware debugging facilities to exploit the vulnerability, but such permissions are typically available to unprivileged users.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:C/C:N/I:N/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2018-12893"
},
{
"type": "WEB",
"url": "https://bugzilla.redhat.com/show_bug.cgi?id=1590979"
},
{
"type": "WEB",
"url": "https://lists.debian.org/debian-lts-announce/2018/11/msg00013.html"
},
{
"type": "WEB",
"url": "https://security.gentoo.org/glsa/201810-06"
},
{
"type": "WEB",
"url": "https://support.citrix.com/article/CTX235748"
},
{
"type": "WEB",
"url": "https://www.debian.org/security/2018/dsa-4236"
},
{
"type": "WEB",
"url": "http://www.openwall.com/lists/oss-security/2018/06/27/11"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/104572"
},
{
"type": "WEB",
"url": "http://www.securitytracker.com/id/1041202"
},
{
"type": "WEB",
"url": "http://xenbits.xen.org/xsa/advisory-265.html"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 951 |
713 | package org.infinispan.marshaller.kryo;
import java.util.concurrent.atomic.AtomicInteger;
import org.infinispan.marshaller.test.User;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* @author <NAME>
* @since 9.0
*/
class UserSerializer extends Serializer<User> {
static final AtomicInteger writeCount = new AtomicInteger();
static final AtomicInteger readCount = new AtomicInteger();
public void write (Kryo kryo, Output output, User user) {
writeCount.incrementAndGet();
output.writeString(user.getName());
}
public User read (Kryo kryo, Input input, Class<User> type) {
readCount.incrementAndGet();
return new User(input.readString());
}
}
| 288 |
2,320 | <reponame>fengyixian3312/PowerJob
package tech.powerjob.common.response;
import lombok.Data;
import java.util.Date;
/**
* WorkflowNodeInfo 对外输出对象
* @author Echo009
* @since 2021/2/20
*/
@Data
public class WorkflowNodeInfoDTO {
private Long id;
private Long appId;
private Long workflowId;
/**
* 任务 ID
*/
private Long jobId;
/**
* 节点别名,默认为对应的任务名称
*/
private String nodeAlias;
/**
* 节点参数
*/
private String nodeParams;
/**
* 是否启用
*/
private Boolean enable;
/**
* 是否允许失败跳过
*/
private Boolean skipWhenFailed;
/**
* 创建时间
*/
private Date gmtCreate;
/**
* 更新时间
*/
private Date gmtModified;
}
| 413 |
450 | /*
* 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.
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include "cmockery.h"
#include "c.h"
#include "postgres.h"
#include "../define.c"
/* ==================== FreeStrFromDefGetString ==================== */
/*
* Tests that need_free flag correctly set in defGetString method.
*/
void
test__DefGetString_NeedFreeFlag(void **state)
{
bool need_free = false;
char *value = NULL;
/* case: T_String expected value: false */
need_free = true;
DefElem *e1 = makeDefElem("def_string", (Node *) makeString("none"));
value = defGetString(e1, &need_free);
assert_false(need_free);
/* case: T_Integer expected value: true */
need_free = false;
DefElem *e2 = makeDefElem("def_int", (Node *) makeInteger(0));
value = defGetString(e2, &need_free);
assert_true(need_free);
/* case: T_Float expected value: false */
need_free = true;
DefElem *e3 = makeDefElem("def_float", (Node *) makeFloat("3.14"));
value = defGetString(e3, &need_free);
assert_false(need_free);
/* case: T_TypeName expected value: true */
need_free = false;
TypeName *tName = makeNode(TypeName);
tName->names = list_make2(makeString("pg_catalog"), makeString("unknown"));
tName->typmod = -1;
tName->location = -1;
DefElem *e4 = makeDefElem("def_typename", (Node *) tName);
value = defGetString(e4, &need_free);
assert_true(need_free);
/* case: T_List expected value: true */
need_free = false;
List *list = NIL;
list = lappend(list, makeString("str1"));
list = lappend(list, makeString("str2"));
DefElem *e5 = makeDefElem("def_list", (Node *) list);
value = defGetString(e5, &need_free);
assert_true(need_free);
}
/* ==================== main ==================== */
int
main(int argc, char* argv[])
{
cmockery_parse_arguments(argc, argv);
const UnitTest tests[] = {
unit_test(test__DefGetString_NeedFreeFlag)
};
return run_tests(tests);
}
| 892 |
1,831 | /**
* Copyright (c) 2020-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <folly/Portability.h>
#include <folly/io/IOBufQueue.h>
#include "logdevice/common/if/gen-cpp2/payload_types.h"
#include "logdevice/common/types_internal.h"
#include "logdevice/include/types.h"
namespace facebook { namespace logdevice {
/**
* Allows encoding/decoding PayloadGroup objects to/from binary
* representation.
*/
class PayloadGroupCodec {
public:
/**
* Supports encoding of a sequence of payloads.
*/
class Encoder {
public:
/** Initializes encoder with expected number of appends */
explicit Encoder(size_t expected_appends_count);
/** Appends payload group. */
void append(const PayloadGroup& payload_group);
/**
* Appends single payload. Single payload is encoded as a PayloadGroup with
* payload at key 0.
*/
void append(folly::IOBuf&& payload);
/**
* Encodes all currently added payloads to a binary representation.
* Encoder must not be re-used after calling this.
* zstd_level must be specified if ZSTD compression is used.
*/
void encode(folly::IOBufQueue& out,
Compression compression,
int zstd_level = 0);
private:
/**
* Updates key in the last added payload group. During append, an empty
* payload group is appended first, and then this group is updated for
* each key.
* iobuf parameter can be null, indicating that key has no payload (used to
* append empty payload groups).
*/
void update(PayloadKey key, const folly::IOBuf* iobuf);
const size_t expected_appends_count_;
size_t appends_count_ = 0;
bool contains_only_empty_groups_ = false;
struct EncodedPayloads {
thrift::CompressedPayloadsMetadata metadata;
folly::IOBuf payloads;
};
std::unordered_map<PayloadKey, EncodedPayloads> encoded_payload_groups_;
};
/**
* Calculates encoded payloads size without doing actual encoding.
*/
class Estimator {
public:
Estimator();
/** Updates estimate for payload group */
void append(const PayloadGroup& payload_group);
/** Updates estimate for single payload */
void append(const folly::IOBuf& payload);
/** Claculates current size of the encoded blob */
size_t calculateSize() const {
return encoded_bytes_;
}
private:
/**
* Updates key in the last added payload group. During append, an empty
* payload group is appended first, and then this group is updated for
* each key.
* iobuf parameter can be null, indicating that key has no payload (used to
* append empty payload groups).
*/
void update(PayloadKey key, const folly::IOBuf* iobuf);
size_t appends_count_ = 0;
bool contains_only_empty_groups_ = false;
size_t encoded_bytes_;
std::unordered_set<PayloadKey> payload_keys_;
};
/**
* Encodes single PayloadGroup to binary representation.
*/
static void encode(const PayloadGroup& payload_group, folly::IOBufQueue& out);
/**
* Encoding several PayloadGroups to binary representation.
*/
static void encode(const std::vector<PayloadGroup>& payload_groups,
folly::IOBufQueue& out);
/**
* Decodes single PayloadGroup from binary representation.
* Returns number of bytes consumed, or 0 in case of error.
* Resulting PayloadGroup can optionally share data with input (for example in
* case it's uncompressed).
*/
FOLLY_NODISCARD
static size_t decode(Slice binary,
PayloadGroup& payload_group_out,
bool allow_buffer_sharing);
/**
* Decodes PayloadGroups from binary representation.
* Decoded PayloadGroups are appended to payload_groups_out on success.
* Returns number of bytes consumed, or 0 in case of error.
* Resulting PayloadGroup can optionally share data with input (for example in
* case it's uncompressed).
*/
FOLLY_NODISCARD
static size_t decode(Slice binary,
std::vector<PayloadGroup>& payload_groups_out,
bool allow_buffer_sharing);
/**
* Decodes compressed representation of payload groups batch.
* Returns number of bytes consumed, or 0 in case of error.
*/
FOLLY_NODISCARD
static size_t decode(const folly::IOBuf& iobuf,
CompressedPayloadGroups& compressed_payload_group_out,
bool allow_buffer_sharing);
};
}} // namespace facebook::logdevice
| 1,671 |
14,668 | // Copyright 2021 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/ash/policy/reporting/user_added_removed/user_added_removed_reporter.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/sequence_checker.h"
#include "base/task/bind_post_task.h"
#include "chrome/browser/ash/login/users/chrome_user_manager.h"
#include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part_chromeos.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "components/user_manager/user_names.h"
namespace reporting {
UserAddedRemovedReporter::UserAddedRemovedReporter(
std::unique_ptr<UserEventReporterHelper> helper)
: helper_(std::move(helper)) {
ProcessRemoveUserCache();
managed_session_observation_.Observe(&managed_session_service_);
}
UserAddedRemovedReporter::UserAddedRemovedReporter()
: helper_(std::make_unique<UserEventReporterHelper>(
Destination::ADDED_REMOVED_EVENTS)) {
ProcessRemoveUserCache();
managed_session_observation_.Observe(&managed_session_service_);
}
UserAddedRemovedReporter::~UserAddedRemovedReporter() = default;
void UserAddedRemovedReporter::OnLogin(Profile* profile) {
if (!helper_->ReportingEnabled(ash::kReportDeviceLoginLogout)) {
return;
}
if (!helper_->IsCurrentUserNew()) {
return;
}
user_manager::User* user =
chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
if (!user || user->IsKioskType() ||
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT ||
user->GetType() == user_manager::USER_TYPE_GUEST) {
return;
}
auto email = user->GetAccountId().GetUserEmail();
UserAddedRemovedRecord record;
record.mutable_user_added_event();
if (helper_->ShouldReportUser(email)) {
record.mutable_affiliated_user()->set_user_email(email);
}
record.set_event_timestamp_sec(base::Time::Now().ToTimeT());
helper_->ReportEvent(&record, ::reporting::Priority::IMMEDIATE);
}
void UserAddedRemovedReporter::OnUserToBeRemoved(const AccountId& account_id) {
if (!helper_->ReportingEnabled(ash::kReportDeviceLoginLogout)) {
return;
}
const user_manager::User* user =
user_manager::UserManager::Get()->FindUser(account_id);
if (!user || user->IsKioskType() ||
user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT ||
user->GetType() == user_manager::USER_TYPE_GUEST) {
return;
}
const std::string email = account_id.GetUserEmail();
users_to_be_deleted_.insert_or_assign(account_id,
helper_->ShouldReportUser(email));
}
void UserAddedRemovedReporter::OnUserRemoved(
const AccountId& account_id,
user_manager::UserRemovalReason reason) {
if (!helper_->ReportingEnabled(ash::kReportDeviceLoginLogout)) {
return;
}
auto it = users_to_be_deleted_.find(account_id);
if (it == users_to_be_deleted_.end()) {
return;
}
bool is_affiliated_user = it->second;
users_to_be_deleted_.erase(it);
UserAddedRemovedRecord record;
record.mutable_user_removed_event()->set_reason(UserRemovalReason(reason));
if (is_affiliated_user) {
record.mutable_affiliated_user()->set_user_email(account_id.GetUserEmail());
}
record.set_event_timestamp_sec(base::Time::Now().ToTimeT());
helper_->ReportEvent(&record, ::reporting::Priority::IMMEDIATE);
}
void UserAddedRemovedReporter::ProcessRemoveUserCache() {
ash::ChromeUserManager* user_manager = ash::ChromeUserManager::Get();
auto users = user_manager->GetRemovedUserCache();
for (const auto& user : users) {
UserAddedRemovedRecord record;
record.set_event_timestamp_sec(base::Time::Now().ToTimeT());
record.mutable_user_removed_event()->set_reason(
UserRemovalReason(user.second));
if (user.first != "") {
record.mutable_affiliated_user()->set_user_email(user.first);
}
helper_->ReportEvent(&record, ::reporting::Priority::IMMEDIATE);
}
user_manager->MarkReporterInitialized();
}
} // namespace reporting
| 1,508 |
605 | //===--- amdgpu/impl/interop_hsa.cpp ------------------------------ 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 "interop_hsa.h"
#include "internal.h"
hsa_status_t interop_hsa_get_symbol_info(
const std::map<std::string, atl_symbol_info_t> &SymbolInfoTable,
int DeviceId, const char *symbol, void **var_addr, unsigned int *var_size) {
/*
// Typical usage:
void *var_addr;
size_t var_size;
interop_hsa_get_symbol_addr(gpu_place, "symbol_name", &var_addr,
&var_size);
impl_memcpy(signal, host_add, var_addr, var_size);
*/
if (!symbol || !var_addr || !var_size)
return HSA_STATUS_ERROR;
// get the symbol info
std::string symbolStr = std::string(symbol);
auto It = SymbolInfoTable.find(symbolStr);
if (It != SymbolInfoTable.end()) {
atl_symbol_info_t info = It->second;
*var_addr = reinterpret_cast<void *>(info.addr);
*var_size = info.size;
return HSA_STATUS_SUCCESS;
} else {
*var_addr = NULL;
*var_size = 0;
return HSA_STATUS_ERROR;
}
}
| 497 |
467 | <reponame>LiuStart/bilisoleil
package com.yoyiyi.soleil.utils;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
/**
* Created by zzq on 2016/12/17.
* 剪贴板相关工具类
*/
public final class ClipboardUtils {
private ClipboardUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* 复制文本到剪贴板
*
* @param text 文本
*/
public static void copyText(CharSequence text) {
ClipboardManager clipboard = (ClipboardManager) AppUtils.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("text", text));
}
/**
* 获取剪贴板的文本
*
* @return 剪贴板的文本
*/
public static CharSequence getText() {
ClipboardManager clipboard = (ClipboardManager) AppUtils.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = clipboard.getPrimaryClip();
if (clip != null && clip.getItemCount() > 0) {
return clip.getItemAt(0).coerceToText(AppUtils.getAppContext());
}
return null;
}
/**
* 复制uri到剪贴板
*
* @param uri uri
*/
public static void copyUri(Uri uri) {
ClipboardManager clipboard = (ClipboardManager) AppUtils.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newUri(AppUtils.getAppContext().getContentResolver(), "uri", uri));
}
/**
* 获取剪贴板的uri
*
* @return 剪贴板的uri
*/
public static Uri getUri() {
ClipboardManager clipboard = (ClipboardManager) AppUtils.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = clipboard.getPrimaryClip();
if (clip != null && clip.getItemCount() > 0) {
return clip.getItemAt(0).getUri();
}
return null;
}
/**
* 复制意图到剪贴板
*
* @param intent 意图
*/
public static void copyIntent(Intent intent) {
ClipboardManager clipboard = (ClipboardManager) AppUtils.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newIntent("intent", intent));
}
/**
* 获取剪贴板的意图
*
* @return 剪贴板的意图
*/
public static Intent getIntent() {
ClipboardManager clipboard = (ClipboardManager) AppUtils.getAppContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = clipboard.getPrimaryClip();
if (clip != null && clip.getItemCount() > 0) {
return clip.getItemAt(0).getIntent();
}
return null;
}
}
| 1,233 |
1,338 | /*
* Copyright 2010, <NAME> <<EMAIL>>
* Distributed under the terms of the MIT License.
*/
#include <Application.h>
#include <Button.h>
#include <ControlLook.h>
#include <SpaceLayoutItem.h>
#include <Window.h>
#include "ALMLayout.h"
#include "ALMGroup.h"
class OperatorWindow : public BWindow {
public:
OperatorWindow(BRect frame)
:
BWindow(frame, "ALM Operator", B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE)
{
BButton* button1 = new BButton("1");
BButton* button2 = new BButton("2");
BButton* button3 = new BButton("3");
BButton* button4 = new BButton("4");
BButton* button5 = new BButton("5");
button1->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
button2->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
button3->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
button4->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
button5->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNLIMITED));
// create a new BALMLayout and use it for this window
float spacing = be_control_look->DefaultItemSpacing();
BALMLayout* layout = new BALMLayout(spacing);
SetLayout(layout);
layout->SetInsets(spacing);
(ALMGroup(button1) | (ALMGroup(button2)
/ (ALMGroup(button3) | ALMGroup(BSpaceLayoutItem::CreateGlue())
| ALMGroup(button4))
/ ALMGroup(button5))).BuildLayout(layout);
// test size limits
BSize min = layout->MinSize();
BSize max = layout->MaxSize();
SetSizeLimits(min.Width(), max.Width(), min.Height(), max.Height());
}
};
int
main()
{
BApplication app("application/x-vnd.haiku.ALMOperator");
OperatorWindow* window = new OperatorWindow(BRect(100, 100, 300, 300));
window->Show();
app.Run();
return 0;
}
| 684 |
652 | #ifndef Py_INTRINSICS_H
#define Py_INTRINSICS_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef WITH_INTRINSICS
# ifdef MS_WINDOWS
# include <intrin.h>
# if defined(MS_WIN64)
# pragma intrinsic(__readgsdword)
# define _Py_get_current_process_id() (__readgsdword(0x40))
# define _Py_get_current_thread_id() (__readgsdword(0x48))
# elif defined(MS_WIN32)
# pragma intrinsic(__readfsdword)
# define _Py_get_current_process_id() __readfsdword(0x20)
# define _Py_get_current_thread_id() __readfsdword(0x24)
# else
# error "Unsupported architecture."
# endif
# define _Py_clflush(p) _mm_clflush(p)
# define _Py_lfence() _mm_lfence()
# define _Py_mfence() _mm_mfence()
# define _Py_sfence() _mm_sfence()
# define _Py_rdtsc() __rdtsc()
# define _Py_popcnt_u32(v) _mm_popcnt_u32(v)
# define _Py_popcnt_u64(v) _mm_popcnt_u64(v)
# define _Py_UINT32_BITS_SET(v) Py_popcnt_u32(v)
# define _Py_UINT64_BITS_SET(v) _Py_popcnt_u64(v)
# else
# error "Intrinsics not available for this platform yet."
# endif
#else /* WITH_INTRINSICS */
# ifdef MS_WINDOWS
# define _Py_get_current_process_id GetCurrentProcessId()
# define _Py_get_current_thread_id GetCurrentThreadId()
# define _Py_clflush() XXX_UNKNOWN
# define _Py_lfence() MemoryBarrier()
# define _Py_mfence() MemoryBarrier()
# define _Py_sfence() MemoryBarrier()
# else /* MS_WINDOWS */
# error "No intrinsics stubs available for this platform."
# endif
#endif
__inline
int
Py_popcnt_u32(unsigned int i)
{
i = i - ((i >> 1 & 0x55555555));
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (i + (i >> 4)) & 0x0f0f0f0f;
i = i + (i >> 8);
i = i + (i >> 16);
return i & 0x0000003f;
}
#ifdef __cplusplus
}
#endif
#endif
/* vim:set ts=8 sw=4 sts=4 tw=78 et: */
| 1,054 |
6,958 | # Copyright @ 2019 Alibaba. All rights reserved.
# Created by ruhuan on 2019.08.31
""" build wheel tool """
from __future__ import print_function
import argparse
parser = argparse.ArgumentParser(description='build pymnn wheel')
parser.add_argument('--x86', dest='x86', action='store_true', default=False,
help='build wheel for 32bit arch, only usable on windows')
parser.add_argument('--version', dest='version', type=str, required=True,
help='MNN dist version')
args = parser.parse_args()
import os
import shutil
import platform
IS_WINDOWS = (platform.system() == 'Windows')
IS_DARWIN = (platform.system() == 'Darwin')
IS_LINUX = (platform.system() == 'Linux')
if __name__ == '__main__':
os.system("pip install -U numpy")
if os.path.exists('build'):
shutil.rmtree('build')
comm_args = '--version ' + args.version
if IS_LINUX:
comm_args += ' --plat-name=manylinux1_x86_64'
if IS_WINDOWS:
os.putenv('DISTUTILS_USE_SDK', '1')
os.putenv('MSSdk', '1')
comm_args += ' --x86' if args.x86 else ''
os.system('python setup.py bdist_wheel %s' % comm_args)
| 454 |
2,406 | <filename>model-optimizer/unit_tests/extensions/ops/interpolate_test.py
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import unittest
import numpy as np
from generator import generator, generate
from extensions.ops.interpolate import Interpolate
from mo.front.common.partial_infer.utils import int64_array
from mo.graph.graph import Node
from unit_tests.utils.graph import build_graph
graph_node_attrs_without_axes = {
'input': {'type': 'Parameter', 'kind': 'op'},
'input_data': {'kind': 'data', 'shape': None, 'value': None},
'sizes': {'type': 'Const', 'kind': 'op', 'shape': None, 'value': None},
'sizes_data': {'kind': 'data', 'shape': None, 'value': None},
'scales': {'type': 'Const', 'kind': 'op', 'shape': None, 'value': None},
'scales_data': {'kind': 'data', 'shape': None, 'value': None},
'interpolate': {
'type': 'Interpolate', 'kind': 'op', 'mode': 'nearest', 'shape_calculation_mode': 'sizes',
'coordinate_transformation_mode': 'half_pixel', 'version': 'opset4',
'nearest_mode': 'round_prefer_floor', 'antialias': 0,
},
'interpolate_data': {'kind': 'data', 'value': None, 'shape': None},
'op_output': {'kind': 'op', 'op': 'Result'},
}
graph_edges_without_axes = [
('input', 'input_data'),
('sizes', 'sizes_data'),
('scales', 'scales_data'),
('input_data', 'interpolate', {'in': 0}),
('sizes_data', 'interpolate', {'in': 1}),
('scales_data', 'interpolate', {'in': 2}),
('interpolate', 'interpolate_data'),
('interpolate_data', 'op_output'),
]
graph_nodes_attrs = {
'input': {'type': 'Parameter', 'kind': 'op'},
'input_data': {'kind': 'data', 'shape': None, 'value': None},
'sizes': {'type': 'Const', 'kind': 'op', 'shape': None, 'value': None},
'sizes_data': {'kind': 'data', 'shape': None, 'value': None},
'scales': {'type': 'Const', 'kind': 'op', 'shape': None, 'value': None},
'scales_data': {'kind': 'data', 'shape': None, 'value': None},
'axes': {'type': 'Const', 'kind': 'op', 'shape': None, 'value': None},
'axes_data': {'kind': 'data', 'shape': None, 'value': None},
'interpolate': {
'type': 'Interpolate', 'kind': 'op', 'mode': 'nearest', 'shape_calculation_mode': 'sizes',
'coordinate_transformation_mode': 'half_pixel', 'version': 'opset4',
'nearest_mode': 'round_prefer_floor', 'antialias': 0,
},
'interpolate_data': {'kind': 'data', 'value': None, 'shape': None},
'op_output': {'kind': 'op', 'op': 'Result'},
}
graph_edges = [
('input', 'input_data'),
('sizes', 'sizes_data'),
('scales', 'scales_data'),
('axes', 'axes_data'),
('input_data', 'interpolate', {'in': 0}),
('sizes_data', 'interpolate', {'in': 1}),
('scales_data', 'interpolate', {'in': 2}),
('axes_data', 'interpolate', {'in': 3}),
('interpolate', 'interpolate_data'),
('interpolate_data', 'op_output'),
]
@generator
class TestInterpolateOp(unittest.TestCase):
@generate(*[([0], [0], [1, 3, 100, 200], [1, 3, 350, 150], [350, 150], [3.5, 150 / 200], [2, 3]),
([0, 3, 10, 10], [0], [16, 7, 190, 400], [8, 10, 390, 600],
[8, 390, 600], [0.5, 390 / 200, 600 / 410], [0, 2, 3]),
([10, 5, 0, 10], [0, 4, 16, 18], [4, 33, 1024, 8000], [56, 42, 520, 8028],
[56, 520], [4.0, 0.5], [0, 2]),
([0], [0], [1, 16, 85, 470, 690], [20, 16, 40, 470, 1380],
[20, 40, 1380], [20.0, 40.0 / 85.0, 1380.0 / 690.0], [0, 2, 4]),
([4, 3, 11, 22, 5], [1, 3, 4, 8, 5], [1, 16, 85, 470, 690], [60, 22, 430, 500, 345],
[60, 430, 345], [10.0, 4.3, 345.0 / 700.0], [0, 2, 4]),
([0], [0], [5, 77, 444, 88, 6050], [100, 308, 4440, 44, 6050],
[100, 308, 4440, 44], [20.0, 4.0, 10.0, 0.5], [0, 1, 2, 3]),
([0], [0], [1, 100, 200], [1, 350, 150], [350, 150], [3.5, 150 / 200], [1, 2]),
([0, 3, 10], [0], [16, 7, 190], [8, 10, 390], [8, 390], [0.5, 390 / 200], [0, 2]),
([10, 0, 10], [0, 16, 18], [4, 1024, 8000], [56, 520, 8028], [56, 520], [4.0, 0.5], [0, 1]),
([0], [0], [1, 690], [20, 1380], [20, 1380], [20.0, 1380.0 / 690.0], [0, 1]),
([4, 3, 11, 22, 5, 0], [1, 3, 4, 8, 5, 0], [1, 16, 85, 470, 690, 349], [60, 22, 430, 500, 345, 349],
[60, 430, 345], [10.0, 4.3, 345.0 / 700.0], [0, 2, 4])
])
def test_interpolate4_using_sizes(self, pads_begin, pads_end, input_shape, output_shape, sizes, scales, axes):
graph = build_graph(nodes_attrs=graph_nodes_attrs,
edges=graph_edges,
update_attributes={
'input_data': {'shape': input_shape},
'sizes': {'shape': int64_array(sizes).shape, 'value': int64_array(sizes)},
'sizes_data': {'shape': int64_array(sizes).shape, 'value': int64_array(sizes)},
'scales': {'shape': np.array(scales).shape, 'value': np.array(scales)},
'scales_data': {'shape': np.array(scales).shape, 'value': np.array(scales)},
'axes': {'shape': int64_array(axes).shape, 'value': int64_array(axes)},
'axes_data': {'shape': int64_array(axes).shape, 'value': int64_array(axes)},
'interpolate': {'pads_begin': int64_array(pads_begin),
'pads_end': int64_array(pads_end)}
})
node = Node(graph, 'interpolate')
tested_class = Interpolate(graph=graph, attrs=node.attrs())
tested_class.infer(node)
msg = "Interpolate-4 infer failed for case: sizes={}, scales={}, pads_begin={}, pads_end={}, axes={}," \
" expected_shape={}, actual_shape={}"
self.assertTrue(np.array_equal(graph.node['interpolate_data']['shape'], int64_array(output_shape)),
msg.format(sizes, scales, pads_begin, pads_end, axes, output_shape,
graph.node['interpolate_data']['shape']))
@generate(*[([0], [0], [1, 3, 100, 200], [1, 3, 350, 150], [350, 150], [3.5, 150 / 200], [2, 3]),
([0, 3, 10, 10], [0], [16, 7, 190, 400], [8, 10, 390, 600],
[8, 390, 600], [0.5, 390 / 200, 600 / 410], [0, 2, 3]),
([10, 5, 0, 10], [0, 4, 16, 18], [4, 33, 1024, 8000], [56, 42, 520, 8028],
[56, 520], [4.0, 0.5], [0, 2]),
([0], [0], [1, 16, 85, 470, 690], [20, 16, 40, 470, 1380],
[20, 40, 1380], [20.0, 40.0 / 85.0, 1380.0 / 690.0], [0, 2, 4]),
([4, 3, 11, 22, 5], [1, 3, 4, 8, 5], [1, 16, 85, 470, 690], [60, 22, 430, 500, 345],
[60, 430, 345], [10.0, 4.3, 345.0 / 700.0], [0, 2, 4]),
([0], [0], [5, 77, 444, 88, 6050], [100, 308, 4440, 44, 6050],
[100, 308, 4440, 44], [20.0, 4.0, 10.0, 0.5], [0, 1, 2, 3]),
([0], [0], [1, 100, 200], [1, 350, 150], [350, 150], [3.5, 150 / 200], [1, 2]),
([0, 3, 10], [0], [16, 7, 190], [8, 10, 390], [8, 390], [0.5, 390 / 200], [0, 2]),
([10, 0, 10], [0, 16, 18], [4, 1024, 8000], [56, 520, 8028], [56, 520], [4.0, 0.5], [0, 1]),
([0], [0], [1, 690], [20, 1380], [20, 1380], [20.0, 1380.0 / 690.0], [0, 1]),
([4, 3, 11, 22, 5, 0], [1, 3, 4, 8, 5, 0], [1, 16, 85, 470, 690, 349], [60, 22, 430, 500, 345, 349],
[60, 430, 345], [10.0, 4.3, 345.0 / 700.0], [0, 2, 4]),
([4, 3, 11, 22, 5, 0, 0], [1, 3, 4, 8, 5, 0, 0], [1, 16, 85, 470, 690, 349, 3],
[60, 22, 430, 500, 345, 349, 1],
[60, 430, 345, 1], [10.0, 4.3, 345.0 / 700.0, 1 / 3], [0, 2, 4, 6]),
([4, 3, 11, 22, 5, 0, 0], [1, 3, 4, 8, 5, 0, 0], [1, 16, 85, 470, 690, 349, 3],
[60, 22, 430, 500, 345, 349, 1],
[60, 430, 345, 1], [10.0, 4.3, 345.0 / 700.0, 0.3333333], [0, 2, 4, 6]),
])
def test_interpolate4_using_scales(self, pads_begin, pads_end, input_shape, output_shape, sizes, scales, axes):
graph = build_graph(nodes_attrs=graph_nodes_attrs,
edges=graph_edges,
update_attributes={
'input_data': {'shape': input_shape},
'sizes': {'shape': int64_array(sizes).shape, 'value': int64_array(sizes)},
'sizes_data': {'shape': int64_array(sizes).shape, 'value': int64_array(sizes)},
'scales': {'shape': np.array(scales).shape, 'value': np.array(scales)},
'scales_data': {'shape': np.array(scales).shape, 'value': np.array(scales)},
'axes': {'shape': int64_array(axes).shape, 'value': int64_array(axes)},
'axes_data': {'shape': int64_array(axes).shape, 'value': int64_array(axes)},
'interpolate': {'pads_begin': int64_array(pads_begin),
'pads_end': int64_array(pads_end),
'shape_calculation_mode': 'scales'}
})
node = Node(graph, 'interpolate')
tested_class = Interpolate(graph=graph, attrs=node.attrs())
tested_class.infer(node)
msg = "Interpolate-4 infer failed for case: sizes={}, scales={}, pads_begin={}, pads_end={}, axes={}," \
" expected_shape={}, actual_shape={}"
self.assertTrue(np.array_equal(graph.node['interpolate_data']['shape'], int64_array(output_shape)),
msg.format(sizes, scales, pads_begin, pads_end, axes, output_shape,
graph.node['interpolate_data']['shape']))
@generate(*[([0], [0], [1, 3, 100, 200], [1, 3, 350, 150], [1, 3, 350, 150], [1.0, 1.0, 3.5, 150 / 200]),
([0, 3, 10, 10], [0], [16, 7, 190, 400], [8, 10, 390, 600],
[8, 10, 390, 600], [0.5, 1.0, 390 / 200, 600 / 410]),
([10, 5, 0, 10], [0, 4, 16, 18], [4, 33, 1024, 8000], [56, 42, 520, 8028],
[56, 42, 520, 8028], [4.0, 1.0, 0.5, 1.0]),
([0], [0], [1, 16, 85, 470, 690], [20, 16, 40, 470, 1380],
[20, 16, 40, 470, 1380], [20.0, 1.0, 40.0 / 85.0, 1.0, 1380.0 / 690.0]),
([4, 3, 11, 22, 5], [1, 3, 4, 8, 5], [1, 16, 85, 470, 690], [60, 22, 430, 500, 345],
[60, 22, 430, 500, 345], [10.0, 1.0, 4.3, 1.0, 345.0 / 700.0]),
([0], [0], [5, 77, 444, 88, 6050], [100, 308, 4440, 44, 6050],
[100, 308, 4440, 44, 6050], [20.0, 4.0, 10.0, 0.5, 1.0]),
([0], [0], [1, 100, 200], [1, 350, 150], [1, 350, 150], [1.0, 3.5, 150 / 200]),
([0, 3, 10], [0], [16, 7, 190], [8, 10, 390], [8, 10, 390], [0.5, 1.0, 390 / 200]),
([10, 0, 10], [0, 16, 18], [4, 1024, 8000], [56, 520, 8028], [56, 520, 8028], [4.0, 0.5, 1.0]),
([0], [0], [1, 690], [20, 1380], [20, 1380], [20.0, 1380.0 / 690.0]),
([4, 3, 11, 22, 5, 0], [1, 3, 4, 8, 5, 0], [1, 16, 85, 470, 690, 349], [60, 22, 430, 500, 345, 349],
[60, 22, 430, 500, 345, 349], [10.0, 1.0, 4.3, 1.0, 345.0 / 700.0, 1.0]),
([4, 3, 11, 22, 5, 0, 0], [1, 3, 4, 8, 5, 0, 0], [1, 16, 85, 470, 690, 349, 3],
[60, 22, 430, 500, 345, 349, 1],
[60, 22, 430, 500, 345, 349, 1], [10.0, 1.0, 4.3, 1.0, 345.0 / 700.0, 1.0, 1 / 3]),
])
def test_interpolate4_using_sizes_without_axes(self, pads_begin, pads_end, input_shape, output_shape, sizes,
scales):
graph = build_graph(nodes_attrs=graph_node_attrs_without_axes,
edges=graph_edges_without_axes,
update_attributes={
'input_data': {'shape': input_shape},
'sizes': {'shape': int64_array(sizes).shape, 'value': int64_array(sizes)},
'sizes_data': {'shape': int64_array(sizes).shape, 'value': int64_array(sizes)},
'scales': {'shape': np.array(scales).shape, 'value': np.array(scales)},
'scales_data': {'shape': np.array(scales).shape, 'value': np.array(scales)},
'interpolate': {'pads_begin': int64_array(pads_begin),
'pads_end': int64_array(pads_end),
'shape_calculation_mode': 'sizes'}
})
node = Node(graph, 'interpolate')
tested_class = Interpolate(graph=graph, attrs=node.attrs())
tested_class.infer(node)
msg = "Interpolate-4 infer failed for case: sizes={}, scales={}, pads_begin={}, pads_end={}," \
" expected_shape={}, actual_shape={}"
self.assertTrue(np.array_equal(graph.node['interpolate_data']['shape'], int64_array(output_shape)),
msg.format(sizes, scales, pads_begin, pads_end, output_shape,
graph.node['interpolate_data']['shape']))
@generate(*[([0], [0], [1, 3, 100, 200], [1, 3, 350, 150], [1, 3, 350, 150], [1.0, 1.0, 3.5, 150 / 200]),
([0, 3, 10, 10], [0], [16, 7, 190, 400], [8, 10, 390, 600],
[8, 10, 390, 600], [0.5, 1.0, 390 / 200, 600 / 410]),
([10, 5, 0, 10], [0, 4, 16, 18], [4, 33, 1024, 8000], [56, 42, 520, 8028],
[56, 42, 520, 8028], [4.0, 1.0, 0.5, 1.0]),
([0], [0], [1, 16, 85, 470, 690], [20, 16, 40, 470, 1380],
[20, 16, 40, 470, 1380], [20.0, 1.0, 40.0 / 85.0, 1.0, 1380.0 / 690.0]),
([4, 3, 11, 22, 5], [1, 3, 4, 8, 5], [1, 16, 85, 470, 690], [60, 22, 430, 500, 345],
[60, 22, 430, 500, 345], [10.0, 1.0, 4.3, 1.0, 345.0 / 700.0]),
([0], [0], [5, 77, 444, 88, 6050], [100, 308, 4440, 44, 6050],
[100, 308, 4440, 44, 6050], [20.0, 4.0, 10.0, 0.5, 1.0]),
([0], [0], [1, 100, 200], [1, 350, 150], [1, 350, 150], [1.0, 3.5, 150 / 200]),
([0, 3, 10], [0], [16, 7, 190], [8, 10, 390], [8, 10, 390], [0.5, 1.0, 390 / 200]),
([10, 0, 10], [0, 16, 18], [4, 1024, 8000], [56, 520, 8028], [56, 520, 8028], [4.0, 0.5, 1.0]),
([0], [0], [1, 690], [20, 1380], [20, 1380], [20.0, 1380.0 / 690.0]),
([4, 3, 11, 22, 5, 0], [1, 3, 4, 8, 5, 0], [1, 16, 85, 470, 690, 349], [60, 22, 430, 500, 345, 349],
[60, 22, 430, 500, 345, 349], [10.0, 1.0, 4.3, 1.0, 345.0 / 700.0, 1.0]),
([4, 3, 11, 22, 5, 0, 0], [1, 3, 4, 8, 5, 0, 0], [1, 16, 85, 470, 690, 349, 3],
[60, 22, 430, 500, 345, 349, 1],
[60, 22, 430, 500, 345, 349, 1], [10.0, 1.0, 4.3, 1.0, 345.0 / 700.0, 1.0, 1 / 3]),
([4, 3, 11, 22, 5, 0, 0], [1, 3, 4, 8, 5, 0, 0], [1, 16, 85, 470, 690, 349, 3],
[60, 22, 430, 500, 345, 349, 1],
[60, 22, 430, 500, 345, 349, 1], [10.0, 1.0, 4.3, 1.0, 345.0 / 700.0, 1.0, 0.3333333]),
])
def test_interpolate4_using_scales_without_axes(self, pads_begin, pads_end, input_shape, output_shape, sizes,
scales):
graph = build_graph(nodes_attrs=graph_node_attrs_without_axes,
edges=graph_edges_without_axes,
update_attributes={
'input_data': {'shape': input_shape},
'sizes': {'shape': int64_array(sizes).shape, 'value': int64_array(sizes)},
'sizes_data': {'shape': int64_array(sizes).shape, 'value': int64_array(sizes)},
'scales': {'shape': np.array(scales).shape, 'value': np.array(scales)},
'scales_data': {'shape': np.array(scales).shape, 'value': np.array(scales)},
'interpolate': {'pads_begin': int64_array(pads_begin),
'pads_end': int64_array(pads_end),
'shape_calculation_mode': 'scales'}
})
node = Node(graph, 'interpolate')
tested_class = Interpolate(graph=graph, attrs=node.attrs())
tested_class.infer(node)
msg = "Interpolate-4 infer failed for case: sizes={}, scales={}, pads_begin={}, pads_end={}," \
" expected_shape={}, actual_shape={}"
self.assertTrue(np.array_equal(graph.node['interpolate_data']['shape'], int64_array(output_shape)),
msg.format(sizes, scales, pads_begin, pads_end, output_shape,
graph.node['interpolate_data']['shape']))
| 9,662 |
2,762 | <reponame>fbordignon/pyqtgraph
# -*- coding: utf-8 -*-
"""
This module exists to smooth out some of the differences between PySide and PyQt4:
* Automatically import either PyQt4 or PySide depending on availability
* Allow to import QtCore/QtGui pyqtgraph.Qt without specifying which Qt wrapper
you want to use.
* Declare QtCore.Signal, .Slot in PyQt4
* Declare loadUiType function for Pyside
"""
import os, sys, re, time, subprocess, warnings
PYSIDE = 'PySide'
PYSIDE2 = 'PySide2'
PYSIDE6 = 'PySide6'
PYQT4 = 'PyQt4'
PYQT5 = 'PyQt5'
PYQT6 = 'PyQt6'
QT_LIB = os.getenv('PYQTGRAPH_QT_LIB')
## Automatically determine which Qt package to use (unless specified by
## environment variable).
## This is done by first checking to see whether one of the libraries
## is already imported. If not, then attempt to import in the order
## specified in libOrder.
if QT_LIB is None:
libOrder = [PYQT5, PYSIDE2, PYSIDE6, PYQT6]
for lib in libOrder:
if lib in sys.modules:
QT_LIB = lib
break
if QT_LIB is None:
for lib in libOrder:
try:
__import__(lib)
QT_LIB = lib
break
except ImportError:
pass
if QT_LIB is None:
raise Exception("PyQtGraph requires one of PyQt5, PyQt6, PySide2 or PySide6; none of these packages could be imported.")
class FailedImport(object):
"""Used to defer ImportErrors until we are sure the module is needed.
"""
def __init__(self, err):
self.err = err
def __getattr__(self, attr):
raise self.err
# Make a loadUiType function like PyQt has
# Credit:
# http://stackoverflow.com/questions/4442286/python-code-genration-with-pyside-uic/14195313#14195313
class _StringIO(object):
"""Alternative to built-in StringIO needed to circumvent unicode/ascii issues"""
def __init__(self):
self.data = []
def write(self, data):
self.data.append(data)
def getvalue(self):
return ''.join(map(str, self.data)).encode('utf8')
def _loadUiType(uiFile):
"""
PySide lacks a "loadUiType" command like PyQt4's, so we have to convert
the ui file to py code in-memory first and then execute it in a
special frame to retrieve the form_class.
from stackoverflow: http://stackoverflow.com/a/14195313/3781327
seems like this might also be a legitimate solution, but I'm not sure
how to make PyQt4 and pyside look the same...
http://stackoverflow.com/a/8717832
"""
pyside2uic = None
if QT_LIB == PYSIDE2:
try:
import pyside2uic
except ImportError:
# later versions of pyside2 have dropped pyside2uic; use the uic binary instead.
pyside2uic = None
if pyside2uic is None:
pyside2version = tuple(map(int, PySide2.__version__.split(".")))
if (5, 14) <= pyside2version < (5, 14, 2, 2):
warnings.warn('For UI compilation, it is recommended to upgrade to PySide >= 5.15')
# get class names from ui file
import xml.etree.ElementTree as xml
parsed = xml.parse(uiFile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
# convert ui file to python code
if pyside2uic is None:
uic_executable = QT_LIB.lower() + '-uic'
uipy = subprocess.check_output([uic_executable, uiFile])
else:
o = _StringIO()
with open(uiFile, 'r') as f:
pyside2uic.compileUi(f, o, indent=0)
uipy = o.getvalue()
# execute python code
pyc = compile(uipy, '<string>', 'exec')
frame = {}
exec(pyc, frame)
# fetch the base_class and form class based on their type in the xml from designer
form_class = frame['Ui_%s'%form_class]
base_class = eval('QtGui.%s'%widget_class)
return form_class, base_class
# For historical reasons, pyqtgraph maintains a Qt4-ish interface back when
# there wasn't a QtWidgets module. This _was_ done by monkey-patching all of
# QtWidgets into the QtGui module. This monkey-patching modifies QtGui at a
# global level.
# To avoid this, we now maintain a local "mirror" of QtCore, QtGui and QtWidgets.
# Thus, when monkey-patching happens later on in this file, they will only affect
# the local modules and not the global modules.
def _copy_attrs(src, dst):
for o in dir(src):
if not hasattr(dst, o):
setattr(dst, o, getattr(src, o))
from . import QtCore, QtGui, QtWidgets
if QT_LIB == PYQT5:
# We're using PyQt5 which has a different structure so we're going to use a shim to
# recreate the Qt4 structure for Qt5
import PyQt5.QtCore, PyQt5.QtGui, PyQt5.QtWidgets
_copy_attrs(PyQt5.QtCore, QtCore)
_copy_attrs(PyQt5.QtGui, QtGui)
_copy_attrs(PyQt5.QtWidgets, QtWidgets)
try:
from PyQt5 import sip
except ImportError:
# some Linux distros package it this way (e.g. Ubuntu)
import sip
from PyQt5 import uic
try:
from PyQt5 import QtSvg
except ImportError as err:
QtSvg = FailedImport(err)
try:
from PyQt5 import QtTest
except ImportError as err:
QtTest = FailedImport(err)
VERSION_INFO = 'PyQt5 ' + QtCore.PYQT_VERSION_STR + ' Qt ' + QtCore.QT_VERSION_STR
elif QT_LIB == PYQT6:
import PyQt6.QtCore, PyQt6.QtGui, PyQt6.QtWidgets
_copy_attrs(PyQt6.QtCore, QtCore)
_copy_attrs(PyQt6.QtGui, QtGui)
_copy_attrs(PyQt6.QtWidgets, QtWidgets)
from PyQt6 import sip, uic
try:
from PyQt6 import QtSvg
except ImportError as err:
QtSvg = FailedImport(err)
try:
from PyQt6 import QtOpenGLWidgets
except ImportError as err:
QtOpenGLWidgets = FailedImport(err)
try:
from PyQt6 import QtTest
except ImportError as err:
QtTest = FailedImport(err)
VERSION_INFO = 'PyQt6 ' + QtCore.PYQT_VERSION_STR + ' Qt ' + QtCore.QT_VERSION_STR
elif QT_LIB == PYSIDE2:
import PySide2.QtCore, PySide2.QtGui, PySide2.QtWidgets
_copy_attrs(PySide2.QtCore, QtCore)
_copy_attrs(PySide2.QtGui, QtGui)
_copy_attrs(PySide2.QtWidgets, QtWidgets)
try:
from PySide2 import QtSvg
except ImportError as err:
QtSvg = FailedImport(err)
try:
from PySide2 import QtTest
except ImportError as err:
QtTest = FailedImport(err)
import shiboken2 as shiboken
import PySide2
VERSION_INFO = 'PySide2 ' + PySide2.__version__ + ' Qt ' + QtCore.__version__
elif QT_LIB == PYSIDE6:
import PySide6.QtCore, PySide6.QtGui, PySide6.QtWidgets
_copy_attrs(PySide6.QtCore, QtCore)
_copy_attrs(PySide6.QtGui, QtGui)
_copy_attrs(PySide6.QtWidgets, QtWidgets)
try:
from PySide6 import QtSvg
except ImportError as err:
QtSvg = FailedImport(err)
try:
from PySide6 import QtOpenGLWidgets
except ImportError as err:
QtOpenGLWidgets = FailedImport(err)
try:
from PySide6 import QtTest
except ImportError as err:
QtTest = FailedImport(err)
import shiboken6 as shiboken
import PySide6
VERSION_INFO = 'PySide6 ' + PySide6.__version__ + ' Qt ' + QtCore.__version__
else:
raise ValueError("Invalid Qt lib '%s'" % QT_LIB)
# common to PyQt5, PyQt6, PySide2 and PySide6
if QT_LIB in [PYQT5, PYQT6, PYSIDE2, PYSIDE6]:
# We're using Qt5 which has a different structure so we're going to use a shim to
# recreate the Qt4 structure
if QT_LIB in [PYQT5, PYSIDE2]:
__QGraphicsItem_scale = QtWidgets.QGraphicsItem.scale
def scale(self, *args):
warnings.warn(
"Deprecated Qt API, will be removed in 0.13.0.",
DeprecationWarning, stacklevel=2
)
if args:
sx, sy = args
tr = self.transform()
tr.scale(sx, sy)
self.setTransform(tr)
else:
return __QGraphicsItem_scale(self)
QtWidgets.QGraphicsItem.scale = scale
def rotate(self, angle):
warnings.warn(
"Deprecated Qt API, will be removed in 0.13.0.",
DeprecationWarning, stacklevel=2
)
tr = self.transform()
tr.rotate(angle)
self.setTransform(tr)
QtWidgets.QGraphicsItem.rotate = rotate
def translate(self, dx, dy):
warnings.warn(
"Deprecated Qt API, will be removed in 0.13.0.",
DeprecationWarning, stacklevel=2
)
tr = self.transform()
tr.translate(dx, dy)
self.setTransform(tr)
QtWidgets.QGraphicsItem.translate = translate
def setMargin(self, i):
warnings.warn(
"Deprecated Qt API, will be removed in 0.13.0.",
DeprecationWarning, stacklevel=2
)
self.setContentsMargins(i, i, i, i)
QtWidgets.QGridLayout.setMargin = setMargin
def setResizeMode(self, *args):
warnings.warn(
"Deprecated Qt API, will be removed in 0.13.0.",
DeprecationWarning, stacklevel=2
)
self.setSectionResizeMode(*args)
QtWidgets.QHeaderView.setResizeMode = setResizeMode
# Import all QtWidgets objects into QtGui
for o in dir(QtWidgets):
if o.startswith('Q'):
setattr(QtGui, o, getattr(QtWidgets,o) )
QtGui.QApplication.setGraphicsSystem = None
if QT_LIB in [PYQT6, PYSIDE6]:
# We're using Qt6 which has a different structure so we're going to use a shim to
# recreate the Qt5 structure
if not isinstance(QtOpenGLWidgets, FailedImport):
QtWidgets.QOpenGLWidget = QtOpenGLWidgets.QOpenGLWidget
# Common to PySide2 and PySide6
if QT_LIB in [PYSIDE2, PYSIDE6]:
QtVersion = QtCore.__version__
loadUiType = _loadUiType
isQObjectAlive = shiboken.isValid
# PySide does not implement qWait
if not isinstance(QtTest, FailedImport):
if not hasattr(QtTest.QTest, 'qWait'):
@staticmethod
def qWait(msec):
start = time.time()
QtGui.QApplication.processEvents()
while time.time() < start + msec * 0.001:
QtGui.QApplication.processEvents()
QtTest.QTest.qWait = qWait
# Common to PyQt5 and PyQt6
if QT_LIB in [PYQT5, PYQT6]:
QtVersion = QtCore.QT_VERSION_STR
# PyQt, starting in v5.5, calls qAbort when an exception is raised inside
# a slot. To maintain backward compatibility (and sanity for interactive
# users), we install a global exception hook to override this behavior.
if sys.excepthook == sys.__excepthook__:
sys_excepthook = sys.excepthook
def pyqt_qabort_override(*args, **kwds):
return sys_excepthook(*args, **kwds)
sys.excepthook = pyqt_qabort_override
def isQObjectAlive(obj):
return not sip.isdeleted(obj)
loadUiType = uic.loadUiType
QtCore.Signal = QtCore.pyqtSignal
# USE_XXX variables are deprecated
USE_PYSIDE = QT_LIB == PYSIDE
USE_PYQT4 = QT_LIB == PYQT4
USE_PYQT5 = QT_LIB == PYQT5
## Make sure we have Qt >= 5.12
versionReq = [5, 12]
m = re.match(r'(\d+)\.(\d+).*', QtVersion)
if m is not None and list(map(int, m.groups())) < versionReq:
print(list(map(int, m.groups())))
raise Exception('pyqtgraph requires Qt version >= %d.%d (your version is %s)' % (versionReq[0], versionReq[1], QtVersion))
App = QtWidgets.QApplication
# subclassing QApplication causes segfaults on PySide{2, 6} / Python 3.8.7+
QAPP = None
def mkQApp(name=None):
"""
Creates new QApplication or returns current instance if existing.
============== ========================================================
**Arguments:**
name (str) Application name, passed to Qt
============== ========================================================
"""
global QAPP
def onPaletteChange(palette):
color = palette.base().color().name()
app = QtWidgets.QApplication.instance()
app.setProperty('darkMode', color.lower() != "#ffffff")
QAPP = QtGui.QApplication.instance()
if QAPP is None:
# hidpi handling
qtVersionCompare = tuple(map(int, QtVersion.split(".")))
if qtVersionCompare > (6, 0):
# Qt6 seems to support hidpi without needing to do anything so continue
pass
elif qtVersionCompare > (5, 14):
os.environ["QT_ENABLE_HIGHDPI_SCALING"] = "1"
QtGui.QApplication.setHighDpiScaleFactorRoundingPolicy(QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
else: # qt 5.12 and 5.13
QtGui.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
QtGui.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
QAPP = QtGui.QApplication(sys.argv or ["pyqtgraph"])
QAPP.paletteChanged.connect(onPaletteChange)
QAPP.paletteChanged.emit(QAPP.palette())
if name is not None:
QAPP.setApplicationName(name)
return QAPP
# exec() is used within _loadUiType, so we define as exec_() here and rename in pg namespace
def exec_():
app = mkQApp()
return app.exec() if hasattr(app, 'exec') else app.exec_()
| 5,985 |
797 | <gh_stars>100-1000
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// IMPORTANT: This is for demo /simulation purposes only. Use a better random
// function in production applications.
#include "libc_rand_impl.h"
#include <assert.h>
#include <stdint.h> // uint64_t
#include <stdlib.h> // srand
namespace rappor {
//
// LibcRand
//
// Similar to client/python/fastrand.c
bool LibcRand::GetMask(float prob, int num_bits, Bits* mask_out) const {
int rand_threshold = static_cast<int>(prob * RAND_MAX);
Bits mask = 0;
for (int i = 0; i < num_bits; ++i) {
// NOTE: could use rand_r(), which is more thread-safe
Bits bit = (rand() < rand_threshold);
mask |= (bit << i);
}
*mask_out = mask;
return true; // no possible failure
}
} // namespace rappor
| 423 |
14,668 | <reponame>chromium/chromium
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/bluetooth/bluetooth.h"
#include <utility>
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "mojo/public/cpp/bindings/associated_receiver_set.h"
#include "mojo/public/cpp/bindings/pending_associated_remote.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_string_unsignedlong.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_bluetooth_advertising_event_init.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_bluetooth_data_filter_init.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_bluetooth_le_scan_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_bluetooth_manufacturer_data_filter_init.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_request_device_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_typedefs.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/frame.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/navigator.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_device.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_error.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_le_scan.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_manufacturer_data_map.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_characteristic.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_service_data_map.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_uuid.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
namespace {
// Per the Bluetooth Spec: The name is a user-friendly name associated with the
// device and consists of a maximum of 248 bytes coded according to the UTF-8
// standard.
const size_t kMaxDeviceNameLength = 248;
const char kDeviceNameTooLong[] =
"A device name can't be longer than 248 bytes.";
const char kInactiveDocumentError[] = "Document not active";
const char kHandleGestureForPermissionRequest[] =
"Must be handling a user gesture to show a permission request.";
const char kFencedFrameError[] =
"Web Bluetooth is not allowed in a fenced frame tree.";
// Does basic checks that are common to all IDL calls, mainly that the window is
// valid, and the request is not being done from a fenced frame tree. Returns
// true if exceptions have been flagged, and false otherwise.
bool IsRequestDenied(LocalDOMWindow* window, ExceptionState& exception_state) {
if (!window) {
exception_state.ThrowTypeError(kInactiveDocumentError);
} else if (window->GetFrame()->IsInFencedFrameTree()) {
exception_state.ThrowDOMException(DOMExceptionCode::kNotAllowedError,
kFencedFrameError);
}
return exception_state.HadException();
}
// Remind developers when they are using Web Bluetooth on unsupported platforms.
// TODO(https://crbug.com/570344): Remove this method when all platforms are
// supported.
void AddUnsupportedPlatformConsoleMessage(ExecutionContext* context) {
#if !BUILDFLAG(IS_CHROMEOS_ASH) && !defined(OS_ANDROID) && !defined(OS_MAC) && \
!defined(OS_WIN)
context->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kJavaScript,
mojom::blink::ConsoleMessageLevel::kInfo,
"Web Bluetooth is experimental on this platform. See "
"https://github.com/WebBluetoothCG/web-bluetooth/blob/main/"
"implementation-status.md"));
#endif
}
void CanonicalizeFilter(
const BluetoothLEScanFilterInit* filter,
mojom::blink::WebBluetoothLeScanFilterPtr& canonicalized_filter,
ExceptionState& exception_state) {
if (!(filter->hasServices() || filter->hasName() || filter->hasNamePrefix() ||
filter->hasManufacturerData())) {
exception_state.ThrowTypeError(
"A filter must restrict the devices in some way.");
return;
}
if (filter->hasServices()) {
if (filter->services().size() == 0) {
exception_state.ThrowTypeError(
"'services', if present, must contain at least one service.");
return;
}
canonicalized_filter->services.emplace();
for (const V8UnionStringOrUnsignedLong* service : filter->services()) {
const String& validated_service =
BluetoothUUID::getService(service, exception_state);
if (exception_state.HadException())
return;
canonicalized_filter->services->push_back(validated_service);
}
}
if (filter->hasName()) {
size_t name_length = filter->name().Utf8().length();
if (name_length > kMaxDeviceNameLength) {
exception_state.ThrowTypeError(kDeviceNameTooLong);
return;
}
canonicalized_filter->name = filter->name();
}
if (filter->hasNamePrefix()) {
size_t name_prefix_length = filter->namePrefix().Utf8().length();
if (name_prefix_length > kMaxDeviceNameLength) {
exception_state.ThrowTypeError(kDeviceNameTooLong);
return;
}
if (filter->namePrefix().length() == 0) {
exception_state.ThrowTypeError(
"'namePrefix', if present, must be non-empty.");
return;
}
canonicalized_filter->name_prefix = filter->namePrefix();
}
if (filter->hasManufacturerData()) {
if (filter->manufacturerData().size() == 0) {
exception_state.ThrowTypeError(
"'manufacturerData', if present, must be non-empty.");
return;
}
canonicalized_filter->manufacturer_data.emplace();
for (const auto& manufacturer_data : filter->manufacturerData()) {
DOMArrayPiece mask_buffer = manufacturer_data->hasMask()
? DOMArrayPiece(manufacturer_data->mask())
: DOMArrayPiece();
DOMArrayPiece data_prefix_buffer =
manufacturer_data->hasDataPrefix()
? DOMArrayPiece(manufacturer_data->dataPrefix())
: DOMArrayPiece();
if (manufacturer_data->hasMask()) {
if (mask_buffer.IsDetached()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"'mask' value buffer has been detached.");
return;
}
if (!manufacturer_data->hasDataPrefix()) {
exception_state.ThrowTypeError(
"'dataPrefix' must be non-empty when 'mask' is present.");
return;
}
if (data_prefix_buffer.ByteLength() != mask_buffer.ByteLength()) {
exception_state.ThrowTypeError(
"'mask' size must be equal to 'dataPrefix' size.");
return;
}
}
Vector<mojom::blink::WebBluetoothDataFilterPtr> data_filters_vector;
if (manufacturer_data->hasDataPrefix()) {
if (data_prefix_buffer.IsDetached()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"'dataPrefix' value buffer has been detached.");
return;
}
if (data_prefix_buffer.ByteLength() == 0) {
exception_state.ThrowTypeError(
"'dataPrefix', if present, must be non-empty.");
return;
}
// Iterate by index here since we're iterating through two arrays.
for (wtf_size_t i = 0; i < data_prefix_buffer.ByteLength(); ++i) {
uint8_t data = data_prefix_buffer.Bytes()[i];
uint8_t mask =
manufacturer_data->hasMask() ? mask_buffer.Bytes()[i] : 0xff;
data_filters_vector.push_back(
mojom::blink::WebBluetoothDataFilter::New(data, mask));
}
}
auto company = mojom::blink::WebBluetoothCompany::New();
company->id = manufacturer_data->companyIdentifier();
auto result = canonicalized_filter->manufacturer_data->insert(
std::move(company), std::move(data_filters_vector));
if (!result.is_new_entry) {
exception_state.ThrowTypeError("'companyIdentifier' must be unique.");
return;
}
}
}
}
void ConvertRequestDeviceOptions(
const RequestDeviceOptions* options,
mojom::blink::WebBluetoothRequestDeviceOptionsPtr& result,
ExecutionContext* execution_context,
ExceptionState& exception_state) {
if (!(options->hasFilters() ^ options->acceptAllDevices())) {
exception_state.ThrowTypeError(
"Either 'filters' should be present or 'acceptAllDevices' should be "
"true, but not both.");
return;
}
result->accept_all_devices = options->acceptAllDevices();
if (options->hasFilters()) {
if (options->filters().IsEmpty()) {
exception_state.ThrowTypeError(
"'filters' member must be non-empty to find any devices.");
return;
}
result->filters.emplace();
for (const BluetoothLEScanFilterInit* filter : options->filters()) {
auto canonicalized_filter = mojom::blink::WebBluetoothLeScanFilter::New();
CanonicalizeFilter(filter, canonicalized_filter, exception_state);
if (exception_state.HadException())
return;
if (canonicalized_filter->manufacturer_data) {
UseCounter::Count(execution_context,
WebFeature::kWebBluetoothManufacturerDataFilter);
}
result->filters->push_back(std::move(canonicalized_filter));
}
}
if (options->hasOptionalServices()) {
for (const V8UnionStringOrUnsignedLong* optional_service :
options->optionalServices()) {
const String& validated_optional_service =
BluetoothUUID::getService(optional_service, exception_state);
if (exception_state.HadException())
return;
result->optional_services.push_back(validated_optional_service);
}
}
if (options->hasOptionalManufacturerData()) {
for (const uint16_t manufacturer_code :
options->optionalManufacturerData()) {
result->optional_manufacturer_data.push_back(manufacturer_code);
}
}
}
} // namespace
ScriptPromise Bluetooth::getAvailability(ScriptState* script_state,
ExceptionState& exception_state) {
LocalDOMWindow* window = GetSupplementable()->DomWindow();
if (IsRequestDenied(window, exception_state)) {
return ScriptPromise();
}
CHECK(window->IsSecureContext());
EnsureServiceConnection(window);
// Subsequent steps are handled in the browser process.
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
service_->GetAvailability(
WTF::Bind([](ScriptPromiseResolver* resolver,
bool result) { resolver->Resolve(result); },
WrapPersistent(resolver)));
return promise;
}
void Bluetooth::GetDevicesCallback(
ScriptPromiseResolver* resolver,
Vector<mojom::blink::WebBluetoothDevicePtr> devices) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed()) {
return;
}
HeapVector<Member<BluetoothDevice>> bluetooth_devices;
for (auto& device : devices) {
BluetoothDevice* bluetooth_device = GetBluetoothDeviceRepresentingDevice(
std::move(device), resolver->GetExecutionContext());
bluetooth_devices.push_back(*bluetooth_device);
}
resolver->Resolve(bluetooth_devices);
}
void Bluetooth::RequestDeviceCallback(
ScriptPromiseResolver* resolver,
mojom::blink::WebBluetoothResult result,
mojom::blink::WebBluetoothDevicePtr device) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed()) {
return;
}
if (result == mojom::blink::WebBluetoothResult::SUCCESS) {
BluetoothDevice* bluetooth_device = GetBluetoothDeviceRepresentingDevice(
std::move(device), resolver->GetExecutionContext());
resolver->Resolve(bluetooth_device);
} else {
resolver->Reject(BluetoothError::CreateDOMException(result));
}
}
ScriptPromise Bluetooth::getDevices(ScriptState* script_state,
ExceptionState& exception_state) {
LocalDOMWindow* window = GetSupplementable()->DomWindow();
if (IsRequestDenied(window, exception_state)) {
return ScriptPromise();
}
AddUnsupportedPlatformConsoleMessage(window);
CHECK(window->IsSecureContext());
EnsureServiceConnection(window);
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
service_->GetDevices(WTF::Bind(&Bluetooth::GetDevicesCallback,
WrapPersistent(this),
WrapPersistent(resolver)));
return promise;
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
ScriptPromise Bluetooth::requestDevice(ScriptState* script_state,
const RequestDeviceOptions* options,
ExceptionState& exception_state) {
LocalDOMWindow* window = GetSupplementable()->DomWindow();
if (IsRequestDenied(window, exception_state)) {
return ScriptPromise();
}
AddUnsupportedPlatformConsoleMessage(window);
CHECK(window->IsSecureContext());
// If the algorithm is not allowed to show a popup, reject promise with a
// SecurityError and abort these steps.
auto* frame = window->GetFrame();
DCHECK(frame);
if (!LocalFrame::HasTransientUserActivation(frame)) {
exception_state.ThrowSecurityError(kHandleGestureForPermissionRequest);
return ScriptPromise();
}
EnsureServiceConnection(window);
// In order to convert the arguments from service names and aliases to just
// UUIDs, do the following substeps:
auto device_options = mojom::blink::WebBluetoothRequestDeviceOptions::New();
ConvertRequestDeviceOptions(options, device_options, GetExecutionContext(),
exception_state);
if (exception_state.HadException())
return ScriptPromise();
// Subsequent steps are handled in the browser process.
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
service_->RequestDevice(
std::move(device_options),
WTF::Bind(&Bluetooth::RequestDeviceCallback, WrapPersistent(this),
WrapPersistent(resolver)));
return promise;
}
static void ConvertRequestLEScanOptions(
const BluetoothLEScanOptions* options,
mojom::blink::WebBluetoothRequestLEScanOptionsPtr& result,
ExceptionState& exception_state) {
if (!(options->hasFilters() ^ options->acceptAllAdvertisements())) {
exception_state.ThrowTypeError(
"Either 'filters' should be present or 'acceptAllAdvertisements' "
"should be true, but not both.");
return;
}
result->accept_all_advertisements = options->acceptAllAdvertisements();
result->keep_repeated_devices = options->keepRepeatedDevices();
if (options->hasFilters()) {
if (options->filters().IsEmpty()) {
exception_state.ThrowTypeError(
"'filters' member must be non-empty to find any devices.");
return;
}
result->filters.emplace();
for (const BluetoothLEScanFilterInit* filter : options->filters()) {
auto canonicalized_filter = mojom::blink::WebBluetoothLeScanFilter::New();
CanonicalizeFilter(filter, canonicalized_filter, exception_state);
if (exception_state.HadException())
return;
result->filters->push_back(std::move(canonicalized_filter));
}
}
}
void Bluetooth::RequestScanningCallback(
ScriptPromiseResolver* resolver,
mojo::ReceiverId id,
mojom::blink::WebBluetoothRequestLEScanOptionsPtr options,
mojom::blink::WebBluetoothResult result) {
if (!resolver->GetExecutionContext() ||
resolver->GetExecutionContext()->IsContextDestroyed()) {
return;
}
if (result != mojom::blink::WebBluetoothResult::SUCCESS) {
resolver->Reject(BluetoothError::CreateDOMException(result));
return;
}
auto* scan =
MakeGarbageCollected<BluetoothLEScan>(id, this, std::move(options));
resolver->Resolve(scan);
}
// https://webbluetoothcg.github.io/web-bluetooth/scanning.html#dom-bluetooth-requestlescan
ScriptPromise Bluetooth::requestLEScan(ScriptState* script_state,
const BluetoothLEScanOptions* options,
ExceptionState& exception_state) {
LocalDOMWindow* window = GetSupplementable()->DomWindow();
if (IsRequestDenied(window, exception_state)) {
return ScriptPromise();
}
// Remind developers when they are using Web Bluetooth on unsupported
// platforms.
window->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kInfo,
"Web Bluetooth Scanning is experimental on this platform. See "
"https://github.com/WebBluetoothCG/web-bluetooth/blob/main/"
"implementation-status.md"));
CHECK(window->IsSecureContext());
// If the algorithm is not allowed to show a popup, reject promise with a
// SecurityError and abort these steps.
auto* frame = window->GetFrame();
// If Navigator::DomWindow() returned a non-null |window|, GetFrame() should
// be valid.
DCHECK(frame);
if (!LocalFrame::HasTransientUserActivation(frame)) {
exception_state.ThrowSecurityError(kHandleGestureForPermissionRequest);
return ScriptPromise();
}
EnsureServiceConnection(window);
auto scan_options = mojom::blink::WebBluetoothRequestLEScanOptions::New();
ConvertRequestLEScanOptions(options, scan_options, exception_state);
if (exception_state.HadException())
return ScriptPromise();
// Subsequent steps are handled in the browser process.
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
mojo::PendingAssociatedRemote<mojom::blink::WebBluetoothAdvertisementClient>
client;
// See https://bit.ly/2S0zRAS for task types.
mojo::ReceiverId id =
client_receivers_.Add(client.InitWithNewEndpointAndPassReceiver(),
window->GetTaskRunner(TaskType::kMiscPlatformAPI));
auto scan_options_copy = scan_options->Clone();
service_->RequestScanningStart(
std::move(client), std::move(scan_options),
WTF::Bind(&Bluetooth::RequestScanningCallback, WrapPersistent(this),
WrapPersistent(resolver), id, std::move(scan_options_copy)));
return promise;
}
void Bluetooth::AdvertisingEvent(
mojom::blink::WebBluetoothAdvertisingEventPtr advertising_event) {
auto* event = MakeGarbageCollected<BluetoothAdvertisingEvent>(
event_type_names::kAdvertisementreceived,
GetBluetoothDeviceRepresentingDevice(std::move(advertising_event->device),
GetSupplementable()->DomWindow()),
std::move(advertising_event));
DispatchEvent(*event);
}
void Bluetooth::PageVisibilityChanged() {
client_receivers_.Clear();
}
void Bluetooth::CancelScan(mojo::ReceiverId id) {
client_receivers_.Remove(id);
}
bool Bluetooth::IsScanActive(mojo::ReceiverId id) const {
return client_receivers_.HasReceiver(id);
}
const WTF::AtomicString& Bluetooth::InterfaceName() const {
return event_type_names::kAdvertisementreceived;
}
ExecutionContext* Bluetooth::GetExecutionContext() const {
return GetSupplementable()->DomWindow();
}
void Bluetooth::Trace(Visitor* visitor) const {
visitor->Trace(device_instance_map_);
visitor->Trace(client_receivers_);
visitor->Trace(service_);
EventTargetWithInlineData::Trace(visitor);
Supplement<Navigator>::Trace(visitor);
PageVisibilityObserver::Trace(visitor);
}
// static
const char Bluetooth::kSupplementName[] = "Bluetooth";
Bluetooth* Bluetooth::bluetooth(Navigator& navigator) {
if (!navigator.DomWindow())
return nullptr;
Bluetooth* supplement = Supplement<Navigator>::From<Bluetooth>(navigator);
if (!supplement) {
supplement = MakeGarbageCollected<Bluetooth>(navigator);
ProvideTo(navigator, supplement);
}
return supplement;
}
Bluetooth::Bluetooth(Navigator& navigator)
: Supplement<Navigator>(navigator),
PageVisibilityObserver(navigator.DomWindow()->GetFrame()->GetPage()),
client_receivers_(this, navigator.DomWindow()),
service_(navigator.DomWindow()) {}
Bluetooth::~Bluetooth() = default;
BluetoothDevice* Bluetooth::GetBluetoothDeviceRepresentingDevice(
mojom::blink::WebBluetoothDevicePtr device_ptr,
ExecutionContext* context) {
// TODO(crbug.com/1275634): convert device_instance_map_ to use
// WebBluetoothDeviceId as key
auto it =
device_instance_map_.find(device_ptr->id.DeviceIdInBase64().c_str());
if (it != device_instance_map_.end()) {
return it->value;
}
BluetoothDevice* device = MakeGarbageCollected<BluetoothDevice>(
context, std::move(device_ptr), this);
auto result = device_instance_map_.insert(
device->GetDevice()->id.DeviceIdInBase64().c_str(), device);
DCHECK(result.is_new_entry);
return device;
}
void Bluetooth::EnsureServiceConnection(ExecutionContext* context) {
if (!service_.is_bound()) {
// See https://bit.ly/2S0zRAS for task types.
auto task_runner = context->GetTaskRunner(TaskType::kMiscPlatformAPI);
context->GetBrowserInterfaceBroker().GetInterface(
service_.BindNewPipeAndPassReceiver(task_runner));
}
}
} // namespace blink
| 8,259 |
399 | <reponame>pbaiz/openrec
from __future__ import print_function
import numpy as np
import random
from multiprocessing import Process
from openrec.tf1.legacy.utils.samplers import Sampler
class _PairwiseSampler(Process):
def __init__(self, dataset, batch_size, q, chronological):
self._dataset = dataset
self._batch_size = batch_size
self._q = q
self._state = 0
self._chronological = chronological
if not chronological:
self._dataset.shuffle()
super(_PairwiseSampler, self).__init__()
def run(self):
while True:
input_npy = np.zeros(self._batch_size, dtype=[('user_id_input', np.int32),
('p_item_id_input', np.int32),
('n_item_id_input', np.int32)])
if self._state + self._batch_size >= len(self._dataset.data):
if not self._chronological:
self._state = 0
self._dataset.shuffle()
else:
break
for sample_itr, entry in enumerate(self._dataset.data[self._state:(self._state + self._batch_size)]):
neg_id = int(random.random() * (self._dataset.max_item() - 1))
while neg_id in self._dataset.get_interactions_by_user_gb_item(entry['user_id']):
neg_id = int(random.random() * (self._dataset.max_item() - 1))
input_npy[sample_itr] = (entry['user_id'], entry['item_id'], neg_id)
self._state += self._batch_size
self._q.put(input_npy, block=True)
class PairwiseSampler(Sampler):
def __init__(self, dataset, batch_size, chronological=False, num_process=5, seed=0):
self._chronological = chronological
if chronological:
num_process = 1
random.seed(seed)
super(PairwiseSampler, self).__init__(dataset=dataset, batch_size=batch_size, num_process=num_process)
def _get_runner(self):
return _PairwiseSampler(dataset=self._dataset,
batch_size=self._batch_size,
q=self._q, chronological=self._chronological)
| 1,142 |
335 | {
"word": "Colloquialism",
"definitions": [
"A word or phrase that is not formal or literary and is used in ordinary or familiar conversation.",
"The use of colloquialisms."
],
"parts-of-speech": "Noun"
} | 91 |
370 | #define DINT
#include <../Source/umfpack_report_perm.c>
| 22 |
2,529 | <reponame>sakibguy/httpd<filename>modules/md/md_store.h
/* 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.
*/
#ifndef mod_md_md_store_h
#define mod_md_md_store_h
struct apr_array_header_t;
struct md_cert_t;
struct md_pkey_t;
struct md_pkey_spec_t;
const char *md_store_group_name(unsigned int group);
typedef struct md_store_t md_store_t;
/**
* A store for domain related data.
*
* The Key for a piece of data is the set of 3 items
* <group> + <domain> + <aspect>
*
* Examples:
* "domains" + "greenbytes.de" + "pubcert.pem"
* "ocsp" + "greenbytes.de" + "ocsp-XXXXX.json"
*
* Storage groups are pre-defined, domain and aspect names can be freely chosen.
*
* Groups reflect use cases and come with security restrictions. The groups
* DOMAINS, ARCHIVE and NONE are only accessible during the startup
* phase of httpd.
*
* Private key are stored unencrypted only in restricted groups. Meaning that certificate
* keys in group DOMAINS are not encrypted, but only readable at httpd start/reload.
* Keys in unrestricted groups are encrypted using a pass phrase generated once and stored
* in NONE.
*/
/** Value types handled by a store */
typedef enum {
MD_SV_TEXT, /* plain text, value is (char*) */
MD_SV_JSON, /* JSON serialization, value is (md_json_t*) */
MD_SV_CERT, /* PEM x509 certificate, value is (md_cert_t*) */
MD_SV_PKEY, /* PEM private key, value is (md_pkey_t*) */
MD_SV_CHAIN, /* list of PEM x509 certificates, value is
(apr_array_header_t*) of (md_cert*) */
} md_store_vtype_t;
/** Store storage groups */
typedef enum {
MD_SG_NONE, /* top level of store, name MUST be NULL in calls */
MD_SG_ACCOUNTS, /* ACME accounts */
MD_SG_CHALLENGES, /* challenge response data for a domain */
MD_SG_DOMAINS, /* live certificates and settings for a domain */
MD_SG_STAGING, /* staged set of certificate and settings, maybe incomplete */
MD_SG_ARCHIVE, /* Archived live sets of a domain */
MD_SG_TMP, /* temporary domain storage */
MD_SG_OCSP, /* OCSP stapling related domain data */
MD_SG_COUNT, /* number of storage groups, used in setups */
} md_store_group_t;
#define MD_FN_MD "md.json"
#define MD_FN_JOB "job.json"
#define MD_FN_HTTPD_JSON "httpd.json"
/* The corresponding names for current cert & key files are constructed
* in md_store and md_crypt.
*/
/* These three legacy filenames are only used in md_store_fs to
* upgrade 1.0 directories. They should not be used for any other
* purpose.
*/
#define MD_FN_PRIVKEY "privkey.pem"
#define MD_FN_PUBCERT "pubcert.pem"
#define MD_FN_CERT "cert.pem"
/**
* Load the JSON value at key "group/name/aspect", allocated from pool p.
* @return APR_ENOENT if there is no such value
*/
apr_status_t md_store_load_json(md_store_t *store, md_store_group_t group,
const char *name, const char *aspect,
struct md_json_t **pdata, apr_pool_t *p);
/**
* Save the JSON value at key "group/name/aspect". If create != 0, fail if there
* already is a value for this key.
*/
apr_status_t md_store_save_json(md_store_t *store, apr_pool_t *p, md_store_group_t group,
const char *name, const char *aspect,
struct md_json_t *data, int create);
/**
* Load the value of type at key "group/name/aspect", allocated from pool p. Usually, the
* type is expected to be the same as used in saving the value. Some conversions will work,
* others will fail the format.
* @return APR_ENOENT if there is no such value
*/
apr_status_t md_store_load(md_store_t *store, md_store_group_t group,
const char *name, const char *aspect,
md_store_vtype_t vtype, void **pdata,
apr_pool_t *p);
/**
* Save the JSON value at key "group/name/aspect". If create != 0, fail if there
* already is a value for this key. The provided data MUST be of the correct type.
*/
apr_status_t md_store_save(md_store_t *store, apr_pool_t *p, md_store_group_t group,
const char *name, const char *aspect,
md_store_vtype_t vtype, void *data,
int create);
/**
* Remove the value stored at key "group/name/aspect". Unless force != 0, a missing
* value will cause the call to fail with APR_ENOENT.
*/
apr_status_t md_store_remove(md_store_t *store, md_store_group_t group,
const char *name, const char *aspect,
apr_pool_t *p, int force);
/**
* Remove everything matching key "group/name".
*/
apr_status_t md_store_purge(md_store_t *store, apr_pool_t *p,
md_store_group_t group, const char *name);
/**
* Remove all items matching the name/aspect patterns that have not been
* modified since the given timestamp.
*/
apr_status_t md_store_remove_not_modified_since(md_store_t *store, apr_pool_t *p,
apr_time_t modified,
md_store_group_t group,
const char *name,
const char *aspect);
/**
* inspect callback function. Invoked for each matched value. Values allocated from
* ptemp may disappear any time after the call returned. If this function returns
* 0, the iteration is aborted.
*/
typedef int md_store_inspect(void *baton, const char *name, const char *aspect,
md_store_vtype_t vtype, void *value, apr_pool_t *ptemp);
/**
* Iterator over all existing values matching the name pattern. Patterns are evaluated
* using apr_fnmatch() without flags.
*/
apr_status_t md_store_iter(md_store_inspect *inspect, void *baton, md_store_t *store,
apr_pool_t *p, md_store_group_t group, const char *pattern,
const char *aspect, md_store_vtype_t vtype);
/**
* Move everything matching key "from/name" from one group to another. If archive != 0,
* move any existing "to/name" into a new "archive/new_name" location.
*/
apr_status_t md_store_move(md_store_t *store, apr_pool_t *p,
md_store_group_t from, md_store_group_t to,
const char *name, int archive);
/**
* Rename a group member.
*/
apr_status_t md_store_rename(md_store_t *store, apr_pool_t *p,
md_store_group_t group, const char *name, const char *to);
/**
* Get the filename of an item stored in "group/name/aspect". The item does
* not have to exist.
*/
apr_status_t md_store_get_fname(const char **pfname,
md_store_t *store, md_store_group_t group,
const char *name, const char *aspect,
apr_pool_t *p);
/**
* Make a compare on the modification time of "group1/name/aspect" vs. "group2/name/aspect".
*/
int md_store_is_newer(md_store_t *store, md_store_group_t group1, md_store_group_t group2,
const char *name, const char *aspect, apr_pool_t *p);
/**
* Iterate over all names that exist in a group, e.g. there are items matching
* "group/pattern". The inspect function is called with the name and NULL aspect
* and value.
*/
apr_status_t md_store_iter_names(md_store_inspect *inspect, void *baton, md_store_t *store,
apr_pool_t *p, md_store_group_t group, const char *pattern);
/**
* Get the modification time of the item store under "group/name/aspect".
* @return modification time or 0 if the item does not exist.
*/
apr_time_t md_store_get_modified(md_store_t *store, md_store_group_t group,
const char *name, const char *aspect, apr_pool_t *p);
/**************************************************************************************************/
/* Storage handling utils */
apr_status_t md_load(md_store_t *store, md_store_group_t group,
const char *name, md_t **pmd, apr_pool_t *p);
apr_status_t md_save(struct md_store_t *store, apr_pool_t *p, md_store_group_t group,
md_t *md, int create);
apr_status_t md_remove(md_store_t *store, apr_pool_t *p, md_store_group_t group,
const char *name, int force);
int md_is_newer(md_store_t *store, md_store_group_t group1, md_store_group_t group2,
const char *name, apr_pool_t *p);
typedef int md_store_md_inspect(void *baton, md_store_t *store, md_t *md, apr_pool_t *ptemp);
apr_status_t md_store_md_iter(md_store_md_inspect *inspect, void *baton, md_store_t *store,
apr_pool_t *p, md_store_group_t group, const char *pattern);
const char *md_pkey_filename(struct md_pkey_spec_t *spec, apr_pool_t *p);
const char *md_chain_filename(struct md_pkey_spec_t *spec, apr_pool_t *p);
apr_status_t md_pkey_load(md_store_t *store, md_store_group_t group,
const char *name, struct md_pkey_spec_t *spec,
struct md_pkey_t **ppkey, apr_pool_t *p);
apr_status_t md_pkey_save(md_store_t *store, apr_pool_t *p, md_store_group_t group,
const char *name, struct md_pkey_spec_t *spec,
struct md_pkey_t *pkey, int create);
apr_status_t md_pubcert_load(md_store_t *store, md_store_group_t group, const char *name,
struct md_pkey_spec_t *spec, struct apr_array_header_t **ppubcert,
apr_pool_t *p);
apr_status_t md_pubcert_save(md_store_t *store, apr_pool_t *p,
md_store_group_t group, const char *name,
struct md_pkey_spec_t *spec,
struct apr_array_header_t *pubcert, int create);
/**************************************************************************************************/
/* X509 complete credentials */
typedef struct md_credentials_t md_credentials_t;
struct md_credentials_t {
struct md_pkey_spec_t *spec;
struct md_pkey_t *pkey;
struct apr_array_header_t *chain;
};
apr_status_t md_creds_load(md_store_t *store, md_store_group_t group, const char *name,
struct md_pkey_spec_t *spec, md_credentials_t **pcreds, apr_pool_t *p);
apr_status_t md_creds_save(md_store_t *store, apr_pool_t *p, md_store_group_t group,
const char *name, md_credentials_t *creds, int create);
/**************************************************************************************************/
/* implementation interface */
typedef apr_status_t md_store_load_cb(md_store_t *store, md_store_group_t group,
const char *name, const char *aspect,
md_store_vtype_t vtype, void **pvalue,
apr_pool_t *p);
typedef apr_status_t md_store_save_cb(md_store_t *store, apr_pool_t *p, md_store_group_t group,
const char *name, const char *aspect,
md_store_vtype_t vtype, void *value,
int create);
typedef apr_status_t md_store_remove_cb(md_store_t *store, md_store_group_t group,
const char *name, const char *aspect,
apr_pool_t *p, int force);
typedef apr_status_t md_store_purge_cb(md_store_t *store, apr_pool_t *p, md_store_group_t group,
const char *name);
typedef apr_status_t md_store_iter_cb(md_store_inspect *inspect, void *baton, md_store_t *store,
apr_pool_t *p, md_store_group_t group, const char *pattern,
const char *aspect, md_store_vtype_t vtype);
typedef apr_status_t md_store_names_iter_cb(md_store_inspect *inspect, void *baton, md_store_t *store,
apr_pool_t *p, md_store_group_t group, const char *pattern);
typedef apr_status_t md_store_move_cb(md_store_t *store, apr_pool_t *p, md_store_group_t from,
md_store_group_t to, const char *name, int archive);
typedef apr_status_t md_store_rename_cb(md_store_t *store, apr_pool_t *p, md_store_group_t group,
const char *from, const char *to);
typedef apr_status_t md_store_get_fname_cb(const char **pfname,
md_store_t *store, md_store_group_t group,
const char *name, const char *aspect,
apr_pool_t *p);
typedef int md_store_is_newer_cb(md_store_t *store,
md_store_group_t group1, md_store_group_t group2,
const char *name, const char *aspect, apr_pool_t *p);
typedef apr_time_t md_store_get_modified_cb(md_store_t *store, md_store_group_t group,
const char *name, const char *aspect, apr_pool_t *p);
typedef apr_status_t md_store_remove_nms_cb(md_store_t *store, apr_pool_t *p,
apr_time_t modified, md_store_group_t group,
const char *name, const char *aspect);
struct md_store_t {
md_store_save_cb *save;
md_store_load_cb *load;
md_store_remove_cb *remove;
md_store_move_cb *move;
md_store_rename_cb *rename;
md_store_iter_cb *iterate;
md_store_names_iter_cb *iterate_names;
md_store_purge_cb *purge;
md_store_get_fname_cb *get_fname;
md_store_is_newer_cb *is_newer;
md_store_get_modified_cb *get_modified;
md_store_remove_nms_cb *remove_nms;
};
#endif /* mod_md_md_store_h */
| 6,870 |
446 | {
"recommendations": [
"dbaeumer.vscode-eslint",
"eamodio.gitlens",
"mgmcdermott.vscode-language-babel",
"wix.vscode-import-cost",
"pflannery.vscode-versionlens",
"prisma.prisma",
"apollographql.vscode-apollo"
],
"unwantedRecommendations": []
}
| 138 |
14,668 | <gh_stars>1000+
# Copyright 2021 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.
"""Updates the DebugScenario enums in histograms with values read from the
corresponding header file.
If the file was pretty-printed, the updated version is pretty-printed too.
"""
from __future__ import print_function
import os
import sys
from update_histogram_enum import UpdateHistogramEnum
if __name__ == '__main__':
if len(sys.argv) > 1:
print('No arguments expected!', file=sys.stderr)
sys.stderr.write(__doc__)
sys.exit(1)
UpdateHistogramEnum(histogram_enum_name='DebugScenario',
source_enum_path='content/common/debug_utils.h',
start_marker='^enum class ?DebugScenario {',
end_marker='^kMaxValue',
calling_script=os.path.basename(__file__))
| 359 |
332 | // Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.queries.messages;
import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.GroupActor;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.objects.messages.responses.GetByConversationMessageIdResponse;
import com.vk.api.sdk.objects.users.Fields;
import java.util.Arrays;
import java.util.List;
/**
* Query for Messages.getByConversationMessageId method
*/
public class MessagesGetByConversationMessageIdQuery extends AbstractQueryBuilder<MessagesGetByConversationMessageIdQuery, GetByConversationMessageIdResponse> {
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
* @param peerId value of "peer id" parameter.
* @param conversationMessageIds value of "conversation message ids" parameter.
*/
public MessagesGetByConversationMessageIdQuery(VkApiClient client, UserActor actor, int peerId,
Integer... conversationMessageIds) {
super(client, "messages.getByConversationMessageId", GetByConversationMessageIdResponse.class);
accessToken(actor.getAccessToken());
peerId(peerId);
conversationMessageIds(conversationMessageIds);
}
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
* @param peerId value of "peer id" parameter.
* @param conversationMessageIds value of "conversation message ids" parameter.
*/
public MessagesGetByConversationMessageIdQuery(VkApiClient client, UserActor actor, int peerId,
List<Integer> conversationMessageIds) {
super(client, "messages.getByConversationMessageId", GetByConversationMessageIdResponse.class);
accessToken(actor.getAccessToken());
peerId(peerId);
conversationMessageIds(conversationMessageIds);
}
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
* @param peerId value of "peer id" parameter.
* @param conversationMessageIds value of "conversation message ids" parameter.
*/
public MessagesGetByConversationMessageIdQuery(VkApiClient client, GroupActor actor, int peerId,
Integer... conversationMessageIds) {
super(client, "messages.getByConversationMessageId", GetByConversationMessageIdResponse.class);
accessToken(actor.getAccessToken());
groupId(actor.getGroupId());
peerId(peerId);
conversationMessageIds(conversationMessageIds);
}
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
* @param peerId value of "peer id" parameter.
* @param conversationMessageIds value of "conversation message ids" parameter.
*/
public MessagesGetByConversationMessageIdQuery(VkApiClient client, GroupActor actor, int peerId,
List<Integer> conversationMessageIds) {
super(client, "messages.getByConversationMessageId", GetByConversationMessageIdResponse.class);
accessToken(actor.getAccessToken());
groupId(actor.getGroupId());
peerId(peerId);
conversationMessageIds(conversationMessageIds);
}
/**
* Destination ID. "For user: 'User ID', e.g. '12345'. For chat: '2000000000' + 'chat_id', e.g. '2000000001'. For community: '- community ID', e.g. '-12345'. "
*
* @param value value of "peer id" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
protected MessagesGetByConversationMessageIdQuery peerId(int value) {
return unsafeParam("peer_id", value);
}
/**
* Information whether the response should be extended
*
* @param value value of "extended" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public MessagesGetByConversationMessageIdQuery extended(Boolean value) {
return unsafeParam("extended", value);
}
/**
* Group ID (for group messages with group access token)
*
* @param value value of "group id" parameter. Minimum is 0.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public MessagesGetByConversationMessageIdQuery groupId(Integer value) {
return unsafeParam("group_id", value);
}
/**
* conversation_message_ids
* Conversation message IDs.
*
* @param value value of "conversation message ids" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
protected MessagesGetByConversationMessageIdQuery conversationMessageIds(Integer... value) {
return unsafeParam("conversation_message_ids", value);
}
/**
* Conversation message IDs.
*
* @param value value of "conversation message ids" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
protected MessagesGetByConversationMessageIdQuery conversationMessageIds(List<Integer> value) {
return unsafeParam("conversation_message_ids", value);
}
/**
* fields
* Profile fields to return.
*
* @param value value of "fields" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public MessagesGetByConversationMessageIdQuery fields(Fields... value) {
return unsafeParam("fields", value);
}
/**
* Profile fields to return.
*
* @param value value of "fields" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public MessagesGetByConversationMessageIdQuery fields(List<Fields> value) {
return unsafeParam("fields", value);
}
@Override
protected MessagesGetByConversationMessageIdQuery getThis() {
return this;
}
@Override
protected List<String> essentialKeys() {
return Arrays.asList("peer_id", "conversation_message_ids", "access_token");
}
}
| 2,296 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.