max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
3,682 | # structure/files.py
def unique_path(directory, name_pattern):
"""Find a path name that does not already exist"""
counter = 0
while True:
counter += 1
path = directory / name_pattern.format(counter)
if not path.exists():
return path
def add_empty_file(path):
"""Create an empty file at the given path"""
print(f"Create file: {path}")
path.parent.mkdir(parents=True, exist_ok=True)
path.touch()
| 178 |
1,062 | <filename>java/test/java/com/google/mr4c/sources/ArchiveDatasetSourceTest.java
/**
* Copyright 2014 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.
*/
package com.google.mr4c.sources;
import com.google.mr4c.config.ConfigDescriptor;
import com.google.mr4c.content.ContentFactories;
import com.google.mr4c.dataset.DataFile;
import com.google.mr4c.dataset.Dataset;
import com.google.mr4c.keys.DataKey;
import com.google.mr4c.keys.DataKeyDimension;
import com.google.mr4c.keys.DataKeyElement;
import com.google.mr4c.keys.DataKeyFactory;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import org.junit.*;
import static org.junit.Assert.*;
public class ArchiveDatasetSourceTest {
private URI m_configNoSelfURI;
private URI m_configSelfURI;
private URI m_inputDir;
private URI m_outputDir;
private FileSource m_inputFileSrc;
private FilesDatasetSourceConfig m_configSelf;
private FilesDatasetSourceConfig m_configNoSelf;
private DatasetSource m_inputSrc;
@Before public void setUp() throws Exception {
m_configNoSelfURI = new URI("input/data/dataset/test1/source.json");
m_configSelfURI = new URI("input/data/dataset/test1/source_self.json");
m_inputDir = new URI("input/data/dataset/test1/input_data");
m_outputDir = new URI("output/data/dataset/archive");
m_inputFileSrc = FileSources.getFileSource(m_inputDir);
m_configNoSelf = FilesDatasetSourceConfig.load(new ConfigDescriptor(m_configNoSelfURI));
m_configSelf = FilesDatasetSourceConfig.load(new ConfigDescriptor(m_configSelfURI));
m_inputSrc = new FilesDatasetSource(m_configNoSelf, m_inputFileSrc);
}
@Test public void testRoundTrip() throws Exception {
doTest(m_configNoSelf, 1);
doTest(m_configSelf, 2);
doTestFail(null, 3);
}
@Test public void testFindFile() throws Exception {
DataKey key = buildKey("1","2455874.21556848", "MS");
DataFile file = m_inputSrc.findDataFile(key);
byte[] bytes = file.getBytes();
assertEquals("Check size of a file", 518371, bytes.length);
}
@Test public void testFindFileNotFound() throws Exception {
DataKey key = buildKey("1","blah_blah", "MS");
assertNull(m_inputSrc.findDataFile(key));
}
private DataKey buildKey(String sensor, String frame, String type) {
DataKeyDimension sensorDim = new DataKeyDimension("sensor");
DataKeyDimension frameDim = new DataKeyDimension("frame");
DataKeyDimension typeDim = new DataKeyDimension("type");
return DataKeyFactory.newKey(
new DataKeyElement(sensor, sensorDim),
new DataKeyElement(frame, frameDim),
new DataKeyElement(type, typeDim)
);
}
private void doTestFail(
FilesDatasetSourceConfig outputConfig,
int testNumber
) throws IOException {
try {
doTest(
outputConfig,
testNumber
);
} catch (IllegalStateException ise) {
return; // its what we wanted
}
fail("Didn't get IllegalStateException");
}
private void doTest(
FilesDatasetSourceConfig outputConfig,
int testNumber
) throws IOException {
URI outputDir = URI.create("output/data/dataset/archive/case"+testNumber);
ArchiveSource outputFileSrc = new MapFileSource(ContentFactories.toPath(outputDir));
outputFileSrc.clear();
DatasetSource outputSrc = new ArchiveDatasetSource(outputConfig, outputFileSrc);
SourceTestUtils.testSource(m_inputSrc, outputSrc);
}
}
| 1,332 |
2,424 | <filename>python/phonenumbers/shortdata/region_MY.py
"""Auto-generated file, do not edit by hand. MY metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_MY = PhoneMetadata(id='MY', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[1369]\\d{2,4}', possible_length=(3, 4, 5)),
toll_free=PhoneNumberDesc(national_number_pattern='112|999', example_number='112', possible_length=(3,)),
emergency=PhoneNumberDesc(national_number_pattern='112|999', example_number='112', possible_length=(3,)),
short_code=PhoneNumberDesc(national_number_pattern='1(?:0[01348]|1(?:[02]|1[128]|311)|2(?:0[125]|[13-6]|2\\d{0,2})|(?:3[1-35-79]|7[45])\\d\\d?|5(?:454|5\\d\\d?|77|888|999?)|8(?:18?|2|8[18])|9(?:[124]\\d?|68|71|9[0679]))|66628|99[1-469]|13[5-7]|(?:1(?:0[569]|309|5[12]|7[136-9]|9[03])|3[23679]\\d\\d)\\d', example_number='100', possible_length=(3, 4, 5)),
standard_rate=PhoneNumberDesc(national_number_pattern='666\\d\\d', example_number='66600', possible_length=(5,)),
sms_services=PhoneNumberDesc(national_number_pattern='(?:3[23679]\\d|666)\\d\\d', example_number='32000', possible_length=(5,)),
short_data=True)
| 503 |
307 | <filename>riptable/tests/test_conversion_utils.py
import unittest
import numpy
from riptable import Dataset, Categorical
from riptable.rt_datetime import DateTimeNano
from riptable.Utils.conversion_utils import (
dataset_as_matrix,
numpy2d_to_dict,
dset_dict_to_list,
append_dataset_dict,
possibly_convert_to_nanotime,
numpy_array_to_dict,
)
class Conversion_Utility_Test(unittest.TestCase):
def test_as_matrix(self):
error_tol = 0.00001
ds = Dataset({'A': [1.2, 3.1, 9.6], 'B': [-1.6, 2.7, 4.6]})
X, _ = dataset_as_matrix(ds)
self.assertIsInstance(X, numpy.ndarray)
self.assertEqual(X.shape[0], ds.shape[0])
self.assertEqual(X.shape[1], ds.shape[1]) # we may break this later
self.assertTrue((numpy.abs(ds.A._np - X[:, 0]) < error_tol).all())
self.assertTrue((numpy.abs(ds.B._np - X[:, 1]) < error_tol).all())
def test_as_matrix_metadata(self):
error_tol = 0.00001
ds = Dataset(
{
'A': ['EXCH1', 'EXCH2', 'EXCH1', 'EXCH3', 'EXCH3'],
'B': [-1.6, 2.7, 4.6, 5.7, 8.9],
'C': Categorical([0, 0, 1, 0, 2], ['CPTYA', 'CPTYB', 'CPTYC']),
}
)
X, X_data = dataset_as_matrix(ds)
self.assertIsInstance(X, numpy.ndarray)
self.assertEqual(X.shape[0], ds.shape[0])
self.assertEqual(X.shape[1], ds.shape[1]) # we may break this later
self.assertEqual(X_data['A']['dtype'], ds.A.dtype)
self.assertEqual(X_data['B']['dtype'], ds.B.dtype)
self.assertEqual(X_data['C']['dtype'], ds.C.dtype)
self.assertEqual(X_data['A']['is_categorical'], False)
self.assertEqual(X_data['B']['is_categorical'], False)
self.assertEqual(X_data['C']['is_categorical'], True)
self.assertTrue(
(numpy.abs(X[:, 0] - numpy.array([0., 1., 0., 2., 2.])) < error_tol).all(),
msg=f"got {X[:, 0]}"
)
self.assertTrue(
(numpy.abs(X[:, 2] - numpy.array([0, 0, 1, 0, 2])) < error_tol).all(),
msg=f"got {X[:, 2]}"
)
self.assertTrue(
(X_data['A']['category_values'][numpy.array([0, 1, 0, 2, 2])] == ds.A).all(),
msg=f"X_data {X_data['A']['category_values'][numpy.array([0, 1, 0, 2, 2])]}\nds.A {ds.A}"
)
def test_as_matrix_int(self):
error_tol = 0.00001
ds = Dataset(
{
_k: list(range(_i * 10, (_i + 1) * 10))
for _i, _k in enumerate('ABCDEFGHIJKLMNOP')
}
)
X, _ = dataset_as_matrix(ds)
self.assertIsInstance(X, numpy.ndarray)
self.assertEqual(X.shape[0], ds.shape[0])
self.assertEqual(X.shape[1], ds.shape[1]) # we may break this later
self.assertTrue((numpy.abs(ds.A._np - X[:, 0]) < error_tol).all())
self.assertTrue((numpy.abs(ds.B._np - X[:, 1]) < error_tol).all())
def test_numpy_array_to_dict(self):
arr = numpy.arange(12).reshape((3, 4)).transpose()
cols = ['A', 'C', 'B']
dd = numpy_array_to_dict(arr, cols)
self.assertEqual(list(dd), cols)
self.assertTrue((dd['A'] == numpy.arange(0, 4)).all())
self.assertTrue((dd['C'] == numpy.arange(4, 8)).all())
self.assertTrue((dd['B'] == numpy.arange(8, 12)).all())
arr = numpy.array(
[(1.0, 'Q'), (-3.0, 'Z')], dtype=[('x', numpy.float64), ('y', 'S1')]
)
dd = numpy_array_to_dict(arr)
self.assertEqual(list(dd), ['x', 'y'])
self.assertTrue(
(dd['x'] == numpy.array([1.0, -3.0], dtype=numpy.float64)).all()
)
self.assertTrue((dd['y'] == numpy.array(['Q', 'Z'], dtype='S1')).all())
# TODO: Remove this? -CLH
def test_numpy2d_to_dict(self):
arr = numpy.arange(12).reshape((3, 4)).transpose()
cols = ['A', 'C', 'B']
dd = numpy2d_to_dict(arr, cols)
self.assertEqual(list(dd), cols)
self.assertTrue((dd['A'] == numpy.arange(0, 4)).all())
self.assertTrue((dd['C'] == numpy.arange(4, 8)).all())
self.assertTrue((dd['B'] == numpy.arange(8, 12)).all())
def test_dset_dict_to_list(self):
ds = Dataset(
{
_k: list(range(_i * 10, (_i + 1) * 10))
for _i, _k in enumerate('abcdefghijklmnop')
}
)
ds0 = ds[:3].copy()
ds1 = ds[6:9].copy()
ds2 = ds[11:15].copy()
dd = {'one': ds0, 'two': ds1, 'μεαν': ds2}
with self.assertRaises(ValueError):
_ = dset_dict_to_list(dd, 'keyfield')
dd = {'one': ds0, 'two': ds1, 3: ds2}
with self.assertRaises(ValueError):
_ = dset_dict_to_list(dd, 'keyfield')
dd = {'one': ds0, 'two': ds1, 'three': ds2}
with self.assertRaises(ValueError):
_ = dset_dict_to_list(dd, 'a')
lst1 = dset_dict_to_list(dd, 'keyfield')
self.assertEqual(id(ds0), id(lst1[0]))
self.assertEqual(id(ds1), id(lst1[1]))
self.assertEqual(id(ds2), id(lst1[2]))
self.assertEqual(list(ds0.keys()), ['a', 'b', 'c', 'keyfield'])
self.assertTrue((ds0.a == list(range(10))).all())
self.assertTrue((ds0.keyfield == 'one').all())
lst2 = dset_dict_to_list(dd, 'a', allow_overwrite=True)
self.assertEqual(id(ds0), id(lst1[0]))
self.assertEqual(list(ds0.keys()), ['a', 'b', 'c', 'keyfield'])
self.assertTrue((ds0.a == 'one').all())
self.assertTrue((ds0.b == list(range(10, 20))).all())
self.assertTrue((ds0.keyfield == 'one').all())
def test_append_dataset_dict(self):
ds = Dataset(
{
_k: list(range(_i * 10, (_i + 1) * 10))
for _i, _k in enumerate('abcdefghijklmnop')
}
)
ds0 = ds[:3].copy()
ds1 = ds[6:9].copy()
ds2 = ds[11:15].copy()
dd = {'one': ds0, 'two': ds1, 'three': ds2}
ds = append_dataset_dict(dd, 'keyfield')
ucols = set()
for _d in dd.values():
ucols.update(_d)
self.assertEqual(set(ds.keys()), ucols)
self.assertEqual(ds.get_nrows(), sum(_d.get_nrows() for _d in dd.values()))
keyfield = []
for _d in dd.values():
keyfield.extend(_d.keyfield)
self.assertTrue((ds.keyfield == keyfield).all())
self.assertTrue((ds.a[:10] == range(10)).all())
self.assertTrue((ds.g[10:20] == range(60, 70)).all())
self.assertTrue((ds.l[20:30] == range(110, 120)).all())
def test_possibly_convert_to_nanotime(self):
ns1 = numpy.int64(1528295695919153408)
arr1 = numpy.array([ns1 + 12 * _i for _i in range(25)])
nt1, okay1 = possibly_convert_to_nanotime(arr1)
self.assertTrue(okay1)
self.assertIsInstance(nt1, DateTimeNano)
arr2 = arr1.astype(numpy.uint64)
nt2, okay2 = possibly_convert_to_nanotime(arr2)
self.assertFalse(okay2)
self.assertNotIsInstance(nt2, DateTimeNano)
self.assertTrue((nt2 == arr2).all())
ns3 = numpy.int64(1070376029353467904)
arr3 = numpy.array([ns3 + 12 * _i for _i in range(25)])
nt3, okay3 = possibly_convert_to_nanotime(arr3)
self.assertFalse(okay3)
self.assertNotIsInstance(nt3, DateTimeNano)
self.assertTrue((nt3 == arr3).all())
if __name__ == "__main__":
tester = unittest.main()
| 4,188 |
877 | <gh_stars>100-1000
import java.util.List;
import org.checkerframework.checker.nullness.qual.*;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.checkerframework.framework.qual.TypeUseLocation;
public class MethodTypeVars4 {
@DefaultQualifier(value = NonNull.class, locations = TypeUseLocation.IMPLICIT_UPPER_BOUND)
interface I {
<T> T doit();
<T> List<T> doit2();
<T extends @Nullable Object> T doit3();
}
void f1(I i) {
// s is implicitly Nullable
String s = i.doit();
List<String> ls = i.doit2();
String s2 = i.doit3();
}
void f2(I i) {
@NonNull String s = i.doit();
s = i.doit3();
// :: error: (type.argument)
List<@Nullable String> ls = i.doit2();
}
}
| 296 |
1,626 | [{"name": "subject_id", "type": "INT64", "mode": "REQUIRED"}, {"name": "hadm_id", "type": "INT64", "mode": "REQUIRED"}, {"name": "pharmacy_id", "type": "INT64", "mode": "REQUIRED"}, {"name": "starttime", "type": "DATETIME", "mode": "NULLABLE"}, {"name": "stoptime", "type": "DATETIME", "mode": "NULLABLE"}, {"name": "drug_type", "type": "STRING", "mode": "REQUIRED"}, {"name": "drug", "type": "STRING", "mode": "REQUIRED"}, {"name": "gsn", "type": "STRING", "mode": "NULLABLE"}, {"name": "ndc", "type": "STRING", "mode": "NULLABLE"}, {"name": "prod_strength", "type": "STRING", "mode": "NULLABLE"}, {"name": "form_rx", "type": "STRING", "mode": "NULLABLE"}, {"name": "dose_val_rx", "type": "STRING", "mode": "NULLABLE"}, {"name": "dose_unit_rx", "type": "STRING", "mode": "NULLABLE"}, {"name": "form_val_disp", "type": "STRING", "mode": "NULLABLE"}, {"name": "form_unit_disp", "type": "STRING", "mode": "NULLABLE"}, {"name": "doses_per_24_hrs", "type": "FLOAT64", "mode": "NULLABLE"}, {"name": "route", "type": "STRING", "mode": "NULLABLE"}] | 399 |
1,428 | /*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.extent.clipboard.io.share;
import com.sk89q.worldedit.WorldEdit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
public class ClipboardShareDestinations {
private static final Map<String, ClipboardShareDestination> aliasMap = new HashMap<>();
private static final List<ClipboardShareDestination> registeredDestinations = new ArrayList<>();
public static void registerClipboardShareDestination(ClipboardShareDestination destination) {
checkNotNull(destination);
checkState(destination.supportsFormat(destination.getDefaultFormat()), "Destination must accept its default format");
for (String key : destination.getAliases()) {
String lowKey = key.toLowerCase(Locale.ROOT);
ClipboardShareDestination old = aliasMap.put(lowKey, destination);
if (old != null) {
aliasMap.put(lowKey, old);
WorldEdit.logger.warn(destination.getClass().getName() + " cannot override existing alias '" + lowKey + "' used by " + old.getClass().getName());
}
}
registeredDestinations.add(destination);
}
static {
for (BuiltInClipboardShareDestinations destination : BuiltInClipboardShareDestinations.values()) {
registerClipboardShareDestination(destination);
}
}
/**
* Find the clipboard format named by the given alias.
*
* @param alias the alias
* @return the format, otherwise null if none is matched
*/
@Nullable
public static ClipboardShareDestination findByAlias(String alias) {
checkNotNull(alias);
return aliasMap.get(alias.toLowerCase(Locale.ROOT).trim());
}
public static Collection<ClipboardShareDestination> getAll() {
return Collections.unmodifiableCollection(registeredDestinations);
}
private ClipboardShareDestinations() {
}
}
| 990 |
581 | <reponame>janniclas/phasar<gh_stars>100-1000
[[clang::annotate("psr.source")]] static int bar(int A, int *B) {
*B = 13;
if (A == 42) {
return 13;
}
return A;
}
namespace {
void foo([[clang::annotate("psr.source")]] int &A) { A = 13; }
} // anonymous namespace
int main() {
int A = 42;
int B = 0;
int C = bar(A, &B);
foo(C);
return C;
}
| 162 |
14,886 | <filename>tools/pnnx/src/pass_level2/F_hardswish.cpp<gh_stars>1000+
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "pass_level2.h"
namespace pnnx {
class F_hardswish : public GraphRewriterPass
{
public:
const char* match_pattern_graph() const
{
return R"PNNXIR(7767517
3 2
pnnx.Input input 0 1 input
aten::hardswish op_0 1 1 input out
pnnx.Output output 1 0 out
)PNNXIR";
}
const char* type_str() const
{
return "F.hardswish";
}
};
REGISTER_GLOBAL_PNNX_GRAPH_REWRITER_PASS(F_hardswish, 10)
class F_hardswish_1 : public GraphRewriterPass
{
public:
const char* match_pattern_graph() const
{
return R"PNNXIR(7767517
11 10
pnnx.Input input 0 1 input
prim::Constant op_0 0 1 392 value=3
prim::Constant op_1 0 1 393 value=1
aten::add op_2 3 1 input 392 393 a
prim::Constant op_3 0 1 394 value=0.000000e+00
prim::Constant op_4 0 1 395 value=6.000000e+00
aten::hardtanh_ op_5 3 1 a 394 395 b
aten::mul op_6 2 1 input b c
prim::Constant op_7 0 1 391 value=6
aten::div op_8 2 1 c 391 out
pnnx.Output output 1 0 out
)PNNXIR";
}
const char* type_str() const
{
return "F.hardswish";
}
};
REGISTER_GLOBAL_PNNX_GRAPH_REWRITER_PASS(F_hardswish_1, 8)
class F_hardswish_2 : public GraphRewriterPass
{
public:
const char* match_pattern_graph() const
{
return R"PNNXIR(7767517
4 3
pnnx.Input input 0 1 input
aten::hardsigmoid op_0 1 1 input a
aten::mul op_1 2 1 input a out
pnnx.Output output 1 0 out
)PNNXIR";
}
const char* type_str() const
{
return "F.hardswish";
}
};
REGISTER_GLOBAL_PNNX_GRAPH_REWRITER_PASS(F_hardswish_2, 9)
class F_hardswish_3 : public GraphRewriterPass
{
public:
const char* match_pattern_graph() const
{
return R"PNNXIR(7767517
11 10
pnnx.Input input 0 1 input
prim::Constant op_0 0 1 12 value=3
prim::Constant op_1 0 1 13 value=1
aten::add op_2 3 1 input 12 13 a
prim::Constant op_3 0 1 17 value=0.000000e+00
prim::Constant op_4 0 1 18 value=6.000000e+00
aten::hardtanh op_5 3 1 a 17 18 b
aten::mul op_6 2 1 input b c
prim::Constant op_7 0 1 22 value=6.000000e+00
aten::div op_8 2 1 c 22 out
pnnx.Output output 1 0 out
)PNNXIR";
}
const char* type_str() const
{
return "F.hardswish";
}
};
REGISTER_GLOBAL_PNNX_GRAPH_REWRITER_PASS(F_hardswish_3, 8)
class F_hardswish_4 : public GraphRewriterPass
{
public:
const char* match_pattern_graph() const
{
return R"PNNXIR(7767517
11 10
pnnx.Input input 0 1 input
prim::Constant op_0 0 1 25 value=3.000000e+00
prim::Constant op_1 0 1 47 value=1
aten::add op_2 3 1 input 25 47 a
prim::Constant op_3 0 1 48 value=0.000000e+00
prim::Constant op_4 0 1 49 value=6.000000e+00
aten::hardtanh_ op_5 3 1 a 48 49 b
prim::Constant op_6 0 1 50 value=6.000000e+00
aten::div op_7 2 1 b 50 c
aten::mul op_8 2 1 c input out
pnnx.Output output 1 0 out
)PNNXIR";
}
const char* type_str() const
{
return "F.hardswish";
}
};
REGISTER_GLOBAL_PNNX_GRAPH_REWRITER_PASS(F_hardswish_4, 8)
class F_hardswish_5 : public GraphRewriterPass
{
public:
const char* match_pattern_graph() const
{
return R"PNNXIR(7767517
9 8
pnnx.Input input 0 1 input
prim::Constant op_0 0 1 25 value=3.000000e+00
prim::Constant op_1 0 1 48 value=1
aten::add op_2 3 1 input 25 48 a
aten::relu6_ op_3 1 1 a b
prim::Constant op_4 0 1 49 value=6.000000e+00
aten::div op_5 2 1 b 49 c
aten::mul op_6 2 1 c input out
pnnx.Output output 1 0 out
)PNNXIR";
}
const char* type_str() const
{
return "F.hardswish";
}
};
REGISTER_GLOBAL_PNNX_GRAPH_REWRITER_PASS(F_hardswish_5, 8)
} // namespace pnnx
| 2,687 |
12,824 | <reponame>tanishiking/dotty
package test;
import java.rmi.RemoteException;
import test.Map;
@SuppressWarnings("unchecked")
public class Test implements Map<String, String> {
public Map.MapTo plus(String o) {
return null;
}
public int $tag() throws RemoteException {
return 0;
}
}
| 104 |
603 | import numpy as np
import pytest
import matplotlib.pyplot as plt
from matplotlib.spines import Spines
from matplotlib.testing.decorators import check_figures_equal, image_comparison
def test_spine_class():
"""Test Spines and SpinesProxy in isolation."""
class SpineMock:
def __init__(self):
self.val = None
def set_val(self, val):
self.val = val
spines_dict = {
'left': SpineMock(),
'right': SpineMock(),
'top': SpineMock(),
'bottom': SpineMock(),
}
spines = Spines(**spines_dict)
assert spines['left'] is spines_dict['left']
assert spines.left is spines_dict['left']
spines[['left', 'right']].set_val('x')
assert spines.left.val == 'x'
assert spines.right.val == 'x'
assert spines.top.val is None
assert spines.bottom.val is None
spines[:].set_val('y')
assert all(spine.val == 'y' for spine in spines.values())
with pytest.raises(KeyError, match='foo'):
spines['foo']
with pytest.raises(KeyError, match='foo, bar'):
spines[['left', 'foo', 'right', 'bar']]
with pytest.raises(ValueError, match='single list'):
spines['left', 'right']
with pytest.raises(ValueError, match='Spines does not support slicing'):
spines['left':'right']
with pytest.raises(ValueError, match='Spines does not support slicing'):
spines['top':]
@image_comparison(['spines_axes_positions'])
def test_spines_axes_positions():
# SF bug 2852168
fig = plt.figure()
x = np.linspace(0, 2*np.pi, 100)
y = 2*np.sin(x)
ax = fig.add_subplot(1, 1, 1)
ax.set_title('centered spines')
ax.plot(x, y)
ax.spines.right.set_position(('axes', 0.1))
ax.yaxis.set_ticks_position('right')
ax.spines.top.set_position(('axes', 0.25))
ax.xaxis.set_ticks_position('top')
ax.spines.left.set_color('none')
ax.spines.bottom.set_color('none')
@image_comparison(['spines_data_positions'])
def test_spines_data_positions():
fig, ax = plt.subplots()
ax.spines.left.set_position(('data', -1.5))
ax.spines.top.set_position(('data', 0.5))
ax.spines.right.set_position(('data', -0.5))
ax.spines.bottom.set_position('zero')
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
@check_figures_equal(extensions=["png"])
def test_spine_nonlinear_data_positions(fig_test, fig_ref):
plt.style.use("default")
ax = fig_test.add_subplot()
ax.set(xscale="log", xlim=(.1, 1))
# Use position="data" to visually swap the left and right spines, using
# linewidth to distinguish them. The calls to tick_params removes labels
# (for image comparison purposes) and harmonizes tick positions with the
# reference).
ax.spines.left.set_position(("data", 1))
ax.spines.left.set_linewidth(2)
ax.spines.right.set_position(("data", .1))
ax.tick_params(axis="y", labelleft=False, direction="in")
ax = fig_ref.add_subplot()
ax.set(xscale="log", xlim=(.1, 1))
ax.spines.right.set_linewidth(2)
ax.tick_params(axis="y", labelleft=False, left=False, right=True)
@image_comparison(['spines_capstyle'])
def test_spines_capstyle():
# issue 2542
plt.rc('axes', linewidth=20)
fig, ax = plt.subplots()
ax.set_xticks([])
ax.set_yticks([])
def test_label_without_ticks():
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.3, bottom=0.3)
ax.plot(np.arange(10))
ax.yaxis.set_ticks_position('left')
ax.spines.left.set_position(('outward', 30))
ax.spines.right.set_visible(False)
ax.set_ylabel('y label')
ax.xaxis.set_ticks_position('bottom')
ax.spines.bottom.set_position(('outward', 30))
ax.spines.top.set_visible(False)
ax.set_xlabel('x label')
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
plt.draw()
spine = ax.spines.left
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
assert ax.yaxis.label.get_position()[0] < spinebbox.xmin, \
"Y-Axis label not left of the spine"
spine = ax.spines.bottom
spinebbox = spine.get_transform().transform_path(
spine.get_path()).get_extents()
assert ax.xaxis.label.get_position()[1] < spinebbox.ymin, \
"X-Axis label not below the spine"
| 1,861 |
26,932 | <filename>external/source/exploits/CVE-2017-13861/liboffsetfinder64/all_img4tool.h
//
// all.h
// img4tool
//
// Created by tihmstar on 15.06.16.
// Copyright © 2016 tihmstar. All rights reserved.
//
#ifndef all_h
#define all_h
#define error(a ...) printf("[Error] %s: ",__func__),printf(a)
#define warning(a ...) printf("[Warning] %s: ",__func__),printf(a)
#ifdef DEBUG //this is for developing with Xcode
#define IMG4TOOL_VERSION_COMMIT_COUNT "Debug"
#define IMG4TOOL_VERSION_COMMIT_SHA "Build: " __DATE__ " " __TIME__
#define HAVE_LIBCOMPRESSION
#else
//#include <config.h>
#define IMG4TOOL_NOLZFSE
#define IMG4TOOL_NOOPENSSL
#endif
#endif /* all_h */
| 269 |
1,440 | <reponame>Venus9023/django_for_beginer
from datetime import date, timedelta
from django.test import TestCase
from members.models import (
GOLD_MEMBERSHIP, PLATINUM_MEMBERSHIP, SILVER_MEMBERSHIP, CorporateMember,
IndividualMember, Team,
)
class IndividualMemberTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.member = IndividualMember.objects.create(
name='DjangoDeveloper',
email='<EMAIL>'
)
def setUp(self):
self.member.refresh_from_db()
def test_str(self):
self.assertEqual(str(self.member), 'DjangoDeveloper')
def test_member_since_should_have_default(self):
self.assertEqual(IndividualMember().member_since, date.today())
def test_is_active(self):
self.assertTrue(self.member.is_active)
self.member.member_until = date.today()
self.assertFalse(self.member.is_active)
class CorporateMemberTests(TestCase):
today = date.today()
tomorrow = today + timedelta(days=1)
@classmethod
def setUpTestData(cls):
cls.member = CorporateMember.objects.create(
display_name='Corporation',
billing_name='foo',
billing_email='<EMAIL>',
contact_email='<EMAIL>',
membership_level=SILVER_MEMBERSHIP,
)
def setUp(self):
self.member.refresh_from_db()
def test_str(self):
self.assertEqual(str(self.member), 'Corporation')
def test_is_invoiced(self):
# No invoices == not invoiced.
self.assertEqual(self.member.is_invoiced, False)
# Invoice but no sent_date == not invoiced.
invoice = self.member.invoice_set.create(amount=500)
self.assertEqual(self.member.is_invoiced, False)
# Invoice with an sent_date == invoiced.
invoice.sent_date = self.today
invoice.save()
self.assertEqual(self.member.is_invoiced, True)
def test_is_paid(self):
# No invoices == not paid.
self.assertEqual(self.member.is_paid, False)
# Invoice but no paid_date == not paid.
invoice = self.member.invoice_set.create(amount=500)
self.assertEqual(self.member.is_paid, False)
# Invoice with a paid_date == paid.
invoice.paid_date = self.today
invoice.save()
self.assertEqual(self.member.is_paid, True)
def test_get_expiry_date(self):
self.assertIsNone(self.member.get_expiry_date())
self.member.invoice_set.create(amount=500)
self.assertIsNone(self.member.get_expiry_date())
self.member.invoice_set.create(amount=500, expiration_date=self.today)
self.assertEqual(self.member.get_expiry_date(), self.today)
self.member.invoice_set.create(amount=500, expiration_date=self.tomorrow)
self.assertEqual(self.member.get_expiry_date(), self.tomorrow)
def test_manager_by_membership_level(self):
self.assertEqual(CorporateMember.objects.by_membership_level(), {})
self.member.invoice_set.create(amount=500, expiration_date=self.tomorrow)
self.assertEqual(CorporateMember.objects.by_membership_level(), {'silver': [self.member]})
self.member.membership_level = GOLD_MEMBERSHIP
self.member.save()
self.assertEqual(CorporateMember.objects.by_membership_level(), {'gold': [self.member]})
self.member.membership_level = PLATINUM_MEMBERSHIP
self.member.save()
self.assertEqual(CorporateMember.objects.by_membership_level(), {'platinum': [self.member]})
class TeamTests(TestCase):
def test_str(self):
self.assertEqual(str(Team(name='Ops')), 'Ops')
| 1,573 |
334 | <filename>AMudanca.java<gh_stars>100-1000
// A Mudança
/*
vide arquivo em assets mudanca.png
Hermione está criando um novo Vira Tempo especialmente para programadores. É
impressionante as vantagens que ele oferece e o conforto pra codar que ele tem.
O artefato ainda está em desenvolvimento e ele prometeu consertar os bugs e
colocar uns apetrechos melhores e, em troca, pediu um sistema simples para o
modo Standy Bay. O problema é que o artefato por si só sempre tem o ângulo de
inclinação do Sol/Lua (de 0 a 360). Valendo um Vira Tempo, caso deseja aceitar:
dada em grau da inclinação do Sol/Lua, informe em qual período do dia ele se
encontra.
• Entrada
A entrada contém um número inteiro M (0 ≤ M ≤ 360) representando o grau do
Sol/Lua. Como a posição muda constantemente seu programa receberá diversos
casos a cada segundo (EOF).
• Saída
Imprima uma saudação referente ao período do dia que ele se encontra: "Boa
Tarde!!", "Boa Noite!!", "Bom Dia!!" e "De Madrugada!!".
*/
import java.io.IOException;
import java.util.Scanner;
public class AMudanca {
public static void main(String[] args) throws IOException {
Scanner leitor = new Scanner(System.in);
String msg;
while (leitor.hasNext()) {
int graus = leitor.nextInt();
if (graus == 360 || graus >= 0 && graus < 90) msg = "Bom Dia!!";
else if (graus >= 90 && graus < 180) msg = "Boa Tarde!!";
else if (graus >= 180 && graus < 270) msg = "Boa Noite!!";
else msg = "De Madrugada!!";
System.out.println(msg);
}
leitor.close();
}
} | 625 |
1,470 | <filename>android/src/main/java/com/pichillilorenzo/flutter_inappwebview/content_blocker/ContentBlockerActionType.java
package com.pichillilorenzo.flutter_inappwebview.content_blocker;
public enum ContentBlockerActionType {
BLOCK ("block"),
CSS_DISPLAY_NONE ("css-display-none"),
MAKE_HTTPS ("make-https");
private final String value;
private ContentBlockerActionType(String value) {
this.value = value;
}
public boolean equalsValue(String otherValue) {
return value.equals(otherValue);
}
public static ContentBlockerActionType fromValue(String value) {
for( ContentBlockerActionType type : ContentBlockerActionType.values()) {
if(value.equals(type.value))
return type;
}
throw new IllegalArgumentException("No enum constant: " + value);
}
@Override
public String toString() {
return this.value;
}
}
| 353 |
18,396 | <gh_stars>1000+
//
// Copyright (c) 2013-2021 Winlin
//
// SPDX-License-Identifier: MIT
//
#ifndef SRS_APP_SOURCE_HPP
#define SRS_APP_SOURCE_HPP
#include <srs_core.hpp>
#include <map>
#include <vector>
#include <string>
#include <srs_app_st.hpp>
#include <srs_app_reload.hpp>
#include <srs_core_performance.hpp>
#include <srs_service_st.hpp>
#include <srs_app_hourglass.hpp>
class SrsFormat;
class SrsRtmpFormat;
class SrsLiveConsumer;
class SrsPlayEdge;
class SrsPublishEdge;
class SrsLiveSource;
class SrsCommonMessage;
class SrsOnMetaDataPacket;
class SrsSharedPtrMessage;
class SrsForwarder;
class SrsRequest;
class SrsStSocket;
class SrsRtmpServer;
class SrsEdgeProxyContext;
class SrsMessageArray;
class SrsNgExec;
class SrsMessageHeader;
class SrsHls;
class SrsRtc;
class SrsDvr;
class SrsDash;
class SrsEncoder;
class SrsBuffer;
#ifdef SRS_HDS
class SrsHds;
#endif
// The time jitter algorithm:
// 1. full, to ensure stream start at zero, and ensure stream monotonically increasing.
// 2. zero, only ensure sttream start at zero, ignore timestamp jitter.
// 3. off, disable the time jitter algorithm, like atc.
enum SrsRtmpJitterAlgorithm
{
SrsRtmpJitterAlgorithmFULL = 0x01,
SrsRtmpJitterAlgorithmZERO,
SrsRtmpJitterAlgorithmOFF
};
int srs_time_jitter_string2int(std::string time_jitter);
// Time jitter detect and correct, to ensure the rtmp stream is monotonically.
class SrsRtmpJitter
{
private:
int64_t last_pkt_time;
int64_t last_pkt_correct_time;
public:
SrsRtmpJitter();
virtual ~SrsRtmpJitter();
public:
// detect the time jitter and correct it.
// @param ag the algorithm to use for time jitter.
virtual srs_error_t correct(SrsSharedPtrMessage* msg, SrsRtmpJitterAlgorithm ag);
// Get current client time, the last packet time.
virtual int64_t get_time();
};
#ifdef SRS_PERF_QUEUE_FAST_VECTOR
// To alloc and increase fixed space, fast remove and insert for msgs sender.
// @see https://github.com/ossrs/srs/issues/251
class SrsFastVector
{
private:
SrsSharedPtrMessage** msgs;
int nb_msgs;
int count;
public:
SrsFastVector();
virtual ~SrsFastVector();
public:
virtual int size();
virtual int begin();
virtual int end();
virtual SrsSharedPtrMessage** data();
virtual SrsSharedPtrMessage* at(int index);
virtual void clear();
virtual void erase(int _begin, int _end);
virtual void push_back(SrsSharedPtrMessage* msg);
virtual void free();
};
#endif
// The message queue for the consumer(client), forwarder.
// We limit the size in seconds, drop old messages(the whole gop) if full.
class SrsMessageQueue
{
private:
// The start and end time.
srs_utime_t av_start_time;
srs_utime_t av_end_time;
private:
// Whether do logging when shrinking.
bool _ignore_shrink;
// The max queue size, shrink if exceed it.
srs_utime_t max_queue_size;
#ifdef SRS_PERF_QUEUE_FAST_VECTOR
SrsFastVector msgs;
#else
std::vector<SrsSharedPtrMessage*> msgs;
#endif
public:
SrsMessageQueue(bool ignore_shrink = false);
virtual ~SrsMessageQueue();
public:
// Get the size of queue.
virtual int size();
// Get the duration of queue.
virtual srs_utime_t duration();
// Set the queue size
// @param queue_size the queue size in srs_utime_t.
virtual void set_queue_size(srs_utime_t queue_size);
public:
// Enqueue the message, the timestamp always monotonically.
// @param msg, the msg to enqueue, user never free it whatever the return code.
// @param is_overflow, whether overflow and shrinked. NULL to ignore.
virtual srs_error_t enqueue(SrsSharedPtrMessage* msg, bool* is_overflow = NULL);
// Get packets in consumer queue.
// @pmsgs SrsSharedPtrMessage*[], used to store the msgs, user must alloc it.
// @count the count in array, output param.
// @max_count the max count to dequeue, must be positive.
virtual srs_error_t dump_packets(int max_count, SrsSharedPtrMessage** pmsgs, int& count);
// Dumps packets to consumer, use specified args.
// @remark the atc/tba/tbv/ag are same to SrsLiveConsumer.enqueue().
virtual srs_error_t dump_packets(SrsLiveConsumer* consumer, bool atc, SrsRtmpJitterAlgorithm ag);
private:
// Remove a gop from the front.
// if no iframe found, clear it.
virtual void shrink();
public:
// clear all messages in queue.
virtual void clear();
};
// The wakable used for some object
// which is waiting on cond.
class ISrsWakable
{
public:
ISrsWakable();
virtual ~ISrsWakable();
public:
// when the consumer(for player) got msg from recv thread,
// it must be processed for maybe it's a close msg, so the cond
// wait must be wakeup.
virtual void wakeup() = 0;
};
// The consumer for SrsLiveSource, that is a play client.
class SrsLiveConsumer : public ISrsWakable
{
private:
SrsRtmpJitter* jitter;
SrsLiveSource* source;
SrsMessageQueue* queue;
bool paused;
// when source id changed, notice all consumers
bool should_update_source_id;
#ifdef SRS_PERF_QUEUE_COND_WAIT
// The cond wait for mw.
// @see https://github.com/ossrs/srs/issues/251
srs_cond_t mw_wait;
bool mw_waiting;
int mw_min_msgs;
srs_utime_t mw_duration;
#endif
public:
SrsLiveConsumer(SrsLiveSource* s);
virtual ~SrsLiveConsumer();
public:
// Set the size of queue.
virtual void set_queue_size(srs_utime_t queue_size);
// when source id changed, notice client to print.
virtual void update_source_id();
public:
// Get current client time, the last packet time.
virtual int64_t get_time();
// Enqueue an shared ptr message.
// @param shared_msg, directly ptr, copy it if need to save it.
// @param whether atc, donot use jitter correct if true.
// @param ag the algorithm of time jitter.
virtual srs_error_t enqueue(SrsSharedPtrMessage* shared_msg, bool atc, SrsRtmpJitterAlgorithm ag);
// Get packets in consumer queue.
// @param msgs the msgs array to dump packets to send.
// @param count the count in array, intput and output param.
// @remark user can specifies the count to get specified msgs; 0 to get all if possible.
virtual srs_error_t dump_packets(SrsMessageArray* msgs, int& count);
#ifdef SRS_PERF_QUEUE_COND_WAIT
// wait for messages incomming, atleast nb_msgs and in duration.
// @param nb_msgs the messages count to wait.
// @param msgs_duration the messages duration to wait.
virtual void wait(int nb_msgs, srs_utime_t msgs_duration);
#endif
// when client send the pause message.
virtual srs_error_t on_play_client_pause(bool is_pause);
// Interface ISrsWakable
public:
// when the consumer(for player) got msg from recv thread,
// it must be processed for maybe it's a close msg, so the cond
// wait must be wakeup.
virtual void wakeup();
};
// cache a gop of video/audio data,
// delivery at the connect of flash player,
// To enable it to fast startup.
class SrsGopCache
{
private:
// if disabled the gop cache,
// The client will wait for the next keyframe for h264,
// and will be black-screen.
bool enable_gop_cache;
// The video frame count, avoid cache for pure audio stream.
int cached_video_count;
// when user disabled video when publishing, and gop cache enalbed,
// We will cache the audio/video for we already got video, but we never
// know when to clear the gop cache, for there is no video in future,
// so we must guess whether user disabled the video.
// when we got some audios after laster video, for instance, 600 audio packets,
// about 3s(26ms per packet) 115 audio packets, clear gop cache.
//
// @remark, it is ok for performance, for when we clear the gop cache,
// gop cache is disabled for pure audio stream.
// @see: https://github.com/ossrs/srs/issues/124
int audio_after_last_video_count;
// cached gop.
std::vector<SrsSharedPtrMessage*> gop_cache;
public:
SrsGopCache();
virtual ~SrsGopCache();
public:
// cleanup when system quit.
virtual void dispose();
// To enable or disable the gop cache.
virtual void set(bool v);
virtual bool enabled();
// only for h264 codec
// 1. cache the gop when got h264 video packet.
// 2. clear gop when got keyframe.
// @param shared_msg, directly ptr, copy it if need to save it.
virtual srs_error_t cache(SrsSharedPtrMessage* shared_msg);
// clear the gop cache.
virtual void clear();
// dump the cached gop to consumer.
virtual srs_error_t dump(SrsLiveConsumer* consumer, bool atc, SrsRtmpJitterAlgorithm jitter_algorithm);
// used for atc to get the time of gop cache,
// The atc will adjust the sequence header timestamp to gop cache.
virtual bool empty();
// Get the start time of gop cache, in srs_utime_t.
// @return 0 if no packets.
virtual srs_utime_t start_time();
// whether current stream is pure audio,
// when no video in gop cache, the stream is pure audio right now.
virtual bool pure_audio();
};
// The handler to handle the event of srs source.
// For example, the http flv streaming module handle the event and
// mount http when rtmp start publishing.
class ISrsLiveSourceHandler
{
public:
ISrsLiveSourceHandler();
virtual ~ISrsLiveSourceHandler();
public:
// when stream start publish, mount stream.
virtual srs_error_t on_publish(SrsLiveSource* s, SrsRequest* r) = 0;
// when stream stop publish, unmount stream.
virtual void on_unpublish(SrsLiveSource* s, SrsRequest* r) = 0;
};
// The mix queue to correct the timestamp for mix_correct algorithm.
class SrsMixQueue
{
private:
uint32_t nb_videos;
uint32_t nb_audios;
std::multimap<int64_t, SrsSharedPtrMessage*> msgs;
public:
SrsMixQueue();
virtual ~SrsMixQueue();
public:
virtual void clear();
virtual void push(SrsSharedPtrMessage* msg);
virtual SrsSharedPtrMessage* pop();
};
// The hub for origin is a collection of utilities for origin only,
// For example, DVR, HLS, Forward and Transcode are only available for origin,
// they are meanless for edge server.
class SrsOriginHub : public ISrsReloadHandler
{
private:
SrsLiveSource* source;
SrsRequest* req;
bool is_active;
private:
// The format, codec information.
SrsRtmpFormat* format;
// hls handler.
SrsHls* hls;
// The DASH encoder.
SrsDash* dash;
// dvr handler.
SrsDvr* dvr;
// transcoding handler.
SrsEncoder* encoder;
#ifdef SRS_HDS
// adobe hds(http dynamic streaming).
SrsHds *hds;
#endif
// nginx-rtmp exec feature.
SrsNgExec* ng_exec;
// To forward stream to other servers
std::vector<SrsForwarder*> forwarders;
public:
SrsOriginHub();
virtual ~SrsOriginHub();
public:
// Initialize the hub with source and request.
// @param r The request object, managed by source.
virtual srs_error_t initialize(SrsLiveSource* s, SrsRequest* r);
// Dispose the hub, release utilities resource,
// For example, delete all HLS pieces.
virtual void dispose();
// Cycle the hub, process some regular events,
// For example, dispose hls in cycle.
virtual srs_error_t cycle();
// Whether the stream hub is active, or stream is publishing.
virtual bool active();
public:
// When got a parsed metadata.
virtual srs_error_t on_meta_data(SrsSharedPtrMessage* shared_metadata, SrsOnMetaDataPacket* packet);
// When got a parsed audio packet.
virtual srs_error_t on_audio(SrsSharedPtrMessage* shared_audio);
// When got a parsed video packet.
virtual srs_error_t on_video(SrsSharedPtrMessage* shared_video, bool is_sequence_header);
public:
// When start publish stream.
virtual srs_error_t on_publish();
// When stop publish stream.
virtual void on_unpublish();
// Internal callback.
public:
// For the SrsForwarder to callback to request the sequence headers.
virtual srs_error_t on_forwarder_start(SrsForwarder* forwarder);
// For the SrsDvr to callback to request the sequence headers.
virtual srs_error_t on_dvr_request_sh();
// Interface ISrsReloadHandler
public:
virtual srs_error_t on_reload_vhost_forward(std::string vhost);
virtual srs_error_t on_reload_vhost_dash(std::string vhost);
virtual srs_error_t on_reload_vhost_hls(std::string vhost);
virtual srs_error_t on_reload_vhost_hds(std::string vhost);
virtual srs_error_t on_reload_vhost_dvr(std::string vhost);
virtual srs_error_t on_reload_vhost_transcode(std::string vhost);
virtual srs_error_t on_reload_vhost_exec(std::string vhost);
private:
virtual srs_error_t create_forwarders();
virtual void destroy_forwarders();
};
// Each stream have optional meta(sps/pps in sequence header and metadata).
// This class cache and update the meta.
class SrsMetaCache
{
private:
// The cached metadata, FLV script data tag.
SrsSharedPtrMessage* meta;
// The cached video sequence header, for example, sps/pps for h.264.
SrsSharedPtrMessage* video;
SrsSharedPtrMessage* previous_video;
// The cached audio sequence header, for example, asc for aac.
SrsSharedPtrMessage* audio;
SrsSharedPtrMessage* previous_audio;
// The format for sequence header.
SrsRtmpFormat* vformat;
SrsRtmpFormat* aformat;
public:
SrsMetaCache();
virtual ~SrsMetaCache();
public:
// Dispose the metadata cache.
virtual void dispose();
// For each publishing, clear the metadata cache.
virtual void clear();
public:
// Get the cached metadata.
virtual SrsSharedPtrMessage* data();
// Get the cached vsh(video sequence header).
virtual SrsSharedPtrMessage* vsh();
virtual SrsFormat* vsh_format();
// Get the cached ash(audio sequence header).
virtual SrsSharedPtrMessage* ash();
virtual SrsFormat* ash_format();
// Dumps cached metadata to consumer.
// @param dm Whether dumps the metadata.
// @param ds Whether dumps the sequence header.
virtual srs_error_t dumps(SrsLiveConsumer* consumer, bool atc, SrsRtmpJitterAlgorithm ag, bool dm, bool ds);
public:
// Previous exists sequence header.
virtual SrsSharedPtrMessage* previous_vsh();
virtual SrsSharedPtrMessage* previous_ash();
// Update previous sequence header, drop old one, set to new sequence header.
virtual void update_previous_vsh();
virtual void update_previous_ash();
public:
// Update the cached metadata by packet.
virtual srs_error_t update_data(SrsMessageHeader* header, SrsOnMetaDataPacket* metadata, bool& updated);
// Update the cached audio sequence header.
virtual srs_error_t update_ash(SrsSharedPtrMessage* msg);
// Update the cached video sequence header.
virtual srs_error_t update_vsh(SrsSharedPtrMessage* msg);
};
// The source manager to create and refresh all stream sources.
class SrsLiveSourceManager : public ISrsHourGlass
{
private:
srs_mutex_t lock;
std::map<std::string, SrsLiveSource*> pool;
SrsHourGlass* timer_;
public:
SrsLiveSourceManager();
virtual ~SrsLiveSourceManager();
public:
virtual srs_error_t initialize();
// create source when fetch from cache failed.
// @param r the client request.
// @param h the event handler for source.
// @param pps the matched source, if success never be NULL.
virtual srs_error_t fetch_or_create(SrsRequest* r, ISrsLiveSourceHandler* h, SrsLiveSource** pps);
private:
// Get the exists source, NULL when not exists.
// update the request and return the exists source.
virtual SrsLiveSource* fetch(SrsRequest* r);
public:
// dispose and cycle all sources.
virtual void dispose();
// interface ISrsHourGlass
private:
virtual srs_error_t setup_ticks();
virtual srs_error_t notify(int event, srs_utime_t interval, srs_utime_t tick);
public:
// when system exit, destroy th`e sources,
// For gmc to analysis mem leaks.
virtual void destroy();
};
// Global singleton instance.
extern SrsLiveSourceManager* _srs_sources;
// For RTMP2RTC, bridge SrsLiveSource to SrsRtcSource
class ISrsLiveSourceBridger
{
public:
ISrsLiveSourceBridger();
virtual ~ISrsLiveSourceBridger();
public:
virtual srs_error_t on_publish() = 0;
virtual srs_error_t on_audio(SrsSharedPtrMessage* audio) = 0;
virtual srs_error_t on_video(SrsSharedPtrMessage* video) = 0;
virtual void on_unpublish() = 0;
};
// The live streaming source.
class SrsLiveSource : public ISrsReloadHandler
{
friend class SrsOriginHub;
private:
// For publish, it's the publish client id.
// For edge, it's the edge ingest id.
// when source id changed, for example, the edge reconnect,
// invoke the on_source_id_changed() to let all clients know.
SrsContextId _source_id;
// previous source id.
SrsContextId _pre_source_id;
// deep copy of client request.
SrsRequest* req;
// To delivery stream to clients.
std::vector<SrsLiveConsumer*> consumers;
// The time jitter algorithm for vhost.
SrsRtmpJitterAlgorithm jitter_algorithm;
// For play, whether use interlaced/mixed algorithm to correct timestamp.
bool mix_correct;
// The mix queue to implements the mix correct algorithm.
SrsMixQueue* mix_queue;
// For play, whether enabled atc.
// The atc(use absolute time and donot adjust time),
// directly use msg time and donot adjust if atc is true,
// otherwise, adjust msg time to start from 0 to make flash happy.
bool atc;
// whether stream is monotonically increase.
bool is_monotonically_increase;
// The time of the packet we just got.
int64_t last_packet_time;
// The event handler.
ISrsLiveSourceHandler* handler;
// The source bridger for other source.
ISrsLiveSourceBridger* bridger_;
// The edge control service
SrsPlayEdge* play_edge;
SrsPublishEdge* publish_edge;
// The gop cache for client fast startup.
SrsGopCache* gop_cache;
// The hub for origin server.
SrsOriginHub* hub;
// The metadata cache.
SrsMetaCache* meta;
private:
// Whether source is avaiable for publishing.
bool _can_publish;
// The last die time, when all consumers quit and no publisher,
// We will remove the source when source die.
srs_utime_t die_at;
public:
SrsLiveSource();
virtual ~SrsLiveSource();
public:
virtual void dispose();
virtual srs_error_t cycle();
// Remove source when expired.
virtual bool expired();
public:
// Initialize the hls with handlers.
virtual srs_error_t initialize(SrsRequest* r, ISrsLiveSourceHandler* h);
// Bridge to other source, forward packets to it.
void set_bridger(ISrsLiveSourceBridger* v);
// Interface ISrsReloadHandler
public:
virtual srs_error_t on_reload_vhost_play(std::string vhost);
public:
// The source id changed.
virtual srs_error_t on_source_id_changed(SrsContextId id);
// Get current source id.
virtual SrsContextId source_id();
virtual SrsContextId pre_source_id();
// Whether source is inactive, which means there is no publishing stream source.
// @remark For edge, it's inactive util stream has been pulled from origin.
virtual bool inactive();
// Update the authentication information in request.
virtual void update_auth(SrsRequest* r);
public:
virtual bool can_publish(bool is_edge);
virtual srs_error_t on_meta_data(SrsCommonMessage* msg, SrsOnMetaDataPacket* metadata);
public:
// TODO: FIXME: Use SrsSharedPtrMessage instead.
virtual srs_error_t on_audio(SrsCommonMessage* audio);
private:
virtual srs_error_t on_audio_imp(SrsSharedPtrMessage* audio);
public:
// TODO: FIXME: Use SrsSharedPtrMessage instead.
virtual srs_error_t on_video(SrsCommonMessage* video);
private:
virtual srs_error_t on_video_imp(SrsSharedPtrMessage* video);
public:
virtual srs_error_t on_aggregate(SrsCommonMessage* msg);
// Publish stream event notify.
// @param _req the request from client, the source will deep copy it,
// for when reload the request of client maybe invalid.
virtual srs_error_t on_publish();
virtual void on_unpublish();
public:
// Create consumer
// @param consumer, output the create consumer.
virtual srs_error_t create_consumer(SrsLiveConsumer*& consumer);
// Dumps packets in cache to consumer.
// @param ds, whether dumps the sequence header.
// @param dm, whether dumps the metadata.
// @param dg, whether dumps the gop cache.
virtual srs_error_t consumer_dumps(SrsLiveConsumer* consumer, bool ds = true, bool dm = true, bool dg = true);
virtual void on_consumer_destroy(SrsLiveConsumer* consumer);
virtual void set_cache(bool enabled);
virtual SrsRtmpJitterAlgorithm jitter();
public:
// For edge, when publish edge stream, check the state
virtual srs_error_t on_edge_start_publish();
// For edge, proxy the publish
virtual srs_error_t on_edge_proxy_publish(SrsCommonMessage* msg);
// For edge, proxy stop publish
virtual void on_edge_proxy_unpublish();
public:
virtual std::string get_curr_origin();
};
#endif
| 7,424 |
372 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.run.v1alpha1.model;
/**
* Deprecated, importer specification will be available via GcpImporterDao.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Run API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class TriggerImporterSpec extends com.google.api.client.json.GenericJson {
/**
* Arguments to use for the importer. These must match the parameters in the EventType's importer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> arguments;
/**
* Name of the EventType that this importer provides.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String eventTypeName;
/**
* Arguments to use for the importer. These must match the parameters in the EventType's importer.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getArguments() {
return arguments;
}
/**
* Arguments to use for the importer. These must match the parameters in the EventType's importer.
* @param arguments arguments or {@code null} for none
*/
public TriggerImporterSpec setArguments(java.util.Map<String, java.lang.String> arguments) {
this.arguments = arguments;
return this;
}
/**
* Name of the EventType that this importer provides.
* @return value or {@code null} for none
*/
public java.lang.String getEventTypeName() {
return eventTypeName;
}
/**
* Name of the EventType that this importer provides.
* @param eventTypeName eventTypeName or {@code null} for none
*/
public TriggerImporterSpec setEventTypeName(java.lang.String eventTypeName) {
this.eventTypeName = eventTypeName;
return this;
}
@Override
public TriggerImporterSpec set(String fieldName, Object value) {
return (TriggerImporterSpec) super.set(fieldName, value);
}
@Override
public TriggerImporterSpec clone() {
return (TriggerImporterSpec) super.clone();
}
}
| 927 |
12,252 | <reponame>rmartinc/keycloak<filename>testsuite/performance/tests/src/main/java/org/keycloak/performance/RealmsConfigurationBuilder.java
package org.keycloak.performance;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import static org.keycloak.common.util.ObjectUtil.capitalize;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class RealmsConfigurationBuilder {
private Random RANDOM = new Random();
private JsonGenerator g;
private String file;
public static final String EXPORT_FILENAME = "benchmark-realms.json";
public RealmsConfigurationBuilder(String filename) {
this.file = filename;
try {
JsonFactory f = new JsonFactory();
g = f.createGenerator(new File(file), JsonEncoding.UTF8);
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
g.setCodec(mapper);
} catch (Exception e) {
throw new RuntimeException("Failed to create realms export file", e);
}
}
public void build() throws IOException {
// There are several realms
startRealms();
for (int i = 0; i < TestConfig.numOfRealms; i++) {
RealmConfig realm = new RealmConfig();
String realmName = "realm_" + i;
startRealm(realmName, realm);
// first create clients,
// then roles, and client roles
// create users at the end
// reason: each next depends on availability of the previous
// each realm has some clients
startClients();
for (int j = 0; j < TestConfig.clientsPerRealm; j++) {
ClientRepresentation client = new ClientRepresentation();
String clientId = computeClientId(realmName, j);
client.setClientId(clientId);
client.setEnabled(true);
String baseDir = computeAppUrl(clientId);
client.setBaseUrl(baseDir);
List<String> uris = new ArrayList<>();
uris.add(baseDir + "/*");
if (isClientConfidential(j)) {
client.setRedirectUris(uris);
client.setSecret(computeSecret(clientId));
} else if (isClientBearerOnly(j)) {
client.setBearerOnly(true);
} else {
client.setPublicClient(true);
client.setRedirectUris(uris);
}
addClient(client);
}
completeClients();
// each realm has some realm roles
startRoles();
startRealmRoles();
for (int j = 0; j < TestConfig.realmRoles; j++) {
addRole("role_" + j + "_ofRealm_" + i);
}
completeRealmRoles();
// each client has some client roles
startClientRoles();
for (int j = 0; j < TestConfig.clientsPerRealm; j++) {
addClientRoles("client_" + j + "_ofRealm_" + i);
}
completeClientRoles();
completeRoles();
// each realm so many users
startUsers();
for (int j = 0; j < TestConfig.usersPerRealm; j++) {
UserRepresentation user = new UserRepresentation();
user.setUsername(computeUsername(realmName, j));
user.setEnabled(true);
user.setEmail(computeEmail(user.getUsername()));
user.setFirstName(computeFirstName(j));
user.setLastName(computeLastName(realmName));
CredentialRepresentation creds = new CredentialRepresentation();
creds.setType("password");
creds.setValue(computePassword(user.getUsername()));
user.setCredentials(Arrays.asList(creds));
// add realm roles
// each user some random realm roles
Set<String> realmRoles = new HashSet<String>();
while (realmRoles.size() < TestConfig.realmRolesPerUser) {
realmRoles.add("role_" + random(TestConfig.realmRoles) + "_ofRealm_" + i);
}
user.setRealmRoles(new ArrayList<>(realmRoles));
// add client roles
// each user some random client roles (random client + random role on that client)
Set<String> clientRoles = new HashSet<String>();
while (clientRoles.size() < TestConfig.clientRolesPerUser) {
int client = random(TestConfig.clientsPerRealm);
int clientRole = random(TestConfig.clientRolesPerClient);
clientRoles.add("clientrole_" + clientRole + "_ofClient_" + client + "_ofRealm_" + i);
}
Map<String, List<String>> clientRoleMappings = new HashMap<>();
for (String item : clientRoles) {
int s = item.indexOf("_ofClient_");
int b = s + "_ofClient_".length();
int e = item.indexOf("_", b);
String key = "client_" + item.substring(b, e) + "_ofRealm_" + i;
List<String> cliRoles = clientRoleMappings.get(key);
if (cliRoles == null) {
cliRoles = new ArrayList<>();
clientRoleMappings.put(key, cliRoles);
}
cliRoles.add(item);
}
user.setClientRoles(clientRoleMappings);
addUser(user);
}
completeUsers();
completeRealm();
}
completeRealms();
g.close();
}
private void addClientRoles(String client) throws IOException {
g.writeArrayFieldStart(client);
for (int i = 0; i < TestConfig.clientRolesPerClient; i++) {
g.writeStartObject();
String name = "clientrole_" + i + "_of" + capitalize(client);
g.writeStringField("name", name);
g.writeStringField("description", "Test realm role - " + name);
g.writeEndObject();
}
g.writeEndArray();
}
private void addClient(ClientRepresentation client) throws IOException {
g.writeObject(client);
}
private void startClients() throws IOException {
g.writeArrayFieldStart("clients");
}
private void completeClients() throws IOException {
g.writeEndArray();
}
private void startRealms() throws IOException {
g.writeStartArray();
}
private void completeRealms() throws IOException {
g.writeEndArray();
}
private int random(int max) {
return RANDOM.nextInt(max);
}
private void startRealm(String realmName, RealmConfig conf) throws IOException {
g.writeStartObject();
g.writeStringField("realm", realmName);
g.writeBooleanField("enabled", true);
g.writeNumberField("accessTokenLifespan", conf.accessTokenLifeSpan);
g.writeStringField("sslRequired", "none");
g.writeBooleanField("registrationAllowed", conf.registrationAllowed);
g.writeStringField("passwordPolicy", "hashIterations(" + TestConfig.hashIterations + ")");
/*
if (conf.requiredCredentials != null) {
g.writeArrayFieldStart("requiredCredentials");
//g.writeStartArray();
for (String item: conf.requiredCredentials) {
g.writeString(item);
}
g.writeEndArray();
}
*/
}
private void completeRealm() throws IOException {
g.writeEndObject();
}
private void startUsers() throws IOException {
g.writeArrayFieldStart("users");
}
private void completeUsers() throws IOException {
g.writeEndArray();
}
private void addUser(UserRepresentation user) throws IOException {
g.writeObject(user);
}
private void startRoles() throws IOException {
g.writeObjectFieldStart("roles");
}
private void startRealmRoles() throws IOException {
g.writeArrayFieldStart("realm");
}
private void startClientRoles() throws IOException {
g.writeObjectFieldStart("client");
}
private void completeClientRoles() throws IOException {
g.writeEndObject();
}
private void addRole(String role) throws IOException {
g.writeStartObject();
g.writeStringField("name", role);
g.writeStringField("description", "Test realm role - " + role);
g.writeEndObject();
}
private void completeRealmRoles() throws IOException {
g.writeEndArray();
}
private void completeRoles() throws IOException {
g.writeEndObject();
}
static boolean isClientConfidential(int index) {
// every third client starting with 0
return index % 3 == 0;
}
static boolean isClientBearerOnly(int index) {
// every third client starting with 1
return index % 3 == 1;
}
static boolean isClientPublic(int index) {
// every third client starting with 2
return index % 3 == 2;
}
static String computeClientId(String realm, int idx) {
return "client_" + idx + "_of" + capitalize(realm);
}
static String computeAppUrl(String clientId) {
return "http://keycloak-test-" + clientId.toLowerCase();
}
static String computeSecret(String clientId) {
return "secretFor_" + clientId;
}
static String computeUsername(String realm, int idx) {
return "user_" + idx + "_of" + capitalize(realm);
}
static String computePassword(String username) {
return "<PASSWORD>_" + username;
}
static String computeFirstName(int userIdx) {
return "User" + userIdx;
}
static String computeLastName(String realm) {
return "O'" + realm.replace("_", "");
}
static String computeEmail(String username) {
return username + "@example.com";
}
public static void main(String[] args) throws IOException {
File exportFile = new File(EXPORT_FILENAME);
TestConfig.validateConfiguration();
System.out.println("Generating test dataset with the following parameters: \n" + TestConfig.toStringDatasetProperties());
new RealmsConfigurationBuilder(exportFile.getAbsolutePath()).build();
System.out.println("Created " + exportFile.getAbsolutePath());
}
}
| 4,977 |
951 | /*----------------------------------------------------------------------*
* M5Stack I2C Common Library v1.0 *
* *
* This work is licensed under the GNU Lesser General Public *
* License v2.1 *
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html *
*----------------------------------------------------------------------*/
#ifndef CommUtil_h
#define CommUtil_h
#include <Arduino.h>
#include <Wire.h>
class CommUtil {
public:
CommUtil();
bool writeCommand(uint8_t address, uint8_t subAddress);
bool writeByte(uint8_t address, uint8_t subAddress, uint8_t data);
bool writeBytes(uint8_t address, uint8_t subAddress, uint8_t *data,uint8_t length);
bool readByte(uint8_t address, uint8_t *result);
bool readByte(uint8_t address, uint8_t subAddress,uint8_t *result);
bool readBytes(uint8_t address, uint8_t count,uint8_t * dest);
bool readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest);
void scanID(bool *result);
private:
};
#endif
| 531 |
1,164 | #!/usr/bin/env python3
import logging
import sys
from benchmarks import composition
from benchmarks import dist_avg
from benchmarks import locality
from benchmarks import predserving
from benchmarks import scaling
from benchmarks import summa
from benchmarks import utils
import client as flclient
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
if len(sys.argv) < 4:
print('Usage: ./run_benchmark.py benchmark_name function_elb num_requests '
+ '{ip}')
sys.exit(1)
f_elb = sys.argv[2]
num_requests = int(sys.argv[3])
if len(sys.argv) == 5:
ip = sys.argv[4]
flconn = flclient.FluentConnection(f_elb, ip)
else:
flconn = flclient.FluentConnection(f_elb)
kvs = flconn.kvs_client
bname = sys.argv[1]
if bname == 'composition':
total, scheduler, kvs, retries = composition.run(flconn, kvs, num_requests,
None)
elif bname == 'locality':
locality.run(flconn, kvs, num_requests, True, None)
total, scheduler, kvs, retries = locality.run(flconn, kvs, num_requests,
False, None)
elif bname == 'pred_serving':
total, scheduler, kvs, retries = predserving.run(flconn, kvs,
num_requests, None)
elif bname == 'avg':
total, scheduler, kvs, retries = dist_avg.run(flconn, kvs, num_requests,
None)
elif bname == 'summa':
total, scheduler, kvs, retries = summa.run(flconn, kvs, num_requests, None)
elif bname == 'scaling':
total, scheduler, kvs, retries = scaling.run(flconn, kvs, num_requests,
None)
else:
print('Unknown benchmark type: %s!' % (bname))
print('Total computation time: %.4f' % (sum(total)))
if total:
utils.print_latency_stats(total, 'E2E')
if scheduler:
utils.print_latency_stats(scheduler, 'SCHEDULER')
if kvs:
utils.print_latency_stats(kvs, 'KVS')
if retries > 0:
print('Number of KVS get retries: %d' % (retries))
| 964 |
5,535 | <reponame>lmwnshn/postgres
/* This file was generated automatically by the Snowball to ISO C compiler */
/* http://snowballstem.org/ */
#ifdef __cplusplus
extern "C" {
#endif
extern struct SN_env * arabic_UTF_8_create_env(void);
extern void arabic_UTF_8_close_env(struct SN_env * z);
extern int arabic_UTF_8_stem(struct SN_env * z);
#ifdef __cplusplus
}
#endif
| 143 |
2,002 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#pragma once
#include "Microsoft.Windows.ApplicationModel.DynamicDependency.CreatePackageDependencyOptions.g.h"
#include "winrt_namespaces.h"
namespace winrt::Microsoft::Windows::ApplicationModel::DynamicDependency::implementation
{
struct CreatePackageDependencyOptions : CreatePackageDependencyOptionsT<CreatePackageDependencyOptions>
{
CreatePackageDependencyOptions() = default;
winrt::PackageDependencyProcessorArchitectures Architectures();
void Architectures(Microsoft::Windows::ApplicationModel::DynamicDependency::PackageDependencyProcessorArchitectures const& value);
bool VerifyDependencyResolution();
void VerifyDependencyResolution(bool value);
winrt::PackageDependencyLifetimeArtifactKind LifetimeArtifactKind();
void LifetimeArtifactKind(Microsoft::Windows::ApplicationModel::DynamicDependency::PackageDependencyLifetimeArtifactKind const& value);
hstring LifetimeArtifact();
void LifetimeArtifact(hstring const& value);
private:
winrt::PackageDependencyProcessorArchitectures m_architectures{ winrt::PackageDependencyProcessorArchitectures::None };
bool m_verifyDependencyResolution{};
winrt::PackageDependencyLifetimeArtifactKind m_lifetimeArtifactKind{ winrt::PackageDependencyLifetimeArtifactKind::Process };
hstring m_lifetimeArtifact;
};
}
namespace winrt::Microsoft::Windows::ApplicationModel::DynamicDependency::factory_implementation
{
struct CreatePackageDependencyOptions : CreatePackageDependencyOptionsT<CreatePackageDependencyOptions, implementation::CreatePackageDependencyOptions>
{
};
}
| 595 |
497 | ////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2006 by <NAME>
//
// Code covered by the MIT License
//
// Permission to use, copy, modify, distribute and sell this software for any
// purpose is hereby granted without fee, provided that the above copyright
// notice appear in all copies and that both that copyright notice and this
// permission notice appear in supporting documentation.
//
// The authors make no representations about the suitability of this software
// for any purpose. It is provided "as is" without express or implied warranty.
//
// This code DOES NOT accompany the book:
// Alexandrescu, Andrei. "Modern C++ Design: Generic Programming and Design
// Patterns Applied". Copyright (c) 2001. Addison-Wesley.
//
////////////////////////////////////////////////////////////////////////////////
#ifndef LOKI_CACHEDFACTORY_INC_
#define LOKI_CACHEDFACTORY_INC_
// $Id: CachedFactory.h 950 2009-01-26 19:45:54Z syntheticpp $
#include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>
#include <map>
#include <cassert>
#include <loki/Key.h>
#ifdef DO_EXTRA_LOKI_TESTS
#define D( x ) x
#else
#define D( x ) ;
#endif
#if defined(_MSC_VER) || defined(__CYGWIN__)
#include <time.h>
#endif
/**
* \defgroup FactoriesGroup Factories
* \defgroup CachedFactoryGroup Cached Factory
* \ingroup FactoriesGroup
* \brief CachedFactory provides an extension of a Factory with caching
* support.
*
* Once used objects are returned to the CachedFactory that manages its
* destruction.
* If your code uses lots of "long to construct/destruct objects" using the
* CachedFactory will surely speedup the execution.
*/
namespace Loki
{
/**
* \defgroup EncapsulationPolicyCachedFactoryGroup Encapsulation policies
* \ingroup CachedFactoryGroup
* \brief Defines how the object is returned to the client
*/
/**
* \class SimplePointer
* \ingroup EncapsulationPolicyCachedFactoryGroup
* \brief No encaspulation : returns the pointer
*
* This implementation does not make any encapsulation.
* It simply returns the object's pointer.
*/
template<class AbstractProduct>
class SimplePointer
{
protected:
typedef AbstractProduct *ProductReturn;
ProductReturn encapsulate(AbstractProduct *pProduct)
{
return pProduct;
}
AbstractProduct *release(ProductReturn &pProduct)
{
AbstractProduct *pPointer(pProduct);
pProduct=NULL;
return pPointer;
}
const char *name()
{
return "pointer";
}
};
/**
* \defgroup CreationPolicyCachedFactoryGroup Creation policies
* \ingroup CachedFactoryGroup
* \brief Defines a way to limit the creation operation.
*
* For instance one may want to be alerted (Exception) when
* - Cache has created a more than X object within the last x seconds
* - Cache creation rate has increased dramatically
* .
* which may result from bad caching strategy, or critical overload
*/
/**
* \class NeverCreate
* \ingroup CreationPolicyCachedFactoryGroup
* \brief Never allows creation. Testing purposes only.
*
* Using this policy will throw an exception.
*/
class NeverCreate
{
protected:
struct Exception : public std::exception
{
const char *what() const throw()
{
return "NeverFetch Policy : No Fetching allowed";
}
};
bool canCreate()
{
throw Exception();
}
void onCreate() {}
void onDestroy() {}
const char *name()
{
return "never";
}
};
/**
* \class AlwaysCreate
* \ingroup CreationPolicyCachedFactoryGroup
* \brief Always allows creation.
*
* Doesn't limit the creation in any way
*/
class AlwaysCreate
{
protected:
bool canCreate()
{
return true;
}
void onCreate() {}
void onDestroy() {}
const char *name()
{
return "always";
}
};
/**
* \class RateLimitedCreation
* \ingroup CreationPolicyCachedFactoryGroup
* \brief Limit in rate.
*
* This implementation will prevent from Creating more than maxCreation objects
* within byTime ms by throwing an exception.
* Could be usefull to detect prevent loads (http connection for instance).
* Use the setRate method to set the rate parameters.
* default is 10 objects in a second.
*/
// !! CAUTION !!
// The std::clock() function is not quite precise
// under linux this policy might not work.
// TODO : get a better implementation (platform dependant)
class RateLimitedCreation
{
private:
typedef std::vector< clock_t > Vector;
Vector m_vTimes;
unsigned maxCreation;
clock_t timeValidity;
clock_t lastUpdate;
void cleanVector()
{
using namespace std;
clock_t currentTime = clock();
D( cout << "currentTime = " << currentTime<< endl; )
D( cout << "currentTime - lastUpdate = " << currentTime - lastUpdate<< endl; )
if(currentTime - lastUpdate > timeValidity)
{
m_vTimes.clear();
D( cout << " is less than time validity " << timeValidity; )
D( cout << " so clearing vector" << endl; )
}
else
{
D( cout << "Cleaning time less than " << currentTime - timeValidity << endl; )
D( displayVector(); )
Vector::iterator newEnd = remove_if(m_vTimes.begin(), m_vTimes.end(), bind2nd(less<clock_t>(), currentTime - timeValidity));
// this rearrangement might be costly, consider optimization
// by calling cleanVector in less used onCreate function
// ... although it may not be correct
m_vTimes.erase(newEnd, m_vTimes.end());
D( displayVector(); )
}
lastUpdate = currentTime;
}
#ifdef DO_EXTRA_LOKI_TESTS
void displayVector()
{
std::cout << "Vector : ";
copy(m_vTimes.begin(), m_vTimes.end(), std::ostream_iterator<clock_t>(std::cout, " "));
std::cout << std::endl;
}
#endif
protected:
RateLimitedCreation() : maxCreation(10), timeValidity(CLOCKS_PER_SEC), lastUpdate(clock())
{}
struct Exception : public std::exception
{
const char *what() const throw()
{
return "RateLimitedCreation Policy : Exceeded the authorized creation rate";
}
};
bool canCreate()
{
cleanVector();
if(m_vTimes.size()>maxCreation)
throw Exception();
else
return true;
}
void onCreate()
{
m_vTimes.push_back(clock());
}
void onDestroy()
{
}
const char *name()
{
return "rate limited";
}
public:
// set the creation rate
// No more than maxCreation within byTime milliseconds
void setRate(unsigned maxCreation, unsigned byTime)
{
assert(byTime>0);
this->maxCreation = maxCreation;
this->timeValidity = static_cast<clock_t>(byTime * CLOCKS_PER_SEC / 1000);
D( std::cout << "Setting no more than "<< maxCreation <<" creation within " << this->timeValidity <<" ms"<< std::endl; )
}
};
/**
* \class AmountLimitedCreation
* \ingroup CreationPolicyCachedFactoryGroup
* \brief Limit by number of objects
*
* This implementation will prevent from Creating more than maxCreation objects
* within byTime ms by calling eviction policy.
* Use the setRate method to set the rate parameters.
* default is 10 objects.
*/
class AmountLimitedCreation
{
private:
unsigned maxCreation;
unsigned created;
protected:
AmountLimitedCreation() : maxCreation(10), created(0)
{}
bool canCreate()
{
return !(created>=maxCreation);
}
void onCreate()
{
++created;
}
void onDestroy()
{
--created;
}
const char *name()
{
return "amount limited";
}
public:
// set the creation max amount
void setMaxCreation(unsigned maxCreation)
{
assert(maxCreation>0);
this->maxCreation = maxCreation;
D( std::cout << "Setting no more than " << maxCreation <<" creation" << std::endl; )
}
};
/**
* \defgroup EvictionPolicyCachedFactoryGroup Eviction policies
* \ingroup CachedFactoryGroup
* \brief Gathers informations about the stored objects and choose a
* candidate for eviction.
*/
class EvictionException : public std::exception
{
public:
const char *what() const throw()
{
return "Eviction Policy : trying to make room but no objects are available";
}
};
// The following class is intented to provide helpers to sort
// the container that will hold an eviction score
template
<
typename ST, // Score type
typename DT // Data type
>
class EvictionHelper
{
protected:
typedef typename std::map< DT, ST > HitMap;
typedef typename HitMap::iterator HitMapItr;
private:
typedef std::pair< ST, DT > SwappedPair;
typedef std::multimap< ST, DT > SwappedHitMap;
typedef typename SwappedHitMap::iterator SwappedHitMapItr;
protected:
HitMap m_mHitCount;
// This function sorts the map according to the score
// and returns the lower bound of the sorted container
DT &getLowerBound()
{
assert(!m_mHitCount.empty());
// inserting the swapped pair into a multimap
SwappedHitMap copyMap;
for(HitMapItr itr = m_mHitCount.begin(); itr != m_mHitCount.end(); ++itr)
copyMap.insert(SwappedPair((*itr).second, (*itr).first));
if((*copyMap.rbegin()).first == 0) // the higher score is 0 ...
throw EvictionException(); // there is no key evict
return (*copyMap.begin()).second;
}
};
/**
* \class EvictLRU
* \ingroup EvictionPolicyCachedFactoryGroup
* \brief Evicts least accessed objects first.
*
* Implementation of the Least recent used algorithm as
* described in http://en.wikipedia.org/wiki/Page_replacement_algorithms .
*
* WARNING : If an object is heavily fetched
* (more than ULONG_MAX = UINT_MAX = 4294967295U)
* it could unfortunately be removed from the cache.
*/
template
<
typename DT, // Data Type (AbstractProduct*)
typename ST = unsigned // default data type to use as Score Type
>
class EvictLRU : public EvictionHelper< ST , DT >
{
private:
typedef EvictionHelper< ST , DT > EH;
protected:
virtual ~EvictLRU() {}
// OnStore initialize the counter for the new key
// If the key already exists, the counter is reseted
void onCreate(const DT &key)
{
EH::m_mHitCount[key] = 0;
}
void onFetch(const DT &)
{
}
// onRelease increments the hit counter associated with the object
void onRelease(const DT &key)
{
++(EH::m_mHitCount[key]);
}
void onDestroy(const DT &key)
{
EH::m_mHitCount.erase(key);
}
// this function is implemented in Cache and redirected
// to the Storage Policy
virtual void remove(DT const key)=0;
// LRU Eviction policy
void evict()
{
remove(EH::getLowerBound());
}
const char *name()
{
return "LRU";
}
};
/**
* \class EvictAging
* \ingroup EvictionPolicyCachedFactoryGroup
* \brief LRU aware of the time span of use
*
* Implementation of the Aging algorithm as
* described in http://en.wikipedia.org/wiki/Page_replacement_algorithms .
*
* This method is much more costly than evict LRU so
* if you need extreme performance consider switching to EvictLRU
*/
template
<
typename DT, // Data Type (AbstractProduct*)
typename ST = unsigned // default data type to use as Score Type
>
class EvictAging : public EvictionHelper< ST, DT >
{
private:
EvictAging(const EvictAging &);
EvictAging &operator=(const EvictAging &);
typedef EvictionHelper< ST, DT > EH;
typedef typename EH::HitMap HitMap;
typedef typename EH::HitMapItr HitMapItr;
// update the counter
template<class T> struct updateCounter : public std::unary_function<T, void>
{
updateCounter(const DT &key): key_(key) {}
void operator()(T x)
{
x.second = (x.first == key_ ? (x.second >> 1) | ( 1 << ((sizeof(ST)-1)*8) ) : x.second >> 1);
D( std::cout << x.second << std::endl; )
}
const DT &key_;
updateCounter(const updateCounter &rhs) : key_(rhs.key_) {}
private:
updateCounter &operator=(const updateCounter &rhs);
};
protected:
EvictAging() {}
virtual ~EvictAging() {}
// OnStore initialize the counter for the new key
// If the key already exists, the counter is reseted
void onCreate(const DT &key)
{
EH::m_mHitCount[key] = 0;
}
void onFetch(const DT &) {}
// onRelease increments the hit counter associated with the object
// Updating every counters by iterating over the map
// If the key is the key of the fetched object :
// the counter is shifted to the right and it's MSB is set to 1
// else
// the counter is shifted to the left
void onRelease(const DT &key)
{
std::for_each(EH::m_mHitCount.begin(), EH::m_mHitCount.end(), updateCounter< typename HitMap::value_type >(key));
}
void onDestroy(const DT &key)
{
EH::m_mHitCount.erase(key);
}
// this function is implemented in Cache and redirected
// to the Storage Policy
virtual void remove(DT const key)=0;
// LRU with Aging Eviction policy
void evict()
{
remove(EH::getLowerBound());
}
const char *name()
{
return "LRU with aging";
}
};
/**
* \class EvictRandom
* \ingroup EvictionPolicyCachedFactoryGroup
* \brief Evicts a random object
*
* Implementation of the Random algorithm as
* described in http://en.wikipedia.org/wiki/Page_replacement_algorithms .
*/
template
<
typename DT, // Data Type (AbstractProduct*)
typename ST = void // Score Type not used by this policy
>
class EvictRandom
{
private:
std::vector< DT > m_vKeys;
typedef typename std::vector< DT >::size_type size_type;
typedef typename std::vector< DT >::iterator iterator;
protected:
virtual ~EvictRandom() {}
void onCreate(const DT &)
{
}
void onFetch(const DT & )
{
}
void onRelease(const DT &key)
{
m_vKeys.push_back(key);
}
void onDestroy(const DT &key)
{
using namespace std;
m_vKeys.erase(remove_if(m_vKeys.begin(), m_vKeys.end(), bind2nd(equal_to< DT >(), key)), m_vKeys.end());
}
// Implemented in Cache and redirected to the Storage Policy
virtual void remove(DT const key)=0;
// Random Eviction policy
void evict()
{
if(m_vKeys.empty())
throw EvictionException();
size_type random = static_cast<size_type>((m_vKeys.size()*rand())/(static_cast<size_type>(RAND_MAX) + 1));
remove(*(m_vKeys.begin()+random));
}
const char *name()
{
return "random";
}
};
/**
* \defgroup StatisticPolicyCachedFactoryGroup Statistic policies
* \ingroup CachedFactoryGroup
* \brief Gathers information about the cache.
*
* For debugging purpose this policy proposes to gather informations
* about the cache. This could be useful to determine whether the cache is
* mandatory or if the policies are well suited to the application.
*/
/**
* \class NoStatisticPolicy
* \ingroup StatisticPolicyCachedFactoryGroup
* \brief Do nothing
*
* Should be used in release code for better performances
*/
class NoStatisticPolicy
{
protected:
void onDebug() {}
void onFetch() {}
void onRelease() {}
void onCreate() {}
void onDestroy() {}
const char *name()
{
return "no";
}
};
/**
* \class SimpleStatisticPolicy
* \ingroup StatisticPolicyCachedFactoryGroup
* \brief Simple statistics
*
* Provides the following informations about the cache :
* - Created objects
* - Fetched objects
* - Destroyed objects
* - Cache hit
* - Cache miss
* - Currently allocated
* - Currently out
* - Cache overall efficiency
*/
class SimpleStatisticPolicy
{
private:
unsigned allocated, created, hit, out, fetched;
protected:
SimpleStatisticPolicy() : allocated(0), created(0), hit(0), out(0), fetched(0)
{
}
void onDebug()
{
using namespace std;
cout << "############################" << endl;
cout << "## About this cache " << this << endl;
cout << "## + Created objects : " << created << endl;
cout << "## + Fetched objects : " << fetched << endl;
cout << "## + Destroyed objects : " << created - allocated << endl;
cout << "## + Cache hit : " << hit << endl;
cout << "## + Cache miss : " << fetched - hit << endl;
cout << "## + Currently allocated : " << allocated << endl;
cout << "## + Currently out : " << out << endl;
cout << "############################" << endl;
if(fetched!=0)
{
cout << "## Overall efficiency " << 100*double(hit)/fetched <<"%"<< endl;
cout << "############################" << endl;
}
cout << endl;
}
void onFetch()
{
++fetched;
++out;
++hit;
}
void onRelease()
{
--out;
}
void onCreate()
{
++created;
++allocated;
--hit;
}
void onDestroy()
{
--allocated;
}
const char *name()
{
return "simple";
}
public:
unsigned getCreated()
{
return created;
}
unsigned getFetched()
{
return fetched;
}
unsigned getHit()
{
return hit;
}
unsigned getMissed()
{
return fetched - hit;
}
unsigned getAllocated()
{
return allocated;
}
unsigned getOut()
{
return out;
}
unsigned getDestroyed()
{
return created-allocated;
}
};
///////////////////////////////////////////////////////////////////////////
// Cache Factory definition
///////////////////////////////////////////////////////////////////////////
class CacheException : public std::exception
{
public:
const char *what() const throw()
{
return "Internal Cache Error";
}
};
/**
* \class CachedFactory
* \ingroup CachedFactoryGroup
* \brief Factory with caching support
*
* This class acts as a Factory (it creates objects)
* but also keeps the already created objects to prevent
* long constructions time.
*
* Note this implementation do not retain ownership.
*/
template
<
class AbstractProduct,
typename IdentifierType,
typename CreatorParmTList = NullType,
template<class> class EncapsulationPolicy = SimplePointer,
class CreationPolicy = AlwaysCreate,
template <typename , typename> class EvictionPolicy = EvictRandom,
class StatisticPolicy = NoStatisticPolicy,
template<typename, class> class FactoryErrorPolicy = DefaultFactoryError,
class ObjVector = std::vector<AbstractProduct *>
>
class CachedFactory :
protected EncapsulationPolicy<AbstractProduct>,
public CreationPolicy, public StatisticPolicy, EvictionPolicy< AbstractProduct * , unsigned >
{
private:
typedef Factory< AbstractProduct, IdentifierType, CreatorParmTList, FactoryErrorPolicy> MyFactory;
typedef FactoryImpl< AbstractProduct, IdentifierType, CreatorParmTList > Impl;
typedef Functor< AbstractProduct * , CreatorParmTList > ProductCreator;
typedef EncapsulationPolicy<AbstractProduct> NP;
typedef CreationPolicy CP;
typedef StatisticPolicy SP;
typedef EvictionPolicy< AbstractProduct * , unsigned > EP;
typedef typename Impl::Parm1 Parm1;
typedef typename Impl::Parm2 Parm2;
typedef typename Impl::Parm3 Parm3;
typedef typename Impl::Parm4 Parm4;
typedef typename Impl::Parm5 Parm5;
typedef typename Impl::Parm6 Parm6;
typedef typename Impl::Parm7 Parm7;
typedef typename Impl::Parm8 Parm8;
typedef typename Impl::Parm9 Parm9;
typedef typename Impl::Parm10 Parm10;
typedef typename Impl::Parm11 Parm11;
typedef typename Impl::Parm12 Parm12;
typedef typename Impl::Parm13 Parm13;
typedef typename Impl::Parm14 Parm14;
typedef typename Impl::Parm15 Parm15;
public:
typedef typename NP::ProductReturn ProductReturn;
private:
typedef Key< Impl, IdentifierType > MyKey;
typedef std::map< MyKey, ObjVector > KeyToObjVectorMap;
typedef std::map< AbstractProduct *, MyKey > FetchedObjToKeyMap;
MyFactory factory;
KeyToObjVectorMap fromKeyToObjVector;
FetchedObjToKeyMap providedObjects;
unsigned outObjects;
ObjVector &getContainerFromKey(MyKey key)
{
return fromKeyToObjVector[key];
}
AbstractProduct *const getPointerToObjectInContainer(ObjVector &entry)
{
if(entry.empty()) // No object available
{
// the object will be created in the calling function.
// It has to be created in the calling function because of
// the variable number of parameters for CreateObject(...) method
return NULL;
}
else
{
// returning the found object
AbstractProduct *pObject(entry.back());
assert(pObject!=NULL);
entry.pop_back();
return pObject;
}
}
bool shouldCreateObject(AbstractProduct *const pProduct)
{
if(pProduct!=NULL) // object already exists
return false;
if(CP::canCreate()==false) // Are we allowed to Create ?
EP::evict(); // calling Eviction Policy to clean up
return true;
}
void ReleaseObjectFromContainer(ObjVector &entry, AbstractProduct *const object)
{
entry.push_back(object);
}
void onFetch(AbstractProduct *const pProduct)
{
SP::onFetch();
EP::onFetch(pProduct);
++outObjects;
}
void onRelease(AbstractProduct *const pProduct)
{
SP::onRelease();
EP::onRelease(pProduct);
--outObjects;
}
void onCreate(AbstractProduct *const pProduct)
{
CP::onCreate();
SP::onCreate();
EP::onCreate(pProduct);
}
void onDestroy(AbstractProduct *const pProduct)
{
CP::onDestroy();
SP::onDestroy();
EP::onDestroy(pProduct);
}
// delete the object
template<class T> struct deleteObject : public std::unary_function<T, void>
{
void operator()(T x)
{
delete x;
}
};
// delete the objects in the vector
template<class T> struct deleteVectorObjects : public std::unary_function<T, void>
{
void operator()(T x)
{
ObjVector &vec(x.second);
std::for_each(vec.begin(), vec.end(), deleteObject< typename ObjVector::value_type>());
}
};
// delete the keys of the map
template<class T> struct deleteMapKeys : public std::unary_function<T, void>
{
void operator()(T x)
{
delete x.first;
}
};
protected:
virtual void remove(AbstractProduct *const pProduct)
{
typename FetchedObjToKeyMap::iterator fetchedItr = providedObjects.find(pProduct);
if(fetchedItr!=providedObjects.end()) // object is unreleased.
throw CacheException();
bool productRemoved = false;
typename KeyToObjVectorMap::iterator objVectorItr;
typename ObjVector::iterator objItr;
for(objVectorItr=fromKeyToObjVector.begin(); objVectorItr!=fromKeyToObjVector.end(); ++objVectorItr)
{
ObjVector &v((*objVectorItr).second);
objItr = remove_if(v.begin(), v.end(), std::bind2nd(std::equal_to<AbstractProduct *>(), pProduct));
if(objItr != v.end()) // we found the vector containing pProduct and removed it
{
onDestroy(pProduct); // warning policies we are about to destroy an object
v.erase(objItr, v.end()); // real removing
productRemoved = true;
break;
}
}
if(productRemoved==false)
throw CacheException(); // the product is not in the cache ?!
delete pProduct; // deleting it
}
public:
CachedFactory() : factory(), fromKeyToObjVector(), providedObjects(), outObjects(0)
{
}
~CachedFactory()
{
using namespace std;
// debug information
SP::onDebug();
// cleaning the Cache
for_each(fromKeyToObjVector.begin(), fromKeyToObjVector.end(),
deleteVectorObjects< typename KeyToObjVectorMap::value_type >()
);
if(!providedObjects.empty())
{
// The factory is responsible for the creation and destruction of objects.
// If objects are out during the destruction of the Factory : deleting anyway.
// This might not be a good idea. But throwing an exception in a destructor is
// considered as a bad pratice and asserting might be too much.
// What to do ? Leaking memory or corrupting in use pointers ? hmm...
D( cout << "====>> Cache destructor : deleting "<< providedObjects.size()<<" in use objects <<====" << endl << endl; )
for_each(providedObjects.begin(), providedObjects.end(),
deleteMapKeys< typename FetchedObjToKeyMap::value_type >()
);
}
}
///////////////////////////////////
// Acts as the proxy pattern and //
// forwards factory methods //
///////////////////////////////////
bool Register(const IdentifierType &id, ProductCreator creator)
{
return factory.Register(id, creator);
}
template <class PtrObj, typename CreaFn>
bool Register(const IdentifierType &id, const PtrObj &p, CreaFn fn)
{
return factory.Register(id, p, fn);
}
bool Unregister(const IdentifierType &id)
{
return factory.Unregister(id);
}
/// Return the registered ID in this Factory
std::vector<IdentifierType>& RegisteredIds()
{
return factory.RegisteredIds();
}
ProductReturn CreateObject(const IdentifierType &id)
{
MyKey key(id);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1)
{
MyKey key(id,p1);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2)
{
MyKey key(id,p1,p2);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3)
{
MyKey key(id,p1,p2,p3);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4)
{
MyKey key(id,p1,p2,p3,p4);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5)
{
MyKey key(id,p1,p2,p3,p4,p5);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6)
{
MyKey key(id,p1,p2,p3,p4,p5,p6);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7 )
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7, Parm8 p8)
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7,p8);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7,key.p8);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7, Parm8 p8, Parm9 p9)
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7,p8,p9);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7,key.p8,key.p9);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7, Parm8 p8, Parm9 p9,Parm10 p10)
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7,key.p8,key.p9,key.p10);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7, Parm8 p8, Parm9 p9, Parm10 p10,
Parm11 p11)
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7,key.p8,key.p9,key.p10,key.p11);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7, Parm8 p8, Parm9 p9, Parm10 p10,
Parm11 p11, Parm12 p12)
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7,key.p8,key.p9,key.p10,key.p11,key.p12);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7, Parm8 p8, Parm9 p9, Parm10 p10,
Parm11 p11, Parm12 p12, Parm13 p13)
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7,key.p8,key.p9,key.p10,key.p11,key.p12
,key.p13);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7, Parm8 p8, Parm9 p9, Parm10 p10,
Parm11 p11, Parm12 p12, Parm13 p13, Parm14 p14)
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7,key.p8,key.p9,key.p10,key.p11,key.p12
,key.p13,key.p14);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
ProductReturn CreateObject(const IdentifierType &id,
Parm1 p1, Parm2 p2, Parm3 p3, Parm4 p4, Parm5 p5,
Parm6 p6, Parm7 p7, Parm8 p8, Parm9 p9, Parm10 p10,
Parm11 p11, Parm12 p12, Parm13 p13, Parm14 p14, Parm15 p15)
{
MyKey key(id,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15);
AbstractProduct *pProduct(getPointerToObjectInContainer(getContainerFromKey(key)));
if(shouldCreateObject(pProduct))
{
pProduct = factory.CreateObject(key.id,key.p1,key.p2,key.p3
,key.p4,key.p5,key.p6,key.p7,key.p8,key.p9,key.p10,key.p11,key.p12
,key.p13,key.p14,key.p15);
onCreate(pProduct);
}
onFetch(pProduct);
providedObjects[pProduct] = key;
return NP::encapsulate(pProduct);
}
/// Use this function to release the object
/**
* if execution brakes in this function then you tried
* to release an object that wasn't provided by this Cache
* ... which is bad :-)
*/
void ReleaseObject(ProductReturn &object)
{
AbstractProduct *pProduct(NP::release(object));
typename FetchedObjToKeyMap::iterator itr = providedObjects.find(pProduct);
if(itr == providedObjects.end())
throw CacheException();
onRelease(pProduct);
ReleaseObjectFromContainer(getContainerFromKey((*itr).second), pProduct);
providedObjects.erase(itr);
}
/// display the cache configuration
void displayCacheType()
{
using namespace std;
cout << "############################" << endl;
cout << "## Cache configuration" << endl;
cout << "## + Encapsulation " << NP::name() << endl;
cout << "## + Creating " << CP::name() << endl;
cout << "## + Eviction " << EP::name() << endl;
cout << "## + Statistics " << SP::name() << endl;
cout << "############################" << endl;
}
};
} // namespace Loki
#endif // end file guardian
| 13,597 |
2,044 | package com.sina.util.dnscache.dnsp.impl;
import com.sina.util.dnscache.dnsp.DnsConfig;
import com.sina.util.dnscache.dnsp.IDnsProvider;
import com.sina.util.dnscache.dnsp.impl.UdpDns.UdnDnsClient.UdpDnsInfo;
import com.sina.util.dnscache.model.HttpDnsPack;
import com.sina.util.dnscache.net.networktype.NetworkManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
public class UdpDns implements IDnsProvider {
@Override
public HttpDnsPack requestDns(String domain) {
try {
UdpDnsInfo info = UdnDnsClient.query(DnsConfig.UDPDNS_SERVER_API, domain);
if (null != info && info.ips.length > 0) {
HttpDnsPack dnsPack = new HttpDnsPack();
String IPArr[] = info.ips;
String TTL = String.valueOf(info.ttl);
dnsPack.rawResult = "domain : " + domain + "\n" + info.toString();
dnsPack.domain = domain;
dnsPack.device_ip = NetworkManager.Util.getLocalIpAddress();
dnsPack.device_sp = NetworkManager.getInstance().getSPID();
dnsPack.dns = new HttpDnsPack.IP[IPArr.length];
for (int i = 0; i < IPArr.length; i++) {
dnsPack.dns[i] = new HttpDnsPack.IP();
dnsPack.dns[i].ip = IPArr[i];
dnsPack.dns[i].ttl = TTL;
dnsPack.dns[i].priority = "0";
}
return dnsPack;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static class UdnDnsClient {
private final static int TIME_OUT = 2000;
private final static int PORT = 53;
private final static int BUF_SIZE = 1024;
static class UdpDnsInfo {
public int ttl;
public String[] ips;
@Override
public String toString() {
StringBuilder info = new StringBuilder();
info.append("ttl : " + ttl + "\n");
info.append("ipArray : ");
if (null != ips) {
for (String ip : ips) {
info.append(ip + ",");
}
} else {
info.append("null ");
}
return info.toString();
}
}
private static UdpDnsInfo query(String dnsServerIP, String domainName) throws SocketTimeoutException, IOException {
UdpDnsInfo info = new UdpDnsInfo();
DatagramSocket socket = new DatagramSocket(0);
socket.setSoTimeout(TIME_OUT);
ByteArrayOutputStream outBuf = new ByteArrayOutputStream(BUF_SIZE);
DataOutputStream output = new DataOutputStream(outBuf);
encodeDNSMessage(output, domainName);
InetAddress host = InetAddress.getByName(dnsServerIP);
DatagramPacket request = new DatagramPacket(outBuf.toByteArray(), outBuf.size(), host, PORT);
socket.send(request);
byte[] inBuf = new byte[BUF_SIZE];
ByteArrayInputStream inBufArray = new ByteArrayInputStream(inBuf);
DataInputStream input = new DataInputStream(inBufArray);
DatagramPacket response = new DatagramPacket(inBuf, inBuf.length);
socket.receive(response);
decodeDNSMessage(input, info);
socket.close();
return info;
}
private static void encodeDNSMessage(DataOutputStream output, String domainName) throws IOException {
// transaction id
output.writeShort(1);
// flags
output.writeShort(0x100);
// number of queries
output.writeShort(1);
// answer, auth, other
output.writeShort(0);
output.writeShort(0);
output.writeShort(0);
encodeDomainName(output, domainName);
// query type
output.writeShort(1);
// query class
output.writeShort(1);
output.flush();
}
private static void encodeDomainName(DataOutputStream output, String domainName) throws IOException {
for (String label : domainName.split("\\.")) {
output.writeByte((byte) label.length());
output.write(label.getBytes());
}
output.writeByte(0);
}
private static void decodeDNSMessage(DataInputStream input, UdpDnsInfo info) throws IOException {
// header
// transaction id
input.skip(2);
// flags
input.skip(2);
// number of queries
input.skip(2);
// answer, auth, other
short numberOfAnswer = input.readShort();
input.skip(2);
input.skip(2);
// question record
skipDomainName(input);
// query type
input.skip(2);
// query class
input.skip(2);
// answer records
for (int i = 0; i < numberOfAnswer; i++) {
input.mark(1);
byte ahead = input.readByte();
input.reset();
if ((ahead & 0xc0) == 0xc0) {
// compressed name
input.skip(2);
} else {
skipDomainName(input);
}
// query type
short type = input.readShort();
// query class
input.skip(2);
// ttl
int ttl = input.readInt();
info.ttl = ttl;
short addrLen = input.readShort();
info.ips = new String[1];
if (type == 1 && addrLen == 4) {
int addr = input.readInt();
info.ips[0] = (longToIp(addr));
} else {
input.skip(addrLen);
}
}
}
private static void skipDomainName(DataInputStream input) throws IOException {
byte labelLength = 0;
do {
labelLength = input.readByte();
input.skip(labelLength);
} while (labelLength != 0);
}
private static String longToIp(long ip) {
return ((ip >> 24) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + (ip & 0xFF);
}
}
@Override
public boolean isActivate() {
return DnsConfig.enableUdpDns;
}
@Override
public String getServerApi() {
return DnsConfig.UDPDNS_SERVER_API;
}
@Override
public int getPriority() {
return 7;
}
}
| 3,576 |
435 | <filename>pybay-2017/videos/christopher-beacham-python-debugging-with-pudb-pybay2017.json
{
"description": "When tracking down a tricky bug, tools are everything. I'll demonstrate three useful debugging tools and we'll see how we can use them to find bugs, whether they are in networking, logic, or performance.\n\n**Abstract**\n\nStop using print statements forever! You'll learn how to use these tools: PUDB - an interactive, ncurses debugger Charles - a web debugging proxy cProfile - python's built-in profiling library RunSnakeRun and SnakeViz - Tool for visualizing profile output I'll also talk about the process of debugging and profiling, common error patterns and how to use your time most efficiently.\n\n**Bio**\n\n<NAME> (aka <NAME>) is a python developer and Senior Software Engineer at Hipmunk. She also does performance, sewing, sculpture and painting in her free time, and is a frequent sight at the Noisebridge Hackerspace, where this talk was first delivered.",
"language": "eng",
"recorded": "2017-08-13",
"related_urls": [
{
"label": "talk slides",
"url": "https://speakerdeck.com/pybay/2017-python-debugging-with-pudb"
}
],
"speakers": [
"<NAME>"
],
"thumbnail_url": "https://i.ytimg.com/vi/mbdYATn7h6Q/hqdefault.jpg",
"title": "Python Debugging with PUDB",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=mbdYATn7h6Q"
}
]
}
| 463 |
589 | package rocks.inspectit.ui.rcp.handlers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.progress.IProgressConstants;
import rocks.inspectit.shared.all.exception.BusinessException;
import rocks.inspectit.shared.all.serializer.SerializationException;
import rocks.inspectit.shared.cs.storage.label.AbstractStorageLabel;
import rocks.inspectit.shared.cs.storage.label.type.impl.ExploredByLabelType;
import rocks.inspectit.ui.rcp.InspectIT;
import rocks.inspectit.ui.rcp.InspectITImages;
import rocks.inspectit.ui.rcp.provider.IStorageDataProvider;
import rocks.inspectit.ui.rcp.repository.CmrRepositoryDefinition.OnlineStatus;
/**
* Handler for deleting a Storage. Handler will inform the user about the users who have mounted the
* storage that is about to be deleted.
*
* @author <NAME>
*
*/
public class DeleteStorageHandler extends AbstractHandler implements IHandler {
/**
* {@inheritDoc}
*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ISelection selection = HandlerUtil.getCurrentSelection(event);
if (selection instanceof StructuredSelection) {
Iterator<?> it = ((StructuredSelection) selection).iterator();
final List<IStorageDataProvider> storagesToDelete = new ArrayList<>();
Set<AbstractStorageLabel<String>> exploredBySet = new HashSet<>();
boolean confirmed = false;
while (it.hasNext()) {
Object nextObject = it.next();
if (nextObject instanceof IStorageDataProvider) {
storagesToDelete.add((IStorageDataProvider) nextObject);
exploredBySet.addAll(((IStorageDataProvider) nextObject).getStorageData().getLabels(new ExploredByLabelType()));
}
}
if (!storagesToDelete.isEmpty()) {
StringBuffer confirmText = new StringBuffer(90);
final boolean plural = storagesToDelete.size() > 1;
if (!plural) {
confirmText.append("Are you sure you want to delete the selected storage? ");
if (!exploredBySet.isEmpty()) {
confirmText.append("Note that the storage was (and still could be) explored by following users: ");
}
} else {
confirmText.append("Are you sure you want to delete the " + storagesToDelete.size() + " selected storages? ");
if (!exploredBySet.isEmpty()) {
confirmText.append("Note that the storages were (and still could be) explored by following users: ");
}
}
if (!exploredBySet.isEmpty()) {
for (AbstractStorageLabel<String> exploredByLabel : exploredBySet) {
confirmText.append("\n * ");
confirmText.append(exploredByLabel.getValue());
}
}
MessageBox confirmDelete = new MessageBox(HandlerUtil.getActiveShell(event), SWT.OK | SWT.CANCEL | SWT.ICON_QUESTION);
confirmDelete.setText("Confirm Delete");
confirmDelete.setMessage(confirmText.toString());
confirmed = SWT.OK == confirmDelete.open();
if (confirmed) {
Job deleteStorageJob = new Job("Delete Storage Job") {
@Override
protected IStatus run(IProgressMonitor monitor) {
List<Status> statuses = new ArrayList<>();
for (final IStorageDataProvider storageDataProvider : storagesToDelete) {
if (storageDataProvider.getCmrRepositoryDefinition().getOnlineStatus() != OnlineStatus.OFFLINE) {
try {
storageDataProvider.getCmrRepositoryDefinition().getStorageService().deleteStorage(storageDataProvider.getStorageData());
InspectIT.getDefault().getInspectITStorageManager().storageRemotelyDeleted(storageDataProvider.getStorageData());
} catch (final BusinessException e) {
String name = storageDataProvider.getStorageData().getName();
statuses.add(new Status(IStatus.ERROR, InspectIT.ID, "Storage '" + name + "' could not be successfully deleted from CMR.", e));
} catch (final SerializationException | IOException e) {
String name = storageDataProvider.getStorageData().getName();
statuses.add(new Status(IStatus.ERROR, InspectIT.ID, "Local data for storage '" + name + "' was not cleared successfully.", e));
}
} else {
String name = storageDataProvider.getStorageData().getName();
statuses.add(new Status(IStatus.WARNING, InspectIT.ID, "Storage '" + name + "' can not be deleted, because CMR where it is located is offline."));
}
}
if (CollectionUtils.isNotEmpty(statuses)) {
if (1 == statuses.size()) {
return statuses.iterator().next();
} else {
return new MultiStatus(InspectIT.ID, IStatus.OK, statuses.toArray(new Status[statuses.size()]), "Delete of several storages failed.", null);
}
} else {
return Status.OK_STATUS;
}
}
};
deleteStorageJob.setUser(true);
deleteStorageJob.setProperty(IProgressConstants.ICON_PROPERTY, InspectIT.getDefault().getImageDescriptor(InspectITImages.IMG_DELETE));
deleteStorageJob.schedule();
}
}
}
return null;
}
}
| 2,056 |
347 |
#include "str.h"
#include <stddef.h>
int isspace(int c) {
switch (c) {
case ' ':
case '\r':
case '\n':
case '\t':
case '\v':
case '\f':
return 1;
default:
return 0;
}
}
int mini_sprintf(char * str, const char * format, ...) {
va_list args;
va_start(args, format);
return mini_vsprintf(str, format, args);
}
int mini_vsprintf(char * str, const char * format, va_list args) {
char * pos = str;
while (*format != 0) {
switch (*format) {
case '\\':
format++;
switch (*format) {
case 'n':
*pos = '\n';
pos++;
break;
case 'r':
*pos = '\r';
pos++;
break;
case '\0':
*pos = '\\';
pos++;
goto end;
default:
pos[0] = '\\';
pos[1] = *format;
pos += 2;
break;
}
break;
case '%':
format++;
switch (*format) {
case 'c': {
int c = va_arg(args, int);
*pos = c;
pos++;
break;
}
case 's': {
const char * subtext = va_arg(args, const char *);
while (*subtext != '\0') {
*pos = *subtext;
pos++;
subtext++;
}
break;
}
case 'd': {
int val = va_arg(args, int);
if (val == 0) {
*pos = '0';
pos++;
} else {
if (val < 0) {
*pos = '-';
pos++;
}
// Calculate digits backwards
char digits[10];
int digpos = 0;
do {
digits[digpos] = '0' + val % 10;
val = val / 10;
digpos++;
} while (val != 0);
// And copy them now also backwards
while (digpos != 0) {
digpos--;
*pos = digits[digpos];
pos++;
}
}
break;
}
case 'x': {
char c;
uint32_t val = va_arg(args, uint32_t);
for (int i = 28; i >= 0; i -= 4) {
c = (val >> i) & 0xF;
if (c < 10) {
c += '0';
} else {
c += 'A' - 0xA;
}
*pos = c;
pos++;
}
break;
}
case '\0':
*pos = '\\';
pos++;
goto end;
default:
pos[0] = '%';
pos[1] = *format;
pos += 2;
break;
}
break;
default:
*pos = *format;
pos++;
break;
}
format++;
}
end:
*pos = '\0';
return pos - str;
}
// The BIOS has already this function but for clearing the console's RAM it's unbearably slow.
void bzero(void * start, uint32_t len) {
uint8_t * bytes = (uint8_t *) start;
while (len) {
*bytes = 0;
bytes++;
len--;
}
}
| 1,452 |
4,200 | package com.dtolabs.rundeck.net.api.util;
import okhttp3.Interceptor;
import okhttp3.Response;
import java.io.IOException;
/**
* Send a header value
*/
public class StaticHeaderInterceptor implements Interceptor {
final String name;
final String value;
public StaticHeaderInterceptor(final String name, final String value) {
this.name = name;
this.value = value;
}
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
return chain.proceed(chain.request().newBuilder().header(name, value).build());
}
} | 197 |
681 | #include "driver2.h"
#include "replays.h"
#include "map.h"
#include "spool.h"
#include "system.h"
#include "cutscene.h"
#include "players.h"
#include "glaunch.h"
#include "mission.h"
#include "director.h"
#include "camera.h"
#include "civ_ai.h"
#include "cutrecorder.h"
char AnalogueUnpack[16] = {
0, -51, -63, -75, -87, -99, -111, -123,
0, 51, 63, 75, 87, 99, 111, 123
};
int gOutOfTape = 0;
REPLAY_PARAMETER_BLOCK *ReplayParameterPtr = NULL;
REPLAY_STREAM ReplayStreams[8];
int NumReplayStreams = 1;
char *ReplayStart;
char *replayptr = NULL;
int ReplaySize = 0;
int PingBufferPos = 0;
PING_PACKET *PingBuffer = NULL;
SXYPAIR *PlayerWayRecordPtr = NULL;
PLAYBACKCAMERA *PlaybackCamera = NULL;
int TimeToWay = 0;
short PlayerWaypoints = 0;
int way_distance = 0;
int gUseStoredPings = 1;
char ReplayMode = 0;
#define REPLAY_IDENT (('D' << 24) | ('2' << 16) | ('R' << 8) | 'P' )
// [D] [T]
void InitPadRecording(void)
{
char *bufferEnd;
int remain, cutsSize;
int i;
// initialize chases
cutsSize = CalcInGameCutsceneSize();
gOutOfTape = 0;
if (gLoadedReplay == 0 &&
CurrentGameMode != GAMEMODE_REPLAY &&
CurrentGameMode != GAMEMODE_DIRECTOR)
{
NumReplayStreams = 0;
ReplayStart = (char*)_replay_buffer;
ReplayParameterPtr = (REPLAY_PARAMETER_BLOCK *)ReplayStart;
PlayerWayRecordPtr = (SXYPAIR *)(ReplayParameterPtr + 1);
PlaybackCamera = (PLAYBACKCAMERA *)(PlayerWayRecordPtr + MAX_REPLAY_WAYPOINTS);
PingBuffer = (PING_PACKET *)(PlaybackCamera + MAX_REPLAY_CAMERAS);
setMem8((u_char*)PingBuffer, -1, sizeof(PING_PACKET) * MAX_REPLAY_PINGS);
replayptr = (char*)(PingBuffer + MAX_REPLAY_PINGS);
// FIXME: is that correct?
bufferEnd = replayptr-13380;
remain = (u_int)ReplayStart - (u_int)bufferEnd - cutsSize;
for (i = 0; i < NumPlayers; i++)
{
AllocateReplayStream(&ReplayStreams[i], remain / sizeof(PADRECORD) / NumPlayers);
NumReplayStreams++;
}
ReplaySize = (replayptr - ReplayStart);
}
else
{
// reset stream count as cutscene/chase can increase it
NumReplayStreams = NumPlayers;
for (i = 0; i < NumReplayStreams; i++)
{
ReplayStreams[i].playbackrun = 0;
ReplayStreams[i].PadRecordBuffer = ReplayStreams[i].InitialPadRecordBuffer;
}
}
TimeToWay = 150;
PlayerWaypoints = 0;
way_distance = 100;
InitDirectorVariables();
InitInGameCutsceneVariables();
}
// [D] [T]
int SaveReplayToBuffer(char *buffer)
{
REPLAY_STREAM_HEADER *sheader;
REPLAY_SAVE_HEADER *header;
if (buffer == NULL)
return 0x3644;
char* pt = buffer;
header = (REPLAY_SAVE_HEADER*)pt;
pt += sizeof(REPLAY_SAVE_HEADER);
header->magic = DRIVER2_REPLAY_MAGIC;
header->GameLevel = GameLevel;
header->GameType = GameType;
header->MissionNumber = gCurrentMissionNumber;
header->NumReplayStreams = NumReplayStreams - NumCutsceneStreams;
header->NumPlayers = NumPlayers;
header->CutsceneEvent = -1;
header->RandomChase = gRandomChase;
header->gCopDifficultyLevel = gCopDifficultyLevel;
header->ActiveCheats = ActiveCheats;
header->wantedCar[0] = wantedCar[0];
header->wantedCar[1] = wantedCar[1];
memcpy((u_char*)&header->SavedData, (u_char*)&MissionEndData, sizeof(MISSION_DATA));
// write each stream data
for (int i = 0; i < NumPlayers; i++)
{
sheader = (REPLAY_STREAM_HEADER *)pt;
pt += sizeof(REPLAY_STREAM_HEADER);
REPLAY_STREAM* srcStream = &ReplayStreams[i];
// copy source type
memcpy((u_char*)&sheader->SourceType, (u_char*)&srcStream->SourceType, sizeof(STREAM_SOURCE));
sheader->Size = srcStream->padCount * sizeof(PADRECORD); // srcStream->PadRecordBufferEnd - srcStream->InitialPadRecordBuffer;
sheader->Length = srcStream->length;
int size = (sheader->Size + sizeof(PADRECORD)) & -4;
// copy pad data to write buffer
memcpy((u_char*)pt, (u_char*)srcStream->InitialPadRecordBuffer, size);
pt += size;
}
memcpy((u_char*)pt, (u_char*)ReplayParameterPtr, sizeof(REPLAY_PARAMETER_BLOCK));
pt += sizeof(REPLAY_PARAMETER_BLOCK);
memcpy((u_char*)pt, (u_char*)PlayerWayRecordPtr, sizeof(SXYPAIR) * MAX_REPLAY_WAYPOINTS);
pt += sizeof(SXYPAIR) * MAX_REPLAY_WAYPOINTS;
memcpy((u_char*)pt, (u_char*)PlaybackCamera, sizeof(PLAYBACKCAMERA) * MAX_REPLAY_CAMERAS);
pt += sizeof(PLAYBACKCAMERA) * MAX_REPLAY_CAMERAS;
memcpy((u_char*)pt, (u_char*)PingBuffer, sizeof(PING_PACKET) * MAX_REPLAY_PINGS);
pt += sizeof(PING_PACKET) * MAX_REPLAY_PINGS;
// [A] is that ever valid?
if (gHaveStoredData)
{
header->HaveStoredData = 0x91827364; // -0x6e7d8c9c
memcpy((u_char*)pt, (u_char*)&MissionStartData, sizeof(MISSION_DATA));
}
#ifdef PSX
return 0x3644; // size?
#else
return pt - buffer;
#endif
}
// [D] [T]
int LoadReplayFromBuffer(char *buffer)
{
REPLAY_SAVE_HEADER *header;
REPLAY_STREAM_HEADER *sheader;
char* pt = buffer;
header = (REPLAY_SAVE_HEADER*)pt;
if (header->magic != DRIVER2_REPLAY_MAGIC)
return 0;
ReplayStart = replayptr = (char*)_replay_buffer;
GameLevel = header->GameLevel;
GameType = (GAMETYPE)header->GameType;
gCurrentMissionNumber = header->MissionNumber;
NumReplayStreams = header->NumReplayStreams;
NumPlayers = header->NumPlayers;
gRandomChase = header->RandomChase;
CutsceneEventTrigger = header->CutsceneEvent;
gCopDifficultyLevel = header->gCopDifficultyLevel;
ActiveCheats = header->ActiveCheats; // TODO: restore old value
wantedCar[0] = header->wantedCar[0];
wantedCar[1] = header->wantedCar[1];
memcpy((u_char*)&MissionEndData, (u_char*)&header->SavedData, sizeof(MISSION_DATA));
pt = (char*)(header+1);
int maxLength = 0;
for (int i = 0; i < NumReplayStreams; i++)
{
sheader = (REPLAY_STREAM_HEADER *)pt;
pt += sizeof(REPLAY_STREAM_HEADER);
REPLAY_STREAM* destStream = &ReplayStreams[i];
// copy source type
memcpy((u_char*)&destStream->SourceType, (u_char*)&sheader->SourceType, sizeof(STREAM_SOURCE));
int size = (sheader->Size + sizeof(PADRECORD)) & -4;
// init buffers
destStream->InitialPadRecordBuffer = (PADRECORD*)replayptr;
destStream->PadRecordBuffer = (PADRECORD*)replayptr;
destStream->PadRecordBufferEnd = (PADRECORD*)(replayptr + size);
destStream->playbackrun = 0;
destStream->padCount = sheader->Size / sizeof(PADRECORD);
// copy pad data and advance buffer
memcpy((u_char*)replayptr, (u_char*)pt, size);
replayptr += size;
pt += size;
destStream->length = sheader->Length;
if (sheader->Length > maxLength)
maxLength = sheader->Length;
}
ReplayParameterPtr = (REPLAY_PARAMETER_BLOCK *)replayptr;
memcpy((u_char*)ReplayParameterPtr, (u_char*)pt, sizeof(REPLAY_PARAMETER_BLOCK));
pt += sizeof(REPLAY_PARAMETER_BLOCK);
PlayerWayRecordPtr = (SXYPAIR *)(ReplayParameterPtr + 1);
memcpy((u_char*)PlayerWayRecordPtr, (u_char*)pt, sizeof(SXYPAIR) * MAX_REPLAY_WAYPOINTS);
pt += sizeof(SXYPAIR) * MAX_REPLAY_WAYPOINTS;
PlaybackCamera = (PLAYBACKCAMERA *)(PlayerWayRecordPtr + MAX_REPLAY_WAYPOINTS);
memcpy((u_char*)PlaybackCamera, (u_char*)pt, sizeof(PLAYBACKCAMERA) * MAX_REPLAY_CAMERAS);
pt += sizeof(PLAYBACKCAMERA) * MAX_REPLAY_CAMERAS;
PingBufferPos = 0;
PingBuffer = (PING_PACKET *)(PlaybackCamera + MAX_REPLAY_CAMERAS);
memcpy((u_char*)PingBuffer, (u_char*)pt, sizeof(PING_PACKET) * MAX_REPLAY_PINGS);
pt += sizeof(PING_PACKET) * MAX_REPLAY_PINGS;
replayptr = (char*)(PingBuffer + MAX_REPLAY_PINGS);
if (header->HaveStoredData == 0x91827364) // -0x6e7d8c9c
{
memcpy((u_char*)&MissionStartData, (u_char*)pt, sizeof(MISSION_DATA));
gHaveStoredData = 1;
}
return 1;
}
#ifndef PSX
int LoadUserAttractReplay(int mission, int userId)
{
char customFilename[64];
if (userId >= 0 && userId < gNumUserChases)
{
sprintf(customFilename, "REPLAYS\\User\\%s\\ATTRACT.%d", gUserReplayFolderList[userId], mission);
if (FileExists(customFilename))
{
if (Loadfile(customFilename, (char*)_other_buffer))
return LoadReplayFromBuffer((char*)_other_buffer);
}
}
return 0;
}
#endif
// [D] [T]
int LoadAttractReplay(int mission)
{
char filename[32];
#ifndef PSX
int userId = -1;
// [A] REDRIVER2 PC - custom attract replays
if (gNumUserChases)
{
userId = rand() % (gNumUserChases + 1);
if (userId == gNumUserChases)
userId = -1;
}
if (LoadUserAttractReplay(mission, userId))
{
printInfo("Loaded custom attract replay (%d) by %s\n", mission, gUserReplayFolderList[userId]);
return 1;
}
#endif
sprintf(filename, "REPLAYS\\ATTRACT.%d", mission);
if (!FileExists(filename))
return 0;
if (!Loadfile(filename, (char*)_other_buffer))
return 0;
return LoadReplayFromBuffer((char*)_other_buffer);
}
// [D] [T]
char GetPingInfo(char *cookieCount)
{
char retCarId;
PING_PACKET *pp;
retCarId = -1;
if (PingBuffer && PingBufferPos < MAX_REPLAY_PINGS)
{
pp = &PingBuffer[PingBufferPos];
// accept only valid car pings
if (pp->frame != 0xFFFF)
{
if (CameraCnt - frameStart < pp->frame)
return -1;
retCarId = pp->carId;
*cookieCount = pp->cookieCount;
}
PingBufferPos++;
}
return retCarId;
}
// [A] returns 1 if can use ping buffer
int IsPingInfoAvailable()
{
if (!_CutRec_IsPlaying() && (gUseStoredPings == 0 || gInGameChaseActive == 0))// && gLoadedReplay == 0)
return 0;
return PingBuffer != NULL && PingBufferPos < MAX_REPLAY_PINGS;
}
// [D] [T]
int valid_region(int x, int z)
{
XYPAIR region_coords;
int region;
region_coords.x = (x >> 16) + regions_across / 2;
region_coords.y = (z >> 16) + regions_down / 2;
if (region_coords.x >= 0 && region_coords.x <= regions_across &&
region_coords.y >= 0 && region_coords.y <= regions_down)
{
region = region_coords.x + region_coords.y * regions_across;
if (region != regions_unpacked[0])
{
if (region == regions_unpacked[1])
return region + 1;
if (region == regions_unpacked[2])
return region + 1;
if (region != regions_unpacked[3])
return 0;
}
return region + 1;
}
return 0;
}
// [D] [T]
int Get(int stream, u_int *pt0)
{
REPLAY_STREAM* rstream;
if (stream < NumReplayStreams)
{
rstream = &ReplayStreams[stream];
if (rstream->PadRecordBuffer + 1 <= rstream->PadRecordBufferEnd)
{
u_int t0 = (rstream->PadRecordBuffer->pad << 8) | rstream->PadRecordBuffer->analogue;
*pt0 = t0;
if (rstream->playbackrun < rstream->PadRecordBuffer->run)
{
rstream->playbackrun++;
}
else
{
rstream->PadRecordBuffer++;
rstream->playbackrun = 0;
}
return 1;
}
}
*pt0 = 0x10;
return 0;
}
// [D] [T]
int Put(int stream, u_int*pt0)
{
REPLAY_STREAM *rstream;
u_int t0;
PADRECORD *padbuf;
rstream = &ReplayStreams[stream];
if (rstream->PadRecordBuffer + 1 >= rstream->PadRecordBufferEnd)
return 0;
padbuf = rstream->PadRecordBuffer;
t0 = *pt0;
if (CameraCnt != 0 && padbuf->run != 0xEE)
{
if (padbuf->pad == ((t0 >> 8) & 0xff) &&
padbuf->analogue == (t0 & 0xff) &&
padbuf->run != 143)
{
padbuf->run++;
return 1;
}
padbuf++;
padbuf->pad = (t0 >> 8) & 0xFF;
padbuf->analogue = t0 & 0xFF;
padbuf->run = 0;
rstream->PadRecordBuffer = padbuf;
rstream->padCount++;
return 1;
}
padbuf->pad = (t0 >> 8) & 0xFF;
padbuf->analogue = t0 & 0xFF;
padbuf->run = 0;
return 1;
}
// [D] [T]
int cjpPlay(int stream, u_int *ppad, char *psteer, char *ptype)
{
int ret;
int t1;
u_int t0;
#ifdef CUTSCENE_RECORDER
if (stream < 0)
stream = -stream;
#endif
ret = Get(stream, &t0);
t1 = (t0 >> 8) & 0xF;
*ppad = t0 & 0xF0FC;
if (t1 == 0)
{
*psteer = 0;
*ptype = 0;
}
else
{
*psteer = AnalogueUnpack[t1];
*ptype = 4;
}
return ret;
}
// [D] [T]
void cjpRecord(int stream, u_int *ppad, char *psteer, char *ptype)
{
int tmp;
int t1;
u_int t0;
if (stream > -1 && stream < NumReplayStreams)
{
RecordWaypoint();
if ((*ptype & 4U) == 0)
{
t1 = 0;
}
else
{
if (*psteer < -45)
{
tmp = -45 - *psteer >> 0x1f; // [A] still need to figure out this
t1 = (((-45 - *psteer) / 6 + tmp >> 1) - tmp) + 1;
}
else if (*psteer < 46)
{
t1 = 8;
}
else
{
tmp = *psteer - 45 >> 0x1f; // [A] still need to figure out this
t1 = (((*psteer - 45) / 6 + tmp >> 1) - tmp) + 9;
}
}
t0 = (t1 & 0xF) << 8 | *ppad & 0xF0FC;
if (Put(stream, &t0) == 0)
{
gOutOfTape = 1;
}
else if(NoPlayerControl == 0)
{
ClearCameras = 1;
if (ReplayMode != 3 && ReplayMode != 8)
{
ReplayStreams[stream].length = CameraCnt;
ReplayParameterPtr->RecordingEnd = CameraCnt;
}
}
t1 = (t0 >> 8) & 0xF;
if (t1 == 0)
{
*psteer = 0;
*ptype = 0;
}
else
{
*psteer = AnalogueUnpack[t1];
*ptype = 4;
}
*ppad = t0 & 0xF0FC;
}
}
// [D] [T]
void AllocateReplayStream(REPLAY_STREAM *stream, int maxpad)
{
stream->playbackrun = 0;
stream->length = 0;
stream->padCount = 0;
stream->InitialPadRecordBuffer = (PADRECORD*)replayptr;
stream->PadRecordBuffer = (PADRECORD*)replayptr;
stream->PadRecordBufferEnd = (PADRECORD *)(replayptr + maxpad * sizeof(PADRECORD));
if (NoPlayerControl == 0)
{
*replayptr = 0;
stream->InitialPadRecordBuffer->analogue = 0;
stream->InitialPadRecordBuffer->run = 238;
}
replayptr = (char *)(((u_int)replayptr + (maxpad+1) * sizeof(PADRECORD)) & -4);
}
// [D] [T]
void RecordWaypoint(void)
{
if (TimeToWay > 0)
{
TimeToWay--;
return;
}
if (PlayerWaypoints < MAX_REPLAY_WAYPOINTS)
{
TimeToWay = way_distance;
PlayerWayRecordPtr->x = (player[0].pos[0] >> 10);
PlayerWayRecordPtr->y = (player[0].pos[2] >> 10);
PlayerWayRecordPtr++;
PlayerWaypoints++;
}
}
| 5,757 |
501 | <reponame>QuESt-Calculator/pyscf
#!/usr/bin/env python
# Copyright 2014-2020 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from pyscf import scf, gto
from pyscf.eph import eph_fd, rhf
import numpy as np
import unittest
mol = gto.M()
mol.atom = [['O', [0.000000000000, -0.000000000775, 0.923671924285]],
['H', [-0.000000000000, -1.432564848017, 2.125164039823]],
['H', [0.000000000000, 1.432564848792, 2.125164035930]]]
mol.unit = 'Bohr'
mol.basis = 'sto3g'
mol.verbose=4
mol.build() # this is a pre-computed relaxed geometry
class KnownValues(unittest.TestCase):
def test_finite_diff_rhf_eph(self):
mf = scf.RHF(mol)
mf.conv_tol = 1e-16
mf.conv_tol_grad = 1e-10
mf.kernel()
grad = mf.nuc_grad_method().kernel()
self.assertTrue(abs(grad).max()<1e-5)
mat, omega = eph_fd.kernel(mf)
matmo, _ = eph_fd.kernel(mf, mo_rep=True)
myeph = rhf.EPH(mf)
eph, _ = myeph.kernel()
ephmo, _ = myeph.kernel(mo_rep=True)
for i in range(len(omega)):
self.assertTrue(min(np.linalg.norm(eph[i]-mat[i]),np.linalg.norm(eph[i]+mat[i]))<1e-5)
self.assertTrue(min(abs(eph[i]-mat[i]).max(), abs(eph[i]+mat[i]).max())<1e-5)
self.assertTrue(min(np.linalg.norm(ephmo[i]-matmo[i]),np.linalg.norm(ephmo[i]+matmo[i]))<1e-5)
self.assertTrue(min(abs(ephmo[i]-matmo[i]).max(), abs(ephmo[i]+matmo[i]).max())<1e-5)
if __name__ == '__main__':
print("Full Tests for RHF")
unittest.main()
| 939 |
704 | package com.java2nb.novel.home.feign;
import com.java2nb.novel.book.api.BookApi;
import com.java2nb.novel.home.feign.fallback.BookFeignFallback;
import org.springframework.cloud.openfeign.FeignClient;
/**
* 小说服务Feign客户端
* @author xiongxiaoyang
* @version 1.0
* @since 2020/5/28
*/
@FeignClient(name = "book-service",fallback = BookFeignFallback.class)
public interface BookFeignClient extends BookApi {
}
| 168 |
892 | <reponame>github/advisory-database<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-7w57-fc78-9x64",
"modified": "2022-05-13T01:05:37Z",
"published": "2022-05-13T01:05:37Z",
"aliases": [
"CVE-2019-0038"
],
"details": "Crafted packets destined to the management interface (fxp0) of an SRX340 or SRX345 services gateway may create a denial of service (DoS) condition due to buffer space exhaustion. This issue only affects the SRX340 and SRX345 services gateways. No other products or platforms are affected by this vulnerability. Affected releases are Juniper Networks Junos OS: 15.1X49 versions prior to 15.1X49-D160 on SRX340/SRX345; 17.3 on SRX340/SRX345; 17.4 versions prior to 17.4R2-S3, 17.4R3 on SRX340/SRX345; 18.1 versions prior to 18.1R3-S1 on SRX340/SRX345; 18.2 versions prior to 18.2R2 on SRX340/SRX345; 18.3 versions prior to 18.3R1-S2, 18.3R2 on SRX340/SRX345. This issue does not affect Junos OS releases prior to 15.1X49 on any platform.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:A/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-0038"
},
{
"type": "WEB",
"url": "https://kb.juniper.net/JSA10927"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/107873"
}
],
"database_specific": {
"cwe_ids": [
"CWE-770"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 680 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Burgaronne","circ":"4ème circonscription","dpt":"Pyrénées-Atlantiques","inscrits":79,"abs":31,"votants":48,"blancs":10,"nuls":3,"exp":35,"res":[{"nuance":"DVD","nom":"<NAME>","voix":22},{"nuance":"REM","nom":"<NAME>","voix":13}]} | 123 |
4,297 | /*
* 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.dolphinscheduler.service.alert;
import org.apache.dolphinscheduler.common.enums.CommandType;
import org.apache.dolphinscheduler.common.enums.Flag;
import org.apache.dolphinscheduler.common.enums.WarningType;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.dao.AlertDao;
import org.apache.dolphinscheduler.dao.entity.Alert;
import org.apache.dolphinscheduler.dao.entity.ProcessAlertContent;
import org.apache.dolphinscheduler.dao.entity.ProcessDefinition;
import org.apache.dolphinscheduler.dao.entity.ProcessInstance;
import org.apache.dolphinscheduler.dao.entity.ProjectUser;
import org.apache.dolphinscheduler.dao.entity.TaskDefinition;
import org.apache.dolphinscheduler.dao.entity.TaskInstance;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* process alert manager
*/
@Component
public class ProcessAlertManager {
/**
* logger of AlertManager
*/
private static final Logger logger = LoggerFactory.getLogger(ProcessAlertManager.class);
/**
* alert dao
*/
@Autowired
private AlertDao alertDao;
/**
* command type convert chinese
*
* @param commandType command type
* @return command name
*/
private String getCommandCnName(CommandType commandType) {
switch (commandType) {
case RECOVER_TOLERANCE_FAULT_PROCESS:
return "recover tolerance fault process";
case RECOVER_SUSPENDED_PROCESS:
return "recover suspended process";
case START_CURRENT_TASK_PROCESS:
return "start current task process";
case START_FAILURE_TASK_PROCESS:
return "start failure task process";
case START_PROCESS:
return "start process";
case REPEAT_RUNNING:
return "repeat running";
case SCHEDULER:
return "scheduler";
case COMPLEMENT_DATA:
return "complement data";
case PAUSE:
return "pause";
case STOP:
return "stop";
default:
return "unknown type";
}
}
/**
* get process instance content
*
* @param processInstance process instance
* @param taskInstances task instance list
* @return process instance format content
*/
public String getContentProcessInstance(ProcessInstance processInstance,
List<TaskInstance> taskInstances,
ProjectUser projectUser) {
String res = "";
if (processInstance.getState().typeIsSuccess()) {
List<ProcessAlertContent> successTaskList = new ArrayList<>(1);
ProcessAlertContent processAlertContent = ProcessAlertContent.newBuilder()
.projectId(projectUser.getProjectId())
.projectName(projectUser.getProjectName())
.owner(projectUser.getUserName())
.processId(processInstance.getId())
.processName(processInstance.getName())
.processType(processInstance.getCommandType())
.processState(processInstance.getState())
.recovery(processInstance.getRecovery())
.runTimes(processInstance.getRunTimes())
.processStartTime(processInstance.getStartTime())
.processEndTime(processInstance.getEndTime())
.processHost(processInstance.getHost())
.build();
successTaskList.add(processAlertContent);
res = JSONUtils.toJsonString(successTaskList);
} else if (processInstance.getState().typeIsFailure()) {
List<ProcessAlertContent> failedTaskList = new ArrayList<>();
for (TaskInstance task : taskInstances) {
if (task.getState().typeIsSuccess()) {
continue;
}
ProcessAlertContent processAlertContent = ProcessAlertContent.newBuilder()
.projectId(projectUser.getProjectId())
.projectName(projectUser.getProjectName())
.owner(projectUser.getUserName())
.processId(processInstance.getId())
.processName(processInstance.getName())
.taskId(task.getId())
.taskName(task.getName())
.taskType(task.getTaskType())
.taskState(task.getState())
.taskStartTime(task.getStartTime())
.taskEndTime(task.getEndTime())
.taskHost(task.getHost())
.logPath(task.getLogPath())
.build();
failedTaskList.add(processAlertContent);
}
res = JSONUtils.toJsonString(failedTaskList);
}
return res;
}
/**
* getting worker fault tolerant content
*
* @param processInstance process instance
* @param toleranceTaskList tolerance task list
* @return worker tolerance content
*/
private String getWorkerToleranceContent(ProcessInstance processInstance, List<TaskInstance> toleranceTaskList) {
List<ProcessAlertContent> toleranceTaskInstanceList = new ArrayList<>();
for (TaskInstance taskInstance : toleranceTaskList) {
ProcessAlertContent processAlertContent = ProcessAlertContent.newBuilder()
.processName(processInstance.getName())
.taskName(taskInstance.getName())
.taskHost(taskInstance.getHost())
.retryTimes(taskInstance.getRetryTimes())
.build();
toleranceTaskInstanceList.add(processAlertContent);
}
return JSONUtils.toJsonString(toleranceTaskInstanceList);
}
/**
* send worker alert fault tolerance
*
* @param processInstance process instance
* @param toleranceTaskList tolerance task list
*/
public void sendAlertWorkerToleranceFault(ProcessInstance processInstance, List<TaskInstance> toleranceTaskList) {
try {
Alert alert = new Alert();
alert.setTitle("worker fault tolerance");
String content = getWorkerToleranceContent(processInstance, toleranceTaskList);
alert.setContent(content);
alert.setCreateTime(new Date());
alert.setAlertGroupId(processInstance.getWarningGroupId() == null ? 1 : processInstance.getWarningGroupId());
alertDao.addAlert(alert);
logger.info("add alert to db , alert : {}", alert);
} catch (Exception e) {
logger.error("send alert failed:{} ", e.getMessage());
}
}
/**
* send process instance alert
*
* @param processInstance process instance
* @param taskInstances task instance list
*/
public void sendAlertProcessInstance(ProcessInstance processInstance,
List<TaskInstance> taskInstances,
ProjectUser projectUser) {
if (Flag.YES == processInstance.getIsSubProcess()) {
return;
}
boolean sendWarnning = false;
WarningType warningType = processInstance.getWarningType();
switch (warningType) {
case ALL:
if (processInstance.getState().typeIsFinished()) {
sendWarnning = true;
}
break;
case SUCCESS:
if (processInstance.getState().typeIsSuccess()) {
sendWarnning = true;
}
break;
case FAILURE:
if (processInstance.getState().typeIsFailure()) {
sendWarnning = true;
}
break;
default:
}
if (!sendWarnning) {
return;
}
Alert alert = new Alert();
String cmdName = getCommandCnName(processInstance.getCommandType());
String success = processInstance.getState().typeIsSuccess() ? "success" : "failed";
alert.setTitle(cmdName + " " + success);
String content = getContentProcessInstance(processInstance, taskInstances,projectUser);
alert.setContent(content);
alert.setAlertGroupId(processInstance.getWarningGroupId());
alert.setCreateTime(new Date());
alertDao.addAlert(alert);
logger.info("add alert to db , alert: {}", alert);
}
/**
* send process timeout alert
*
* @param processInstance process instance
* @param processDefinition process definition
*/
public void sendProcessTimeoutAlert(ProcessInstance processInstance, ProcessDefinition processDefinition) {
alertDao.sendProcessTimeoutAlert(processInstance, processDefinition);
}
public void sendTaskTimeoutAlert(ProcessInstance processInstance, TaskInstance taskInstance, TaskDefinition taskDefinition) {
alertDao.sendTaskTimeoutAlert(processInstance.getWarningGroupId(), processInstance.getId(),processInstance.getName(),
taskInstance.getId(), taskInstance.getName());
}
}
| 4,411 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "enumattributesaver.h"
#include "i_enum_store_dictionary.h"
#include "iattributesavetarget.h"
#include <vespa/searchlib/util/bufferwriter.h>
#include <vespa/vespalib/datastore/unique_store_enumerator.hpp>
namespace search {
EnumAttributeSaver::
EnumAttributeSaver(const IEnumStore &enumStore)
: _enumStore(enumStore),
_enumerator(enumStore.make_enumerator())
{
}
EnumAttributeSaver::~EnumAttributeSaver()
{
}
void
EnumAttributeSaver::writeUdat(IAttributeSaveTarget &saveTarget)
{
if (saveTarget.getEnumerated()) {
auto udatWriter = saveTarget.udatWriter().allocBufferWriter();
_enumerator->foreach_key([&](vespalib::datastore::EntryRef idx){
_enumStore.write_value(*udatWriter, idx);
});
udatWriter->flush();
}
}
} // namespace search
namespace vespalib::datastore {
template class UniqueStoreEnumerator<search::IEnumStore::InternalIndex>;
}
| 390 |
2,151 | <gh_stars>1000+
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/public/cpp/menu_utils.h"
#include <utility>
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/menu_model.h"
#include "ui/base/models/menu_separator_types.h"
#include "ui/base/models/simple_menu_model.h"
using base::ASCIIToUTF16;
namespace ash {
namespace menu_utils {
using MenuModelList = std::vector<std::unique_ptr<ui::SimpleMenuModel>>;
class MenuUtilsTest : public testing::Test,
public ui::SimpleMenuModel::Delegate {
public:
MenuUtilsTest() {}
~MenuUtilsTest() override {}
// testing::Test overrides:
void SetUp() override {
menu_model_ = std::make_unique<ui::SimpleMenuModel>(this);
}
protected:
ui::SimpleMenuModel* root_menu() { return menu_model_.get(); }
MenuModelList* submenus() { return &submenu_models_; }
ui::SimpleMenuModel* CreateSubmenu() {
std::unique_ptr<ui::SimpleMenuModel> submenu =
std::make_unique<ui::SimpleMenuModel>(this);
ui::SimpleMenuModel* submenu_ptr = submenu.get();
submenu_models_.push_back(std::move(submenu));
return submenu_ptr;
}
bool IsCommandIdChecked(int command_id) const override {
// Assume that we have a checked item in every 3 items.
return command_id % 3 == 0;
}
bool IsCommandIdEnabled(int command_id) const override {
// Assume that we have a enabled item in every 4 items.
return command_id % 4 == 0;
}
void ExecuteCommand(int command_id, int event_flags) override {}
void CheckMenuItemsMatched(const MenuItemList& mojo_menu,
const ui::MenuModel* menu) {
EXPECT_EQ(mojo_menu.size(), static_cast<size_t>(menu->GetItemCount()));
for (size_t i = 0; i < mojo_menu.size(); i++) {
VLOG(1) << "Checking item at " << i;
mojom::MenuItem* mojo_item = mojo_menu[i].get();
EXPECT_EQ(mojo_item->type, menu->GetTypeAt(i));
EXPECT_EQ(mojo_item->command_id, menu->GetCommandIdAt(i));
EXPECT_EQ(mojo_item->label, menu->GetLabelAt(i));
if (mojo_item->type == ui::MenuModel::TYPE_SUBMENU) {
VLOG(1) << "It's a submenu, let's do a recursion.";
CheckMenuItemsMatched(mojo_item->submenu.value(),
menu->GetSubmenuModelAt(i));
continue;
}
EXPECT_EQ(mojo_item->enabled, menu->IsEnabledAt(i));
EXPECT_EQ(mojo_item->checked, menu->IsItemCheckedAt(i));
EXPECT_EQ(mojo_item->radio_group_id, menu->GetGroupIdAt(i));
}
}
private:
std::unique_ptr<ui::SimpleMenuModel> menu_model_;
MenuModelList submenu_models_;
DISALLOW_COPY_AND_ASSIGN(MenuUtilsTest);
};
TEST_F(MenuUtilsTest, Basic) {
ui::SimpleMenuModel* menu = root_menu();
// Populates items into |menu| for testing.
int command_id = 0;
menu->AddItem(command_id++, ASCIIToUTF16("Item0"));
menu->AddItem(command_id++, ASCIIToUTF16("Item1"));
menu->AddSeparator(ui::NORMAL_SEPARATOR);
menu->AddCheckItem(command_id++, ASCIIToUTF16("CheckItem0"));
menu->AddCheckItem(command_id++, ASCIIToUTF16("CheckItem1"));
menu->AddRadioItem(command_id++, ASCIIToUTF16("RadioItem0"),
0 /* group_id */);
menu->AddRadioItem(command_id++, ASCIIToUTF16("RadioItem1"),
0 /* group_id */);
// Creates a submenu.
ui::SimpleMenuModel* submenu = CreateSubmenu();
submenu->AddItem(command_id++, ASCIIToUTF16("SubMenu-Item0"));
submenu->AddItem(command_id++, ASCIIToUTF16("SubMenu-Item1"));
submenu->AddSeparator(ui::NORMAL_SEPARATOR);
submenu->AddCheckItem(command_id++, ASCIIToUTF16("SubMenu-CheckItem0"));
submenu->AddCheckItem(command_id++, ASCIIToUTF16("SubMenu-CheckItem1"));
submenu->AddRadioItem(command_id++, ASCIIToUTF16("SubMenu-RadioItem0"),
1 /* group_id */);
submenu->AddRadioItem(command_id++, ASCIIToUTF16("SubMenu-RadioItem1"),
1 /* group_id */);
menu->AddSubMenu(command_id++, ASCIIToUTF16("SubMenu"), submenu);
// Converts the menu into mojo format.
MenuItemList mojo_menu_items = GetMojoMenuItemsFromModel(menu);
CheckMenuItemsMatched(mojo_menu_items, menu);
// Converts backwards.
ui::SimpleMenuModel new_menu(this);
SubmenuList new_submenus;
PopulateMenuFromMojoMenuItems(&new_menu, this, mojo_menu_items,
&new_submenus);
CheckMenuItemsMatched(mojo_menu_items, &new_menu);
// Tests |GetMenuItemByCommandId|.
for (int command_to_find = 0; command_to_find < command_id;
command_to_find++) {
// Gets the mojo item.
const mojom::MenuItemPtr& mojo_item =
GetMenuItemByCommandId(mojo_menu_items, command_to_find);
// Gets the item index with this command from the original root menu.
int index = menu->GetIndexOfCommandId(command_to_find);
ui::MenuModel* menu_to_find = menu;
if (index < 0) {
// We cannot find it from the original root menu. Then it should be in the
// submenu.
index = submenu->GetIndexOfCommandId(command_to_find);
EXPECT_LE(0, index);
menu_to_find = submenu;
}
// Checks whether they match.
EXPECT_EQ(mojo_item->type, menu_to_find->GetTypeAt(index));
EXPECT_EQ(mojo_item->command_id, menu_to_find->GetCommandIdAt(index));
EXPECT_EQ(mojo_item->label, menu_to_find->GetLabelAt(index));
EXPECT_EQ(mojo_item->enabled, menu_to_find->IsEnabledAt(index));
EXPECT_EQ(mojo_item->checked, menu_to_find->IsItemCheckedAt(index));
EXPECT_EQ(mojo_item->radio_group_id, menu_to_find->GetGroupIdAt(index));
}
// For unknown command ids, we'll get a singleton stub item.
const mojom::MenuItemPtr& item_not_found_1 =
GetMenuItemByCommandId(mojo_menu_items, command_id + 1);
const mojom::MenuItemPtr& item_not_found_2 =
GetMenuItemByCommandId(mojo_menu_items, command_id + 2);
EXPECT_EQ(item_not_found_1.get(), item_not_found_2.get());
}
} // namespace menu_utils
} // namespace ash
| 2,497 |
407 | <gh_stars>100-1000
/*
* Copyright (c) 2017-2019, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "priv/EngineAST.h"
#include "priv/Profile.h"
#include "priv/Tensor.h"
#include "ErrorMacros.h"
using std::endl;
namespace nvdla
{
namespace priv
{
void engine_ast::RubikNode::captureCanonicalParams()
{
}
/*
* Rubik engine has special requirement that its input and output channels
* should be aligned to: 16 (for fp16/int16) and 32 (for int8)
*/
Dims4 engine_ast::RubikNode::suggestSurfaceDims(surface::TensorSurfaceDesc* tsd)
{
NvDlaError e = NvDlaSuccess;
bool isSrcTSD = false;
bool isDstTSD = false;
Dims4 suggestedDims(-1,-1,-1,-1);
PROPAGATE_ERROR_FAIL( verifyEdgePorts() );
isSrcTSD = inputEdges()[0]->tensorSurfaceDesc() == tsd;
isDstTSD = outputEdges()[0]->tensorSurfaceDesc() == tsd;
if (!isSrcTSD && !isDstTSD)
{
ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD %s doesn't belong to %s", tsd->id().c_str(), name().c_str());
}
if (isSrcTSD)
{
Dims4 inSurfDims(-1,-1,-1,-1);
Edge* inEdge = inputEdges()[0];
Node* srcNode = graph()->upstreamNodes(inEdge).size() ? graph()->upstreamNodes(inEdge)[0] : NULL;
if (srcNode)
{
inSurfDims = srcNode->suggestSurfaceDims(inEdge->tensorSurfaceDesc());
}
suggestedDims.n = std::max<NvS32>(params().contractOpParams().inDims.n, inSurfDims.n);
suggestedDims.c = std::max<NvS32>(params().contractOpParams().inDims.c, inSurfDims.c);
suggestedDims.h = std::max<NvS32>(params().contractOpParams().inDims.h, inSurfDims.h);
suggestedDims.w = std::max<NvS32>(params().contractOpParams().inDims.w, inSurfDims.w);
// use this opportunity to update the contract op params if they seem outdated
if (suggestedDims != params().contractOpParams().inDims)
{
RubikEngineParams::ContractOpParams updatedContractOps = params().contractOpParams();
updatedContractOps.inDims = suggestedDims;
params().setContractOpParams(updatedContractOps);
}
}
else
{
suggestedDims.n = std::max<NvS32>(params().contractOpParams().outDims.n, tsd->dimensions().n);
suggestedDims.c = std::max<NvS32>(params().contractOpParams().outDims.c, tsd->dimensions().c);
suggestedDims.h = std::max<NvS32>(params().contractOpParams().outDims.h, tsd->dimensions().h);
suggestedDims.w = std::max<NvS32>(params().contractOpParams().outDims.w, tsd->dimensions().w);
// use this opportunity to update the contract op params if they seem outdated
if (suggestedDims != params().contractOpParams().outDims)
{
RubikEngineParams::ContractOpParams updatedContractOps = params().contractOpParams();
updatedContractOps.outDims = suggestedDims;
params().setContractOpParams(updatedContractOps);
}
}
fail:
return suggestedDims;
}
NvU32 engine_ast::RubikNode::suggestLineStride(surface::TensorSurfaceDesc* tsd)
{
NvDlaError e = NvDlaSuccess;
NvU32 lineStride = 0;
PROPAGATE_ERROR_FAIL( verifyEdgePorts() );
if (m_nodeTSDLineStride.find(tsd) != m_nodeTSDLineStride.end())
{
lineStride = m_nodeTSDLineStride[tsd];
goto fail;
}
{
surface::TensorSurfaceDesc probeTSD = *tsd;
Dims4 surfDims = suggestSurfaceDims(tsd);
probeTSD.setDimensions(surfDims);
probeTSD.resetLineStride();
lineStride = probeTSD.lineStride();
}
m_nodeTSDLineStride[tsd] = lineStride;
fail:
return lineStride;
}
NvU32 engine_ast::RubikNode::suggestSurfaceStride(surface::TensorSurfaceDesc* tsd)
{
NvDlaError e = NvDlaSuccess;
NvU32 surfaceStride = 0;
PROPAGATE_ERROR_FAIL( verifyEdgePorts() );
if (m_nodeTSDSurfaceStride.find(tsd) != m_nodeTSDSurfaceStride.end())
{
surfaceStride = m_nodeTSDSurfaceStride[tsd];
goto fail;
}
{
surface::TensorSurfaceDesc probeTSD = *tsd;
Dims4 surfDims = suggestSurfaceDims(tsd);
probeTSD.setDimensions(surfDims);
probeTSD.resetSurfaceStride();
surfaceStride = probeTSD.surfaceStride();
}
m_nodeTSDSurfaceStride[tsd] = surfaceStride;
fail:
return surfaceStride;
}
NvU64 engine_ast::RubikNode::suggestSurfaceSize(surface::TensorSurfaceDesc* tsd)
{
NvDlaError e = NvDlaSuccess;
NvU64 size = 0;
PROPAGATE_ERROR_FAIL( verifyEdgePorts() );
if (m_nodeTSDSurfaceSize.find(tsd) != m_nodeTSDSurfaceSize.end())
{
size = m_nodeTSDSurfaceSize[tsd];
goto fail;
}
{
surface::TensorSurfaceDesc probeTSD = *tsd;
Dims4 surfDims = suggestSurfaceDims(tsd);
probeTSD.setDimensions(surfDims);
probeTSD.resetSize();
size = probeTSD.size();
}
m_nodeTSDSurfaceSize[tsd] = size;
fail:
return size;
}
/*------------------------------Handle Multi-Batch---------------------*/
NvDlaError engine_ast::RubikNode::handleMultiBatch()
{
NvDlaError e = NvDlaSuccess;
//Handle operation parameters for the multi-batch operations
NvU32 numBatches = graph()->profile()->multiBatchSize();
for (NvU32 nn = 1; nn < numBatches; ++nn)
{
params(nn) = params(0);
}
return e;
}
NvDlaError engine_ast::RubikNode::determineContractOpParams()
{
NvDlaError e = NvDlaSuccess;
NvU16 CInExt, COutExt;
Dims4 origRubikInDims, origRubikOutDims;
engine_ast::RubikEngineParams::ContractOpParams contractOpParams;
NvU32 atom_k_size = graph()->target_config()->atomicKSize();
NvU32 chnlAlign = graph()->profile()->computePrecision() ==
surface::SurfacePrecisionEnum::NVDLA_PRECISION_INT8 ? atom_k_size : atom_k_size / 2;
if (params().mode().v() != RubikModeEnum::RUBIK_MODE_CONTRACT)
{
ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "Can't determine Contract op params for %s which is"
" not selected for Contract mode", name().c_str());
}
PROPAGATE_ERROR_FAIL( repopulateEdgePorts() );
origRubikInDims = inputEdges()[0]->originalTensor()->getDimensions();
origRubikOutDims = outputEdges()[0]->originalTensor()->getDimensions();
contractOpParams.inDims = origRubikInDims;
contractOpParams.outDims = origRubikOutDims;
if ( debugRubik() )
{
gLogInfo << "orig rubik in dims: " << origRubikInDims.c << "x"
<< origRubikInDims.h << "x" << origRubikInDims.w << endl;
gLogInfo << "orig rubik out dims: " << origRubikOutDims.c << "x"
<< origRubikOutDims.h << "x" << origRubikOutDims.w << endl;
}
/* Step-1: determine input side contract op details */
CInExt = ROUNDUP_AND_ALIGN(origRubikInDims.c, chnlAlign);
contractOpParams.inDims.c = CInExt;
/* Step-2: Determine output side contract op details */
COutExt = ROUNDUP_AND_ALIGN(origRubikOutDims.c, chnlAlign);
contractOpParams.outDims.c = COutExt;
params().setContractOpParams(contractOpParams);
if ( debugRubik() )
{
gLogInfo << "rubik contract op " << name() << " in: "
<< contractOpParams.inDims.n << "x" << contractOpParams.inDims.c << "x"
<< contractOpParams.inDims.h << "x" << contractOpParams.inDims.w << endl;
gLogInfo << "rubik contract op " << name() << " out: "
<< contractOpParams.outDims.n << "x" << contractOpParams.outDims.c << "x"
<< contractOpParams.outDims.h << "x" << contractOpParams.outDims.w << endl;
}
fail:
return e;
}
/*----------------------Code Emission-----------------------------------*/
NvDlaError engine_ast::RubikNode::emitOp(Graph *g,
DLAInterface *target_dla,
NvU32 op_slot, NvU32 batch_id,
DLACommonOpDescAccessor dep,
DLAOperationContainerAccessor op,
DLASurfaceContainerAccessor surf)
{
NvDlaError e = NvDlaSuccess;
DLARubikOpDescAccessor rubikOp = op.rubikOpDescAccessor(0);
DLARubikSurfaceDescAccessor surfAcc = surf.rubikSurfaceDescAccessor(0);
DLADataCubeAccessor srcDataAcc = surfAcc.srcDataAccessor();
DLADataCubeAccessor dstDataAcc = surfAcc.dstDataAccessor();
surface::TensorSurfaceDesc *srcTSD = g->nodeInputTensorSurface(this, 0, supportedInSurfCategories());
surface::TensorSurfaceDesc *dstTSD = g->nodeOutputTensorSurface(this, 0, supportedOutSurfCategories());
*rubikOp.precision() = ASTToDLAInterface::getRubikPrecision(target_dla, srcTSD->surfaceFormat().precision());
*rubikOp.mode() = ASTToDLAInterface::getRubikMode(target_dla, params(batch_id).mode());
*rubikOp.strideX() = (int)params(batch_id).deconvStride().w;
*rubikOp.strideY() = (int)params(batch_id).deconvStride().h;
emitDependencyParams(target_dla, dep, batch_id);
setDataCubeAccessor(srcDataAcc, srcTSD, IODirectionEnum::INPUT, batch_id);
setDataCubeAccessor(dstDataAcc, dstTSD, IODirectionEnum::UNKNOWN, batch_id);
if (params(batch_id).mode() == RubikModeEnum::RUBIK_MODE_CONTRACT)
{
*srcDataAcc.channel() = params(batch_id).contractOpParams().inDims.c;
*dstDataAcc.channel() = params(batch_id).contractOpParams().outDims.c;
}
if ( g->debugOps() )
{
gLogInfo << "Rubik node @ op_slot = " << op_slot << " batch_id = " << batch_id << endl;
gLogInfo << "\trubik precision " << (int)*rubikOp.precision() << endl;
gLogInfo << "\trubik mode " << (int)*rubikOp.mode() << endl;
gLogInfo << "\tdeconv-stride-x " << (int)*rubikOp.strideX() << endl;
gLogInfo << "\tdeconv-stride-Y " << (int)*rubikOp.strideY() << endl;
gLogInfo << "\tsrc tsd:" << srcTSD->id() << endl;
gLogInfo << "\tdst tsd:" << dstTSD->id() << endl;
gLogInfo << "\tsrc addr=" << (int) *srcDataAcc.address() << endl;
gLogInfo << "\tsrc type=" << (int) *srcDataAcc.type() << endl;
gLogInfo << "\tdependencyCount" << (int)*dep.dependencyCount() << endl;
gLogInfo << "\tsrc size " << *srcDataAcc.size() << endl;
gLogInfo << "\tsrc width " << *srcDataAcc.width() << endl;
gLogInfo << "\tsrc height " << *srcDataAcc.height() << endl;
gLogInfo << "\tsrc channel " << *srcDataAcc.channel() << endl;
gLogInfo << "\tsrc linestride " << *srcDataAcc.lineStride() << endl;
gLogInfo << "\tsrc surfstride " << *srcDataAcc.surfStride() << endl;
gLogInfo << "\tdst addr=" << (int) *dstDataAcc.address() << endl;
gLogInfo << "\tdst type=" << (int) *dstDataAcc.type() << endl;
gLogInfo << "\tdst size " << *dstDataAcc.size() << endl;
gLogInfo << "\tdst width " << *dstDataAcc.width() << endl;
gLogInfo << "\tdst height " << *dstDataAcc.height() << endl;
gLogInfo << "\tdst channel " << *dstDataAcc.channel() << endl;
gLogInfo << "\tdst linestride " << *dstDataAcc.lineStride() << endl;
gLogInfo << "\tdst surfstride " << *dstDataAcc.surfStride() << endl;
}
return e;
}
}; // nvdla::priv::
}; // nvdla::
| 5,489 |
4,238 | <gh_stars>1000+
// Copyright 2012 Google Inc
// All Rights Reserved.
//
//
// This windows service installation code is inspired from the MSDN article:
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb540475(v=vs.85).aspx
#include "grr_response_client/nanny/windows_nanny.h"
#include <shellapi.h>
#include <psapi.h>
#include <stdio.h>
#include <tchar.h>
#include <time.h>
/* On Windows 8 or later a separate include is required
* earlier versions implicitly include winbase.h from windows.h
*/
#if WINVER >= 0x602
#include <Processthreadsapi.h>
#endif
#include <windows.h>
#include <memory>
#include <string>
// Windows uses evil macros which interfere with proper C++.
#ifdef GetCurrentTime
#undef GetCurrentTime
#endif
#include "grr_response_client/nanny/child_controller.h"
#include "grr_response_client/nanny/event_logger.h"
using ::grr::EventLogger;
namespace grr {
// Global objects for synchronization.
SERVICE_STATUS g_service_status;
SERVICE_STATUS_HANDLE g_service_status_handler;
HANDLE g_service_stop_event = NULL;
// Open initial connection with event log.
WindowsEventLogger::WindowsEventLogger(const char *message) : StdOutLogger() {
// If this fails, we do not log anything. There is nothing else we could do if
// we cannot log to the event log.
event_source = RegisterEventSource(NULL, kNannyConfig->service_name);
if (message) {
Log(message);
}
}
WindowsEventLogger::WindowsEventLogger() {
// If this fails, we do not log anything. There is nothing else we could do if
// we cannot log to the event log.
event_source = RegisterEventSource(NULL, kNannyConfig->service_name);
}
// Unregister with the event log.
WindowsEventLogger::~WindowsEventLogger() {
if (event_source) {
DeregisterEventSource(event_source);
}
}
// Write the log message to the event log.
void WindowsEventLogger::WriteLog(std::string message) {
const TCHAR *strings[2];
strings[0] = kNannyConfig->service_name;
strings[1] = message.c_str();
// TODO(user): change this into overwriting % with place holder chars
// or equiv
if (message.find("%") != std::string::npos) {
strings[1] = "Invalid event message (Contains %%)";
}
if (event_source) {
ReportEvent(event_source, // event log handle
EVENTLOG_ERROR_TYPE, // event type
0, // event category
1, // event identifier
NULL, // no security identifier
2, // size of lpszStrings array
0, // no binary data
strings, // array of strings
NULL); // no binary data
}
}
// ---------------------------------------------------------
// StdOutLogger: A logger to stdout.
// ---------------------------------------------------------
StdOutLogger::StdOutLogger() {}
StdOutLogger::~StdOutLogger() {}
StdOutLogger::StdOutLogger(const char *message) {
printf("%s\n", message);
}
// Gets the current epoch time..
time_t StdOutLogger::GetCurrentTime() {
return time(NULL);
}
void StdOutLogger::WriteLog(std::string message) {
printf("%s\n", message.c_str());
}
// ---------------------------------------------------------
// WindowsChildProcess: Implementation of the windows child controller.
// ---------------------------------------------------------
class WindowsChildProcess : public grr::ChildProcess {
public:
WindowsChildProcess();
virtual ~WindowsChildProcess();
// The methods below are overridden from Childprocess. See child_controller.h
// for more information.
virtual void KillChild(const std::string &msg);
virtual bool CreateChildProcess();
virtual time_t GetCurrentTime();
virtual EventLogger *GetEventLogger();
virtual void SetNannyMessage(const std::string &msg);
virtual void SetPendingNannyMessage(const std::string &msg);
virtual void SetNannyStatus(const std::string &msg);
virtual time_t GetHeartbeat();
virtual void ClearHeartbeat();
virtual void SetHeartbeat(unsigned int value);
virtual void Heartbeat();
virtual size_t GetMemoryUsage();
virtual bool IsAlive();
virtual bool Started();
virtual void ChildSleep(unsigned int milliseconds);
private:
PROCESS_INFORMATION child_process;
WindowsEventLogger logger_;
std::string pendingNannyMsg_;
DISALLOW_COPY_AND_ASSIGN(WindowsChildProcess);
};
EventLogger *WindowsChildProcess::GetEventLogger() {
return &logger_;
}
// Kills the child.
void WindowsChildProcess::KillChild(const std::string &msg) {
if (child_process.hProcess == NULL)
return;
SetNannyStatus(msg);
TerminateProcess(child_process.hProcess, 0);
// Wait for the process to exit.
if (WaitForSingleObject(child_process.hProcess, 2000) != WAIT_OBJECT_0) {
logger_.Log("Unable to kill child within specified time.");
}
CloseHandle(child_process.hProcess);
CloseHandle(child_process.hThread);
child_process.hProcess = NULL;
return;
}
// Returns the last time the child produced a heartbeat.
time_t WindowsChildProcess::GetHeartbeat() {
DWORD last_heartbeat = 0;
DWORD data_len = sizeof(last_heartbeat);
DWORD type;
if (RegQueryValueEx(kNannyConfig->service_key,
kGrrServiceHeartbeatTimeKey,
0, &type, reinterpret_cast<BYTE*>(&last_heartbeat),
&data_len) != ERROR_SUCCESS ||
type != REG_DWORD || data_len != sizeof(last_heartbeat)) {
return 0;
}
return last_heartbeat;
}
// Clears the heartbeat.
void WindowsChildProcess::ClearHeartbeat() {
SetHeartbeat(0);
}
// Sets the heartbeat to the current time.
void WindowsChildProcess::Heartbeat() {
SetHeartbeat((unsigned int)GetCurrentTime());
}
void WindowsChildProcess::SetHeartbeat(unsigned int value) {
DWORD v = value;
HRESULT result = 0;
result = RegSetValueEx(kNannyConfig->service_key,
kGrrServiceHeartbeatTimeKey,
0,
REG_DWORD,
reinterpret_cast<BYTE*>(&v),
sizeof(DWORD));
if (result != ERROR_SUCCESS) {
TCHAR errormsg[1024];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, result, 0, errormsg,
1024, NULL);
logger_.Log("Unable to set heartbeat value: %s", errormsg);
}
}
// This sends a status message back to the server in case of a child kill.
void WindowsChildProcess::SetNannyStatus(const std::string &msg) {
if (RegSetValueExA(kNannyConfig->service_key,
kGrrServiceNannyStatusKey, 0, REG_SZ,
reinterpret_cast<const BYTE*>(msg.c_str()),
(DWORD)(msg.size() + 1)) != ERROR_SUCCESS) {
logger_.Log("Unable to set Nanny status (%s).", msg.c_str());
}
}
void WindowsChildProcess::SetPendingNannyMessage(const std::string &msg) {
pendingNannyMsg_ = msg;
}
// This sends a message back to the server.
void WindowsChildProcess::SetNannyMessage(const std::string &msg) {
if (RegSetValueExA(kNannyConfig->service_key,
kGrrServiceNannyMessageKey, 0, REG_SZ,
reinterpret_cast<const BYTE*>(msg.c_str()),
(DWORD)(msg.size() + 1)) != ERROR_SUCCESS) {
logger_.Log("Unable to set Nanny message (%s).", msg.c_str());
}
}
// Launch the child process.
bool WindowsChildProcess::CreateChildProcess() {
DWORD creation_flags = 0;
if (pendingNannyMsg_ != "") {
SetNannyMessage(pendingNannyMsg_);
pendingNannyMsg_ = "";
}
// If the child is already running or we have a handle to it, try to kill it.
if (IsAlive()) {
KillChild("Child process restart.");
}
// Just copy our own startup info for the child.
STARTUPINFO startup_info;
GetStartupInfo(&startup_info);
// From: http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx
// If this parameter is NULL and the environment block of the parent process
// contains Unicode characters, you must also ensure that dwCreationFlags
// includes CREATE_UNICODE_ENVIRONMENT.
#if defined( UNICODE )
creation_flags = CREATE_UNICODE_ENVIRONMENT;
#endif
// Now try to start it.
if (!CreateProcess(
kNannyConfig->child_process_name, // Application Name
kNannyConfig->child_command_line, // Command line
NULL, // Process attributes
NULL, // lpThreadAttributes
0, // bInheritHandles
creation_flags, // dwCreationFlags
NULL, // lpEnvironment
NULL, // lpCurrentDirectory
&startup_info, // lpStartupInfo
&child_process)) {
logger_.Log("Unable to launch child process: %s %u.",
kNannyConfig->child_process_name,
GetLastError());
return false;
}
return true;
}
// Return the current date and time in seconds since 1970.
time_t WindowsChildProcess::GetCurrentTime() {
return time(NULL);
}
void WindowsChildProcess::ChildSleep(unsigned int milliseconds) {
Sleep(milliseconds);
}
size_t WindowsChildProcess::GetMemoryUsage() {
PROCESS_MEMORY_COUNTERS pmc;
if (!child_process.hProcess) {
return 0;
}
if (GetProcessMemoryInfo(child_process.hProcess, &pmc, sizeof(pmc))) {
return (size_t) pmc.WorkingSetSize;
}
DWORD res = GetLastError();
TCHAR errormsg[1024];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, res, 0, errormsg, 1024, NULL);
logger_.Log("Could not obtain memory information: %s", errormsg);
return 0;
}
bool WindowsChildProcess::IsAlive() {
DWORD exit_code = 0;
if (!child_process.hProcess) {
return true;
}
if (!GetExitCodeProcess(child_process.hProcess, &exit_code)) {
return false;
}
return exit_code == STILL_ACTIVE;
}
bool WindowsChildProcess::Started() {
return child_process.hProcess != NULL;
}
WindowsChildProcess::WindowsChildProcess()
: logger_(NULL), pendingNannyMsg_("") {
ClearHeartbeat();
}
WindowsChildProcess::~WindowsChildProcess() {
KillChild("Shutting down.");
}
// -----------------------------------------------------------
// Implementation of the WindowsControllerConfig configuration
// manager.
// -----------------------------------------------------------
WindowsControllerConfig::WindowsControllerConfig()
: logger_(NULL) {
// Child must stay dead for this many seconds.
controller_config.resurrection_period = 60;
// If we receive no heartbeats from the client in this long, child
// is killed.
controller_config.unresponsive_kill_period = 180;
controller_config.unresponsive_grace_period = 600;
controller_config.event_log_message_suppression = 60 * 60 * 24;
controller_config.failure_count_to_revert = 0;
controller_config.client_memory_limit = 1024 * 1024 * 1024;
service_hive = HKEY_LOCAL_MACHINE;
service_key = NULL;
service_key_name = NULL;
service_name[0] = '\0';
service_description[0] = '\0';
action = TEXT("");
}
WindowsControllerConfig::~WindowsControllerConfig() {
if (service_key) {
RegCloseKey(service_key);
}
}
// Read a value from the service key and store in dest.
DWORD WindowsControllerConfig::ReadValue(const TCHAR *value_name,
TCHAR *dest, DWORD len) {
DWORD type;
if (RegQueryValueEx(service_key,
value_name, 0, &type,
reinterpret_cast<BYTE*>(dest),
&len) != ERROR_SUCCESS ||
type != REG_SZ || len >= MAX_PATH) {
logger_.Log("Unable to open value %s.", value_name);
return ERROR_INVALID_DATA;
}
// Ensure it is null terminated.
dest[len] = '\0';
return ERROR_SUCCESS;
}
// Parses configuration parameters from __argv.
DWORD WindowsControllerConfig::ParseConfiguration(void) {
int i;
for (i = 1; i < __argc; i++) {
char * parameter = __argv[i];
if (!strcmp(__argv[i], "--service_key") && i + 1 < __argc) {
i++;
service_key_name = __argv[i];
continue;
}
if (!strcmp(__argv[i], "install")) {
action = __argv[i];
continue;
}
logger_.Log("Unable to parse command line parameter %s", __argv[i]);
return ERROR_INVALID_DATA;
}
if (!service_key_name) {
logger_.Log("No service key set. Please ensure --service_key is "
"specified.");
return ERROR_INVALID_DATA;
}
// Try to open the service key now.
HRESULT result = RegOpenKeyEx(service_hive,
service_key_name,
0,
KEY_READ | KEY_WRITE,
&service_key);
if (result != ERROR_SUCCESS) {
service_key = 0;
TCHAR errormsg[1024];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, result, 0, errormsg,
1024, NULL);
logger_.Log("Unable to open service key (%s): %s", service_key_name,
errormsg);
return result;
}
// Get the child command line from the service key. The installer
// should pre-populate this key for us. We fail if we can not find
// it
result = ReadValue(kGrrServiceBinaryChildKey, child_process_name,
sizeof(child_process_name));
if (result != ERROR_SUCCESS)
return result;
result = ReadValue(kGrrServiceBinaryCommandLineKey, child_command_line,
sizeof(child_command_line));
if (result != ERROR_SUCCESS)
return result;
result = ReadValue(kGrrServiceNameKey, service_name, sizeof(service_name));
if (result != ERROR_SUCCESS)
return result;
result = ReadValue(kGrrServiceDescKey, service_description,
sizeof(service_description));
if (result != ERROR_SUCCESS)
service_description[0] = '\0';
return ERROR_SUCCESS;
}
// ---------------------------------------------------------
// Service Setup and installation.
// ---------------------------------------------------------
// ---------------------------------------------------------
// StopService()
//
// Waits a predetermined time for the service to stop.
// Returns false if we failed to stop the service.
// ---------------------------------------------------------
bool StopService(SC_HANDLE service_handle, int time_out) {
// Send a stop code to the service.
SERVICE_STATUS_PROCESS service_status_process;
DWORD bytes_needed;
time_t start_time = GetTickCount();
int count = 0;
WindowsEventLogger logger;
printf("Stopping Service\n");
// Make sure the service is not already stopped.
if (!QueryServiceStatusEx(
service_handle,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&service_status_process,
sizeof(SERVICE_STATUS_PROCESS),
&bytes_needed)) {
logger.Log("QueryServiceStatusEx failed (%d)\n", GetLastError());
return false;
}
if (service_status_process.dwCurrentState == SERVICE_STOPPED) {
printf("Service is already stopped.\n");
return true;
}
// If a stop is pending, wait for it.
while (service_status_process.dwCurrentState == SERVICE_STOP_PENDING) {
printf("%d Service stop pending...\n", count++);
Sleep(1000);
if (!QueryServiceStatusEx(
service_handle,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&service_status_process,
sizeof(SERVICE_STATUS_PROCESS),
&bytes_needed)) {
logger.Log("QueryServiceStatusEx failed (%d)\n", GetLastError());
return false;
}
if (service_status_process.dwCurrentState == SERVICE_STOPPED) {
printf("Service stopped successfully.\n");
return true;
}
if ( GetTickCount() - start_time > time_out ) {
logger.Log("Service stop timed out.\n");
return false;
}
}
if (!ControlService(service_handle, SERVICE_CONTROL_STOP,
reinterpret_cast<SERVICE_STATUS*>(
&service_status_process))) {
logger.Log("Unable to stop existing service\n");
return false;
}
// Wait for the service to stop.
while (service_status_process.dwCurrentState != SERVICE_STOPPED) {
Sleep(service_status_process.dwWaitHint);
if (!QueryServiceStatusEx(service_handle,
SC_STATUS_PROCESS_INFO,
reinterpret_cast<BYTE*>(&service_status_process),
sizeof(SERVICE_STATUS_PROCESS),
&bytes_needed)) {
logger.Log("Unable to stop existing service\n");
return false;
}
if (GetTickCount() - start_time > time_out) {
logger.Log("Wait timed out\n");
return false;
}
}
printf("Service stopped successfully\n");
return true;
}
#if defined(_WIN32)
typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, BOOL*);
// ---------------------------------------------------------
// windows_nanny_IsWow64Process()
//
// Replace of IsWow64Process function for Windows XP SP1
// and earlier versions. Uses dynamic late binding to call the
// IsWow64Process function or returns False otherwise.
// Returns True if successful, False otherwise
// ---------------------------------------------------------
BOOL windows_nanny_IsWow64Process(HANDLE hProcess, BOOL *Wow64Process) {
LPFN_ISWOW64PROCESS function = NULL;
HMODULE library_handle = NULL;
BOOL result = FALSE;
if (hProcess == NULL) {
return FALSE;
}
if (Wow64Process == NULL) {
return FALSE;
}
library_handle = LoadLibrary(_T("kernel32.dll"));
if (library_handle == NULL) {
return FALSE;
}
function = (LPFN_ISWOW64PROCESS) GetProcAddress(
library_handle, (LPCSTR) "IsWow64Process");
if (function != NULL) {
result = function(hProcess, Wow64Process);
} else {
*Wow64Process = FALSE;
result = TRUE;
}
if (FreeLibrary(library_handle) != TRUE) {
result = FALSE;
}
return result;
}
#endif
// ---------------------------------------------------------
// InstallService()
//
// Installs the service. This function typically runs in the context of the
// command shell hence printf() works.
// Returns -1 if service failed to be installed, and 0 on success.
// ---------------------------------------------------------
bool InstallService() {
SC_HANDLE service_control_manager;
SC_HANDLE service_handle = NULL;
TCHAR module_name[MAX_PATH];
SERVICE_DESCRIPTION service_descriptor;
WindowsEventLogger logger(NULL);
unsigned int tries = 0;
DWORD error_code = 0;
#if defined(_WIN32)
BOOL f64 = FALSE;
BOOL result = FALSE;
// Using dynamic late binding here to support WINVER < 0x501
// TODO(user): remove this function make sure to have the installer
// detect right platform also see:
// http://blogs.msdn.com/b/david.wang/archive/2006/03/26/
// howto-detect-process-bitness.aspx
result = windows_nanny_IsWow64Process(GetCurrentProcess(), &f64);
if (result && f64) {
printf("32 bit installer should not be run on a 64 bit machine!\n");
return false;
}
#endif
if (!GetModuleFileName(NULL, module_name, MAX_PATH)) {
logger.Log("Cannot install service.\n");
return false;
}
service_control_manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (service_control_manager == NULL) {
error_code = GetLastError();
logger.Log("Unable to open Service Control Manager - error code: "
"0x%08x.\n", error_code);
return false;
}
// module_name contains the path to the service binary and is used in the
// service command line. kNannyConfig->service_name contains the name of the
// service.
std::string command_line(module_name);
command_line += " --service_key \"";
command_line += kNannyConfig->service_key_name;
command_line += "\"";
service_handle = OpenService(
service_control_manager, // SCM database
kNannyConfig->service_name, // name of service
SERVICE_ALL_ACCESS); // need delete access
if (service_handle == NULL) {
error_code = GetLastError();
if (error_code != ERROR_SERVICE_DOES_NOT_EXIST) {
printf("Unable to open service: %s unexpected error - error code: "
"0x%08x.\n", kNannyConfig->service_name, error_code);
goto on_error;
}
// If the service does not exists, create it.
service_handle = CreateService(
service_control_manager, kNannyConfig->service_name,
kNannyConfig->service_name,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS, // Run in our own process.
SERVICE_AUTO_START, // Come up on regular startup.
SERVICE_ERROR_NORMAL, // If we fail to start, log it and move on.
command_line.c_str(), // Command line for the service.
NULL, NULL, NULL,
NULL, NULL); // Run as LocalSystem so no username and password.
if (service_handle == NULL) {
error_code = GetLastError();
printf("Unable to create service: %s - error code: 0x%08x.\n",
kNannyConfig->service_name, error_code);
goto on_error;
}
} else {
if (!StopService(service_handle, 60000)) {
printf("Service could not be stopped. This is ok if the service is not "
"already started.\n");
}
// Set the path to the service binary.
if (ChangeServiceConfig(
service_handle, SERVICE_NO_CHANGE,
SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, command_line.c_str(),
NULL, NULL, NULL, NULL, NULL, NULL) == 0) {
error_code = GetLastError();
printf("Unable to change service: %s configuration - error code: "
"0x%08x.\n", kNannyConfig->service_name, error_code);
}
}
// Set the service description.
service_descriptor.lpDescription = kNannyConfig->service_description;
if (!ChangeServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION,
&service_descriptor)) {
error_code = GetLastError();
logger.Log("Unable to set service: %s description - error code: 0x%08x.\n",
kNannyConfig->service_name, error_code);
}
// Start the service.
if (!StartService(service_handle, 0, NULL)) {
error_code = GetLastError();
printf("Unable to start service: %s - error code: 0x%08x.\n",
kNannyConfig->service_name, error_code);
} else {
printf("Service: %s started as: %s\n",
kNannyConfig->service_name, module_name);
}
CloseServiceHandle(service_handle);
CloseServiceHandle(service_control_manager);
return true;
on_error:
if (service_handle != NULL) {
CloseServiceHandle(service_handle);
}
if (service_control_manager != NULL) {
CloseServiceHandle(service_control_manager);
}
return false;
}
// Send a status report to the service event manager.
void ReportSvcStatus(DWORD current_state, DWORD win32_exit_code,
DWORD wait_hint) {
static DWORD check_point = 1;
// Fill in the SERVICE_STATUS structure.
g_service_status.dwCurrentState = current_state;
g_service_status.dwWin32ExitCode = win32_exit_code;
g_service_status.dwWaitHint = wait_hint;
g_service_status.dwControlsAccepted = (
current_state == SERVICE_START_PENDING ? 0 : SERVICE_ACCEPT_STOP);
if (current_state == SERVICE_RUNNING ||
current_state == SERVICE_STOPPED) {
g_service_status.dwCheckPoint = 0;
} else {
g_service_status.dwCheckPoint = check_point++;
}
// Report the status of the service to the SCM.
SetServiceStatus(g_service_status_handler, &g_service_status);
}
// Handles the requested control code.
VOID WINAPI SvcCtrlHandler(DWORD control) {
switch (control) {
case SERVICE_CONTROL_STOP:
ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
// Signal the service to stop.
SetEvent(g_service_stop_event);
ReportSvcStatus(g_service_status.dwCurrentState, NO_ERROR, 0);
return;
case SERVICE_CONTROL_INTERROGATE:
break;
default:
break;
}
}
// The main function for the service.
VOID WINAPI ServiceMain(int argc, LPTSTR *argv) {
WindowsControllerConfig global_config;
WindowsEventLogger logger;
// Parse the configuration and set the global object.
if (global_config.ParseConfiguration() == ERROR_SUCCESS) {
kNannyConfig = &global_config;
} else {
printf("Unable to parse command line.");
return;
}
// Registers the handler function for the service.
g_service_status_handler = RegisterServiceCtrlHandler(
kNannyConfig->service_name, SvcCtrlHandler);
if (!g_service_status_handler) {
logger.Log("RegisterServiceCtrlHandler failed.");
return;
}
// These SERVICE_STATUS members remain as set here.
g_service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
g_service_status.dwServiceSpecificExitCode = 0;
// Report initial status to the SCM.
ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);
// Create an event. The control handler function, SvcCtrlHandler, signals this
// event when it receives the stop control code.
g_service_stop_event = CreateEvent(
NULL, // default security attributes
TRUE, // manual reset event
FALSE, // not signaled
NULL); // no name
if (!g_service_stop_event) {
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
return;
}
// Create a new child to control.
WindowsChildProcess child;
grr::ChildController child_controller(kNannyConfig->controller_config,
&child);
// Report running status when initialization is complete.
ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
child.CreateChildProcess();
// Give the child process some time to start up. During boot it sometimes
// takes significantly more time than the unresponsive_kill_period to start
// the child so we disable checking for heartbeats for a while.
child.Heartbeat();
time_t sleep_time = kNannyConfig->controller_config.unresponsive_grace_period;
// Spin in this loop until the service is stopped.
while (1) {
for (unsigned int i = 0; i < sleep_time; i++) {
// Check every second whether to stop the service.
if (WaitForSingleObject(g_service_stop_event, 1000) != WAIT_TIMEOUT) {
child.KillChild("Service stopped.");
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
return;
}
if (child.GetMemoryUsage() >
kNannyConfig->controller_config.client_memory_limit) {
child.KillChild("Child process exceeded memory limit.");
break;
}
if (child.Started() && !child.IsAlive()) {
int shutdown_pending = GetSystemMetrics(SM_SHUTTINGDOWN);
if (shutdown_pending == 0) {
child.SetPendingNannyMessage("Unexpected child process exit!");
child.KillChild("Child process exited.");
break;
} else {
// The machine is shutting down. We just keep going until we get
// the service_stop_event.
continue;
}
}
}
// Run the child a bit more.
sleep_time = child_controller.Run();
}
}
// The main function.
int _cdecl real_main(int argc, TCHAR *argv[]) {
// If command-line parameter is "install", install the service.
// Otherwise, the service is probably being started by the SCM.
WindowsControllerConfig global_config;
// Parse the configuration and set the global object.
if (global_config.ParseConfiguration() == ERROR_SUCCESS) {
kNannyConfig = &global_config;
} else {
printf("Unable to parse command line.\n");
return -1;
}
if (lstrcmpi(global_config.action, TEXT("install")) == 0) {
return InstallService() ? 0 : -1;
}
// This table contains all the services provided by this binary.
SERVICE_TABLE_ENTRY kDispatchTable[] = {
{ kNannyConfig->service_name,
reinterpret_cast<LPSERVICE_MAIN_FUNCTION>(ServiceMain) },
{ NULL, NULL }
};
// This call returns when the service has stopped.
// The process should simply terminate when the call returns.
if (!StartServiceCtrlDispatcher(kDispatchTable)) {
WindowsEventLogger("StartServiceCtrlDispatcher");
}
return 0;
}
} // namespace grr
// Main entry point when built as a windows application.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
char *lpCmdLine, int nCmdShow) {
return grr::real_main(__argc, __argv);
}
// Main entry point when build as a console application.
int _tmain(int argc, char *argv[]) {
return grr::real_main(argc, argv);
}
| 10,531 |
615 | /**
* @file viterbi_scorer.h
* @author <NAME>
*
* All files in META are dual-licensed under the MIT and NCSA licenses. For more
* details, consult the file LICENSE.mit and LICENSE.ncsa in the root of the
* project.
*/
#ifndef META_SEQUENCE_CRF_VITERBI_SCORER_H_
#define META_SEQUENCE_CRF_VITERBI_SCORER_H_
#include "meta/sequence/crf/scorer.h"
namespace meta
{
namespace sequence
{
/**
* Scorer for performing viterbi-based tagging.
*/
class crf::viterbi_scorer
{
public:
/**
* Constructs a new scorer against the given model.
* @param model The model to score with
*/
viterbi_scorer(const crf& model);
/**
* Runs the viterbi algorithm to produce a trellis with
* back-pointers.
*
* @param seq The sequence to score
* @return a trellis with back-pointers indicating the path with
* the highest score
*/
viterbi_trellis viterbi(const sequence& seq);
private:
/// the internal scorer used
crf::scorer scorer_;
/// a back-pointer to the model this scorer uses to tag
const crf* model_;
};
}
}
#endif
| 417 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.netapp.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.management.Resource;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.netapp.fluent.models.AccountProperties;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
/** NetApp account patch resource. */
@Fluent
public final class NetAppAccountPatch extends Resource {
@JsonIgnore private final ClientLogger logger = new ClientLogger(NetAppAccountPatch.class);
/*
* NetApp Account properties
*/
@JsonProperty(value = "properties")
private AccountProperties innerProperties;
/**
* Get the innerProperties property: NetApp Account properties.
*
* @return the innerProperties value.
*/
private AccountProperties innerProperties() {
return this.innerProperties;
}
/** {@inheritDoc} */
@Override
public NetAppAccountPatch withLocation(String location) {
super.withLocation(location);
return this;
}
/** {@inheritDoc} */
@Override
public NetAppAccountPatch withTags(Map<String, String> tags) {
super.withTags(tags);
return this;
}
/**
* Get the provisioningState property: Azure lifecycle management.
*
* @return the provisioningState value.
*/
public String provisioningState() {
return this.innerProperties() == null ? null : this.innerProperties().provisioningState();
}
/**
* Get the activeDirectories property: Active Directories.
*
* @return the activeDirectories value.
*/
public List<ActiveDirectory> activeDirectories() {
return this.innerProperties() == null ? null : this.innerProperties().activeDirectories();
}
/**
* Set the activeDirectories property: Active Directories.
*
* @param activeDirectories the activeDirectories value to set.
* @return the NetAppAccountPatch object itself.
*/
public NetAppAccountPatch withActiveDirectories(List<ActiveDirectory> activeDirectories) {
if (this.innerProperties() == null) {
this.innerProperties = new AccountProperties();
}
this.innerProperties().withActiveDirectories(activeDirectories);
return this;
}
/**
* Get the encryption property: Encryption settings.
*
* @return the encryption value.
*/
public AccountEncryption encryption() {
return this.innerProperties() == null ? null : this.innerProperties().encryption();
}
/**
* Set the encryption property: Encryption settings.
*
* @param encryption the encryption value to set.
* @return the NetAppAccountPatch object itself.
*/
public NetAppAccountPatch withEncryption(AccountEncryption encryption) {
if (this.innerProperties() == null) {
this.innerProperties = new AccountProperties();
}
this.innerProperties().withEncryption(encryption);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (innerProperties() != null) {
innerProperties().validate();
}
}
}
| 1,241 |
937 | <reponame>zmyer/cyclops-react
package com.oath.cyclops.react.async.subscription;
import com.oath.cyclops.async.adapters.Queue;
public interface Continueable {
public void closeQueueIfFinished(Queue queue);
public void addQueue(Queue queue);
public void registerSkip(long skip);
public void registerLimit(long limit);
public void closeAll(Queue q);
public boolean closed();
public void closeQueueIfFinishedStateless(Queue queue);
public void closeAll();
public long timeLimit();
public void registerTimeLimit(long nanos);
}
| 180 |
303 | {"id":1919,"line-1":"Hawaii","line-2":"United States","attribution":"©2014 CyberCity 3D, Inc. / 3D Travel Inc., DigitalGlobe, U.S. Geological Survey, USGS","url":"https://www.google.com/maps/@21.261825,-157.809431,17z/data=!3m1!1e3"} | 91 |
808 | <filename>lite/tests/unittest_py/model_test/run_model_test.py
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import argparse
URL = "url"
MODEL_NAME = "model_name"
FILE_NAME = "file_name"
INPUT_SHAPES = "input_shapes"
all_configs = []
MobileNetV1_config = {
"url":
"https://paddle-inference-dist.bj.bcebos.com/AI-Rank/mobile/MobileNetV1.tar.gz",
"model_name": "MobileNetV1",
"file_name": "MobileNetV1.tar.gz",
"input_shapes": ["1,3,224,224"]
}
MobileNetV2_config = {
"url":
"https://paddle-inference-dist.bj.bcebos.com/AI-Rank/mobile/MobileNetV2.tar.gz",
"model_name": "MobileNetV2",
"file_name": "MobileNetV2.tar.gz",
"input_shapes": ["1,3,224,224"]
}
MobileNetV3_large_x1_0_config = {
"url":
"https://paddle-inference-dist.bj.bcebos.com/AI-Rank/mobile/MobileNetV3_large_x1_0.tar.gz",
"model_name": "MobileNetV3_large_x1_0",
"file_name": "MobileNetV3_large_x1_0.tar.gz",
"input_shapes": ["1,3,224,224"]
}
MobileNetV3_small_x1_0_config = {
"url":
"https://paddle-inference-dist.bj.bcebos.com/AI-Rank/mobile/MobileNetV3_small_x1_0.tar.gz",
"model_name": "MobileNetV3_small_x1_0",
"file_name": "MobileNetV3_small_x1_0.tar.gz",
"input_shapes": ["1,3,224,224"]
}
ResNet50_config = {
"url":
"https://paddle-inference-dist.bj.bcebos.com/AI-Rank/mobile/ResNet50.tar.gz",
"model_name": "ResNet50",
"file_name": "ResNet50.tar.gz",
"input_shapes": ["1,3,224,224"]
}
ssdlite_mobilenet_v3_large_config = {
"url":
"https://paddle-inference-dist.bj.bcebos.com/AI-Rank/mobile/ssdlite_mobilenet_v3_large.tar.gz",
"model_name": "ssdlite_mobilenet_v3_large",
"file_name": "ssdlite_mobilenet_v3_large.tar.gz",
"input_shapes": ["1,3,320,320"]
}
all_configs.append(MobileNetV1_config)
all_configs.append(MobileNetV2_config)
all_configs.append(MobileNetV3_large_x1_0_config)
all_configs.append(MobileNetV3_small_x1_0_config)
all_configs.append(ResNet50_config)
all_configs.append(ssdlite_mobilenet_v3_large_config)
parser = argparse.ArgumentParser()
parser.add_argument("--target", help="set target, default=X86", default="X86")
args = parser.parse_args()
for config in all_configs:
input_info_str = ""
for input_shape in config[INPUT_SHAPES]:
input_info_str = input_info_str + " --input_shapes={}".format(
input_shape)
if args.target == "X86":
command = "python3.7 {}/model_test_base.py --target=X86 --url={} --model_name={} --file_name={} {}".format(
os.getcwd(), config[URL], config[MODEL_NAME],
config[FILE_NAME], input_info_str)
elif args.target == "Host":
command = "python3.7 {}/model_test_base.py --target=Host --url={} --model_name={} --file_name={} {}".format(
os.getcwd(), config[URL], config[MODEL_NAME],
config[FILE_NAME], input_info_str)
elif args.target == "ARM":
command = "python3.8 {}/model_test_base.py --target=ARM --url={} --model_name={} --file_name={} {}".format(
os.getcwd(), config[URL], config[MODEL_NAME],
config[FILE_NAME], input_info_str)
elif args.target == "OpenCL":
command = "python3.8 {}/model_test_base.py --target=OpenCL --url={} --model_name={} --file_name={} {}".format(
os.getcwd(), config[URL], config[MODEL_NAME],
config[FILE_NAME], input_info_str)
elif args.target == "Metal":
command = "python3.8 {}/model_test_base.py --target=Metal --url={} --model_name={} --file_name={} {}".format(
os.getcwd(), config[URL], config[MODEL_NAME],
config[FILE_NAME], input_info_str)
print(command)
os.system(command)
| 1,905 |
2,661 | <filename>earth_enterprise/src/third_party/sgl/v0_8_6/src/SkMask.cpp
/* libs/graphics/sgl/SkMask.cpp
**
** Copyright 2007, 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.
*/
#include "SkMask.h"
size_t SkMask::computeImageSize() const
{
return fBounds.height() * fRowBytes;
}
size_t SkMask::computeTotalImageSize() const
{
size_t size = this->computeImageSize();
if (fFormat == SkMask::k3D_Format)
size *= 3;
return size;
}
/** We explicitly use this allocator for SkBimap pixels, so that we can
freely assign memory allocated by one class to the other.
*/
uint8_t* SkMask::AllocImage(size_t size)
{
return (uint8_t*)sk_malloc_throw(SkAlign4(size));
}
/** We explicitly use this allocator for SkBimap pixels, so that we can
freely assign memory allocated by one class to the other.
*/
void SkMask::FreeImage(void* image)
{
sk_free(image);
}
| 472 |
325 | <gh_stars>100-1000
package com.box.l10n.mojito.service.thirdparty.smartling;
import com.box.l10n.mojito.service.tm.search.TextUnitDTO;
import com.box.l10n.mojito.test.TestIdWatcher;
import com.google.common.collect.ImmutableList;
import org.junit.Rule;
import org.junit.Test;
import java.util.List;
import static com.box.l10n.mojito.service.thirdparty.smartling.SmartlingPluralFix.fixTextUnits;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class SmartlingPluralFixTest {
@Rule
public TestIdWatcher testIdWatcher = new TestIdWatcher();
@Test
public void testFixTextUnits() {
List<TextUnitDTO> input = ImmutableList.of();
assertThat(fixTextUnits(input)).isEmpty();
String textContent = testIdWatcher.getEntityName("textContent");
input = ImmutableList.of(
textUnit("singular1", textContent, null, null),
textUnit("singular2", textContent, null, null));
assertThat(fixTextUnits(input)).containsExactlyElementsOf(input);
textContent = testIdWatcher.getEntityName("textContent2");
input = ImmutableList.of(
textUnit("singular1", textContent, null, null),
textUnit("singular2", textContent, null, null),
textUnit("plural1_zero", textContent, "zero", "plural1_other"),
textUnit("plural1_other", textContent, "other", "plural1_other"));
assertThat(fixTextUnits(input)).extracting("name", "target", "pluralForm", "pluralFormOther")
.containsExactlyInAnyOrder(
tuple("singular1", textContent, null, null),
tuple("singular2", textContent, null, null),
tuple("plural1_zero", textContent, "zero", "plural1_other"),
tuple("plural1_many", textContent, "many", "plural1_other"),
tuple("plural1_other", textContent, "other", "plural1_other"));
textContent = testIdWatcher.getEntityName("textContent3");
input = ImmutableList.of(
textUnit("plural1_zero", textContent, "zero", "plural1_other"),
textUnit("plural1_other", textContent, "other", "plural1_other"),
textUnit("plural2_zero", textContent, "zero", null),
textUnit("plural2_one", textContent, "one", null));
assertThat(fixTextUnits(input)).extracting("name", "target", "pluralForm", "pluralFormOther")
.containsExactlyInAnyOrder(
tuple("plural1_zero", textContent, "zero", "plural1_other"),
tuple("plural1_many", textContent, "many", "plural1_other"),
tuple("plural1_other", textContent, "other", "plural1_other"),
tuple("plural2_zero", textContent, "zero", null),
tuple("plural2_one", textContent, "one", null));
String repository = testIdWatcher.getEntityName("repository");
String assetPath = testIdWatcher.getEntityName("asset");
String targetLocale = "cz-CZ";
textContent = testIdWatcher.getEntityName("textContent4");
input = ImmutableList.of(
textUnit("plural1_zero", textContent, "zero", "plural1_other", repository, assetPath, targetLocale),
textUnit("plural1_other", textContent, "other", "plural1_other", repository, assetPath, targetLocale),
textUnit("plural2_zero", textContent, "zero", "plural2_other", repository, assetPath, targetLocale),
textUnit("plural2_one", textContent, "one", "plural2_other", repository, assetPath, targetLocale),
textUnit("plural2_other", textContent, "other", "plural2_other", repository, assetPath, targetLocale));
assertThat(fixTextUnits(input)).extracting("name", "target", "pluralForm", "pluralFormOther", "repositoryName", "assetPath", "targetLocale")
.containsExactlyInAnyOrder(
tuple("plural1_zero", textContent, "zero", "plural1_other", repository, assetPath, targetLocale),
tuple("plural1_other", textContent, "other", "plural1_other", repository, assetPath, targetLocale),
tuple("plural1_many", textContent, "many", "plural1_other", repository, assetPath, targetLocale),
tuple("plural2_zero", textContent, "zero", "plural2_other", repository, assetPath, targetLocale),
tuple("plural2_one", textContent, "one", "plural2_other", repository, assetPath, targetLocale),
tuple("plural2_many", textContent, "many", "plural2_other", repository, assetPath, targetLocale),
tuple("plural2_other", textContent, "other", "plural2_other", repository, assetPath, targetLocale));
}
private TextUnitDTO textUnit(String name, String content, String pluralForm, String pluralFormOther){
return textUnit(name, content, pluralForm, pluralFormOther, null, null, null);
}
private TextUnitDTO textUnit(String name, String content, String pluralForm, String pluralFormOther,
String repositoryName, String assetPath, String targetLocale){
TextUnitDTO textUnit = new TextUnitDTO();
textUnit.setName(name);
textUnit.setTarget(content);
textUnit.setPluralForm(pluralForm);
textUnit.setPluralFormOther(pluralFormOther);
textUnit.setRepositoryName(repositoryName);
textUnit.setAssetPath(assetPath);
textUnit.setTargetLocale(targetLocale);
return textUnit;
}
}
| 2,439 |
403 | /* autogenerated by generator-surface.js */
#pragma once
#include <nan.h>
#include <node.h>
#include <girepository.h>
#include <glib.h>
#include <cairo.h>
namespace GNodeJS {
namespace Cairo {
class Surface: public Nan::ObjectWrap {
public:
static Nan::Persistent<v8::FunctionTemplate> constructorTemplate;
static Nan::Persistent<v8::Function> constructor;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static void SetupTemplate();
static Local<v8::FunctionTemplate> GetTemplate();
static Local<v8::Function> GetConstructor();
static NAN_METHOD(New);
static NAN_METHOD(createSimilar);
static NAN_METHOD(createSimilarImage);
static NAN_METHOD(createForRectangle);
static NAN_METHOD(writeToPng);
static NAN_METHOD(status);
static NAN_METHOD(finish);
static NAN_METHOD(flush);
static NAN_METHOD(getDevice);
static NAN_METHOD(getFontOptions);
static NAN_METHOD(getContent);
static NAN_METHOD(markDirty);
static NAN_METHOD(markDirtyRectangle);
static NAN_METHOD(setDeviceOffset);
static NAN_METHOD(getDeviceOffset);
static NAN_METHOD(getDeviceScale);
static NAN_METHOD(setDeviceScale);
static NAN_METHOD(setFallbackResolution);
static NAN_METHOD(getFallbackResolution);
static NAN_METHOD(getType);
static NAN_METHOD(getReferenceCount);
static NAN_METHOD(copyPage);
static NAN_METHOD(showPage);
static NAN_METHOD(hasShowTextGlyphs);
static NAN_METHOD(supportsMimeType);
static NAN_METHOD(mapToImage);
static NAN_METHOD(unmapImage);
Surface(cairo_surface_t* data);
~Surface();
cairo_surface_t* _data;
};
class ImageSurface: public Surface {
public:
static Nan::Persistent<v8::FunctionTemplate> constructorTemplate;
static Nan::Persistent<v8::Function> constructor;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static void SetupTemplate(Local<v8::FunctionTemplate> parentTpl);
static Local<v8::FunctionTemplate> GetTemplate();
static Local<v8::Function> GetConstructor();
static NAN_METHOD(New);
static NAN_METHOD(createFromPng);
static NAN_METHOD(getData);
static NAN_METHOD(getFormat);
static NAN_METHOD(getWidth);
static NAN_METHOD(getHeight);
static NAN_METHOD(getStride);
ImageSurface(cairo_surface_t* data) : Surface(data) {};
};
class RecordingSurface: public Surface {
public:
static Nan::Persistent<v8::FunctionTemplate> constructorTemplate;
static Nan::Persistent<v8::Function> constructor;
static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target);
static void SetupTemplate(Local<v8::FunctionTemplate> parentTpl);
static Local<v8::FunctionTemplate> GetTemplate();
static Local<v8::Function> GetConstructor();
static NAN_METHOD(New);
static NAN_METHOD(inkExtents);
static NAN_METHOD(getExtents);
RecordingSurface(cairo_surface_t* data) : Surface(data) {};
};
}; // Cairo
}; // GNodeJS | 1,104 |
451 | /*Header-MicMac-eLiSe-25/06/2007
MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation
eLiSe : ELements of an Image Software Environnement
www.micmac.ign.fr
Copyright : Institut Geographique National
Author : <NAME>
Contributors : <NAME>, <NAME>.
[1] <NAME>, <NAME>.
"A multiresolution and optimization-based image matching approach:
An application to surface reconstruction from SPOT5-HRS stereo imagery."
In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space
(With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006.
[2] <NAME>, "MicMac, un lociel de mise en correspondance
d'images, adapte au contexte geograhique" to appears in
Bulletin d'information de l'Institut Geographique National, 2007.
Francais :
MicMac est un logiciel de mise en correspondance d'image adapte
au contexte de recherche en information geographique. Il s'appuie sur
la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la
licences Cecill-B. Voir en bas de fichier et http://www.cecill.info.
English :
MicMac is an open source software specialized in image matching
for research in geographic information. MicMac is built on the
eLiSe image library. MicMac is governed by the "Cecill-B licence".
See below and http://www.cecill.info.
Header-MicMac-eLiSe-25/06/2007*/
#include "StdAfx.h"
/******************************************/
/* */
/* cTrapuFace */
/* */
/******************************************/
cTrapuFace::cTrapuFace
(
INT aNum
) :
mNum (aNum)
{
}
void cTrapuFace::AddSom(INT aNum)
{
mSoms.push_back(aNum);
}
/******************************************/
/* */
/* cTrapuBat */
/* */
/******************************************/
cTrapuBat::cTrapuBat() :
mFirstPt(true)
{
}
INT cTrapuBat::GetNumSom(Pt3dr aP,REAL aEpsilon)
{
REAL aDMin = aEpsilon*2+1;
INT aKMin = -1;
for (INT aK=0 ; aK<INT(mSoms.size()) ; aK++)
{
REAL aDist = euclid(mSoms[aK]-aP);
if (aDist<aDMin)
{
aDMin = aDist;
aKMin = aK;
}
}
if (aDMin<aEpsilon)
return aKMin;
mSoms.push_back(aP);
return (int) mSoms.size()-1;
}
INT cTrapuBat::NbFaces() const
{
return (INT) mFaces.size();
}
std::vector<Pt3dr> & cTrapuBat::Soms()
{
return mSoms;
}
Pt3dr & cTrapuBat::P0() {return mP0;}
Pt3dr & cTrapuBat::P1() {return mP1;}
std::vector<Pt3dr> cTrapuBat::PtKiemeFace(INT aK) const
{
const std::vector<INT> & aVI = mFaces[aK].mSoms;
std::vector<Pt3dr> aRes;
for (INT aK=0; aK<INT(aVI.size()); aK++)
aRes.push_back(mSoms[aVI[aK]]);
return aRes;
}
void cTrapuBat::AddFace
(
const std::vector<Pt3dr> & aVP,
REAL aEps,
INT aNum
)
{
mFaces.push_back(cTrapuFace(aNum));
INT aNb = (int) aVP.size();
for (INT aK=0 ; aK<aNb ; aK++)
{
Pt3dr aP0 = aVP[(aK+aNb-1)%aNb];
Pt3dr aP1 = aVP[aK];
Pt3dr aP2 = aVP[(aK+1)%aNb];
ElSeg3D aSeg(aP0,aP2);
if (
(aSeg.AbscOfProj(aP1) < aSeg.AbscOfProj(aP0) - aEps)
|| (aSeg.AbscOfProj(aP1) > aSeg.AbscOfProj(aP2) + aEps)
|| (aSeg.DistDoite(aP1) > aEps)
)
{
mFaces.back().AddSom(GetNumSom(aP1,aEps));
}
if (mFirstPt)
{
mFirstPt = false;
mP0 = aP1;
mP1 = aP1;
}
else
{
mP0 = Inf(mP0,aP1);
mP1 = Sup(mP1,aP1);
}
}
}
Pt3dr cTrapuBat::P0() const {return mP0;}
Pt3dr cTrapuBat::P1() const {return mP1;}
void cTrapuBat::PutXML(class cElXMLFileIn & aFile)
{
cElXMLFileIn::cTag aTagGlob(aFile,"BatimentTrapu");
{
cElXMLFileIn::cTag aTagPoints(aFile,"TableauPoints3D");
for (INT aK=0 ; aK<INT(mSoms.size()) ; aK++)
aFile.PutPt3dr(mSoms[aK]);
aTagPoints.NoOp();
}
{
cElXMLFileIn::cTag aTagPoints(aFile,"EnsembleDeFaces");
for (INT aK=0 ; aK<INT(mFaces.size()) ; aK++)
aFile.PutTabInt(mFaces[aK].mSoms,"UneFace");
}
aTagGlob.NoOp();
}
/******************************************/
/* */
/* cElImagesOfTrapu */
/* */
/******************************************/
Im2D_INT1 cElImagesOfTrapu::ImLabel()
{
return mImLabel;
}
Im2D_REAL4 cElImagesOfTrapu::ImZ()
{
return mImZ;
}
Im2D_U_INT1 cElImagesOfTrapu::ImShade()
{
return mImShade;
}
Pt2di cElImagesOfTrapu::Dec() const {return mDec;}
cElImagesOfTrapu::cElImagesOfTrapu
(
const cTrapuBat & aBat,INT aRab,bool Sup,Pt2di * aDec
) :
mImLabel (1,1),
mImZ (1,1),
mImShade (1,1)
{
Pt3dr aP0 = aBat.P0();
Pt3dr aP1 = aBat.P1();
Pt2di aSz(round_ni(aP1.x-aP0.x+2*aRab),round_ni(aP1.y-aP0.y+2*aRab));
mDec = Pt2di(round_ni(aP0.x-aRab),round_ni(aP0.y-aRab));
if (aDec)
mDec = *aDec;
mImLabel.Resize(aSz);
mImZ.Resize(aSz);
ELISE_COPY(mImLabel.all_pts(),-1,mImLabel.out());
ELISE_COPY(mImZ.all_pts(),0.0,mImZ.out());
INT1 ** aDLab = mImLabel.data();
REAL4 ** aDZ = mImZ.data();
for (INT aKF=0 ; aKF<aBat.NbFaces() ; aKF++)
{
// cout << "aKF " << aKF << "\n";
std::vector<Pt3dr> aVP3 = aBat.PtKiemeFace(aKF);
std::vector<Pt2dr> aVP2;
Pt2di aP0( 100000, 100000);
Pt2di aP1(-100000,-100000);
for (INT aKP =0; aKP<INT(aVP3.size()); aKP++)
{
Pt3dr aP3 = aVP3[aKP];
Pt2dr aP2(aP3.x,aP3.y);
aVP2.push_back(aP2);
aP0.SetInf(Pt2di(aP2));
aP1.SetSup(Pt2di(aP2));
}
aP0 -= Pt2di(3,3);
aP1 += Pt2di(3,3);
cElPlan3D aPl(aVP3,0);
for (INT aX=aP0.x; aX<=aP1.x; aX++)
{
for (INT aY=aP0.y; aY<=aP1.y; aY++)
{
Pt2di aP(aX,aY);
if (PointInPoly(aVP2,Pt2dr(aP)))
{
REAL4 aNewZ = (REAL4) aPl.ZOfXY(Pt2dr(aP));
REAL4& aZCur = aDZ[aY-mDec.y][aX-mDec.x];
if (
(aDLab[aY-mDec.y][aX-mDec.x]==-1)
|| (Sup && (aNewZ>aZCur))
|| ((!Sup) && (aNewZ<aZCur))
)
{
aZCur = aNewZ;
aDLab[aY-mDec.y][aX-mDec.x] = aKF;
}
}
}
}
}
mImShade = Shading(aSz,mImZ.in()/1.0,8,0.7);
}
/*Footer-MicMac-eLiSe-25/06/2007
Ce logiciel est un programme informatique servant à la mise en
correspondances d'images pour la reconstruction du relief.
Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
termes.
Footer-MicMac-eLiSe-25/06/2007*/
| 4,377 |
1,821 | /*
* Copyright 2018- The Pixie 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <memory>
#include <string>
#include <sole.hpp>
#include "src/stirling/source_connectors/dynamic_tracer/dynamic_tracing/ir/logicalpb/logical.pb.h"
#include "src/stirling/stirling.h"
#include "src/vizier/services/agent/manager/manager.h"
namespace px {
namespace vizier {
namespace agent {
struct TracepointInfo {
std::string name;
sole::uuid id;
statuspb::LifeCycleState expected_state;
statuspb::LifeCycleState current_state;
std::chrono::time_point<std::chrono::steady_clock> last_updated_at;
};
/**
* TracepointManager handles the lifecycles management of dynamic probes.
*
* This includes tracking all existing probes, listening for new probes from
* the incoming message stream and replying to status requests.
*/
class TracepointManager : public Manager::MessageHandler {
public:
TracepointManager() = delete;
TracepointManager(px::event::Dispatcher* dispatcher, Info* agent_info,
Manager::VizierNATSConnector* nats_conn, stirling::Stirling* stirling,
table_store::TableStore* table_store,
RelationInfoManager* relation_info_manager);
Status HandleMessage(std::unique_ptr<messages::VizierMessage> msg) override;
std::string DebugString() const;
private:
// The tracepoint Monitor that is responsible for watching and updating the state of
// active tracepoints.
void Monitor();
Status HandleRegisterTracepointRequest(const messages::RegisterTracepointRequest& req);
Status HandleRemoveTracepointRequest(const messages::RemoveTracepointRequest& req);
Status UpdateSchema(const stirling::stirlingpb::Publish& publish_proto);
px::event::Dispatcher* dispatcher_;
Manager::VizierNATSConnector* nats_conn_;
stirling::Stirling* stirling_;
table_store::TableStore* table_store_;
RelationInfoManager* relation_info_manager_;
event::TimerUPtr tracepoint_monitor_timer_;
mutable std::mutex mu_;
// Mapping from UUIDs to tracepoint information.
absl::flat_hash_map<sole::uuid, TracepointInfo> tracepoints_;
};
} // namespace agent
} // namespace vizier
} // namespace px
| 889 |
577 | <gh_stars>100-1000
/*
* Copyright (c) 2018-2020, <NAME>
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2019-03-29 <NAME> first implementation
*
* Notes:
* This is a keyword spotting example using NNoM
*
*/
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "nnom.h"
#include "kws_weights.h"
#include "mfcc.h"
#include "math.h"
// NNoM model
nnom_model_t *model;
// 10 labels-1
//const char label_name[][10] = {"yes", "no", "up", "down", "left", "right", "on", "off", "stop", "go", "unknow"};
// 10 labels-2
//const char label_name[][10] = {"marvin", "sheila", "yes", "no", "left", "right", "forward", "backward", "stop", "go", "unknow"};
// full 34 labels
const char label_name[][10] = {"backward", "bed", "bird", "cat", "dog", "down", "eight","five", "follow", "forward",
"four", "go", "happy", "house", "learn", "left", "marvin", "nine", "no", "off", "on", "one", "right",
"seven", "sheila", "six", "stop", "three", "tree", "two", "up", "visual", "yes", "zero", "unknow"};
int16_t audio[512];
char ground_truth[12000][10];
#define SAMP_FREQ 16000
#define AUDIO_FRAME_LEN (512) //31.25ms * 16000hz = 512, // FFT (windows size must be 2 power n)
mfcc_t * mfcc;
//int32_t audio_data[4000]; //32000/8
int dma_audio_buffer[AUDIO_FRAME_LEN]; //512
int16_t audio_buffer_16bit[(int)(AUDIO_FRAME_LEN*1.5)]; // an easy method for 50% overlapping
int audio_sample_i = 0;
//the mfcc feature for kws
#define MFCC_LEN (62)
#define MFCC_COEFFS_FIRST (1) // ignore the mfcc feature before this number
#define MFCC_COEFFS_LEN (13) // the total coefficient to calculate
#define MFCC_TOTAL_NUM_BANK (26) // total number of filter bands
#define MFCC_COEFFS (MFCC_COEFFS_LEN-MFCC_COEFFS_FIRST)
#define MFCC_FEAT_SIZE (MFCC_LEN * MFCC_COEFFS)
float mfcc_features_f[MFCC_COEFFS]; // output of mfcc
int8_t mfcc_features[MFCC_LEN][MFCC_COEFFS]; // ring buffer
int8_t mfcc_features_seq[MFCC_LEN][MFCC_COEFFS]; // sequencial buffer for neural network input.
uint32_t mfcc_feat_index = 0;
// msh debugging controls
bool is_print_abs_mean = false; // to print the mean of absolute value of the mfcc_features_seq[][]
bool is_print_mfcc = false; // to print the raw mfcc features at each update
void Error_Handler()
{
printf("error\n");
}
static int32_t abs_mean(int8_t *p, size_t size)
{
int64_t sum = 0;
for(size_t i = 0; i<size; i++)
{
if(p[i] < 0)
sum+=-p[i];
else
sum += p[i];
}
return sum/size;
}
void quantize_data(float*din, int8_t *dout, uint32_t size, uint32_t int_bit)
{
#define _MAX(x, y) (((x) > (y)) ? (x) : (y))
#define _MIN(x, y) (((x) < (y)) ? (x) : (y))
float limit = (1 << int_bit);
float d;
for(uint32_t i=0; i<size; i++)
{
d = round(_MAX(_MIN(din[i], limit), -limit) / limit * 128);
d = d/128.0f;
dout[i] = round(d *127);
}
}
void thread_kws_serv()
{
#define SaturaLH(N, L, H) (((N)<(L))?(L):(((N)>(H))?(H):(N)))
int *p_raw_audio;
// calculate 13 coefficient, use number #2~13 coefficient. discard #1
// features, offset, bands, 512fft, 0 preempha, attached_energy_to_band0
mfcc = mfcc_create(MFCC_COEFFS_LEN, MFCC_COEFFS_FIRST, MFCC_TOTAL_NUM_BANK, AUDIO_FRAME_LEN, 0.97f, true);
if (audio_sample_i == 15872)
memset(&dma_audio_buffer[128], 0, sizeof(int) * 128); //to fill the latest quarter in the latest frame
p_raw_audio = dma_audio_buffer;
// memory move
// audio buffer = | 256 byte old data | 256 byte new data 1 | 256 byte new data 2 |
// ^------------------------------------------|
memcpy(audio_buffer_16bit, &audio_buffer_16bit[AUDIO_FRAME_LEN], (AUDIO_FRAME_LEN/2)*sizeof(int16_t));
// convert it to 16 bit.
// volume*4
for(int i = 0; i < AUDIO_FRAME_LEN; i++)
{
audio_buffer_16bit[AUDIO_FRAME_LEN/2+i] = p_raw_audio[i];
}
// MFCC
// do the first mfcc with half old data(256) and half new data(256)
// then do the second mfcc with all new data(512).
// take mfcc buffer
for(int i=0; i<2; i++)
{
if ((audio_sample_i != 0 || i==1) && (audio_sample_i != 15872 || i==0)) //to skip computing first mfcc block that's half empty
{
mfcc_compute(mfcc, &audio_buffer_16bit[i*AUDIO_FRAME_LEN/2], mfcc_features_f);
// quantise them using the same scale as training data (in keras), by 2^n.
quantize_data(mfcc_features_f, mfcc_features[mfcc_feat_index], MFCC_COEFFS, 3);
// debug only, to print mfcc data on console
if(0)
{
for(int q=0; q<MFCC_COEFFS; q++)
printf("%d ", mfcc_features[mfcc_feat_index][q]);
printf("\n");
}
mfcc_feat_index++;
if(mfcc_feat_index >= MFCC_LEN)
mfcc_feat_index = 0;
}
}
}
int main(void)
{
uint32_t last_mfcc_index = 0;
uint32_t label;
float prob;
audio_sample_i = 0;
int s = 0; //number of audio samples to scan
float acc;
int correct = 0;
FILE * file;
FILE * ground_truth_f;
char str[10];
int j=0;
int F = 512;
file = fopen ("test_x.txt","r"); //the audio data stored in a textfile
ground_truth_f = fopen ("test_y.txt","r"); //the ground truth textfile
while (!feof (ground_truth_f))
{
fscanf (ground_truth_f, "%s", ground_truth[j]);
j++;
}
fclose (ground_truth_f);
int p = 0;
// create and compile the model
model = nnom_model_create();
while(1)
{
while (p<F)
{
fscanf(file, "%d", &dma_audio_buffer[p]);
p++;
}
p=0;
thread_kws_serv();
audio_sample_i = audio_sample_i + F;
if(audio_sample_i == 15872) //31*512
F = 128; //0.25*512
else
F = 512;
if(audio_sample_i>=16000)
{
// ML
memcpy(nnom_input_data, mfcc_features, MFCC_FEAT_SIZE);
nnom_predict(model, &label, &prob);
// output
printf("%d %s : %d%% - Ground Truth is: %s\n", s, (char*)&label_name[label], (int)(prob * 100),ground_truth[s]);
if(strcmp(ground_truth[s], label_name[label])==0) correct++;
if(s%100==0 && s > 0)
{
acc = ((float)correct/(s) * 100);
printf("Accuracy : %.6f%%\n",acc);
}
audio_sample_i = 0;
F = 512;
s=s+1;
}
if(s>=11000) break;
}
acc = ((float)correct/(s) * 100);
printf("Accuracy : %.6f%%\n",acc);
fclose(file);
}
| 3,756 |
6,873 | <filename>MGWeChat/MGWeChat/Class/Other/ThirdLib/MLLabel/Category/NSAttributedString+MLLabel.h
//
// NSAttributedString+MLLabel.h
// Pods
//
// Created by molon on 15/6/13.
//
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface NSAttributedString (MLLabel)
+ (instancetype)attributedStringWithHTML:(NSString*)htmlString;
@end
| 138 |
645 | #include <iostream>
#include <{{ns_path}}/{{first_stem}}.hpp>
int main() {
std::cout << "I am an example executable\n";
std::cout << "Let's calculate the value...\n";
const auto value = {{root_ns}}::calculate_value();
std::cout << "The value we got is " << value << '\n';
}
| 116 |
7,738 | {
"compilerOptions": {
"outDir": "lib",
"module": "ESNext",
"target": "ES2020",
"lib": [
"es2016",
"dom",
"es5"
],
"jsx": "preserve",
"resolveJsonModule": true,
"experimentalDecorators": true,
"isolatedModules": true,
"skipLibCheck": true,
"declaration": true,
"strictFunctionTypes": true,
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"plugins": [
{
"transform": "@zerollup/ts-transform-paths"
}
]
},
"include": [
"src/"
],
"exclude": [
"node_modules/"
]
} | 286 |
317 | #include "smack.h"
#include <assert.h>
#include <math.h>
// @expect error
int main(void) {
long double NaN = 0.0l / 0.0l;
long double Inf = 1.0l / 0.0l;
long double negInf = -1.0l / 0.0l;
long double val = __VERIFIER_nondet_long_double();
if (!__isnanl(val) && !__isinfl(val) && !__iszerol(val)) {
assert(ceill(val) >= val);
assert(ceill(val) <= val + 0.5);
}
assert(ceill(0.0l) == 0.0l);
assert(ceill(-0.0l) == -0.0l);
int isNeg = __signbitl(ceill(-0.0l));
assert(isNeg);
assert(ceill(Inf) == Inf);
assert(ceill(negInf) == negInf);
assert(__isnanl(ceill(NaN)));
return 0;
}
| 286 |
921 | package sqlancer.citus.gen;
import java.util.List;
import sqlancer.IgnoreMeException;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.postgres.PostgresGlobalState;
import sqlancer.postgres.PostgresSchema.PostgresTable;
import sqlancer.postgres.gen.PostgresAlterTableGenerator;
public class CitusAlterTableGenerator extends PostgresAlterTableGenerator {
public CitusAlterTableGenerator(PostgresTable randomTable, PostgresGlobalState globalState,
boolean generateOnlyKnown) {
super(randomTable, globalState, generateOnlyKnown);
}
public static SQLQueryAdapter create(PostgresTable randomTable, PostgresGlobalState globalState,
boolean generateOnlyKnown) {
return new CitusAlterTableGenerator(randomTable, globalState, generateOnlyKnown).generate();
}
@Override
public List<Action> getActions(ExpectedErrors errors) {
List<Action> action = super.getActions(errors);
CitusCommon.addCitusErrors(errors);
action.remove(Action.ALTER_COLUMN_SET_STATISTICS);
action.remove(Action.ALTER_COLUMN_SET_ATTRIBUTE_OPTION);
action.remove(Action.ALTER_COLUMN_RESET_ATTRIBUTE_OPTION);
action.remove(Action.ALTER_COLUMN_SET_STORAGE);
action.remove(Action.DISABLE_ROW_LEVEL_SECURITY);
action.remove(Action.ENABLE_ROW_LEVEL_SECURITY);
action.remove(Action.FORCE_ROW_LEVEL_SECURITY);
action.remove(Action.NO_FORCE_ROW_LEVEL_SECURITY);
action.remove(Action.CLUSTER_ON);
action.remove(Action.SET_WITHOUT_CLUSTER);
action.remove(Action.SET_WITH_OIDS);
action.remove(Action.SET_WITHOUT_OIDS);
action.remove(Action.SET_LOGGED_UNLOGGED);
action.remove(Action.NOT_OF);
action.remove(Action.OWNER_TO);
action.remove(Action.REPLICA_IDENTITY);
if (action.isEmpty()) {
throw new IgnoreMeException();
}
return action;
}
}
| 801 |
455 | <reponame>madhubandubey9/StarEngine
#include "UIDock.h"
#include "UIObject.h"
#include "../GraphicsManager.h"
namespace star
{
UIDock::UIDock(const tstring & name)
: UIObject(name)
, m_Dimensions(
GraphicsManager::GetInstance()->GetScreenResolution().x,
GraphicsManager::GetInstance()->GetScreenResolution().y)
{
}
UIDock::UIDock(
const tstring & name,
float32 width,
float32 height
)
: UIObject(name)
, m_Dimensions(width, height)
{
}
UIDock::~UIDock(void)
{
}
void UIDock::SetHorizontalAlignment(
HorizontalAlignment alignment,
bool redefineCenter
)
{
if(redefineCenter)
{
switch(alignment)
{
case HorizontalAlignment::Left:
GetTransform()->SetCenterX(0);
break;
case HorizontalAlignment::Center:
GetTransform()->SetCenterX(
m_Dimensions.x / 2.0f
);
break;
case HorizontalAlignment::Right:
GetTransform()->SetCenterX(
m_Dimensions.x
);
break;
}
}
UIObject::SetHorizontalAlignment(
alignment,
redefineCenter
);
}
void UIDock::SetVerticalAlignment(
VerticalAlignment alignment,
bool redefineCenter
)
{
if(redefineCenter)
{
switch(alignment)
{
case VerticalAlignment::Bottom:
GetTransform()->SetCenterY(0);
break;
case VerticalAlignment::Center:
GetTransform()->SetCenterY(
m_Dimensions.y / 2.0f
);
break;
case VerticalAlignment::Top:
GetTransform()->SetCenterY(
m_Dimensions.y
);
break;
}
}
UIObject::SetVerticalAlignment(
alignment,
redefineCenter
);
}
void UIDock::SetDimensions(const vec2 & dimensions)
{
m_Dimensions = dimensions;
RepositionChildren();
}
void UIDock::SetDimensions(float32 x, float32 y)
{
m_Dimensions.x = x;
m_Dimensions.y = y;
RepositionChildren();
}
void UIDock::SetDimensionsX(float32 x)
{
m_Dimensions.x = x;
RepositionChildren();
}
void UIDock::SetDimensionsY(float32 y)
{
m_Dimensions.y = y;
RepositionChildren();
}
vec2 UIDock::GetDimensions() const
{
return m_Dimensions;
}
bool UIDock::CheckCulling(
float32 left,
float32 right,
float32 top,
float32 bottom
)
{
return
(m_Position.x + m_Dimensions.x >= left && m_Position.x <= right)
&&
(m_Position.y + m_Dimensions.y >= bottom && m_Position.y <= top);
}
}
| 1,201 |
634 | /****************************************************************
* 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.james.mailbox.spamassassin;
import java.util.Objects;
import java.util.Optional;
import org.apache.james.util.Host;
import com.google.common.base.MoreObjects;
public class SpamAssassinConfiguration {
private final Optional<Host> host;
public SpamAssassinConfiguration(Optional<Host> host) {
this.host = host;
}
public boolean isEnable() {
return host.isPresent();
}
public Optional<Host> getHost() {
return host;
}
@Override
public final boolean equals(Object o) {
if (o instanceof SpamAssassinConfiguration) {
SpamAssassinConfiguration that = (SpamAssassinConfiguration) o;
return Objects.equals(this.host, that.host);
}
return false;
}
@Override
public final int hashCode() {
return Objects.hash(host);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("host", host)
.toString();
}
}
| 861 |
302 | # -*- coding: utf-8 -*-
# Copyright 2019 Yelp 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.
from __future__ import absolute_import
from kafka_utils.kafka_check.commands.replica_unavailability import _prepare_output
UNAVAILABLE_REPLICAS = [
('Topic0', 0),
('Topic0', 1),
('Topic13', 13),
]
UNAVAILABLE_BROKERS = [123456, 987456]
def test_prepare_output_ok_no_verbose():
expected = {
'message': "All replicas available for communication.",
'raw': {
'replica_unavailability_count': 0,
}
}
assert _prepare_output([], [], False, -1) == expected
def test_prepare_output_ok_verbose():
expected = {
'message': "All replicas available for communication.",
'raw': {
'replica_unavailability_count': 0,
'partitions': [],
}
}
assert _prepare_output([], [], True, -1) == expected
def test_prepare_output_critical_verbose():
expected = {
'message': "3 replicas unavailable for communication. Unavailable Brokers: 123456, 987456",
'verbose': (
"Partitions:\n"
"Topic0:0\n"
"Topic0:1\n"
"Topic13:13"
),
'raw': {
'replica_unavailability_count': 3,
'partitions': [
{'partition': 0, 'topic': 'Topic0'},
{'partition': 1, 'topic': 'Topic0'},
{'partition': 13, 'topic': 'Topic13'},
],
}
}
assert _prepare_output(UNAVAILABLE_REPLICAS, UNAVAILABLE_BROKERS, True, -1) == expected
def test_prepare_output_critical_verbose_with_head():
expected = {
'message': "3 replicas unavailable for communication. Unavailable Brokers: 123456, 987456",
'verbose': (
"Top 2 partitions:\n"
"Topic0:0\n"
"Topic0:1"
),
'raw': {
'replica_unavailability_count': 3,
'partitions': [
{'partition': 0, 'topic': 'Topic0'},
{'partition': 1, 'topic': 'Topic0'},
],
}
}
assert _prepare_output(UNAVAILABLE_REPLICAS, UNAVAILABLE_BROKERS, True, 2) == expected
| 1,183 |
16,110 | """
Check that the rev value in the example pre-commit configuration matches
the latest version of Black. This saves us from forgetting to update that
during the release process.
Why can't we just use `rev: stable` and call it a day? Well pre-commit
won't auto update the hook as you may expect (and for good reasons, some
technical and some pragmatic). Encouraging bad practice is also just
not ideal. xref: https://github.com/psf/black/issues/420
"""
import os
import sys
import commonmark
import yaml
from bs4 import BeautifulSoup
def main(changes: str, source_version_control: str) -> None:
changes_html = commonmark.commonmark(changes)
changes_soup = BeautifulSoup(changes_html, "html.parser")
headers = changes_soup.find_all("h2")
latest_tag, *_ = [
header.string for header in headers if header.string != "Unreleased"
]
source_version_control_html = commonmark.commonmark(source_version_control)
source_version_control_soup = BeautifulSoup(
source_version_control_html, "html.parser"
)
pre_commit_repos = yaml.safe_load(
source_version_control_soup.find(class_="language-yaml").string
)["repos"]
for repo in pre_commit_repos:
pre_commit_rev = repo["rev"]
if not pre_commit_rev == latest_tag:
print(
"Please set the rev in ``source_version_control.md`` to be the latest "
f"one.\nExpected {latest_tag}, got {pre_commit_rev}.\n"
)
sys.exit(1)
if __name__ == "__main__":
with open("CHANGES.md", encoding="utf-8") as fd:
changes = fd.read()
with open(
os.path.join("docs", "integrations", "source_version_control.md"),
encoding="utf-8",
) as fd:
source_version_control = fd.read()
main(changes, source_version_control)
| 694 |
1,604 | <gh_stars>1000+
package org.bouncycastle.oer.its;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
/**
* <pre>
* SEQUENCE SIZE(3..MAX) OF TwoDLocation
* </pre>
*/
public class PolygonalRegion
extends ASN1Object
implements RegionInterface
{
private final List<TwoDLocation> points;
public PolygonalRegion(List<TwoDLocation> locations)
{
points = Collections.unmodifiableList(locations);
}
public static PolygonalRegion getInstance(Object o)
{
if (o instanceof PolygonalRegion)
{
return (PolygonalRegion)o;
}
else if (o != null)
{
return new PolygonalRegion(Utils.fillList(TwoDLocation.class, ASN1Sequence.getInstance(o)));
}
return null;
}
public List<TwoDLocation> getPoints()
{
return points;
}
public ASN1Primitive toASN1Primitive()
{
return Utils.toSequence(points);
}
public static class Builder
{
private List<TwoDLocation> locations = new ArrayList<TwoDLocation>();
public Builder setLocations(List<TwoDLocation> locations)
{
this.locations = locations;
return this;
}
public Builder setLocations(TwoDLocation... locations)
{
this.locations.addAll(Arrays.asList(locations));
return this;
}
public PolygonalRegion createPolygonalRegion()
{
return new PolygonalRegion(locations);
}
}
}
| 748 |
2,151 | <filename>net/third_party/quiche/src/http2/hpack/varint/hpack_varint_encoder.cc
// 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.
#include "net/third_party/quiche/src/http2/hpack/varint/hpack_varint_encoder.h"
#include "net/third_party/quiche/src/http2/platform/api/http2_logging.h"
namespace http2 {
HpackVarintEncoder::HpackVarintEncoder()
: varint_(0), encoding_in_progress_(false) {}
unsigned char HpackVarintEncoder::StartEncoding(uint8_t high_bits,
uint8_t prefix_length,
uint64_t varint) {
DCHECK(!encoding_in_progress_);
DCHECK_EQ(0u, varint_);
DCHECK_LE(1u, prefix_length);
DCHECK_LE(prefix_length, 8u);
// prefix_mask defines the sequence of low-order bits of the first byte
// that encode the prefix of the value. It is also the marker in those bits
// of the first byte indicating that at least one extension byte is needed.
const uint8_t prefix_mask = (1 << prefix_length) - 1;
DCHECK_EQ(0, high_bits & prefix_mask);
if (varint < prefix_mask) {
// The integer fits into the prefix in its entirety.
return high_bits | static_cast<unsigned char>(varint);
}
// We need extension bytes.
varint_ = varint - prefix_mask;
encoding_in_progress_ = true;
return high_bits | prefix_mask;
}
size_t HpackVarintEncoder::ResumeEncoding(size_t max_encoded_bytes,
Http2String* output) {
DCHECK(encoding_in_progress_);
DCHECK_NE(0u, max_encoded_bytes);
size_t encoded_bytes = 0;
while (encoded_bytes < max_encoded_bytes) {
++encoded_bytes;
if (varint_ < 128) {
// Encode final seven bits, with continuation bit set to zero.
output->push_back(varint_);
varint_ = 0;
encoding_in_progress_ = false;
break;
}
// Encode the next seven bits, with continuation bit set to one.
output->push_back(0b10000000 | (varint_ % 128));
varint_ >>= 7;
}
return encoded_bytes;
}
bool HpackVarintEncoder::IsEncodingInProgress() const {
return encoding_in_progress_;
}
} // namespace http2
| 899 |
819 | /*
Copyright 2017 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.
*/
#ifndef VR_SEURAT_COMPRESSOR_RESAMPLER_GL_LINEAR_UPSAMPLER_H_
#define VR_SEURAT_COMPRESSOR_RESAMPLER_GL_LINEAR_UPSAMPLER_H_
#include "ion/math/vector.h"
#include "seurat/compressor/resampler/resampler.h"
#include "seurat/image/image.h"
namespace seurat {
namespace compressor {
// Implements a method for upsampling images that simulates the OpenGL's
// GL_LINEAR algorithm. Half-pixel texture borders are assumed: the vertices of
// a textured quad have texture coordinates {0.5f, 0.5f},
// {tsize[0] - 0.5f, 0.5f}, {tsize[0] - 0.5f, tsize[1] - 0.5f},
// {0.5f, tsize[1] - 0.5f}, where tsize is the texture size.
class GlLinearUpsampler : public Resampler {
public:
// Returns an image of size |target_size| given the source image |image|.
image::Image4f Resample(
const image::Image4f& image,
const ion::math::Vector2i& target_size) const override;
};
} // namespace compressor
} // namespace seurat
#endif // VR_SEURAT_COMPRESSOR_RESAMPLER_GL_LINEAR_UPSAMPLER_H_
| 535 |
442 | /*
SoLoud audio engine
Copyright (c) 2013-2015 <NAME>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "soloud.h"
#include "soloud_echofilter.h"
namespace SoLoud
{
EchoFilterInstance::EchoFilterInstance(EchoFilter *aParent)
{
mParent = aParent;
mBuffer = 0;
mBufferLength = 0;
mOffset = 0;
initParams(1);
}
void EchoFilterInstance::filter(float *aBuffer, unsigned int aSamples, unsigned int aChannels, float aSamplerate, double aTime)
{
updateParams(aTime);
if (mBuffer == 0)
{
mBufferLength = (int)ceil(mParent->mDelay * aSamplerate);
mBuffer = new float[mBufferLength * aChannels];
unsigned int i;
for (i = 0; i < mBufferLength * aChannels; i++)
{
mBuffer[i] = 0;
}
}
float decay = mParent->mDecay;
unsigned int i, j;
int prevofs = (mOffset + mBufferLength - 1) % mBufferLength;
for (i = 0; i < aSamples; i++)
{
for (j = 0; j < aChannels; j++)
{
int chofs = j * mBufferLength;
int bchofs = j * aSamples;
mBuffer[mOffset + chofs] = mParent->mFilter * mBuffer[prevofs + chofs] + (1 - mParent->mFilter) * mBuffer[mOffset + chofs];
float n = aBuffer[i + bchofs] + mBuffer[mOffset + chofs] * decay;
mBuffer[mOffset + chofs] = n;
aBuffer[i + bchofs] += (n - aBuffer[i + bchofs]) * mParam[0];
}
prevofs = mOffset;
mOffset = (mOffset + 1) % mBufferLength;
}
}
EchoFilterInstance::~EchoFilterInstance()
{
delete[] mBuffer;
}
EchoFilter::EchoFilter()
{
mDelay = 0.3f;
mDecay = 0.7f;
mFilter = 0.0f;
}
result EchoFilter::setParams(float aDelay, float aDecay, float aFilter)
{
if (aDelay <= 0 || aDecay <= 0 || aFilter < 0 || aFilter >= 1.0f)
return INVALID_PARAMETER;
mDecay = aDecay;
mDelay = aDelay;
mFilter = aFilter;
return 0;
}
FilterInstance *EchoFilter::createInstance()
{
return new EchoFilterInstance(this);
}
}
| 1,015 |
6,036 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "gtest/gtest.h"
#include "test/providers/provider_test_utils.h"
namespace onnxruntime {
namespace test {
// Disable TensorRT on the tests because axis=0 is not supported
template <typename T>
void RunUniqueTest(const std::vector<int64_t>& X_dims,
const std::vector<T>& X,
const int64_t* axis,
bool sorted,
const std::vector<int64_t>& Y_dims,
const std::vector<T>& Y,
const std::vector<int64_t>& indices_dims,
const std::vector<int64_t>& indices,
const std::vector<int64_t>& inverse_indices_dims,
const std::vector<int64_t>& inverse_indices,
const std::vector<int64_t>& counts_dims,
const std::vector<int64_t>& counts) {
OpTester test("Unique", 11);
if (axis) {
test.AddAttribute("axis", *axis);
}
test.AddAttribute("sorted", static_cast<int64_t>(sorted));
test.AddInput<T>("X", X_dims, X);
test.AddOutput<T>("Y", Y_dims, Y);
test.AddOutput<int64_t>("indices", indices_dims, indices);
test.AddOutput<int64_t>("inverse_indices", inverse_indices_dims, inverse_indices);
test.AddOutput<int64_t>("counts", counts_dims, counts);
test.Run();
}
TEST(Unique, Flatten_Unsorted) {
const std::vector<int64_t> X_dims{2, 3};
const std::vector<float> X{1.f, 4.f, 1.f, 2.f, 2.f, 0.f};
const int64_t* axis = nullptr;
bool sorted = false;
const std::vector<int64_t> Y_dims{4};
const std::vector<float> Y{1.f, 4.f, 2.f, 0.f};
const std::vector<int64_t> indices_dims{4};
const std::vector<int64_t> indices{0, 1, 3, 5};
const std::vector<int64_t> inverse_indices_dims{6};
const std::vector<int64_t> inverse_indices{0, 1, 0, 2, 2, 3};
const std::vector<int64_t> counts_dims{4};
const std::vector<int64_t> counts{2, 1, 2, 1};
RunUniqueTest<float>(X_dims, X, axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
// TEMPORARY. The ONNX test expected data for Y for unique_not_sorted_without_axis doesn't match the comments in that
// test and is in sorted order. This unit test validates we have the correct behavior, pending fixing the onnx test
// data.
TEST(Unique, Flatten_Unsorted_MatchOnnxTest) {
const std::vector<int64_t> X_dims{6};
const std::vector<float> X{2.f, 1.f, 1.f, 3.f, 4.f, 3.f};
const int64_t* axis = nullptr;
bool sorted = false;
const std::vector<int64_t> Y_dims{4};
const std::vector<float> Y{2.f, 1.f, 3.f, 4.f};
const std::vector<int64_t> indices_dims{4};
const std::vector<int64_t> indices{0, 1, 3, 4};
const std::vector<int64_t> inverse_indices_dims{6};
const std::vector<int64_t> inverse_indices{0, 1, 1, 2, 3, 2};
const std::vector<int64_t> counts_dims{4};
const std::vector<int64_t> counts{1, 2, 2, 1};
RunUniqueTest<float>(X_dims, X, axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, Flatten_Sorted) {
const std::vector<int64_t> X_dims{2, 3};
const std::vector<float> X{1.f, 4.f, 1.f, 2.f, 2.f, 0.f};
const int64_t* axis = nullptr;
bool sorted = true;
const std::vector<int64_t> Y_dims{4};
const std::vector<float> Y{0.f, 1.f, 2.f, 4.f};
const std::vector<int64_t> indices_dims{4};
const std::vector<int64_t> indices{5, 0, 3, 1};
const std::vector<int64_t> inverse_indices_dims{6};
const std::vector<int64_t> inverse_indices{1, 3, 1, 2, 2, 0};
const std::vector<int64_t> counts_dims{4};
const std::vector<int64_t> counts{1, 2, 2, 1};
RunUniqueTest<float>(X_dims, X, axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, Flatten_Sorted_String) {
const std::vector<int64_t> X_dims{2, 3};
const std::vector<std::string> X{"1.f", "4.f", "1.f", "2.f", "2.f", "0.f"};
const int64_t* axis = nullptr;
bool sorted = true;
const std::vector<int64_t> Y_dims{4};
const std::vector<std::string> Y{"0.f", "1.f", "2.f", "4.f"};
const std::vector<int64_t> indices_dims{4};
const std::vector<int64_t> indices{5, 0, 3, 1};
const std::vector<int64_t> inverse_indices_dims{6};
const std::vector<int64_t> inverse_indices{1, 3, 1, 2, 2, 0};
const std::vector<int64_t> counts_dims{4};
const std::vector<int64_t> counts{1, 2, 2, 1};
RunUniqueTest<std::string>(X_dims, X, axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, NoOptionalOutput) {
const std::vector<int64_t> X_dims{2, 4};
const std::vector<int8_t> X{1, 4, -1, 2, 2, 0, -1, 4};
bool sorted = true;
const std::vector<int64_t> Y_dims{5};
const std::vector<int8_t> Y{-1, 0, 1, 2, 4};
OpTester test("Unique", 11);
test.AddAttribute("sorted", static_cast<int64_t>(sorted));
test.AddInput("X", X_dims, X);
test.AddOutput("Y", Y_dims, Y);
test.Run();
}
TEST(Unique, Axis0_Unsorted) {
const std::vector<int64_t> X_dims{4, 2};
const std::vector<float> X{0.f, 1.f,
1.f, 1.f,
0.f, 1.f,
1.f, 0.f};
const int64_t axis = 0;
bool sorted = false;
const std::vector<int64_t> Y_dims{3, 2};
const std::vector<float> Y{0.f, 1.f,
1.f, 1.f,
1.f, 0.f};
const std::vector<int64_t> indices_dims{3};
const std::vector<int64_t> indices{0, 1, 3};
const std::vector<int64_t> inverse_indices_dims{4};
const std::vector<int64_t> inverse_indices{0, 1, 0, 2};
const std::vector<int64_t> counts_dims{3};
const std::vector<int64_t> counts{2, 1, 1};
RunUniqueTest<float>(X_dims, X, &axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, Axis0_Sorted) {
const std::vector<int64_t> X_dims{4, 2};
const std::vector<float> X{0.f, 1.f,
1.f, 1.f,
0.f, 1.f,
1.f, 0.f};
const int64_t axis = 0;
bool sorted = true;
const std::vector<int64_t> Y_dims{3, 2};
const std::vector<float> Y{0.f, 1.f,
1.f, 0.f,
1.f, 1.f};
const std::vector<int64_t> indices_dims{3};
const std::vector<int64_t> indices{0, 3, 1};
const std::vector<int64_t> inverse_indices_dims{4};
const std::vector<int64_t> inverse_indices{0, 2, 0, 1};
const std::vector<int64_t> counts_dims{3};
const std::vector<int64_t> counts{2, 1, 1};
RunUniqueTest<float>(X_dims, X, &axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, Axis0_Unsorted_String) {
const std::vector<int64_t> X_dims{4, 2};
const std::vector<std::string> X{"0.f", "1.f",
"1.f", "1.f",
"0.f", "1.f",
"1.f", "0.f"};
const int64_t axis = 0;
bool sorted = false;
const std::vector<int64_t> Y_dims{3, 2};
const std::vector<std::string> Y{"0.f", "1.f",
"1.f", "1.f",
"1.f", "0.f"};
const std::vector<int64_t> indices_dims{3};
const std::vector<int64_t> indices{0, 1, 3};
const std::vector<int64_t> inverse_indices_dims{4};
const std::vector<int64_t> inverse_indices{0, 1, 0, 2};
const std::vector<int64_t> counts_dims{3};
const std::vector<int64_t> counts{2, 1, 1};
RunUniqueTest<std::string>(X_dims, X, &axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, Axis1_Unsorted) {
const std::vector<int64_t> X_dims{2, 4, 2};
const std::vector<int8_t> X{1, 1,
0, 1,
2, 1,
0, 1,
1, 1,
0, 1,
2, 1,
0, 1};
const int64_t axis = 1;
bool sorted = false;
const std::vector<int64_t> Y_dims{2, 3, 2};
const std::vector<int8_t> Y{1, 1,
0, 1,
2, 1,
1, 1,
0, 1,
2, 1};
const std::vector<int64_t> indices_dims{3};
const std::vector<int64_t> indices{0, 1, 2};
const std::vector<int64_t> inverse_indices_dims{4};
const std::vector<int64_t> inverse_indices{0, 1, 2, 1};
const std::vector<int64_t> counts_dims{3};
const std::vector<int64_t> counts{1, 2, 1};
RunUniqueTest<int8_t>(X_dims, X, &axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, Axis1_Sorted) {
const std::vector<int64_t> X_dims{2, 4, 2};
const std::vector<int64_t> X{1, 1,
0, 1,
2, 1,
0, 1,
1, 1,
0, 1,
2, 1,
0, 1};
const int64_t axis = 1;
bool sorted = true;
const std::vector<int64_t> Y_dims{2, 3, 2};
const std::vector<int64_t> Y{0, 1,
1, 1,
2, 1,
0, 1,
1, 1,
2, 1};
const std::vector<int64_t> indices_dims{3};
const std::vector<int64_t> indices{1, 0, 2};
const std::vector<int64_t> inverse_indices_dims{4};
const std::vector<int64_t> inverse_indices{1, 0, 2, 0};
const std::vector<int64_t> counts_dims{3};
const std::vector<int64_t> counts{2, 1, 1};
RunUniqueTest<int64_t>(X_dims, X, &axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, Axis2_Unsorted) {
const std::vector<int64_t> X_dims{2, 2, 4};
const std::vector<int64_t> X{1, 1, 0, 1,
2, 1, 0, 1,
1, 1, 0, 1,
2, 1, 0, 1};
const int64_t axis = 2;
bool sorted = false;
const std::vector<int64_t> Y_dims{2, 2, 3};
const std::vector<int64_t> Y{1, 1, 0,
2, 1, 0,
1, 1, 0,
2, 1, 0};
const std::vector<int64_t> indices_dims{3};
const std::vector<int64_t> indices{0, 1, 2};
const std::vector<int64_t> inverse_indices_dims{4};
const std::vector<int64_t> inverse_indices{0, 1, 2, 1};
const std::vector<int64_t> counts_dims{3};
const std::vector<int64_t> counts{1, 2, 1};
RunUniqueTest<int64_t>(X_dims, X, &axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, Axis2_Sorted) {
const std::vector<int64_t> X_dims{2, 2, 4};
const std::vector<int64_t> X{1, 1, 0, 1,
2, 1, 0, 1,
1, 1, 0, 1,
2, 1, 0, 1};
const int64_t axis = 2;
bool sorted = true;
const std::vector<int64_t> Y_dims{2, 2, 3};
const std::vector<int64_t> Y{0, 1, 1,
0, 1, 2,
0, 1, 1,
0, 1, 2};
const std::vector<int64_t> indices_dims{3};
const std::vector<int64_t> indices{2, 1, 0};
const std::vector<int64_t> inverse_indices_dims{4};
const std::vector<int64_t> inverse_indices{2, 1, 0, 1};
const std::vector<int64_t> counts_dims{3};
const std::vector<int64_t> counts{1, 2, 1};
RunUniqueTest<int64_t>(X_dims, X, &axis, sorted, Y_dims, Y, indices_dims, indices,
inverse_indices_dims, inverse_indices, counts_dims, counts);
}
TEST(Unique, InvalidAxis) {
const int64_t axis = 12;
const std::vector<int64_t> X_dims{2, 3};
const std::vector<float> X{1.f, 4.f, 1.f, 2.f, 2.f, 0.f};
const std::vector<int64_t> Y_dims{};
const std::vector<float> Y{0.f};
OpTester test("Unique", 11);
test.AddAttribute("axis", axis);
test.AddInput("X", X_dims, X);
test.AddOutput("Y", Y_dims, Y);
test.Run(OpTester::ExpectResult::kExpectFailure, "[ShapeInferenceError] Invalid value for attribute axis");
}
// check empty input is gracefully handled
TEST(Unique, EmptyInput) {
const std::vector<int64_t> X_dims{0};
const std::vector<float> X{};
const std::vector<int64_t> Y_dims{0};
const std::vector<float> Y{};
const std::vector<int64_t> indices_dims{0};
const std::vector<int64_t> indices{};
const std::vector<int64_t> inverse_indices_dims{0};
const std::vector<int64_t> inverse_indices{};
const std::vector<int64_t> counts_dims{0};
const std::vector<int64_t> counts{};
OpTester test("Unique", 11);
test.AddInput("X", X_dims, X);
test.AddOutput("Y", Y_dims, Y);
test.AddOutput<int64_t>("indices", indices_dims, indices);
test.AddOutput<int64_t>("inverse_indices", inverse_indices_dims, inverse_indices);
test.AddOutput<int64_t>("counts", counts_dims, counts);
test.Run();
}
} // namespace test
} // namespace onnxruntime
| 7,003 |
2,116 | /*
* Copyright (C) 2018 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.cloud.demo.iot.nirvana.frontend.datastore;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Parent;
/** Class that represents Datastore entity describing a temperature for city */
@Entity
public class CityTemperature {
@Parent Key<CityEntity> city;
@Id long id;
double temperature;
public CityTemperature() {
;
}
/**
* The temperature of a city
*
* @param city reference to the parent entity (the CityEntity)
* @param id the id of this temperature (UNIX epoch)
* @param temperature the temperature of the city
*/
public CityTemperature(Key<CityEntity> city, long id, double temperature) {
this.city = city;
this.id = id;
this.temperature = temperature;
}
public Key<CityEntity> getCity() {
return city;
}
public void setCity(Key<CityEntity> city) {
this.city = city;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
}
| 554 |
3,153 | # -*- coding: utf-8 -*-
"""
@author:XuMing(<EMAIL>), Abtion(<EMAIL>)
@description:
"""
import os
import json
import torch
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
class DataCollator:
def __init__(self, tokenizer):
self.tokenizer = tokenizer
def __call__(self, data):
ori_texts, cor_texts, wrong_idss = zip(*data)
encoded_texts = [self.tokenizer.tokenize(t) for t in ori_texts]
max_len = max([len(t) for t in encoded_texts]) + 2
det_labels = torch.zeros(len(ori_texts), max_len).long()
for i, (encoded_text, wrong_ids) in enumerate(zip(encoded_texts, wrong_idss)):
for idx in wrong_ids:
margins = []
for word in encoded_text[:idx]:
if word == '[UNK]':
break
if word.startswith('##'):
margins.append(len(word) - 3)
else:
margins.append(len(word) - 1)
margin = sum(margins)
move = 0
while (abs(move) < margin) or (idx + move >= len(encoded_text)) \
or encoded_text[idx + move].startswith('##'):
move -= 1
det_labels[i, idx + move + 1] = 1
return ori_texts, cor_texts, det_labels
class CscDataset(Dataset):
def __init__(self, file_path):
self.data = json.load(open(file_path, 'r', encoding='utf-8'))
def __len__(self):
return len(self.data)
def __getitem__(self, index):
return self.data[index]['original_text'], self.data[index]['correct_text'], self.data[index]['wrong_ids']
def make_loaders(collate_fn, train_path='', valid_path='', test_path='',
batch_size=32, num_workers=4):
train_loader = None
if train_path and os.path.exists(train_path):
train_loader = DataLoader(CscDataset(train_path),
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
collate_fn=collate_fn)
valid_loader = None
if valid_path and os.path.exists(valid_path):
valid_loader = DataLoader(CscDataset(valid_path),
batch_size=batch_size,
num_workers=num_workers,
collate_fn=collate_fn)
test_loader = None
if test_path and os.path.exists(test_path):
test_loader = DataLoader(CscDataset(test_path),
batch_size=batch_size,
num_workers=num_workers,
collate_fn=collate_fn)
return train_loader, valid_loader, test_loader
| 1,521 |
302 | import drawBot
drawBot.size(200, 200)
drawBot.stroke(0)
drawBot.strokeWidth(10)
drawBot.fill(1, 0.3, 0)
drawBot.polygon((40, 40), (40, 160))
drawBot.polygon((60, 40), (60, 160), (130, 160))
drawBot.polygon((100, 40), (160, 160), (160, 40), close=False)
| 107 |
1,370 | <gh_stars>1000+
package ser;
import org.junit.Test;
import org.nustaq.serialization.FSTConfiguration;
/**
* Created by ruedi on 12.12.14.
*/
public class BasicAndroidTest extends BasicFSTTest {
@Override
protected FSTConfiguration getTestConfiguration() {
FSTConfiguration.isAndroid = true;
return FSTConfiguration.createAndroidDefaultConfiguration();
}
@Override @Test
public void testSelfRef() {
super.testSelfRef();
}
@Override @Test
public void testSelfRefArr() {
super.testSelfRefArr();
}
}
| 209 |
413 | <reponame>CatKang/zeppelin
// Copyright 2017 Qihoo
//
// 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 SRC_NODE_ZP_DATA_ENTITY_H_
#define SRC_NODE_ZP_DATA_ENTITY_H_
#include <string>
#include <ostream>
class Node {
public:
std::string ip;
int port;
Node()
: port(0) {}
Node(const std::string& _ip, const int& _port)
: ip(_ip), port(_port) {}
Node(const Node& node)
: ip(node.ip),
port(node.port) {}
Node& operator=(const Node& node) {
ip = node.ip;
port = node.port;
return *this;
}
bool empty() {
return (ip.empty() || port == 0);
}
bool operator== (const Node& rhs) const {
return (ip == rhs.ip && port == rhs.port);
}
bool operator!= (const Node& rhs) const {
return (ip != rhs.ip || port != rhs.port);
}
bool operator< (const Node& rhs) const {
return (ip < rhs.ip ||
(ip == rhs.ip && port < rhs.port));
}
friend std::ostream& operator<< (std::ostream& stream, const Node& node) {
stream << node.ip << ":" << node.port;
return stream;
}
};
#endif // SRC_NODE_ZP_DATA_ENTITY_H_
| 582 |
309 | #! /usr/bin/env python2
# -*- coding: utf-8; mode: python -*-
""" Small experimental bot for our Slack team at SCEE (https://sceeteam.slack.com/), CentraleSupélec campus de Rennes.
It reads a file full of quotes (from TV shows), and post one randomly at random times on the channel #random.
Requirements:
- slackclient is required
- If progressbar (https://pypi.python.org/pypi/progressbar) is installed, use it.
About:
- *Date:* 13/02/2017.
- *Author:* <NAME>, (C) 2017
- *Licence:* MIT Licence (http://lbesson.mit-license.org).
"""
from __future__ import division, print_function # Python 2 compatibility
import sys
import os
import random
from os.path import join, expanduser
import time
import logging
logging.basicConfig(
format="%(asctime)s %(levelname)s: %(message)s",
datefmt='%m-%d-%Y %I:%M:%S %p',
level=logging.INFO
)
from numpy.random import poisson
from slackclient import SlackClient
sys.path.insert(0, '..')
# Import algorithms
from Policies import Thompson
# --- Parameters of the bot
MINUTES = 60
HOURS = 60 * MINUTES
QUOTE_FILE = os.getenv("quotes", expanduser(join("~", ".quotes.txt")))
SLACK_TOKEN = open(expanduser(join("~", ".slack_api_key")), 'r').readline().strip()
USE_CHANNEL = False # DEBUG
USE_CHANNEL = True
DONTSEND = True # DEBUG
DONTSEND = False
SLACK_USER = "@lilian"
SLACK_CHANNEL = "#random"
SLACK_CHANNEL = "#test"
DEFAULT_CHANNEL = SLACK_CHANNEL if USE_CHANNEL else SLACK_USER
MEAN_TIME = (1 * HOURS) if USE_CHANNEL else 60
URL = "https://bitbucket.org/lbesson/bin/src/master/my-small-slack-bot.py"
POSITIVE_REACTIONS = ['up', '+1', 'thumbsup']
NEGATIVES_REACTIONS = ['down', '-1', 'thumbsdown']
# --- Functions
def sleeptime(lmbda=MEAN_TIME, use_poisson=True):
"""Random time until next message."""
if use_poisson:
return poisson(lmbda)
else:
return lmbda
def sleep_bar(secs):
"""Sleep with a bar, or not"""
try:
# From progressbar example #3, https://github.com/niltonvolpato/python-progressbar/blob/master/examples.py#L67
from progressbar import Bar, ETA, ProgressBar, ReverseBar
widgets = [Bar('>'), ' ', ETA(), ' ', ReverseBar('<')]
pbar = ProgressBar(widgets=widgets, maxval=100).start()
for i in range(100):
# do something
time.sleep(secs / 110.)
pbar.update(i)
pbar.finish()
except ImportError:
time.sleep(secs)
def random_line(lines):
"""Read the file and select one line."""
try:
return random.choice(lines).replace('`', '').replace('_', '')
except Exception as e: # Default quote
logging.info("Failed to read a random line from this list with {} lines...".format(len(lines))) # DEBUG
return "I love you !"
def print_TS(TS, name_channels):
print("For this Thompson sampling algorithm ({}), the posteriors on channels are currently:".format(TS))
for arm in range(TS.nbArms):
print(" - For arm #{:^2} named {:^15} : posterior = {} ...".format(arm, name_channels[arm], TS.posterior[arm]))
# --- API calls
def get_list_channels(sc):
"""Get list of channels."""
# https://api.slack.com/methods/channels.list
response = sc.api_call(
"channels.list",
)
return response['channels']
def get_full_list_channels(sc, list_channels=None):
"""Get list of channels."""
if list_channels is None:
list_channels = get_list_channels(sc)
full_list_channels = []
for c in list_channels:
# https://api.slack.com/methods/channels.info
response = sc.api_call(
"channels.info", channel=c['id']
)
if response['ok']:
full_list_channels.append(response['channel'])
return full_list_channels
def choose_channel(list_channels):
"""Any method to choose the channels. Pure random currently."""
return random.choice(list_channels)['name']
def most_popular_channel(list_channels):
"""Any method to choose the channels. Choose the more crowded."""
nums_names = [(c['num_members'], c['name']) for c in list_channels]
maxnum = sorted(nums_names, reverse=True)[0][0]
return random.choice([c[1] for c in nums_names if c[0] == maxnum])
def last_read_channel(sc, full_list_channels):
"""Any method to choose the channels. Choose the last read one."""
nums_names = [(c['last_read'], c['name']) for c in full_list_channels if 'last_read' in c]
maxnum = sorted(nums_names, reverse=True)[0][0]
return random.choice([c[1] for c in nums_names if c[0] == maxnum])
def get_reactions(list_of_ts_channel, sc):
"""Get the reaction of users on all the messages sent by the bot, to increase or decrease the frequency of messages."""
scale_factor = 1.
try:
for (ts, c) in list_of_ts_channel:
# https://api.slack.com/methods/reactions.get
reaction = sc.api_call(
"reactions.get", channel=c, timestamp=ts
)
logging.debug("reaction =", reaction)
if 'message' not in reaction:
continue
text = {t['name']: t['count'] for t in reaction['message']['reactions']}
logging.info("text =", text)
if any(s in text.keys() for s in POSITIVE_REACTIONS):
nb = max([0.5] + [text[s] for s in POSITIVE_REACTIONS if s in text.keys()])
logging.info("I read {} positive reactions ...".format(int(nb)))
scale_factor /= 2 * nb
elif any(s in text for s in NEGATIVES_REACTIONS):
nb = max([0.5] + [text[s] for s in NEGATIVES_REACTIONS if s in text.keys()])
logging.info("I read {} negative reactions ...".format(int(nb)))
scale_factor *= 2 * nb
elif "rage" in text:
raise ValueError("One user reacted with :rage:, the bot will quit...")
return scale_factor
except KeyError:
return scale_factor
def send(text, sc, channel=DEFAULT_CHANNEL, dontsend=False):
"""Send text to channel SLACK_CHANNEL with client sc.
- https://github.com/slackapi/python-slackclient#sending-a-message
"""
text = "{}\n> (Sent by an _open-source_ Python script :snake:, {}, written by <NAME>)".format(text, URL)
logging.info("{}ending the message '{}' to channel/user '{}' ...".format("NOT s" if dontsend else "S", text, channel))
if dontsend:
return {} # Empty response
else:
# https://api.slack.com/methods/chat.postMessage
response1 = sc.api_call(
"chat.postMessage", channel=channel, text=text,
username="Citations aléatoires", icon_emoji=":robot_face:"
)
ts = response1['ts']
response2 = sc.api_call(
"pins.add", channel=channel, ts=ts
)
return response1
def has_been_sent(sc, t0, t1, ts, c):
# https://api.slack.com/methods/chat.postMessage
response = sc.api_call(
"channels.history", channel=c, oldest=t0, latest=t1,
)
# print(response) # DEBUG
return response['ok'] and 0 < len([True for m in response['messages'] if m['ts'] == ts])
def has_been_seen(sc, ts, c):
# https://api.slack.com/methods/chat.postMessage
response = sc.api_call(
"channels.info", channel=c,
)
# print(response['channel']['last_read']) # DEBUG
# print("ts =", ts) # DEBUG
return response['ok'] and ts <= response['channel']['last_read']
def loop(quote_file=QUOTE_FILE, random_channel=False, dontsend=False):
"""Main loop."""
logging.info("Starting my Slack bot, reading random quotes from the file {}...".format(quote_file))
# Get list of quotes and parameters
the_quote_file = open(quote_file, 'r')
lines = the_quote_file.readlines()
lmbda = MEAN_TIME
# API
sc = SlackClient(SLACK_TOKEN)
list_channels = get_list_channels(sc)
name_channels = [c['name'] for c in list_channels]
full_list_channels = get_full_list_channels(sc, list_channels)
nb_channels = len(list_channels)
# Thompson sampling algorithms
TS = Thompson(nb_channels)
TS.startGame()
# Start loop
list_of_ts_channel = []
while True:
# 1. get random quote
text = random_line(lines)
# logging.info("New message:\n{}".format(text))
if random_channel:
# channel1 = choose_channel(list_channels)
# print("- method choose_channel gave channel1 =", channel1) # DEBUG
# channel2 = most_popular_channel(list_channels)
# print("- method most_popular_channel gave channel2 =", channel2) # DEBUG
# channel3 = last_read_channel(sc, full_list_channels)
# print("- method last_read_channel gave channel3 =", channel3) # DEBUG
channel4 = list_channels[TS.choice()]['name']
# print("- method TS.choice gave channel3 =", channel4) # DEBUG
channel = random.choice([SLACK_CHANNEL, SLACK_USER, channel4])
# print("- method random.choice gave channel =", channel) # DEBUG
# channel = SLACK_CHANNEL
channel = channel4
else:
channel = DEFAULT_CHANNEL
response = send(text, sc, channel=channel, dontsend=dontsend)
# 2. sleep until next quote
secs = sleeptime(lmbda)
str_secs = time.asctime(time.localtime(time.time() + secs))
logging.info(" ... Next message in {} seconds, at {} ...".format(secs, str_secs))
sleep_bar(secs)
# 3. get response
try:
ts, c = response['ts'], response['channel']
list_of_ts_channel.append((ts, c))
# Get reaction from users on the messages already posted
scale_factor = get_reactions(list_of_ts_channel, sc)
lmbda = scale_factor * MEAN_TIME # Don't accumulate this!
except KeyError:
pass
logging.info(" Currently, the mean time between messages is {} ...".format(lmbda))
# 4. try to know if the last message was seen, to give a reward to the TS algorithm
try:
ts, c = response['ts'], response['channel']
# response = int(has_been_sent(sc, ts-60*60, ts+10+secs, ts, c))
reward = int(has_been_seen(sc, ts, c))
except KeyError:
reward = 0 # not seen, by default
cnl = channel.replace('#', '')
ch = name_channels.index(cnl) if cnl in name_channels else -1
if ch >= 0:
print("Giving reward", reward, "for channel", ch, "to Thompson algorithm ...")
# 5. Print current posteriors
TS.getReward(ch, reward)
print_TS(TS, name_channels)
else:
print("reward =", reward) # DEBUG
print("cnl =", cnl) # DEBUG
return 0
# --- Main script
if __name__ == '__main__':
quote_file = sys.argv[1] if len(sys.argv) > 1 else QUOTE_FILE
sys.exit(loop(quote_file, random_channel=True, dontsend=DONTSEND))
# End of my-small-slack-bot.py
| 4,619 |
1,724 | /*
* Copyright 2008-present MongoDB, 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.bson.codecs.pojo.entities;
import java.util.List;
public class InvalidCollectionModel {
private InvalidCollection collectionField;
public InvalidCollectionModel() {
}
public InvalidCollectionModel(final List<Integer> list) {
this.collectionField = new InvalidCollection(list);
}
public InvalidCollection getCollectionField() {
return collectionField;
}
public void setCollectionField(final InvalidCollection collectionField) {
this.collectionField = collectionField;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InvalidCollectionModel that = (InvalidCollectionModel) o;
return collectionField.equals(that.collectionField);
}
@Override
public int hashCode() {
return collectionField.hashCode();
}
}
| 512 |
1,602 | extern double test_rand_double(void);
extern unsigned int test_rand_uint32(void);
void run_smallcrush_testu01_double(const char* name);
void run_smallcrush_testu01_uint(const char* name);
void run_crush_testu01_double(const char* name);
void run_crush_testu01_uint(const char* name);
| 100 |
2,151 | <reponame>zipated/src
// 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 "ash/shelf/app_list_button.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "ash/app_list/app_list_controller_impl.h"
#include "ash/assistant/assistant_controller.h"
#include "ash/public/cpp/shelf_types.h"
#include "ash/session/session_controller.h"
#include "ash/shelf/assistant_overlay.h"
#include "ash/shelf/ink_drop_button_listener.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_constants.h"
#include "ash/shelf/shelf_view.h"
#include "ash/shell.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/system/tray/tray_popup_utils.h"
#include "ash/voice_interaction/voice_interaction_controller.h"
#include "base/command_line.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/timer/timer.h"
#include "chromeos/chromeos_switches.h"
#include "components/account_id/account_id.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/scoped_canvas.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/animation/ink_drop_mask.h"
#include "ui/views/painter.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace {
constexpr int kVoiceInteractionAnimationDelayMs = 200;
constexpr int kVoiceInteractionAnimationHideDelayMs = 500;
} // namespace
constexpr uint8_t kVoiceInteractionRunningAlpha = 255; // 100% alpha
constexpr uint8_t kVoiceInteractionNotRunningAlpha = 138; // 54% alpha
AppListButton::AppListButton(InkDropButtonListener* listener,
ShelfView* shelf_view,
Shelf* shelf)
: views::ImageButton(nullptr),
listener_(listener),
shelf_view_(shelf_view),
shelf_(shelf) {
DCHECK(listener_);
DCHECK(shelf_view_);
DCHECK(shelf_);
Shell::Get()->AddShellObserver(this);
Shell::Get()->session_controller()->AddObserver(this);
Shell::Get()->voice_interaction_controller()->AddObserver(this);
SetInkDropMode(InkDropMode::ON_NO_GESTURE_HANDLER);
set_ink_drop_base_color(kShelfInkDropBaseColor);
set_ink_drop_visible_opacity(kShelfInkDropVisibleOpacity);
SetAccessibleName(
l10n_util::GetStringUTF16(IDS_ASH_SHELF_APP_LIST_LAUNCHER_TITLE));
SetSize(gfx::Size(kShelfSize, kShelfSize));
SetFocusPainter(TrayPopupUtils::CreateFocusPainter());
set_notify_action(Button::NOTIFY_ON_PRESS);
// Initialize voice interaction overlay and sync the flags if active user
// session has already started. This could happen when an external monitor
// is plugged in.
if (Shell::Get()->session_controller()->IsActiveUserSessionStarted() &&
chromeos::switches::IsVoiceInteractionEnabled()) {
InitializeVoiceInteractionOverlay();
}
}
AppListButton::~AppListButton() {
Shell::Get()->voice_interaction_controller()->RemoveObserver(this);
Shell::Get()->RemoveShellObserver(this);
Shell::Get()->session_controller()->RemoveObserver(this);
}
void AppListButton::OnAppListShown() {
AnimateInkDrop(views::InkDropState::ACTIVATED, nullptr);
is_showing_app_list_ = true;
shelf_->UpdateAutoHideState();
}
void AppListButton::OnAppListDismissed() {
AnimateInkDrop(views::InkDropState::DEACTIVATED, nullptr);
is_showing_app_list_ = false;
shelf_->UpdateAutoHideState();
}
void AppListButton::OnGestureEvent(ui::GestureEvent* event) {
// Handle gesture events that are on the app list circle.
switch (event->type()) {
case ui::ET_GESTURE_SCROLL_BEGIN:
AnimateInkDrop(views::InkDropState::HIDDEN, event);
ImageButton::OnGestureEvent(event);
return;
case ui::ET_GESTURE_TAP:
case ui::ET_GESTURE_TAP_CANCEL:
if (UseVoiceInteractionStyle()) {
assistant_overlay_->EndAnimation();
assistant_animation_delay_timer_->Stop();
}
ImageButton::OnGestureEvent(event);
return;
case ui::ET_GESTURE_TAP_DOWN:
if (UseVoiceInteractionStyle()) {
assistant_animation_delay_timer_->Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(
kVoiceInteractionAnimationDelayMs),
base::Bind(&AppListButton::StartVoiceInteractionAnimation,
base::Unretained(this)));
}
if (!Shell::Get()->app_list_controller()->IsVisible())
AnimateInkDrop(views::InkDropState::ACTION_PENDING, event);
ImageButton::OnGestureEvent(event);
return;
case ui::ET_GESTURE_LONG_PRESS:
if (UseVoiceInteractionStyle()) {
base::RecordAction(base::UserMetricsAction(
"VoiceInteraction.Started.AppListButtonLongPress"));
Shell::Get()->app_list_controller()->StartVoiceInteractionSession();
assistant_overlay_->BurstAnimation();
event->SetHandled();
} else if (chromeos::switches::IsAssistantEnabled()) {
// TODO: Handle overlay animation similarly to above. Also needs to
// factor in Assistant enabled state.
Shell::Get()->assistant_controller()->StartInteraction();
event->SetHandled();
} else {
ImageButton::OnGestureEvent(event);
}
return;
case ui::ET_GESTURE_LONG_TAP:
if (UseVoiceInteractionStyle() ||
chromeos::switches::IsAssistantEnabled()) {
// Also consume the long tap event. This happens after the user long
// presses and lifts the finger. We already handled the long press
// ignore the long tap to avoid bringing up the context menu again.
AnimateInkDrop(views::InkDropState::HIDDEN, event);
event->SetHandled();
} else {
ImageButton::OnGestureEvent(event);
}
return;
default:
ImageButton::OnGestureEvent(event);
return;
}
}
bool AppListButton::OnMousePressed(const ui::MouseEvent& event) {
ImageButton::OnMousePressed(event);
shelf_view_->PointerPressedOnButton(this, ShelfView::MOUSE, event);
return true;
}
void AppListButton::OnMouseReleased(const ui::MouseEvent& event) {
ImageButton::OnMouseReleased(event);
shelf_view_->PointerReleasedOnButton(this, ShelfView::MOUSE, false);
}
void AppListButton::OnMouseCaptureLost() {
shelf_view_->PointerReleasedOnButton(this, ShelfView::MOUSE, true);
ImageButton::OnMouseCaptureLost();
}
bool AppListButton::OnMouseDragged(const ui::MouseEvent& event) {
ImageButton::OnMouseDragged(event);
shelf_view_->PointerDraggedOnButton(this, ShelfView::MOUSE, event);
return true;
}
void AppListButton::GetAccessibleNodeData(ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kButton;
node_data->SetName(shelf_view_->GetTitleForView(this));
}
std::unique_ptr<views::InkDropRipple> AppListButton::CreateInkDropRipple()
const {
gfx::Point center = GetCenterPoint();
gfx::Rect bounds(center.x() - kAppListButtonRadius,
center.y() - kAppListButtonRadius, 2 * kAppListButtonRadius,
2 * kAppListButtonRadius);
return std::make_unique<views::FloodFillInkDropRipple>(
size(), GetLocalBounds().InsetsFrom(bounds),
GetInkDropCenterBasedOnLastEvent(), GetInkDropBaseColor(),
ink_drop_visible_opacity());
}
void AppListButton::NotifyClick(const ui::Event& event) {
ImageButton::NotifyClick(event);
if (listener_)
listener_->ButtonPressed(this, event, GetInkDrop());
}
bool AppListButton::ShouldEnterPushedState(const ui::Event& event) {
if (!shelf_view_->ShouldEventActivateButton(this, event))
return false;
if (Shell::Get()->app_list_controller()->IsVisible())
return false;
return views::ImageButton::ShouldEnterPushedState(event);
}
std::unique_ptr<views::InkDrop> AppListButton::CreateInkDrop() {
std::unique_ptr<views::InkDropImpl> ink_drop =
Button::CreateDefaultInkDropImpl();
ink_drop->SetShowHighlightOnHover(false);
return std::move(ink_drop);
}
std::unique_ptr<views::InkDropMask> AppListButton::CreateInkDropMask() const {
return std::make_unique<views::CircleInkDropMask>(size(), GetCenterPoint(),
kAppListButtonRadius);
}
void AppListButton::PaintButtonContents(gfx::Canvas* canvas) {
gfx::PointF circle_center(GetCenterPoint());
// Paint a white ring as the foreground for the app list circle. The ceil/dsf
// math assures that the ring draws sharply and is centered at all scale
// factors.
float ring_outer_radius_dp = 7.f;
float ring_thickness_dp = 1.5f;
if (UseVoiceInteractionStyle()) {
ring_outer_radius_dp = 8.f;
ring_thickness_dp = 1.f;
}
{
gfx::ScopedCanvas scoped_canvas(canvas);
const float dsf = canvas->UndoDeviceScaleFactor();
circle_center.Scale(dsf);
cc::PaintFlags fg_flags;
fg_flags.setAntiAlias(true);
fg_flags.setStyle(cc::PaintFlags::kStroke_Style);
fg_flags.setColor(kShelfIconColor);
if (UseVoiceInteractionStyle()) {
mojom::VoiceInteractionState state = Shell::Get()
->voice_interaction_controller()
->voice_interaction_state();
// active: 100% alpha, inactive: 54% alpha
fg_flags.setAlpha(state == mojom::VoiceInteractionState::RUNNING
? kVoiceInteractionRunningAlpha
: kVoiceInteractionNotRunningAlpha);
}
const float thickness = std::ceil(ring_thickness_dp * dsf);
const float radius = std::ceil(ring_outer_radius_dp * dsf) - thickness / 2;
fg_flags.setStrokeWidth(thickness);
// Make sure the center of the circle lands on pixel centers.
canvas->DrawCircle(circle_center, radius, fg_flags);
if (UseVoiceInteractionStyle()) {
fg_flags.setAlpha(255);
const float kCircleRadiusDp = 5.f;
fg_flags.setStyle(cc::PaintFlags::kFill_Style);
canvas->DrawCircle(circle_center, std::ceil(kCircleRadiusDp * dsf),
fg_flags);
}
}
}
gfx::Point AppListButton::GetCenterPoint() const {
// For a bottom-aligned shelf, the button bounds could have a larger height
// than width (in the case of touch-dragging the shelf upwards) or a larger
// width than height (in the case of a shelf hide/show animation), so adjust
// the y-position of the circle's center to ensure correct layout. Similarly
// adjust the x-position for a left- or right-aligned shelf.
const int x_mid = width() / 2.f;
const int y_mid = height() / 2.f;
const ShelfAlignment alignment = shelf_->alignment();
if (alignment == SHELF_ALIGNMENT_BOTTOM ||
alignment == SHELF_ALIGNMENT_BOTTOM_LOCKED) {
return gfx::Point(x_mid, x_mid);
} else if (alignment == SHELF_ALIGNMENT_RIGHT) {
return gfx::Point(y_mid, y_mid);
} else {
DCHECK_EQ(alignment, SHELF_ALIGNMENT_LEFT);
return gfx::Point(width() - y_mid, y_mid);
}
}
void AppListButton::OnAppListVisibilityChanged(bool shown,
aura::Window* root_window) {
aura::Window* window = GetWidget() ? GetWidget()->GetNativeWindow() : nullptr;
if (!window || window->GetRootWindow() != root_window)
return;
if (shown)
OnAppListShown();
else
OnAppListDismissed();
}
void AppListButton::OnVoiceInteractionStatusChanged(
mojom::VoiceInteractionState state) {
SchedulePaint();
if (!assistant_overlay_)
return;
switch (state) {
case mojom::VoiceInteractionState::STOPPED:
UMA_HISTOGRAM_TIMES(
"VoiceInteraction.OpenDuration",
base::TimeTicks::Now() - voice_interaction_start_timestamp_);
break;
case mojom::VoiceInteractionState::NOT_READY:
// If we are showing the bursting or waiting animation, no need to do
// anything. Otherwise show the waiting animation now.
if (!assistant_overlay_->IsBursting() &&
!assistant_overlay_->IsWaiting()) {
assistant_overlay_->WaitingAnimation();
}
break;
case mojom::VoiceInteractionState::RUNNING:
// we start hiding the animation if it is running.
if (assistant_overlay_->IsBursting() || assistant_overlay_->IsWaiting()) {
assistant_animation_hide_delay_timer_->Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(
kVoiceInteractionAnimationHideDelayMs),
base::Bind(&AssistantOverlay::HideAnimation,
base::Unretained(assistant_overlay_)));
}
voice_interaction_start_timestamp_ = base::TimeTicks::Now();
break;
}
}
void AppListButton::OnVoiceInteractionSettingsEnabled(bool enabled) {
SchedulePaint();
}
void AppListButton::OnVoiceInteractionSetupCompleted(bool completed) {
SchedulePaint();
}
void AppListButton::OnActiveUserSessionChanged(const AccountId& account_id) {
SchedulePaint();
// Initialize voice interaction overlay when primary user session becomes
// active.
if (Shell::Get()->session_controller()->IsUserPrimary() &&
!assistant_overlay_ && chromeos::switches::IsVoiceInteractionEnabled()) {
InitializeVoiceInteractionOverlay();
}
}
void AppListButton::StartVoiceInteractionAnimation() {
// We only show the voice interaction icon and related animation when the
// shelf is at the bottom position and voice interaction is not running and
// voice interaction setup flow has completed.
ShelfAlignment alignment = shelf_->alignment();
mojom::VoiceInteractionState state =
Shell::Get()->voice_interaction_controller()->voice_interaction_state();
bool show_icon =
(alignment == SHELF_ALIGNMENT_BOTTOM ||
alignment == SHELF_ALIGNMENT_BOTTOM_LOCKED) &&
state == mojom::VoiceInteractionState::STOPPED &&
Shell::Get()->voice_interaction_controller()->setup_completed();
assistant_overlay_->StartAnimation(show_icon);
}
bool AppListButton::UseVoiceInteractionStyle() {
VoiceInteractionController* controller =
Shell::Get()->voice_interaction_controller();
bool settings_enabled = controller->settings_enabled();
bool setup_completed = controller->setup_completed();
bool is_feature_allowed =
controller->allowed_state() == mojom::AssistantAllowedState::ALLOWED;
if (assistant_overlay_ && is_feature_allowed &&
(settings_enabled || !setup_completed)) {
return true;
}
return false;
}
void AppListButton::InitializeVoiceInteractionOverlay() {
assistant_overlay_ = new AssistantOverlay(this);
AddChildView(assistant_overlay_);
assistant_overlay_->SetVisible(false);
assistant_animation_delay_timer_ = std::make_unique<base::OneShotTimer>();
assistant_animation_hide_delay_timer_ =
std::make_unique<base::OneShotTimer>();
}
} // namespace ash
| 5,717 |
692 | <reponame>iMats/Singularity
package com.hubspot.singularity.data;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
public class ZkCache<T> {
private final Cache<String, T> cache;
private final Meter hitMeter;
private final Meter missMeter;
public ZkCache(
int maxSize,
int initialSize,
long millisToExpireAfterAccess,
MetricRegistry registry,
String name
) {
cache =
CacheBuilder
.newBuilder()
.maximumSize(maxSize)
.concurrencyLevel(2)
.initialCapacity(initialSize)
.expireAfterAccess(millisToExpireAfterAccess, TimeUnit.MILLISECONDS)
.build();
this.hitMeter = registry.meter(String.format("zk.caches.%s.hits", name));
this.missMeter = registry.meter(String.format("zk.caches.%s.miss", name));
registry.register(
String.format("zk.caches.%s.size", name),
new Gauge<Long>() {
@Override
public Long getValue() {
return cache.size();
}
}
);
}
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public Optional<T> get(String path) {
T fromCache = cache.getIfPresent(path);
if (fromCache == null) {
missMeter.mark();
} else {
hitMeter.mark();
}
return Optional.ofNullable(fromCache);
}
public void delete(String path) {
cache.invalidate(path);
}
public void set(String path, T object) {
cache.put(path, object);
}
public void invalidateAll() {
cache.invalidateAll();
}
}
| 714 |
4,012 | <filename>cpp/tests/groupby/structs_tests.cpp
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* 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 <tests/groupby/groupby_test_util.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/iterator_utilities.hpp>
#include <cudf_test/type_lists.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
using namespace cudf::test::iterators;
namespace cudf {
namespace test {
template <typename V>
struct groupby_structs_test : public cudf::test::BaseFixture {
};
TYPED_TEST_SUITE(groupby_structs_test, cudf::test::FixedWidthTypes);
using V = int32_t; // Type of Aggregation Column.
using M0 = int32_t; // Type of STRUCT's first (i.e. 0th) member.
using R = cudf::detail::target_type_t<V, aggregation::SUM>; // Type of aggregation result.
using offsets = std::vector<cudf::offset_type>;
using strings = strings_column_wrapper;
using structs = structs_column_wrapper;
template <typename T>
using fwcw = fixed_width_column_wrapper<T>;
template <typename T>
using lcw = lists_column_wrapper<T>;
namespace {
static constexpr auto null = -1; // Signifies null value.
// Checking with a single aggregation, and aggregation column.
// This test is orthogonal to the aggregation type; it focuses on testing the grouping
// with STRUCT keys.
auto sum_agg() { return cudf::make_sum_aggregation<groupby_aggregation>(); }
// Set this to true to enable printing, for debugging.
auto constexpr print_enabled = false;
void print_agg_results(column_view const& keys, column_view const& vals)
{
if constexpr (print_enabled) {
auto requests = std::vector<groupby::aggregation_request>{};
requests.push_back(groupby::aggregation_request{});
requests.back().values = vals;
requests.back().aggregations.push_back(sum_agg());
requests.back().aggregations.push_back(
cudf::make_nth_element_aggregation<groupby_aggregation>(0));
auto gby = groupby::groupby{table_view({keys}), null_policy::INCLUDE, sorted::NO, {}, {}};
auto result = gby.aggregate(requests);
std::cout << "Results: Keys: " << std::endl;
print(result.first->get_column(0).view());
std::cout << "Results: Values: " << std::endl;
print(result.second.front().results[0]->view());
}
}
void test_sort_based_sum_agg(column_view const& keys,
column_view const& values,
column_view const& expected_keys,
column_view const& expected_values)
{
test_single_agg(keys,
values,
expected_keys,
expected_values,
sum_agg(),
force_use_sort_impl::YES,
null_policy::INCLUDE);
}
void test_hash_based_sum_agg(column_view const& keys,
column_view const& values,
column_view const& expected_keys,
column_view const& expected_values)
{
test_single_agg(keys,
values,
expected_keys,
expected_values,
sum_agg(),
force_use_sort_impl::NO,
null_policy::INCLUDE);
}
void test_sum_agg(column_view const& keys,
column_view const& values,
column_view const& expected_keys,
column_view const& expected_values)
{
test_sort_based_sum_agg(keys, values, expected_keys, expected_values);
test_hash_based_sum_agg(keys, values, expected_keys, expected_values);
}
} // namespace
TYPED_TEST(groupby_structs_test, basic)
{
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto member_0 = fwcw<M0>{ 1, 2, 3, 1, 2, 2, 1, 3, 3, 2};
auto member_1 = fwcw<M1>{ 11, 22, 33, 11, 22, 22, 11, 33, 33, 22};
auto member_2 = strings {"11", "22", "33", "11", "22", "22", "11", "33", "33", "22"};
auto keys = structs{member_0, member_1, member_2};
auto expected_values = fwcw<R> { 9, 19, 17 };
auto expected_member_0 = fwcw<M0>{ 1, 2, 3 };
auto expected_member_1 = fwcw<M1>{ 11, 22, 33 };
auto expected_member_2 = strings {"11", "22", "33"};
auto expected_keys = structs{expected_member_0, expected_member_1, expected_member_2};
// clang-format on
test_sum_agg(keys, values, expected_keys, expected_values);
}
TYPED_TEST(groupby_structs_test, structs_with_nulls_in_members)
{
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto member_0 = fwcw<M0>{{ 1, null, 3, 1, 2, 2, 1, 3, 3, 2 }, null_at(1)};
auto member_1 = fwcw<M1>{{ 11, 22, 33, 11, 22, 22, 11, null, 33, 22 }, null_at(7)};
auto member_2 = strings { "11", "22", "33", "11", "22", "22", "11", "33", "33", "22"};
auto keys = structs{{member_0, member_1, member_2}};
// clang-format on
print_agg_results(keys, values);
// clang-format off
auto expected_values = fwcw<R> { 9, 18, 10, 7, 1 };
auto expected_member_0 = fwcw<M0>{ { 1, 2, 3, 3, null }, null_at(4)};
auto expected_member_1 = fwcw<M1>{ { 11, 22, 33, null, 22 }, null_at(3)};
auto expected_member_2 = strings { "11", "22", "33", "33", "22" };
auto expected_keys = structs{expected_member_0, expected_member_1, expected_member_2};
// clang-format on
test_sum_agg(keys, values, expected_keys, expected_values);
}
TYPED_TEST(groupby_structs_test, structs_with_null_rows)
{
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto member_0 = fwcw<M0>{ 1, 2, 3, 1, 2, 2, 1, 3, 3, 2};
auto member_1 = fwcw<M1>{ 11, 22, 33, 11, 22, 22, 11, 33, 33, 22};
auto member_2 = strings {"11", "22", "33", "11", "22", "22", "11", "33", "33", "22"};
auto keys = structs{{member_0, member_1, member_2}, nulls_at({0, 3})};
auto expected_values = fwcw<R> { 6, 19, 17, 3 };
auto expected_member_0 = fwcw<M0>{ { 1, 2, 3, null }, null_at(3)};
auto expected_member_1 = fwcw<M1>{ { 11, 22, 33, null }, null_at(3)};
auto expected_member_2 = strings { {"11", "22", "33", "null" }, null_at(3)};
auto expected_keys = structs{{expected_member_0, expected_member_1, expected_member_2}, null_at(3)};
// clang-format on
print_agg_results(keys, values);
test_sum_agg(keys, values, expected_keys, expected_values);
}
TYPED_TEST(groupby_structs_test, structs_with_nulls_in_rows_and_members)
{
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto member_0 = fwcw<M0>{{ 1, 2, 3, 1, 2, 2, 1, 3, 3, 2 }, null_at(1)};
auto member_1 = fwcw<M1>{{ 11, 22, 33, 11, 22, 22, 11, 33, 33, 22 }, null_at(7)};
auto member_2 = strings { "11", "22", "33", "11", "22", "22", "11", "33", "33", "22"};
auto keys = structs{{member_0, member_1, member_2}, null_at(4)};
// clang-format on
print_agg_results(keys, values);
// clang-format off
auto expected_values = fwcw<R> { 9, 14, 10, 7, 1, 4 };
auto expected_member_0 = fwcw<M0>{{ 1, 2, 3, 3, null, null }, nulls_at({4,5})};
auto expected_member_1 = fwcw<M1>{{ 11, 22, 33, null, 22, null }, nulls_at({3,5})};
auto expected_member_2 = strings {{ "11", "22", "33", "33", "22", "null" }, null_at(5)};
auto expected_keys = structs{{expected_member_0, expected_member_1, expected_member_2}, null_at(5)};
// clang-format on
print_agg_results(keys, values);
test_sum_agg(keys, values, expected_keys, expected_values);
}
TYPED_TEST(groupby_structs_test, null_members_differ_from_null_structs)
{
// This test specifically confirms that a non-null STRUCT row `{null, null, null}` is grouped
// differently from a null STRUCT row (whose members are incidentally null).
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto member_0 = fwcw<M0>{{ 1, null, 3, 1, 2, 2, 1, 3, 3, 2 }, null_at(1)};
auto member_1 = fwcw<M1>{{ 11, null, 33, 11, 22, 22, 11, 33, 33, 22 }, null_at(1)};
auto member_2 = strings {{ "11", "null", "33", "11", "22", "22", "11", "33", "33", "22"}, null_at(1)};
auto keys = structs{{member_0, member_1, member_2}, null_at(4)};
// clang-format on
print_agg_results(keys, values);
// Index-3 => Non-null Struct row, with nulls for all members.
// Index-4 => Null Struct row.
// clang-format off
auto expected_values = fwcw<R> { 9, 14, 17, 1, 4 };
auto expected_member_0 = fwcw<M0>{ { 1, 2, 3, null, null }, nulls_at({3,4})};
auto expected_member_1 = fwcw<M1>{ { 11, 22, 33, null, null }, nulls_at({3,4})};
auto expected_member_2 = strings { {"11", "22", "33", "null", "null" }, nulls_at({3,4})};
auto expected_keys = structs{{expected_member_0, expected_member_1, expected_member_2}, null_at(4)};
// clang-format on
test_sum_agg(keys, values, expected_keys, expected_values);
}
TYPED_TEST(groupby_structs_test, structs_of_structs)
{
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto struct_0_member_0 = fwcw<M0>{{ 1, null, 3, 1, 2, 2, 1, 3, 3, 2 }, null_at(1)};
auto struct_0_member_1 = fwcw<M1>{{ 11, null, 33, 11, 22, 22, 11, 33, 33, 22 }, null_at(1)};
auto struct_0_member_2 = strings {{ "11", "null", "33", "11", "22", "22", "11", "33", "33", "22"}, null_at(1)};
// clang-format on
auto struct_0 = structs{{struct_0_member_0, struct_0_member_1, struct_0_member_2}, null_at(4)};
auto struct_1_member_1 = fwcw<M1>{8, 9, 6, 8, 0, 7, 8, 6, 6, 7};
auto keys = structs{{struct_0, struct_1_member_1}}; // Struct of structs.
print_agg_results(keys, values);
// clang-format off
auto expected_values = fwcw<R> { 9, 14, 17, 1, 4 };
auto expected_member_0 = fwcw<M0>{ { 1, 2, 3, null, null }, nulls_at({3,4})};
auto expected_member_1 = fwcw<M1>{ { 11, 22, 33, null, null }, nulls_at({3,4})};
auto expected_member_2 = strings { {"11", "22", "33", "null", "null" }, nulls_at({3,4})};
auto expected_structs = structs{{expected_member_0, expected_member_1, expected_member_2}, null_at(4)};
auto expected_struct_1_member_1 = fwcw<M1>{ 8, 7, 6, 9, 0 };
auto expected_keys = structs{{expected_structs, expected_struct_1_member_1}};
// clang-format on
test_sum_agg(keys, values, expected_keys, expected_values);
}
TYPED_TEST(groupby_structs_test, empty_input)
{
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> {};
auto member_0 = fwcw<M0>{};
auto member_1 = fwcw<M1>{};
auto member_2 = strings {};
auto keys = structs{member_0, member_1, member_2};
auto expected_values = fwcw<R> {};
auto expected_member_0 = fwcw<M0>{};
auto expected_member_1 = fwcw<M1>{};
auto expected_member_2 = strings {};
auto expected_keys = structs{expected_member_0, expected_member_1, expected_member_2};
// clang-format on
test_sum_agg(keys, values, expected_keys, expected_values);
}
TYPED_TEST(groupby_structs_test, all_null_input)
{
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto member_0 = fwcw<M0>{ 1, 2, 3, 1, 2, 2, 1, 3, 3, 2};
auto member_1 = fwcw<M1>{ 11, 22, 33, 11, 22, 22, 11, 33, 33, 22};
auto member_2 = strings {"11", "22", "33", "11", "22", "22", "11", "33", "33", "22"};
auto keys = structs{{member_0, member_1, member_2}, all_nulls()};
auto expected_values = fwcw<R> { 45 };
auto expected_member_0 = fwcw<M0>{ null };
auto expected_member_1 = fwcw<M1>{ null };
auto expected_member_2 = strings {"null"};
auto expected_keys = structs{{expected_member_0, expected_member_1, expected_member_2}, all_nulls()};
// clang-format on
test_sum_agg(keys, values, expected_keys, expected_values);
}
TYPED_TEST(groupby_structs_test, lists_are_unsupported)
{
using M1 = TypeParam; // Type of STRUCT's second (i.e. 1th) member.
// clang-format off
auto values = fwcw<V> { 0, 1, 2, 3, 4 };
auto member_0 = lcw<M0> { {1,1}, {2,2}, {3,3}, {1,1}, {2,2} };
auto member_1 = fwcw<M1>{ 1, 2, 3, 1, 2 };
// clang-format on
auto keys = structs{{member_0, member_1}};
EXPECT_THROW(test_sort_based_sum_agg(keys, values, keys, values), cudf::logic_error);
EXPECT_THROW(test_hash_based_sum_agg(keys, values, keys, values), cudf::logic_error);
}
} // namespace test
} // namespace cudf
| 6,568 |
1,546 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* 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.android.systemui.shared.system;
import android.content.Context;
import com.android.internal.util.LatencyTracker;
import com.android.systemui.shared.QuickstepCompat;
/**
* @see LatencyTracker
*/
public class LatencyTrackerCompat {
/**
* @see LatencyTracker
* @deprecated Please use {@link LatencyTrackerCompat#logToggleRecents(Context, int)} instead.
*/
@Deprecated
public static void logToggleRecents(int duration) {
if (!QuickstepCompat.ATLEAST_S) {
return;
}
LatencyTracker.logActionDeprecated(LatencyTracker.ACTION_TOGGLE_RECENTS, duration, false);
}
/** @see LatencyTracker */
public static void logToggleRecents(Context context, int duration) {
if (!QuickstepCompat.ATLEAST_S) {
return;
}
LatencyTracker.getInstance(context).logAction(LatencyTracker.ACTION_TOGGLE_RECENTS,
duration);
}
} | 525 |
360 | /*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* capture_view.cpp
* support utility to capture view to json file
*
* IDENTIFICATION
* src/gausskernel/cbb/instruments/capture_view/capture_view.cpp
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "fmgr.h"
#include "knl/knl_instance.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "commands/dbcommands.h"
#include "access/hash.h"
#include "utils/memutils.h"
#include "executor/spi.h"
#include "catalog/pg_database.h"
#include "postmaster/syslogger.h"
#include "utils/snapmgr.h"
#include "access/tableam.h"
#define VIEW_NAME_LEN (2 * NAMEDATALEN)
#define MAX_PERF_FILE_SIZE (64 * 1024 * 1024)
#define PERF_FILE_PREFIX "pg_perf-"
/*
* We really want line-buffered mode for logfile output, but Windows does
* not have it, and interprets _IOLBF as _IOFBF (bozos). So use _IONBF
* instead on Windows.
*/
#ifdef WIN32
#define LBF_MODE _IONBF
#else
#define LBF_MODE _IOLBF
#endif
typedef struct {
char database_name[NAMEDATALEN];
char view_name[VIEW_NAME_LEN];
} ViewJsonFileKey;
typedef struct {
ViewJsonFileKey key;
pthread_mutex_t mutex;
FILE* perfFile;
} ViewJsonFile;
typedef struct {
const char *view_name;
const char *filter;
} ViewFilter;
/* get valid and controlled json result set,
* CAUTION:
* only support one single "'" in filter.
*/
static const ViewFilter perf_view_filter[] {
{"pg_stat_activity", "where state != 'idle'"},
{"dbe_perf.wait_events", "where wait != 0 or failed_wait != 0"},
{"dbe_perf.session_memory", "where init_mem != 0 or used_mem != 0 or peak_mem != 0"},
{"dbe_perf.session_memory_detail", "order by totalsize desc limit 1000"}
};
static char *jsonfile_getname(const char* database_name, const char* view_name);
static FILE *jsonfile_open(const char* database_name, const char* view_name);
static void rotate_view_file_if_needs(ViewJsonFile* entry);
static void lock_entry(ViewJsonFile *entry);
static void unlock_entry(ViewJsonFile *entry);
static void generate_json_to_view_file(ViewJsonFile* entry, const char* value);
static List *get_database_list();
static void output_query_to_json(const char *query, const char *database_name, const char *view_name);
static char *gen_perf_path(const char *database_name, const char *view_name);
static const char *get_view_filter(const char *view_name, bool need_double_quotes);
static uint32 view_json_file_hash(const void* key, Size size)
{
const ViewJsonFileKey* k = (const ViewJsonFileKey*)key;
return hash_any((const unsigned char*)k->database_name, strlen(k->database_name)) ^
hash_any((const unsigned char*)k->view_name, strlen(k->view_name));
}
static int view_json_file_match(const void* key1, const void* key2, Size keysize)
{
const ViewJsonFileKey* k1 = (const ViewJsonFileKey*)key1;
const ViewJsonFileKey* k2 = (const ViewJsonFileKey*)key2;
if (k1 != NULL && k2 != NULL &&
strcmp(k1->database_name, k2->database_name) == 0 &&
strcmp(k1->view_name, k2->view_name) == 0) {
return 0;
} else {
return 1;
}
}
void init_capture_view_hash()
{
MemoryContext mem_cxt = AllocSetContextCreate(g_instance.instance_context,
"CaptureViewContext",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE,
SHARED_CONTEXT);
HASHCTL ctl;
errno_t rc;
rc = memset_s(&ctl, sizeof(ctl), 0, sizeof(ctl));
securec_check_c(rc, "\0", "\0");
ctl.hcxt = mem_cxt;
ctl.keysize = sizeof(ViewJsonFileKey);
ctl.entrysize = sizeof(ViewJsonFile);
ctl.hash = view_json_file_hash;
ctl.match = view_json_file_match;
g_instance.stat_cxt.capture_view_file_hashtbl = hash_create("view json file hash table", 100, &ctl,
HASH_ELEM | HASH_SHRCTX | HASH_FUNCTION | HASH_COMPARE | HASH_NOEXCEPT);
}
static void output_json_file(ViewJsonFile* entry, const char *database_name, const char *view_name)
{
lock_entry(entry);
int saveInterruptHoldoffCount = t_thrd.int_cxt.InterruptHoldoffCount;
PG_TRY();
{
if (entry->perfFile == NULL) {
entry->perfFile = jsonfile_open(database_name, view_name);
}
rotate_view_file_if_needs(entry);
for (uint32 i = 0; i < SPI_processed; i ++) {
bool isnull = true;
Datum val = SPI_getbinval(SPI_tuptable->vals[i], SPI_tuptable->tupdesc, 1, &isnull);
if (!isnull) {
/* generate json to file */
char* value = TextDatumGetCString(val);
generate_json_to_view_file(entry, value);
}
}
unlock_entry(entry);
}
PG_CATCH();
{
/*
* handle ereport error will reset InterruptHoldoffCount issue, if not handle,
* LWLockRelease will be failed on assert
*/
t_thrd.int_cxt.InterruptHoldoffCount = saveInterruptHoldoffCount;
unlock_entry(entry);
LWLockRelease(CaptureViewFileHashLock);
PG_RE_THROW();
}
PG_END_TRY();
LWLockRelease(CaptureViewFileHashLock);
}
static void cache_and_ouput_json_file(const char* database_name, const char* view_name)
{
ViewJsonFileKey key = {0};
int rc = 0;
rc = memcpy_s(key.database_name, sizeof(key.database_name),
database_name, strlen(database_name));
securec_check(rc, "\0", "\0");
rc = memcpy_s(key.view_name, sizeof(key.view_name),
view_name, strlen(view_name));
securec_check(rc, "\0", "\0");
LWLockAcquire(CaptureViewFileHashLock, LW_SHARED);
ViewJsonFile* entry = (ViewJsonFile*)hash_search(g_instance.stat_cxt.capture_view_file_hashtbl, &key, HASH_FIND, NULL);
if (entry == NULL) {
LWLockRelease(CaptureViewFileHashLock);
LWLockAcquire(CaptureViewFileHashLock, LW_EXCLUSIVE);
bool found = true;
entry = (ViewJsonFile*)hash_search(g_instance.stat_cxt.capture_view_file_hashtbl, &key, HASH_ENTER, &found);
if (entry == NULL) {
LWLockRelease(CaptureViewFileHashLock);
ereport(ERROR, (errmodule(MOD_INSTR), errcode_for_file_access(),
errmsg("[CapView] OOM in capture view")));
return;
}
if (!found) {
/* reset entry, create file descriptor */
(void)pthread_mutex_init(&entry->mutex, NULL);
entry->perfFile = NULL;
char *file_dir = gen_perf_path(database_name, view_name);
if (file_dir != NULL) {
/* race condition: need to create dir here */
(void)pg_mkdir_p(file_dir, S_IRWXU);
pfree(file_dir);
}
}
}
/* release lock in this method */
output_json_file(entry, database_name, view_name);
}
static void generate_json_to_view_file(ViewJsonFile* entry, const char* json_row)
{
if (entry == NULL || json_row == NULL)
return;
StringInfoData json_with_line_break;
initStringInfo(&json_with_line_break);
appendStringInfo(&json_with_line_break, "%s\n", json_row);
size_t count = strlen(json_with_line_break.data);
size_t rc = 0;
retry1:
rc = fwrite(json_with_line_break.data, 1, count, entry->perfFile);
if (rc != count) {
/*
* If no disk space, we will retry, and we can not report a log as
* there is not space to write.
*/
if (errno == ENOSPC) {
pg_usleep(1000000);
goto retry1;
}
pfree(json_with_line_break.data);
ereport(ERROR, (errcode_for_file_access(), errmsg("[CapView] could not write to view perf file: %m")));
}
pfree(json_with_line_break.data);
}
static void rotate_view_file_if_needs(ViewJsonFile* entry)
{
if (entry == NULL || entry->perfFile == NULL) {
return;
}
long current_file_size = ftell(entry->perfFile);
if (current_file_size < 0) {
int save_errno = errno;
ereport(ERROR, (errmodule(MOD_INSTR), errcode_for_file_access(),
errmsg("[CapView] could not ftell json file :%m")));
errno = save_errno;
}
if (current_file_size >= MAX_PERF_FILE_SIZE) {
fclose(entry->perfFile);
entry->perfFile = jsonfile_open(entry->key.database_name, entry->key.view_name);
}
}
static void check_capture_view_parameter(const char *database_name, const char *view_name)
{
if (database_name == NULL || view_name == NULL) {
ereport(ERROR, (errmodule(MOD_INSTR), errmsg("[CapView] pls check database name and view name!")));
}
if (strlen(view_name) > VIEW_NAME_LEN) {
ereport(ERROR, (errmodule(MOD_INSTR), errmsg("[CapView] view name is too long!")));
}
for (size_t i = 0; i < strlen(view_name); i++) {
char chr = view_name[i];
if ((chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z') || (chr >= '0' && chr <= '9') ||
chr == '_' || chr == '.') {
continue;
} else {
ereport(ERROR, (errmodule(MOD_INSTR), errmsg("[CapView] invalid view name!")));
}
}
}
static void cross_db_view_to_json(const char *view_name, const char *main_query)
{
/* cross database */
List *all_db = get_database_list();
ListCell *cell = NULL;
if (all_db != NIL) {
foreach(cell, all_db) {
char *curr_db = (char *)lfirst(cell);
StringInfoData db_query;
initStringInfo(&db_query);
appendStringInfo(&db_query, "select json from wdr_xdb_query('dbname=%s', '%s') as r(json text)",
curr_db, main_query);
output_query_to_json(db_query.data, curr_db, view_name);
pfree(db_query.data);
}
}
list_free_deep(all_db);
}
/* support to capture view to json file */
Datum capture_view_to_json(PG_FUNCTION_ARGS)
{
if (!superuser() && !isMonitoradmin(GetUserId()))
ereport(ERROR, (errmodule(MOD_INSTR), errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
(errmsg("[CapView] only system/monitor admin can capure view"))));
if (PG_ARGISNULL(0) || PG_ARGISNULL(1)) {
ereport(ERROR, (errmodule(MOD_INSTR),
errmsg("[CapView] in capture_view_to_json proc, view_name or is_all_db can not by null")));
}
int is_all_db = PG_GETARG_INT32(1);
if (is_all_db != 0 && is_all_db != 1) {
ereport(ERROR, (errmodule(MOD_INSTR),
errmsg("[CapView] in capture_view_to_json proc, is_all_db can only be 0 or 1")));
}
char *view_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
char *database_name = get_and_check_db_name(u_sess->proc_cxt.MyDatabaseId, true);
check_capture_view_parameter(database_name, view_name);
char quota[3] = {0};
quota[0] = '\'';
if (is_all_db == 1) {
quota[1] = '\'';
}
int rc = 0;
const char *filter = get_view_filter(view_name, is_all_db == 1);
StringInfoData query;
initStringInfo(&query);
appendStringInfo(&query, "select row_to_json(src_view) as json from ("
" select * from "
" floor(EXTRACT(epoch FROM clock_timestamp()) * 1000) as record_time, "
" current_setting(%spgxc_node_name%s) as perf_node_name, "
" current_database() as perf_database_name, "
" (select %s%s%s as perf_view_name), "
" %s %s) as src_view;", quota, quota, quota, view_name, quota, view_name, filter);
pfree_ext(filter);
/* get query result to json */
if ((rc = SPI_connect()) != SPI_OK_CONNECT) {
ereport(ERROR,
(errmodule(MOD_INSTR),
(errcode(ERRCODE_SPI_CONNECTION_FAILURE),
errmsg("[CapView] SPI_connect failed: %s", SPI_result_code_string(rc)))));
}
ErrorData* edata = NULL;
MemoryContext oldcontext = CurrentMemoryContext;
PG_TRY();
{
if (is_all_db == 0) {
/* current database */
output_query_to_json(query.data, database_name, view_name);
} else if (is_all_db == 1) {
cross_db_view_to_json(view_name, query.data);
}
}
PG_CATCH();
{
SPI_finish();
pfree(query.data);
pfree(view_name);
pfree(database_name);
(void)MemoryContextSwitchTo(oldcontext);
edata = CopyErrorData();
FlushErrorState();
ereport(ERROR, (errmodule(MOD_INSTR),
errmsg("[CapView] capture view to json failed! detail: %s", edata->message)));
}
PG_END_TRY();
SPI_finish();
pfree(query.data);
pfree(view_name);
pfree(database_name);
PG_RETURN_INT32(0);
}
static void lock_entry(ViewJsonFile *entry)
{
pthread_mutex_lock(&entry->mutex);
}
static void unlock_entry(ViewJsonFile *entry)
{
pthread_mutex_unlock(&entry->mutex);
}
void init_capture_view()
{
/* create perf directory if not present, ignore errors */
if (g_instance.attr.attr_common.Perf_directory == NULL) {
init_instr_log_directory(true, PERF_JOB_TAG);
} else {
(void)pg_mkdir_p(g_instance.attr.attr_common.Perf_directory, S_IRWXU);
}
init_capture_view_hash();
}
static FILE* jsonfile_open(const char* database_name, const char* view_name)
{
char* filename = jsonfile_getname(database_name, view_name);
bool exist = false;
if (filename == NULL) {
ereport(ERROR, (errmodule(MOD_INSTR), errcode(ERRCODE_UNEXPECTED_NULL_VALUE),
errmsg("[CapView] json file can not by NULL")));
}
char rel_path[PATH_MAX] = {0};
if (strlen(filename) >= MAXPGPATH || (realpath(filename, rel_path) == NULL && errno != ENOENT)) {
pfree(filename);
ereport(ERROR, (errmodule(MOD_INSTR), errmsg("[CapView] calc realpath failed")));
}
struct stat checkdir;
if (stat(rel_path, &checkdir) == 0) {
exist = true;
}
FILE* fh = NULL;
fh = fopen(rel_path, "a");
if (fh != NULL) {
setvbuf(fh, NULL, LBF_MODE, 0);
} else {
int save_errno = errno;
ereport(ERROR, (errcode_for_file_access(),
errmsg("[CapView] could not open log file \"%s\": %m", filename)));
errno = save_errno;
}
if (!exist) {
if (chmod(filename, S_IWUSR | S_IRUSR) < 0) {
int save_errno = errno;
ereport(ERROR, (errcode_for_file_access(),
errmsg("[CapView] could not chmod view json file \"%s\": %m", filename)));
errno = save_errno;
}
}
pfree(filename);
return fh;
}
/* replace '.' with '_' from view name */
static char *format_view_name(const char *view_name)
{
if (view_name == NULL)
return NULL;
char *tmp_view_name = pstrdup(view_name);
for (size_t i = 0; i < strlen(tmp_view_name); i ++) {
if (tmp_view_name[i] == '.') {
tmp_view_name[i] = '_';
}
}
return tmp_view_name;
}
static char *gen_perf_path(const char *database_name, const char *view_name)
{
if (database_name == NULL || view_name == NULL)
return NULL;
char *formatted_view_name = format_view_name(view_name);
StringInfoData path;
initStringInfo(&path);
appendStringInfo(&path, "%s/", g_instance.attr.attr_common.Perf_directory);
appendStringInfo(&path, "%s/", formatted_view_name);
appendStringInfo(&path, "%s/", database_name);
pfree(formatted_view_name);
return path.data;
}
static char *jsonfile_getname(const char* database_name, const char* view_name)
{
int ret = 0;
size_t len = 0;
pg_time_t file_time = time(NULL);
char *path = gen_perf_path(database_name, view_name);
if (path == NULL) {
return NULL;
}
char *jsonfile_name = NULL;
jsonfile_name = (char*)palloc0(MAXPGPATH + 1);
/* If want to use cm agent to cleanup perf files, must obey the
* file name format: pg_perf-2020-03-23_072301.database-view.log
* for example:
* pg_perf-2020-03-23_072301.postgres-dbe_perf.statement.log
* pg_perf-2020-03-23_072301.postgres-pg_proc.log
*/
ret = snprintf_s(jsonfile_name + len, MAXPGPATH - len, MAXPGPATH - len - 1, "%s/%s",
path, PERF_FILE_PREFIX);
pfree(path);
securec_check_ss(ret,"\0","\0");
pg_tm* tz = pg_localtime(&file_time, log_timezone);
if (tz == NULL) {
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("[CapView] calc localtime failed")));
}
len = strlen(jsonfile_name);
pg_strftime(jsonfile_name + len, MAXPGPATH - len, "%Y-%m-%d_%H%M%S", tz);
len = strlen(jsonfile_name);
ret = snprintf_s(jsonfile_name + len, MAXPGPATH - len, MAXPGPATH - len - 1, ".%s-%s.log", database_name, view_name);
securec_check_ss(ret,"\0","\0");
len = strlen(jsonfile_name);
return jsonfile_name;
}
static void output_query_to_json(const char *query, const char *database_name, const char *view_name) {
if (SPI_execute(query, true, 0) != SPI_OK_SELECT) {
ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("[CapView] invalid query")));
}
if (SPI_processed > 0) {
cache_and_ouput_json_file(database_name, view_name);
}
}
static List *get_database_list()
{
Relation rel = NULL;
HeapTuple tup = NULL;
TableScanDesc scan = NULL;
List *dblist = NIL;
rel = heap_open(DatabaseRelationId, AccessShareLock);
scan = tableam_scan_begin(rel, SnapshotNow, 0, NULL);
while (HeapTupleIsValid(tup = (HeapTuple) tableam_scan_getnexttuple(scan, ForwardScanDirection))) {
Form_pg_database database = (Form_pg_database) GETSTRUCT(tup);
if (!database->datistemplate) {
dblist = lappend(dblist, pstrdup(NameStr(database->datname)));
}
}
tableam_scan_end(scan);
heap_close(rel, AccessShareLock);
return dblist;
}
static const char *get_view_filter(const char *view_name, bool need_double_quotes) {
Size filter_count = sizeof(perf_view_filter) / sizeof(perf_view_filter[0]);
const char *filter = NULL;
StringInfoData filter_str;
initStringInfo(&filter_str);
for (Size i = 0; i < filter_count; i ++) {
if (pg_strcasecmp(perf_view_filter[i].view_name, view_name) == 0) {
filter = perf_view_filter[i].filter;
break;
}
}
if (filter == NULL) {
return filter_str.data;
}
if (need_double_quotes) {
for (Size i = 0; i < strlen(filter); i ++) {
if (filter[i] == '\'') {
appendStringInfo(&filter_str, "%c%c", '\'', '\'');
} else {
appendStringInfo(&filter_str, "%c", filter[i]);
}
}
} else {
appendStringInfo(&filter_str, "%s", filter);
}
return filter_str.data;
}
| 8,586 |
1,755 | <reponame>cclauss/VTK
/*=========================================================================
Program: Visualization Toolkit
Module: vtk_cli11.h
Copyright (c) <NAME>, <NAME>, <NAME>
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtk_cli11_h
#define vtk_cli11_h
// VTK_MODULE_USE_EXTERNAL_VTK_cli11 is defined in this header,
// so include it.
#include <vtk_cli11_external.h>
#if VTK_MODULE_USE_EXTERNAL_VTK_cli11
# include <CLI/CLI.hpp>
#else
#if defined(vtk_cli11_forward_h) && defined(VTK_CLI)
// vtk_cli11_forward.h defines VTK_CLI to help mangle forward declarations.
// However that can conflict with definitions in CLI.hpp, so we undef it here,
// if the header was already included.
#undef VTK_CLI
#endif
# include <vtkcli11/CLI/CLI.hpp>
#endif // VTK_MODULE_USE_EXTERNAL_VTK_cli11
#endif
| 386 |
536 | <reponame>al1020119/BABaseProject
//
// DemoVC2_02_HeaderView.h
// BABaseProject
//
// Created by 博爱 on 16/7/7.
// Copyright © 2016年 博爱之家. All rights reserved.
//
#import "BABaseHeaderFooterView.h"
#import "BARotateView.h"
@interface DemoVC2_02_HeaderView : BABaseHeaderFooterView
/*!
* Change to normal state.
*
* @param animated Animated or not.
*/
- (void)ba_normalStateAnimated:(BOOL)animated;
/*!
* Change to extended state.
*
* @param animated Animated or not.
*/
- (void)ba_extendStateAnimated:(BOOL)animated;
@end
| 219 |
315 | <filename>src/c++/main/fastainfo.cpp
// -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Copyright (c) 2010-2015 Illumina, Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* \brief Retrieve contig lengths for a FASTA file
*
* \file fastainfo.cpp
* \author <NAME>
* \email <EMAIL>
*
*/
#include <boost/program_options.hpp>
#include <iostream>
#include <fstream>
#include "json/json.h"
#include "Fasta.hh"
#include "Version.hh"
#include "Error.hh"
int main(int argc, char* argv[]) {
namespace po = boost::program_options;
std::string file;
std::string output;
try
{
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("version", "Show version")
("input-file", po::value< std::string >(), "The input files")
("output-file", po::value<std::string>(), "The output file name.")
;
po::positional_options_description popts;
popts.add("input-file", 1);
popts.add("output-file", 1);
po::options_description cmdline_options;
cmdline_options
.add(desc)
;
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(cmdline_options).positional(popts).run(), vm);
po::notify(vm);
if (vm.count("version"))
{
std::cout << "fastainfo version " << HAPLOTYPES_VERSION << "\n";
return 0;
}
if (vm.count("help"))
{
std::cout << desc << "\n";
return 1;
}
if (vm.count("input-file"))
{
file = vm["input-file"].as< std::string > ();
}
if (vm.count("output-file"))
{
output = vm["output-file"].as< std::string >();
}
if(file.size() == 0)
{
std::cerr << "Please specify an input file.\n";
return 1;
}
if (output == "")
{
std::cerr << "Please specify an output file.\n";
return 1;
}
}
catch (po::error & e)
{
std::cerr << e.what() << "\n";
return 1;
}
try
{
Json::StyledWriter writer;
FastaFile f(file.c_str());
Json::Value root;
for (auto const & contig : f.getContigNames())
{
Json::Value field;
field["length"] = (Json::UInt64 )f.contigSize(contig);
field["n_trimmed_length"] = (Json::UInt64 )f.contigNonNSize(contig);
root[contig] = field;
}
root["*"] = Json::Value();
root["*"]["length"] = (Json::UInt64 )f.contigSize();
root["*"]["n_trimmed_length"] = (Json::UInt64 )f.contigNonNSize();
std::ofstream out(output.c_str());
out << writer.write(root);
}
catch(std::runtime_error & e)
{
std::cerr << e.what() << std::endl;
return 1;
}
catch(std::logic_error & e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
| 1,926 |
558 | package com.endava.cats.fuzzer.fields;
import com.endava.cats.model.FuzzingData;
import io.quarkus.test.junit.QuarkusTest;
import io.swagger.v3.oas.models.media.IntegerSchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import org.apache.commons.lang3.math.NumberUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@QuarkusTest
class DecimalValuesInIntegerFieldsFuzzerTest {
private DecimalValuesInIntegerFieldsFuzzer decimalValuesInIntegerFieldsFuzzer;
@BeforeEach
void setup() {
decimalValuesInIntegerFieldsFuzzer = new DecimalValuesInIntegerFieldsFuzzer(null, null, null, null);
}
@Test
void givenANewDecimalFieldsFuzzer_whenCreatingANewInstance_thenTheMethodsBeingOverriddenAreMatchingTheDecimalFuzzer() {
NumberSchema nrSchema = new NumberSchema();
Assertions.assertThat(decimalValuesInIntegerFieldsFuzzer.getSchemasThatTheFuzzerWillApplyTo().stream().anyMatch(schema -> schema.isAssignableFrom(IntegerSchema.class))).isTrue();
Assertions.assertThat(NumberUtils.isCreatable(decimalValuesInIntegerFieldsFuzzer.getBoundaryValue(nrSchema))).isTrue();
Assertions.assertThat(decimalValuesInIntegerFieldsFuzzer.hasBoundaryDefined("test", FuzzingData.builder().build())).isTrue();
Assertions.assertThat(decimalValuesInIntegerFieldsFuzzer.description()).isNotNull();
Assertions.assertThat(decimalValuesInIntegerFieldsFuzzer.typeOfDataSentToTheService()).isNotNull();
}
}
| 561 |
406 | from flask import Flask
from flask_sslify import SSLify
from pytest import fixture
@fixture
def sslify():
app = Flask(__name__)
app.config['DEBUG'] = False
app.config['TESTING'] = False
app.config['SERVER_NAME'] = 'example.com'
sslify = SSLify(app)
@app.route('/')
def home():
return 'home'
return sslify
def test_default_config(sslify):
assert sslify.hsts_include_subdomains is False
assert sslify.permanent is False
assert sslify.skip_list is None
def test_redirection(sslify):
client = sslify.app.test_client()
r = client.get('/')
assert r.status_code == 302
assert r.headers['Location'] == 'https://example.com/'
def test_hsts_header(sslify):
client = sslify.app.test_client()
r = client.get('/', base_url='https://example.com')
assert r.status_code == 200
assert r.data.decode('utf-8') == 'home'
assert r.headers['Strict-Transport-Security'] == 'max-age=31536000'
| 378 |
482 | <filename>src/main/java/com/blog/service/impl/AdminServiceImpl.java
package com.blog.service.impl;
import com.blog.dao.AdminDao;
import com.blog.domain.Admin;
import com.blog.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AdminServiceImpl implements AdminService{
@Autowired
public AdminDao adminDao;
public Admin getById(Integer id) {
return adminDao.selectByPrimaryKey(id);
}
}
| 174 |
1,078 | <filename>Src/StdLib/MakeModuleList.py
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
# Copies working standard library modules to the provided output directory
# Usage: ipy getModuleList.py <output directory>
#--Imports---------------------------------------------------------------------
import sys, os
import clr
import shutil
#List of predetermined directories and files which should not be included in
#the MSI
excludedDirectories = []
excludedFiles = []
def find_root():
test_dirs = ['Src', 'Build', 'Package', 'Tests', 'Util']
root = os.getcwd()
test = all([os.path.exists(os.path.join(root, x)) for x in test_dirs])
while not test:
root = os.path.dirname(root)
test = all([os.path.exists(os.path.join(root, x)) for x in test_dirs])
return root
root = find_root()
#Automatically determine what's currently not working under IronPython
sys.path.append(os.path.join(root, 'Tests', 'Tools'))
base_dir = os.path.abspath(os.path.join(root, 'Src', 'StdLib'))
import stdmodules
BROKEN_LIST = stdmodules.main(base_dir)
if len(BROKEN_LIST)<10:
#If there are less than ten modules/directories listed in BROKEN_LIST
#chances are good stdmodules is broken!
exc_msg = "It's highly unlikely that only %d CPy standard modules are broken under IP!" % len(BROKEN_LIST)
print exc_msg
raise Exception(exc_msg)
#Specify Packages and Modules that should not be included here.
excludedDirectories += [
"/Lib/test",
"/Lib/idlelib",
"/Lib/lib-tk",
"/Lib/site-packages"
]
excludedDirectories += [x for x in BROKEN_LIST if not x.endswith(".py")]
excludedFiles += [
#*.py modules IronPython has implemented in *.cs
"/Lib/copy_reg.py",
"/Lib/re.py",
]
excludedFiles += [x for x in BROKEN_LIST if x.endswith(".py") and not any(x.startswith(y) for y in excludedDirectories)]
excludedDirectoriesCase = [os.path.join(base_dir, x[1:]).replace('/', '\\') + '\\' for x in excludedDirectories]
excludedDirectories = [x.lower() for x in excludedDirectoriesCase]
excludedFilesCase = [os.path.join(base_dir, x[1:]).replace('/', '\\') for x in excludedFiles]
excludedFiles = [x.lower() for x in excludedFilesCase]
f = file('StdLib.pyproj')
content = ''.join(f.readlines())
header = ' <!-- Begin Generated Project Items -->'
footer = ' <!-- End Generated Project Items -->'
if header == -1 or footer == -1:
print "no header or footer"
sys.exit(1)
start = content.find(header)
end = content.find(footer)
f.close()
content_start = content[:start + len(header)] + '\n'
content_end = content[end:]
files = []
for excluded in excludedDirectoriesCase:
files.append(" $(StdLibPath)\\{}**\\*;\n".format(excluded[len(base_dir) + 5:]))
for excluded in excludedFilesCase:
files.append(" $(StdLibPath)\\{};\n".format(excluded[len(base_dir) + 5:]))
file_list = ''.join(files)
f = file('StdLib.pyproj', 'w')
f.write(content_start)
f.write(file_list)
f.write(content_end)
f.close()
| 1,301 |
5,169 | {
"name": "TLLayoutTransitioning",
"version": "0.0.1",
"summary": "Components for transitioning between UICollectionView layouts.",
"description": "\t\t\t\t\tTLLayoutTransitioning solves two problems with collection view layout transitions:\n\n\t\t\t\t\t1. The stock `UICollectionViewLayoutTransition` does not handle the content offset well, often leaving cells where you don't want them. `TLTransitionLayout` provides elegant control of the content offset relative to a specified cell or cells with Minimal, Center, Top, Left, Bottom and Right placement options.\n\n\t\t\t\t\t2. The `-[UICollectionView setCollectionViewLayout:animated:completion]` method of animating between layouts is flakey (cells jumping, etc.) and there are no animation options. TLLayoutTransitioning can animate between two layouts with duration, 30+ easing curves and content offset control. This is done by combining `UICollectionViewLayoutTransition` with an automated `CADisplayLink` progress driver.\n\t\t\t\t\t\n\t\t\t\t\tCheck out the demos in the Examples workspace!\n",
"homepage": "github.com/wtmoose/TLLayoutTransitioning",
"license": {
"type": "MIT"
},
"authors": {
"wtmoose": "<EMAIL>"
},
"source": {
"git": "https://github.com/wtmoose/TLLayoutTransitioning.git",
"tag": "0.0.1"
},
"platforms": {
"ios": "7.0"
},
"source_files": "TLLayoutTransitioning/**/*.{h,m,c}",
"frameworks": [
"UIKit",
"QuartzCore",
"Foundation"
],
"requires_arc": true
}
| 513 |
314 | <filename>Multiplex/IDEHeaders/IDEHeaders/DVTFoundation/DVTToolchainRegistry.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "CDStructures.h"
@class DVTDispatchLock, DVTMutableOrderedDictionary, DVTSearchPath, NSMutableDictionary;
@interface DVTToolchainRegistry : NSObject <NSFastEnumeration>
{
DVTSearchPath *_searchPath;
DVTMutableOrderedDictionary *_identsToToolchains;
NSMutableDictionary *_aliasesToToolchains;
DVTDispatchLock *_lock;
}
+ (id)defaultRegistry;
@property(readonly) DVTDispatchLock *lock; // @synthesize lock=_lock;
@property(readonly) NSMutableDictionary *aliasesToToolchains; // @synthesize aliasesToToolchains=_aliasesToToolchains;
@property(readonly) DVTMutableOrderedDictionary *identsToToolchains; // @synthesize identsToToolchains=_identsToToolchains;
@property(readonly) DVTSearchPath *searchPath; // @synthesize searchPath=_searchPath;
- (unsigned long long)countByEnumeratingWithState:(CDStruct_70511ce9 *)arg1 objects:(id *)arg2 count:(unsigned long long)arg3;
- (BOOL)scanSearchPathAndRegisterToolchains:(id *)arg1;
- (id)allRegisteredToolchains;
- (id)defaultToolchain;
- (id)toolchainForIdentifier:(id)arg1;
- (BOOL)registerToolchain:(id)arg1 error:(id *)arg2;
- (id)init;
- (id)initWithSearchPath:(id)arg1;
@end
| 486 |
604 | <reponame>python245/Mandar-virus-por-gmail
import os
import sys
from .color import green, white, red, blue, start, alert, numbering
def RedirectHelp():
print(numbering(1) + white + " Create Redirect Page " + numbering(1))
print(numbering(2) + white + " Info And HowTo Use " + numbering(2))
print(numbering(99) + white + " Quit Redirecting Creation " + numbering(99))
OptionPick = int(input(green + "root@phishmailer/Bypass/Redirect:~ " + white))
if OptionPick == 1:
os.system("clear")
RedirectCreator()
elif OptionPick == 2:
os.system("clear")
HowInfo()
elif OptionPick == 99:
print("Ok...")
else:
print("Wrong Input!")
def RedirectionMain():
print(green)
print("""
__ ___ __ __ ___ __ ___ __ __
|__) |__ | \ | |__) |__ / ` | / \ |__)
| \ |___ |__/ | | \ |___ \__, | \__/ | \
-------------------MainMenu------------------""")
RedirectHelp()
def RedirectCreator():
print(green + """
__ ___ __ __ ___ __ ___ __ __
|__) |__ | \ | |__) |__ / ` | / \ |__)
| \ |___ |__/ | | \ |___ \__, | \__/ | \
-------------------Creator-------------------""")
print("")
print(numbering(1) + white + " Already With Your PhishingLink " + numbering(1))
print(numbering(2) + white + " Add It YourSelf (just the htmlFile Without PhishingUrl) " + numbering(2))
print(numbering(99) + white + " Quit Creation " + numbering(99))
Creator = int(input(green + "root@phishmailer/Redirect/Creator:~ " + white))
if Creator == 1:
Url = input(start + "Enter Your Url: " + white)
FileName = input(start + "Name Of File: " + white)
print(alert + " Enter for '/root/Desktop/PhishMailer/Redirection/'")
FileSave = input(start + " Where Do You Want To Save The File?: " + white)
if FileSave == "":
FileLocation = "/root/Desktop/PhishMailer/Redirection/"
else:
FileLocation = FileSave
CompleteLocator = os.path.join(FileLocation, FileName+".html")
Html_file = open(CompleteLocator,"w")
Html_file.write("""
<!DOCTYPE html>
<html>
<head>
<title>Redirecting</title>
<meta http-equiv="refresh" content="1; url={}">
</head>
<body>
<p>Redirecting....</p>
</body>
</html> """.format(Url))
Html_file.close()
print(alert + " File Created, Saved At: " + FileLocation)
elif Creator == 2:
FileName = input(start + "Name Of File: " + white)
print(alert + " Enter for '/root/Desktop/PhishMailer/Redirection/'")
FileSave = input(start + " Where Do You Want To Save The File?: " + white)
if FileSave == "":
FileLocation = "/root/Desktop/PhishMailer/Redirection/"
else:
FileLocation = FileSave
CompleteLocator = os.path.join(FileLocation, FileName+".html")
Html_file = open(CompleteLocator,"w")
Html_file.write("""
<!DOCTYPE html>
<html>
<head>
<title>Redirecting</title>
<meta http-equiv="refresh" content="1; url=https://www.PhishingSite.com/">
</head>
<body>
<p>Redirecting....</p>
</body>
</html> """)
Html_file.close()
print(alert + " HTML File Saved At " + FileLocation)
print(alert + " Remember You Need To Enter Your PhishingUrl Manually!")
elif Creator == 99:
os.system("clear")
print(red + "Hope It Works Out Another Way")
os.system("clear")
else:
print("OK...")
def HowInfo():
print(green)
print("""
__ ___ __ __ ___ __ ___ __ __
|__) |__ | \ | |__) |__ / ` | / \ |__)
| \ |___ |__/ | | \ |___ \__, | \__/ | \
----------------Info And HowTo---------------""")
print(numbering(1) + white + " How To Use " + numbering(1))
print(numbering(2) + white + " How It Works " + numbering(2))
print(numbering(3) + white + " To Creator " + numbering(3))
print(numbering(99) + white + " Exit " + numbering(99))
OptionPick = int(input(green + "root@phishmailer/Bypass/Redirect/Help:~ " + white))
if OptionPick == 99:
RedirectCreator()
elif OptionPick == 1:
print(numbering(1) + white + " Create The Redirection Html File And Make Sure You Type In Your URL Correctly \n")
print(numbering(2) + white + " Now You Need A Hosting Service Like 000Webhost (They Will Not Block This) \n")
print(numbering(3) + white + " Upload Your Redirection Page Recommend That You Name This 'index.html' So It Will Run automatically \n")
print(numbering(4) + white + " And When You Create Your Phishing Email Be Sure That You Put In The Url To Your Redirection Site And Not Your Phishing Url \n")
print(numbering(5) + white + " When You Send Your Phishing Email Now The Email Service can't 'Read' Your Phishing Site That Is Connected Too The Email \n")
print(start + white + " This Will Make It A Little harder For Them To Flag The Email")
RedirectionMain()
elif OptionPick == 2:
print(numbering(1) + white + " One Way That Your Emails Get Flaged Is Because The Email Service Provider Scans All The Sites That Is Connected To The Email \n")
print(numbering(2) + white + " So When You Put In A Url That Just Redirects The Target To The Real Phishing Site It Will Not Read The Phishing Site Just the Redirection \n")
print(numbering(3) + white + " This Is One Way To Help You Launch A successful Phishing Attack \n")
print(alert + white + " This Is Not The Only Way They Detect Phishing Emails So It Won't Always Works But It Help Me Out In The Beginning \n")
print(start + white + " I Will Come With More Ways To Try Bypass The Spam Filters")
RedirectionMain()
elif OptionPick == 3:
os.system("clear")
RedirectCreator()
else:
print(start + " Hope I See You Soon Again " + start)
sys.exit()
#HtmlKod:
#<!DOCTYPE html>
#<html>
# <head>
# <title>HTML Meta Tag</title>
# <meta http-equiv = "refresh" content = "1; url = https://www.PhishingSite.com />
# </head>
# <body>
# <p>Redirecting....</p>
# </body>
#</html>
| 2,209 |
346 | #include "Directories.h"
#include "Font.h"
#include "Input.h"
#include "Interface.h"
#include "Local.h"
#include "Timer_Control.h"
#include "Fade_Screen.h"
#include "SysUtil.h"
#include "MercTextBox.h"
#include "VSurface.h"
#include "Cursors.h"
#include "MessageBoxScreen.h"
#include "Font_Control.h"
#include "Game_Clock.h"
#include "Map_Screen_Interface.h"
#include "RenderWorld.h"
#include "GameLoop.h"
#include "English.h"
#include "GameSettings.h"
#include "Cursor_Control.h"
#include "Laptop.h"
#include "Text.h"
#include "MapScreen.h"
#include "Overhead_Map.h"
#include "Button_System.h"
#include "JAScreens.h"
#include "Video.h"
#include "UILayout.h"
#include <string_theory/format>
#include <string_theory/string>
#define MSGBOX_DEFAULT_WIDTH 300
#define MSGBOX_BUTTON_WIDTH 61
#define MSGBOX_BUTTON_HEIGHT 20
#define MSGBOX_BUTTON_X_SEP 15
#define MSGBOX_SMALL_BUTTON_WIDTH 31
#define MSGBOX_SMALL_BUTTON_X_SEP 8
// old mouse x and y positions
static SGPPoint pOldMousePosition;
static SGPRect MessageBoxRestrictedCursorRegion;
// if the cursor was locked to a region
static BOOLEAN fCursorLockedToArea = FALSE;
BOOLEAN gfInMsgBox = FALSE;
static SGPRect gOldCursorLimitRectangle;
MESSAGE_BOX_STRUCT gMsgBox;
static BOOLEAN gfNewMessageBox = FALSE;
static BOOLEAN gfStartedFromGameScreen = FALSE;
BOOLEAN gfStartedFromMapScreen = FALSE;
BOOLEAN fRestoreBackgroundForMessageBox = FALSE;
BOOLEAN gfDontOverRideSaveBuffer = TRUE; //this variable can be unset if ur in a non gamescreen and DONT want the msg box to use the save buffer
ST::string gzUserDefinedButton1;
ST::string gzUserDefinedButton2;
static void ContractMsgBoxCallback(GUI_BUTTON* btn, INT32 reason);
static void LieMsgBoxCallback(GUI_BUTTON* btn, INT32 reason);
static void NOMsgBoxCallback(GUI_BUTTON* btn, INT32 reason);
static void NumberedMsgBoxCallback(GUI_BUTTON* btn, INT32 reason);
static void OKMsgBoxCallback(GUI_BUTTON* btn, INT32 reason);
static void YESMsgBoxCallback(GUI_BUTTON* btn, INT32 reason);
static GUIButtonRef MakeButton(const ST::string& text, INT16 fore_colour, INT16 shadow_colour, INT16 x, INT16 y, GUI_CALLBACK click, UINT16 cursor)
{
GUIButtonRef const btn = CreateIconAndTextButton(gMsgBox.iButtonImages, text, FONT12ARIAL, fore_colour, shadow_colour, fore_colour, shadow_colour, x, y, MSYS_PRIORITY_HIGHEST, click);
btn->SetCursor(cursor);
ForceButtonUnDirty(btn);
return btn;
}
struct MessageBoxStyle
{
MercPopUpBackground background;
MercPopUpBorder border;
char const* btn_image;
INT32 btn_off;
INT32 btn_on;
UINT8 font_colour;
UINT8 shadow_colour;
UINT16 cursor;
};
static MessageBoxStyle const g_msg_box_style[] =
{
{ DIALOG_MERC_POPUP_BACKGROUND, DIALOG_MERC_POPUP_BORDER, INTERFACEDIR "/popupbuttons.sti", 0, 1, FONT_MCOLOR_WHITE, DEFAULT_SHADOW, CURSOR_NORMAL }, // MSG_BOX_BASIC_STYLE
{ WHITE_MERC_POPUP_BACKGROUND, RED_MERC_POPUP_BORDER, INTERFACEDIR "/msgboxredbuttons.sti", 0, 1, 2, NO_SHADOW, CURSOR_LAPTOP_SCREEN }, // MSG_BOX_RED_ON_WHITE
{ GREY_MERC_POPUP_BACKGROUND, BLUE_MERC_POPUP_BORDER, INTERFACEDIR "/msgboxgreybuttons.sti", 0, 1, 2, FONT_MCOLOR_WHITE, CURSOR_LAPTOP_SCREEN }, // MSG_BOX_BLUE_ON_GREY
{ DIALOG_MERC_POPUP_BACKGROUND, DIALOG_MERC_POPUP_BORDER, INTERFACEDIR "/popupbuttons.sti", 2, 3, FONT_MCOLOR_WHITE, DEFAULT_SHADOW, CURSOR_NORMAL }, // MSG_BOX_BASIC_SMALL_BUTTONS
{ IMP_POPUP_BACKGROUND, DIALOG_MERC_POPUP_BORDER, INTERFACEDIR "/msgboxgreybuttons.sti", 0, 1, 2, FONT_MCOLOR_WHITE, CURSOR_LAPTOP_SCREEN }, // MSG_BOX_IMP_STYLE
{ LAPTOP_POPUP_BACKGROUND, LAPTOP_POP_BORDER, INTERFACEDIR "/popupbuttons.sti", 0, 1, FONT_MCOLOR_WHITE, DEFAULT_SHADOW, CURSOR_LAPTOP_SCREEN } // MSG_BOX_LAPTOP_DEFAULT
};
static MessageBoxStyle const g_msg_box_style_default = { BASIC_MERC_POPUP_BACKGROUND, BASIC_MERC_POPUP_BORDER, INTERFACEDIR "/msgboxbuttons.sti", 0, 1, FONT_MCOLOR_WHITE, DEFAULT_SHADOW, CURSOR_NORMAL };
void DoMessageBox(MessageBoxStyleID ubStyle, const ST::string str, ScreenID uiExitScreen, MessageBoxFlags usFlags, MSGBOX_CALLBACK ReturnCallback, const SGPBox* centering_rect)
{
GetMousePos(&pOldMousePosition);
//this variable can be unset if ur in a non gamescreen and DONT want the msg box to use the save buffer
gfDontOverRideSaveBuffer = TRUE;
SetCurrentCursorFromDatabase(CURSOR_NORMAL);
if (gMsgBox.BackRegion.uiFlags & MSYS_REGION_EXISTS) return;
MessageBoxStyle const& style = ubStyle < lengthof(g_msg_box_style) ?
g_msg_box_style[ubStyle] : g_msg_box_style_default;
// Set some values!
gMsgBox.usFlags = usFlags;
gMsgBox.uiExitScreen = uiExitScreen;
gMsgBox.ExitCallback = ReturnCallback;
gMsgBox.fRenderBox = TRUE;
gMsgBox.bHandled = MSG_BOX_RETURN_NONE;
// Init message box
UINT16 usTextBoxWidth;
UINT16 usTextBoxHeight;
gMsgBox.box = PrepareMercPopupBox(0, style.background, style.border, str, MSGBOX_DEFAULT_WIDTH, 40, 10, 30, &usTextBoxWidth, &usTextBoxHeight);
// Save height,width
gMsgBox.usWidth = usTextBoxWidth;
gMsgBox.usHeight = usTextBoxHeight;
// Determine position (centered in rect)
if (centering_rect)
{
gMsgBox.uX = centering_rect->x + (centering_rect->w - usTextBoxWidth) / 2;
gMsgBox.uY = centering_rect->y + (centering_rect->h - usTextBoxHeight) / 2;
}
else
{
gMsgBox.uX = (SCREEN_WIDTH - usTextBoxWidth) / 2;
gMsgBox.uY = (SCREEN_HEIGHT - usTextBoxHeight) / 2;
}
if (guiCurrentScreen == GAME_SCREEN)
{
gfStartedFromGameScreen = TRUE;
}
if (fInMapMode)
{
gfStartedFromMapScreen = TRUE;
fMapPanelDirty = TRUE;
}
// Set pending screen
SetPendingNewScreen(MSG_BOX_SCREEN);
// Init save buffer
gMsgBox.uiSaveBuffer = AddVideoSurface(usTextBoxWidth, usTextBoxHeight, PIXEL_DEPTH);
//Save what we have under here...
SGPBox const r = { gMsgBox.uX, gMsgBox.uY, usTextBoxWidth, usTextBoxHeight };
BltVideoSurface(gMsgBox.uiSaveBuffer, FRAME_BUFFER, 0, 0, &r);
UINT16 const cursor = style.cursor;
// Create top-level mouse region
MSYS_DefineRegion(&gMsgBox.BackRegion, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, MSYS_PRIORITY_HIGHEST, cursor, MSYS_NO_CALLBACK, MSYS_NO_CALLBACK);
if (!gGameSettings.fOptions[TOPTION_DONT_MOVE_MOUSE])
{
UINT32 x = gMsgBox.uX + usTextBoxWidth / 2;
UINT32 y = gMsgBox.uY + usTextBoxHeight - 4;
if (usFlags == MSG_BOX_FLAG_OK)
{
x += 27;
y -= 6;
}
SimulateMouseMovement(x, y);
}
// findout if cursor locked, if so, store old params and store, restore when done
if (IsCursorRestricted())
{
fCursorLockedToArea = TRUE;
GetRestrictedClipCursor(&MessageBoxRestrictedCursorRegion);
FreeMouseCursor();
}
UINT16 x = gMsgBox.uX;
const UINT16 y = gMsgBox.uY + usTextBoxHeight - MSGBOX_BUTTON_HEIGHT - 10;
gMsgBox.iButtonImages = LoadButtonImage(style.btn_image, style.btn_off, style.btn_on);
INT16 const dx = MSGBOX_BUTTON_WIDTH + MSGBOX_BUTTON_X_SEP;
UINT8 const font_colour = style.font_colour;
UINT8 const shadow_colour = style.shadow_colour;
switch (usFlags)
{
case MSG_BOX_FLAG_FOUR_NUMBERED_BUTTONS:
{
// This is exclusive of any other buttons... no ok, no cancel, no nothing
const INT16 dx = MSGBOX_SMALL_BUTTON_WIDTH + MSGBOX_SMALL_BUTTON_X_SEP;
x += (usTextBoxWidth - (MSGBOX_SMALL_BUTTON_WIDTH + dx * 3)) / 2;
for (UINT8 i = 0; i < 4; ++i)
{
ST::string text = ST::format("{}", i + 1);
GUIButtonRef const btn = MakeButton(text, font_colour, shadow_colour, x + dx * i, y, NumberedMsgBoxCallback, cursor);
gMsgBox.uiButton[i] = btn;
btn->SetUserData(i + 1);
}
break;
}
case MSG_BOX_FLAG_OK:
x += (usTextBoxWidth - GetDimensionsOfButtonPic(gMsgBox.iButtonImages)->w) / 2;
gMsgBox.uiOKButton = MakeButton(pMessageStrings[MSG_OK], font_colour, shadow_colour, x, y, OKMsgBoxCallback, cursor);
break;
case MSG_BOX_FLAG_YESNO:
x += (usTextBoxWidth - (MSGBOX_BUTTON_WIDTH + dx)) / 2;
gMsgBox.uiYESButton = MakeButton(pMessageStrings[MSG_YES], font_colour, shadow_colour, x, y, YESMsgBoxCallback, cursor);
gMsgBox.uiNOButton = MakeButton(pMessageStrings[MSG_NO], font_colour, shadow_colour, x + dx, y, NOMsgBoxCallback, cursor);
break;
case MSG_BOX_FLAG_CONTINUESTOP:
x += (usTextBoxWidth - (MSGBOX_BUTTON_WIDTH + dx)) / 2;
gMsgBox.uiYESButton = MakeButton(pUpdatePanelButtons[0], font_colour, shadow_colour, x, y, YESMsgBoxCallback, cursor);
gMsgBox.uiNOButton = MakeButton(pUpdatePanelButtons[1], font_colour, shadow_colour, x + dx, y, NOMsgBoxCallback, cursor);
break;
case MSG_BOX_FLAG_OKCONTRACT:
x += (usTextBoxWidth - (MSGBOX_BUTTON_WIDTH + dx)) / 2;
gMsgBox.uiYESButton = MakeButton(pMessageStrings[MSG_OK], font_colour, shadow_colour, x, y, YESMsgBoxCallback, cursor);
gMsgBox.uiNOButton = MakeButton(pMessageStrings[MSG_REHIRE], font_colour, shadow_colour, x + dx, y, ContractMsgBoxCallback, cursor);
break;
case MSG_BOX_FLAG_GENERICCONTRACT:
x += (usTextBoxWidth - (MSGBOX_BUTTON_WIDTH + dx * 2)) / 2;
gMsgBox.uiYESButton = MakeButton(gzUserDefinedButton1, font_colour, shadow_colour, x, y, YESMsgBoxCallback, cursor);
gMsgBox.uiNOButton = MakeButton(gzUserDefinedButton2, font_colour, shadow_colour, x + dx, y, NOMsgBoxCallback, cursor);
gMsgBox.uiOKButton = MakeButton(pMessageStrings[MSG_REHIRE], font_colour, shadow_colour, x + dx * 2, y, ContractMsgBoxCallback, cursor);
break;
case MSG_BOX_FLAG_GENERIC:
x += (usTextBoxWidth - (MSGBOX_BUTTON_WIDTH + dx)) / 2;
gMsgBox.uiYESButton = MakeButton(gzUserDefinedButton1, font_colour, shadow_colour, x, y, YESMsgBoxCallback, cursor);
gMsgBox.uiNOButton = MakeButton(gzUserDefinedButton2, font_colour, shadow_colour, x + dx, y, NOMsgBoxCallback, cursor);
break;
case MSG_BOX_FLAG_YESNOLIE:
x += (usTextBoxWidth - (MSGBOX_BUTTON_WIDTH + dx * 2)) / 2;
gMsgBox.uiYESButton = MakeButton(pMessageStrings[MSG_YES], font_colour, shadow_colour, x, y, YESMsgBoxCallback, cursor);
gMsgBox.uiNOButton = MakeButton(pMessageStrings[MSG_NO], font_colour, shadow_colour, x + dx, y, NOMsgBoxCallback, cursor);
gMsgBox.uiOKButton = MakeButton(pMessageStrings[MSG_LIE], font_colour, shadow_colour, x + dx * 2, y, LieMsgBoxCallback, cursor);
break;
case MSG_BOX_FLAG_OKSKIP:
x += (usTextBoxWidth - (MSGBOX_BUTTON_WIDTH + dx)) / 2;
gMsgBox.uiYESButton = MakeButton(pMessageStrings[MSG_OK], font_colour, shadow_colour, x, y, YESMsgBoxCallback, cursor);
gMsgBox.uiNOButton = MakeButton(pMessageStrings[MSG_SKIP], font_colour, shadow_colour, x + dx, y, NOMsgBoxCallback, cursor);
break;
}
InterruptTime();
PauseGame();
LockPauseState(LOCK_PAUSE_MSGBOX);
// Pause timers as well....
PauseTime(TRUE);
// Save mouse restriction region...
GetRestrictedClipCursor(&gOldCursorLimitRectangle);
FreeMouseCursor();
gfNewMessageBox = TRUE;
gfInMsgBox = TRUE;
}
static void OKMsgBoxCallback(GUI_BUTTON* btn, INT32 reason)
{
if (reason & MSYS_CALLBACK_REASON_LBUTTON_UP)
{
gMsgBox.bHandled = MSG_BOX_RETURN_OK;
}
}
static void YESMsgBoxCallback(GUI_BUTTON* btn, INT32 reason)
{
if (reason & MSYS_CALLBACK_REASON_LBUTTON_UP)
{
gMsgBox.bHandled = MSG_BOX_RETURN_YES;
}
}
static void NOMsgBoxCallback(GUI_BUTTON* btn, INT32 reason)
{
if (reason & MSYS_CALLBACK_REASON_LBUTTON_UP)
{
gMsgBox.bHandled = MSG_BOX_RETURN_NO;
}
}
static void ContractMsgBoxCallback(GUI_BUTTON* btn, INT32 reason)
{
if (reason & MSYS_CALLBACK_REASON_LBUTTON_UP)
{
gMsgBox.bHandled = MSG_BOX_RETURN_CONTRACT;
}
}
static void LieMsgBoxCallback(GUI_BUTTON* btn, INT32 reason)
{
if (reason & MSYS_CALLBACK_REASON_LBUTTON_UP)
{
gMsgBox.bHandled = MSG_BOX_RETURN_LIE;
}
}
static void NumberedMsgBoxCallback(GUI_BUTTON* btn, INT32 reason)
{
if (reason & MSYS_CALLBACK_REASON_LBUTTON_UP)
{
gMsgBox.bHandled = static_cast<MessageBoxReturnValue>(btn->GetUserData());
}
}
static ScreenID ExitMsgBox(MessageBoxReturnValue const ubExitCode)
{
RemoveMercPopupBox(gMsgBox.box);
gMsgBox.box = 0;
//Delete buttons!
switch (gMsgBox.usFlags)
{
case MSG_BOX_FLAG_FOUR_NUMBERED_BUTTONS:
RemoveButton(gMsgBox.uiButton[0]);
RemoveButton(gMsgBox.uiButton[1]);
RemoveButton(gMsgBox.uiButton[2]);
RemoveButton(gMsgBox.uiButton[3]);
break;
case MSG_BOX_FLAG_OK:
RemoveButton(gMsgBox.uiOKButton);
break;
case MSG_BOX_FLAG_YESNO:
case MSG_BOX_FLAG_OKCONTRACT:
case MSG_BOX_FLAG_GENERIC:
case MSG_BOX_FLAG_CONTINUESTOP:
case MSG_BOX_FLAG_OKSKIP:
RemoveButton(gMsgBox.uiYESButton);
RemoveButton(gMsgBox.uiNOButton);
break;
case MSG_BOX_FLAG_GENERICCONTRACT:
case MSG_BOX_FLAG_YESNOLIE:
RemoveButton(gMsgBox.uiYESButton);
RemoveButton(gMsgBox.uiNOButton);
RemoveButton(gMsgBox.uiOKButton);
break;
}
// Delete button images
UnloadButtonImage(gMsgBox.iButtonImages);
// Unpause game....
UnLockPauseState();
UnPauseGame();
// UnPause timers as well....
PauseTime(FALSE);
// Restore mouse restriction region...
RestrictMouseCursor(&gOldCursorLimitRectangle);
gfInMsgBox = FALSE;
// Call done callback!
if (gMsgBox.ExitCallback != NULL) gMsgBox.ExitCallback(ubExitCode);
//if you are in a non gamescreen and DONT want the msg box to use the save buffer, unset gfDontOverRideSaveBuffer in your callback
if ((gMsgBox.uiExitScreen != GAME_SCREEN || fRestoreBackgroundForMessageBox) && gfDontOverRideSaveBuffer)
{
// restore what we have under here...
BltVideoSurface(FRAME_BUFFER, gMsgBox.uiSaveBuffer, gMsgBox.uX, gMsgBox.uY, NULL);
InvalidateRegion(gMsgBox.uX, gMsgBox.uY, gMsgBox.uX + gMsgBox.usWidth, gMsgBox.uY + gMsgBox.usHeight);
}
fRestoreBackgroundForMessageBox = FALSE;
gfDontOverRideSaveBuffer = TRUE;
if (fCursorLockedToArea)
{
SGPPoint pPosition;
GetMousePos(&pPosition);
if (pPosition.iX > MessageBoxRestrictedCursorRegion.iRight ||
(pPosition.iX > MessageBoxRestrictedCursorRegion.iLeft && pPosition.iY < MessageBoxRestrictedCursorRegion.iTop && pPosition.iY > MessageBoxRestrictedCursorRegion.iBottom))
{
SimulateMouseMovement(pOldMousePosition.iX, pOldMousePosition.iY);
}
fCursorLockedToArea = FALSE;
RestrictMouseCursor(&MessageBoxRestrictedCursorRegion);
}
MSYS_RemoveRegion(&gMsgBox.BackRegion);
DeleteVideoSurface(gMsgBox.uiSaveBuffer);
switch (gMsgBox.uiExitScreen)
{
case GAME_SCREEN:
if (InOverheadMap())
{
gfOverheadMapDirty = TRUE;
}
else
{
SetRenderFlags(RENDER_FLAG_FULL);
}
break;
case MAP_SCREEN:
fMapPanelDirty = TRUE;
break;
default:
break;
}
if (gfFadeInitialized)
{
SetPendingNewScreen(FADE_SCREEN);
return FADE_SCREEN;
}
return gMsgBox.uiExitScreen;
}
ScreenID MessageBoxScreenHandle(void)
{
if (gfNewMessageBox)
{
// If in game screen....
if (gfStartedFromGameScreen || gfStartedFromMapScreen)
{
if (gfStartedFromGameScreen)
{
HandleTacticalUILoseCursorFromOtherScreen();
}
else
{
HandleMAPUILoseCursorFromOtherScreen();
}
gfStartedFromGameScreen = FALSE;
gfStartedFromMapScreen = FALSE;
}
gfNewMessageBox = FALSE;
return MSG_BOX_SCREEN;
}
UnmarkButtonsDirty();
// Render the box!
if (gMsgBox.fRenderBox)
{
switch (gMsgBox.usFlags)
{
case MSG_BOX_FLAG_FOUR_NUMBERED_BUTTONS:
MarkAButtonDirty(gMsgBox.uiButton[0]);
MarkAButtonDirty(gMsgBox.uiButton[1]);
MarkAButtonDirty(gMsgBox.uiButton[2]);
MarkAButtonDirty(gMsgBox.uiButton[3]);
break;
case MSG_BOX_FLAG_OK:
MarkAButtonDirty(gMsgBox.uiOKButton);
break;
case MSG_BOX_FLAG_YESNO:
case MSG_BOX_FLAG_OKCONTRACT:
case MSG_BOX_FLAG_GENERIC:
case MSG_BOX_FLAG_CONTINUESTOP:
case MSG_BOX_FLAG_OKSKIP:
MarkAButtonDirty(gMsgBox.uiYESButton);
MarkAButtonDirty(gMsgBox.uiNOButton);
break;
case MSG_BOX_FLAG_GENERICCONTRACT:
case MSG_BOX_FLAG_YESNOLIE:
MarkAButtonDirty(gMsgBox.uiYESButton);
MarkAButtonDirty(gMsgBox.uiNOButton);
MarkAButtonDirty(gMsgBox.uiOKButton);
break;
}
RenderMercPopUpBox(gMsgBox.box, gMsgBox.uX, gMsgBox.uY, FRAME_BUFFER);
//gMsgBox.fRenderBox = FALSE;
// ATE: Render each frame...
}
RenderButtons();
EndFrameBufferRender();
// carter, need key shortcuts for clearing up message boxes
// Check for esc
InputAtom InputEvent;
while (DequeueEvent(&InputEvent))
{
if (InputEvent.usEvent != KEY_UP) continue;
switch (gMsgBox.usFlags)
{
case MSG_BOX_FLAG_YESNO:
switch (InputEvent.usParam)
{
case 'n':
case SDLK_ESCAPE: gMsgBox.bHandled = MSG_BOX_RETURN_NO; break;
case 'y':
case SDLK_RETURN: gMsgBox.bHandled = MSG_BOX_RETURN_YES; break;
}
break;
case MSG_BOX_FLAG_OK:
switch (InputEvent.usParam)
{
case 'o':
case SDLK_RETURN: gMsgBox.bHandled = MSG_BOX_RETURN_OK; break;
}
break;
case MSG_BOX_FLAG_CONTINUESTOP:
switch (InputEvent.usParam)
{
case SDLK_RETURN: gMsgBox.bHandled = MSG_BOX_RETURN_OK; break;
}
break;
case MSG_BOX_FLAG_FOUR_NUMBERED_BUTTONS:
switch (InputEvent.usParam)
{
case '1': gMsgBox.bHandled = MSG_BOX_RETURN_1; break;
case '2': gMsgBox.bHandled = MSG_BOX_RETURN_2; break;
case '3': gMsgBox.bHandled = MSG_BOX_RETURN_3; break;
case '4': gMsgBox.bHandled = MSG_BOX_RETURN_4; break;
}
break;
default:
break;
}
}
if (gMsgBox.bHandled != MSG_BOX_RETURN_NONE)
{
SetRenderFlags(RENDER_FLAG_FULL);
return ExitMsgBox(gMsgBox.bHandled);
}
return MSG_BOX_SCREEN;
}
void MessageBoxScreenShutdown()
{
if (!gMsgBox.box) return;
RemoveMercPopupBox(gMsgBox.box);
gMsgBox.box = 0;
}
// a basic box that don't care what screen we came from
void DoScreenIndependantMessageBox(const ST::string& msg, MessageBoxFlags flags, MSGBOX_CALLBACK callback)
{
SGPBox const centering_rect = {0, 0, SCREEN_WIDTH, INV_INTERFACE_START_Y };
switch (ScreenID const screen = guiCurrentScreen)
{
case AUTORESOLVE_SCREEN:
case GAME_SCREEN: DoMessageBox( MSG_BOX_BASIC_STYLE, msg, screen, flags, callback, ¢ering_rect); break;
case LAPTOP_SCREEN: DoLapTopSystemMessageBoxWithRect(MSG_BOX_LAPTOP_DEFAULT, msg, screen, flags, callback, ¢ering_rect); break;
case MAP_SCREEN: DoMapMessageBoxWithRect( MSG_BOX_BASIC_STYLE, msg, screen, flags, callback, ¢ering_rect); break;
case OPTIONS_SCREEN: DoOptionsMessageBoxWithRect( msg, screen, flags, callback, ¢ering_rect); break;
case SAVE_LOAD_SCREEN: DoSaveLoadMessageBoxWithRect( msg, screen, flags, callback, ¢ering_rect); break;
default:
break;
}
}
| 8,126 |
602 | {
"remote.data.address": "tcp://data.quantos.org:8910",
"remote.data.username": "17621969269",
"remote.data.password": "<KEY>"
}
| 54 |
1,118 | <filename>vendor/rinvex/countries/resources/translations/mq.json
{"deu":{"common":"Martinique","official":"Martinique"},"fin":{"common":"Martinique","official":"Martinique"},"fra":{"common":"Martinique","official":"Martinique"},"hrv":{"common":"Martinique","official":"Martinique"},"ita":{"common":"Martinica","official":"Martinique"},"jpn":{"common":"マルティニーク","official":"マルティニーク島"},"nld":{"common":"Martinique","official":"Martinique"},"por":{"common":"Martinica","official":"Martinique"},"rus":{"common":"Мартиника","official":"Мартиника"},"spa":{"common":"Martinica","official":"Martinica"}}
| 177 |
3,794 | #ifndef HV_SCOPE_H_
#define HV_SCOPE_H_
#include <functional>
typedef std::function<void()> Function;
#include "hdef.h"
// same as golang defer
class Defer {
public:
Defer(Function&& fn) : _fn(std::move(fn)) {}
~Defer() { if(_fn) _fn();}
private:
Function _fn;
};
#define defer(code) Defer STRINGCAT(_defer_, __LINE__)([&](){code});
class ScopeCleanup {
public:
template<typename Fn, typename... Args>
ScopeCleanup(Fn&& fn, Args&&... args) {
_cleanup = std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...);
}
~ScopeCleanup() {
_cleanup();
}
private:
Function _cleanup;
};
template<typename T>
class ScopeFree {
public:
ScopeFree(T* p) : _p(p) {}
~ScopeFree() {SAFE_FREE(_p);}
private:
T* _p;
};
template<typename T>
class ScopeDelete {
public:
ScopeDelete(T* p) : _p(p) {}
~ScopeDelete() {SAFE_DELETE(_p);}
private:
T* _p;
};
template<typename T>
class ScopeDeleteArray {
public:
ScopeDeleteArray(T* p) : _p(p) {}
~ScopeDeleteArray() {SAFE_DELETE_ARRAY(_p);}
private:
T* _p;
};
template<typename T>
class ScopeRelease {
public:
ScopeRelease(T* p) : _p(p) {}
~ScopeRelease() {SAFE_RELEASE(_p);}
private:
T* _p;
};
template<typename T>
class ScopeLock {
public:
ScopeLock(T& mutex) : _mutex(mutex) {_mutex.lock();}
~ScopeLock() {_mutex.unlock();}
private:
T& _mutex;
};
#endif // HV_SCOPE_H_
| 662 |
5,169 | <filename>Specs/CC3DPerspectiveAnimationHeaderTableView/0.1.0/CC3DPerspectiveAnimationHeaderTableView.podspec.json
{
"name": "CC3DPerspectiveAnimationHeaderTableView",
"version": "0.1.0",
"summary": "3D perspective animation view.",
"description": "CC3DPerspectiveAnimationHeaderTableView is a UITableView which implemented 3D perspective animation header.",
"homepage": "https://github.com/caesarcat/CC3DPerspectiveAnimationHeaderTableView",
"screenshots": "https://raw.githubusercontent.com/caesarcat/CC3DPerspectiveAnimationHeaderTableView/master/sample1.gif",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"social_media_url": "https://twitter.com/caesar_cat",
"platforms": {
"ios": "7.0"
},
"source": {
"git": "https://github.com/caesarcat/CC3DPerspectiveAnimationHeaderTableView.git",
"tag": "0.1.0"
},
"source_files": "src/*.{h,m}",
"requires_arc": true
}
| 357 |
2,209 | import unittest
from test import test_support
import string
import StringIO
mimetools = test_support.import_module("mimetools", deprecated=True)
msgtext1 = mimetools.Message(StringIO.StringIO(
"""Content-Type: text/plain; charset=iso-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Foo!
"""))
class MimeToolsTest(unittest.TestCase):
def test_decodeencode(self):
start = string.ascii_letters + "=" + string.digits + "\n"
for enc in ['7bit','8bit','base64','quoted-printable',
'uuencode', 'x-uuencode', 'uue', 'x-uue']:
i = StringIO.StringIO(start)
o = StringIO.StringIO()
mimetools.encode(i, o, enc)
i = StringIO.StringIO(o.getvalue())
o = StringIO.StringIO()
mimetools.decode(i, o, enc)
self.assertEqual(o.getvalue(), start)
def test_boundary(self):
s = set([""])
for i in xrange(100):
nb = mimetools.choose_boundary()
self.assertNotIn(nb, s)
s.add(nb)
def test_message(self):
msg = mimetools.Message(StringIO.StringIO(msgtext1))
self.assertEqual(msg.gettype(), "text/plain")
self.assertEqual(msg.getmaintype(), "text")
self.assertEqual(msg.getsubtype(), "plain")
self.assertEqual(msg.getplist(), ["charset=iso-8859-1", "format=flowed"])
self.assertEqual(msg.getparamnames(), ["charset", "format"])
self.assertEqual(msg.getparam("charset"), "iso-8859-1")
self.assertEqual(msg.getparam("format"), "flowed")
self.assertEqual(msg.getparam("spam"), None)
self.assertEqual(msg.getencoding(), "8bit")
def test_main():
test_support.run_unittest(MimeToolsTest)
if __name__=="__main__":
test_main()
| 825 |
459 | /*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2021, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.solver.constraints.nary.cnf;
import org.chocosolver.solver.constraints.nary.sat.PropSat;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ConstraintsName;
import org.chocosolver.util.ESat;
/**
* <br/>
*
* @author <NAME>
* @since 22 nov. 2010
*/
public class SatConstraint extends Constraint {
private final PropSat miniSat;
public SatConstraint(Model model) {
super(ConstraintsName.SATCONSTRAINT,new PropSat(model));
miniSat = (PropSat) propagators[0];
}
@Override
public ESat isSatisfied() {
ESat so = ESat.UNDEFINED;
for (int i = 0; i < propagators.length; i++) {
so = propagators[i].isEntailed();
if (!so.equals(ESat.TRUE)) {
return so;
}
}
return so;
}
public PropSat getPropSat() {
return miniSat;
}
}
| 428 |
348 | {"nom":"Ytrac","circ":"1ère circonscription","dpt":"Cantal","inscrits":3351,"abs":1589,"votants":1762,"blancs":84,"nuls":41,"exp":1637,"res":[{"nuance":"REM","nom":"<NAME>","voix":824},{"nuance":"LR","nom":"<NAME>","voix":813}]} | 94 |
981 | #define INIT
#define FINI \
dyn->insts[ninst].x64.addr = addr; \
if(ninst) dyn->insts[ninst-1].x64.size = dyn->insts[ninst].x64.addr - dyn->insts[ninst-1].x64.addr;
#define MESSAGE(A, ...)
#define EMIT(A)
#define READFLAGS(A) dyn->insts[ninst].x64.use_flags = A
#define SETFLAGS(A,B) {dyn->insts[ninst].x64.set_flags = A; dyn->insts[ninst].x64.state_flags = B;}
#define NEW_INST \
dyn->insts[ninst].x64.addr = ip; \
if(ninst) dyn->insts[ninst-1].x64.size = dyn->insts[ninst].x64.addr - dyn->insts[ninst-1].x64.addr;
#define INST_EPILOG
#define INST_NAME(name)
| 294 |
575 | <reponame>iridium-browser/iridium-browser
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_MANAGER_H_
#define CONTENT_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_MANAGER_H_
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/callback_forward.h"
#include "base/cancelable_callback.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "content/browser/background_sync/background_sync.pb.h"
#include "content/browser/background_sync/background_sync_op_scheduler.h"
#include "content/browser/background_sync/background_sync_proxy.h"
#include "content/browser/background_sync/background_sync_status.h"
#include "content/browser/devtools/devtools_background_services_context_impl.h"
#include "content/browser/service_worker/service_worker_context_core_observer.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include "content/browser/service_worker/service_worker_registry.h"
#include "content/common/content_export.h"
#include "content/public/browser/background_sync_controller.h"
#include "content/public/browser/background_sync_parameters.h"
#include "content/public/browser/background_sync_registration.h"
#include "content/public/browser/browser_thread.h"
#include "third_party/blink/public/common/service_worker/service_worker_status_code.h"
#include "third_party/blink/public/mojom/background_sync/background_sync.mojom.h"
#include "third_party/blink/public/mojom/permissions/permission_status.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace blink {
namespace mojom {
enum class PermissionStatus;
} // namespace mojom
} // namespace blink
namespace content {
class BackgroundSyncNetworkObserver;
class ServiceWorkerContextWrapper;
// BackgroundSyncManager manages and stores the set of background sync
// registrations across all registered service workers for a profile.
// Registrations are stored along with their associated Service Worker
// registration in ServiceWorkerStorage. If the ServiceWorker is unregistered,
// the sync registrations are removed. This class runs on the UI thread.
// The asynchronous methods are executed sequentially.
class CONTENT_EXPORT BackgroundSyncManager
: public ServiceWorkerContextCoreObserver {
public:
using BoolCallback = base::OnceCallback<void(bool)>;
using StatusCallback = base::OnceCallback<void(BackgroundSyncStatus)>;
using StatusAndRegistrationCallback =
base::OnceCallback<void(BackgroundSyncStatus,
std::unique_ptr<BackgroundSyncRegistration>)>;
using StatusAndRegistrationsCallback = base::OnceCallback<void(
BackgroundSyncStatus,
std::vector<std::unique_ptr<BackgroundSyncRegistration>>)>;
using BackgroundSyncEventKeepAlive =
BackgroundSyncController::BackgroundSyncEventKeepAlive;
static std::unique_ptr<BackgroundSyncManager> Create(
scoped_refptr<ServiceWorkerContextWrapper> service_worker_context,
scoped_refptr<DevToolsBackgroundServicesContextImpl> devtools_context);
~BackgroundSyncManager() override;
// Stores the given background sync registration and adds it to the scheduling
// queue. It will overwrite an existing registration with the same tag unless
// they're identical (save for the id). Calls |callback| with
// BACKGROUND_SYNC_STATUS_OK and the accepted registration on success.
// The accepted registration will have a unique id. It may also have altered
// parameters if the user or UA chose different parameters than those
// supplied.
void Register(int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions options,
StatusAndRegistrationCallback callback);
// Removes the Periodic Background Sync registration identified by |tag| for
// the service worker identified by |sw_registration_id|. Calls |callback|
// with BACKGROUND_SYNC_STATUS_OK on success.
void UnregisterPeriodicSync(int64_t sw_registration_id,
const std::string& tag,
StatusCallback callback);
// Called after the client has resolved its registration promise. At this
// point it's safe to fire any pending registrations.
void DidResolveRegistration(
blink::mojom::BackgroundSyncRegistrationInfoPtr registration_info);
// Finds the one-shot Background Sync registrations associated with
// |sw_registration_id|. Calls |callback| with BACKGROUND_SYNC_STATUS_OK on
// success.
void GetOneShotSyncRegistrations(int64_t sw_registration_id,
StatusAndRegistrationsCallback callback);
// Finds the periodic Background Sync registrations associated with
// |sw_registration_id|. Calls |callback| with BACKGROUND_SYNC_STATUS_OK on
// success.
void GetPeriodicSyncRegistrations(int64_t sw_registration_id,
StatusAndRegistrationsCallback callback);
// Goes through the list of active Periodic Background Sync registrations and
// unregisters any origins that no longer have the required permission.
void UnregisterPeriodicSyncForOrigin(const url::Origin& origin);
// ServiceWorkerContextCoreObserver overrides.
void OnRegistrationDeleted(int64_t sw_registration_id,
const GURL& pattern) override;
void OnStorageWiped() override;
BackgroundSyncNetworkObserver* GetNetworkObserverForTesting() {
return network_observer_.get();
}
void set_clock(base::Clock* clock) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
clock_ = clock;
}
void set_proxy_for_testing(std::unique_ptr<BackgroundSyncProxy> proxy) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
proxy_ = std::move(proxy);
}
// Called from DevTools
void EmulateDispatchSyncEvent(
const std::string& tag,
scoped_refptr<ServiceWorkerVersion> active_version,
bool last_chance,
ServiceWorkerVersion::StatusCallback callback);
void EmulateDispatchPeriodicSyncEvent(
const std::string& tag,
scoped_refptr<ServiceWorkerVersion> active_version,
ServiceWorkerVersion::StatusCallback callback);
// Called from DevTools to toggle service worker "offline" status
void EmulateServiceWorkerOffline(int64_t service_worker_id, bool is_offline);
// Scans the list of available events and fires those of type |sync_type| that
// are ready to fire. For those that can't yet be fired, wakeup alarms are
// set. Once all of this is done, invokes |callback|.
virtual void FireReadyEvents(
blink::mojom::BackgroundSyncType sync_type,
bool reschedule,
base::OnceClosure callback,
std::unique_ptr<BackgroundSyncEventKeepAlive> keepalive = nullptr);
// Gets the soonest delta after which the browser should be woken up to send
// a Background Sync event. If set to max, the browser won't be woken up.
// Only registrations of type |sync_type| are considered.
// Browsers can have a hard limit on how often to wake themselves up to
// process Periodic Background Sync registrations. We apply this limit if
// |last_browser_wakeup_time| is not null.
// This limit is only applied when calculating the soonest wake up delta to
// wake up Chrome. It's not applied when calculating the time after which a
// delayed task should be run to process Background Sync registrations.
virtual base::TimeDelta GetSoonestWakeupDelta(
blink::mojom::BackgroundSyncType sync_type,
base::Time last_browser_wakeup_time);
// Browsers can have a hard limit on how often to wake themselves up to
// process Periodic Background Sync registrations. If the browser can't be
// woken up after |wakeup_delta| to do so, returns an updated delta after
// which it's safe to wake the browser. This limit doesn't apply to retries.
base::TimeDelta MaybeApplyBrowserWakeupCountLimit(
base::TimeDelta wakeup_delta,
base::Time last_browser_wakeup_time);
// Finds all periodicsync registrations for the |origin|, and returns the time
// till the soonest scheduled periodicsync event for this origin, skipping
// over the registration with tag |tag_to_skip|. If there's
// none, it returns base::TimeDelta::Max(). If the soonest such event is
// scheduled to be fired in the past, returns base::TimeDelta().
base::TimeDelta GetSmallestPeriodicSyncEventDelayForOrigin(
const url::Origin& origin,
const std::string& tag_to_skip) const;
// Revive any pending periodic Background Sync registrations for |origin|.
void RevivePeriodicSyncRegistrations(url::Origin origin);
protected:
BackgroundSyncManager(
scoped_refptr<ServiceWorkerContextWrapper> context,
scoped_refptr<DevToolsBackgroundServicesContextImpl> devtools_context);
// Init must be called before any public member function. Only call it once.
void Init();
// The following methods are virtual for testing.
virtual void StoreDataInBackend(
int64_t sw_registration_id,
const url::Origin& origin,
const std::string& backend_key,
const std::string& data,
ServiceWorkerRegistry::StatusCallback callback);
virtual void GetDataFromBackend(
const std::string& backend_key,
ServiceWorkerRegistry::GetUserDataForAllRegistrationsCallback callback);
virtual void DispatchSyncEvent(
const std::string& tag,
scoped_refptr<ServiceWorkerVersion> active_version,
bool last_chance,
ServiceWorkerVersion::StatusCallback callback);
virtual void DispatchPeriodicSyncEvent(
const std::string& tag,
scoped_refptr<ServiceWorkerVersion> active_version,
ServiceWorkerVersion::StatusCallback callback);
virtual void HasMainFrameWindowClient(const url::Origin& origin,
BoolCallback callback);
private:
friend class TestBackgroundSyncManager;
friend class BackgroundSyncManagerTest;
struct BackgroundSyncRegistrations {
using RegistrationMap =
std::map<std::pair<std::string, blink::mojom::BackgroundSyncType>,
BackgroundSyncRegistration>;
BackgroundSyncRegistrations();
BackgroundSyncRegistrations(const BackgroundSyncRegistrations& other);
~BackgroundSyncRegistrations();
RegistrationMap registration_map;
url::Origin origin;
};
static const size_t kMaxTagLength = 10240;
// Disable the manager. Already queued operations will abort once they start
// to run (in their impl methods). Future operations will not queue.
// The list of active registrations is cleared and the backend is also cleared
// (if it's still functioning). The manager will reenable itself once it
// receives the OnStorageWiped message or on browser restart.
void DisableAndClearManager(base::OnceClosure callback);
void DisableAndClearDidGetRegistrations(
base::OnceClosure callback,
const std::vector<std::pair<int64_t, std::string>>& user_data,
blink::ServiceWorkerStatusCode status);
void DisableAndClearManagerClearedOne(base::OnceClosure barrier_closure,
blink::ServiceWorkerStatusCode status);
// Returns the existing registration or nullptr if it cannot be found.
BackgroundSyncRegistration* LookupActiveRegistration(
const blink::mojom::BackgroundSyncRegistrationInfo& registration_info);
// Write all registrations for a given |sw_registration_id| to persistent
// storage.
void StoreRegistrations(int64_t sw_registration_id,
ServiceWorkerRegistry::StatusCallback callback);
// Removes the active registration if it is in the map.
void RemoveActiveRegistration(
const blink::mojom::BackgroundSyncRegistrationInfo& registration_info);
void AddOrUpdateActiveRegistration(
int64_t sw_registration_id,
const url::Origin& origin,
const BackgroundSyncRegistration& sync_registration);
void InitImpl(base::OnceClosure callback);
void InitDidGetControllerParameters(
base::OnceClosure callback,
std::unique_ptr<BackgroundSyncParameters> parameters);
void InitDidGetDataFromBackend(
base::OnceClosure callback,
const std::vector<std::pair<int64_t, std::string>>& user_data,
blink::ServiceWorkerStatusCode status);
void GetRegistrations(blink::mojom::BackgroundSyncType sync_type,
int64_t sw_registration_id,
StatusAndRegistrationsCallback callback);
// Register callbacks
void RegisterCheckIfHasMainFrame(
int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions options,
StatusAndRegistrationCallback callback);
void RegisterDidCheckIfMainFrame(
int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions options,
StatusAndRegistrationCallback callback,
bool has_main_frame_client);
void RegisterImpl(int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions options,
StatusAndRegistrationCallback callback);
void RegisterDidAskForPermission(
int64_t sw_registration_id,
blink::mojom::SyncRegistrationOptions options,
StatusAndRegistrationCallback callback,
std::pair<blink::mojom::PermissionStatus, blink::mojom::PermissionStatus>
permission_statuses);
void RegisterDidGetDelay(int64_t sw_registration_id,
BackgroundSyncRegistration new_registration,
StatusAndRegistrationCallback callback,
base::TimeDelta delay);
void RegisterDidStore(int64_t sw_registration_id,
const BackgroundSyncRegistration& new_registration,
StatusAndRegistrationCallback callback,
blink::ServiceWorkerStatusCode status);
void UnregisterPeriodicSyncImpl(int64_t sw_registration_id,
const std::string& tag,
StatusCallback callback);
void UnregisterPeriodicSyncDidStore(StatusCallback callback,
blink::ServiceWorkerStatusCode status);
// DidResolveRegistration callbacks
void DidResolveRegistrationImpl(
blink::mojom::BackgroundSyncRegistrationInfoPtr registration_info);
void ResolveRegistrationDidCreateKeepAlive(
std::unique_ptr<BackgroundSyncEventKeepAlive> keepalive);
// GetRegistrations callbacks
void GetRegistrationsImpl(blink::mojom::BackgroundSyncType sync_type,
int64_t sw_registration_id,
StatusAndRegistrationsCallback callback);
bool AreOptionConditionsMet();
bool IsRegistrationReadyToFire(const BackgroundSyncRegistration& registration,
int64_t service_worker_id);
// Determines if the browser needs to be able to run in the background (e.g.,
// to run a pending registration or verify that a firing registration
// completed). If background processing is required it calls out to
// BackgroundSyncProxy to enable it.
// Assumes that all registrations in the pending state are not currently ready
// to fire. Therefore this should not be called directly and should only be
// called by FireReadyEvents.
void ScheduleDelayedProcessingOfRegistrations(
blink::mojom::BackgroundSyncType sync_type);
// Cancels waking up of the browser to process (Periodic) BackgroundSync
// registrations.
void CancelDelayedProcessingOfRegistrations(
blink::mojom::BackgroundSyncType sync_type);
// Fires ready events for |sync_type|.
// |reschedule| is true when it's ok to schedule background processing from
// this method, false otherwise.
// |scheduler_id| is an id unique to the |op_scheduler_| task. It's passed to
// correctly mark this operation as finished with the |op_scheduler_| and run
// the next operation scheduled.
// |keepalive| is used to keep the browser alive until the first attempt to
// fire a sync event has been made.
void FireReadyEventsImpl(
blink::mojom::BackgroundSyncType sync_type,
bool reschedule,
base::OnceClosure callback,
std::unique_ptr<BackgroundSyncEventKeepAlive> keepalive);
void FireReadyEventsDidFindRegistration(
blink::mojom::BackgroundSyncRegistrationInfoPtr registration_info,
std::unique_ptr<BackgroundSyncEventKeepAlive> keepalive,
base::OnceClosure event_fired_callback,
base::OnceClosure event_completed_callback,
blink::ServiceWorkerStatusCode service_worker_status,
scoped_refptr<ServiceWorkerRegistration> service_worker_registration);
void FireReadyEventsAllEventsFiring(
blink::mojom::BackgroundSyncType sync_type,
bool reschedule,
base::OnceClosure callback);
// Called when a sync event has completed.
void EventComplete(
scoped_refptr<ServiceWorkerRegistration> service_worker_registration,
blink::mojom::BackgroundSyncRegistrationInfoPtr registration_info,
std::unique_ptr<BackgroundSyncEventKeepAlive> keepalive,
base::OnceClosure callback,
blink::ServiceWorkerStatusCode status_code);
void EventCompleteImpl(
blink::mojom::BackgroundSyncRegistrationInfoPtr registration_info,
std::unique_ptr<BackgroundSyncEventKeepAlive> keepalive,
blink::ServiceWorkerStatusCode status_code,
const url::Origin& origin,
base::OnceClosure callback);
void EventCompleteDidGetDelay(
blink::mojom::BackgroundSyncRegistrationInfoPtr registration_info,
blink::ServiceWorkerStatusCode status_code,
const url::Origin& origin,
base::OnceClosure callback,
base::TimeDelta delay);
void EventCompleteDidStore(blink::mojom::BackgroundSyncType sync_type,
int64_t service_worker_id,
base::OnceClosure callback,
blink::ServiceWorkerStatusCode status_code);
// Called when all sync events have completed.
static void OnAllSyncEventsCompleted(
blink::mojom::BackgroundSyncType sync_type,
const base::TimeTicks& start_time,
bool from_wakeup_task,
int number_of_batched_sync_events,
base::OnceClosure callback);
// OnRegistrationDeleted callbacks
void OnRegistrationDeletedImpl(int64_t sw_registration_id,
base::OnceClosure callback);
// OnStorageWiped callbacks
void OnStorageWipedImpl(base::OnceClosure callback);
void OnNetworkChanged();
// Whether an event should be logged for debuggability, for |sync_type|.
bool ShouldLogToDevTools(blink::mojom::BackgroundSyncType sync_type);
void ReviveOriginImpl(url::Origin origin, base::OnceClosure callback);
void ReviveDidGetNextEventDelay(int64_t service_worker_registration_id,
BackgroundSyncRegistration registration,
base::OnceClosure done_closure,
base::TimeDelta delay);
void ReviveDidStoreRegistration(int64_t service_worker_registration_id,
base::OnceClosure done_closure,
blink::ServiceWorkerStatusCode status);
void DidReceiveDelaysForSuspendedRegistrations(base::OnceClosure callback);
// Helper methods to unregister Periodic Background Sync registrations
// associated with |origin|.
void UnregisterForOriginImpl(const url::Origin& origin,
base::OnceClosure callback);
void UnregisterForOriginDidStore(base::OnceClosure done_closure,
blink::ServiceWorkerStatusCode status);
void UnregisterForOriginScheduleDelayedProcessing(base::OnceClosure callback);
base::OnceClosure MakeEmptyCompletion();
blink::ServiceWorkerStatusCode CanEmulateSyncEvent(
scoped_refptr<ServiceWorkerVersion> active_version);
// Read or update |num_firing_registrations_one_shot_| or
// |num_firing_registrations_periodic_| based on |sync_type|.
int GetNumFiringRegistrations(blink::mojom::BackgroundSyncType sync_type);
void UpdateNumFiringRegistrationsBy(
blink::mojom::BackgroundSyncType sync_type,
int to_add);
// Returns true if all registrations are waiting to be resolved.
// false otherwise.
bool AllRegistrationsWaitingToBeResolved() const;
// Returns true if a registration can fire immediately once we have network
// connectivity.
bool AllConditionsExceptConnectivitySatisfied(
const BackgroundSyncRegistration& registration,
int64_t service_worker_id);
// Returns true if any registration of |sync_type| can be fired right when we
// have network connectivity.
bool CanFireAnyRegistrationUponConnectivity(
blink::mojom::BackgroundSyncType sync_type);
// Returns a reference to the bool that notes whether delayed processing for
// registrations of |sync_type| is currently scheduled.
bool& delayed_processing_scheduled(
blink::mojom::BackgroundSyncType sync_type);
// If we should schedule delayed processing, this does so.
// If we should cancel delayed processing, this does so.
// Else, this does nothing.
void ScheduleOrCancelDelayedProcessing(
blink::mojom::BackgroundSyncType sync_type);
// Map from service worker registration id to its Background Sync
// registrations.
std::map<int64_t, BackgroundSyncRegistrations> active_registrations_;
BackgroundSyncOpScheduler op_scheduler_;
scoped_refptr<ServiceWorkerContextWrapper> service_worker_context_;
std::unique_ptr<BackgroundSyncProxy> proxy_;
scoped_refptr<DevToolsBackgroundServicesContextImpl> devtools_context_;
std::unique_ptr<BackgroundSyncParameters> parameters_;
// True if the manager is disabled and registrations should fail.
bool disabled_;
// The number of registrations currently in the firing state.
int num_firing_registrations_one_shot_;
int num_firing_registrations_periodic_;
bool delayed_processing_scheduled_one_shot_sync_ = false;
bool delayed_processing_scheduled_periodic_sync_ = false;
std::unique_ptr<BackgroundSyncNetworkObserver> network_observer_;
base::Clock* clock_;
std::map<int64_t, int> emulated_offline_sw_;
SEQUENCE_CHECKER(sequence_checker_);
base::WeakPtrFactory<BackgroundSyncManager> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(BackgroundSyncManager);
};
} // namespace content
#endif // CONTENT_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_MANAGER_H_
| 7,484 |
7,897 | <reponame>shawabhishek/Cpp-Primer<gh_stars>1000+
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 04 Feb 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//
// Exercise 16.29:
// Revise your Blob class to use your version of shared_ptr rather than the
// library version.
//
#include <iostream>
#include <vector>
#include <memory>
#include <functional>
#include "DebugDelete.h"
#include "shared_pointer.h"
#include "unique_pointer.h"
#include "Blob.h"
int main()
{
Blob<std::string> b;
b.push_back("sss");
b[0] = "zzzz";
std::cout << b[0] << "\n";
}
| 272 |
1,117 | <gh_stars>1000+
# Copyright 2017--2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not
# use this file except in compliance with the License. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
import pytest
from unittest import mock
from collections import Counter
import sockeye.constants as C
from sockeye.vocab import (build_vocab, get_ordered_tokens_from_vocab, is_valid_vocab, \
_get_sorted_source_vocab_fnames, count_tokens)
def test_count_tokens():
data = ["a b c", "c d e"]
raw_vocab = count_tokens(data)
assert raw_vocab == Counter({"a": 1, "b": 1, "c": 2, "d": 1, "e": 1})
test_vocab = [
# Example 1
(["one two three", "one two three"], None, 1,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "two": 4, "three": 5, "one": 6}),
(["one two three", "one two three"], 3, 1,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "two": 4, "three": 5, "one": 6}),
(["one two three", "one two three"], 3, 2,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "two": 4, "three": 5, "one": 6}),
(["one two three", "one two three"], 2, 2,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "two": 4, "three": 5}),
# Example 2
(["one one two three ", "one two three"], 3, 1,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "one": 4, "two": 5, "three": 6}),
(["one one two three ", "one two three"], 3, 2,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "one": 4, "two": 5, "three": 6}),
(["one one two three ", "one two three"], 3, 3,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "one": 4}),
(["one one two three ", "one two three"], 2, 1,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "one": 4, "two": 5}),
# Example 3 (including special symbols)
(["one two three <s> <s>", "one two three <s> <s>"], None, 1,
{"<pad>": 0, "<unk>": 1, "<s>": 2, "</s>": 3, "two": 4, "three": 5, "one": 6}),
]
@pytest.mark.parametrize("data,size,min_count,expected", test_vocab)
def test_build_vocab(data, size, min_count, expected):
vocab = build_vocab(data=data, num_words=size, min_count=min_count)
assert vocab == expected
@pytest.mark.parametrize("num_types,pad_to_multiple_of,expected_vocab_size",
[(4, None, 8), (2, 8, 8), (4, 8, 8), (8, 8, 16), (10, 16, 16), (13, 16, 32)])
def test_padded_build_vocab(num_types, pad_to_multiple_of, expected_vocab_size):
data = [" ".join('word%d' % i for i in range(num_types))]
size = None
min_count = 1
vocab = build_vocab(data, size, min_count, pad_to_multiple_of=pad_to_multiple_of)
assert len(vocab) == expected_vocab_size
test_constants = [
# Example 1
(["one two three", "one two three"], 3, 1, C.VOCAB_SYMBOLS),
(["one two three", "one two three"], 3, 2, C.VOCAB_SYMBOLS),
(["one two three", "one two three"], 2, 2, C.VOCAB_SYMBOLS),
# Example 2
(["one one two three ", "one two three"], 3, 1, C.VOCAB_SYMBOLS),
(["one one two three ", "one two three"], 3, 2, C.VOCAB_SYMBOLS),
(["one one two three ", "one two three"], 3, 3, C.VOCAB_SYMBOLS),
(["one one two three ", "one two three"], 2, 1, C.VOCAB_SYMBOLS),
]
@pytest.mark.parametrize("data,size,min_count,constants", test_constants)
def test_constants_in_vocab(data, size, min_count, constants):
vocab = build_vocab(data, size, min_count)
for const in constants:
assert const in vocab
@pytest.mark.parametrize("vocab, expected_output", [({"<pad>": 0, "a": 4, "b": 2}, ["<pad>", "b", "a"]),
({}, [])])
def test_get_ordered_tokens_from_vocab(vocab, expected_output):
assert get_ordered_tokens_from_vocab(vocab) == expected_output
@pytest.mark.parametrize(
"vocab, expected_result",
[
({symbol: idx for idx, symbol in enumerate(C.VOCAB_SYMBOLS + ["w1", "w2"])}, True),
# A vocabulary with just the valid symbols doesn't make much sense but is technically valid
({symbol: idx for idx, symbol in enumerate(C.VOCAB_SYMBOLS)}, True),
# Manually specifying the list of required special symbol so that we avoid making a backwards-incompatible
# change by adding a new symbol to C.VOCAB_SYMBOLS
({symbol: idx for idx, symbol in enumerate([C.PAD_SYMBOL, C.UNK_SYMBOL, C.BOS_SYMBOL, C.EOS_SYMBOL])}, True),
# PAD_ID must have word id 0
({symbol: idx for idx, symbol in enumerate(reversed(C.VOCAB_SYMBOLS))}, False),
({symbol: idx for idx, symbol in enumerate(list(reversed(C.VOCAB_SYMBOLS)) + ["w1", "w2"])}, False),
# If there is a gap the vocabulary is not valid:
({symbol: idx if symbol != "w2" else idx + 1 for idx, symbol in enumerate(C.VOCAB_SYMBOLS + ["w1", "w2"])}, False),
# There shouldn't be any duplicate word ids
({symbol: idx if symbol != "w2" else idx - 1 for idx, symbol in enumerate(C.VOCAB_SYMBOLS + ["w1", "w2"])}, False),
]
)
def test_verify_valid_vocab(vocab, expected_result):
assert is_valid_vocab(vocab) == expected_result
def test_get_sorted_source_vocab_fnames():
expected_fnames = [C.VOCAB_SRC_NAME % i for i in [1, 2, 10]]
with mock.patch('os.listdir') as mocked_listdir:
mocked_listdir.return_value = [C.VOCAB_SRC_NAME % i for i in [2, 1, 10]]
fnames = _get_sorted_source_vocab_fnames(None)
assert fnames == expected_fnames
| 2,604 |
809 | /*
* LensKit, an open-source toolkit for recommender systems.
* Copyright 2014-2017 LensKit contributors (see CONTRIBUTORS.md)
* Copyright 2010-2014 Regents of the University of Minnesota
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.lenskit.util.io;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.hamcrest.Matchers;
import org.junit.Test;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public class GroupingObjectStreamTest {
public static class FirstLetterObjectStream extends GroupingObjectStream<List<String>, String> {
private boolean inGroup;
private char firstChar;
private List<String> strings;
public FirstLetterObjectStream(ObjectStream<String> base) {
super(base);
}
public FirstLetterObjectStream(Iterable<String> vals) {
this(ObjectStreams.wrap(vals.iterator()));
}
@Override
protected boolean handleItem(@Nonnull String item) {
if (!inGroup) {
assert strings == null;
strings = Lists.newArrayList(item);
firstChar = item.charAt(0);
inGroup = true;
return true;
} else if (firstChar == item.charAt(0)) {
strings.add(item);
return true;
} else {
return false;
}
}
@Nonnull
@Override
protected List<String> finishGroup() {
List<String> ret = strings;
inGroup = false;
strings = null;
return ret;
}
@Override
protected void clearGroup() {
strings = null;
inGroup = false;
}
public Character getFirstChar() {
return firstChar;
}
public void setFirstChar(Character firstChar) {
this.firstChar = firstChar;
}
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> strings) {
this.strings = strings;
}
}
@Test
public void testEmptyStream() {
FirstLetterObjectStream cur = new FirstLetterObjectStream(new ArrayList<String>());
assertThat(cur.readObject(), nullValue());
}
@Test
public void testSingleton() {
FirstLetterObjectStream cur = new FirstLetterObjectStream(Arrays.asList("foo"));
assertThat(cur.readObject(),
equalTo(Arrays.asList("foo")));
assertThat(cur.readObject(), nullValue());
}
@Test
@SuppressWarnings("unchecked")
public void testSameLetter() {
List<String> items = Lists.newArrayList("foo", "frob", "fizzle");
FirstLetterObjectStream cur = new FirstLetterObjectStream(items);
assertThat(cur, Matchers.<List<String>>contains(ImmutableList.copyOf(items)));
}
@Test
@SuppressWarnings("unchecked")
public void testSeveralGroups() {
FirstLetterObjectStream cur = new FirstLetterObjectStream(Arrays.asList("foo", "frob", "bar", "wombat", "woozle"));
assertThat(cur, contains(Arrays.asList("foo", "frob"),
Arrays.asList("bar"),
Arrays.asList("wombat", "woozle")));
}
}
| 1,815 |
530 | <reponame>popescunsergiu/node-zwave-js<filename>packages/config/config/devices/0x014f/lbr30z-1_5.16-5.16.json<gh_stars>100-1000
{
"manufacturer": "Nortek Security & Control LLC",
"manufacturerId": "0x014f",
"label": "LBR30Z-1",
"description": "Dimmable LED Light Bulb",
"devices": [
{
"productType": "0x4754",
"productId": "0x4252"
}
],
"firmwareVersion": {
"min": "5.16",
"max": "5.16"
},
"paramInformation": [
{
"#": "1",
"label": "Dim Level Memory",
"valueSize": 1,
"minValue": 0,
"maxValue": 1,
"defaultValue": 0,
"allowManualEntry": false,
"options": [
{
"label": "Disable dim level memory",
"value": 0
},
{
"label": "Enable dim level memory",
"value": 1
}
]
},
{
"#": "9",
"label": "Dim / Bright Step Level",
"description": "How much the brightness will change with each dimming step",
"valueSize": 1,
"minValue": 1,
"maxValue": 99,
"defaultValue": 1
},
{
"#": "10",
"label": "Dim / Bright Speed",
"description": "How fast the brightness will change with each dimming step",
"valueSize": 1,
"minValue": 1,
"maxValue": 10,
"defaultValue": 3
}
]
}
| 557 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.