max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
2,293 | <gh_stars>1000+
"""macresource - Locate and open the resources needed for a script."""
from warnings import warnpy3k
warnpy3k("In 3.x, the macresource module is removed.", stacklevel=2)
from Carbon import Res
import os
import sys
import MacOS
import macostools
class ArgumentError(TypeError): pass
class ResourceFileNotFoundError(ImportError): pass
def need(restype, resid, filename=None, modname=None):
"""Open a resource file, if needed. restype and resid
are required parameters, and identify the resource for which to test. If it
is available we are done. If it is not available we look for a file filename
(default: modname with .rsrc appended) either in the same folder as
where modname was loaded from, or otherwise across sys.path.
Returns the refno of the resource file opened (or None)"""
if modname is None and filename is None:
raise ArgumentError, "Either filename or modname argument (or both) must be given"
if type(resid) is type(1):
try:
h = Res.GetResource(restype, resid)
except Res.Error:
pass
else:
return None
else:
try:
h = Res.GetNamedResource(restype, resid)
except Res.Error:
pass
else:
return None
# Construct a filename if we don't have one
if not filename:
if '.' in modname:
filename = modname.split('.')[-1] + '.rsrc'
else:
filename = modname + '.rsrc'
# Now create a list of folders to search
searchdirs = []
if modname == '__main__':
# If we're main we look in the current directory
searchdirs = [os.curdir]
if sys.modules.has_key(modname):
mod = sys.modules[modname]
if hasattr(mod, '__file__'):
searchdirs = [os.path.dirname(mod.__file__)]
searchdirs.extend(sys.path)
# And look for the file
for dir in searchdirs:
pathname = os.path.join(dir, filename)
if os.path.exists(pathname):
break
else:
raise ResourceFileNotFoundError, filename
refno = open_pathname(pathname)
# And check that the resource exists now
if type(resid) is type(1):
h = Res.GetResource(restype, resid)
else:
h = Res.GetNamedResource(restype, resid)
return refno
def open_pathname(pathname, verbose=0):
"""Open a resource file given by pathname, possibly decoding an
AppleSingle file"""
try:
refno = Res.FSpOpenResFile(pathname, 1)
except Res.Error, arg:
if arg[0] in (-37, -39):
# No resource fork. We may be on OSX, and this may be either
# a data-fork based resource file or a AppleSingle file
# from the CVS repository.
try:
refno = Res.FSOpenResourceFile(pathname, u'', 1)
except Res.Error, arg:
if arg[0] != -199:
# -199 is "bad resource map"
raise
else:
return refno
# Finally try decoding an AppleSingle file
pathname = _decode(pathname, verbose=verbose)
refno = Res.FSOpenResourceFile(pathname, u'', 1)
else:
raise
return refno
def resource_pathname(pathname, verbose=0):
"""Return the pathname for a resource file (either DF or RF based).
If the pathname given already refers to such a file simply return it,
otherwise first decode it."""
try:
refno = Res.FSpOpenResFile(pathname, 1)
Res.CloseResFile(refno)
except Res.Error, arg:
if arg[0] in (-37, -39):
# No resource fork. We may be on OSX, and this may be either
# a data-fork based resource file or a AppleSingle file
# from the CVS repository.
try:
refno = Res.FSOpenResourceFile(pathname, u'', 1)
except Res.Error, arg:
if arg[0] != -199:
# -199 is "bad resource map"
raise
else:
return refno
# Finally try decoding an AppleSingle file
pathname = _decode(pathname, verbose=verbose)
else:
raise
return pathname
def open_error_resource():
"""Open the resource file containing the error code to error message
mapping."""
need('Estr', 1, filename="errors.rsrc", modname=__name__)
def _decode(pathname, verbose=0):
# Decode an AppleSingle resource file, return the new pathname.
newpathname = pathname + '.df.rsrc'
if os.path.exists(newpathname) and \
os.stat(newpathname).st_mtime >= os.stat(pathname).st_mtime:
return newpathname
if hasattr(os, 'access') and not \
os.access(os.path.dirname(pathname), os.W_OK|os.X_OK):
# The destination directory isn't writeable. Create the file in
# a temporary directory
import tempfile
fd, newpathname = tempfile.mkstemp(".rsrc")
if verbose:
print 'Decoding', pathname, 'to', newpathname
import applesingle
applesingle.decode(pathname, newpathname, resonly=1)
return newpathname
| 2,212 |
3,631 | <gh_stars>1000+
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.verifier.core.index.select;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.drools.verifier.core.index.keys.Value;
import org.drools.verifier.core.index.matchers.ExactMatcher;
import org.drools.verifier.core.index.matchers.Matcher;
import org.drools.verifier.core.maps.KeyDefinition;
import org.drools.verifier.core.maps.MultiMap;
import org.drools.verifier.core.maps.MultiMapFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals;
@RunWith( Parameterized.class )
public class SelectExactMatcherNegateTest {
private int amount;
private Select<Item> select;
private Object firstValue;
private Object lastValue;
private MultiMap<Value, Item, List<Item>> makeMap() {
final MultiMap<Value, Item, List<Item>> itemKeyTreeMap = MultiMapFactory.make();
itemKeyTreeMap.put( new Value( null ),
new Item( null ) );
itemKeyTreeMap.put( new Value( 0 ),
new Item( 0 ) );
itemKeyTreeMap.put( new Value( 56 ),
new Item( 56 ) );
itemKeyTreeMap.put( new Value( 100 ),
new Item( 100 ) );
itemKeyTreeMap.put( new Value( 1200 ),
new Item( 1200 ) );
return itemKeyTreeMap;
}
public SelectExactMatcherNegateTest( final int amount,
final Object firstValue,
final Object lastValue,
final Matcher matcher ) throws Exception {
this.firstValue = firstValue;
this.lastValue = lastValue;
this.amount = amount;
this.select = new Select<>( makeMap(),
matcher );
}
@Parameterized.Parameters
public static Collection<Object[]> testData() {
return Arrays.asList( new Object[][]{
{5, null, 1200, new ExactMatcher( KeyDefinition.newKeyDefinition().withId( "cost" ).build(),
13,
true )},
{4, 0, 1200, new ExactMatcher( KeyDefinition.newKeyDefinition().withId( "cost" ).build(),
null,
true )},
} );
}
@Test
public void testAll() throws Exception {
final Collection<Item> all = select.all();
assertEquals( amount, all.size() );
}
@Test
public void testFirst() throws Exception {
assertEquals( firstValue,
select.first().cost );
}
@Test
public void testLast() throws Exception {
assertEquals( lastValue,
select.last().cost );
}
private class Item {
private Integer cost;
public Item( final Integer cost ) {
this.cost = cost;
}
}
} | 1,682 |
1,338 | /*
** Copyright 2003, <NAME>, <EMAIL>. All rights reserved.
** Distributed under the terms of the MIT License.
*/
#ifndef FILE_H
#define FILE_H
#include <boot/vfs.h>
#include "Volume.h"
namespace FFS {
class File : public Node {
public:
File(Volume &volume, int32 block);
virtual ~File();
status_t InitCheck();
virtual status_t Open(void **_cookie, int mode);
virtual status_t Close(void *cookie);
virtual ssize_t ReadAt(void *cookie, off_t pos, void *buffer, size_t bufferSize);
virtual ssize_t WriteAt(void *cookie, off_t pos, const void *buffer, size_t bufferSize);
virtual status_t GetName(char *nameBuffer, size_t bufferSize) const;
virtual int32 Type() const;
virtual off_t Size() const;
virtual ino_t Inode() const;
private:
Volume &fVolume;
FileBlock fNode;
};
} // namespace FFS
#endif /* FILE_H */
| 306 |
789 | package io.advantageous.qbit.util;
import java.io.IOException;
import java.net.ServerSocket;
/**
* created by rhightower on 3/4/15.
*/
public class PortUtils {
public static int useOneOfThesePorts(int... ports) {
for (int port : ports) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
serverSocket.close();
return port;
} catch (IOException ex) {
//
} finally {
if (serverSocket != null) {
if (!serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
// if the program gets here, no port in the range was found
throw new IllegalStateException("no free port found");
}
public static int useOneOfThePortsInThisRange(int start, int stop) {
for (int index = start; index < stop; index++) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(index);
serverSocket.close();
return index;
} catch (IOException ex) {
//
} finally {
if (serverSocket != null) {
if (!serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
// if the program gets here, no port in the range was found
throw new IllegalStateException("no free port found");
}
public static int findOpenPort() {
return useOneOfThePortsInThisRange(6000, 30_000);
}
public static int findOpenPortStartAt(int start) {
return useOneOfThePortsInThisRange(start, 30_000);
}
}
| 1,155 |
325 | <reponame>mewbak/wasmdec<gh_stars>100-1000
#include <stdio.h>
int main() {
int i = 1;
++i;
printf("i is %d\n", i);
return 0;
} | 68 |
14,668 | <gh_stars>1000+
// Copyright 2019 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 WEBLAYER_PUBLIC_DOWNLOAD_DELEGATE_H_
#define WEBLAYER_PUBLIC_DOWNLOAD_DELEGATE_H_
#include <string>
#include "base/callback_forward.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/origin.h"
class GURL;
namespace weblayer {
class Download;
class Tab;
using AllowDownloadCallback = base::OnceCallback<void(bool /*allow*/)>;
// An interface that allows clients to handle download requests originating in
// the browser. The object is safe to hold on to until DownloadCompleted or
// DownloadFailed are called.
class DownloadDelegate {
public:
// Gives the embedder the opportunity to asynchronously allow or disallow the
// given download. The download is paused until the callback is run. It's safe
// to run |callback| synchronously.
virtual void AllowDownload(Tab* tab,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
AllowDownloadCallback callback) = 0;
// A download of |url| has been requested with the specified details. If
// it returns true the download will be considered intercepted and WebLayer
// won't proceed with it. Note that there are many corner cases where the
// embedder downloading it won't work (e.g. POSTs, one-time URLs, requests
// that depend on cookies or auth state). This is called after AllowDownload.
virtual bool InterceptDownload(const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
int64_t content_length) = 0;
// A download has started. There will be 0..n calls to
// DownloadProgressChanged, then either a call to DownloadCompleted or
// DownloadFailed.
virtual void DownloadStarted(Download* download) {}
// The progress percentage of a download has changed.
virtual void DownloadProgressChanged(Download* download) {}
// A download has completed successfully.
virtual void DownloadCompleted(Download* download) {}
// A download has failed because the user cancelled it or because of a server
// or network error.
virtual void DownloadFailed(Download* download) {}
protected:
virtual ~DownloadDelegate() {}
};
} // namespace weblayer
#endif // WEBLAYER_PUBLIC_DOWNLOAD_DELEGATE_H_
| 911 |
716 | // Copyright (c) 2022 The Orbit 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 ORBIT_API_UTILS_API_ENABLE_INFO_H_
#define ORBIT_API_UTILS_API_ENABLE_INFO_H_
#include <stdint.h>
#include <type_traits>
namespace orbit_api {
// This structure is used on Windows when calling "orbit_api_set_enabled_from_struct" remotely
// using the "CreateRemoteThread" api, which takes in a single parameter for the thread function.
// This struct needs to be POD so that we can easily copy it in a remote process address space.
struct ApiEnableInfo {
// Address of orbit_api_get_function_table_address_win_vN function.
uint64_t orbit_api_function_address;
uint64_t api_version;
bool api_enabled;
};
static_assert(std::is_trivial<ApiEnableInfo>::value, "ApiEnableInfo must be a trivial type.");
} // namespace orbit_api
#endif // ORBIT_API_UTILS_API_ENABLE_INFO_H_
| 313 |
13,885 | <filename>third_party/benchmark/test/user_counters_thousands_test.cc
#undef NDEBUG
#include "benchmark/benchmark.h"
#include "output_test.h"
// ========================================================================= //
// ------------------------ Thousands Customisation ------------------------ //
// ========================================================================= //
void BM_Counters_Thousands(benchmark::State& state) {
for (auto _ : state) {
}
namespace bm = benchmark;
state.counters.insert({
{"t0_1000000DefaultBase",
bm::Counter(1000 * 1000, bm::Counter::kDefaults)},
{"t1_1000000Base1000", bm::Counter(1000 * 1000, bm::Counter::kDefaults,
benchmark::Counter::OneK::kIs1000)},
{"t2_1000000Base1024", bm::Counter(1000 * 1000, bm::Counter::kDefaults,
benchmark::Counter::OneK::kIs1024)},
{"t3_1048576Base1000", bm::Counter(1024 * 1024, bm::Counter::kDefaults,
benchmark::Counter::OneK::kIs1000)},
{"t4_1048576Base1024", bm::Counter(1024 * 1024, bm::Counter::kDefaults,
benchmark::Counter::OneK::kIs1024)},
});
}
BENCHMARK(BM_Counters_Thousands)->Repetitions(2);
ADD_CASES(
TC_ConsoleOut,
{
{"^BM_Counters_Thousands/repeats:2 %console_report "
"t0_1000000DefaultBase=1000k "
"t1_1000000Base1000=1000k t2_1000000Base1024=976.56[23]k "
"t3_1048576Base1000=1048.58k t4_1048576Base1024=1024k$"},
{"^BM_Counters_Thousands/repeats:2 %console_report "
"t0_1000000DefaultBase=1000k "
"t1_1000000Base1000=1000k t2_1000000Base1024=976.56[23]k "
"t3_1048576Base1000=1048.58k t4_1048576Base1024=1024k$"},
{"^BM_Counters_Thousands/repeats:2_mean %console_report "
"t0_1000000DefaultBase=1000k t1_1000000Base1000=1000k "
"t2_1000000Base1024=976.56[23]k t3_1048576Base1000=1048.58k "
"t4_1048576Base1024=1024k$"},
{"^BM_Counters_Thousands/repeats:2_median %console_report "
"t0_1000000DefaultBase=1000k t1_1000000Base1000=1000k "
"t2_1000000Base1024=976.56[23]k t3_1048576Base1000=1048.58k "
"t4_1048576Base1024=1024k$"},
{"^BM_Counters_Thousands/repeats:2_stddev %console_time_only_report [ "
"]*2 t0_1000000DefaultBase=0 t1_1000000Base1000=0 "
"t2_1000000Base1024=0 t3_1048576Base1000=0 t4_1048576Base1024=0$"},
});
ADD_CASES(TC_JSONOut,
{{"\"name\": \"BM_Counters_Thousands/repeats:2\",$"},
{"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next},
{"\"run_type\": \"iteration\",$", MR_Next},
{"\"iterations\": %int,$", MR_Next},
{"\"real_time\": %float,$", MR_Next},
{"\"cpu_time\": %float,$", MR_Next},
{"\"time_unit\": \"ns\",$", MR_Next},
{"\"t0_1000000DefaultBase\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t1_1000000Base1000\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t2_1000000Base1024\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t3_1048576Base1000\": 1\\.048576(0)*e\\+(0)*6,$", MR_Next},
{"\"t4_1048576Base1024\": 1\\.048576(0)*e\\+(0)*6$", MR_Next},
{"}", MR_Next}});
ADD_CASES(TC_JSONOut,
{{"\"name\": \"BM_Counters_Thousands/repeats:2\",$"},
{"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next},
{"\"run_type\": \"iteration\",$", MR_Next},
{"\"iterations\": %int,$", MR_Next},
{"\"real_time\": %float,$", MR_Next},
{"\"cpu_time\": %float,$", MR_Next},
{"\"time_unit\": \"ns\",$", MR_Next},
{"\"t0_1000000DefaultBase\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t1_1000000Base1000\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t2_1000000Base1024\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t3_1048576Base1000\": 1\\.048576(0)*e\\+(0)*6,$", MR_Next},
{"\"t4_1048576Base1024\": 1\\.048576(0)*e\\+(0)*6$", MR_Next},
{"}", MR_Next}});
ADD_CASES(TC_JSONOut,
{{"\"name\": \"BM_Counters_Thousands/repeats:2_mean\",$"},
{"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next},
{"\"run_type\": \"aggregate\",$", MR_Next},
{"\"aggregate_name\": \"mean\",$", MR_Next},
{"\"iterations\": 2,$", MR_Next},
{"\"real_time\": %float,$", MR_Next},
{"\"cpu_time\": %float,$", MR_Next},
{"\"time_unit\": \"ns\",$", MR_Next},
{"\"t0_1000000DefaultBase\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t1_1000000Base1000\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t2_1000000Base1024\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t3_1048576Base1000\": 1\\.048576(0)*e\\+(0)*6,$", MR_Next},
{"\"t4_1048576Base1024\": 1\\.048576(0)*e\\+(0)*6$", MR_Next},
{"}", MR_Next}});
ADD_CASES(TC_JSONOut,
{{"\"name\": \"BM_Counters_Thousands/repeats:2_median\",$"},
{"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next},
{"\"run_type\": \"aggregate\",$", MR_Next},
{"\"aggregate_name\": \"median\",$", MR_Next},
{"\"iterations\": 2,$", MR_Next},
{"\"real_time\": %float,$", MR_Next},
{"\"cpu_time\": %float,$", MR_Next},
{"\"time_unit\": \"ns\",$", MR_Next},
{"\"t0_1000000DefaultBase\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t1_1000000Base1000\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t2_1000000Base1024\": 1\\.(0)*e\\+(0)*6,$", MR_Next},
{"\"t3_1048576Base1000\": 1\\.048576(0)*e\\+(0)*6,$", MR_Next},
{"\"t4_1048576Base1024\": 1\\.048576(0)*e\\+(0)*6$", MR_Next},
{"}", MR_Next}});
ADD_CASES(TC_JSONOut,
{{"\"name\": \"BM_Counters_Thousands/repeats:2_stddev\",$"},
{"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next},
{"\"run_type\": \"aggregate\",$", MR_Next},
{"\"aggregate_name\": \"stddev\",$", MR_Next},
{"\"iterations\": 2,$", MR_Next},
{"\"real_time\": %float,$", MR_Next},
{"\"cpu_time\": %float,$", MR_Next},
{"\"time_unit\": \"ns\",$", MR_Next},
{"\"t0_1000000DefaultBase\": 0\\.(0)*e\\+(0)*,$", MR_Next},
{"\"t1_1000000Base1000\": 0\\.(0)*e\\+(0)*,$", MR_Next},
{"\"t2_1000000Base1024\": 0\\.(0)*e\\+(0)*,$", MR_Next},
{"\"t3_1048576Base1000\": 0\\.(0)*e\\+(0)*,$", MR_Next},
{"\"t4_1048576Base1024\": 0\\.(0)*e\\+(0)*$", MR_Next},
{"}", MR_Next}});
ADD_CASES(
TC_CSVOut,
{{"^\"BM_Counters_Thousands/"
"repeats:2\",%csv_report,1e\\+(0)*6,1e\\+(0)*6,1e\\+(0)*6,1\\.04858e\\+("
"0)*6,1\\.04858e\\+(0)*6$"},
{"^\"BM_Counters_Thousands/"
"repeats:2\",%csv_report,1e\\+(0)*6,1e\\+(0)*6,1e\\+(0)*6,1\\.04858e\\+("
"0)*6,1\\.04858e\\+(0)*6$"},
{"^\"BM_Counters_Thousands/"
"repeats:2_mean\",%csv_report,1e\\+(0)*6,1e\\+(0)*6,1e\\+(0)*6,1\\."
"04858e\\+(0)*6,1\\.04858e\\+(0)*6$"},
{"^\"BM_Counters_Thousands/"
"repeats:2_median\",%csv_report,1e\\+(0)*6,1e\\+(0)*6,1e\\+(0)*6,1\\."
"04858e\\+(0)*6,1\\.04858e\\+(0)*6$"},
{"^\"BM_Counters_Thousands/repeats:2_stddev\",%csv_report,0,0,0,0,0$"}});
// VS2013 does not allow this function to be passed as a lambda argument
// to CHECK_BENCHMARK_RESULTS()
void CheckThousands(Results const& e) {
if (e.name != "BM_Counters_Thousands/repeats:2")
return; // Do not check the aggregates!
// check that the values are within 0.01% of the expected values
CHECK_FLOAT_COUNTER_VALUE(e, "t0_1000000DefaultBase", EQ, 1000 * 1000,
0.0001);
CHECK_FLOAT_COUNTER_VALUE(e, "t1_1000000Base1000", EQ, 1000 * 1000, 0.0001);
CHECK_FLOAT_COUNTER_VALUE(e, "t2_1000000Base1024", EQ, 1000 * 1000, 0.0001);
CHECK_FLOAT_COUNTER_VALUE(e, "t3_1048576Base1000", EQ, 1024 * 1024, 0.0001);
CHECK_FLOAT_COUNTER_VALUE(e, "t4_1048576Base1024", EQ, 1024 * 1024, 0.0001);
}
CHECK_BENCHMARK_RESULTS("BM_Counters_Thousands", &CheckThousands);
// ========================================================================= //
// --------------------------- TEST CASES END ------------------------------ //
// ========================================================================= //
int main(int argc, char* argv[]) { RunOutputTests(argc, argv); }
| 4,181 |
56,632 | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2018, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
#ifndef OPENCV_DNN_VKCOM_HPP
#define OPENCV_DNN_VKCOM_HPP
#include <vector>
namespace cv { namespace dnn { namespace vkcom {
#ifdef HAVE_VULKAN
enum Format{
kFormatInvalid = -1,
kFormatFp16,
kFormatFp32,
kFormatFp64,
kFormatInt32,
kFormatNum
};
enum OpType {
kOpTypeConv,
kOpTypePool,
kOpTypeDWConv,
kOpTypeLRN,
kOpTypeConcat,
kOpTypeSoftmax,
kOpTypeReLU,
kOpTypePriorBox,
kOpTypePermute,
kOpTypeNum
};
enum PaddingMode { kPaddingModeSame, kPaddingModeValid, kPaddingModeCaffe, kPaddingModeNum };
enum FusedActivationType { kNone, kRelu, kRelu1, kRelu6, kActivationNum };
typedef std::vector<int> Shape;
bool isAvailable();
#endif // HAVE_VULKAN
}}} // namespace cv::dnn::vkcom
#include "tensor.hpp"
#include "buffer.hpp"
#include "op_base.hpp"
#include "op_concat.hpp"
#include "op_conv.hpp"
#include "op_lrn.hpp"
#include "op_softmax.hpp"
#include "op_relu.hpp"
#include "op_pool.hpp"
#include "op_prior_box.hpp"
#include "op_permute.hpp"
#endif // OPENCV_DNN_VKCOM_HPP
| 566 |
425 | <reponame>yeze322/botbuilder-dotnet
{"Sections":[{"Errors":[],"SectionType":"newEntitySection","Id":"newEntitySection_1","Body":"","Name":"1","Type":"ml","ListBody":[" - @ ml s1 usesFeature x1"],"Range":{"Start":{"Line":2,"Character":0},"End":{"Line":3,"Character":29}}},{"Errors":[],"SectionType":"newEntitySection","Id":"newEntitySection_x1","Body":"","Name":"x1","Type":"regex","ListBody":[],"Range":{"Start":{"Line":4,"Character":0},"End":{"Line":5,"Character":8}}}],"Content":"\n@ml 1 = \n - @ ml s1 usesFeature x1\n@regex x1\n \n","Errors":[]} | 192 |
678 | <reponame>bzxy/cydia
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iTunesStoreUI.framework/iTunesStoreUI
*/
@class SUTableDataSource, NSArray;
@protocol SUDownloadsChildViewController <NSObject>
@property(retain, nonatomic) NSArray *scriptButtons;
@property(retain, nonatomic) SUTableDataSource *dataSource;
// declared property setter: - (void)setScriptButtons:(id)buttons;
// declared property getter: - (id)scriptButtons;
// declared property setter: - (void)setDataSource:(id)source;
// declared property getter: - (id)dataSource;
- (id)visibleDownloadCellForDownload:(id)download;
- (void)reloadData;
- (void)reloadDownloadCellForDownload:(id)download;
@end
| 238 |
348 | <gh_stars>100-1000
{"nom":"Butot-Vénesville","circ":"10ème circonscription","dpt":"Seine-Maritime","inscrits":212,"abs":127,"votants":85,"blancs":7,"nuls":0,"exp":78,"res":[{"nuance":"REM","nom":"<NAME>","voix":40},{"nuance":"FN","nom":"Mme <NAME>","voix":38}]} | 106 |
353 | <gh_stars>100-1000
#ifndef THP_AUTOGRAD_H
#define THP_AUTOGRAD_H
PyObject * THPAutograd_initExtension(PyObject *_unused, PyObject *unused);
void THPAutograd_initFunctions();
namespace torch { namespace autograd {
PyMethodDef* python_functions();
}}
#include <torch/csrc/autograd/python_function.h>
#include <torch/csrc/autograd/python_variable.h>
#include <torch/csrc/autograd/python_engine.h>
#endif
| 180 |
2,151 | <reponame>zipated/src<filename>third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.cc
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/animation/svg_transform_list_interpolation_type.h"
#include <memory>
#include <utility>
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/animation/interpolable_value.h"
#include "third_party/blink/renderer/core/animation/non_interpolable_value.h"
#include "third_party/blink/renderer/core/animation/string_keyframe.h"
#include "third_party/blink/renderer/core/animation/svg_interpolation_environment.h"
#include "third_party/blink/renderer/core/svg/svg_transform.h"
#include "third_party/blink/renderer/core/svg/svg_transform_list.h"
namespace blink {
class SVGTransformNonInterpolableValue : public NonInterpolableValue {
public:
~SVGTransformNonInterpolableValue() override = default;
static scoped_refptr<SVGTransformNonInterpolableValue> Create(
Vector<SVGTransformType>& transform_types) {
return base::AdoptRef(
new SVGTransformNonInterpolableValue(transform_types));
}
const Vector<SVGTransformType>& TransformTypes() const {
return transform_types_;
}
DECLARE_NON_INTERPOLABLE_VALUE_TYPE();
private:
SVGTransformNonInterpolableValue(Vector<SVGTransformType>& transform_types) {
transform_types_.swap(transform_types);
}
Vector<SVGTransformType> transform_types_;
};
DEFINE_NON_INTERPOLABLE_VALUE_TYPE(SVGTransformNonInterpolableValue);
DEFINE_NON_INTERPOLABLE_VALUE_TYPE_CASTS(SVGTransformNonInterpolableValue);
namespace {
std::unique_ptr<InterpolableValue> TranslateToInterpolableValue(
SVGTransform* transform) {
FloatPoint translate = transform->Translate();
std::unique_ptr<InterpolableList> result = InterpolableList::Create(2);
result->Set(0, InterpolableNumber::Create(translate.X()));
result->Set(1, InterpolableNumber::Create(translate.Y()));
return std::move(result);
}
SVGTransform* TranslateFromInterpolableValue(const InterpolableValue& value) {
const InterpolableList& list = ToInterpolableList(value);
SVGTransform* transform = SVGTransform::Create(kSvgTransformTranslate);
transform->SetTranslate(ToInterpolableNumber(list.Get(0))->Value(),
ToInterpolableNumber(list.Get(1))->Value());
return transform;
}
std::unique_ptr<InterpolableValue> ScaleToInterpolableValue(
SVGTransform* transform) {
FloatSize scale = transform->Scale();
std::unique_ptr<InterpolableList> result = InterpolableList::Create(2);
result->Set(0, InterpolableNumber::Create(scale.Width()));
result->Set(1, InterpolableNumber::Create(scale.Height()));
return std::move(result);
}
SVGTransform* ScaleFromInterpolableValue(const InterpolableValue& value) {
const InterpolableList& list = ToInterpolableList(value);
SVGTransform* transform = SVGTransform::Create(kSvgTransformScale);
transform->SetScale(ToInterpolableNumber(list.Get(0))->Value(),
ToInterpolableNumber(list.Get(1))->Value());
return transform;
}
std::unique_ptr<InterpolableValue> RotateToInterpolableValue(
SVGTransform* transform) {
FloatPoint rotation_center = transform->RotationCenter();
std::unique_ptr<InterpolableList> result = InterpolableList::Create(3);
result->Set(0, InterpolableNumber::Create(transform->Angle()));
result->Set(1, InterpolableNumber::Create(rotation_center.X()));
result->Set(2, InterpolableNumber::Create(rotation_center.Y()));
return std::move(result);
}
SVGTransform* RotateFromInterpolableValue(const InterpolableValue& value) {
const InterpolableList& list = ToInterpolableList(value);
SVGTransform* transform = SVGTransform::Create(kSvgTransformRotate);
transform->SetRotate(ToInterpolableNumber(list.Get(0))->Value(),
ToInterpolableNumber(list.Get(1))->Value(),
ToInterpolableNumber(list.Get(2))->Value());
return transform;
}
std::unique_ptr<InterpolableValue> SkewXToInterpolableValue(
SVGTransform* transform) {
return InterpolableNumber::Create(transform->Angle());
}
SVGTransform* SkewXFromInterpolableValue(const InterpolableValue& value) {
SVGTransform* transform = SVGTransform::Create(kSvgTransformSkewx);
transform->SetSkewX(ToInterpolableNumber(value).Value());
return transform;
}
std::unique_ptr<InterpolableValue> SkewYToInterpolableValue(
SVGTransform* transform) {
return InterpolableNumber::Create(transform->Angle());
}
SVGTransform* SkewYFromInterpolableValue(const InterpolableValue& value) {
SVGTransform* transform = SVGTransform::Create(kSvgTransformSkewy);
transform->SetSkewY(ToInterpolableNumber(value).Value());
return transform;
}
std::unique_ptr<InterpolableValue> ToInterpolableValue(
SVGTransform* transform,
SVGTransformType transform_type) {
switch (transform_type) {
case kSvgTransformTranslate:
return TranslateToInterpolableValue(transform);
case kSvgTransformScale:
return ScaleToInterpolableValue(transform);
case kSvgTransformRotate:
return RotateToInterpolableValue(transform);
case kSvgTransformSkewx:
return SkewXToInterpolableValue(transform);
case kSvgTransformSkewy:
return SkewYToInterpolableValue(transform);
case kSvgTransformMatrix:
case kSvgTransformUnknown:
NOTREACHED();
}
NOTREACHED();
return nullptr;
}
SVGTransform* FromInterpolableValue(const InterpolableValue& value,
SVGTransformType transform_type) {
switch (transform_type) {
case kSvgTransformTranslate:
return TranslateFromInterpolableValue(value);
case kSvgTransformScale:
return ScaleFromInterpolableValue(value);
case kSvgTransformRotate:
return RotateFromInterpolableValue(value);
case kSvgTransformSkewx:
return SkewXFromInterpolableValue(value);
case kSvgTransformSkewy:
return SkewYFromInterpolableValue(value);
case kSvgTransformMatrix:
case kSvgTransformUnknown:
NOTREACHED();
}
NOTREACHED();
return nullptr;
}
const Vector<SVGTransformType>& GetTransformTypes(
const InterpolationValue& value) {
return ToSVGTransformNonInterpolableValue(*value.non_interpolable_value)
.TransformTypes();
}
class SVGTransformListChecker : public InterpolationType::ConversionChecker {
public:
static std::unique_ptr<SVGTransformListChecker> Create(
const InterpolationValue& underlying) {
return base::WrapUnique(new SVGTransformListChecker(underlying));
}
bool IsValid(const InterpolationEnvironment&,
const InterpolationValue& underlying) const final {
// TODO(suzyh): change maybeConvertSingle so we don't have to recalculate
// for changes to the interpolable values
if (!underlying && !underlying_)
return true;
if (!underlying || !underlying_)
return false;
return underlying_.interpolable_value->Equals(
*underlying.interpolable_value) &&
GetTransformTypes(underlying_) == GetTransformTypes(underlying);
}
private:
SVGTransformListChecker(const InterpolationValue& underlying)
: underlying_(underlying.Clone()) {}
const InterpolationValue underlying_;
};
} // namespace
InterpolationValue SVGTransformListInterpolationType::MaybeConvertNeutral(
const InterpolationValue&,
ConversionCheckers&) const {
NOTREACHED();
// This function is no longer called, because maybeConvertSingle has been
// overridden.
return nullptr;
}
InterpolationValue SVGTransformListInterpolationType::MaybeConvertSVGValue(
const SVGPropertyBase& svg_value) const {
if (svg_value.GetType() != kAnimatedTransformList)
return nullptr;
const SVGTransformList& svg_list = ToSVGTransformList(svg_value);
std::unique_ptr<InterpolableList> result =
InterpolableList::Create(svg_list.length());
Vector<SVGTransformType> transform_types;
for (size_t i = 0; i < svg_list.length(); i++) {
const SVGTransform* transform = svg_list.at(i);
SVGTransformType transform_type(transform->TransformType());
if (transform_type == kSvgTransformMatrix) {
// TODO(ericwilligers): Support matrix interpolation.
return nullptr;
}
result->Set(i, ToInterpolableValue(transform->Clone(), transform_type));
transform_types.push_back(transform_type);
}
return InterpolationValue(
std::move(result),
SVGTransformNonInterpolableValue::Create(transform_types));
}
InterpolationValue SVGTransformListInterpolationType::MaybeConvertSingle(
const PropertySpecificKeyframe& keyframe,
const InterpolationEnvironment& environment,
const InterpolationValue& underlying,
ConversionCheckers& conversion_checkers) const {
Vector<SVGTransformType> types;
Vector<std::unique_ptr<InterpolableValue>> interpolable_parts;
if (keyframe.Composite() == EffectModel::kCompositeAdd) {
if (underlying) {
types.AppendVector(GetTransformTypes(underlying));
interpolable_parts.push_back(underlying.interpolable_value->Clone());
}
conversion_checkers.push_back(SVGTransformListChecker::Create(underlying));
} else {
DCHECK(!keyframe.IsNeutral());
}
if (!keyframe.IsNeutral()) {
SVGPropertyBase* svg_value =
ToSVGInterpolationEnvironment(environment)
.SvgBaseValue()
.CloneForAnimation(ToSVGPropertySpecificKeyframe(keyframe).Value());
InterpolationValue value = MaybeConvertSVGValue(*svg_value);
if (!value)
return nullptr;
types.AppendVector(GetTransformTypes(value));
interpolable_parts.push_back(std::move(value.interpolable_value));
}
std::unique_ptr<InterpolableList> interpolable_list =
InterpolableList::Create(types.size());
size_t interpolable_list_index = 0;
for (auto& part : interpolable_parts) {
InterpolableList& list = ToInterpolableList(*part);
for (size_t i = 0; i < list.length(); ++i) {
interpolable_list->Set(interpolable_list_index,
std::move(list.GetMutable(i)));
++interpolable_list_index;
}
}
return InterpolationValue(std::move(interpolable_list),
SVGTransformNonInterpolableValue::Create(types));
}
SVGPropertyBase* SVGTransformListInterpolationType::AppliedSVGValue(
const InterpolableValue& interpolable_value,
const NonInterpolableValue* non_interpolable_value) const {
SVGTransformList* result = SVGTransformList::Create();
const InterpolableList& list = ToInterpolableList(interpolable_value);
const Vector<SVGTransformType>& transform_types =
ToSVGTransformNonInterpolableValue(non_interpolable_value)
->TransformTypes();
for (size_t i = 0; i < list.length(); ++i)
result->Append(FromInterpolableValue(*list.Get(i), transform_types.at(i)));
return result;
}
PairwiseInterpolationValue SVGTransformListInterpolationType::MaybeMergeSingles(
InterpolationValue&& start,
InterpolationValue&& end) const {
if (GetTransformTypes(start) != GetTransformTypes(end))
return nullptr;
return PairwiseInterpolationValue(std::move(start.interpolable_value),
std::move(end.interpolable_value),
std::move(end.non_interpolable_value));
}
void SVGTransformListInterpolationType::Composite(
UnderlyingValueOwner& underlying_value_owner,
double underlying_fraction,
const InterpolationValue& value,
double interpolation_fraction) const {
underlying_value_owner.Set(*this, value);
}
} // namespace blink
| 4,100 |
18,396 | /*
* SRT - Secure, Reliable, Transport
* Copyright (c) 2018 Haivision Systems Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
/*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
nor the names of its contributors may be used to
endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#ifndef INC__HANDSHAKE_H
#define INC__HANDSHAKE_H
#include "crypto.h"
#include "utilities.h"
typedef Bits<31, 16> HS_CMDSPEC_CMD;
typedef Bits<15, 0> HS_CMDSPEC_SIZE;
// NOTE: Some of these flags represent CAPABILITIES, that is,
// as long as these flags are defined, they must be always set
// (unless they are deprecated).
enum SrtOptions
{
SRT_OPT_TSBPDSND = BIT(0), /* Timestamp-based Packet delivery real-time data sender */
SRT_OPT_TSBPDRCV = BIT(1), /* Timestamp-based Packet delivery real-time data receiver */
SRT_OPT_HAICRYPT = BIT(2), /* CAPABILITY: HaiCrypt AES-128/192/256-CTR */
SRT_OPT_TLPKTDROP = BIT(3), /* Drop real-time data packets too late to be processed in time */
SRT_OPT_NAKREPORT = BIT(4), /* Periodic NAK report */
SRT_OPT_REXMITFLG = BIT(5), // CAPABILITY: One bit in payload packet msgno is "retransmitted" flag
// (this flag can be reused for something else, when pre-1.2.0 versions are all abandoned)
SRT_OPT_STREAM = BIT(6), // STREAM MODE (not MESSAGE mode)
SRT_OPT_FILTERCAP = BIT(7), // CAPABILITY: Packet filter supported
};
inline int SrtVersionCapabilities()
{
// NOTE: SRT_OPT_REXMITFLG is not included here because
// SRT is prepared to handle also peers that don't have this
// capability, so a listener responding to a peer that doesn't
// support it should NOT set this flag.
//
// This state will remain until this backward compatibility is
// decided to be broken, in which case this flag will be always
// set, and clients that do not support this capability will be
// rejected.
return SRT_OPT_HAICRYPT | SRT_OPT_FILTERCAP;
}
std::string SrtFlagString(int32_t flags);
const int SRT_CMD_REJECT = 0, // REJECT is only a symbol for return type
SRT_CMD_HSREQ = 1,
SRT_CMD_HSRSP = 2,
SRT_CMD_KMREQ = 3,
SRT_CMD_KMRSP = 4,
SRT_CMD_SID = 5,
SRT_CMD_CONGESTION = 6,
SRT_CMD_FILTER = 7,
SRT_CMD_NONE = -1; // for cases when {no pong for ping is required} | {no extension block found}
enum SrtDataStruct
{
SRT_HS_VERSION = 0,
SRT_HS_FLAGS,
SRT_HS_LATENCY,
// Keep it always last
SRT_HS__SIZE
};
// For HSv5 the lo and hi part is used for particular side's latency
typedef Bits<31, 16> SRT_HS_LATENCY_RCV;
typedef Bits<15, 0> SRT_HS_LATENCY_SND;
// For HSv4 only the lower part is used.
typedef Bits<15, 0> SRT_HS_LATENCY_LEG;
// XXX These structures are currently unused. The code can be changed
// so that these are used instead of manual tailoring of the messages.
struct SrtHandshakeExtension
{
protected:
uint32_t m_SrtCommand; // Used only in extension
public:
SrtHandshakeExtension(int cmd)
{
m_SrtCommand = cmd;
}
void setCommand(int cmd)
{
m_SrtCommand = cmd;
}
};
struct SrtHSRequest: public SrtHandshakeExtension
{
typedef Bits<31, 16> SRT_HSTYPE_ENCFLAGS;
typedef Bits<15, 0> SRT_HSTYPE_HSFLAGS;
// For translating PBKEYLEN into crypto flags
// This value is 16, 24, 32; after cutting off
// the leftmost 3 bits, it is 2, 3, 4.
typedef Bits<5, 3> SRT_PBKEYLEN_BITS;
// This value fits ins SRT_HSTYPE_HSFLAGS.
// .... HAIVISIOn
static const int32_t SRT_MAGIC_CODE = 0x4A17;
static int32_t wrapFlags(bool withmagic, int crypto_keylen)
{
int32_t base = withmagic ? SRT_MAGIC_CODE : 0;
return base | SRT_HSTYPE_ENCFLAGS::wrap( SRT_PBKEYLEN_BITS::unwrap(crypto_keylen) );
}
private:
friend class CHandShake;
static const size_t SRT_HS_SIZE = 4*sizeof(uint32_t); // 4 existing fields
static const size_t SRT_EXT_HS_SIZE = 2*sizeof(uint32_t) + SRT_HS_SIZE; // SRT magic and SRT HS type, used only in UDT HS ext
typedef Bits<15, 0> SRT_TSBPD_DELAY;
uint32_t m_iSrtVersion;
uint32_t m_iSrtFlags;
uint32_t m_iSrtTsbpd;
uint32_t m_iSrtReserved;
public:
SrtHSRequest(): SrtHandshakeExtension(SRT_CMD_HSREQ), m_iSrtVersion(), m_iSrtFlags(), m_iSrtTsbpd(), m_iSrtReserved() {}
void setVersion(uint32_t v) { m_iSrtVersion = v; }
uint32_t version() const { return m_iSrtVersion; }
void setFlag(SrtOptions opt) { m_iSrtFlags |= uint32_t(opt); }
void clearFlag(SrtOptions opt) { m_iSrtFlags &= ~opt; }
uint32_t flags() const { return m_iSrtFlags; }
void setTsbPdDelay(uint16_t delay) { m_iSrtTsbpd |= SRT_TSBPD_DELAY::wrap(delay); }
// Unknown what the 1-16 bits have to be used for.
uint16_t tsbPdDelay() const
{
return SRT_TSBPD_DELAY::unwrap(m_iSrtTsbpd);
}
size_t size() const { return SRT_EXT_HS_SIZE; }
bool serialize(char* p, size_t size) const;
bool deserialize(const char* mem, size_t size);
};
struct SrtKMRequest: public SrtHandshakeExtension
{
uint32_t m_iKmState;
char m_aKey[1]; // dynamic size
};
////////////////////////////////////////////////////////////////////////////////
enum UDTRequestType
{
URQ_INDUCTION_TYPES = 0, // XXX used to check in one place. Consdr rm.
URQ_INDUCTION = 1, // First part for client-server connection
URQ_WAVEAHAND = 0, // First part for rendezvous connection
URQ_CONCLUSION = -1, // Second part of handshake negotiation
URQ_AGREEMENT = -2, // Extra (last) step for rendezvous only
URQ_DONE = -3, // Special value used only in state-switching, to state that nothing should be sent in response
// Note: the client-server connection uses:
// --> INDUCTION (empty)
// <-- INDUCTION (cookie)
// --> CONCLUSION (cookie)
// <-- CONCLUSION (ok)
// The rendezvous HSv4 (legacy):
// --> WAVEAHAND (effective only if peer is also connecting)
// <-- CONCLUSION (empty) (consider yourself connected upon reception)
// --> AGREEMENT (sent as a response for conclusion, requires no response)
// The rendezvous HSv5 (using SRT extensions):
// --> WAVEAHAND (with cookie)
// --- (selecting INITIATOR/RESPONDER by cookie contest - comparing one another's cookie)
// <-- CONCLUSION (without extensions, if RESPONDER, with extensions, if INITIATOR)
// --> CONCLUSION (with response extensions, if RESPONDER)
// <-- AGREEMENT (sent exclusively by INITIATOR upon reception of CONCLUSIOn with response extensions)
// Errors reported by the peer, also used as useless error codes
// in handshake processing functions.
URQ_FAILURE_TYPES = 1000
// NOTE: codes above 1000 are reserved for failure codes for
// rejection reason, as per `SRT_REJECT_REASON` enum. DO NOT
// add any new values here.
};
inline UDTRequestType URQFailure(SRT_REJECT_REASON reason)
{
return UDTRequestType(URQ_FAILURE_TYPES + int(reason));
}
inline SRT_REJECT_REASON RejectReasonForURQ(UDTRequestType req)
{
if (req < URQ_FAILURE_TYPES || req - URQ_FAILURE_TYPES >= SRT_REJ__SIZE)
return SRT_REJ_UNKNOWN;
return SRT_REJECT_REASON(req - URQ_FAILURE_TYPES);
}
// DEPRECATED values. Use URQFailure(SRT_REJECT_REASON).
const UDTRequestType URQ_ERROR_REJECT SRT_ATR_DEPRECATED = (UDTRequestType)1002; // == 1000 + SRT_REJ_PEER
const UDTRequestType URQ_ERROR_INVALID SRT_ATR_DEPRECATED = (UDTRequestType)1004; // == 1000 + SRT_REJ_ROGUE
// XXX Change all uses of that field to UDTRequestType when possible
#if ENABLE_LOGGING
std::string RequestTypeStr(UDTRequestType);
#else
inline std::string RequestTypeStr(UDTRequestType) { return ""; }
#endif
class CHandShake
{
public:
CHandShake();
int store_to(char* buf, ref_t<size_t> size);
int load_from(const char* buf, size_t size);
public:
// This is the size of SERIALIZED handshake.
// Might be defined as simply sizeof(CHandShake), but the
// enum values would have to be forced as int32_t, which is only
// available in C++11. Theoretically they are all 32-bit, but
// such a statement is not reliable and not portable.
static const size_t m_iContentSize = 48; // Size of hand shake data
// Extension flags
static const int32_t HS_EXT_HSREQ = BIT(0);
static const int32_t HS_EXT_KMREQ = BIT(1);
static const int32_t HS_EXT_CONFIG = BIT(2);
static std::string ExtensionFlagStr(int32_t fl);
// Applicable only when m_iVersion == HS_VERSION_SRT1
int32_t flags() { return m_iType; }
public:
int32_t m_iVersion; // UDT version (HS_VERSION_* symbols)
int32_t m_iType; // UDT4: socket type (only UDT_DGRAM is valid); SRT1: extension flags
int32_t m_iISN; // random initial sequence number
int32_t m_iMSS; // maximum segment size
int32_t m_iFlightFlagSize; // flow control window size
UDTRequestType m_iReqType; // handshake stage
int32_t m_iID; // socket ID
int32_t m_iCookie; // cookie
uint32_t m_piPeerIP[4]; // The IP address that the peer's UDP port is bound to
bool m_extension;
std::string show();
// The rendezvous state machine used in HSv5 only (in HSv4 everything is happening the old way).
//
// The WAVING state is the very initial state of the rendezvous connection and restored after the
// connection is closed.
// The ATTENTION and FINE are two alternative states that are transited to from WAVING. The possible
// situations are:
// - "serial arrangement": one party transits to ATTENTION and the other party transits to FINE
// - "parallel arrangement" both parties transit to ATTENTION
//
// Parallel arrangement is a "virtually impossible" case, in which both parties must send the first
// URQ_WAVEAHAND message in a perfect time synchronization, when they are started at exactly the same
// time, on machines with exactly the same performance and all things preceding the message sending
// have taken perfectly identical amount of time. This isn't anyhow possible otherwise because if
// the clients have started at different times, the one who started first sends a message and the
// system of the receiver buffers this message even before the client binds the port for enough long
// time so that it outlasts also the possible second, repeated waveahand.
enum RendezvousState
{
RDV_INVALID, //< This socket wasn't prepared for rendezvous process. Reject any events.
RDV_WAVING, //< Initial state for rendezvous. No contact seen from the peer.
RDV_ATTENTION, //< When received URQ_WAVEAHAND. [WAVING]:URQ_WAVEAHAND --> [ATTENTION].
RDV_FINE, //< When received URQ_CONCLUSION. [WAVING]:URQ_CONCLUSION --> [FINE].
RDV_INITIATED, //< When received URQ_CONCLUSION+HSREQ extension in ATTENTION state.
RDV_CONNECTED //< Final connected state. [ATTENTION]:URQ_CONCLUSION --> [CONNECTED] <-- [FINE]:URQ_AGREEMENT.
};
#if ENABLE_LOGGING
static std::string RdvStateStr(RendezvousState s);
#else
static std::string RdvStateStr(RendezvousState) { return ""; }
#endif
};
#endif
| 4,596 |
312 | package org.reveno.atp.utils;
import com.google.common.io.Files;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Date;
public class VersionedFileUtilsTest {
@Test
public void test() throws IOException {
File temp = Files.createTempDir();
String fileName = VersionedFileUtils.nextVersionFile(temp, "tx");
Assert.assertTrue(fileName.startsWith("tx-" + VersionedFileUtils.format().format(new Date()) + "-00000000000000000001"));
new File(temp, fileName).createNewFile();
String nextFile = VersionedFileUtils.nextVersionFile(temp, "tx");
Assert.assertNotEquals(nextFile, fileName);
Assert.assertTrue(nextFile.compareTo(fileName) == 1);
temp.delete();
}
}
| 276 |
512 | {
"name": "etcd",
"description": "Distributed reliable key-value store for the most critical data of a distributed system",
"version": "3.5.0",
"pre-version": "3.5.0",
"homepage": "https://etcd.io/",
"bug": "https://github.com/etcd-io/etcd/issues",
"github": "etcd-io/etcd",
"releases": "https://github.com/etcd-io/etcd/releases",
"url": "https://github.com/etcd-io/etcd/releases/download/v${VERSION}/etcd-v${VERSION}-windows-amd64.zip",
"url-mirror": "https://mirrors.huaweicloud.com/etcd/v${VERSION}/etcd-v${VERSION}-windows-amd64.zip",
"command": "etcd",
"scripts": {
"install": [
"_cleanup etcd",
"_unzip $filename $unzipDesc",
"Copy-item -r -force etcd\\etcd-v${VERSION}-windows-amd64\\etcd.exe C:\\bin\\",
"Copy-item -r -force etcd\\etcd-v${VERSION}-windows-amd64\\etcdctl.exe C:\\bin\\",
"_cleanup etcd"
],
"uninstall": "_cleanup C:\\bin\\etcd.exe C:\\bin\\etcdctl.exe",
"test": "printInfo $(etcd --version)[0] install success",
"version": "(etcd --version).split(' ')[2]",
"hash": [
"invoke-webrequest https://mirrors.huaweicloud.com/etcd/v${VERSION}/SHA256SUMS -outFile Temp:/etcd-sha256",
"$hash=(get-content Temp:/etcd-sha256 | select-string $filename).Line.split(' ')[0]",
"if($hash -and ((Get-SHA256 $filename) -ne $hash)){printError \"$filename sha256 check failed \"}"
]
},
"path": [
"C:\\bin"
],
"platform": [
{
"os": "windows",
"architecture": "amd64"
}
]
}
| 652 |
21,382 | from abc import ABCMeta, abstractmethod
from gym.spaces import Discrete
import numpy as np
from pathlib import Path
import unittest
from ray.rllib.utils.exploration.exploration import Exploration
from ray.rllib.utils.framework import try_import_tf, try_import_torch
from ray.rllib.utils.from_config import from_config
from ray.rllib.utils.test_utils import check, framework_iterator
tf1, tf, tfv = try_import_tf()
torch, _ = try_import_torch()
class DummyComponent:
"""A simple class that can be used for testing framework-agnostic logic.
Implements a simple `add()` method for adding a value to
`self.prop_b`.
"""
def __init__(self,
prop_a,
prop_b=0.5,
prop_c=None,
framework="tf",
**kwargs):
self.framework = framework
self.prop_a = prop_a
self.prop_b = prop_b
self.prop_c = prop_c or "default"
self.prop_d = kwargs.pop("prop_d", 4)
self.kwargs = kwargs
def add(self, value):
if self.framework == "tf":
return self._add_tf(value)
return self.prop_b + value
def _add_tf(self, value):
return tf.add(self.prop_b, value)
class NonAbstractChildOfDummyComponent(DummyComponent):
pass
class AbstractDummyComponent(DummyComponent, metaclass=ABCMeta):
"""Used for testing `from_config()`.
"""
@abstractmethod
def some_abstract_method(self):
raise NotImplementedError
class TestFrameWorkAgnosticComponents(unittest.TestCase):
"""
Tests the Component base class to implement framework-agnostic functional
units.
"""
def test_dummy_components(self):
# Bazel makes it hard to find files specified in `args`
# (and `data`).
# Use the true absolute path.
script_dir = Path(__file__).parent
abs_path = script_dir.absolute()
for fw, sess in framework_iterator(session=True):
fw_ = fw if fw != "tfe" else "tf"
# Try to create from an abstract class w/o default constructor.
# Expect None.
test = from_config({
"type": AbstractDummyComponent,
"framework": fw_
})
check(test, None)
# Create a Component via python API (config dict).
component = from_config(
dict(
type=DummyComponent,
prop_a=1.0,
prop_d="non_default",
framework=fw_))
check(component.prop_d, "non_default")
# Create a tf Component from json file.
config_file = str(abs_path.joinpath("dummy_config.json"))
component = from_config(config_file, framework=fw_)
check(component.prop_c, "default")
check(component.prop_d, 4) # default
value = component.add(3.3)
if sess:
value = sess.run(value)
check(value, 5.3) # prop_b == 2.0
# Create a torch Component from yaml file.
config_file = str(abs_path.joinpath("dummy_config.yml"))
component = from_config(config_file, framework=fw_)
check(component.prop_a, "something else")
check(component.prop_d, 3)
value = component.add(1.2)
if sess:
value = sess.run(value)
check(value, np.array([2.2])) # prop_b == 1.0
# Create tf Component from json-string (e.g. on command line).
component = from_config(
'{"type": "ray.rllib.utils.tests.'
'test_framework_agnostic_components.DummyComponent", '
'"prop_a": "A", "prop_b": -1.0, "prop_c": "non-default", '
'"framework": "' + fw_ + '"}')
check(component.prop_a, "A")
check(component.prop_d, 4) # default
value = component.add(-1.1)
if sess:
value = sess.run(value)
check(value, -2.1) # prop_b == -1.0
# Test recognizing default module path.
component = from_config(
DummyComponent, '{"type": "NonAbstractChildOfDummyComponent", '
'"prop_a": "A", "prop_b": -1.0, "prop_c": "non-default",'
'"framework": "' + fw_ + '"}')
check(component.prop_a, "A")
check(component.prop_d, 4) # default
value = component.add(-1.1)
if sess:
value = sess.run(value)
check(value, -2.1) # prop_b == -1.0
# Test recognizing default package path.
scope = None
if sess:
scope = tf1.variable_scope("exploration_object")
scope.__enter__()
component = from_config(
Exploration, {
"type": "EpsilonGreedy",
"action_space": Discrete(2),
"framework": fw_,
"num_workers": 0,
"worker_index": 0,
"policy_config": {},
"model": None
})
if scope:
scope.__exit__(None, None, None)
check(component.epsilon_schedule.outside_value, 0.05) # default
# Create torch Component from yaml-string.
component = from_config(
"type: ray.rllib.utils.tests."
"test_framework_agnostic_components.DummyComponent\n"
"prop_a: B\nprop_b: -1.5\nprop_c: non-default\nframework: "
"{}".format(fw_))
check(component.prop_a, "B")
check(component.prop_d, 4) # default
value = component.add(-5.1)
if sess:
value = sess.run(value)
check(value, np.array([-6.6])) # prop_b == -1.5
def test_unregistered_envs(self):
"""Tests, whether an Env can be specified simply by its absolute class.
"""
env_cls = "ray.rllib.examples.env.stateless_cartpole.StatelessCartPole"
env = from_config(env_cls, {"config": 42.0})
state = env.reset()
self.assertTrue(state.shape == (2, ))
if __name__ == "__main__":
import pytest
import sys
sys.exit(pytest.main(["-v", __file__]))
| 3,164 |
739 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
import pygtk
pygtk.require('2.0')
import sys, os, errno
import gtk
import pango
RESPONSE_FORWARD = 0
RESPONSE_BACKWARD = 1
book_closed_xpm = [
"16 16 6 1",
" c None s None",
". c black",
"X c red",
"o c yellow",
"O c #808080",
"# c white",
" ",
" .. ",
" ..XX. ",
" ..XXXXX. ",
" ..XXXXXXXX. ",
".ooXXXXXXXXX. ",
"..ooXXXXXXXXX. ",
".X.ooXXXXXXXXX. ",
".XX.ooXXXXXX.. ",
" .XX.ooXXX..#O ",
" .XX.oo..##OO. ",
" .XX..##OO.. ",
" .X.#OO.. ",
" ..O.. ",
" .. ",
" "]
def hsv_to_rgb(h, s, v):
if s == 0.0:
return (v, v, v)
else:
hue = h * 6.0
saturation = s
value = v
if hue >= 6.0:
hue = 0.0
f = hue - int(hue)
p = value * (1.0 - saturation)
q = value * (1.0 - saturation * f)
t = value * (1.0 - saturation * (1.0 - f))
ihue = int(hue)
if ihue == 0:
return(value, t, p)
elif ihue == 1:
return(q, value, p)
elif ihue == 2:
return(p, value, t)
elif ihue == 3:
return(p, q, value)
elif ihue == 4:
return(t, p, value)
elif ihue == 5:
return(value, p, q)
def hue_to_color(hue):
if hue > 1.0:
raise ValueError
h, s, v = hsv_to_rgb (hue, 1.0, 1.0)
return (h*65535, s*65535, v*65535)
class FileSel(gtk.FileSelection):
def __init__(self):
gtk.FileSelection.__init__(self)
self.result = False
def ok_cb(self, button):
self.hide()
if self.ok_func(self.get_filename()):
self.destroy()
self.result = True
else:
self.show()
def run(self, parent, title, start_file, func):
if start_file:
self.set_filename(start_file)
self.ok_func = func
self.ok_button.connect("clicked", self.ok_cb)
self.cancel_button.connect("clicked", lambda x: self.destroy())
self.connect("destroy", lambda x: gtk.main_quit())
self.set_modal(True)
self.show()
gtk.main()
return self.result
class Buffer(gtk.TextBuffer):
N_COLORS = 16
PANGO_SCALE = 1024
def __init__(self):
gtk.TextBuffer.__init__(self)
tt = self.get_tag_table()
self.refcount = 0
self.filename = None
self.untitled_serial = -1
self.color_tags = []
self.color_cycle_timeout_id = 0
self.start_hue = 0.0
for i in range(Buffer.N_COLORS):
tag = self.create_tag()
self.color_tags.append(tag)
#self.invisible_tag = self.create_tag(None, invisible=True)
self.not_editable_tag = self.create_tag(editable=False,
foreground="purple")
self.found_text_tag = self.create_tag(foreground="red")
tabs = pango.TabArray(4, True)
tabs.set_tab(0, pango.TAB_LEFT, 10)
tabs.set_tab(1, pango.TAB_LEFT, 30)
tabs.set_tab(2, pango.TAB_LEFT, 60)
tabs.set_tab(3, pango.TAB_LEFT, 120)
self.custom_tabs_tag = self.create_tag(tabs=tabs, foreground="green")
TestText.buffers.push(self)
def pretty_name(self):
if self.filename:
return os.path.basename(self.filename)
else:
if self.untitled_serial == -1:
self.untitled_serial = TestText.untitled_serial
TestText.untitled_serial += 1
if self.untitled_serial == 1:
return "Untitled"
else:
return "Untitled #%d" % self.untitled_serial
def filename_set(self):
for view in TestText.views:
if view.text_view.get_buffer() == self:
view.set_view_title()
def search(self, str, view, forward):
# remove tag from whole buffer
start, end = self.get_bounds()
self.remove_tag(self.found_text_tag, start, end)
iter = self.get_iter_at_mark(self.get_insert())
i = 0
if str:
if forward:
while 1:
res = iter.forward_search(str, gtk.TEXT_SEARCH_TEXT_ONLY)
if not res:
break
match_start, match_end = res
i += 1
self.apply_tag(self.found_text_tag, match_start, match_end)
iter = match_end
else:
while 1:
res = iter.backward_search(str, gtk.TEXT_SEARCH_TEXT_ONLY)
if not res:
break
match_start, match_end = res
i += 1
self.apply_tag(self.found_text_tag, match_start, match_end)
iter = match_start
dialog = gtk.MessageDialog(view,
gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_INFO,
gtk.BUTTONS_OK,
"%d strings found and marked in red" % i)
dialog.connect("response", lambda x,y: dialog.destroy())
dialog.show()
def search_forward(self, str, view):
self.search(str, view, True)
def search_backward(self, str, view):
self.search(str, view, False)
def ref(self):
self.refcount += 1
def unref(self):
self.refcount -= 1
if self.refcount == 0:
self.set_colors(False)
TestText.buffers.remove(self)
del self
def color_cycle_timeout(self):
self.cycle_colors()
return True
def set_colors(self, enabled):
hue = 0.0
if (enabled and self.color_cycle_timeout_id == 0):
self.color_cycle_timeout_id = gtk.timeout_add(
200, self.color_cycle_timeout)
elif (not enabled and self.color_cycle_timeout_id != 0):
gtk.timeout_remove(self.color_cycle_timeout_id)
self.color_cycle_timeout_id = 0
for tag in self.color_tags:
if enabled:
color = apply(TestText.colormap.alloc_color,
hue_to_color(hue))
tag.set_property("foreground_gdk", color)
else:
tag.set_property("foreground_set", False)
hue += 1.0 / Buffer.N_COLORS
def cycle_colors(self):
hue = self.start_hue
for tag in self.color_tags:
color = apply(TestText.colormap.alloc_color,
hue_to_color (hue))
tag.set_property("foreground_gdk", color)
hue += 1.0 / Buffer.N_COLORS
if hue > 1.0:
hue = 0.0
self.start_hue += 1.0 / Buffer.N_COLORS
if self.start_hue > 1.0:
self.start_hue = 0.0
def tag_event_handler(self, tag, widget, event, iter):
char_index = iter.get_offset()
tag_name = tag.get_property("name")
if event.type == gtk.gdk.MOTION_NOTIFY:
print "Motion event at char %d tag `%s'\n" % (char_index, tag_name)
elif event.type == gtk.gdk.BUTTON_PRESS:
print "Button press at char %d tag `%s'\n" % (char_index, tag_name)
elif event.type == gtk.gdk._2BUTTON_PRESS:
print "Double click at char %d tag `%s'\n" % (char_index, tag_name)
elif event.type == gtk.gdk._3BUTTON_PRESS:
print "Triple click at char %d tag `%s'\n" % (char_index, tag_name)
elif event.type == gtk.gdk.BUTTON_RELEASE:
print "Button release at char %d tag `%s'\n" % (char_index, tag_name)
elif (event.type == gtk.gdk.KEY_PRESS or
event.type == gtk.gdk.KEY_RELEASE):
print "Key event at char %d tag `%s'\n" % (char_index, tag_name)
return False
def init_tags(self):
colormap = TestText.colormap
color = colormap.alloc_color(0, 0, 0xffff)
tag = self.create_tag("fg_blue",
foreground_gdk=color,
background='yellow',
size_points=24.0)
tag.connect("event", self.tag_event_handler)
color = colormap.alloc_color(0xffff, 0, 0)
tag = self.create_tag("fg_red",
rise= -4*Buffer.PANGO_SCALE,
foreground_gdk=color)
tag.connect("event", self.tag_event_handler)
color = colormap.alloc_color(0, 0xffff, 0)
tag = self.create_tag("bg_green",
background_gdk=color,
size_points=10.0)
tag.connect("event", self.tag_event_handler)
tag = self.create_tag("strikethrough",
strikethrough=True)
tag.connect("event", self.tag_event_handler)
tag = self.create_tag("underline",
underline=pango.UNDERLINE_SINGLE)
tag.connect("event", self.tag_event_handler)
tag = self.create_tag("centered",
justification=gtk.JUSTIFY_CENTER)
tag = self.create_tag("rtl_quote",
wrap_mode=gtk.WRAP_WORD,
direction=gtk.TEXT_DIR_RTL,
indent=30,
left_margin=20,
right_margin=20)
tag = self.create_tag("negative_indent",
indent=-25)
def fill_example_buffer(self):
tagtable = self.get_tag_table()
if not tagtable.lookup("fg_blue"):
self.init_tags()
iter = self.get_iter_at_offset(0)
anchor = self.create_child_anchor(iter)
self.set_data("anchor", anchor)
pixbuf = gtk.gdk.pixbuf_new_from_xpm_data(book_closed_xpm)
#pixbuf = gtk.gdk.pixbuf_new_from_file('book_closed.xpm')
for i in range(100):
iter = self.get_iter_at_offset(0)
self.insert_pixbuf(iter, pixbuf)
str = "%d Hello World! blah blah blah blah blah blah blah blah blah blah blah blah\nwoo woo woo woo woo woo woo woo woo woo woo woo woo woo woo\n" % i
self.insert(iter, str)
iter = self.get_iter_at_line_offset(0, 5)
self.insert(iter,
"(Hello World!)\nfoo foo Hello this is some text we are using to text word wrap. It has punctuation! gee; blah - hmm, great.\nnew line with a significant quantity of text on it. This line really does contain some text. More text! More text! More text!\n"
"German (Deutsch Süd) Grüß Gott Greek (Ελληνικά) Γειά σας Hebrew(שלום) Hebrew punctuation(\xd6\xbfש\xd6\xbb\xd6\xbc\xd6\xbb\xd6\xbfל\xd6\xbcו\xd6\xbc\xd6\xbb\xd6\xbb\xd6\xbfם\xd6\xbc\xd6\xbb\xd6\xbf) Japanese (日本語) Thai (สวัสดีครับ) Thai wrong spelling (คำต่อไปนื่สะกดผิด พัั้ัั่งโกะ)\n")
temp_mark = self.create_mark("tmp_mark", iter, True);
iter = self.get_iter_at_line_offset(0, 6)
iter2 = self.get_iter_at_line_offset(0, 13)
self.apply_tag_by_name("fg_blue", iter, iter2)
iter = self.get_iter_at_line_offset(1, 10)
iter2 = self.get_iter_at_line_offset(1, 16)
self.apply_tag_by_name("underline", iter, iter2)
iter = self.get_iter_at_line_offset(1, 14)
iter2 = self.get_iter_at_line_offset(1, 24)
self.apply_tag_by_name("strikethrough", iter, iter2)
iter = self.get_iter_at_line_offset(0, 9)
iter2 = self.get_iter_at_line_offset(0, 16)
self.apply_tag_by_name("bg_green", iter, iter2)
iter = self.get_iter_at_line_offset(4, 2)
iter2 = self.get_iter_at_line_offset(4, 10)
self.apply_tag_by_name("bg_green", iter, iter2)
iter = self.get_iter_at_line_offset(4, 8)
iter2 = self.get_iter_at_line_offset(4, 15)
self.apply_tag_by_name("fg_red", iter, iter2)
iter = self.get_iter_at_mark(temp_mark)
self.insert(iter, "Centered text!\n")
iter2 = self.get_iter_at_mark(temp_mark)
self.apply_tag_by_name("centered", iter2, iter)
self.move_mark(temp_mark, iter)
self.insert(iter, "Word wrapped, Right-to-left Quote\n")
self.insert(iter, "وقد بدأ ثلاث من أكثر المؤسسات تقدما في شبكة اكسيون برامجها كمنظمات لا تسعى للربح، ثم تحولت في السنوات الخمس الماضية إلى مؤسسات مالية منظمة، وباتت جزءا من النظام المالي في بلدانها، ولكنها تتخصص في خدمة قطاع المشروعات الصغيرة. وأحد أكثر هذه المؤسسات نجاحا هو »بانكوسول« في بوليفيا.\n")
iter2 = self.get_iter_at_mark(temp_mark)
self.apply_tag_by_name("rtl_quote", iter2, iter)
self.insert_with_tags(iter,
"Paragraph with negative indentation. blah blah blah blah blah. The quick brown fox jumped over the lazy dog.\n",
self.get_tag_table().lookup("negative_indent"))
print "%d lines %d chars\n" % (self.get_line_count(),
self.get_char_count())
# Move cursor to start
iter = self.get_iter_at_offset(0)
self.place_cursor(iter)
self.set_modified(False)
def fill_file_buffer(self, filename):
try:
f = open(filename, "r")
except IOError, (errnum, errmsg):
err = "Cannot open file '%s': %s" % (filename, errmsg)
view = TestText.active_window_stack.get()
dialog = gtk.MessageDialog(view, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO,
gtk.BUTTONS_OK, err);
result = dialog.run()
dialog.destroy()
return False
iter = self.get_iter_at_offset(0)
buf = f.read()
f.close()
self.set_text(buf)
self.set_modified(False)
return True
def save_buffer(self):
result = False
have_backup = False
if not self.filename:
return False
bak_filename = self.filename + "~"
try:
os.rename(self.filename, bak_filename)
except (OSError, IOError), (errnum, errmsg):
if errnum != errno.ENOENT:
err = "Cannot back up '%s' to '%s': %s" % (self.filename,
bak_filename,
errmsg)
view = TestText.active_window_stack.get()
dialog = gtk.MessageDialog(view, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO,
gtk.BUTTONS_OK, err);
dialog.run()
dialog.destroy()
return False
have_backup = True
start, end = self.get_bounds()
chars = self.get_slice(start, end, False)
try:
file = open(self.filename, "w")
file.write(chars)
file.close()
result = True
self.set_modified(False)
except IOError, (errnum, errmsg):
err = "Error writing to '%s': %s" % (self.filename, errmsg)
view = TestText.active_window_stack.get()
dialog = gtk.MessageDialog(view, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO,
gtk.BUTTONS_OK, err);
dialog.run()
dialog.destroy()
if not result and have_backup:
try:
os.rename(bak_filename, self.filename)
except OSError, (errnum, errmsg):
err = "Can't restore backup file '%s' to '%s': %s\nBackup left as '%s'" % (
self.filename, bak_filename, errmsg, bak_filename)
view = TestText.active_window_stack.get()
dialog = gtk.MessageDialog(view, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO,
gtk.BUTTONS_OK, err);
dialog.run()
dialog.destroy()
return result
def save_as_ok_func(self, filename):
old_filename = self.filename
if (not self.filename or filename != self.filename):
if os.path.exists(filename):
err = "Ovewrite existing file '%s'?" % filename
view = TestText.active_window_stack.get()
dialog = gtk.MessageDialog(view, gtk.DIALOG_MODAL,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO, err);
result = dialog.run()
dialog.destroy()
if result != gtk.RESPONSE_YES:
return False
self.filename = filename
if self.save_buffer():
self.filename_set()
return True
else:
self.filename = old_filename
return False
def save_as_buffer(self):
return FileSel().run(self, "Save File", None, self.save_as_ok_func)
def check_buffer_saved(self):
if self.get_modified():
pretty_name = self.pretty_name()
msg = "Save changes to '%s'?" % pretty_name
view = TestText.active_window_stack.get()
dialog = gtk.MessageDialog(view, gtk.DIALOG_MODAL,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO, msg);
dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
result = dialog.run()
dialog.destroy()
if result == gtk.RESPONSE_YES:
if self.filename:
return self.save_buffer()
return self.save_as_buffer()
elif result == gtk.RESPONSE_NO:
return True
else:
return False
else:
return True
class View(gtk.Window):
def __init__(self, buffer=None):
menu_items = [
( "/_File", None, None, 0, "<Branch>" ),
( "/File/_New", "<control>N", self.do_new, 0, None ),
( "/File/New _View", None, self.do_new_view, 0, None ),
( "/File/_Open", "<control>O", self.do_open, 0, None ),
( "/File/_Save", "<control>S", self.do_save, 0, None ),
( "/File/Save _As...", None, self.do_save_as, 0, None ),
( "/File/sep1", None, None, 0, "<Separator>" ),
( "/File/_Close", "<control>W" , self.do_close, 0, None ),
( "/File/E_xit", "<control>Q" , self.do_exit, 0, None ),
( "/_Edit", None, None, 0, "<Branch>" ),
( "/Edit/Find...", None, self.do_search, 0, None ),
( "/_Settings", None, None, 0, "<Branch>" ),
( "/Settings/Wrap _Off", None, self.do_wrap_changed, gtk.WRAP_NONE, "<RadioItem>" ),
( "/Settings/Wrap _Words", None, self.do_wrap_changed, gtk.WRAP_WORD, "/Settings/Wrap Off" ),
( "/Settings/Wrap _Chars", None, self.do_wrap_changed, gtk.WRAP_CHAR, "/Settings/Wrap Off" ),
( "/Settings/sep1", None, None, 0, "<Separator>" ),
( "/Settings/Editable", None, self.do_editable_changed, True, "<RadioItem>" ),
( "/Settings/Not editable", None, self.do_editable_changed, False, "/Settings/Editable" ),
( "/Settings/sep1", None, None, 0, "<Separator>" ),
( "/Settings/Cursor visible", None, self.do_cursor_visible_changed, True, "<RadioItem>" ),
( "/Settings/Cursor not visible", None, self.do_cursor_visible_changed, False, "/Settings/Cursor visible" ),
( "/Settings/sep1", None, None, 0, "<Separator>" ),
( "/Settings/Left-to-Right", None, self.do_direction_changed, gtk.TEXT_DIR_LTR, "<RadioItem>" ),
( "/Settings/Right-to-Left", None, self.do_direction_changed, gtk.TEXT_DIR_RTL, "/Settings/Left-to-Right" ),
( "/Settings/sep1", None, None, 0, "<Separator>" ),
( "/Settings/Sane spacing", None, self.do_spacing_changed, False, "<RadioItem>" ),
( "/Settings/Funky spacing", None, self.do_spacing_changed, True, "/Settings/Sane spacing" ),
( "/Settings/sep1", None, None, 0, "<Separator>" ),
( "/Settings/Don't cycle color tags", None, self.do_color_cycle_changed, False, "<RadioItem>" ),
( "/Settings/Cycle colors", None, self.do_color_cycle_changed, True, "/Settings/Don't cycle color tags" ),
( "/_Attributes", None, None, 0, "<Branch>" ),
( "/Attributes/Editable", None, self.do_apply_editable, True, None ),
( "/Attributes/Not editable", None, self.do_apply_editable, False, None ),
( "/Attributes/Invisible", None, self.do_apply_invisible, False, None ),
( "/Attributes/Visible", None, self.do_apply_invisible, True, None ),
( "/Attributes/Custom tabs", None, self.do_apply_tabs, False, None ),
( "/Attributes/Default tabs", None, self.do_apply_tabs, True, None ),
( "/Attributes/Color cycles", None, self.do_apply_colors, True, None ),
( "/Attributes/No colors", None, self.do_apply_colors, False, None ),
( "/Attributes/Remove all tags", None, self.do_remove_tags, 0, None ),
( "/Attributes/Properties", None, self.do_properties, 0, None ),
( "/_Test", None, None, 0, "<Branch>" ),
( "/Test/_Example", None, self.do_example, 0, None ),
( "/Test/_Insert and scroll", None, self.do_insert_and_scroll, 0, None ),
( "/Test/_Add movable children", None, self.do_add_children, 0, None ),
( "/Test/A_dd focusable children", None, self.do_add_focus_children, 0, None ),
]
if not buffer:
buffer = Buffer()
gtk.Window.__init__(self)
TestText.views.push(self)
buffer.ref()
if not TestText.colormap:
TestText.colormap = self.get_colormap()
self.connect("delete_event", self.delete_event_cb)
self.accel_group = gtk.AccelGroup()
self.item_factory = gtk.ItemFactory(gtk.MenuBar, "<main>",
self.accel_group)
self.item_factory.set_data("view", self)
self.item_factory.create_items(menu_items)
self.add_accel_group(self.accel_group)
vbox = gtk.VBox(False, 0)
self.add(vbox)
vbox.pack_start(self.item_factory.get_widget("<main>"),
False, False, 0)
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.text_view = gtk.TextView(buffer)
self.text_view.set_wrap_mode(gtk.WRAP_WORD)
# Make sure border width works, no real reason to do this other
# than testing
self.text_view.set_border_width(10)
# Draw tab stops in the top and bottom windows.
self.text_view.set_border_window_size(gtk.TEXT_WINDOW_TOP, 15)
self.text_view.set_border_window_size(gtk.TEXT_WINDOW_BOTTOM, 15)
self.text_view.connect("expose_event", self.tab_stops_expose)
self.bhid = buffer.connect("mark_set", self.cursor_set_callback)
# Draw line numbers in the side windows; we should really be
# more scientific about what width we set them to.
self.text_view.set_border_window_size(gtk.TEXT_WINDOW_RIGHT, 30)
self.text_view.set_border_window_size(gtk.TEXT_WINDOW_LEFT, 30)
self.text_view.connect("expose_event", self.line_numbers_expose)
vbox.pack_start(sw, True, True, 0)
sw.add(self.text_view)
self.set_default_size(500, 500)
self.text_view.grab_focus()
self.set_view_title()
self.init_menus()
self.add_example_widgets()
self.show_all()
def delete_event_cb(self, window, event, data=None):
TestText.active_window_stack.push(self)
self.check_close_view()
TestText.active_window_stack.pop()
return True
#
# Menu callbacks
#
def get_empty_view(self):
buffer = self.text_view.get_buffer()
if (not buffer.filename and not buffer.get_modified()):
return self
else:
return View(Buffer())
def view_from_widget(widget):
if isinstance(widget, gtk.MenuItem):
item_factory = gtk.item_factory_from_widget(widget)
return item_factory.get_data("view")
else:
app = widget.get_toplevel()
return app.get_data("view")
def do_new(self, callback_action, widget):
View()
def do_new_view(self, callback_action, widget):
View(self.text_view.get_buffer())
def open_ok_func(self, filename):
new_view = self.get_empty_view()
buffer = new_view.text_view.get_buffer()
if not buffer.fill_file_buffer(filename):
if new_view != self:
new_view.close_view()
return False
else:
buffer.filename = filename
buffer.filename_set()
return True;
def do_open(self, callback_action, widget):
FileSel().run(self, "Open File", None, self.open_ok_func)
def do_save_as(self, callback_action, widget):
TestText.active_window_stack.push(self)
self.text_view.get_buffer().save_as_buffer()
TestText.active_window_stack.pop()
def do_save(self, callback_action, widget):
TestText.active_window_stack.push(self)
buffer = self.text_view.get_buffer()
if not buffer.filename:
self.do_save_as(callback_data, callback_action)
else:
buffer.save_buffer()
TestText.active_window_stack.pop()
def do_close(self, callback_action, widget):
TestText.active_window_stack.push(self)
self.check_close_view()
TestText.active_window_stack.pop()
def do_exit(self, callback_action, widget):
TestText.active_window_stack.push(self)
for tmp in TestText.buffers:
if not tmp.check_buffer_saved():
return
gtk.main_quit()
TestText.active_window_stack.pop()
def do_example(self, callback_action, widget):
new_view = self.get_empty_view()
buffer = new_view.text_view.get_buffer()
buffer.fill_example_buffer()
new_view.add_example_widgets()
def do_insert_and_scroll(self, callback_action, widget):
buffer = self.text_view.get_buffer()
start, end = buffer.get_bounds()
mark = buffer.create_mark(None, end, False)
buffer.insert(end,
"Hello this is multiple lines of text\n"
"Line 1\n" "Line 2\n"
"Line 3\n" "Line 4\n"
"Line 5\n")
self.text_view.scroll_to_mark(mark, 0, True, 0.0, 1.0)
buffer.delete_mark(mark)
def do_wrap_changed(self, callback_action, widget):
self.text_view.set_wrap_mode(callback_action)
def do_direction_changed(self, callback_action, widget):
self.text_view.set_direction(callback_action)
self.text_view.queue_resize()
def do_spacing_changed(self, callback_action, widget):
if callback_action:
self.text_view.set_pixels_above_lines(23)
self.text_view.set_pixels_below_lines(21)
self.text_view.set_pixels_inside_wrap(9)
else:
self.text_view.set_pixels_above_lines(0)
self.text_view.set_pixels_below_lines(0)
self.text_view.set_pixels_inside_wrap(0)
def do_editable_changed(self, callback_action, widget):
self.text_view.set_editable(callback_action)
def do_cursor_visible_changed(self, callback_action, widget):
self.text_view.set_cursor_visible(callback_action)
def do_color_cycle_changed(self, callback_action, widget):
self.text_view.get_buffer().set_colors(callback_action)
def do_apply_editable(self, callback_action, widget):
buffer = self.text_view.get_buffer()
bounds = buffer.get_selection_bounds()
if bounds:
start, end = bounds
if callback_action:
buffer.remove_tag(buffer.not_editable_tag, start, end)
else:
buffer.apply_tag(buffer.not_editable_tag, start, end)
def do_apply_invisible(self, callback_action, widget):
buffer = self.text_view.get_buffer()
bounds = buffer.get_selection_bounds()
if bounds:
start, end = bounds
if callback_action:
buffer.remove_tag(buffer.invisible_tag, start, end)
else:
buffer.apply_tag(buffer.invisible_tag, start, end)
def do_apply_tabs(self, callback_action, widget):
buffer = self.text_view.get_buffer()
bounds = buffer.get_selection_bounds()
if bounds:
start, end = bounds
if callback_action:
buffer.remove_tag(buffer.custom_tabs_tag, start, end)
else:
buffer.apply_tag(buffer.custom_tabs_tag, start, end)
def do_apply_colors(self, callback_action, widget):
buffer = self.text_view.get_buffer()
bounds = buffer.get_selection_bounds()
if bounds:
start, end = bounds
if not callback_action:
for tag in buffer.color_tags:
buffer.remove_tag(tag, start, end)
else:
tmp = buffer.color_tags
i = 0
next = start.copy()
while next.compare(end) < 0:
next.forward_chars(2)
if next.compare(end) >= 0:
next = end
buffer.apply_tag(tmp[i], start, next)
i += 1
if i >= len(tmp):
i = 0
start = next.copy()
def do_remove_tags(self, callback_action, widget):
buffer = self.text_view.get_buffer()
bounds = buffer.get_selection_bounds()
if bounds:
start, end = bounds
buffer.remove_all_tags(start, end)
def do_properties(self, callback_action, widget):
#create_prop_editor(view.text_view, 0)
pass
def dialog_response_callback(self, dialog, response_id):
if (response_id != RESPONSE_FORWARD and
response_id != RESPONSE_BACKWARD):
dialog.destroy()
return
start, end = dialog.buffer.get_bounds()
search_string = start.get_text(end)
print "Searching for `%s'\n" % search_string
buffer = self.text_view.get_buffer()
if response_id == RESPONSE_FORWARD:
buffer.search_forward(search_string, self)
elif response_id == RESPONSE_BACKWARD:
buffer.search_backward(search_string, self)
dialog.destroy()
def do_search(self, callback_action, widget):
search_text = gtk.TextView()
dialog = gtk.Dialog("Search", self,
gtk.DIALOG_DESTROY_WITH_PARENT,
("Forward", RESPONSE_FORWARD,
"Backward", RESPONSE_BACKWARD,
gtk.STOCK_CANCEL, gtk.RESPONSE_NONE))
dialog.vbox.pack_end(search_text, True, True, 0)
dialog.buffer = search_text.get_buffer()
dialog.connect("response", self.dialog_response_callback)
search_text.show()
search_text.grab_focus()
dialog.show_all()
def movable_child_callback(self, child, event):
text_view = self.text_view
info = child.get_data("testtext-move-info")
if not info:
info = {}
info['start_x'] = -1
info['start_y'] = -1
info['button'] = -1
child.set_data("testtext-move-info", info)
if event.type == gtk.gdk.BUTTON_PRESS:
if info['button'] < 0:
info['button'] = event.button
info['start_x'] = child.allocation.x
info['start_y'] = child.allocation.y
info['click_x'] = child.allocation.x + event.x
info['click_y'] = child.allocation.y + event.y
elif event.type == gtk.gdk.BUTTON_RELEASE:
if info['button'] < 0:
return False
if info['button'] == event.button:
info['button'] = -1;
# convert to window coords from event box coords
x = info['start_x'] + (event.x + child.allocation.x \
- info['click_x'])
y = info['start_y'] + (event.y + child.allocation.y \
- info['click_y'])
text_view.move_child(child, x, y)
elif gtk.gdk.MOTION_NOTIFY:
if info['button'] < 0:
return False
x, y = child.get_pointer() # ensure more events
# to window coords from event box coords
x += child.allocation.x
y += child.allocation.y
x = info['start_x'] + (x - info['click_x'])
y = info['start_y'] + (y - info['click_y'])
text_view.move_child(child, x, y)
return False
def add_movable_child(self, text_view, window):
label = gtk.Label("Drag me around")
event_box = gtk.EventBox()
event_box.add_events(gtk.gdk.BUTTON_PRESS_MASK |
gtk.gdk.BUTTON_RELEASE_MASK |
gtk.gdk.POINTER_MOTION_MASK |
gtk.gdk.POINTER_MOTION_HINT_MASK)
color = TestText.colormap.alloc_color(0xffff, 0, 0)
event_box.modify_bg(gtk.STATE_NORMAL, color)
event_box.add(label)
event_box.show_all()
event_box.connect("event", self.movable_child_callback)
text_view.add_child_in_window(event_box, window, 0, 0)
def do_add_children(self, callback_action, widget):
text_view = self.text_view
self.add_movable_child(text_view, gtk.TEXT_WINDOW_WIDGET)
self.add_movable_child(text_view, gtk.TEXT_WINDOW_LEFT)
self.add_movable_child(text_view, gtk.TEXT_WINDOW_RIGHT)
self.add_movable_child(text_view, gtk.TEXT_WINDOW_TEXT)
self.add_movable_child(text_view, gtk.TEXT_WINDOW_TOP)
self.add_movable_child(text_view, gtk.TEXT_WINDOW_BOTTOM)
def do_add_focus_children(self, callback_action, widget):
text_view = self.text_view
child = gtk.EventBox()
b = gtk.Button("Button _A in widget.window")
child.add(b)
text_view.add_child_in_window(child, gtk.TEXT_WINDOW_WIDGET, 0, 200)
child = gtk.EventBox()
b = gtk.Button("Button _B in text.window")
child.add(b)
text_view.add_child_in_window(child, gtk.TEXT_WINDOW_TEXT, 50, 50)
child = gtk.EventBox()
b = gtk.Button("Button _T in top window")
child.add(b)
text_view.add_child_in_window(child, gtk.TEXT_WINDOW_TOP, 100, 0)
child = gtk.EventBox()
b = gtk.Button("Button _W in bottom window")
child.add(b)
text_view.add_child_in_window(child, gtk.TEXT_WINDOW_BOTTOM, 100, 0)
child = gtk.EventBox()
b = gtk.Button("Button _C in left window")
child.add(b)
text_view.add_child_in_window(child, gtk.TEXT_WINDOW_LEFT, 0, 50)
child = gtk.EventBox()
b = gtk.Button("Button _D in right window")
child.add(b)
text_view.add_child_in_window(child, gtk.TEXT_WINDOW_RIGHT, 0, 25)
buffer = text_view.get_buffer()
iter = buffer.get_start_iter()
anchor = buffer.create_child_anchor(iter)
child = gtk.Button("Button _E in buffer")
text_view.add_child_at_anchor(child, anchor)
anchor = buffer.create_child_anchor(iter)
child = gtk.Button("Button _F in buffer")
text_view.add_child_at_anchor(child, anchor)
anchor = buffer.create_child_anchor(iter)
child = gtk.Button("Button _G in buffer")
text_view.add_child_at_anchor(child, anchor)
# show all the buttons
text_view.show_all()
def init_menus(self):
text_view = self.text_view
direction = text_view.get_direction()
wrap_mode = text_view.get_wrap_mode()
menu_item = None
if direction == gtk.TEXT_DIR_LTR:
menu_item = self.item_factory.get_widget("/Settings/Left-to-Right")
elif direction == gtk.TEXT_DIR_RTL:
menu_item = self.item_factory.get_widget("/Settings/Right-to-Left")
if menu_item:
menu_item.activate()
if wrap_mode == gtk.WRAP_NONE:
menu_item = self.item_factory.get_widget("/Settings/Wrap Off")
elif wrap_mode == gtk.WRAP_WORD:
menu_item = self.item_factory.get_widget("/Settings/Wrap Words")
elif wrap_mode == gtk.WRAP_CHAR:
menu_item = self.item_factory.get_widget("/Settings/Wrap Chars")
if menu_item:
menu_item.activate()
def close_view(self):
TestText.views.remove(self)
buffer = self.text_view.get_buffer()
buffer.unref()
buffer.disconnect(self.bhid)
self.text_view.destroy()
del self.text_view
self.text_view = None
self.destroy()
del self
if not TestText.views:
gtk.main_quit()
def check_close_view(self):
buffer = self.text_view.get_buffer()
if (buffer.refcount > 1 or
buffer.check_buffer_saved()):
self.close_view()
def set_view_title(self):
pretty_name = self.text_view.get_buffer().pretty_name()
title = "testtext - " + pretty_name
self.set_title(title)
def cursor_set_callback(self, buffer, location, mark):
# Redraw tab windows if the cursor moves
# on the mapped widget (windows may not exist before realization...
text_view = self.text_view
if mark == buffer.get_insert():
tab_window = text_view.get_window(gtk.TEXT_WINDOW_TOP)
tab_window.invalidate_rect(None, False)
#tab_window.invalidate_rect(tab_window.get_geometry()[:4], False)
tab_window = text_view.get_window(gtk.TEXT_WINDOW_BOTTOM)
tab_window.invalidate_rect(None, False)
#tab_window.invalidate_rect(tab_window.get_geometry()[:4], False)
def tab_stops_expose(self, widget, event):
#print self, widget, event
text_view = widget
# See if this expose is on the tab stop window
top_win = text_view.get_window(gtk.TEXT_WINDOW_TOP)
bottom_win = text_view.get_window(gtk.TEXT_WINDOW_BOTTOM)
if event.window == top_win:
type = gtk.TEXT_WINDOW_TOP
target = top_win
elif event.window == bottom_win:
type = gtk.TEXT_WINDOW_BOTTOM
target = bottom_win
else:
return False
first_x = event.area.x
last_x = first_x + event.area.width
first_x, y = text_view.window_to_buffer_coords(type, first_x, 0)
last_x, y = text_view.window_to_buffer_coords(type, last_x, 0)
buffer = text_view.get_buffer()
insert = buffer.get_iter_at_mark(buffer.get_insert())
attrs = gtk.TextAttributes()
insert.get_attributes(attrs)
tabslist = []
in_pixels = False
if attrs.tabs:
tabslist = attrs.tabs.get_tabs()
in_pixels = attrs.tabs.get_positions_in_pixels()
for align, position in tabslist:
if not in_pixels:
position = pango.PIXELS(position)
pos, y = text_view.buffer_to_window_coords(type, position, 0)
target.draw_line(text_view.style.fg_gc[text_view.state],
pos, 0, pos, 15)
return True
def get_lines(self, first_y, last_y, buffer_coords, numbers):
text_view = self.text_view
# Get iter at first y
iter, top = text_view.get_line_at_y(first_y)
# For each iter, get its location and add it to the arrays.
# Stop when we pass last_y
count = 0
size = 0
while not iter.is_end():
y, height = text_view.get_line_yrange(iter)
buffer_coords.append(y)
line_num = iter.get_line()
numbers.append(line_num)
count += 1
if (y + height) >= last_y:
break
iter.forward_line()
return count
def line_numbers_expose(self, widget, event, user_data=None):
text_view = widget
# See if this expose is on the line numbers window
left_win = text_view.get_window(gtk.TEXT_WINDOW_LEFT)
right_win = text_view.get_window(gtk.TEXT_WINDOW_RIGHT)
if event.window == left_win:
type = gtk.TEXT_WINDOW_LEFT
target = left_win
elif event.window == right_win:
type = gtk.TEXT_WINDOW_RIGHT
target = right_win
else:
return False
first_y = event.area.y
last_y = first_y + event.area.height
x, first_y = text_view.window_to_buffer_coords(type, 0, first_y)
x, last_y = text_view.window_to_buffer_coords(type, 0, last_y)
numbers = []
pixels = []
count = self.get_lines(first_y, last_y, pixels, numbers)
# Draw fully internationalized numbers!
layout = widget.create_pango_layout("")
for i in range(count):
x, pos = text_view.buffer_to_window_coords(type, 0, pixels[i])
str = "%d" % numbers[i]
layout.set_text(str)
widget.style.paint_layout(target, widget.state, False,
None, widget, None, 2, pos + 2, layout)
# don't stop emission, need to draw children
return False
def add_example_widgets(self):
buffer = self.text_view.get_buffer()
anchor = buffer.get_data("anchor")
if (anchor and not anchor.get_deleted()):
widget = gtk.Button("Foo")
self.text_view.add_child_at_anchor(widget, anchor)
widget.show()
class Stack(list):
def __init__(self):
list.__init__(self)
def push(self, item):
self.insert(-1, item)
def pop(self):
del self[0]
def get(self):
return self[0]
class TestText:
untitled_serial = 1
colormap = None
active_window_stack = Stack()
buffers = Stack()
views = Stack()
def __init__(self, filelist):
view = View()
self.active_window_stack.push(view)
for fname in filelist:
filename = os.path.abspath(fname)
view.open_ok_func(filename)
self.active_window_stack.pop()
def main(self):
gtk.main()
return 0
if __name__ == "__main__":
testtext = TestText(sys.argv[1:])
testtext.main()
| 22,379 |
2,151 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/extensions/platform_keys_natives.h"
#include <memory>
#include <string>
#include <utility>
#include "base/values.h"
#include "content/public/renderer/v8_value_converter.h"
#include "extensions/renderer/script_context.h"
#include "third_party/blink/public/platform/web_crypto_algorithm.h"
#include "third_party/blink/public/platform/web_crypto_algorithm_params.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/public/web/web_crypto_normalize.h"
namespace extensions {
namespace {
bool StringToWebCryptoOperation(const std::string& str,
blink::WebCryptoOperation* op) {
if (str == "GenerateKey") {
*op = blink::kWebCryptoOperationGenerateKey;
return true;
}
if (str == "ImportKey") {
*op = blink::kWebCryptoOperationImportKey;
return true;
}
if (str == "Sign") {
*op = blink::kWebCryptoOperationSign;
return true;
}
if (str == "Verify") {
*op = blink::kWebCryptoOperationVerify;
return true;
}
return false;
}
std::unique_ptr<base::DictionaryValue> WebCryptoAlgorithmToBaseValue(
const blink::WebCryptoAlgorithm& algorithm) {
DCHECK(!algorithm.IsNull());
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
const blink::WebCryptoAlgorithmInfo* info =
blink::WebCryptoAlgorithm::LookupAlgorithmInfo(algorithm.Id());
dict->SetKey("name", base::Value(info->name));
const blink::WebCryptoAlgorithm* hash = nullptr;
const blink::WebCryptoRsaHashedKeyGenParams* rsaHashedKeyGen =
algorithm.RsaHashedKeyGenParams();
if (rsaHashedKeyGen) {
dict->SetKey(
"modulusLength",
base::Value(static_cast<int>(rsaHashedKeyGen->ModulusLengthBits())));
const blink::WebVector<unsigned char>& public_exponent =
rsaHashedKeyGen->PublicExponent();
dict->SetWithoutPathExpansion(
"publicExponent",
base::Value::CreateWithCopiedBuffer(
reinterpret_cast<const char*>(public_exponent.Data()),
public_exponent.size()));
hash = &rsaHashedKeyGen->GetHash();
DCHECK(!hash->IsNull());
}
const blink::WebCryptoRsaHashedImportParams* rsaHashedImport =
algorithm.RsaHashedImportParams();
if (rsaHashedImport) {
hash = &rsaHashedImport->GetHash();
DCHECK(!hash->IsNull());
}
if (hash) {
const blink::WebCryptoAlgorithmInfo* hash_info =
blink::WebCryptoAlgorithm::LookupAlgorithmInfo(hash->Id());
std::unique_ptr<base::DictionaryValue> hash_dict(new base::DictionaryValue);
hash_dict->SetKey("name", base::Value(hash_info->name));
dict->SetWithoutPathExpansion("hash", std::move(hash_dict));
}
// Otherwise, |algorithm| is missing support here or no parameters were
// required.
return dict;
}
} // namespace
PlatformKeysNatives::PlatformKeysNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context) {}
void PlatformKeysNatives::AddRoutes() {
RouteHandlerFunction("NormalizeAlgorithm",
base::Bind(&PlatformKeysNatives::NormalizeAlgorithm,
base::Unretained(this)));
}
void PlatformKeysNatives::NormalizeAlgorithm(
const v8::FunctionCallbackInfo<v8::Value>& call_info) {
DCHECK_EQ(call_info.Length(), 2);
DCHECK(call_info[0]->IsObject());
DCHECK(call_info[1]->IsString());
blink::WebCryptoOperation operation;
if (!StringToWebCryptoOperation(
*v8::String::Utf8Value(call_info.GetIsolate(), call_info[1]),
&operation)) {
return;
}
blink::WebString error_details;
int exception_code = 0;
blink::WebCryptoAlgorithm algorithm = blink::NormalizeCryptoAlgorithm(
v8::Local<v8::Object>::Cast(call_info[0]), operation, &exception_code,
&error_details, call_info.GetIsolate());
std::unique_ptr<base::DictionaryValue> algorithm_dict;
if (!algorithm.IsNull())
algorithm_dict = WebCryptoAlgorithmToBaseValue(algorithm);
if (!algorithm_dict)
return;
call_info.GetReturnValue().Set(content::V8ValueConverter::Create()->ToV8Value(
algorithm_dict.get(), context()->v8_context()));
}
} // namespace extensions
| 1,651 |
2,338 | // RUN: %clang_cc1 -triple powerpc64le-unknown-unknown -fsyntax-only \
// RUN: -fcxx-exceptions -target-cpu pwr10 %s -verify
// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -fsyntax-only \
// RUN: -fcxx-exceptions -target-cpu pwr10 %s -verify
// vector quad
// alias
using vq_t = __vector_quad;
void testVQAlias(int *inp, int *outp) {
vq_t *vqin = (vq_t *)inp;
vq_t *vqout = (vq_t *)outp;
*vqout = *vqin;
}
class TestClassVQ {
// method argument
public:
void testVQArg1(__vector_quad vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_quad *vqp = (__vector_quad *)ptr;
*vqp = vq;
*vqp1 = vq;
}
void testVQArg2(const __vector_quad vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_quad *vqp = (__vector_quad *)ptr;
*vqp = vq;
*vqp2 = vq;
}
void testVQArg3(__vector_quad *vq, int *ptr) {
__vector_quad *vqp = (__vector_quad *)ptr;
*vqp = *vq;
vqp1 = vqp;
}
void testVQArg4(const __vector_quad *const vq, int *ptr) {
__vector_quad *vqp = (__vector_quad *)ptr;
*vqp = *vq;
vqp2 = vqp;
}
void testVQArg5(__vector_quad vqa[], int *ptr) {
__vector_quad *vqp = (__vector_quad *)ptr;
*vqp = vqa[0];
*vqp1 = vqa[1];
}
void testVQArg6(const vq_t vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_quad *vqp = (__vector_quad *)ptr;
*vqp = vq;
*vqp2 = vq;
}
void testVQArg7(const vq_t *vq, int *ptr) {
__vector_quad *vqp = (__vector_quad *)ptr;
*vqp = *vq;
vqp1 = vqp;
}
// method return
__vector_quad testVQRet1(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_quad *vqp = (__vector_quad *)ptr;
vq1 = *vqp;
return *vqp; // expected-error {{invalid use of PPC MMA type}}
}
__vector_quad *testVQRet2(int *ptr) {
__vector_quad *vqp = (__vector_quad *)ptr;
vq2 = *vqp;
return vqp + 2;
}
const __vector_quad *testVQRet3(int *ptr) {
__vector_quad *vqp = (__vector_quad *)ptr;
vqp1 = vqp;
return vqp + 2;
}
const vq_t testVQRet4(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_quad *vqp = (__vector_quad *)ptr;
vqp2 = vqp;
return *vqp; // expected-error {{invalid use of PPC MMA type}}
}
const vq_t *testVQRet5(int *ptr) {
__vector_quad *vqp = (__vector_quad *)ptr;
vq1 = *vqp;
return vqp + 2;
}
// template argument
template <typename T = __vector_quad>
void testVQTemplate(T v, T *p) { // expected-note {{candidate template ignored: substitution failure [with T = __vector_quad]: invalid use of PPC MMA type}} \
expected-note {{candidate template ignored: substitution failure [with T = __vector_quad]: invalid use of PPC MMA type}}
*(p + 1) = v;
}
// class field
public:
__vector_quad vq1; // expected-error {{invalid use of PPC MMA type}}
__vector_quad *vqp1;
private:
vq_t vq2; // expected-error {{invalid use of PPC MMA type}}
vq_t *vqp2;
};
// template
template <typename T>
class ClassTemplateVQ1 {
T t; // expected-error {{invalid use of PPC MMA type}}
};
template <typename T>
class ClassTemplateVQ2 {
T *t;
};
template <typename T>
class ClassTemplateVQ3 {
int foo(T t) { return 10; }
};
template <typename T, typename... Ts>
class ClassTemplateVQ4 {
public:
T operator()(Ts...) const {} // expected-error {{invalid use of PPC MMA type}}
};
void testVQTemplate() {
ClassTemplateVQ1<__vector_quad> t1; // expected-note {{in instantiation of template class 'ClassTemplateVQ1<__vector_quad>' requested here}}
ClassTemplateVQ1<__vector_quad *> t2;
ClassTemplateVQ2<__vector_quad> t3;
ClassTemplateVQ2<__vector_quad *> t4;
ClassTemplateVQ3<int(int, int, int)> t5;
// The following case is not prevented but it ok, this function type cannot be
// instantiated because we prevent any function from returning an MMA type.
ClassTemplateVQ3<__vector_quad(int, int, int)> t6;
ClassTemplateVQ3<int(__vector_quad, int, int)> t7; // expected-error {{invalid use of PPC MMA type}}
ClassTemplateVQ4<int, int, int, __vector_quad> t8; // expected-note {{in instantiation of template class 'ClassTemplateVQ4<int, int, int, __vector_quad>' requested here}}
ClassTemplateVQ4<int, int, int, __vector_quad *> t9;
TestClassVQ tc;
__vector_quad vq;
__vector_quad *vqp = &vq;
tc.testVQTemplate(&vq, &vqp);
tc.testVQTemplate<vq_t *>(&vq, &vqp);
tc.testVQTemplate(vq, vqp); // expected-error {{no matching member function for call to 'testVQTemplate'}}
tc.testVQTemplate<vq_t>(vq, vqp); // expected-error {{no matching member function for call to 'testVQTemplate'}}
}
// trailing return type
auto testVQTrailing1() {
__vector_quad vq;
return vq; // expected-error {{invalid use of PPC MMA type}}
}
auto testVQTrailing2() {
__vector_quad *vqp;
return vqp;
}
auto testVQTrailing3() -> vq_t { // expected-error {{invalid use of PPC MMA type}}
__vector_quad vq;
return vq; // expected-error {{invalid use of PPC MMA type}}
}
auto testVQTrailing4() -> vq_t * {
__vector_quad *vqp;
return vqp;
}
// new/delete
void testVQNewDelete() {
__vector_quad *vqp1 = new __vector_quad;
__vector_quad *vqp2 = new __vector_quad[100];
delete vqp1;
delete[] vqp2;
}
// lambdas expressions
void TestVQLambda() {
auto f1 = [](void *ptr) -> __vector_quad {
__vector_quad *vqp = (__vector_quad *)ptr;
return *vqp; // expected-error {{invalid use of PPC MMA type}}
};
auto f2 = [](void *ptr) {
__vector_quad *vqp = (__vector_quad *)ptr;
return *vqp; // expected-error {{invalid use of PPC MMA type}}
};
auto f3 = [] { __vector_quad vq; __builtin_mma_xxsetaccz(&vq); return vq; }; // expected-error {{invalid use of PPC MMA type}}
}
// cast
void TestVQCast() {
__vector_quad vq;
int *ip = reinterpret_cast<int *>(&vq);
__vector_quad *vq2 = reinterpret_cast<__vector_quad *>(ip);
}
// throw
void TestVQThrow() {
__vector_quad vq;
throw vq; // expected-error {{invalid use of PPC MMA type}}
}
// vector pair
// alias
using vp_t = __vector_pair;
void testVPAlias(int *inp, int *outp) {
vp_t *vpin = (vp_t *)inp;
vp_t *vpout = (vp_t *)outp;
*vpout = *vpin;
}
class TestClassVP {
// method argument
public:
void testVPArg1(__vector_pair vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_pair *vpp = (__vector_pair *)ptr;
*vpp = vp;
*vpp1 = vp;
}
void testVPArg2(const __vector_pair vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_pair *vpp = (__vector_pair *)ptr;
*vpp = vp;
*vpp2 = vp;
}
void testVPArg3(__vector_pair *vp, int *ptr) {
__vector_pair *vpp = (__vector_pair *)ptr;
*vpp = *vp;
vpp1 = vpp;
}
void testVPArg4(const __vector_pair *const vp, int *ptr) {
__vector_pair *vpp = (__vector_pair *)ptr;
*vpp = *vp;
vpp2 = vpp;
}
void testVPArg5(__vector_pair vpa[], int *ptr) {
__vector_pair *vpp = (__vector_pair *)ptr;
*vpp = vpa[0];
*vpp1 = vpa[1];
}
void testVPArg6(const vp_t vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_pair *vpp = (__vector_pair *)ptr;
*vpp = vp;
*vpp2 = vp;
}
void testVPArg7(const vp_t *vp, int *ptr) {
__vector_pair *vpp = (__vector_pair *)ptr;
*vpp = *vp;
vpp1 = vpp;
}
// method return
__vector_pair testVPRet1(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_pair *vpp = (__vector_pair *)ptr;
vp1 = *vpp;
return *vpp; // expected-error {{invalid use of PPC MMA type}}
}
__vector_pair *testVPRet2(int *ptr) {
__vector_pair *vpp = (__vector_pair *)ptr;
vp2 = *vpp;
return vpp + 2;
}
const __vector_pair *testVPRet3(int *ptr) {
__vector_pair *vpp = (__vector_pair *)ptr;
vpp1 = vpp;
return vpp + 2;
}
const vp_t testVPRet4(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
__vector_pair *vpp = (__vector_pair *)ptr;
vpp2 = vpp;
return *vpp; // expected-error {{invalid use of PPC MMA type}}
}
const vp_t *testVPRet5(int *ptr) {
__vector_pair *vpp = (__vector_pair *)ptr;
vp1 = *vpp;
return vpp + 2;
}
// template argument
template <typename T = __vector_pair>
void testVPTemplate(T v, T *p) { // expected-note {{candidate template ignored: substitution failure [with T = __vector_pair]: invalid use of PPC MMA type}} \
expected-note {{candidate template ignored: substitution failure [with T = __vector_pair]: invalid use of PPC MMA type}}
*(p + 1) = v;
}
// class field
public:
__vector_pair vp1; // expected-error {{invalid use of PPC MMA type}}
__vector_pair *vpp1;
private:
vp_t vp2; // expected-error {{invalid use of PPC MMA type}}
vp_t *vpp2;
};
// template
template <typename T>
class ClassTemplateVP1 {
T t; // expected-error {{invalid use of PPC MMA type}}
};
template <typename T>
class ClassTemplateVP2 {
T *t;
};
template <typename T>
class ClassTemplateVP3 {
int foo(T t) { return 10; }
};
template <typename T, typename... Ts>
class ClassTemplateVP4 {
public:
T operator()(Ts...) const {} // expected-error {{invalid use of PPC MMA type}}
};
void testVPTemplate() {
ClassTemplateVP1<__vector_pair> t1; // expected-note {{in instantiation of template class 'ClassTemplateVP1<__vector_pair>' requested here}}
ClassTemplateVP1<__vector_pair *> t2;
ClassTemplateVP2<__vector_pair> t3;
ClassTemplateVP2<__vector_pair *> t4;
ClassTemplateVP3<int(int, int, int)> t5;
// The following case is not prevented but it ok, this function type cannot be
// instantiated because we prevent any function from returning an MMA type.
ClassTemplateVP3<__vector_pair(int, int, int)> t6;
ClassTemplateVP3<int(__vector_pair, int, int)> t7; // expected-error {{invalid use of PPC MMA type}}
ClassTemplateVP4<int, int, int, __vector_pair> t8; // expected-note {{in instantiation of template class 'ClassTemplateVP4<int, int, int, __vector_pair>' requested here}}
ClassTemplateVP4<int, int, int, __vector_pair *> t9;
TestClassVP tc;
__vector_pair vp;
__vector_pair *vpp = &vp;
tc.testVPTemplate(&vp, &vpp);
tc.testVPTemplate<vp_t *>(&vp, &vpp);
tc.testVPTemplate(vp, vpp); // expected-error {{no matching member function for call to 'testVPTemplate'}}
tc.testVPTemplate<vp_t>(vp, vpp); // expected-error {{no matching member function for call to 'testVPTemplate'}}
}
// trailing return type
auto testVPTrailing1() {
__vector_pair vp;
return vp; // expected-error {{invalid use of PPC MMA type}}
}
auto testVPTrailing2() {
__vector_pair *vpp;
return vpp;
}
auto testVPTrailing3() -> vp_t { // expected-error {{invalid use of PPC MMA type}}
__vector_pair vp;
return vp; // expected-error {{invalid use of PPC MMA type}}
}
auto testVPTrailing4() -> vp_t * {
__vector_pair *vpp;
return vpp;
}
// new/delete
void testVPNewDelete() {
__vector_pair *vpp1 = new __vector_pair;
__vector_pair *vpp2 = new __vector_pair[100];
delete vpp1;
delete[] vpp2;
}
// lambdas expressions
void TestVPLambda() {
auto f1 = [](void *ptr) -> __vector_pair {
__vector_pair *vpp = (__vector_pair *)ptr;
return *vpp; // expected-error {{invalid use of PPC MMA type}}
};
auto f2 = [](void *ptr) {
__vector_pair *vpp = (__vector_pair *)ptr;
return *vpp; // expected-error {{invalid use of PPC MMA type}}
};
auto f3 = [](vector unsigned char vc) { __vector_pair vp; __builtin_vsx_assemble_pair(&vp, vc, vc); return vp; }; // expected-error {{invalid use of PPC MMA type}}
auto f4 = [](vector unsigned char vc) { __vector_pair vp; __builtin_vsx_build_pair(&vp, vc, vc); return vp; }; // expected-error {{invalid use of PPC MMA type}}
}
// cast
void TestVPCast() {
__vector_pair vp;
int *ip = reinterpret_cast<int *>(&vp);
__vector_pair *vp2 = reinterpret_cast<__vector_pair *>(ip);
}
// throw
void TestVPThrow() {
__vector_pair vp;
throw vp; // expected-error {{invalid use of PPC MMA type}}
}
| 4,905 |
6,557 | <gh_stars>1000+
{
"dragDescriptionKeyboard": "Paspauskite „Enter“, kad pradėtumėte vilkti.",
"dragDescriptionTouch": "Palieskite dukart, kad pradėtumėte vilkti.",
"dragDescriptionVirtual": "Spustelėkite, kad pradėtumėte vilkti.",
"dragItem": "Vilkti {itemText}",
"dragSelectedItems": "Vilkti {count, plural, one {# pasirinktą elementą} other {# pasirinktus elementus}}",
"dragStartedKeyboard": "Pradėta vilkti. Paspauskite „Tab“, kad pereitumėte į tiesioginę paskirties vietą, tada paspauskite „Enter“, kad numestumėte, arba „Escape“, kad atšauktumėte.",
"dragStartedTouch": "Pradėta vilkti. Eikite į tiesioginę paskirties vietą, tada palieskite dukart, kad numestumėte.",
"dragStartedVirtual": "Pradėta vilkti. Eikite į tiesioginę paskirties vietą ir spustelėkite arba paspauskite „Enter“, kad numestumėte.",
"dropCanceled": "Numetimas atšauktas.",
"dropComplete": "Numesta.",
"dropDescriptionKeyboard": "Paspauskite „Enter“, kad numestumėte. Paspauskite „Escape“, kad atšauktumėte vilkimą.",
"dropDescriptionTouch": "Palieskite dukart, kad numestumėte.",
"dropDescriptionVirtual": "Spustelėkite, kad numestumėte.",
"dropIndicator": "numetimo indikatorius",
"dropOnItem": "Numesti ant {itemText}",
"dropOnRoot": "Numesti ant",
"endDragKeyboard": "Velkama. Paspauskite „Enter“, kad atšauktumėte vilkimą.",
"endDragTouch": "Velkama. Spustelėkite dukart, kad atšauktumėte vilkimą.",
"endDragVirtual": "Velkama. Spustelėkite, kad atšauktumėte vilkimą.",
"insertAfter": "Įterpti po {itemText}",
"insertBefore": "Įterpti prieš {itemText}",
"insertBetween": "Įterpti tarp {beforeItemText} ir {afterItemText}"
}
| 756 |
529 | /* Copyright 2019 Stanford
*
* 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 "taso/ops.h"
using namespace taso;
TensorHandle Graph::pad(const TensorHandle _input,
const std::vector<int>& _pad_before,
const std::vector<int>& _pad_after,
float _pad_value)
{
assert(_pad_before.size() == (size_t)(_input->numDim));
assert(_pad_after.size() == (size_t)(_input->numDim));
Op op = model->get_or_create_pad(*_input, _pad_before, _pad_after, _pad_value);
assert(op != Op::INVALID_OP);
add_edge(_input->op, op, _input->idx, 0);
TensorHandle t = new Tensor(op.ptr->outputs[0]);
t->op = op;
return t;
}
Op Model::get_or_create_pad(const Tensor& _input,
const std::vector<int>& _pad_before,
const std::vector<int>& _pad_after,
float _pad_value)
{
PadKey key(_input, _pad_before, _pad_after, _pad_value);
Pad* padOp;
if (pad.find(key) != pad.end()) {
padOp = pad[key];
} else {
padOp = new Pad(this, _input, _pad_before, _pad_after, _pad_value);
measure_pad_cost(padOp);
pad[key] = padOp;
}
Op ret;
ret.guid = global_unique_id ++;
ret.ptr = padOp;
return ret;
}
Pad::Pad(Model* _model, const Tensor& _input,
const std::vector<int>& _pad_before,
const std::vector<int>& _pad_after,
float _pad_value)
: OpBase(_input, _model, OP_PAD), pad_before(_pad_before),
pad_after(_pad_after), pad_value(_pad_value)
{
numOutputs = 1;
// Pad currently only support the defacult layout
assert(_input.default_layout());
outputs[0].numDim = _input.numDim;
int cnt = 1;
for (int i = _input.numDim-1; i >= 0; i--) {
outputs[0].dim[i] = _input.dim[i] + pad_before[i] + pad_after[i];
outputs[0].stride[i] = cnt;
outputs[0].split[i] = SplitInfo::NO_SPLIT;
cnt *= outputs[0].dim[i];
}
outputs[0].idx = 0;
}
Pad::~Pad(void)
{
}
bool Pad::get_int_parameter(PMParameter para, int* value)
{
return OpBase::get_int_parameter(para, value);
}
void Pad::collect_costs(float& exe_time, float& flops,
float& mem_acc, int& num_kernels)
{
exe_time += runtime;
flops += inputs[0].volume();
mem_acc += inputs[0].volume() + outputs[0].volume();
num_kernels += 1;
printf(" cost[Pad]: cost(%.4lf) total_cost(%.4lf)\n",
runtime, exe_time);
}
PadKey::PadKey(const Tensor& _input,
const std::vector<int>& _pad_before,
const std::vector<int>& _pad_after,
float _pad_value)
{
//TODO: currently we do not include pad_value in the hash
int idx = 0;
keys[idx++] = _pad_before.size();
for (size_t j = 0; j < _pad_before.size(); j++)
keys[idx++] = _pad_before[j];
for (size_t j = 0; j < _pad_after.size(); j++)
keys[idx++] = _pad_after[j];
_input.serialize(keys, idx);
while (idx < KEY_LENGTH)
keys[idx++] = 0;
assert(idx == KEY_LENGTH);
}
| 1,509 |
450 | <gh_stars>100-1000
package com.dlazaro66.sampleapp;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import com.dlazaro66.wheelindicatorview.WheelIndicatorItem;
import com.dlazaro66.wheelindicatorview.WheelIndicatorView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WheelIndicatorView wheelIndicatorView = (WheelIndicatorView) findViewById(R.id.wheel_indicator_view);
//WheelIndicatorView wheelIndicatorView = new WheelIndicatorView(this);
// dummy data
float dailyKmsTarget = 4.0f; // 4.0Km is the user target, for example
float totalKmsDone = 3.0f; // User has done 3 Km
int percentageOfExerciseDone = (int) (totalKmsDone/dailyKmsTarget * 100); //
wheelIndicatorView.setFilledPercent(percentageOfExerciseDone);
WheelIndicatorItem bikeActivityIndicatorItem = new WheelIndicatorItem(1.8f, Color.parseColor("#ff9000"));
WheelIndicatorItem walkingActivityIndicatorItem = new WheelIndicatorItem(0.9f, Color.argb(255, 194, 30, 92));
WheelIndicatorItem runningActivityIndicatorItem = new WheelIndicatorItem(0.3f, getResources().getColor(R.color.my_wonderful_blue_color));
wheelIndicatorView.addWheelIndicatorItem(bikeActivityIndicatorItem);
wheelIndicatorView.addWheelIndicatorItem(walkingActivityIndicatorItem);
wheelIndicatorView.addWheelIndicatorItem(runningActivityIndicatorItem);
// Or you can add it as
//wheelIndicatorView.setWheelIndicatorItems(Arrays.asList(runningActivityIndicatorItem,walkingActivityIndicatorItem,bikeActivityIndicatorItem));
wheelIndicatorView.startItemsAnimation(); // Animate!
}
}
| 639 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Congratulation",
"definitions": [
"Words expressing one's praise for an achievement or good wishes on a special occasion.",
"The action of expressing congratulations."
],
"parts-of-speech": "Noun"
} | 101 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzFramework/Network/NetBindable.h>
#include <AzFramework/Network/NetBindingHandlerBus.h>
#include <AzFramework/Network/NetSystemBus.h>
#include <AzFramework/Network/NetworkContext.h>
#include <AzCore/RTTI/ReflectContext.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
namespace AzFramework
{
////////////////
// NetBindable
////////////////
NetBindable::NetBindable()
: m_isSyncEnabled(true)
{
}
NetBindable::~NetBindable()
{
if (m_chunk)
{
// NetBindable is a base class for handlers for replica chunks, so we have to clear the handler since this object is about to go away
m_chunk->SetHandler(nullptr);
m_chunk = nullptr;
}
}
GridMate::ReplicaChunkPtr NetBindable::GetNetworkBinding()
{
NetworkContext* netContext = nullptr;
NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext);
AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext");
if (netContext)
{
m_chunk = netContext->CreateReplicaChunk(azrtti_typeid(this));
netContext->Bind(this, m_chunk, NetworkContextBindMode::Authoritative);
return m_chunk;
}
return nullptr;
}
void NetBindable::SetNetworkBinding (GridMate::ReplicaChunkPtr chunk)
{
m_chunk = chunk;
NetworkContext* netContext = nullptr;
NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext);
AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext");
if (netContext)
{
netContext->Bind(this, m_chunk, NetworkContextBindMode::NonAuthoritative);
}
}
void NetBindable::UnbindFromNetwork()
{
if (m_chunk)
{
// NetworkContext-reflected chunks need access to the handler when they are being destroyed, so we won't null handler in here
m_chunk = nullptr;
}
}
void NetBindable::NetInit()
{
NetworkContext* netContext = nullptr;
NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext);
AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext");
if (netContext)
{
netContext->Bind(this, nullptr, NetworkContextBindMode::NonAuthoritative);
}
}
void NetBindable::Reflect(AZ::ReflectContext* reflection)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection);
if (serializeContext)
{
serializeContext->Class<NetBindable>()
->Field("m_isSyncEnabled", &NetBindable::m_isSyncEnabled);
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<NetBindable>(
"Network Bindable", "Network-bindable components are synchronized over the network.")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::Category, "Networking")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c))
->DataElement(AZ::Edit::UIHandlers::Default, &NetBindable::m_isSyncEnabled, "Bind To network", "Enable binding to the network.");
}
}
}
}
| 1,644 |
3,857 | package dev.skidfuscator.obf.number.encrypt.impl;
import dev.skidfuscator.obf.maple.FakeArithmeticExpr;
import dev.skidfuscator.obf.number.encrypt.NumberTransformer;
import org.mapleir.ir.code.Expr;
import org.mapleir.ir.code.expr.ArithmeticExpr;
import org.mapleir.ir.code.expr.ConstantExpr;
import org.mapleir.ir.code.expr.VarExpr;
import org.mapleir.ir.locals.Local;
import org.objectweb.asm.Type;
/**
* @author Ghast
* @since 09/03/2021
* SkidfuscatorV2 © 2021
*/
public class DebugNumberTransformer implements NumberTransformer {
@Override
public Expr getNumber(final int outcome, final int starting, final Local startingExpr) {
return new ConstantExpr(outcome);
}
}
| 257 |
17,318 | <reponame>woozhijun/cat
/*
* Copyright (c) 2011-2018, <NAME>. All Rights Reserved.
*
* 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 com.dianping.cat;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import com.dianping.cat.message.Transaction;
public class CatInitTest {
@Test
public void testInitCat() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(100);
for (int i = 0; i < 50; i++) {
Threads.forGroup("cat").start(new InitTask(latch));
latch.countDown();
}
for (int i = 0; i < 50; i++) {
Threads.forGroup("cat").start(new InitWithJobTask(latch));
latch.countDown();
}
Thread.sleep(50 * 1000);
}
public static class InitTask implements Task {
private CountDownLatch m_latch;
public InitTask(CountDownLatch latch) {
m_latch = latch;
}
@Override
public void run() {
try {
m_latch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Transaction t = Cat.newTransaction("test", "test");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.complete();
}
@Override
public String getName() {
return null;
}
@Override
public void shutdown() {
}
}
public static class InitWithJobTask implements Task {
private CountDownLatch m_latch;
public InitWithJobTask(CountDownLatch latch) {
m_latch = latch;
}
@Override
public void run() {
try {
m_latch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Cat.initializeByDomain("cat", "127.0.0.1", "127.0.0.2");
Transaction t = Cat.newTransaction("test", "test");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.complete();
}
@Override
public String getName() {
return null;
}
@Override
public void shutdown() {
}
}
}
| 977 |
4,186 | #define CONFIG_PAGE "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n\
<html>\
<head></head>\
<meta name='viewport' content='width=device-width, initial-scale=1'>\
<body>\
<h1>ESP WiFi NAT Router Config</h1>\
<div id='config'>\
<script>\
if (window.location.search.substr(1) != '')\
{\
document.getElementById('config').display = 'none';\
document.body.innerHTML ='<h1>ESP WiFi NAT Router Config</h1>The new settings have been sent to the device...';\
setTimeout(\"location.href = '/'\",10000);\
}\
</script>\
<h2>STA Settings</h2>\
<form action='' method='GET'>\
<table>\
<tr>\
<td>SSID:</td>\
<td><input type='text' name='ssid' value='%s'/></td>\
</tr>\
<tr>\
<td>Password:</td>\
<td><input type='password' name='password' value='%s'/></td>\
</tr>\
<td>Automesh:</td>\
<td><input type='checkbox' name='am' value='mesh' %s></td>\
</tr>\
<tr>\
<td></td>\
<td><input type='submit' value='Connect'/></td>\
</tr>\
\
</table>\
</form>\
\
<h2>AP Settings</h2>\
<form action='' method='GET'>\
<table>\
<tr>\
<td>SSID:</td>\
<td><input type='text' name='ap_ssid' value='%s'/></td>\
</tr>\
<tr>\
<td>Password:</td>\
<td><input type='text' name='ap_password' value='%s'/></td>\
</tr>\
<tr>\
<td>Security:</td>\
<td>\
<select name='ap_open'>\
<option value='open'%s>Open</option>\
<option value='wpa2'%s>WPA2</option>\
</select>\
</td>\
</tr>\
<tr>\
<td>Subnet:</td>\
<td><input type='text' name='network' value='%d.%d.%d.%d'/></td>\
</tr>\
<tr>\
<td></td>\
<td><input type='submit' value='Set' /></td>\
</tr>\
</table>\
<small>\
<i>Password: </i>min. 8 chars<br />\
</small>\
</form>\
\
<h2>Lock Config</h2>\
<form action='' method='GET'>\
<table>\
<tr>\
<td>Lock Device:</td>\
<td><input type='checkbox' name='lock' value='l'></td>\
</tr>\
<tr>\
<td></td>\
<td><input type='submit' name='dolock' value='Lock'/></td>\
</tr>\
</table>\
</form>\
\
<h2>Device Management</h2>\
<form action='' method='GET'>\
<table>\
<tr>\
<td>Reset Device:</td>\
<td><input type='submit' name='reset' value='Restart'/></td>\
</tr>\
</table>\
</form>\
</div>\
</body>\
</html>\
"
#define LOCK_PAGE "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n\
<html>\
<head></head>\
<meta name='viewport' content='width=device-width, initial-scale=1'>\
<body>\
<h1>ESP WiFi NAT Router Config</h1>\
<div id='config'>\
<script>\
if (window.location.search.substr(1) != '')\
{\
document.getElementById('config').display = 'none';\
document.body.innerHTML ='<h1>ESP WiFi NAT Router Config</h1>Unlock request has been sent to the device...';\
setTimeout(\"location.href = '/'\",1000);\
}\
</script>\
<h2>Config Locked</h2>\
<form autocomplete='off' action='' method='GET'>\
<table>\
<tr>\
<td>Password:</td>\
<td><input type='password' name='unlock_password'/></td>\
</tr>\
<tr>\
<td></td>\
<td><input type='submit' value='Unlock'/></td>\
</tr>\
\
</table>\
<small>\
<i>Default: STA password to unlock<br />\
</small>\
</form>\
</div>\
</body>\
</html>\
"
| 1,304 |
2,338 | <filename>clang/test/SemaCXX/attr-section.cpp
// RUN: %clang_cc1 -verify -fsyntax-only -triple x86_64-linux-gnu %s
int x __attribute__((section(
42))); // expected-error {{'section' attribute requires a string}}
// PR6007
void test() {
__attribute__((section("NEAR,x"))) int n1; // expected-error {{'section' attribute only applies to functions, global variables, Objective-C methods, and Objective-C properties}}
__attribute__((section("NEAR,x"))) static int n2; // ok.
}
// pr9356
void __attribute__((section("foo"))) test2(); // expected-note {{previous attribute is here}}
void __attribute__((section("bar"))) test2() {} // expected-warning {{section does not match previous declaration}}
enum __attribute__((section("NEAR,x"))) e { one }; // expected-error {{'section' attribute only applies to}}
extern int a; // expected-note {{previous declaration is here}}
int *b = &a;
extern int a __attribute__((section("foo,zed"))); // expected-warning {{section attribute is specified on redeclared variable}}
// Not a warning.
extern int c;
int c __attribute__((section("foo,zed")));
// Also OK.
struct r_debug {};
extern struct r_debug _r_debug;
struct r_debug _r_debug __attribute__((nocommon, section(".r_debug,bar")));
namespace override {
struct A {
__attribute__((section("foo"))) virtual void f(){};
};
struct B : A {
void f() {} // ok
};
struct C : A {
__attribute__((section("bar"))) void f(); // expected-note {{previous}}
};
__attribute__((section("baz"))) // expected-warning {{section does not match}}
void C::f() {}
}
// Check for section type conflicts between global variables and function templates
template <typename> __attribute__((section("template_fn1"))) void template_fn1() {} // expected-note {{declared here}}
const int const_global_var __attribute__((section("template_fn1"))) = 42; // expected-error {{'const_global_var' causes a section type conflict with 'template_fn1'}}
int mut_global_var __attribute__((section("template_fn2"))) = 42; // expected-note {{declared here}}
template <typename> __attribute__((section("template_fn2"))) void template_fn2() {} // expected-error {{'template_fn2' causes a section type conflict with 'mut_global_var'}}
| 714 |
4,822 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.common.path;
import org.opensearch.common.path.PathTrie.TrieMatchingMode;
import org.opensearch.rest.RestUtils;
import org.opensearch.test.OpenSearchTestCase;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class PathTrieTests extends OpenSearchTestCase {
public static final PathTrie.Decoder NO_DECODER = new PathTrie.Decoder() {
@Override
public String decode(String value) {
return value;
}
};
public void testPath() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("/a/b/c", "walla");
trie.insert("a/d/g", "kuku");
trie.insert("x/b/c", "lala");
trie.insert("a/x/*", "one");
trie.insert("a/b/*", "two");
trie.insert("*/*/x", "three");
trie.insert("{index}/insert/{docId}", "bingo");
assertThat(trie.retrieve("a/b/c"), equalTo("walla"));
assertThat(trie.retrieve("a/d/g"), equalTo("kuku"));
assertThat(trie.retrieve("x/b/c"), equalTo("lala"));
assertThat(trie.retrieve("a/x/b"), equalTo("one"));
assertThat(trie.retrieve("a/b/d"), equalTo("two"));
assertThat(trie.retrieve("a/b"), nullValue());
assertThat(trie.retrieve("a/b/c/d"), nullValue());
assertThat(trie.retrieve("g/t/x"), equalTo("three"));
Map<String, String> params = new HashMap<>();
assertThat(trie.retrieve("index1/insert/12", params), equalTo("bingo"));
assertThat(params.size(), equalTo(2));
assertThat(params.get("index"), equalTo("index1"));
assertThat(params.get("docId"), equalTo("12"));
}
public void testEmptyPath() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("/", "walla");
assertThat(trie.retrieve(""), equalTo("walla"));
}
public void testDifferentNamesOnDifferentPath() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("/a/{type}", "test1");
trie.insert("/b/{name}", "test2");
Map<String, String> params = new HashMap<>();
assertThat(trie.retrieve("/a/test", params), equalTo("test1"));
assertThat(params.get("type"), equalTo("test"));
params.clear();
assertThat(trie.retrieve("/b/testX", params), equalTo("test2"));
assertThat(params.get("name"), equalTo("testX"));
}
public void testSameNameOnDifferentPath() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("/a/c/{name}", "test1");
trie.insert("/b/{name}", "test2");
Map<String, String> params = new HashMap<>();
assertThat(trie.retrieve("/a/c/test", params), equalTo("test1"));
assertThat(params.get("name"), equalTo("test"));
params.clear();
assertThat(trie.retrieve("/b/testX", params), equalTo("test2"));
assertThat(params.get("name"), equalTo("testX"));
}
public void testPreferNonWildcardExecution() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("{test}", "test1");
trie.insert("b", "test2");
trie.insert("{test}/a", "test3");
trie.insert("b/a", "test4");
trie.insert("{test}/{testB}", "test5");
trie.insert("{test}/x/{testC}", "test6");
Map<String, String> params = new HashMap<>();
assertThat(trie.retrieve("/b", params), equalTo("test2"));
assertThat(trie.retrieve("/b/a", params), equalTo("test4"));
assertThat(trie.retrieve("/v/x", params), equalTo("test5"));
assertThat(trie.retrieve("/v/x/c", params), equalTo("test6"));
}
// https://github.com/elastic/elasticsearch/pull/17916
public void testWildcardMatchingModes() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("{testA}", "test1");
trie.insert("{testA}/{testB}", "test2");
trie.insert("a/{testB}", "test3");
trie.insert("{testA}/b", "test4");
trie.insert("{testA}/b/c", "test5");
trie.insert("a/{testB}/c", "test6");
trie.insert("a/b/{testC}", "test7");
trie.insert("{testA}/b/{testB}", "test8");
trie.insert("x/{testB}/z", "test9");
trie.insert("{testA}/{testB}/{testC}", "test10");
Map<String, String> params = new HashMap<>();
assertThat(trie.retrieve("/a", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), nullValue());
assertThat(trie.retrieve("/a", params, TrieMatchingMode.WILDCARD_ROOT_NODES_ALLOWED), equalTo("test1"));
assertThat(trie.retrieve("/a", params, TrieMatchingMode.WILDCARD_LEAF_NODES_ALLOWED), equalTo("test1"));
assertThat(trie.retrieve("/a", params, TrieMatchingMode.WILDCARD_NODES_ALLOWED), equalTo("test1"));
Iterator<String> allPaths = trie.retrieveAll("/a", () -> params);
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo("test1"));
assertThat(allPaths.next(), equalTo("test1"));
assertThat(allPaths.next(), equalTo("test1"));
assertFalse(allPaths.hasNext());
assertThat(trie.retrieve("/a/b", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), nullValue());
assertThat(trie.retrieve("/a/b", params, TrieMatchingMode.WILDCARD_ROOT_NODES_ALLOWED), equalTo("test4"));
assertThat(trie.retrieve("/a/b", params, TrieMatchingMode.WILDCARD_LEAF_NODES_ALLOWED), equalTo("test3"));
assertThat(trie.retrieve("/a/b", params, TrieMatchingMode.WILDCARD_NODES_ALLOWED), equalTo("test3"));
allPaths = trie.retrieveAll("/a/b", () -> params);
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo("test4"));
assertThat(allPaths.next(), equalTo("test3"));
assertThat(allPaths.next(), equalTo("test3"));
assertFalse(allPaths.hasNext());
assertThat(trie.retrieve("/a/b/c", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), nullValue());
assertThat(trie.retrieve("/a/b/c", params, TrieMatchingMode.WILDCARD_ROOT_NODES_ALLOWED), equalTo("test5"));
assertThat(trie.retrieve("/a/b/c", params, TrieMatchingMode.WILDCARD_LEAF_NODES_ALLOWED), equalTo("test7"));
assertThat(trie.retrieve("/a/b/c", params, TrieMatchingMode.WILDCARD_NODES_ALLOWED), equalTo("test7"));
allPaths = trie.retrieveAll("/a/b/c", () -> params);
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo("test5"));
assertThat(allPaths.next(), equalTo("test7"));
assertThat(allPaths.next(), equalTo("test7"));
assertFalse(allPaths.hasNext());
assertThat(trie.retrieve("/x/y/z", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), nullValue());
assertThat(trie.retrieve("/x/y/z", params, TrieMatchingMode.WILDCARD_ROOT_NODES_ALLOWED), nullValue());
assertThat(trie.retrieve("/x/y/z", params, TrieMatchingMode.WILDCARD_LEAF_NODES_ALLOWED), nullValue());
assertThat(trie.retrieve("/x/y/z", params, TrieMatchingMode.WILDCARD_NODES_ALLOWED), equalTo("test9"));
allPaths = trie.retrieveAll("/x/y/z", () -> params);
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo("test9"));
assertFalse(allPaths.hasNext());
assertThat(trie.retrieve("/d/e/f", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), nullValue());
assertThat(trie.retrieve("/d/e/f", params, TrieMatchingMode.WILDCARD_ROOT_NODES_ALLOWED), nullValue());
assertThat(trie.retrieve("/d/e/f", params, TrieMatchingMode.WILDCARD_LEAF_NODES_ALLOWED), nullValue());
assertThat(trie.retrieve("/d/e/f", params, TrieMatchingMode.WILDCARD_NODES_ALLOWED), equalTo("test10"));
allPaths = trie.retrieveAll("/d/e/f", () -> params);
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo(null));
assertThat(allPaths.next(), equalTo("test10"));
assertFalse(allPaths.hasNext());
}
// https://github.com/elastic/elasticsearch/pull/17916
public void testExplicitMatchingMode() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("{testA}", "test1");
trie.insert("a", "test2");
trie.insert("{testA}/{testB}", "test3");
trie.insert("a/{testB}", "test4");
trie.insert("{testA}/b", "test5");
trie.insert("a/b", "test6");
trie.insert("{testA}/b/{testB}", "test7");
trie.insert("x/{testA}/z", "test8");
trie.insert("{testA}/{testB}/{testC}", "test9");
trie.insert("a/b/c", "test10");
Map<String, String> params = new HashMap<>();
assertThat(trie.retrieve("/a", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), equalTo("test2"));
assertThat(trie.retrieve("/x", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), nullValue());
assertThat(trie.retrieve("/a/b", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), equalTo("test6"));
assertThat(trie.retrieve("/a/x", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), nullValue());
assertThat(trie.retrieve("/a/b/c", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), equalTo("test10"));
assertThat(trie.retrieve("/x/y/z", params, TrieMatchingMode.EXPLICIT_NODES_ONLY), nullValue());
}
public void testSamePathConcreteResolution() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("{x}/{y}/{z}", "test1");
trie.insert("{x}/_y/{k}", "test2");
Map<String, String> params = new HashMap<>();
assertThat(trie.retrieve("/a/b/c", params), equalTo("test1"));
assertThat(params.get("x"), equalTo("a"));
assertThat(params.get("y"), equalTo("b"));
assertThat(params.get("z"), equalTo("c"));
params.clear();
assertThat(trie.retrieve("/a/_y/c", params), equalTo("test2"));
assertThat(params.get("x"), equalTo("a"));
assertThat(params.get("k"), equalTo("c"));
}
public void testNamedWildcardAndLookupWithWildcard() {
PathTrie<String> trie = new PathTrie<>(NO_DECODER);
trie.insert("x/{test}", "test1");
trie.insert("{test}/a", "test2");
trie.insert("/{test}", "test3");
trie.insert("/{test}/_endpoint", "test4");
trie.insert("/*/{test}/_endpoint", "test5");
Map<String, String> params = new HashMap<>();
assertThat(trie.retrieve("/x/*", params), equalTo("test1"));
assertThat(params.get("test"), equalTo("*"));
params = new HashMap<>();
assertThat(trie.retrieve("/b/a", params), equalTo("test2"));
assertThat(params.get("test"), equalTo("b"));
params = new HashMap<>();
assertThat(trie.retrieve("/*", params), equalTo("test3"));
assertThat(params.get("test"), equalTo("*"));
params = new HashMap<>();
assertThat(trie.retrieve("/*/_endpoint", params), equalTo("test4"));
assertThat(params.get("test"), equalTo("*"));
params = new HashMap<>();
assertThat(trie.retrieve("a/*/_endpoint", params), equalTo("test5"));
assertThat(params.get("test"), equalTo("*"));
}
// https://github.com/elastic/elasticsearch/issues/14177
// https://github.com/elastic/elasticsearch/issues/13665
public void testEscapedSlashWithinUrl() {
PathTrie<String> pathTrie = new PathTrie<>(RestUtils.REST_DECODER);
pathTrie.insert("/{index}/{type}/{id}", "test");
HashMap<String, String> params = new HashMap<>();
assertThat(pathTrie.retrieve("/index/type/a%2Fe", params), equalTo("test"));
assertThat(params.get("index"), equalTo("index"));
assertThat(params.get("type"), equalTo("type"));
assertThat(params.get("id"), equalTo("a/e"));
params.clear();
assertThat(pathTrie.retrieve("/<logstash-{now%2Fd}>/type/id", params), equalTo("test"));
assertThat(params.get("index"), equalTo("<logstash-{now/d}>"));
assertThat(params.get("type"), equalTo("type"));
assertThat(params.get("id"), equalTo("id"));
}
}
| 5,864 |
892 | <reponame>westonsteimel/advisory-database-github<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-6w2f-q3rq-jh8v",
"modified": "2022-01-08T00:00:35Z",
"published": "2021-12-31T00:00:33Z",
"aliases": [
"CVE-2021-20156"
],
"details": "Trendnet AC2600 TEW-827DRU version 2.08B01 contains an improper access control configuration that could allow for a malicious firmware update. It is possible to manually install firmware that may be malicious in nature as there does not appear to be any signature validation done to determine if it is from a known and trusted source. This includes firmware updates that are done via the automated \"check for updates\" in the admin interface. If an attacker is able to masquerade as the update server, the device will not verify that the firmware updates downloaded are legitimate.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20156"
},
{
"type": "WEB",
"url": "https://www.tenable.com/security/research/tra-2021-54"
}
],
"database_specific": {
"cwe_ids": [
"CWE-347"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 454 |
2,112 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef incl_THRIFT_MUTEX_PORTABILITY_H
#define incl_THRIFT_MUTEX_PORTABILITY_H
#ifdef THRIFT_MUTEX_EMULATE_PTHREAD_TIMEDLOCK
/* Backport of pthread_*_timed*lock() */
template <class MutexType>
inline int thrift_pthread_timedlock_impl(
MutexType* mutex,
const timespec* ts,
int (*lockfunc)(MutexType*),
int (*trylockfunc)(MutexType*)) {
if (!ts || ((ts->tv_sec == 0) && (ts->tv_nsec == 0))) {
return lockfunc(mutex);
}
timespec waiting = *ts;
timespec delay;
// Use a wait of 1/20th the total time to block between trylock calls.
delay.tv_sec = waiting.tv_sec / 20;
delay.tv_nsec = ((waiting.tv_sec % 20) * 50000000) + (waiting.tv_nsec / 20);
do {
auto ret = trylockfunc(mutex);
if (ret != EBUSY) {
return ret;
}
if ((delay.tv_sec > waiting.tv_sec) ||
((delay.tv_sec == waiting.tv_sec) &&
(delay.tv_nsec > waiting.tv_nsec))) {
// Less than delay-time left to wait
delay = waiting;
}
timespec rem;
if (nanosleep(&delay, &rem)) {
// nanosleep was interrupted,
// put the remainder back on before subtracting the delay
if (1000000000 - waiting.tv_nsec < rem.tv_nsec) {
++waiting.tv_sec;
waiting.tv_nsec = rem.tv_nsec - (1000000000 - waiting.tv_nsec);
} else {
waiting.tv_nsec += rem.tv_nsec;
}
waiting.tv_sec += rem.tv_sec;
}
if (delay.tv_nsec > waiting.tv_nsec) {
--waiting.tv_sec;
waiting.tv_nsec = 1000000000 - (delay.tv_nsec - waiting.tv_nsec);
} else {
waiting.tv_nsec -= delay.tv_nsec;
}
waiting.tv_sec -= delay.tv_sec;
} while ((waiting.tv_sec > 0) || (waiting.tv_nsec > 0));
return EBUSY;
}
inline int pthread_mutex_timedlock(pthread_mutex_t* mutex, const timespec* ts) {
return thrift_pthread_timedlock_impl(
mutex, ts, pthread_mutex_lock, pthread_mutex_trylock);
}
inline int pthread_rwlock_timedwrlock(
pthread_rwlock_t* rwlock, const timespec* ts) {
return thrift_pthread_timedlock_impl(
rwlock, ts, pthread_rwlock_wrlock, pthread_rwlock_trywrlock);
}
inline int pthread_rwlock_timedrdlock(
pthread_rwlock_t* rwlock, const timespec* ts) {
return thrift_pthread_timedlock_impl(
rwlock, ts, pthread_rwlock_rdlock, pthread_rwlock_tryrdlock);
}
#endif // THRIFT_MUTEX_EMULATE_PTHREAD_TIMEDLOCK
#endif // incl_THRIFT_MUTEX_PORTABILITY_H
| 1,216 |
474 | <reponame>HeraShowFeng/PLShortVideoKit
//
// TuSDKMediaAssetExtractorPitch.h
// TuSDKVideo
//
// Created by sprint on 2019/8/7.
// Copyright © 2019 TuSDK. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
低帧率视频补帧补丁
@since v3.4.2
*/
@interface TuSDKMediaAssetExtractorPitch : NSObject
/**
上一帧视频输出时间
@since v3.4.2
*/
@property (nonatomic) CMTime preOutputPresentationTimeStamp;
/**
最小帧间隔,使用此字段确定输出帧率
@since v3.4.2
*/
@property (nonatomic) CMTime frameDuration;
/**
原视频的平均帧间隔时长,用于对第一帧时长过长时的补帧
@since v3.4.6
*/
@property (nonatomic) CMTime naturalFrameDuration;
/**
是否需要该补丁
@since v3.4.2
*/
@property (nonatomic,readonly) BOOL needPitch;
/**
设置当前输出视频帧 会与 preOutputPresentationTimeStamp 比较确定是否需要补帧
@since v3.4.2
*/
@property (nonatomic) CMSampleBufferRef outputSampleBuffer;
/**
重置补丁
@since v3.4.2
*/
- (void)reset;
@end
NS_ASSUME_NONNULL_END
| 536 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.wizards;
import java.awt.Dimension;
import org.netbeans.api.j2ee.core.Profile;
import org.openide.util.NbBundle;
import org.netbeans.modules.web.api.webmodule.WebModule;
/** A single panel for a wizard - the GUI portion.
*
* @author mk115033
*/
public class TagHandlerPanel extends javax.swing.JPanel {
/** The wizard panel descriptor associated with this GUI panel.
* If you need to fire state changes or something similar, you can
* use this handle to do so.
*/
private TagHandlerSelection wizardPanel;
private Profile j2eeVersion;
/** Create the wizard panel and set up some basic properties. */
public TagHandlerPanel(TagHandlerSelection wizardPanel, Profile j2eeVersion) {
this.wizardPanel=wizardPanel;
this.j2eeVersion=j2eeVersion;
initComponents();
// Provide a name in the title bar.
setName(NbBundle.getMessage(TagHandlerPanel.class, "TITLE_tagHandlerPanel"));
if (Profile.J2EE_13.equals(j2eeVersion)) {
simpleTagButton.setEnabled(false);
bodyTagButton.setSelected(true);
} else {
simpleTagButton.setSelected(true);
}
/*
// Optional: provide a special description for this pane.
// You must have turned on WizardDescriptor.WizardPanel_helpDisplayed
// (see descriptor in standard iterator template for an example of this).
try {
putClientProperty (WizardDescriptor.PROP_HELP_URL, // NOI18N
new URL ("nbresloc:/org/netbeans/modules/web/wizards/TagHandlerHelp.html")); // NOI18N
} catch (MalformedURLException mfue) {
throw new IllegalStateException (mfue.toString ());
}
*/
// a11y part
//issue #84131
int height = jLabel1.getFontMetrics(jLabel1.getFont()).getHeight() * 6 + 35;
if (height > this.getHeight()) {
Dimension dim = new Dimension(this.getWidth(), height);
setMinimumSize(dim);
setPreferredSize(dim);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
simpleTagButton = new javax.swing.JRadioButton();
bodyTagButton = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
descriptionArea = new javax.swing.JTextArea();
setRequestFocusEnabled(false);
setLayout(new java.awt.GridBagLayout());
buttonGroup1.add(simpleTagButton);
simpleTagButton.setMnemonic(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "LBL_SimpleTag_Mnemonic").charAt(0));
simpleTagButton.setText(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "OPT_SimpleTag")); // NOI18N
simpleTagButton.setMargin(new java.awt.Insets(2, 2, 0, 2));
simpleTagButton.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
TagHandlerPanel.this.itemStateChanged(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
add(simpleTagButton, gridBagConstraints);
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/netbeans/modules/web/wizards/Bundle"); // NOI18N
simpleTagButton.getAccessibleContext().setAccessibleDescription(bundle.getString("DESC_SimpleTag")); // NOI18N
buttonGroup1.add(bodyTagButton);
bodyTagButton.setMnemonic(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "LBL_BodyTag_Mnemonic").charAt(0));
bodyTagButton.setText(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "OPT_BodyTag")); // NOI18N
bodyTagButton.setMargin(new java.awt.Insets(0, 2, 2, 2));
bodyTagButton.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
TagHandlerPanel.this.itemStateChanged(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
add(bodyTagButton, gridBagConstraints);
bodyTagButton.getAccessibleContext().setAccessibleDescription(bundle.getString("DESC_BodyTag")); // NOI18N
jLabel1.setText(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "LBL_TagSupportClass")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0);
add(jLabel1, gridBagConstraints);
jLabel2.setDisplayedMnemonic(java.util.ResourceBundle.getBundle("org/netbeans/modules/web/wizards/Bundle").getString("A11Y_Description_mnem").charAt(0));
jLabel2.setLabelFor(descriptionArea);
jLabel2.setText(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "LBL_description")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 0);
add(jLabel2, gridBagConstraints);
descriptionArea.setEditable(false);
descriptionArea.setLineWrap(true);
descriptionArea.setText(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "DESC_SimpleTag")); // NOI18N
descriptionArea.setWrapStyleWord(true);
jScrollPane1.setViewportView(descriptionArea);
descriptionArea.getAccessibleContext().setAccessibleDescription(bundle.getString("A11Y_DESC_Description")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 6);
add(jScrollPane1, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void itemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_itemStateChanged
if (simpleTagButton.isSelected())
descriptionArea.setText(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "DESC_SimpleTag"));
else
descriptionArea.setText(org.openide.util.NbBundle.getMessage(TagHandlerPanel.class, "DESC_BodyTag"));
wizardPanel.fireChangeEvent();
}//GEN-LAST:event_itemStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JRadioButton bodyTagButton;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JTextArea descriptionArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JRadioButton simpleTagButton;
// End of variables declaration//GEN-END:variables
boolean isBodyTagSupport() {
return bodyTagButton.isSelected();
}
}
| 3,662 |
325 | <filename>webapp/src/main/java/com/box/l10n/mojito/service/branch/notification/job/BranchNotificationJobInput.java<gh_stars>100-1000
package com.box.l10n.mojito.service.branch.notification.job;
public class BranchNotificationJobInput {
Long branchId;
public Long getBranchId() {
return branchId;
}
public void setBranchId(Long branchId) {
this.branchId = branchId;
}
}
| 162 |
867 | <gh_stars>100-1000
/*
* $Id: LuaException.java,v 1.6 2006/12/22 14:06:40 thiago Exp $
* Copyright (C) 2003-2007 Kepler Project.
*
* 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.keplerproject.luajava;
/**
* LuaJava exception
*
* @author <NAME>
*
*/
public class LuaException extends Exception
{
/**
*
*/
private static final long serialVersionUID = 1L;
public LuaException(String str)
{
super(str);
}
/**
* Will work only on Java 1.4 or later.
* To work with Java 1.3, comment the first line and uncomment the second one.
*/
public LuaException(Exception e)
{
super((e.getCause() != null) ? e.getCause() : e);
//super(e.getMessage());
}
} | 565 |
30,023 | <reponame>domwillcode/home-assistant
"""Tests for the Nest component."""
| 24 |
1,627 | <reponame>Floboy/PyWebIO<gh_stars>1000+
import subprocess
import time
from selenium.webdriver import Chrome
import pywebio
import template
import util
from pywebio.input import *
from pywebio.utils import to_coroutine, run_as_function
def target():
template.basic_output()
template.background_output()
run_as_function(template.basic_input())
actions(buttons=['Continue'])
template.background_input()
async def async_target():
template.basic_output()
await template.coro_background_output()
await to_coroutine(template.basic_input())
await actions(buttons=['Continue'])
await template.coro_background_input()
def test(server_proc: subprocess.Popen, browser: Chrome):
template.test_output(browser)
time.sleep(1)
template.test_input(browser)
time.sleep(1)
template.save_output(browser, '15.tornado_http_multiple_session_p1.html')
browser.get('http://localhost:8080/?_pywebio_debug=1&_pywebio_http_pull_interval=400&app=p2')
template.test_output(browser)
time.sleep(1)
template.test_input(browser)
time.sleep(1)
template.save_output(browser, '15.tornado_http_multiple_session_p2.html')
def start_test_server():
pywebio.enable_debug()
from pywebio.platform.tornado_http import start_server
start_server({'p1': target, 'p2': async_target}, port=8080, host='127.0.0.1', cdn=False)
if __name__ == '__main__':
util.run_test(start_test_server, test,
address='http://localhost:8080/?_pywebio_debug=1&_pywebio_http_pull_interval=400&app=p1')
| 593 |
1,091 | /*
* Copyright 2016-present Open Networking Foundation
*
* 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.onosproject.ui.model.topo;
import org.junit.Test;
import org.onosproject.net.DeviceId;
import org.onosproject.net.region.RegionId;
import org.onosproject.ui.model.AbstractUiModelTest;
import static org.junit.Assert.assertEquals;
import static org.onosproject.net.DeviceId.deviceId;
import static org.onosproject.net.PortNumber.P0;
import static org.onosproject.net.region.RegionId.regionId;
/**
* Unit tests for {@link UiRegionDeviceLink}.
*/
public class UiRegionDeviceLinkTest extends AbstractUiModelTest {
private static final RegionId R1 = regionId("r1");
private static final DeviceId DEV_X = deviceId("device-X");
@Test
public void basic() {
title("basic");
UiLinkId id = UiLinkId.uiLinkId(R1, DEV_X, P0);
UiRegionDeviceLink link = new UiRegionDeviceLink(null, id);
print(link);
assertEquals("region", R1, link.region());
assertEquals("device", DEV_X, link.device());
assertEquals("port", P0, link.port());
}
}
| 542 |
380 | <reponame>geralltf/mini-tor
#pragma once
#include <mini/string.h>
#include <mini/ctl.h>
#include <winsock2.h>
namespace mini::net {
class ip_address
{
public:
constexpr ip_address(
void
) = default;
constexpr ip_address(
const ip_address& other
) = default;
constexpr ip_address(
ip_address&& other
) = default;
constexpr ip_address(
uint32_t value
)
: _ip(value)
{
}
ip_address(
const string_ref value
)
: _ip(inet_addr(value.get_buffer()))
{
}
ip_address&
operator=(
const ip_address& other
) = default;
ip_address&
operator=(
ip_address&& other
) = default;
static constexpr ip_address
from_int(
uint32_t value
)
{
return ip_address(value);
}
static constexpr ip_address
from_string(
const char* value
)
{
return ip_address(ip_string_to_int(value));
}
static constexpr uint32_t
to_int(
const char* value
)
{
return ip_string_to_int(value);
}
string
to_string(
void
) const
{
return string(inet_ntoa(to_in_addr()));
}
in_addr
to_in_addr(
void
) const
{
in_addr result;
result.S_un.S_addr = _ip;
return result;
}
constexpr uint32_t
to_int(
void
) const
{
return _ip;
}
private:
static constexpr uint32_t
ip_string_to_int(
const char* value
)
{
return
static_cast<uint32_t>(ctl::atoi(value)) |
static_cast<uint32_t>(ctl::atoi(ctl::strchr(value, '.') + 1)) << 8 |
static_cast<uint32_t>(ctl::atoi(ctl::strchr(ctl::strchr(value, '.') + 1, '.') + 1)) << 16 |
static_cast<uint32_t>(ctl::atoi(ctl::strchr(ctl::strchr(ctl::strchr(value, '.') + 1, '.') + 1, '.') + 1)) << 24;
}
uint32_t _ip = 0;
};
}
| 977 |
324 | /**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef UTIL_HISTOGRAM_HEADER
#define UTIL_HISTOGRAM_HEADER
#include <string>
#include <stdint.h>
namespace mongo {
/**
* A histogram for a 32-bit integer range.
*/
class Histogram {
public:
/**
* Construct a histogram with 'numBuckets' buckets, optionally
* having the first bucket start at 'initialValue' rather than
* 0. By default, the histogram buckets will be 'bucketSize' wide.
*
* Usage example:
* Histogram::Options opts;
* opts.numBuckets = 3;
* opts.bucketSize = 10;
* Histogram h( opts );
*
* Generates the bucket ranges [0..10],[11..20],[21..max_int]
*
* Alternatively, the flag 'exponential' could be turned on, in
* which case a bucket's maximum value will be
* initialValue + bucketSize * 2 ^ [0..numBuckets-1]
*
* Usage example:
* Histogram::Options opts;
* opts.numBuckets = 4;
* opts.bucketSize = 125;
* opts.exponential = true;
* Histogram h( opts );
*
* Generates the bucket ranges [0..125],[126..250],[251..500],[501..max_int]
*/
struct Options {
uint32_t numBuckets;
uint32_t bucketSize;
uint32_t initialValue;
// use exponential buckets?
bool exponential;
Options()
: numBuckets(0)
, bucketSize(0)
, initialValue(0)
, exponential(false) {}
};
explicit Histogram( const Options& opts );
~Histogram();
/**
* Find the bucket that 'element' falls into and increment its count.
*/
void insert( uint32_t element );
/**
* Render the histogram as string that can be used inside an
* HTML doc.
*/
std::string toHTML() const;
// testing interface below -- consider it private
/**
* Return the count for the 'bucket'-th bucket.
*/
uint64_t getCount( uint32_t bucket ) const;
/**
* Return the maximum element that would fall in the
* 'bucket'-th bucket.
*/
uint32_t getBoundary( uint32_t bucket ) const;
/**
* Return the number of buckets in this histogram.
*/
uint32_t getBucketsNum() const;
private:
/**
* Returns the bucket where 'element' should fall
* into. Currently assumes that 'element' is greater than the
* minimum 'inialValue'.
*/
uint32_t _findBucket( uint32_t element ) const;
uint32_t _initialValue; // no value lower than it is recorded
uint32_t _numBuckets; // total buckets in the histogram
// all below owned here
uint32_t* _boundaries; // maximum element of each bucket
uint64_t* _buckets; // current count of each bucket
Histogram( const Histogram& );
Histogram& operator=( const Histogram& );
};
} // namespace mongo
#endif // UTIL_HISTOGRAM_HEADER
| 1,685 |
1,053 | <filename>tos/lib/tosthreads/chips/m16c60/chip_thread.h
/*
* Copyright (c) 2009 Communication Group and Eislab at
* Lulea University of Technology
*
* Contact: <NAME>, LTU
* Mail: <EMAIL>
* 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 Communication Group at Lulea University of Technology
* nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANFORD
* UNIVERSITY OR ITS 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.
*/
/*
* Copyright (c) 2008 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
* - Neither the name of the Stanford University nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE 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 STANFORD
* UNIVERSITY OR ITS 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.
*/
/**
* This file contains M16c/60 mcu-specific routines for implementing
* threads in TinyOS
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
typedef struct thread_regs {
uint16_t r0;
uint16_t r1;
uint16_t r2;
uint16_t r3;
uint16_t a0;
uint16_t a1;
uint16_t fb;
uint16_t flg;
uint16_t mem0;
uint16_t mem2;
uint16_t mem4;
uint16_t mem6;
uint16_t mem8;
uint16_t mem10;
uint16_t mem12;
uint16_t mem14;
} thread_regs_t;
/**
* Memory is addressed by 16 bits on M16c/60 but because
* is can be addressed in 8 bit units we typedef the
* stack pointer as a uint8_t.
*/
typedef uint8_t* stack_ptr_t;
#define STACK_TOP(stack, size) \
(&(((uint8_t*)stack)[size - 1]))
//Save stack pointer
#define SAVE_STACK_PTR(t) \
asm volatile ("stc sp, %0": "=r"(t->stack_ptr));
//Save status register
#define SAVE_STATUS(t) \
asm volatile ("stc flg, %0": "=r"(t->regs.flg));
//Save General Purpose Registers
#define SAVE_GPR(t) \
asm volatile ("mov.w r0, %0 \n\t" : "=r" ((t)->regs.r0) : ); \
asm volatile ("mov.w r1, %0 \n\t" : "=r" ((t)->regs.r1) : ); \
asm volatile ("mov.w r2, %0 \n\t" : "=r" ((t)->regs.r2) : ); \
asm volatile ("mov.w r3, %0 \n\t" : "=r" ((t)->regs.r3) : ); \
asm volatile ("mov.w a0, %0 \n\t" : "=r" ((t)->regs.a0) : ); \
asm volatile ("mov.w a1, %0 \n\t" : "=r" ((t)->regs.a1) : ); \
asm volatile ("stc fb, %0 \n\t" : "=r" ((t)->regs.fb) : ); \
asm volatile ("mov.w mem0, %0 \n\t" : "=r" ((t)->regs.mem0) : ); \
asm volatile ("mov.w mem2, %0 \n\t" : "=r" ((t)->regs.mem2) : ); \
asm volatile ("mov.w mem4, %0 \n\t" : "=r" ((t)->regs.mem4) : ); \
asm volatile ("mov.w mem6, %0 \n\t" : "=r" ((t)->regs.mem6) : ); \
asm volatile ("mov.w mem8, %0 \n\t" : "=r" ((t)->regs.mem8) : ); \
asm volatile ("mov.w mem10, %0 \n\t" : "=r" ((t)->regs.mem10) : ); \
asm volatile ("mov.w mem12, %0 \n\t" : "=r" ((t)->regs.mem12) : ); \
asm volatile ("mov.w mem14, %0 \n\t" : "=r" ((t)->regs.mem14) : );
//Restore stack pointer
#define RESTORE_STACK_PTR(t) \
asm volatile ("ldc %0, sp \n\t" :: "r" ((t)->stack_ptr))
//Restore status register
#define RESTORE_STATUS(t) \
asm volatile ("ldc %0, flg \n\t" :: "r" (t->regs.flg) );
//Restore the general purpose registers
#define RESTORE_GPR(t) \
asm volatile ("mov.w %0, r0 \n\t" :: "r" ((t)->regs.r0) ); \
asm volatile ("mov.w %0, r1 \n\t" :: "r" ((t)->regs.r1) ); \
asm volatile ("mov.w %0, r2 \n\t" :: "r" ((t)->regs.r2) ); \
asm volatile ("mov.w %0, r3 \n\t" :: "r" ((t)->regs.r3) ); \
asm volatile ("mov.w %0, a0 \n\t" :: "r" ((t)->regs.a0) ); \
asm volatile ("mov.w %0, a1 \n\t" :: "r" ((t)->regs.a1) ); \
asm volatile ("ldc %0, fb \n\t" :: "r" ((t)->regs.fb) ); \
asm volatile ("mov.w %0, mem0 \n\t" :: "r" ((t)->regs.mem0) ); \
asm volatile ("mov.w %0, mem2 \n\t" :: "r" ((t)->regs.mem2) ); \
asm volatile ("mov.w %0, mem4 \n\t" :: "r" ((t)->regs.mem4) ); \
asm volatile ("mov.w %0, mem6 \n\t" :: "r" ((t)->regs.mem6) ); \
asm volatile ("mov.w %0, mem8 \n\t" :: "r" ((t)->regs.mem8) ); \
asm volatile ("mov.w %0, mem10 \n\t" :: "r" ((t)->regs.mem10) ); \
asm volatile ("mov.w %0, mem12 \n\t" :: "r" ((t)->regs.mem12) ); \
asm volatile ("mov.w %0, mem14 \n\t" :: "r" ((t)->regs.mem14) );
#define SAVE_TCB(t) \
SAVE_GPR(t); \
SAVE_STATUS(t); \
SAVE_STACK_PTR(t)
#define RESTORE_TCB(t) \
RESTORE_STACK_PTR(t); \
RESTORE_STATUS(t); \
RESTORE_GPR(t)
#define SWITCH_CONTEXTS(from, to) \
SAVE_TCB(from); \
RESTORE_TCB(to)
#define PREPARE_THREAD(t, start_function) \
t->stack_ptr[0] = 0; \
t->stack_ptr[-1] = (uint8_t)((uint16_t)&start_function >> 8) & 0xFF; \
t->stack_ptr[-2] = (uint8_t)((uint16_t)&start_function) & 0xFF; \
t->stack_ptr -= 2; \
SAVE_STATUS(t)
| 3,053 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.debugger.jpda.truffle.source;
import org.netbeans.api.debugger.jpda.JPDADebugger;
/**
* A script source position.
*/
public class SourcePosition {
private final long id;
private final Source src;
private final int startLine;
private final int startColumn;
private final int endLine;
private final int endColumn;
public SourcePosition(JPDADebugger debugger, long id, Source src, String sourceSection) {
this.id = id;
this.src = src;
int i1 = 0, i2 = sourceSection.indexOf(',');
this.startLine = Integer.parseInt(sourceSection.substring(i1, i2));
i1 = i2 + 1;
i2 = sourceSection.indexOf(',', i1);
this.startColumn = Integer.parseInt(sourceSection.substring(i1, i2));
i1 = i2 + 1;
i2 = sourceSection.indexOf(',', i1);
this.endLine = Integer.parseInt(sourceSection.substring(i1, i2));
i1 = i2 + 1;
this.endColumn = Integer.parseInt(sourceSection.substring(i1));
}
public Source getSource() {
return src;
}
public int getStartLine() {
return startLine;
}
public int getStartColumn() {
return startColumn;
}
public int getEndLine() {
return endLine;
}
public int getEndColumn() {
return endColumn;
}
}
| 761 |
2,360 | <reponame>kkauder/spack
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
import llnl.util.tty as tty
from llnl.util.filesystem import mkdirp, working_dir
import spack.paths
from spack.util.executable import ProcessError, which
_SPACK_UPSTREAM = 'https://github.com/spack/spack'
description = "create a new installation of spack in another prefix"
section = "admin"
level = "long"
def setup_parser(subparser):
subparser.add_argument(
'-r', '--remote', action='store', dest='remote',
help="name of the remote to clone from", default='origin')
subparser.add_argument(
'prefix',
help="name of prefix where we should install spack")
def get_origin_info(remote):
git_dir = os.path.join(spack.paths.prefix, '.git')
git = which('git', required=True)
try:
branch = git('symbolic-ref', '--short', 'HEAD', output=str)
except ProcessError:
branch = 'develop'
tty.warn('No branch found; using default branch: %s' % branch)
if remote == 'origin' and \
branch not in ('master', 'develop'):
branch = 'develop'
tty.warn('Unknown branch found; using default branch: %s' % branch)
try:
origin_url = git(
'--git-dir=%s' % git_dir,
'config', '--get', 'remote.%s.url' % remote,
output=str)
except ProcessError:
origin_url = _SPACK_UPSTREAM
tty.warn('No git repository found; '
'using default upstream URL: %s' % origin_url)
return (origin_url.strip(), branch.strip())
def clone(parser, args):
origin_url, branch = get_origin_info(args.remote)
prefix = args.prefix
tty.msg("Fetching spack from '%s': %s" % (args.remote, origin_url))
if os.path.isfile(prefix):
tty.die("There is already a file at %s" % prefix)
mkdirp(prefix)
if os.path.exists(os.path.join(prefix, '.git')):
tty.die("There already seems to be a git repository in %s" % prefix)
files_in_the_way = os.listdir(prefix)
if files_in_the_way:
tty.die("There are already files there! "
"Delete these files before boostrapping spack.",
*files_in_the_way)
tty.msg("Installing:",
"%s/bin/spack" % prefix,
"%s/lib/spack/..." % prefix)
with working_dir(prefix):
git = which('git', required=True)
git('init', '--shared', '-q')
git('remote', 'add', 'origin', origin_url)
git('fetch', 'origin', '%s:refs/remotes/origin/%s' % (branch, branch),
'-n', '-q')
git('reset', '--hard', 'origin/%s' % branch, '-q')
git('checkout', '-B', branch, 'origin/%s' % branch, '-q')
tty.msg("Successfully created a new spack in %s" % prefix,
"Run %s/bin/spack to use this installation." % prefix)
| 1,255 |
324 | /*
* 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.jclouds.azurecompute.arm.compute.extensions;
import static org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions.Builder.resourceGroup;
import static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.net.URI;
import java.util.Map;
import java.util.Properties;
import org.jclouds.azurecompute.arm.AzureComputeApi;
import org.jclouds.azurecompute.arm.AzureComputeProviderMetadata;
import org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;
import org.jclouds.compute.ComputeTestUtils;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;
import org.jclouds.domain.Location;
import org.jclouds.providers.ProviderMetadata;
import org.jclouds.sshj.config.SshjSshClientModule;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
/**
* Live tests for the {@link org.jclouds.compute.extensions.ImageExtension}
* integration.
*/
@Test(groups = "live", singleThreaded = true, testName = "AzureComputeImageExtensionLiveTest")
public class AzureComputeImageExtensionLiveTest extends BaseImageExtensionLiveTest {
private Predicate<URI> resourceDeleted;
private String resourceGroupName;
public AzureComputeImageExtensionLiveTest() {
provider = "azurecompute-arm";
resourceGroupName = getClass().getSimpleName().toLowerCase();
}
@BeforeClass(groups = { "integration", "live" })
public void setupContext() {
super.setupContext();
resourceDeleted = context.utils().injector().getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {
}, Names.named(TIMEOUT_RESOURCE_DELETED)));
createResourceGroup(resourceGroupName);
}
@AfterClass(groups = { "integration", "live" })
@Override
protected void tearDownContext() {
try {
URI uri = view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().delete(resourceGroupName);
if (uri != null) {
assertTrue(resourceDeleted.apply(uri),
String.format("Resource %s was not terminated in the configured timeout", uri));
}
} finally {
super.tearDownContext();
}
}
@Override
protected void prepareNodeBeforeCreatingImage(NodeMetadata node) {
// Don't wrap in the init-script, since the comand will clear the user
// config, and jclouds won't be able to execute more than one command
// (won't be able to poll for the execution status of the command when
// running with the init-script)
ExecResponse result = view.getComputeService().runScriptOnNode(node.getId(), "waagent -deprovision+user -force",
wrapInInitScript(false));
assertEquals(result.getExitStatus(), 0);
}
@Override
protected Module getSshModule() {
return new SshjSshClientModule();
}
@Override
protected Properties setupProperties() {
Properties properties = super.setupProperties();
AzureLiveTestUtils.defaultProperties(properties);
setIfTestSystemPropertyPresent(properties, "oauth.endpoint");
return properties;
}
@Override
protected ProviderMetadata createProviderMetadata() {
return AzureComputeProviderMetadata.builder().build();
}
@Override
public TemplateBuilder getNodeTemplate() {
Map<String, String> keyPair = ComputeTestUtils.setupKeyPair();
return super.getNodeTemplate().options(
resourceGroup(resourceGroupName).authorizePublicKey(keyPair.get("public")).overrideLoginPrivateKey(
keyPair.get("private")));
}
private void createResourceGroup(String name) {
Location location = getNodeTemplate().build().getLocation();
view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(name, location.getId(), null);
}
}
| 1,706 |
597 | """Validate services schema."""
import voluptuous as vol
from .const import ATTR_IGNORE_CONDITIONS, JobCondition
SCHEMA_JOBS_CONFIG = vol.Schema(
{
vol.Optional(ATTR_IGNORE_CONDITIONS, default=list): [vol.Coerce(JobCondition)],
},
extra=vol.REMOVE_EXTRA,
)
| 115 |
479 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=E1102
# python3
"""Retrieves customer data from our companies "internal" customer data serivce.
This data service is meant to be illustrative for demo purposes, as its just
hard coded data. This can be any internal or on-premise data store.
"""
class CustomerDataService(object):
_CUSTOMER_DATA = {
'mars': {
'customer_name': '<NAME>.',
'customer_logo':
'https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/' +
'OSIRIS_Mars_true_color.jpg/550px-OSIRIS_Mars_true_color.jpg',
'curr_q': 'Q2',
'curr_q_total_sales': '$2,532,124',
'curr_q_qoq': '0.054',
'prev_q': 'Q1',
'prev_q_total_sales': '$2,413,584',
'next_q': 'Q3',
'next_q_total_sales_proj': '$2,634,765',
'next_q_qoq_proj': '0.041',
'top1_sku': 'Phobos',
'top1_sales': '$334,384',
'top2_sku': 'Deimos',
'top2_sales': '$315,718',
'top3_sku': 'Charon',
'top3_sales': '$285,727',
'top4_sku': 'Nix',
'top4_sales': '$264,023',
'top5_sku': 'Hydra',
'top5_sales': '$212,361',
},
'jupiter': {
'customer_name': '<NAME>',
'customer_logo':
'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/' +
'Jupiter_and_its_shrunken_Great_Red_Spot.jpg/660px-Jupiter_' +
'and_its_shrunken_Great_Red_Spot.jpg',
'curr_q': 'Q2',
'curr_q_total_sales': '$1,532,124',
'curr_q_qoq': '0.031',
'prev_q': 'Q1',
'prev_q_total_sales': '$1,413,584',
'next_q': 'Q3',
'next_q_total_sales_proj': '$1,634,765',
'next_q_qoq_proj': '0.021',
'top1_sku': 'Io',
'top1_sales': '$234,384',
'top2_sku': 'Europa',
'top2_sales': '$215,718',
'top3_sku': 'Ganymede',
'top3_sales': '$185,727',
'top4_sku': 'Callisto',
'top4_sales': '$164,023',
'top5_sku': 'Amalthea',
'top5_sales': '$112,361',
},
'saturn': {
'customer_name': 'Saturn',
'customer_logo':
'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/' +
'Saturn_during_Equinox.jpg/800px-Saturn_during_Equinox.jpg',
'curr_q': 'Q2',
'curr_q_total_sales': '$2,532,124',
'curr_q_qoq': '0.032',
'prev_q': 'Q1',
'prev_q_total_sales': '$2,413,584',
'next_q': 'Q3',
'next_q_total_sales_proj': '$2,634,765',
'next_q_qoq_proj': '0.029',
'top1_sku': 'Mimas',
'top1_sales': '$334,384',
'top2_sku': 'Enceladus',
'top2_sales': '$315,718',
'top3_sku': 'Tethys',
'top3_sales': '$285,727',
'top4_sku': 'Dione',
'top4_sales': '$264,023',
'top5_sku': 'Rhea',
'top5_sales': '$212,361',
},
'neptune': {
'customer_name': 'Neptune',
'customer_logo':
'https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/' +
'Neptune_Full.jpg/600px-Neptune_Full.jpg',
'curr_q': 'Q2',
'curr_q_total_sales': '$2,532,124',
'curr_q_qoq': '0.027',
'prev_q': 'Q1',
'prev_q_total_sales': '$2,413,584',
'next_q': 'Q3',
'next_q_total_sales_proj': '$2,634,765',
'next_q_qoq_proj': '0.039',
'top1_sku': 'Triton',
'top1_sales': '$334,384',
'top2_sku': 'Nereid',
'top2_sales': '$315,718',
'top3_sku': 'Naiad',
'top3_sales': '$285,727',
'top4_sku': 'Thalassa',
'top4_sales': '$264,023',
'top5_sku': 'Despina',
'top5_sales': '$212,361',
},
}
def GetCustomerData(self, customer_id, properties):
customer_data = self._CUSTOMER_DATA[customer_id]
return [customer_data[p.lower()] for p in properties]
| 2,776 |
14,668 | <filename>ios/chrome/browser/ui/omnibox/popup/omnibox_popup_row_cell.h
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_OMNIBOX_POPUP_ROW_CELL_H_
#define IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_OMNIBOX_POPUP_ROW_CELL_H_
#import <UIKit/UIKit.h>
@protocol AutocompleteSuggestion;
@protocol FaviconRetriever;
@protocol ImageRetriever;
@class OmniboxIconView;
@class OmniboxPopupRowCell;
namespace {
NSString* OmniboxPopupRowCellReuseIdentifier = @"OmniboxPopupRowCell";
// This mimimum height causes most of the rows to be the same height. Some have
// multiline answers, so those heights may be taller than this minimum.
const CGFloat kOmniboxPopupCellMinimumHeight = 58;
} // namespace
// Protocol for informing delegate that the trailing button for this cell
// was tapped
@protocol OmniboxPopupRowCellDelegate
// The trailing button was tapped.
- (void)trailingButtonTappedForCell:(OmniboxPopupRowCell*)cell;
@end
// Table view cell to display an autocomplete suggestion in the omnibox popup.
// It handles all the layout logic internally.
@interface OmniboxPopupRowCell : UITableViewCell
@property(nonatomic, weak) id<OmniboxPopupRowCellDelegate> delegate;
// Used to fetch favicons.
@property(nonatomic, weak) id<FaviconRetriever> faviconRetriever;
@property(nonatomic, weak) id<ImageRetriever> imageRetriever;
// The semanticContentAttribute determined by the text in the omnibox. The
// views in this cell should be updated to match this.
@property(nonatomic, assign)
UISemanticContentAttribute omniboxSemanticContentAttribute;
// Whether the table row separator appears. This can't use the default
// UITableView separators because the leading edge of the separator must be
// aligned with the text, which is positioned using a layout guide, so the
// tableView's separatorInsets can't be calculated.
@property(nonatomic, assign) BOOL showsSeparator;
// Image view for the leading image.
@property(nonatomic, strong, readonly) OmniboxIconView* leadingIconView;
// Layout this cell with the given data before displaying.
- (void)setupWithAutocompleteSuggestion:(id<AutocompleteSuggestion>)suggestion
incognito:(BOOL)incognito;
@end
#endif // IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_OMNIBOX_POPUP_ROW_CELL_H_
| 798 |
2,757 | <reponame>CEOALT1/RefindPlusUDK<filename>EdkCompatibilityPkg/Foundation/Library/EdkIIGlueLib/EntryPoints/EdkIIGluePeimEntryPoint.c
/*++
Copyright (c) 2004 - 2011, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
EdkIIGluePeimEntryPoint.c
Abstract:
PEIM entry point template file
--*/
#include "EdkIIGluePeim.h"
#include "Common/EdkIIGlueDependencies.h"
#ifdef __EDKII_GLUE_EFI_CALLER_ID_GUID__
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiCallerIdGuid = __EDKII_GLUE_EFI_CALLER_ID_GUID__;
#endif
//
// Library constructors
//
VOID
EFIAPI
ProcessLibraryConstructorList (
IN EFI_FFS_FILE_HEADER *FfsHeader,
IN EFI_PEI_SERVICES **PeiServices
)
{
//
// EdkII Glue Library Constructors:
// PeiServicesTablePointerLib PeiServicesTablePointerLibConstructor()
// PeiServicesTablePointerLibMm7 PeiServicesTablePointerLibConstructor()
// PeiServicesTablePointerLibKr1 PeiServicesTablePointerLibConstructor()
//
#if defined(__EDKII_GLUE_PEI_SERVICES_TABLE_POINTER_LIB_MM7__) \
|| defined(__EDKII_GLUE_PEI_SERVICES_TABLE_POINTER_LIB_KR1__) \
|| defined(__EDKII_GLUE_PEI_SERVICES_TABLE_POINTER_LIB__)
EFI_STATUS Status;
Status = PeiServicesTablePointerLibConstructor (FfsHeader, PeiServices);
ASSERT_EFI_ERROR (Status);
#endif
}
EFI_PEIM_ENTRY_POINT (_ModuleEntryPoint);
EFI_STATUS
EFIAPI
__EDKII_GLUE_MODULE_ENTRY_POINT__ (
IN EFI_FFS_FILE_HEADER *FfsHeader,
IN EFI_PEI_SERVICES **PeiServices
);
/**
Image entry point of Peim.
@param FfsHeader Pointer to FFS header the loaded driver.
@param PeiServices Pointer to the PEI services.
@return Status returned by entry points of Peims.
--*/
EFI_STATUS
EFIAPI
_ModuleEntryPoint (
IN EFI_FFS_FILE_HEADER *FfsHeader,
IN EFI_PEI_SERVICES **PeiServices
)
{
// if (_gPeimRevision != 0) {
// //
// // Make sure that the PEI spec revision of the platform is >= PEI spec revision of the driver
// //
// ASSERT ((*PeiServices)->Hdr.Revision >= _gPeimRevision);
// }
//
// Call constructor for all libraries
//
ProcessLibraryConstructorList (FfsHeader, PeiServices);
//
// Call the driver entry point
//
return __EDKII_GLUE_MODULE_ENTRY_POINT__ (FfsHeader, PeiServices);
}
/**
Wrapper of Peim image entry point.
@param FfsHeader Pointer to FFS header the loaded driver.
@param PeiServices Pointer to the PEI services.
@return Status returned by entry points of Peims.
**/
EFI_STATUS
EFIAPI
EfiMain (
IN EFI_FFS_FILE_HEADER *FfsHeader,
IN EFI_PEI_SERVICES **PeiServices
)
{
return _ModuleEntryPoint (FfsHeader, PeiServices);
}
//
// Guids not present in EDK code base
//
//
// Protocol/Arch Protocol GUID globals
//
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gUefiDriverConfigurationProtocolGuid = { 0xbfd7dc1d, 0x24f1, 0x40d9, { 0x82, 0xe7, 0x2e, 0x09, 0xbb, 0x6b, 0x4e, 0xbe } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gUefiDriverDiagnosticsProtocolGuid = { 0x4d330321, 0x025f, 0x4aac, { 0x90, 0xd8, 0x5e, 0xd9, 0x00, 0x17, 0x3b, 0x63 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiArpProtocolGuid = { 0xf4b427bb, 0xba21, 0x4f16, { 0xbc, 0x4e, 0x43, 0xe4, 0x16, 0xab, 0x61, 0x9c } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiArpServiceBindingProtocolGuid = { 0xf44c00ee, 0x1f2c, 0x4a00, { 0xaa, 0x09, 0x1c, 0x9f, 0x3e, 0x08, 0x00, 0xa3 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiDhcp4ProtocolGuid = { 0x8a219718, 0x4ef5, 0x4761, { 0x91, 0xc8, 0xc0, 0xf0, 0x4b, 0xda, 0x9e, 0x56 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiDhcp4ServiceBindingProtocolGuid = { 0x9d9a39d8, 0xbd42, 0x4a73, { 0xa4, 0xd5, 0x8e, 0xe9, 0x4b, 0xe1, 0x13, 0x80 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiIp4ProtocolGuid = { 0x41d94cd2, 0x35b6, 0x455a, { 0x82, 0x58, 0xd4, 0xe5, 0x13, 0x34, 0xaa, 0xdd } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiIp4ServiceBindingProtocolGuid = { 0xc51711e7, 0xb4bf, 0x404a, { 0xbf, 0xb8, 0x0a, 0x04, 0x8e, 0xf1, 0xff, 0xe4 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiIp4ConfigProtocolGuid = { 0x3b95aa31, 0x3793, 0x434b, { 0x86, 0x67, 0xc8, 0x07, 0x08, 0x92, 0xe0, 0x5e } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiManagedNetworkProtocolGuid = { 0x7ab33a91, 0xace5, 0x4326, { 0xb5, 0x72, 0xe7, 0xee, 0x33, 0xd3, 0x9f, 0x16 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiManagedNetworkServiceBindingProtocolGuid = { 0xf36ff770, 0xa7e1, 0x42cf, { 0x9e, 0xd2, 0x56, 0xf0, 0xf2, 0x71, 0xf4, 0x4c } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiMtftp4ProtocolGuid = { 0x3ad9df29, 0x4501, 0x478d, { 0xb1, 0xf8, 0x7f, 0x7f, 0xe7, 0x0e, 0x50, 0xf3 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiMtftp4ServiceBindingProtocolGuid = { 0x2FE800BE, 0x8F01, 0x4aa6, { 0x94, 0x6B, 0xD7, 0x13, 0x88, 0xE1, 0x83, 0x3F } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiTcp4ProtocolGuid = { 0x65530BC7, 0xA359, 0x410f, { 0xB0, 0x10, 0x5A, 0xAD, 0xC7, 0xEC, 0x2B, 0x62 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiTcp4ServiceBindingProtocolGuid = { 0x00720665, 0x67EB, 0x4a99, { 0xBA, 0xF7, 0xD3, 0xC3, 0x3A, 0x1C, 0x7C, 0xC9 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiUdp4ProtocolGuid = { 0x3ad9df29, 0x4501, 0x478d, { 0xb1, 0xf8, 0x7f, 0x7f, 0xe7, 0x0e, 0x50, 0xf3 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiUdp4ServiceBindingProtocolGuid = { 0x83f01464, 0x99bd, 0x45e5, { 0xb3, 0x83, 0xaf, 0x63, 0x05, 0xd8, 0xe9, 0xe6 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiAuthenticationInfoProtocolGuid = { 0x7671d9d0, 0x53db, 0x4173, { 0xaa, 0x69, 0x23, 0x27, 0xf2, 0x1f, 0x0b, 0xc7 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiDevicePathFromTextProtocolGuid = { 0x5c99a21, 0xc70f, 0x4ad2, { 0x8a, 0x5f, 0x35, 0xdf, 0x33, 0x43, 0xf5, 0x1e } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiDevicePathToTextProtocolGuid = { 0x8b843e20, 0x8132, 0x4852, { 0x90, 0xcc, 0x55, 0x1a, 0x4e, 0x4a, 0x7f, 0x1c } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiDevicePathUtilitiesProtocolGuid = { 0x379be4e, 0xd706, 0x437d, { 0xb0, 0x37, 0xed, 0xb8, 0x2f, 0xb7, 0x72, 0xa4 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHashProtocolGuid = { 0xc5184932, 0xdba5, 0x46db, { 0xa5, 0xba, 0xcc, 0x0b, 0xda, 0x9c, 0x14, 0x35 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHashServiceBindingProtocolGuid = { 0x42881c98, 0xa4f3, 0x44b0, { 0xa3, 0x9d, 0xdf, 0xa1, 0x86, 0x67, 0xd8, 0xcd } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiIScsiInitiatorNameProtocolGuid = { 0xa6a72875, 0x2962, 0x4c18, { 0x9f, 0x46, 0x8d, 0xa6, 0x44, 0xcc, 0xfe, 0x00 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiExtScsiPassThruProtocolGuid = { 0x1d3de7f0, 0x0807, 0x424f, { 0xaa, 0x69, 0x11, 0xa5, 0x4e, 0x19, 0xa4, 0x6f } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiTapeIoProtocolGuid = { 0x1e93e633, 0xd65a, 0x459e, { 0xab, 0x84, 0x93, 0xd9, 0xec, 0x26, 0x6d, 0x18 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiUsb2HcProtocolGuid = { 0x3e745226, 0x9818, 0x45b6, { 0xa2, 0xac, 0xd7, 0xcd, 0x0e, 0x8b, 0xa2, 0xbc } };
//
// PPI GUID globals
//
//
// GUID globals
//
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHobMemoryAllocBspStoreGuid = { 0x564b33cd, 0xc92a, 0x4593, { 0x90, 0xbf, 0x24, 0x73, 0xe4, 0x3c, 0x63, 0x22 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHobMemoryAllocStackGuid = { 0x4ed4bf27, 0x4092, 0x42e9, { 0x80, 0x7d, 0x52, 0x7b, 0x1d, 0x00, 0xc9, 0xbd } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHobMemoryAllocModuleGuid = { 0xf8e21975, 0x0899, 0x4f58, { 0xa4, 0xbe, 0x55, 0x25, 0xa9, 0xc6, 0xd7, 0x7a } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiAuthenticationChapRadiusGuid = { 0xd6062b50, 0x15ca, 0x11da, { 0x92, 0x19, 0x00, 0x10, 0x83, 0xff, 0xca, 0x4d } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiAuthenticationChapLocalGuid = { 0xc280c73e, 0x15ca, 0x11da, { 0xb0, 0xca, 0x00, 0x10, 0x83, 0xff, 0xca, 0x4d } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHashAlgorithmSha1Guid = { 0x2ae9d80f, 0x3fb2, 0x4095, { 0xb7, 0xb1, 0xe9, 0x31, 0x57, 0xb9, 0x46, 0xb6 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHashAlgorithmSha224Guid = { 0x8df01a06, 0x9bd5, 0x4bf7, { 0xb0, 0x21, 0xdb, 0x4f, 0xd9, 0xcc, 0xf4, 0x5b } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHashAlgorithmSha256Guid = { 0x51aa59de, 0xfdf2, 0x4ea3, { 0xbc, 0x63, 0x87, 0x5f, 0xb7, 0x84, 0x2e, 0xe9 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHashAlgorithmSha384Guid = { 0xefa96432, 0xde33, 0x4dd2, { 0xae, 0xe6, 0x32, 0x8c, 0x33, 0xdf, 0x77, 0x7a } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHashAlgorithmSha512Guid = { 0xcaa4381e, 0x750c, 0x4770, { 0xb8, 0x70, 0x7a, 0x23, 0xb4, 0xe4, 0x21, 0x30 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiHashAlgorithmMD5Guid = { 0xaf7c79c, 0x65b5, 0x4319, { 0xb0, 0xae, 0x44, 0xec, 0x48, 0x4e, 0x4a, 0xd7 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gBootObjectAuthorizationParmsetGuid = { 0xedd35e31, 0x7b9, 0x11d2, { 0x83, 0xa3, 0x00, 0xa0, 0xc9, 0x1f, 0xad, 0xcf } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gSmmCommunicateHeaderGuid = { 0xf328e36c, 0x23b6, 0x4a95, { 0x85, 0x4b, 0x32, 0xe1, 0x95, 0x34, 0xcd, 0x75 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiCapsuleGuid = { 0x3B6686BD, 0x0D76, 0x4030, { 0xB7, 0x0E, 0xB5, 0x51, 0x9E, 0x2F, 0xC5, 0xA0 } };
GLOBAL_REMOVE_IF_UNREFERENCED EFI_GUID gEfiConfigFileNameGuid = { 0x98B8D59B, 0xE8BA, 0x48EE, { 0x98, 0xDD, 0xC2, 0x95, 0x39, 0x2F, 0x1E, 0xDB } };
| 6,105 |
892 | <filename>advisories/unreviewed/2022/05/GHSA-rrfm-4fhv-2623/GHSA-rrfm-4fhv-2623.json
{
"schema_version": "1.2.0",
"id": "GHSA-rrfm-4fhv-2623",
"modified": "2022-05-02T06:13:56Z",
"published": "2022-05-02T06:13:56Z",
"aliases": [
"CVE-2010-0589"
],
"details": "The Web Install ActiveX control (CSDWebInstaller) in Cisco Secure Desktop (CSD) before 3.5.841 does not properly verify the signatures of downloaded programs, which allows remote attackers to force the download and execution of arbitrary files via a crafted web page, aka Bug ID CSCta25876.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2010-0589"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/57812"
},
{
"type": "WEB",
"url": "http://securitytracker.com/id?1023881"
},
{
"type": "WEB",
"url": "http://www.cisco.com/en/US/products/products_security_advisory09186a0080b25d01.shtml"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/39478"
},
{
"type": "WEB",
"url": "http://www.zerodayinitiative.com/advisories/ZDI-10-072/"
}
],
"database_specific": {
"cwe_ids": [
"CWE-20"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 637 |
507 | <reponame>mjuenema/python-terrascript<filename>terrascript/data/vultr/vultr.py
# terrascript/data/vultr/vultr.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:31:06 UTC)
import terrascript
class vultr_account(terrascript.Data):
pass
class vultr_application(terrascript.Data):
pass
class vultr_backup(terrascript.Data):
pass
class vultr_bare_metal_plan(terrascript.Data):
pass
class vultr_bare_metal_server(terrascript.Data):
pass
class vultr_block_storage(terrascript.Data):
pass
class vultr_dns_domain(terrascript.Data):
pass
class vultr_firewall_group(terrascript.Data):
pass
class vultr_instance(terrascript.Data):
pass
class vultr_instance_ipv4(terrascript.Data):
pass
class vultr_iso_private(terrascript.Data):
pass
class vultr_iso_public(terrascript.Data):
pass
class vultr_load_balancer(terrascript.Data):
pass
class vultr_object_storage(terrascript.Data):
pass
class vultr_os(terrascript.Data):
pass
class vultr_plan(terrascript.Data):
pass
class vultr_private_network(terrascript.Data):
pass
class vultr_region(terrascript.Data):
pass
class vultr_reserved_ip(terrascript.Data):
pass
class vultr_reverse_ipv4(terrascript.Data):
pass
class vultr_reverse_ipv6(terrascript.Data):
pass
class vultr_snapshot(terrascript.Data):
pass
class vultr_ssh_key(terrascript.Data):
pass
class vultr_startup_script(terrascript.Data):
pass
class vultr_user(terrascript.Data):
pass
__all__ = [
"vultr_account",
"vultr_application",
"vultr_backup",
"vultr_bare_metal_plan",
"vultr_bare_metal_server",
"vultr_block_storage",
"vultr_dns_domain",
"vultr_firewall_group",
"vultr_instance",
"vultr_instance_ipv4",
"vultr_iso_private",
"vultr_iso_public",
"vultr_load_balancer",
"vultr_object_storage",
"vultr_os",
"vultr_plan",
"vultr_private_network",
"vultr_region",
"vultr_reserved_ip",
"vultr_reverse_ipv4",
"vultr_reverse_ipv6",
"vultr_snapshot",
"vultr_ssh_key",
"vultr_startup_script",
"vultr_user",
]
| 962 |
3,034 | <reponame>NgSekLong/logging-log4j2<filename>log4j-api/src/main/java/org/apache/logging/log4j/message/Message.java
/*
* 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.logging.log4j.message;
import java.io.Serializable;
import org.apache.logging.log4j.util.StringBuilderFormattable;
/**
* An interface for various Message implementations that can be logged. Messages can act as wrappers
* around Objects so that user can have control over converting Objects to Strings when necessary without
* requiring complicated formatters and as a way to manipulate the message based on information available
* at runtime such as the locale of the system.
* <p>
* Custom Message implementations should consider implementing the {@link StringBuilderFormattable}
* interface for more efficient processing. Garbage-free Layouts will call
* {@link StringBuilderFormattable#formatTo(StringBuilder) formatTo(StringBuilder)} instead of
* {@link Message#getFormattedMessage()} if the Message implements StringBuilderFormattable.
* </p>
* <p>
* Note: Message objects should not be considered to be thread safe nor should they be assumed to be
* safely reusable even on the same thread. The logging system may provide information to the Message
* objects and the Messages might be queued for asynchronous delivery. Thus, any modifications to a
* Message object by an application should by avoided after the Message has been passed as a parameter on
* a Logger method.
* </p>
*
* @see StringBuilderFormattable
*/
/*
* Implementation note: this interface extends Serializable since LogEvents must be serializable.
*/
public interface Message extends Serializable {
/**
* Gets the Message formatted as a String. Each Message implementation determines the
* appropriate way to format the data encapsulated in the Message. Messages that provide
* more than one way of formatting the Message will implement MultiformatMessage.
* <p>
* When configured to log asynchronously, this method is called before the Message is queued, unless this
* message implements {@link ReusableMessage} or is annotated with {@link AsynchronouslyFormattable}.
* This gives the Message implementation class a chance to create a formatted message String with the current value
* of any mutable objects.
* The intention is that the Message implementation caches this formatted message and returns it on subsequent
* calls. (See <a href="https://issues.apache.org/jira/browse/LOG4J2-763">LOG4J2-763</a>.)
* </p>
* <p>
* When logging synchronously, this method will not be called for Messages that implement the
* {@link StringBuilderFormattable} interface: instead, the
* {@link StringBuilderFormattable#formatTo(StringBuilder) formatTo(StringBuilder)} method will be called so the
* Message can format its contents without creating intermediate String objects.
* </p>
*
* @return The message String.
*/
String getFormattedMessage();
/**
* Gets the format portion of the Message.
*
* @return The message format. Some implementations, such as ParameterizedMessage, will use this as
* the message "pattern". Other Messages may simply return an empty String.
* TODO Do all messages have a format? What syntax? Using a Formatter object could be cleaner.
* (RG) In SimpleMessage the format is identical to the formatted message. In ParameterizedMessage and
* StructuredDataMessage it is not. It is up to the Message implementer to determine what this
* method will return. A Formatter is inappropriate as this is very specific to the Message
* implementation so it isn't clear to me how having a Formatter separate from the Message would be cleaner.
*/
String getFormat();
/**
* Gets parameter values, if any.
*
* @return An array of parameter values or null.
*/
Object[] getParameters();
/**
* Gets the throwable, if any.
*
* @return the throwable or null.
*/
Throwable getThrowable();
}
| 1,307 |
8,054 | #include "labelwithbuttonswidget.h"
#include <QLabel>
#include <QHBoxLayout>
#include <QStyleOption>
#include <QPainter>
#include <QDebug>
#include <QStyle>
#include <QToolButton>
#include <QAction>
#include <core/vnotex.h>
#include <utils/iconutils.h>
using namespace vnotex;
LabelWithButtonsWidget::LabelWithButtonsWidget(const QString &p_label, Buttons p_buttons, QWidget *p_parent)
: QWidget(p_parent)
{
setupUI(p_buttons);
setLabel(p_label);
}
void LabelWithButtonsWidget::setupUI(Buttons p_buttons)
{
auto mainLayout = new QHBoxLayout(this);
m_label = new QLabel(this);
mainLayout->addWidget(m_label);
if (p_buttons & Button::Delete) {
auto btn = createButton(Button::Delete, this);
mainLayout->addWidget(btn);
}
}
void LabelWithButtonsWidget::setLabel(const QString &p_label)
{
m_label->setText(p_label);
}
void LabelWithButtonsWidget::paintEvent(QPaintEvent *p_event)
{
Q_UNUSED(p_event);
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
QToolButton *LabelWithButtonsWidget::createButton(Button p_button, QWidget *p_parent)
{
auto btn = new QToolButton(p_parent);
QAction *act = nullptr;
switch (p_button) {
case Button::Delete:
act = new QAction(generateIcon(QStringLiteral("delete.svg")), tr("Delete"), p_parent);
break;
default:
Q_ASSERT(false);
break;
}
if (act) {
act->setData(static_cast<int>(p_button));
btn->setDefaultAction(act);
connect(btn, &QToolButton::triggered,
this, [this](QAction *p_act) {
emit triggered(static_cast<Button>(p_act->data().toInt()));
});
}
return btn;
}
QIcon LabelWithButtonsWidget::generateIcon(const QString &p_name) const
{
auto iconFile = VNoteX::getInst().getThemeMgr().getIconFile(p_name);
return IconUtils::fetchIcon(iconFile);
}
| 844 |
4,829 | //
// Copyright <NAME> (<EMAIL>), <NAME> (<EMAIL>) 2014-2021
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include "td/telegram/td_api.h"
#include "td/telegram/telegram_api.h"
#include "td/utils/common.h"
namespace td {
class GroupCallVideoPayload {
struct GroupCallVideoSourceGroup {
string semantics_;
vector<int32> source_ids_;
};
vector<GroupCallVideoSourceGroup> source_groups_;
string endpoint_;
bool is_paused_ = false;
friend bool operator==(const GroupCallVideoPayload &lhs, const GroupCallVideoPayload &rhs);
public:
GroupCallVideoPayload() = default;
explicit GroupCallVideoPayload(const telegram_api::groupCallParticipantVideo *video);
bool is_empty() const;
td_api::object_ptr<td_api::groupCallParticipantVideoInfo> get_group_call_participant_video_info_object() const;
};
bool operator==(const GroupCallVideoPayload &lhs, const GroupCallVideoPayload &rhs);
} // namespace td
| 356 |
14,668 | // Copyright (c) 2010 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/http/http_auth_handler_factory.h"
#include <set>
#include "base/containers/contains.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "net/base/net_errors.h"
#include "net/dns/host_resolver.h"
#include "net/http/http_auth_challenge_tokenizer.h"
#include "net/http/http_auth_filter.h"
#include "net/http/http_auth_handler_basic.h"
#include "net/http/http_auth_handler_digest.h"
#include "net/http/http_auth_handler_ntlm.h"
#include "net/http/http_auth_preferences.h"
#include "net/http/http_auth_scheme.h"
#include "net/log/net_log_values.h"
#include "net/net_buildflags.h"
#include "net/ssl/ssl_info.h"
#include "url/scheme_host_port.h"
#if BUILDFLAG(USE_KERBEROS)
#include "net/http/http_auth_handler_negotiate.h"
#endif
namespace {
base::Value NetLogParamsForCreateAuth(
const std::string& scheme,
const std::string& challenge,
const int net_error,
const url::SchemeHostPort& scheme_host_port,
const absl::optional<bool>& allows_default_credentials,
net::NetLogCaptureMode capture_mode) {
base::Value dict(base::Value::Type::DICTIONARY);
dict.SetKey("scheme", net::NetLogStringValue(scheme));
if (net::NetLogCaptureIncludesSensitive(capture_mode))
dict.SetKey("challenge", net::NetLogStringValue(challenge));
dict.SetStringKey("origin", scheme_host_port.Serialize());
if (allows_default_credentials)
dict.SetBoolKey("allows_default_credentials", *allows_default_credentials);
if (net_error < 0)
dict.SetIntKey("net_error", net_error);
return dict;
}
} // namespace
namespace net {
int HttpAuthHandlerFactory::CreateAuthHandlerFromString(
const std::string& challenge,
HttpAuth::Target target,
const SSLInfo& ssl_info,
const NetworkIsolationKey& network_isolation_key,
const url::SchemeHostPort& scheme_host_port,
const NetLogWithSource& net_log,
HostResolver* host_resolver,
std::unique_ptr<HttpAuthHandler>* handler) {
HttpAuthChallengeTokenizer props(challenge.begin(), challenge.end());
return CreateAuthHandler(&props, target, ssl_info, network_isolation_key,
scheme_host_port, CREATE_CHALLENGE, 1, net_log,
host_resolver, handler);
}
int HttpAuthHandlerFactory::CreatePreemptiveAuthHandlerFromString(
const std::string& challenge,
HttpAuth::Target target,
const NetworkIsolationKey& network_isolation_key,
const url::SchemeHostPort& scheme_host_port,
int digest_nonce_count,
const NetLogWithSource& net_log,
HostResolver* host_resolver,
std::unique_ptr<HttpAuthHandler>* handler) {
HttpAuthChallengeTokenizer props(challenge.begin(), challenge.end());
SSLInfo null_ssl_info;
return CreateAuthHandler(&props, target, null_ssl_info, network_isolation_key,
scheme_host_port, CREATE_PREEMPTIVE,
digest_nonce_count, net_log, host_resolver, handler);
}
namespace {
const char* const kDefaultAuthSchemes[] = {kBasicAuthScheme, kDigestAuthScheme,
#if BUILDFLAG(USE_KERBEROS) && !defined(OS_ANDROID)
kNegotiateAuthScheme,
#endif
kNtlmAuthScheme};
} // namespace
HttpAuthHandlerRegistryFactory::HttpAuthHandlerRegistryFactory() = default;
HttpAuthHandlerRegistryFactory::~HttpAuthHandlerRegistryFactory() = default;
void HttpAuthHandlerRegistryFactory::SetHttpAuthPreferences(
const std::string& scheme,
const HttpAuthPreferences* prefs) {
HttpAuthHandlerFactory* factory = GetSchemeFactory(scheme);
if (factory)
factory->set_http_auth_preferences(prefs);
}
void HttpAuthHandlerRegistryFactory::RegisterSchemeFactory(
const std::string& scheme,
HttpAuthHandlerFactory* factory) {
std::string lower_scheme = base::ToLowerASCII(scheme);
if (factory) {
factory->set_http_auth_preferences(http_auth_preferences());
factory_map_[lower_scheme] = base::WrapUnique(factory);
} else {
factory_map_.erase(lower_scheme);
}
}
HttpAuthHandlerFactory* HttpAuthHandlerRegistryFactory::GetSchemeFactory(
const std::string& scheme) const {
std::string lower_scheme = base::ToLowerASCII(scheme);
auto it = factory_map_.find(lower_scheme);
if (it == factory_map_.end()) {
return nullptr; // |scheme| is not registered.
}
return it->second.get();
}
// static
std::unique_ptr<HttpAuthHandlerRegistryFactory>
HttpAuthHandlerFactory::CreateDefault(
const HttpAuthPreferences* prefs
#if BUILDFLAG(USE_EXTERNAL_GSSAPI)
,
const std::string& gssapi_library_name
#endif
#if BUILDFLAG(USE_KERBEROS)
,
HttpAuthMechanismFactory negotiate_auth_system_factory
#endif
) {
std::vector<std::string> auth_types(std::begin(kDefaultAuthSchemes),
std::end(kDefaultAuthSchemes));
return HttpAuthHandlerRegistryFactory::Create(prefs, auth_types
#if BUILDFLAG(USE_EXTERNAL_GSSAPI)
,
gssapi_library_name
#endif
#if BUILDFLAG(USE_KERBEROS)
,
negotiate_auth_system_factory
#endif
);
}
// static
std::unique_ptr<HttpAuthHandlerRegistryFactory>
HttpAuthHandlerRegistryFactory::Create(
const HttpAuthPreferences* prefs,
const std::vector<std::string>& auth_schemes
#if BUILDFLAG(USE_EXTERNAL_GSSAPI)
,
const std::string& gssapi_library_name
#endif
#if BUILDFLAG(USE_KERBEROS)
,
HttpAuthMechanismFactory negotiate_auth_system_factory
#endif
) {
std::set<std::string> auth_schemes_set(auth_schemes.begin(),
auth_schemes.end());
std::unique_ptr<HttpAuthHandlerRegistryFactory> registry_factory(
new HttpAuthHandlerRegistryFactory());
if (base::Contains(auth_schemes_set, kBasicAuthScheme)) {
registry_factory->RegisterSchemeFactory(
kBasicAuthScheme, new HttpAuthHandlerBasic::Factory());
}
if (base::Contains(auth_schemes_set, kDigestAuthScheme)) {
registry_factory->RegisterSchemeFactory(
kDigestAuthScheme, new HttpAuthHandlerDigest::Factory());
}
if (base::Contains(auth_schemes_set, kNtlmAuthScheme)) {
HttpAuthHandlerNTLM::Factory* ntlm_factory =
new HttpAuthHandlerNTLM::Factory();
#if defined(OS_WIN)
ntlm_factory->set_sspi_library(
std::make_unique<SSPILibraryDefault>(NTLMSP_NAME));
#endif // defined(OS_WIN)
registry_factory->RegisterSchemeFactory(kNtlmAuthScheme, ntlm_factory);
}
#if BUILDFLAG(USE_KERBEROS)
if (base::Contains(auth_schemes_set, kNegotiateAuthScheme)) {
HttpAuthHandlerNegotiate::Factory* negotiate_factory =
new HttpAuthHandlerNegotiate::Factory(negotiate_auth_system_factory);
#if defined(OS_WIN)
negotiate_factory->set_library(
std::make_unique<SSPILibraryDefault>(NEGOSSP_NAME));
#elif BUILDFLAG(USE_EXTERNAL_GSSAPI)
negotiate_factory->set_library(
std::make_unique<GSSAPISharedLibrary>(gssapi_library_name));
#endif
registry_factory->RegisterSchemeFactory(kNegotiateAuthScheme,
negotiate_factory);
}
#endif // BUILDFLAG(USE_KERBEROS)
if (prefs) {
registry_factory->set_http_auth_preferences(prefs);
for (auto& factory_entry : registry_factory->factory_map_) {
factory_entry.second->set_http_auth_preferences(prefs);
}
}
return registry_factory;
}
int HttpAuthHandlerRegistryFactory::CreateAuthHandler(
HttpAuthChallengeTokenizer* challenge,
HttpAuth::Target target,
const SSLInfo& ssl_info,
const NetworkIsolationKey& network_isolation_key,
const url::SchemeHostPort& scheme_host_port,
CreateReason reason,
int digest_nonce_count,
const NetLogWithSource& net_log,
HostResolver* host_resolver,
std::unique_ptr<HttpAuthHandler>* handler) {
auto scheme = challenge->auth_scheme();
int net_error;
if (scheme.empty()) {
handler->reset();
net_error = ERR_INVALID_RESPONSE;
} else {
auto it = factory_map_.find(scheme);
if (it == factory_map_.end()) {
handler->reset();
net_error = ERR_UNSUPPORTED_AUTH_SCHEME;
} else {
DCHECK(it->second);
net_error = it->second->CreateAuthHandler(
challenge, target, ssl_info, network_isolation_key, scheme_host_port,
reason, digest_nonce_count, net_log, host_resolver, handler);
}
}
net_log.AddEvent(
NetLogEventType::AUTH_HANDLER_CREATE_RESULT,
[&](NetLogCaptureMode capture_mode) {
return NetLogParamsForCreateAuth(
scheme, challenge->challenge_text(), net_error, scheme_host_port,
*handler
? absl::make_optional((*handler)->AllowsDefaultCredentials())
: absl::nullopt,
capture_mode);
});
return net_error;
}
} // namespace net
| 3,744 |
30,023 | """Shared constants."""
from homeassistant.components import vacuum
MQTT_VACUUM_ATTRIBUTES_BLOCKED = frozenset(
{
vacuum.ATTR_BATTERY_ICON,
vacuum.ATTR_BATTERY_LEVEL,
vacuum.ATTR_FAN_SPEED,
}
)
| 112 |
922 | <gh_stars>100-1000
//
// SynchroScrollView.h
// edenx
//
// Created by <NAME> on 2/21/09.
// Copied from http://developer.apple.com/documentation/Cocoa/Conceptual/NSScrollViewGuide/Articles/SynchroScroll.html
//
#import <Cocoa/Cocoa.h>
@interface SynchroScrollView : NSScrollView {
NSScrollView* synchronizedScrollView; // not retained
}
@property(assign) BOOL scrollHorizontal;
- (void)setSynchronizedScrollView:(NSScrollView*)scrollview;
- (void)stopSynchronizing;
- (void)synchronizedViewContentBoundsDidChange:(NSNotification *)notification;
@end | 200 |
786 | <reponame>edustaff/spyne
# coding: utf-8
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
#
"""Complex model tests runnable on different Python implementations."""
import unittest
from spyne.model.complex import (ComplexModel, ComplexModelMeta,
ComplexModelBase, Array)
from spyne.model.primitive import Unicode, Integer, String
from spyne.util.six import add_metaclass
class DeclareOrder_declare(ComplexModel.customize(declare_order='declared')):
field3 = Integer
field1 = Integer
field2 = Integer
class MyComplexModelMeta(ComplexModelMeta):
"""Custom complex model metaclass."""
def __new__(mcs, name, bases, attrs):
attrs['new_field'] = Unicode
attrs['field1'] = Unicode
new_cls = super(MyComplexModelMeta, mcs).__new__(mcs, name, bases,
attrs)
return new_cls
@add_metaclass(MyComplexModelMeta)
class MyComplexModel(ComplexModelBase):
"""Custom complex model class."""
class Attributes(ComplexModelBase.Attributes):
declare_order = 'declared'
class MyModelWithDeclaredOrder(MyComplexModel):
"""Test model for complex model with custom metaclass."""
class Attributes(MyComplexModel.Attributes):
declare_order = 'declared'
field3 = Integer
field1 = Integer
field2 = Integer
class TestComplexModel(unittest.TestCase):
def test_add_field(self):
class C(ComplexModel):
u = Unicode
C.append_field('i', Integer)
assert C._type_info['i'] is Integer
def test_insert_field(self):
class C(ComplexModel):
u = Unicode
C.insert_field(0, 'i', Integer)
assert C._type_info.keys() == ['i', 'u']
def test_variants(self):
class C(ComplexModel):
u = Unicode
CC = C.customize(child_attrs=dict(u=dict(min_len=5)))
print(dict(C.Attributes._variants.items()))
r, = C.Attributes._variants
assert r is CC
assert CC.Attributes.parent_variant is C
C.append_field('i', Integer)
assert C._type_info['i'] is Integer
assert CC._type_info['i'] is Integer
def test_child_customization(self):
class C(ComplexModel):
u = Unicode
CC = C.customize(child_attrs=dict(u=dict(min_len=5)))
assert CC._type_info['u'].Attributes.min_len == 5
assert C._type_info['u'].Attributes.min_len != 5
def test_array_customization(self):
CC = Array(Unicode).customize(
serializer_attrs=dict(min_len=5), punks='roll',
)
assert CC.Attributes.punks == 'roll'
assert CC._type_info[0].Attributes.min_len == 5
def test_array_customization_complex(self):
class C(ComplexModel):
u = Unicode
CC = Array(C).customize(
punks='roll',
serializer_attrs=dict(bidik=True)
)
assert CC.Attributes.punks == 'roll'
assert CC._type_info[0].Attributes.bidik == True
def test_delayed_child_customization_append(self):
class C(ComplexModel):
u = Unicode
CC = C.customize(child_attrs=dict(i=dict(ge=5)))
CC.append_field('i', Integer)
assert CC._type_info['i'].Attributes.ge == 5
assert not 'i' in C._type_info
def test_delayed_child_customization_insert(self):
class C(ComplexModel):
u = Unicode
CC = C.customize(child_attrs=dict(i=dict(ge=5)))
CC.insert_field(1, 'i', Integer)
assert CC._type_info['i'].Attributes.ge == 5
assert not 'i' in C._type_info
def test_array_member_name(self):
print(Array(String, member_name="punk")._type_info)
assert 'punk' in Array(String, member_name="punk")._type_info
def test_customize(self):
class Base(ComplexModel):
class Attributes(ComplexModel.Attributes):
prop1 = 3
prop2 = 6
Base2 = Base.customize(prop1=4)
self.assertNotEquals(Base.Attributes.prop1, Base2.Attributes.prop1)
self.assertEqual(Base.Attributes.prop2, Base2.Attributes.prop2)
class Derived(Base):
class Attributes(Base.Attributes):
prop3 = 9
prop4 = 12
Derived2 = Derived.customize(prop1=5, prop3=12)
self.assertEqual(Base.Attributes.prop1, 3)
self.assertEqual(Base2.Attributes.prop1, 4)
self.assertEqual(Derived.Attributes.prop1, 3)
self.assertEqual(Derived2.Attributes.prop1, 5)
self.assertNotEquals(Derived.Attributes.prop3, Derived2.Attributes.prop3)
self.assertEqual(Derived.Attributes.prop4, Derived2.Attributes.prop4)
Derived3 = Derived.customize(prop3=12)
Base.prop1 = 4
# changes made to bases propagate, unless overridden
self.assertEqual(Derived.Attributes.prop1, Base.Attributes.prop1)
self.assertNotEquals(Derived2.Attributes.prop1, Base.Attributes.prop1)
self.assertEqual(Derived3.Attributes.prop1, Base.Attributes.prop1)
def test_declare_order(self):
self.assertEqual(["field3", "field1", "field2"],
list(DeclareOrder_declare._type_info))
self.assertEqual(["field3", "field1", "field2", "new_field"],
list(MyModelWithDeclaredOrder._type_info))
if __name__ == '__main__':
import sys
sys.exit(unittest.main())
| 2,604 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.php.editor.verification;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.BadLocationException;
import org.netbeans.editor.BaseDocument;
import org.netbeans.modules.csl.api.EditList;
import org.netbeans.modules.csl.api.Hint;
import org.netbeans.modules.csl.api.HintFix;
import org.netbeans.modules.csl.api.OffsetRange;
import org.netbeans.modules.csl.spi.support.CancelSupport;
import org.netbeans.modules.php.editor.parser.PHPParseResult;
import org.netbeans.modules.php.editor.parser.astnodes.Block;
import org.netbeans.modules.php.editor.parser.astnodes.DoStatement;
import org.netbeans.modules.php.editor.parser.astnodes.ForEachStatement;
import org.netbeans.modules.php.editor.parser.astnodes.ForStatement;
import org.netbeans.modules.php.editor.parser.astnodes.IfStatement;
import org.netbeans.modules.php.editor.parser.astnodes.Statement;
import org.netbeans.modules.php.editor.parser.astnodes.WhileStatement;
import org.netbeans.modules.php.editor.parser.astnodes.visitors.DefaultVisitor;
import org.openide.filesystems.FileObject;
import org.openide.util.NbBundle;
/**
*
* @author <NAME> <<EMAIL>>
*/
public abstract class BracesHint extends HintRule {
@Override
public void invoke(PHPRuleContext context, List<Hint> hints) {
PHPParseResult phpParseResult = (PHPParseResult) context.parserResult;
if (phpParseResult.getProgram() != null) {
FileObject fileObject = phpParseResult.getSnapshot().getSource().getFileObject();
if (fileObject != null) {
if (CancelSupport.getDefault().isCancelled()) {
return;
}
CheckVisitor checkVisitor = createVisitor(fileObject, context.doc);
phpParseResult.getProgram().accept(checkVisitor);
if (CancelSupport.getDefault().isCancelled()) {
return;
}
hints.addAll(checkVisitor.getHints());
}
}
}
abstract CheckVisitor createVisitor(FileObject fileObject, BaseDocument baseDocument);
public static final class IfBracesHint extends BracesHint {
private static final String HINT_ID = "If.Braces.Hint"; //NOI18N
@Override
protected CheckVisitor createVisitor(FileObject fileObject, BaseDocument baseDocument) {
return new IfVisitor(this, fileObject, baseDocument);
}
private static final class IfVisitor extends CheckVisitor {
public IfVisitor(BracesHint bracesHint, FileObject fileObject, BaseDocument baseDocument) {
super(bracesHint, fileObject, baseDocument);
}
@Override
@NbBundle.Messages("IfBracesHintText=If-Else Statements Must Use Braces")
public void visit(IfStatement node) {
if (CancelSupport.getDefault().isCancelled()) {
return;
}
super.visit(node);
Statement trueStatement = node.getTrueStatement();
if (trueStatement != null && !(trueStatement instanceof Block)) {
addHint(node, trueStatement, Bundle.IfBracesHintText());
}
Statement falseStatement = node.getFalseStatement();
if (falseStatement != null && !(falseStatement instanceof Block) && !(falseStatement instanceof IfStatement)) {
addHint(node, falseStatement, Bundle.IfBracesHintText());
}
}
}
@Override
public String getId() {
return HINT_ID;
}
@Override
@NbBundle.Messages("IfBracesHintDesc=If-Else Statements Must Use Braces")
public String getDescription() {
return Bundle.IfBracesHintDesc();
}
@Override
@NbBundle.Messages("IfBracesHintDisp=If-Else Statements Must Use Braces")
public String getDisplayName() {
return Bundle.IfBracesHintDisp();
}
}
public static final class DoWhileBracesHint extends BracesHint {
private static final String HINT_ID = "Do.While.Braces.Hint"; //NOI18N
@Override
protected CheckVisitor createVisitor(FileObject fileObject, BaseDocument baseDocument) {
return new DoWhileVisitor(this, fileObject, baseDocument);
}
private static final class DoWhileVisitor extends CheckVisitor {
public DoWhileVisitor(BracesHint bracesHint, FileObject fileObject, BaseDocument baseDocument) {
super(bracesHint, fileObject, baseDocument);
}
@Override
@NbBundle.Messages("DoWhileBracesHintText=Do-While Loops Must Use Braces")
public void visit(DoStatement node) {
if (CancelSupport.getDefault().isCancelled()) {
return;
}
super.visit(node);
Statement bodyStatement = node.getBody();
if (bodyStatement != null && !(bodyStatement instanceof Block)) {
addHint(node, bodyStatement, Bundle.DoWhileBracesHintText());
}
}
}
@Override
public String getId() {
return HINT_ID;
}
@Override
@NbBundle.Messages("DoWhileBracesHintDesc=Do-While Loops Must Use Braces")
public String getDescription() {
return Bundle.DoWhileBracesHintDesc();
}
@Override
@NbBundle.Messages("DoWhileBracesHintDisp=Do-While Loops Must Use Braces")
public String getDisplayName() {
return Bundle.DoWhileBracesHintDisp();
}
}
public static final class WhileBracesHint extends BracesHint {
private static final String HINT_ID = "While.Braces.Hint"; //NOI18N
@Override
protected CheckVisitor createVisitor(FileObject fileObject, BaseDocument baseDocument) {
return new WhileVisitor(this, fileObject, baseDocument);
}
private static final class WhileVisitor extends CheckVisitor {
public WhileVisitor(BracesHint bracesHint, FileObject fileObject, BaseDocument baseDocument) {
super(bracesHint, fileObject, baseDocument);
}
@Override
@NbBundle.Messages("WhileBracesHintText=While Loops Must Use Braces")
public void visit(WhileStatement node) {
if (CancelSupport.getDefault().isCancelled()) {
return;
}
super.visit(node);
Statement bodyStatement = node.getBody();
if (bodyStatement != null && !(bodyStatement instanceof Block)) {
addHint(node, bodyStatement, Bundle.WhileBracesHintText());
}
}
}
@Override
public String getId() {
return HINT_ID;
}
@Override
@NbBundle.Messages("WhileBracesHintDesc=While Loops Must Use Braces")
public String getDescription() {
return Bundle.WhileBracesHintDesc();
}
@Override
@NbBundle.Messages("WhileBracesHintDisp=While Loops Must Use Braces")
public String getDisplayName() {
return Bundle.WhileBracesHintDisp();
}
}
public static final class ForBracesHint extends BracesHint {
private static final String HINT_ID = "For.Braces.Hint"; //NOI18N
@Override
protected CheckVisitor createVisitor(FileObject fileObject, BaseDocument baseDocument) {
return new ForVisitor(this, fileObject, baseDocument);
}
private static final class ForVisitor extends CheckVisitor {
public ForVisitor(BracesHint bracesHint, FileObject fileObject, BaseDocument baseDocument) {
super(bracesHint, fileObject, baseDocument);
}
@Override
@NbBundle.Messages("ForBracesHintText=For Loops Must Use Braces")
public void visit(ForStatement node) {
if (CancelSupport.getDefault().isCancelled()) {
return;
}
super.visit(node);
Statement bodyStatement = node.getBody();
if (bodyStatement != null && !(bodyStatement instanceof Block)) {
addHint(node, bodyStatement, Bundle.ForBracesHintText());
}
}
}
@Override
public String getId() {
return HINT_ID;
}
@Override
@NbBundle.Messages("ForBracesHintDesc=For Loops Must Use Braces")
public String getDescription() {
return Bundle.ForBracesHintDesc();
}
@Override
@NbBundle.Messages("ForBracesHintDisp=For Loops Must Use Braces")
public String getDisplayName() {
return Bundle.ForBracesHintDisp();
}
}
public static final class ForEachBracesHint extends BracesHint {
private static final String HINT_ID = "ForEach.Braces.Hint"; //NOI18N
@Override
protected CheckVisitor createVisitor(FileObject fileObject, BaseDocument baseDocument) {
return new ForEachVisitor(this, fileObject, baseDocument);
}
private static final class ForEachVisitor extends CheckVisitor {
public ForEachVisitor(BracesHint bracesHint, FileObject fileObject, BaseDocument baseDocument) {
super(bracesHint, fileObject, baseDocument);
}
@Override
@NbBundle.Messages("ForEachBracesHintText=ForEach Loops Must Use Braces")
public void visit(ForEachStatement node) {
if (CancelSupport.getDefault().isCancelled()) {
return;
}
super.visit(node);
Statement bodyStatement = node.getStatement();
if (bodyStatement != null && !(bodyStatement instanceof Block)) {
addHint(node, bodyStatement, Bundle.ForEachBracesHintText());
}
}
}
@Override
public String getId() {
return HINT_ID;
}
@Override
@NbBundle.Messages("ForEachBracesHintDesc=ForEach Loops Must Use Braces")
public String getDescription() {
return Bundle.ForEachBracesHintDesc();
}
@Override
@NbBundle.Messages("ForEachBracesHintDisp=ForEach Loops Must Use Braces")
public String getDisplayName() {
return Bundle.ForEachBracesHintDisp();
}
}
private abstract static class CheckVisitor extends DefaultVisitor {
private final List<Hint> hints;
private final BaseDocument baseDocument;
private final FileObject fileObject;
private final BracesHint bracesHint;
private CheckVisitor(BracesHint bracesHint, FileObject fileObject, BaseDocument baseDocument) {
this.bracesHint = bracesHint;
this.fileObject = fileObject;
this.baseDocument = baseDocument;
this.hints = new ArrayList<>();
}
protected void addHint(Statement enclosingStatement, Statement node, String description) {
OffsetRange offsetRange = new OffsetRange(node.getStartOffset(), node.getEndOffset());
if (bracesHint.showHint(offsetRange, baseDocument)) {
if (CancelSupport.getDefault().isCancelled()) {
return;
}
hints.add(new Hint(bracesHint, description, fileObject, offsetRange, Collections.<HintFix>singletonList(new Fix(enclosingStatement, node, baseDocument)), 500));
}
}
public List<Hint> getHints() {
return hints;
}
}
private static final class Fix implements HintFix {
private final Statement node;
private final Statement enclosingStatement;
private final BaseDocument baseDocument;
public Fix(Statement enclosingStatement, Statement node, BaseDocument baseDocument) {
this.node = node;
this.enclosingStatement = enclosingStatement;
this.baseDocument = baseDocument;
}
@Override
@NbBundle.Messages("AddBraces=Add Braces")
public String getDescription() {
return Bundle.AddBraces();
}
@Override
public void implement() throws Exception {
int removeLength = enclosingStatement.getEndOffset() - enclosingStatement.getStartOffset();
EditList editList = new EditList(baseDocument);
editList.replace(enclosingStatement.getStartOffset(), removeLength, createReplaceText(), true, 0);
editList.apply();
}
private String createReplaceText() throws BadLocationException {
String leadingText = baseDocument.getText(enclosingStatement.getStartOffset(), node.getStartOffset() - enclosingStatement.getStartOffset());
String middleText = baseDocument.getText(node.getStartOffset(), node.getEndOffset() - node.getStartOffset());
String trailingText = baseDocument.getText(node.getEndOffset(), enclosingStatement.getEndOffset() - node.getEndOffset());
return leadingText + "{\n" + middleText + "\n}" + trailingText; //NOI18N
}
@Override
public boolean isSafe() {
return true;
}
@Override
public boolean isInteractive() {
return false;
}
}
}
| 6,119 |
12,252 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.models.map.storage.hotRod.common;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasSize;
import static org.keycloak.models.map.storage.hotRod.common.HotRodTypesUtils.getMapValueFromSet;
import static org.keycloak.models.map.storage.hotRod.common.HotRodTypesUtils.migrateMapToSet;
import static org.keycloak.models.map.storage.hotRod.common.HotRodTypesUtils.migrateSetToMap;
import static org.keycloak.models.map.storage.hotRod.common.HotRodTypesUtils.removeFromSetByMapKey;
public class HotRodTypesUtilsTest {
@Test
public void testMigrateMapToSet() {
// Test null map
assertThat(migrateMapToSet((Map<String, String>) null, Map.Entry::getKey), nullValue());
Map<String, String> m = new HashMap<>();
m.put("key", "value");
assertThat(migrateMapToSet(m, e -> e.getKey() + "#" + e.getValue()),
contains("key#value"));
}
@Test
public void testMigrateSetToMap() {
// Test null map
assertThat(migrateSetToMap((Set<String>) null, Function.identity(), Function.identity()), nullValue());
Set<String> s = new HashSet<>();
s.add("key#value");
Map<String, String> result = HotRodTypesUtils.migrateSetToMap(s, e -> e.split("#")[0], e -> e.split("#")[1]);
assertThat(result.keySet(), hasSize(1));
assertThat(result, hasEntry("key", "value"));
}
@Test
public void testRemoveFromSetByMapKey() {
assertThat(removeFromSetByMapKey((Set<String>) null, null, Function.identity()), is(false));
assertThat(removeFromSetByMapKey(Collections.emptySet(), null, Function.identity()), is(false));
Set<String> s = new HashSet<>();
s.add("key#value");
s.add("key1#value1");
s.add("key2#value2");
// Remove existing
Set<String> testSet = new HashSet<>(s);
assertThat(removeFromSetByMapKey(testSet, "key", e -> e.split("#")[0]), is(true));
assertThat(testSet, hasSize(2));
assertThat(testSet, containsInAnyOrder("key1#value1", "key2#value2"));
// Remove not existing
testSet = new HashSet<>(s);
assertThat(removeFromSetByMapKey(testSet, "key3", e -> e.split("#")[0]), is(false));
assertThat(testSet, hasSize(3));
assertThat(testSet, containsInAnyOrder("key#value", "key1#value1", "key2#value2"));
}
@Test
public void testGetMapValueFromSet() {
assertThat(getMapValueFromSet((Set<String>) null, null, Function.identity(), Function.identity()), nullValue());
assertThat(getMapValueFromSet(Collections.emptySet(), "key", Function.identity(), Function.identity()), nullValue());
Set<String> s = new HashSet<>();
s.add("key#value");
s.add("key1#value1");
s.add("key2#value2");
// search existing
assertThat(getMapValueFromSet(s, "key", e -> e.split("#")[0], e -> e.split("#")[1]), is("value"));
assertThat(getMapValueFromSet(s, "key1", e -> e.split("#")[0], e -> e.split("#")[1]), is("value1"));
// Search not existing
assertThat(getMapValueFromSet(s, "key3", e -> e.split("#")[0], e -> e.split("#")[1]), nullValue());
}
} | 1,649 |
571 | /***************************************************************************
Copyright 2015 Ufora 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.
****************************************************************************/
#pragma once
#include <typeinfo>
#include <boost/unordered_map.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
class ArbitraryTypeMap {
public:
ArbitraryTypeMap()
{
}
~ArbitraryTypeMap();
ArbitraryTypeMap(const ArbitraryTypeMap& in);
ArbitraryTypeMap& operator=(const ArbitraryTypeMap& in);
size_t size() const
{
return mInstances.size();
}
template<class T>
T& get()
{
static bool isInitialized = false;
void* tname = (void*)typeid(T).name();
if (!isInitialized)
{
boost::mutex::scoped_lock lock(mFunctionsMutex);
mDestructors[tname] = boost::bind(&destroy<T>, boost::arg<1>());
mDuplicators[tname] = boost::bind(&duplicate<T>, boost::arg<1>());
}
if (mInstances.find(tname) == mInstances.end())
mInstances[tname] = (void*)new T();
return *(T*)mInstances[tname];
}
template<class T>
void erase()
{
void* tname = (void*)typeid(T).name();
auto it = mInstances.find(tname);
if (it == mInstances.end())
return;
void* value = it->second;
mInstances.erase(it);
boost::mutex::scoped_lock lock(mFunctionsMutex);
mDestructors[tname](value);
}
void clear()
{
*this = ArbitraryTypeMap();
}
private:
template<class T>
static void* duplicate(void* inValue)
{
return (void*)new T(*(T*)inValue);
}
template<class T>
static void destroy(void* inValue)
{
((T*)inValue)->~T();
}
boost::unordered_map<void*, void*> mInstances;
static boost::mutex mFunctionsMutex;
static boost::unordered_map<void*, boost::function1<void, void*> > mDestructors;
static boost::unordered_map<void*, boost::function1<void*, void*> > mDuplicators;
};
| 839 |
364 | // AUTOGENERATED CODE. DO NOT MODIFY DIRECTLY! Instead, please modify the tuple/TupleGenerators.ftl file.
// See the README in the module's src/template directory for details.
package com.linkedin.dagli.tuple;
import java.util.Iterator;
/**
* Tuple generators create tuples of a fixed dimension from a variety of inputs. Note that these methods are always
* equivalent to the static methods available on the TupleX interfaces; the benefit of TupleGenerators is that they
* provide an efficient way to generate many tuples of a given size when the tuple size is only known at runtime.
*
* You can get the generator for a specific size by calling Tuple.generator(size).
*/
final class TupleGenerators {
private TupleGenerators() {
}
private enum Generator1 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 1;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple1.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple1.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple1.fromIteratorUnsafe(elements);
}
}
private enum Generator2 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 2;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple2.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple2.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple2.fromIteratorUnsafe(elements);
}
}
private enum Generator3 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 3;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple3.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple3.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple3.fromIteratorUnsafe(elements);
}
}
private enum Generator4 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 4;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple4.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple4.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple4.fromIteratorUnsafe(elements);
}
}
private enum Generator5 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 5;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple5.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple5.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple5.fromIteratorUnsafe(elements);
}
}
private enum Generator6 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 6;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple6.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple6.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple6.fromIteratorUnsafe(elements);
}
}
private enum Generator7 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 7;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple7.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple7.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple7.fromIteratorUnsafe(elements);
}
}
private enum Generator8 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 8;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple8.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple8.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple8.fromIteratorUnsafe(elements);
}
}
private enum Generator9 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 9;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple9.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple9.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple9.fromIteratorUnsafe(elements);
}
}
private enum Generator10 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 10;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple10.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple10.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple10.fromIteratorUnsafe(elements);
}
}
private enum Generator11 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 11;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple11.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple11.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple11.fromIteratorUnsafe(elements);
}
}
private enum Generator12 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 12;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple12.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple12.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple12.fromIteratorUnsafe(elements);
}
}
private enum Generator13 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 13;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple13.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple13.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple13.fromIteratorUnsafe(elements);
}
}
private enum Generator14 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 14;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple14.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple14.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple14.fromIteratorUnsafe(elements);
}
}
private enum Generator15 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 15;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple15.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple15.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple15.fromIteratorUnsafe(elements);
}
}
private enum Generator16 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 16;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple16.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple16.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple16.fromIteratorUnsafe(elements);
}
}
private enum Generator17 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 17;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple17.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple17.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple17.fromIteratorUnsafe(elements);
}
}
private enum Generator18 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 18;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple18.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple18.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple18.fromIteratorUnsafe(elements);
}
}
private enum Generator19 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 19;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple19.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple19.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple19.fromIteratorUnsafe(elements);
}
}
private enum Generator20 implements TupleGenerator {
INSTANCE;
@Override
public int size() {
return 20;
}
@Override
public Tuple fromArray(Object[] elements) {
return Tuple20.fromArrayUnsafe(elements);
}
@Override
public Tuple fromIterable(Iterable<?> elements) {
return Tuple20.fromIterableUnsafe(elements);
}
@Override
public Tuple fromIterator(Iterator<?> elements) {
return Tuple20.fromIteratorUnsafe(elements);
}
}
final static TupleGenerator[] GENERATORS = getGeneratorArray();
private static TupleGenerator[] getGeneratorArray() {
TupleGenerator[] result = new TupleGenerator[20];
result[0] = Generator1.INSTANCE;
result[1] = Generator2.INSTANCE;
result[2] = Generator3.INSTANCE;
result[3] = Generator4.INSTANCE;
result[4] = Generator5.INSTANCE;
result[5] = Generator6.INSTANCE;
result[6] = Generator7.INSTANCE;
result[7] = Generator8.INSTANCE;
result[8] = Generator9.INSTANCE;
result[9] = Generator10.INSTANCE;
result[10] = Generator11.INSTANCE;
result[11] = Generator12.INSTANCE;
result[12] = Generator13.INSTANCE;
result[13] = Generator14.INSTANCE;
result[14] = Generator15.INSTANCE;
result[15] = Generator16.INSTANCE;
result[16] = Generator17.INSTANCE;
result[17] = Generator18.INSTANCE;
result[18] = Generator19.INSTANCE;
result[19] = Generator20.INSTANCE;
return result;
}
}
| 4,383 |
1,391 | <reponame>newluhux/plan9port
/*% cc -gpc %
* These transformation routines maintain stacks of transformations
* and their inverses.
* t=pushmat(t) push matrix stack
* t=popmat(t) pop matrix stack
* rot(t, a, axis) multiply stack top by rotation
* qrot(t, q) multiply stack top by rotation, q is unit quaternion
* scale(t, x, y, z) multiply stack top by scale
* move(t, x, y, z) multiply stack top by translation
* xform(t, m) multiply stack top by m
* ixform(t, m, inv) multiply stack top by m. inv is the inverse of m.
* look(t, e, l, u) multiply stack top by viewing transformation
* persp(t, fov, n, f) multiply stack top by perspective transformation
* viewport(t, r, aspect)
* multiply stack top by window->viewport transformation.
*/
#include <u.h>
#include <libc.h>
#include <draw.h>
#include <geometry.h>
Space *pushmat(Space *t){
Space *v;
v=malloc(sizeof(Space));
if(t==0){
ident(v->t);
ident(v->tinv);
}
else
*v=*t;
v->next=t;
return v;
}
Space *popmat(Space *t){
Space *v;
if(t==0) return 0;
v=t->next;
free(t);
return v;
}
void rot(Space *t, double theta, int axis){
double s=sin(radians(theta)), c=cos(radians(theta));
Matrix m, inv;
int i=(axis+1)%3, j=(axis+2)%3;
ident(m);
m[i][i] = c;
m[i][j] = -s;
m[j][i] = s;
m[j][j] = c;
ident(inv);
inv[i][i] = c;
inv[i][j] = s;
inv[j][i] = -s;
inv[j][j] = c;
ixform(t, m, inv);
}
void qrot(Space *t, Quaternion q){
Matrix m, inv;
int i, j;
qtom(m, q);
for(i=0;i!=4;i++) for(j=0;j!=4;j++) inv[i][j]=m[j][i];
ixform(t, m, inv);
}
void scale(Space *t, double x, double y, double z){
Matrix m, inv;
ident(m);
m[0][0]=x;
m[1][1]=y;
m[2][2]=z;
ident(inv);
inv[0][0]=1/x;
inv[1][1]=1/y;
inv[2][2]=1/z;
ixform(t, m, inv);
}
void move(Space *t, double x, double y, double z){
Matrix m, inv;
ident(m);
m[0][3]=x;
m[1][3]=y;
m[2][3]=z;
ident(inv);
inv[0][3]=-x;
inv[1][3]=-y;
inv[2][3]=-z;
ixform(t, m, inv);
}
void xform(Space *t, Matrix m){
Matrix inv;
if(invertmat(m, inv)==0) return;
ixform(t, m, inv);
}
void ixform(Space *t, Matrix m, Matrix inv){
matmul(t->t, m);
matmulr(t->tinv, inv);
}
/*
* multiply the top of the matrix stack by a view-pointing transformation
* with the eyepoint at e, looking at point l, with u at the top of the screen.
* The coordinate system is deemed to be right-handed.
* The generated transformation transforms this view into a view from
* the origin, looking in the positive y direction, with the z axis pointing up,
* and x to the right.
*/
void look(Space *t, Point3 e, Point3 l, Point3 u){
Matrix m, inv;
Point3 r;
l=unit3(sub3(l, e));
u=unit3(vrem3(sub3(u, e), l));
r=cross3(l, u);
/* make the matrix to transform from (rlu) space to (xyz) space */
ident(m);
m[0][0]=r.x; m[0][1]=r.y; m[0][2]=r.z;
m[1][0]=l.x; m[1][1]=l.y; m[1][2]=l.z;
m[2][0]=u.x; m[2][1]=u.y; m[2][2]=u.z;
ident(inv);
inv[0][0]=r.x; inv[0][1]=l.x; inv[0][2]=u.x;
inv[1][0]=r.y; inv[1][1]=l.y; inv[1][2]=u.y;
inv[2][0]=r.z; inv[2][1]=l.z; inv[2][2]=u.z;
ixform(t, m, inv);
move(t, -e.x, -e.y, -e.z);
}
/*
* generate a transformation that maps the frustum with apex at the origin,
* apex angle=fov and clipping planes y=n and y=f into the double-unit cube.
* plane y=n maps to y'=-1, y=f maps to y'=1
*/
int persp(Space *t, double fov, double n, double f){
Matrix m;
double z;
if(n<=0 || f<=n || fov<=0 || 180<=fov) /* really need f!=n && sin(v)!=0 */
return -1;
z=1/tan(radians(fov)/2);
m[0][0]=z; m[0][1]=0; m[0][2]=0; m[0][3]=0;
m[1][0]=0; m[1][1]=(f+n)/(f-n); m[1][2]=0; m[1][3]=f*(1-m[1][1]);
m[2][0]=0; m[2][1]=0; m[2][2]=z; m[2][3]=0;
m[3][0]=0; m[3][1]=1; m[3][2]=0; m[3][3]=0;
xform(t, m);
return 0;
}
/*
* Map the unit-cube window into the given screen viewport.
* r has min at the top left, max just outside the lower right. Aspect is the
* aspect ratio (dx/dy) of the viewport's pixels (not of the whole viewport!)
* The whole window is transformed to fit centered inside the viewport with equal
* slop on either top and bottom or left and right, depending on the viewport's
* aspect ratio.
* The window is viewed down the y axis, with x to the left and z up. The viewport
* has x increasing to the right and y increasing down. The window's y coordinates
* are mapped, unchanged, into the viewport's z coordinates.
*/
void viewport(Space *t, Rectangle r, double aspect){
Matrix m;
double xc, yc, wid, hgt, scale;
xc=.5*(r.min.x+r.max.x);
yc=.5*(r.min.y+r.max.y);
wid=(r.max.x-r.min.x)*aspect;
hgt=r.max.y-r.min.y;
scale=.5*(wid<hgt?wid:hgt);
ident(m);
m[0][0]=scale;
m[0][3]=xc;
m[1][1]=0;
m[1][2]=-scale;
m[1][3]=yc;
m[2][1]=1;
m[2][2]=0;
/* should get inverse by hand */
xform(t, m);
}
| 2,211 |
575 | <filename>ash/display/display_util.h
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_DISPLAY_DISPLAY_UTIL_H_
#define ASH_DISPLAY_DISPLAY_UTIL_H_
#include <memory>
#include <string>
#include "ash/ash_export.h"
namespace aura {
class Window;
}
namespace display {
class DisplayManager;
}
namespace gfx {
class Point;
class Rect;
}
namespace ash {
class AshWindowTreeHost;
class MouseWarpController;
// Creates a MouseWarpController for the current display
// configuration. |drag_source| is the window where dragging
// started, or nullptr otherwise.
std::unique_ptr<MouseWarpController> CreateMouseWarpController(
display::DisplayManager* manager,
aura::Window* drag_source);
// Creates edge bounds from |bounds_in_screen| that fits the edge
// of the native window for |ash_host|.
ASH_EXPORT gfx::Rect GetNativeEdgeBounds(AshWindowTreeHost* ash_host,
const gfx::Rect& bounds_in_screen);
// Moves the cursor to the point inside the |ash_host| that is closest to
// the point_in_screen, which may be outside of the root window.
// |update_last_loation_now| is used for the test to update the mouse
// location synchronously.
void MoveCursorTo(AshWindowTreeHost* ash_host,
const gfx::Point& point_in_screen,
bool update_last_location_now);
// Shows the notification message for display related issues, and optionally
// adds a button to send a feedback report.
void ShowDisplayErrorNotification(const std::u16string& message,
bool allow_feedback);
// Returns whether `rect_in_screen` is contained by any display.
bool IsRectContainedByAnyDisplay(const gfx::Rect& rect_in_screen);
// Takes a refresh rate represented as a float and rounds it to two decimal
// places. If the rounded refresh rate is a whole number, the mantissa is
// removed. Ex: 54.60712 -> "54.61"
ASH_EXPORT std::u16string ConvertRefreshRateToString16(float refresh_rate);
ASH_EXPORT std::u16string GetDisplayErrorNotificationMessageForTest();
} // namespace ash
#endif // ASH_DISPLAY_DISPLAY_UTIL_H_
| 749 |
491 | // Copyright (C) 2021 THL A29 Limited, a Tencent company. 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.
//
// ╔════════════════════════════════════════════════════════════════════════════════════════╗
// ║──█████████╗───███████╗───████████╗───██╗──────██╗───███████╗───████████╗───████████╗───║
// ║──██╔══════╝──██╔════██╗──██╔════██╗──██║──────██║──██╔════██╗──██╔════██╗──██╔════██╗──║
// ║──████████╗───██║────██║──████████╔╝──██║──█╗──██║──█████████║──████████╔╝──██║────██║──║
// ║──██╔═════╝───██║────██║──██╔════██╗──██║█████╗██║──██╔════██║──██╔════██╗──██║────██║──║
// ║──██║─────────╚███████╔╝──██║────██║──╚████╔████╔╝──██║────██║──██║────██║──████████╔╝──║
// ║──╚═╝──────────╚══════╝───╚═╝────╚═╝───╚═══╝╚═══╝───╚═╝────╚═╝──╚═╝────╚═╝──╚═══════╝───║
// ╚════════════════════════════════════════════════════════════════════════════════════════╝
//
// Authors: <NAME> (<EMAIL>)
// Yzx (<EMAIL>)
// <NAME> (<EMAIL>)
// <NAME> (<EMAIL>)
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "fwd_tf/tf_cvt/tf_desc_creators/i_tf_layer_creator.h"
FWD_TF_NAMESPACE_BEGIN
/**
* \brief Clamp 层描述创建器
*/
template <>
class TLayerDescCreator<TrtClampDesc> : public ILayerDescCreator {
public:
bool Check(const Operation& op) override {
const auto type = op.OpType();
return type == "Relu6";
}
std::shared_ptr<TrtLayerDesc> Create(const Operation& op, const Graph& graph,
std::vector<Output>& op_inputs) override {
LOG(INFO) << "TrtClampDesc::Create";
const auto op_type = op.OpType();
const auto input = op.Input(0);
op_inputs.push_back(input);
auto layer_desc = std::make_shared<TrtClampDesc>();
// TODO(yzx): 暂时还没发现其他 Clamp 操作
if (op_type == "Relu6") {
layer_desc->max = 6.0f;
layer_desc->min = 0.0f;
}
return layer_desc;
}
};
FWD_TF_NAMESPACE_END
| 1,178 |
772 | package com.sksamuel.scrimage.filter;
import thirdparty.marvin.image.MarvinAbstractImagePlugin;
import thirdparty.marvin.image.edge.Sobel;
public class SobelsFilter extends MarvinFilter {
@Override
public MarvinAbstractImagePlugin plugin() {
return new Sobel();
}
}
| 97 |
1,717 | /**
* Package that contains abstractions needed to support optional
* non-blocking decoding (parsing) functionality.
* Although parsers are constructed normally via
* {@link com.fasterxml.jackson.core.JsonFactory}
* (and are, in fact, sub-types of {@link com.fasterxml.jackson.core.JsonParser}),
* the way input is provided differs.
*
* @since 2.9
*/
package com.fasterxml.jackson.core.async;
| 124 |
1,894 | <gh_stars>1000+
# Copyright 2019 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.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import functools
import mock
from dashboard.pinpoint import test
from dashboard.pinpoint.models import change as change_module
from dashboard.pinpoint.models import evaluators
from dashboard.pinpoint.models import event as event_module
from dashboard.pinpoint.models import job as job_module
from dashboard.pinpoint.models import task as task_module
from dashboard.pinpoint.models.tasks import find_isolate
from dashboard.pinpoint.models.tasks import run_test
from dashboard.pinpoint.models.tasks import bisection_test_util
DIMENSIONS = [
{
'key': 'pool',
'value': 'Chrome-perf-pinpoint'
},
{
'key': 'key',
'value': 'value'
},
]
@mock.patch('dashboard.services.swarming.Tasks.New')
@mock.patch('dashboard.services.swarming.Task.Result')
class EvaluatorTest(test.TestCase):
def setUp(self):
super(EvaluatorTest, self).setUp()
self.maxDiff = None
self.job = job_module.Job.New((), ())
task_module.PopulateTaskGraph(
self.job,
run_test.CreateGraph(
run_test.TaskOptions(
build_options=find_isolate.TaskOptions(
builder='Some Builder',
target='telemetry_perf_tests',
bucket='luci.bucket',
change=change_module.Change.FromDict({
'commits': [{
'repository': 'chromium',
'git_hash': 'aaaaaaa',
}]
})),
swarming_server='some_server',
dimensions=DIMENSIONS,
extra_args=[],
attempts=10)))
def testEvaluateToCompletion(self, swarming_task_result, swarming_tasks_new):
swarming_tasks_new.return_value = {'task_id': 'task id'}
evaluator = evaluators.SequenceEvaluator(
evaluators=(
evaluators.FilteringEvaluator(
predicate=evaluators.TaskTypeEq('find_isolate'),
delegate=evaluators.SequenceEvaluator(
evaluators=(bisection_test_util.FakeFoundIsolate(self.job),
evaluators.TaskPayloadLiftingEvaluator()))),
run_test.Evaluator(self.job),
))
self.assertNotEqual({},
task_module.Evaluate(
self.job,
event_module.Event(
type='initiate', target_task=None, payload={}),
evaluator))
# Ensure that we've found all the 'run_test' tasks.
self.assertEqual(
{
'run_test_chromium@aaaaaaa_%s' % (attempt,): {
'status': 'ongoing',
'swarming_server': 'some_server',
'dimensions': DIMENSIONS,
'extra_args': [],
'swarming_request_body': {
'name': mock.ANY,
'user': mock.ANY,
'priority': mock.ANY,
'task_slices': mock.ANY,
'tags': mock.ANY,
'pubsub_auth_token': mock.ANY,
'pubsub_topic': mock.ANY,
'pubsub_userdata': mock.ANY,
'service_account': mock.ANY,
},
'swarming_task_id': 'task id',
'tries': 1,
'change': mock.ANY,
'index': attempt,
} for attempt in range(10)
},
task_module.Evaluate(
self.job,
event_module.Event(type='select', target_task=None, payload={}),
evaluators.Selector(task_type='run_test')))
# Ensure that we've actually made the calls to the Swarming service.
swarming_tasks_new.assert_called()
self.assertGreaterEqual(swarming_tasks_new.call_count, 10)
# Then we propagate an event for each of the run_test tasks in the graph.
swarming_task_result.return_value = {
'bot_id': 'bot id',
'exit_code': 0,
'failure': False,
'outputs_ref': {
'isolatedserver': 'output isolate server',
'isolated': 'output isolate hash',
},
'state': 'COMPLETED',
}
for attempt in range(10):
self.assertNotEqual(
{},
task_module.Evaluate(
self.job,
event_module.Event(
type='update',
target_task='run_test_chromium@aaaaaaa_%s' % (attempt,),
payload={}), evaluator), 'Attempt #%s' % (attempt,))
# Ensure that we've polled the status of each of the tasks, and that we've
# marked the tasks completed.
self.assertEqual(
{
'run_test_chromium@aaaaaaa_%s' % (attempt,): {
'status': 'completed',
'swarming_server': 'some_server',
'dimensions': DIMENSIONS,
'extra_args': [],
'swarming_request_body': {
'name': mock.ANY,
'user': mock.ANY,
'priority': mock.ANY,
'task_slices': mock.ANY,
'tags': mock.ANY,
'pubsub_auth_token': mock.ANY,
'pubsub_topic': mock.ANY,
'pubsub_userdata': mock.ANY,
'service_account': mock.ANY,
},
'swarming_task_result': {
'bot_id': mock.ANY,
'state': 'COMPLETED',
'failure': False,
},
'isolate_server': 'output isolate server',
'isolate_hash': 'output isolate hash',
'swarming_task_id': 'task id',
'tries': 1,
'change': mock.ANY,
'index': attempt,
} for attempt in range(10)
},
task_module.Evaluate(
self.job,
event_module.Event(type='select', target_task=None, payload={}),
evaluators.Selector(task_type='run_test')))
# Ensure that we've actually made the calls to the Swarming service.
swarming_task_result.assert_called()
self.assertGreaterEqual(swarming_task_result.call_count, 10)
def testEvaluateToCompletion_CAS(self, swarming_task_result,
swarming_tasks_new):
swarming_tasks_new.return_value = {'task_id': 'task id'}
evaluator = evaluators.SequenceEvaluator(
evaluators=(
evaluators.FilteringEvaluator(
predicate=evaluators.TaskTypeEq('find_isolate'),
delegate=evaluators.SequenceEvaluator(
evaluators=(bisection_test_util.FakeFoundIsolate(self.job),
evaluators.TaskPayloadLiftingEvaluator()))),
run_test.Evaluator(self.job),
))
self.assertNotEqual({},
task_module.Evaluate(
self.job,
event_module.Event(
type='initiate', target_task=None, payload={}),
evaluator))
# Ensure that we've found all the 'run_test' tasks.
self.assertEqual(
{
'run_test_chromium@aaaaaaa_%s' % (attempt,): {
'status': 'ongoing',
'swarming_server': 'some_server',
'dimensions': DIMENSIONS,
'extra_args': [],
'swarming_request_body': {
'name': mock.ANY,
'user': mock.ANY,
'priority': mock.ANY,
'task_slices': mock.ANY,
'tags': mock.ANY,
'pubsub_auth_token': mock.ANY,
'pubsub_topic': mock.ANY,
'pubsub_userdata': mock.ANY,
'service_account': mock.ANY,
},
'swarming_task_id': 'task id',
'tries': 1,
'change': mock.ANY,
'index': attempt,
} for attempt in range(10)
},
task_module.Evaluate(
self.job,
event_module.Event(type='select', target_task=None, payload={}),
evaluators.Selector(task_type='run_test')))
# Ensure that we've actually made the calls to the Swarming service.
swarming_tasks_new.assert_called()
self.assertGreaterEqual(swarming_tasks_new.call_count, 10)
# Then we propagate an event for each of the run_test tasks in the graph.
swarming_task_result.return_value = {
'bot_id': 'bot id',
'exit_code': 0,
'failure': False,
'cas_output_root': {
'cas_instance': 'output cas server',
'digest': {
'hash': 'output cas hash',
"byteSize": 91,
},
},
'state': 'COMPLETED',
}
for attempt in range(10):
self.assertNotEqual(
{},
task_module.Evaluate(
self.job,
event_module.Event(
type='update',
target_task='run_test_chromium@aaaaaaa_%s' % (attempt,),
payload={}), evaluator), 'Attempt #%s' % (attempt,))
# Ensure that we've polled the status of each of the tasks, and that we've
# marked the tasks completed.
self.assertEqual(
{
'run_test_chromium@aaaaaaa_%s' % (attempt,): {
'status': 'completed',
'swarming_server': 'some_server',
'dimensions': DIMENSIONS,
'extra_args': [],
'swarming_request_body': {
'name': mock.ANY,
'user': mock.ANY,
'priority': mock.ANY,
'task_slices': mock.ANY,
'tags': mock.ANY,
'pubsub_auth_token': mock.ANY,
'pubsub_topic': mock.ANY,
'pubsub_userdata': mock.ANY,
'service_account': mock.ANY,
},
'swarming_task_result': {
'bot_id': mock.ANY,
'state': 'COMPLETED',
'failure': False,
},
'cas_root_ref': {
'cas_instance': 'output cas server',
'digest': {
'hash': 'output cas hash',
"byteSize": 91,
},
},
'swarming_task_id': 'task id',
'tries': 1,
'change': mock.ANY,
'index': attempt,
} for attempt in range(10)
},
task_module.Evaluate(
self.job,
event_module.Event(type='select', target_task=None, payload={}),
evaluators.Selector(task_type='run_test')))
# Ensure that we've actually made the calls to the Swarming service.
swarming_task_result.assert_called()
self.assertGreaterEqual(swarming_task_result.call_count, 10)
def testEvaluateFailedDependency(self, *_):
evaluator = evaluators.SequenceEvaluator(
evaluators=(
evaluators.FilteringEvaluator(
predicate=evaluators.TaskTypeEq('find_isolate'),
delegate=evaluators.SequenceEvaluator(
evaluators=(
bisection_test_util.FakeFindIsolateFailed(self.job),
evaluators.TaskPayloadLiftingEvaluator()))),
run_test.Evaluator(self.job),
))
# When we initiate the run_test tasks, we should immediately see the tasks
# failing because the dependency has a hard failure status.
self.assertEqual(
dict([('find_isolate_chromium@aaaaaaa', mock.ANY)] +
[('run_test_chromium@aaaaaaa_%s' % (attempt,), {
'status': 'failed',
'errors': mock.ANY,
'dimensions': DIMENSIONS,
'extra_args': [],
'swarming_server': 'some_server',
'change': mock.ANY,
'index': attempt,
}) for attempt in range(10)]),
task_module.Evaluate(
self.job,
event_module.Event(type='initiate', target_task=None, payload={}),
evaluator))
def testEvaluatePendingDependency(self, *_):
# Ensure that tasks stay pending in the event of an update.
self.assertEqual(
dict([('find_isolate_chromium@aaaaaaa', {
'builder': 'Some Builder',
'target': 'telemetry_perf_tests',
'bucket': 'luci.bucket',
'change': mock.ANY,
'status': 'pending',
})] + [('run_test_chromium@aaaaaaa_%s' % (attempt,), {
'status': 'pending',
'dimensions': DIMENSIONS,
'extra_args': [],
'swarming_server': 'some_server',
'change': mock.ANY,
'index': attempt,
}) for attempt in range(10)]),
task_module.Evaluate(
self.job,
event_module.Event(
type='update',
target_task=None,
payload={
'kind': 'synthetic',
'action': 'poll'
}), run_test.Evaluator(self.job)))
@mock.patch('dashboard.services.swarming.Task.Stdout')
def testEvaluateHandleFailures_Hard(self, swarming_task_stdout,
swarming_task_result, swarming_tasks_new):
swarming_tasks_new.return_value = {'task_id': 'task id'}
evaluator = evaluators.SequenceEvaluator(
evaluators=(
evaluators.FilteringEvaluator(
predicate=evaluators.TaskTypeEq('find_isolate'),
delegate=evaluators.SequenceEvaluator(
evaluators=(bisection_test_util.FakeFoundIsolate(self.job),
evaluators.TaskPayloadLiftingEvaluator()))),
run_test.Evaluator(self.job),
))
self.assertNotEqual({},
task_module.Evaluate(
self.job,
event_module.Event(
type='initiate', target_task=None, payload={}),
evaluator))
# We set it up so that when we poll the swarming task, that we're going to
# get an error status. We're expecting that hard failures are detected.
swarming_task_stdout.return_value = {
'output':
"""Traceback (most recent call last):
File "../../testing/scripts/run_performance_tests.py", line 282, in <module>
sys.exit(main())
File "../../testing/scripts/run_performance_tests.py", line 226, in main
benchmarks = args.benchmark_names.split(',')
AttributeError: 'Namespace' object has no attribute 'benchmark_names'"""
}
swarming_task_result.return_value = {
'bot_id': 'bot id',
'exit_code': 1,
'failure': True,
'outputs_ref': {
'isolatedserver': 'output isolate server',
'isolated': 'output isolate hash',
},
'state': 'COMPLETED',
}
for attempt in range(10):
self.assertNotEqual({},
task_module.Evaluate(
self.job,
event_module.Event(
type='update',
target_task='run_test_chromium@aaaaaaa_%s' %
(attempt,),
payload={
'kind': 'pubsub_message',
'action': 'poll'
}), evaluator), 'Attempt #%s' % (attempt,))
self.assertEqual(
{
'run_test_chromium@aaaaaaa_%s' % (attempt,): {
'status': 'failed',
'swarming_server': 'some_server',
'dimensions': DIMENSIONS,
'errors': mock.ANY,
'extra_args': [],
'swarming_request_body': {
'name': mock.ANY,
'user': mock.ANY,
'priority': mock.ANY,
'task_slices': mock.ANY,
'tags': mock.ANY,
'pubsub_auth_token': mock.ANY,
'pubsub_topic': mock.ANY,
'pubsub_userdata': mock.ANY,
'service_account': mock.ANY,
},
'swarming_task_result': {
'bot_id': mock.ANY,
'state': 'COMPLETED',
'failure': True,
},
'isolate_server': 'output isolate server',
'isolate_hash': 'output isolate hash',
'swarming_task_id': 'task id',
'tries': 1,
'change': mock.ANY,
'index': attempt,
} for attempt in range(10)
},
task_module.Evaluate(
self.job,
event_module.Event(type='select', target_task=None, payload={}),
evaluators.Selector(task_type='run_test')))
def testEvaluateHandleFailures_Expired(self, swarming_task_result,
swarming_tasks_new):
swarming_tasks_new.return_value = {'task_id': 'task id'}
evaluator = evaluators.SequenceEvaluator(
evaluators=(
evaluators.FilteringEvaluator(
predicate=evaluators.TaskTypeEq('find_isolate'),
delegate=evaluators.SequenceEvaluator(
evaluators=(bisection_test_util.FakeFoundIsolate(self.job),
evaluators.TaskPayloadLiftingEvaluator()))),
run_test.Evaluator(self.job),
))
self.assertNotEqual({},
task_module.Evaluate(
self.job,
event_module.Event(
type='initiate', target_task=None, payload={}),
evaluator))
swarming_task_result.return_value = {
'state': 'EXPIRED',
}
for attempt in range(10):
self.assertNotEqual({},
task_module.Evaluate(
self.job,
event_module.Event(
type='update',
target_task='run_test_chromium@aaaaaaa_%s' %
(attempt,),
payload={
'kind': 'pubsub_message',
'action': 'poll'
}), evaluator), 'Attempt #%s' % (attempt,))
self.assertEqual(
{
'run_test_chromium@aaaaaaa_%s' % (attempt,): {
'status': 'failed',
'swarming_server': 'some_server',
'dimensions': DIMENSIONS,
'errors': [{
'reason': 'SwarmingExpired',
'message': mock.ANY
},],
'extra_args': [],
'swarming_request_body': {
'name': mock.ANY,
'user': mock.ANY,
'priority': mock.ANY,
'task_slices': mock.ANY,
'tags': mock.ANY,
'pubsub_auth_token': mock.ANY,
'pubsub_topic': mock.ANY,
'pubsub_userdata': mock.ANY,
'service_account': mock.ANY,
},
'swarming_task_result': {
'state': 'EXPIRED',
},
'swarming_task_id': 'task id',
'tries': 1,
'change': mock.ANY,
'index': attempt,
} for attempt in range(10)
},
task_module.Evaluate(
self.job,
event_module.Event(type='select', target_task=None, payload={}),
evaluators.Selector(task_type='run_test')))
def testEvaluateHandleFailures_Retry(self, *_):
self.skipTest('Deferring implementation pending design.')
class ValidatorTest(test.TestCase):
def setUp(self):
super(ValidatorTest, self).setUp()
self.maxDiff = None
def testMissingDependency(self):
job = job_module.Job.New((), ())
task_module.PopulateTaskGraph(
job,
task_module.TaskGraph(
vertices=[
task_module.TaskVertex(
id='run_test_bbbbbbb_0',
vertex_type='run_test',
payload={
'swarming_server': 'some_server',
'dimensions': DIMENSIONS,
'extra_args': [],
}),
],
edges=[]))
self.assertEqual(
{
'run_test_bbbbbbb_0': {
'errors': [{
'cause': 'DependencyError',
'message': mock.ANY
}]
}
},
task_module.Evaluate(
job,
event_module.Event(type='validate', target_task=None, payload={}),
run_test.Validator()))
def testMissingDependencyInputs(self):
job = job_module.Job.New((), ())
task_module.PopulateTaskGraph(
job,
task_module.TaskGraph(
vertices=[
task_module.TaskVertex(
id='find_isolate_chromium@aaaaaaa',
vertex_type='find_isolate',
payload={
'builder': 'Some Builder',
'target': 'telemetry_perf_tests',
'bucket': 'luci.bucket',
'change': {
'commits': [{
'repository': 'chromium',
'git_hash': 'aaaaaaa',
}]
}
}),
task_module.TaskVertex(
id='run_test_chromium@aaaaaaa_0',
vertex_type='run_test',
payload={
'swarming_server': 'some_server',
'dimensions': DIMENSIONS,
'extra_args': [],
}),
],
edges=[
task_module.Dependency(
from_='run_test_chromium@aaaaaaa_0',
to='find_isolate_chromium@aaaaaaa')
],
))
# This time we're fine, there should be no errors.
self.assertEqual({},
task_module.Evaluate(
job,
event_module.Event(
type='validate', target_task=None, payload={}),
run_test.Validator()))
# Send an initiate message then catch that we've not provided the required
# payload in the task when it's ongoing.
self.assertEqual(
{
'find_isolate_chromium@aaaaaaa': mock.ANY,
'run_test_chromium@aaaaaaa_0': {
'errors': [{
'cause': 'MissingDependencyInputs',
'message': mock.ANY
}]
}
},
task_module.Evaluate(
job,
event_module.Event(type='initiate', target_task=None, payload={}),
evaluators.FilteringEvaluator(
predicate=evaluators.TaskTypeEq('find_isolate'),
delegate=evaluators.SequenceEvaluator(
evaluators=(
functools.partial(
bisection_test_util.FakeNotFoundIsolate, job),
evaluators.TaskPayloadLiftingEvaluator(),
)),
alternative=run_test.Validator()),
))
def testMissingExecutionOutputs(self):
self.skipTest('Not implemented yet.')
| 13,674 |
1,127 | <reponame>ryanloney/openvino-1
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <tuple>
#include <vector>
#include <string>
#include <memory>
#include "shared_test_classes/base/layer_test_utils.hpp"
#include "ngraph_functions/utils/ngraph_helpers.hpp"
#include "ngraph_functions/builders.hpp"
namespace SubgraphTestsDefinitions {
typedef std::tuple<
InferenceEngine::Precision, // Network Precision
std::string, // Target Device
std::map<std::string, std::string>, // Configuration
std::vector<size_t>, // Input Shapes
size_t, // Num of Split outputs (concat inputs)
bool // with FC or not
> SplitConcatMultiInputsParams;
class SplitConcatMultiInputsTest : public testing::WithParamInterface<SplitConcatMultiInputsParams>,
public LayerTestsUtils::LayerTestsCommon {
public:
static std::string getTestCaseName(testing::TestParamInfo<SplitConcatMultiInputsParams> obj);
protected:
void SetUp() override;
InferenceEngine::Blob::Ptr GenerateInput(const InferenceEngine::InputInfo &info) const override;
float inputDataMin = 0.0;
float inputDataMax = 0.2;
float inputDataResolution = 1;
int32_t seed = 1;
};
} // namespace SubgraphTestsDefinitions
| 617 |
3,539 | /*
* libwebsockets - small server side websockets and web server implementation
*
* Copyright (C) 2010 - 2021 <NAME> <<EMAIL>>
*
* 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.
*/
#include "private-lib-core.h"
void
lws_tls_session_tag_discrete(const char *vhname, const char *host,
uint16_t port, char *buf, size_t len)
{
/*
* We have to include the vhost name in the session tag, since
* different vhosts may make connections to the same endpoint using
* different client certs.
*/
lws_snprintf(buf, len, "%s_%s_%u", vhname, host, port);
}
int
lws_tls_session_tag_from_wsi(struct lws *wsi, char *buf, size_t len)
{
const char *host;
if (!wsi)
return 1;
if (!wsi->stash)
return 1;
host = wsi->stash->cis[CIS_HOST];
if (!host)
host = wsi->stash->cis[CIS_ADDRESS];
if (!host)
return 1;
lws_tls_session_tag_discrete(wsi->a.vhost->name, host, wsi->c_port,
buf, len);
return 0;
}
| 640 |
3,483 | <reponame>extremenelson/sirius
package info.ephyra.trec;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* A parser for the TREC 8-12 QA tracks.
*
* @author <NAME>
* @version 2007-05-25
*/
public class TREC8To12Parser {
/** Type of the TREC 8 to 11 questions. */
private static final String QTYPE = "FACTOID";
/**
* Loads the questions from a file.
*
* @param filename file that contains the questions
* @return questions or <code>null</code>, if the file could not be parsed
*/
public static TRECQuestion[] loadQuestions(String filename) {
File file = new File(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String id = "";
String type = "";
String line, questionString;
TRECQuestion question;
ArrayList<TRECQuestion> questions = new ArrayList<TRECQuestion>();
while (in.ready()) {
line = in.readLine();
if (line.matches("<num>.*")) {
id = line.split(": ")[1].trim();
type = QTYPE; // TREC 8 to 11
} else if (line.matches("<type>.*")) {
type = line.split(": ")[1].trim().toUpperCase(); // TREC 12
} else if (line.matches("<desc>.*")) {
questionString = in.readLine().trim();
question = new TRECQuestion(id, type, questionString);
questions.add(question);
}
}
in.close();
return questions.toArray(new TRECQuestion[questions.size()]);
} catch (IOException e) {
return null; // file could not be parsed
}
}
/**
* Loads the patterns from a file.
*
* @param filename file that contains the patterns
* @return patterns or <code>null</code>, if the file could not be parsed
*/
public static TRECPattern[] loadPatterns(String filename) {
TRECPattern[] aligned = loadPatternsAligned(filename);
if (aligned == null) return null;
// remove null-entries
ArrayList<TRECPattern> patterns = new ArrayList<TRECPattern>();
for (TRECPattern pattern : aligned)
if (pattern != null) patterns.add(pattern);
return patterns.toArray(new TRECPattern[patterns.size()]);
}
/**
* Loads the patterns from a file. For each skipped question ID in the input
* file, a <code>null</code> entry is added to the array of patterns.
*
* @param filename file that contains the patterns
* @return patterns aligned to question IDs or <code>null</code>, if the
* file could not be parsed
*/
public static TRECPattern[] loadPatternsAligned(String filename) {
File file = new File(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String[] line;
int id, lastId = -1;
String regex = "";
TRECPattern pattern;
ArrayList<TRECPattern> patterns = new ArrayList<TRECPattern>();
while (in.ready()) {
line = in.readLine().split(" ", 2);
id = Integer.parseInt(line[0]);
if (id == lastId)
// if still the same pattern, append the regular expression
regex += "|" + line[1].trim();
else { // next pattern
if (!(lastId == -1)) {
// if not first pattern, add previous pattern to results
regex += ")";
pattern = new TRECPattern(Integer.toString(lastId),
new String[] {regex});
patterns.add(pattern);
// some number might have been skipped
for (int i = lastId + 1; i < id; i++)
patterns.add(null);
}
// start new pattern
lastId = id;
regex = "(?i)(" + line[1].trim(); // case is ignored
}
}
// add last pattern to results
regex += ")";
pattern = new TRECPattern(Integer.toString(lastId),
new String[] {regex});
patterns.add(pattern);
in.close();
return patterns.toArray(new TRECPattern[patterns.size()]);
} catch (IOException e) {
return null; // file could not be parsed
}
}
/**
* Loads the answers to the TREC9 questions from a file.
*
* @param filename file that contains the answers
* @return answers or <code>null</code>, if the file could not be parsed
*/
public static TRECAnswer[] loadTREC9Answers(String filename) {
File file = new File(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String id;
String line, answerString;
TRECAnswer answer;
ArrayList<TRECAnswer> answers = new ArrayList<TRECAnswer>();
while (in.ready()) {
line = in.readLine();
if (line.matches("Question.*")) {
id = line.split(" ")[1];
in.readLine();
in.readLine();
answerString = in.readLine().trim();
answer = new TRECAnswer(id, answerString);
answers.add(answer);
}
}
in.close();
return answers.toArray(new TRECAnswer[answers.size()]);
} catch (IOException e) {
return null; // file could not be parsed
}
}
}
| 2,101 |
310 | //==============================================================
// Copyright © 2020 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <oneapi/dpl/algorithm>
#include <oneapi/dpl/execution>
#include <oneapi/dpl/iterator>
#include <iostream>
#include <CL/sycl.hpp>
using namespace sycl;
using namespace oneapi::dpl::execution;
int main() {
//const int n = 10;
//const int k = 5;
const int num_elements = 5;
auto R = range(num_elements);
//Create queue with default selector
queue q;
std::cout << "Device : " << q.get_device().get_info<info::device::name>() << std::endl;
//Initialize the input vector for search
std::vector<int> input_seq{0, 2, 2, 2, 3, 3, 3, 3, 6, 6};
//Initialize the input vector for search pattern
std::vector<int> input_pattern{0, 2, 4, 7, 6};
//Output vector where we get the results back
std::vector<int> output_values(num_elements,0);
//Create buffers for the above vectors
buffer buf_in(input_seq);
buffer buf_seq(input_pattern);
buffer buf_out(output_values);
// create buffer iterators
auto keys_begin = oneapi::dpl::begin(buf_in);
auto keys_end = oneapi::dpl::end(buf_in);
auto vals_begin = oneapi::dpl::begin(buf_seq);
auto vals_end = oneapi::dpl::end(buf_seq);
auto result_begin = oneapi::dpl::begin(buf_out);
// use policy for algorithms execution
auto policy = make_device_policy(q);
//function object to be passed to sort function
//Calling the oneDPL binary search algorithm. We pass in the policy, the buffer iterators for the input vectors and the output.
// Default comparator is the operator < used here.
const auto i = oneapi::dpl::binary_search(policy,keys_begin,keys_end,vals_begin,vals_end,result_begin);
// 3.Checking results by creating the host accessors
host_accessor result_vals(buf_out,read_only);
std::cout<< "Input sequence = [";
std::copy(input_seq.begin(),input_seq.end(),std::ostream_iterator<int>(std::cout," "));
std::cout <<"]"<< "\n";
std::cout<< "Search sequence = [";
std::copy(input_pattern.begin(),input_pattern.end(),std::ostream_iterator<int>(std::cout," "));
std::cout <<"]"<< "\n";
std::cout<< "Search results = [";
std::copy(output_values.begin(),output_values.end(),std::ostream_iterator<bool>(std::cout," "));
std::cout <<"]"<< "\n";
return 0;
}
| 929 |
340 | <reponame>georgio/kremlin<filename>kremlib/c/fstar_int16.c
/* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#include "FStar_Int16.h"
Prims_string FStar_Int16_to_string(int16_t i) {
char *buf = KRML_HOST_MALLOC(24);
KRML_HOST_SNPRINTF(buf, 24, "%"PRId16, i);
return buf;
}
| 144 |
1,159 | <filename>src/base/gui/shadow.h
#ifndef GUI_SHADOW
#define GUI_SHADOW
#include "widget.h"
namespace GUI
{
class Shadow
{
public:
enum class Side : uint32_t { Left, Right };
Shadow(Widget *parent, Side side);
void draw(Gfx::ICanvas &canvas);
private:
Widget *parent;
Side side;
};
}
#endif
| 121 |
4,241 | #include "test.h"
#include <float.h>
#include <stdalign.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdnoreturn.h>
int main() {
printf("OK\n");
return 0;
}
| 86 |
496 | '''
Import the necessary libraries
'''
# !pip install selenium
from selenium import webdriver
import time
import pandas as pd
from bs4 import BeautifulSoup as soup
'''
Define the browser/driver and open the desired webpage
'''
driver = webdriver.Chrome(
'D:\\Softwares\\chromedriver_win32\\chromedriver.exe'
)
driver.get('https://www.cardekho.com/filter/new-cars')
'''
Keep scrolling automatically and extract the data from the webpage and store it
'''
for i in range(0, 20):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(1)
driver.execute_script("window.scrollTo(0, \
(document.body.scrollHeight)*0.73)")
time.sleep(1)
res = driver.execute_script("return document.documentElement.outerHTML")
driver.quit()
psoup = soup(res, "lxml")
containers = psoup.findAll(
"div", {"gsc_col-md-12 gsc_col-sm-12 gsc_col-xs-12 append_list"}
)
cars = []
prices = []
engines = []
mileages = []
for i in containers:
# cars.append(i.div.img["alt"])
price = i.findAll("div", {"class": "price"})
q = price[0].text
s = ""
for h in q:
if h != "*":
s += h
else:
break
prices.append(s)
m = i.findAll("div", {"class": "dotlist"})
f = m[0].findAll("span", {"title": "Mileage"})
if len(f) != 0:
mileages.append(f[0].text)
else:
mileages.append(" ")
e = m[0].findAll("span", {"title": "Engine Displacement"})
if len(e) != 0:
engines.append(e[0].text)
else:
engines.append(" ")
df = pd.DataFrame(
{
'Car Name': cars,
'Price': prices,
'Engine': engines,
'Mileage': mileages
}
)
df.to_csv('carScrap.csv', index=False, encoding='utf-8')
| 745 |
3,083 | // Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.security.zynamics.binnavi.yfileswrap.Gui.MainWindow.ProjectTree.Nodes.Root.Component;
import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.ZyGraph2DView;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.ScrollPaneConstants;
import y.view.DefaultBackgroundRenderer;
import y.view.Graph2D;
import y.view.Graph2DView;
/**
* Component that is shown in the right side of the main window when the root node of the project
* tree is selected.
*/
public final class CRootNodeComponent extends CAbstractNodeComponent {
/**
* Used for serialization.
*/
private static final long serialVersionUID = 8966402427627112682L;
/**
* Background image that shows the BinNavi logo.
*/
private final Image BACKGROUND_IMAGE = new ImageIcon(
CMain.class.getResource("data/binnavi_logo3.png")).getImage();
/**
* Creates a new component object.
*/
public CRootNodeComponent() {
super(new BorderLayout());
createGui();
}
/**
* Creates the GUI of this component.
*/
private void createGui() {
final Graph2DView view = new ZyGraph2DView(new Graph2D());
view.setScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
final DefaultBackgroundRenderer backgroundRenderer = new DefaultBackgroundRenderer(view);
backgroundRenderer.setImage(BACKGROUND_IMAGE);
backgroundRenderer.setMode(DefaultBackgroundRenderer.CENTERED);
backgroundRenderer.setColor(Color.white);
view.setBackgroundRenderer(backgroundRenderer);
add(view, BorderLayout.CENTER);
}
@Override
public void dispose() {
// No listeners to dispose
}
}
| 801 |
359 | /**
* Touhou Community Reliant Automatic Patcher
* BGM modding library for games using uncompressed PCM music
*
* ----
*
* Header file, covering all source files.
*/
#pragma once
#include <memory>
/// String constants
/// ----------------
extern const stringref_t LOOP_INFIX;
/// ----------------
/// Sampling rate / bit depth / channel structure
/// ---------------------------------------------
#define PCM_FORMAT_DESC_FMT "%u Hz / %u Bit / %uch"
struct pcm_format_t {
uint32_t samplingrate;
uint16_t bitdepth;
uint16_t channels;
bool operator ==(const pcm_format_t &other) const {
return samplingrate == other.samplingrate
&& bitdepth == other.bitdepth
&& channels == other.channels;
}
bool operator !=(const pcm_format_t &other) const {
return !(*this == other);
}
// "Function returning array is not allowed", so...
struct desc_t {
char str[
DECIMAL_DIGITS_BOUND(decltype(samplingrate)) - 2
+ DECIMAL_DIGITS_BOUND(decltype(bitdepth)) - 2
+ DECIMAL_DIGITS_BOUND(decltype(channels)) - 2
+ sizeof(PCM_FORMAT_DESC_FMT)
];
size_t len;
} to_string() const
{
desc_t ret;
ret.len = snprintf(
ret.str, sizeof(ret.str), PCM_FORMAT_DESC_FMT,
samplingrate, bitdepth, channels
);
return ret;
}
// Writes this format to the given variety of a WAVEFORMAT* structure.
void patch(WAVEFORMATEX &wfx) const;
void patch(PCMWAVEFORMAT &pwf) const;
};
/// ---------------------------------------------
/// Track class
/// -----------
struct track_t {
const pcm_format_t pcmf;
// Sizes are in decoded PCM bytes according to [pcmf].
const size_t intro_size;
const size_t total_size;
// Single decoding call that also handles looping. Should return
// the number of bytes actually decoded, which can be less than
// [size]. If an error occured, it should return -1, and show a
// message box.
virtual size_t decode_single(void *buf, size_t size) = 0;
// Seeks to the raw decoded audio byte, according to [pcmf].
// Can get arbitrarily large, therefore the looping section
// should be treated as infinitely long.
virtual void seek_to_byte(size_t byte) = 0;
// *Always* fills [buf] entirely. Returns true if successful,
// or false in case of an unrecoverable decoding error, in
// which case the buffer is filled with zeroes.
bool decode(void *buf, size_t size);
track_t(
const pcm_format_t &pcmf,
const size_t &intro_size, const size_t &total_size
)
: pcmf(pcmf), intro_size(intro_size), total_size(total_size) {
}
virtual ~track_t() {}
};
struct pcm_part_info_t {
const pcm_format_t pcmf;
// Size of this part, in decoded PCM bytes according to [pcmf].
const size_t part_bytes;
};
// Base class for an individual intro or loop file.
// Should be derived for each supported codec.
struct pcm_part_t : public pcm_part_info_t {
// Single decoding call. Should return the number of bytes actually
// decoded, which can be less than [size]. If an error occured, it
// should return -1, and show a message box.
virtual size_t part_decode_single(void *buf, size_t size) = 0;
// Seeks to the raw decoded, non-interleaved audio sample (byte
// divided by bitdepth and number of channels). Guaranteed to be
// less than the total number of samples in the stream.
virtual void part_seek_to_sample(size_t sample) = 0;
pcm_part_t(pcm_part_info_t &&info)
: pcm_part_info_t(info) {
}
virtual ~pcm_part_t() {}
};
// Generic implementation for PCM-based codecs, with separate intro and
// loop files.
struct track_pcm_t : public track_t {
std::unique_ptr<pcm_part_t> intro;
std::unique_ptr<pcm_part_t> loop;
pcm_part_t *cur;
/// track_t functions
size_t decode_single(void *buf, size_t size);
void seek_to_byte(size_t byte);
track_pcm_t(
std::unique_ptr<pcm_part_t> &&intro_in,
std::unique_ptr<pcm_part_t> &&loop_in
) : track_t(
intro_in->pcmf,
loop_in ? intro_in->part_bytes : 0,
intro_in->part_bytes + (loop_in ? loop_in->part_bytes : 0)
) {
intro = std::move(intro_in);
loop = std::move(loop_in);
cur = intro.get();
}
virtual ~track_pcm_t() {}
};
// Opens [stream] as a part of a modded track, using a specific codec.
// Should show a message box if [stream] is not a valid file for this codec.
typedef std::unique_ptr<pcm_part_t> pcm_part_open_t(HANDLE &&stream);
std::unique_ptr<track_pcm_t> pcm_open(
pcm_part_open_t &codec_open, HANDLE &&intro, HANDLE &&loop
);
/// -----------
/// Codecs
/// ------
struct codec_t {
stringref_t ext;
pcm_part_open_t &open;
};
extern const codec_t CODECS[3];
/// ------
/// Stack file resolution
/// ---------------------
std::unique_ptr<track_t> stack_bgm_resolve(const stringref_t &basename);
/// ---------------------
/// Streaming APIs
/// --------------
// MMIO implementation
// -------------------
namespace mmio
{
// Initializes BGM modding for the MMIO API.
// No module function, has to be called manually.
int detour(void);
bool is_modded_handle(HMMIO hmmio);
}
// -------------------
/// --------------
/// Error reporting and debugging
/// -----------------------------
extern logger_t bgmmod_log;
#define bgmmod_debugf(text, ...) \
log_debugf("[BGM] " text, ##__VA_ARGS__)
// TODO: Filename?
#define bgmmod_format_log(format) \
bgmmod_log.prefixed("(" format ") ")
/// -----------------------------
| 1,895 |
5,133 | <gh_stars>1000+
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.ap.test.nullcheck.strategy;
public class HouseDto {
private String owner;
private Integer number;
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
| 212 |
488 | class Foo
{
Class bar()
{
return gnu.classpath.VMStackWalker.getCallingClass();
}
}
public class WalkerTest
{
public static void main(String[] argv)
{
System.out.println(new Foo().bar());
}
}
| 80 |
4,071 | /* Copyright (C) 2016-2018 Alibaba Group Holding Limited
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.
==============================================================================*/
// Copyright 2018 Alibaba Inc. All Rights Reserved.
#include "tdm/local_store.h"
#include <stdio.h>
#include <string>
#include <vector>
#include "tdm/store_kv.pb.h"
namespace tdm {
LocalStore::LocalStore(): Store() {
}
LocalStore::~LocalStore() {
}
bool LocalStore::Init(const std::string& config) {
(void) config;
return true;
}
bool LocalStore::Dump(const std::string& filename) {
FILE* fp = fopen(filename.c_str(), "wb");
if (fp == nullptr) {
return false;
}
for (auto it = data_.begin(); it != data_.end(); ++it) {
KVItem item;
item.set_key(it->first);
item.set_value(it->second);
std::string content;
if (!item.SerializeToString(&content)) {
fclose(fp);
return false;
}
int len = content.size();
fwrite(&len, sizeof(len), 1, fp);
fwrite(content.data(), 1, len, fp);
}
fclose(fp);
return true;
}
bool LocalStore::Get(const std::string& key, std::string* value) {
auto it = data_.find(key);
if (it == data_.end()) {
return false;
}
*value = it->second;
return true;
}
bool LocalStore::Put(const std::string& key, const std::string& value) {
return data_.insert({key, value}).second;
}
std::vector<bool>
LocalStore::MGet(const std::vector<std::string>& keys,
std::vector<std::string>* values) {
std::vector<bool> ret(keys.size(), false);
if (values == nullptr) {
return ret;
}
if (values->size() != keys.size()) {
values->resize(keys.size());
}
for (size_t i = 0; i < keys.size(); ++i) {
ret[i] = Get(keys[i], &values->at(i));
}
return ret;
}
std::vector<bool>
LocalStore::MPut(const std::vector<std::string>& keys,
const std::vector<std::string>& values) {
std::vector<bool> rets(keys.size(), false);
for (size_t i = 0; i < keys.size(); ++i) {
rets[i] = Put(keys[i], values[i]);
}
return rets;
}
bool LocalStore::Remove(const std::string& key) {
data_.erase(key);
return true;
}
class LocalStoreFactory: public StoreFactory {
public:
Store* NewStore(const std::string& config) {
LocalStore* store = new LocalStore();
if (!store->Init(config)) {
delete store;
return NULL;
}
return store;
}
};
class LocalStoreRegister {
public:
LocalStoreRegister() {
Store::RegisterStoreFactory("LOCAL", new LocalStoreFactory);
}
};
static LocalStoreRegister registrar;
} // namespace tdm
| 1,094 |
335 | <reponame>Safal08/Hacktoberfest-1<filename>L/Larynx_noun.json
{
"word": "Larynx",
"definitions": [
"The hollow muscular organ forming an air passage to the lungs and holding the vocal cords in humans and other mammals; the voice box."
],
"parts-of-speech": "Noun"
} | 109 |
828 | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.dataql.fx.encryt;
/**
* 摘要算法类型枚举
* @author 赵永春 (<EMAIL>)
* @version : 2020-03-31
*/
public enum DigestType {
MD5("MD5"), //
SHA("SHA"), //
SHA1("SHA1"), //
SHA256("SHA256"), //
SHA512("SHA512"); //
private final String digestDesc;
private DigestType(String digestDesc) {
this.digestDesc = digestDesc;
}
public static DigestType formString(String digestString) {
for (DigestType digestType : DigestType.values()) {
if (digestType.name().equalsIgnoreCase(digestString)) {
return digestType;
}
}
return null;
}
public String getDigestDesc() {
return digestDesc;
}
} | 514 |
387 | /**
* Copyright 2017-2021 LinkedIn Corporation. All rights reserved.
* Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.coral.common.functions;
/**
* Exception indicating failure to resolve user-defined or builtin
* function name in SQL
*/
public class UnknownSqlFunctionException extends RuntimeException {
private final String functionName;
/**
* Constructs an exception indicating unknown function name
* @param functionName function name that could not be resolved
*/
public UnknownSqlFunctionException(String functionName) {
super(String.format("Unknown function name: %s", functionName));
this.functionName = functionName;
}
public String getFunctionName() {
return functionName;
}
}
| 207 |
662 | """Writer utils."""
import io
import struct
import typing
import numpy as np
try:
import crc32c
except ImportError:
crc32c = None
from tfrecord import example_pb2
class TFRecordWriter:
"""Opens a TFRecord file for writing.
Params:
-------
data_path: str
Path to the tfrecord file.
"""
def __init__(self, data_path: str) -> None:
self.file = io.open(data_path, "wb")
def close(self) -> None:
"""Close the tfrecord file."""
self.file.close()
def write(self, datum: typing.Dict[str, typing.Tuple[typing.Any, str]],
sequence_datum: typing.Union[typing.Dict[str, typing.Tuple[typing.List[typing.Any], str]], None] = None,
) -> None:
"""Write an example into tfrecord file. Either as a Example
SequenceExample depending on the presence of `sequence_datum`.
If `sequence_datum` is None (by default), this writes a Example
to file. Otherwise, it writes a SequenceExample to file, assuming
`datum` to be the context and `sequence_datum` to be the sequential
features.
Params:
-------
datum: dict
Dictionary of tuples of form (value, dtype). dtype can be
"byte", "float" or "int".
sequence_datum: dict
By default, it is set to None. If this value is present, then the
Dictionary of tuples of the form (value, dtype). dtype can be
"byte", "float" or "int". value should be the sequential features.
"""
if sequence_datum is None:
record = TFRecordWriter.serialize_tf_example(datum)
else:
record = TFRecordWriter.serialize_tf_sequence_example(datum, sequence_datum)
length = len(record)
length_bytes = struct.pack("<Q", length)
self.file.write(length_bytes)
self.file.write(TFRecordWriter.masked_crc(length_bytes))
self.file.write(record)
self.file.write(TFRecordWriter.masked_crc(record))
@staticmethod
def masked_crc(data: bytes) -> bytes:
"""CRC checksum."""
mask = 0xa282ead8
crc = crc32c.crc32(data)
masked = ((crc >> 15) | (crc << 17)) + mask
masked = np.uint32(masked & np.iinfo(np.uint32).max)
masked_bytes = struct.pack("<I", masked)
return masked_bytes
@staticmethod
def serialize_tf_example(datum: typing.Dict[str, typing.Tuple[typing.Any, str]]) -> bytes:
"""Serialize example into tfrecord.Example proto.
Params:
-------
datum: dict
Dictionary of tuples of form (value, dtype). dtype can be
"byte", "float" or "int".
Returns:
--------
proto: bytes
Serialized tfrecord.example to bytes.
"""
feature_map = {
"byte": lambda f: example_pb2.Feature(
bytes_list=example_pb2.BytesList(value=f)),
"float": lambda f: example_pb2.Feature(
float_list=example_pb2.FloatList(value=f)),
"int": lambda f: example_pb2.Feature(
int64_list=example_pb2.Int64List(value=f))
}
def serialize(value, dtype):
if not isinstance(value, (list, tuple, np.ndarray)):
value = [value]
return feature_map[dtype](value)
features = {key: serialize(value, dtype) for key, (value, dtype) in datum.items()}
example_proto = example_pb2.Example(features=example_pb2.Features(feature=features))
return example_proto.SerializeToString()
@staticmethod
def serialize_tf_sequence_example(context_datum: typing.Dict[str, typing.Tuple[typing.Any, str]],
features_datum: typing.Dict[str, typing.Tuple[typing.List[typing.Any], str]],
) -> bytes:
"""Serialize sequence example into tfrecord.SequenceExample proto.
Params:
-------
context_datum: dict
Dictionary of tuples of form (value, dtype). dtype can be
"byte", "float" or int.
features_datum: dict
Same as `context_datum`, but for the features.
Returns:
--------
proto: bytes
Serialized tfrecord.SequenceExample to bytes.
"""
feature_map = {
"byte": lambda f: example_pb2.Feature(
bytes_list=example_pb2.BytesList(value=f)),
"float": lambda f: example_pb2.Feature(
float_list=example_pb2.FloatList(value=f)),
"int": lambda f: example_pb2.Feature(
int64_list=example_pb2.Int64List(value=f))
}
def serialize(value, dtype):
if not isinstance(value, (list, tuple, np.ndarray)):
value = [value]
return feature_map[dtype](value)
def serialize_repeated(value, dtype):
feature_list = example_pb2.FeatureList()
for v in value:
feature_list.feature.append(serialize(v, dtype))
return feature_list
context = {key: serialize(value, dtype) for key, (value, dtype) in context_datum.items()}
features = {key: serialize_repeated(value, dtype) for key, (value, dtype) in features_datum.items()}
context = example_pb2.Features(feature=context)
features = example_pb2.FeatureLists(feature_list=features)
proto = example_pb2.SequenceExample(context=context, feature_lists=features)
return proto.SerializeToString()
| 2,514 |
2,094 | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: Dataset.h (data)
// Authors: <NAME>
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "DataVector.h"
#include "Dataset.h"
#include "Example.h"
#include "ExampleIterator.h"
#include <utilities/include/AbstractInvoker.h>
#include <utilities/include/TypeTraits.h>
#include <functional>
#include <ostream>
#include <random>
#include <vector>
namespace ell
{
namespace data
{
// forward declaration of Dataset, since AnyDataset and Dataset have a cyclical dependence
template <typename ExampleType>
class Dataset;
/// <summary> Polymorphic interface for datasets, enables dynamic_cast operations. </summary>
struct DatasetBase
{
virtual ~DatasetBase() = default;
};
/// <summary> Implements an untyped data set. This class is used to send data to trainers and evaluators </summary>
class AnyDataset
{
public:
/// <summary> Constructs an instance of AnyDataset. </summary>
///
/// <param name="pDataset"> Pointer to an DatasetBase. </param>
/// <param name="fromIndex"> Zero-based index of the first example referenced by the iterator. </param>
/// <param name="size"> The number of examples referenced by the iterator. </param>
AnyDataset(const DatasetBase* pDataset, size_t fromIndex, size_t size);
/// <summary> Gets an example iterator of a given example type. </summary>
///
/// <typeparam name="ExampleType"> Example type. </typeparam>
///
/// <returns> The example iterator. </returns>
template <typename ExampleType>
ExampleIterator<ExampleType> GetExampleIterator() const;
/// <summary> Returns the number of examples in the dataset. </summary>
///
/// <returns> Number of examples. </returns>
size_t NumExamples() const { return _size; }
private:
const DatasetBase* _pDataset;
size_t _fromIndex;
size_t _size;
};
/// <summary> A data set of a specific example type. </summary>
template <typename DatasetExampleT>
class Dataset : public DatasetBase
{
public:
using DatasetExampleType = DatasetExampleT;
/// <summary> Iterator class. </summary>
template <typename IteratorExampleType>
class DatasetExampleIterator : public IExampleIterator<IteratorExampleType>
{
public:
using InternalIteratorType = typename std::vector<DatasetExampleType>::const_iterator;
/// <summary></summary>
DatasetExampleIterator(InternalIteratorType begin, InternalIteratorType end);
/// <summary> Returns true if the iterator is currently pointing to a valid iterate. </summary>
///
/// <returns> true if the iterator is currently pointing to a valid iterate. </returns>
bool IsValid() const override { return _current < _end; }
/// <summary> Proceeds to the Next iterate. </summary>
void Next() override { ++_current; }
/// <summary> Gets the current example pointer to by the iterator. </summary>
///
/// <returns> The example. </returns>
IteratorExampleType Get() const override { return _current->template CopyAs<IteratorExampleType>(); }
private:
InternalIteratorType _current;
InternalIteratorType _end;
};
Dataset() = default;
Dataset(Dataset&&) = default;
Dataset(const Dataset&) = delete;
/// <summary> Constructs an instance of Dataset by making shallow copies of supervised examples. </summary>
///
/// <param name="exampleIterator"> The example iterator. </param>
Dataset(ExampleIterator<DatasetExampleType> exampleIterator);
/// <summary> Constructs an instance of Dataset from an AnyDataset. </summary>
///
/// <param name="anyDataset"> the AnyDataset. </param>
Dataset(const AnyDataset& anyDataset);
Dataset<DatasetExampleType>& operator=(Dataset&&) = default;
Dataset<DatasetExampleType>& operator=(const Dataset&) = delete;
/// <summary> Swaps the contents of this dataset with the contents of another. </summary>
///
/// <param name="other"> The other dataset. </param>
void Swap(Dataset& other);
/// <summary> Returns the number of examples in the data set. </summary>
///
/// <returns> The number of examples. </returns>
size_t NumExamples() const { return _examples.size(); }
/// <summary> Returns the maximal size of any example. </summary>
///
/// <returns> The maximal size of any example. </returns>
size_t NumFeatures() const { return _numFeatures; }
/// <summary> Returns a reference to an example. </summary>
///
/// <param name="index"> Zero-based index of the row. </param>
///
/// <returns> Reference to the specified example. </returns>
DatasetExampleType& GetExample(size_t index);
/// <summary> Returns a const reference to an example. </summary>
///
/// <param name="index"> Zero-based index of the row. </param>
///
/// <returns> Const reference to the specified example. </returns>
const DatasetExampleType& GetExample(size_t index) const;
/// <summary> Returns a reference to an example. </summary>
///
/// <param name="index"> Zero-based index of the row. </param>
///
/// <returns> Reference to the specified example. </returns>
DatasetExampleType& operator[](size_t index);
/// <summary> Returns a const reference to an example. </summary>
///
/// <param name="index"> Zero-based index of the row. </param>
///
/// <returns> Const reference to the specified example. </returns>
const DatasetExampleType& operator[](size_t index) const;
/// <summary> Returns an iterator that traverses the examples. </summary>
///
/// <param name="firstExample"> Zero-based index of the first example to iterate over. </param>
/// <param name="size"> The number of examples to iterate over, a value of zero means all
/// the way to the end. </param>
///
/// <returns> The iterator. </returns>
template <typename IteratorExampleType = DatasetExampleType>
ExampleIterator<IteratorExampleType> GetExampleIterator(size_t fromIndex = 0, size_t size = 0) const;
/// <summary> Gets an example reference iterator. </summary>
///
/// <param name="firstExample"> Zero-based index of the first example to iterate over. </param>
/// <param name="size"> The number of examples to iterate over, a value of zero means all
/// the way to the end. </param>
///
/// <returns> The example reference iterator. </returns>
ExampleReferenceIterator<DatasetExampleType> GetExampleReferenceIterator(size_t fromIndex = 0, size_t size = 0) const;
/// <summary> Returns an AnyDataset that represents an interval of examples from this dataset. </summary>
///
/// <param name="firstExample"> Zero-based index of the first example in the AnyDataset. </param>
/// <param name="size"> The number of examples to include, a value of zero means all
/// the way to the end. </param>
///
/// <returns> The dataset. </returns>
AnyDataset GetAnyDataset(size_t fromIndex = 0, size_t size = 0) const { return AnyDataset(this, fromIndex, size); }
/// <summary> Returns a dataset whose examples have been converted from this dataset. </summary>
///
/// <typeparam name="otherExampleType"> Example type returned by the transformation function. </typeparam>
/// <param name="transformationFunction"> The function that is called on each example, returning the transformed example. </param>
///
/// <returns> The dataset. </returns>
template <typename otherExampleType>
Dataset<otherExampleType> Transform(std::function<otherExampleType(const DatasetExampleType&)> transformationFunction);
/// <summary> Adds an example at the bottom of the matrix. </summary>
///
/// <param name="example"> The example. </param>
void AddExample(DatasetExampleType example);
/// <summary> Erases all of the examples in the Dataset. </summary>
void Reset();
/// <summary> Permutes the rows of the matrix so that a prefix of them is uniformly distributed. </summary>
///
/// <param name="rng"> [in,out] The random number generator. </param>
/// <param name="prefixSize"> Size of the prefix that should be uniformly distributed, zero to permute the entire data set. </param>
void RandomPermute(std::default_random_engine& rng, size_t prefixSize = 0);
/// <summary> Randomly permutes a range of rows in the data set so that a prefix of them is uniformly distributed. </summary>
///
/// <param name="rng"> [in,out] The random number generator. </param>
/// <param name="rangeFirstIndex"> Zero-based index of the firest example in the range. </param>
/// <param name="rangeSize"> Size of the range. </param>
/// <param name="prefixSize"> Size of the prefix that should be uniformly distributed, zero to permute the entire range. </param>
void RandomPermute(std::default_random_engine& rng, size_t rangeFirstIndex, size_t rangeSize, size_t prefixSize = 0);
/// <summary> Choses an example uniformly from a given range and swaps it with a given example (which can either be inside or outside of the range).
///
/// <param name="rng"> [in,out] The random number generator. </param>
/// <param name="targetExampleIndex"> Zero-based index of the target example. </param>
/// <param name="rangeFirstIndex"> Index of the first example in the range from which the example is chosen. </param>
/// <param name="rangeSize"> Number of examples in the range from which the example is chosen. </param>
void RandomSwap(std::default_random_engine& rng, size_t targetExampleIndex, size_t rangeFirstIndex, size_t rangeSize);
/// <summary> Sorts an interval of examples by a certain key. </summary>
///
/// <typeparam name="SortKeyType"> Type of the sort key. </typeparam>
/// <param name="sortKey"> A function that takes const reference to DatasetExampleType and returns a sort key. </param>
/// <param name="fromIndex"> Zero-based index of the first row to sort. </param>
/// <param name="size"> The number of examples to sort. </param>
template <typename SortKeyType>
void Sort(SortKeyType sortKey, size_t fromIndex = 0, size_t size = 0);
/// <summary> Partitions an iterval of examples by a certain Boolean predicate (similar to sorting
/// by the predicate, but in linear time). </summary>
///
/// <typeparam name="PartitionKeyType"> Type of predicate. </typeparam>
/// <param name="sortKey"> A function that takes const reference to DatasetExampleType and returns a
/// bool. </param>
/// <param name="fromIndex"> Zero-based index of the first row of the interval. </param>
/// <param name="size"> The number of examples in the interval. </param>
template <typename PartitionKeyType>
void Partition(PartitionKeyType partitionKey, size_t fromIndex = 0, size_t size = 0);
/// <summary> Prints this object. </summary>
///
/// <param name="os"> [in,out] Stream to write data to. </param>
/// <param name="tabs"> The number of tabs. </param>
/// <param name="fromIndex"> Zero-based index of the first row to print. </param>
/// <param name="size"> The number of rows to print, or 0 to print until the end. </param>
void Print(std::ostream& os, size_t tabs = 0, size_t fromIndex = 0, size_t size = 0) const;
private:
size_t CorrectRangeSize(size_t fromIndex, size_t size) const;
std::vector<DatasetExampleType> _examples;
size_t _numFeatures = 0;
};
// friendly names
typedef Dataset<AutoSupervisedExample> AutoSupervisedDataset;
typedef Dataset<AutoSupervisedMultiClassExample> AutoSupervisedMultiClassDataset;
typedef Dataset<DenseSupervisedExample> DenseSupervisedDataset;
/// <summary> Prints a data set to an ostream. </summary>
///
/// <param name="os"> [in,out] The ostream to write data to. </param>
/// <param name="dataset"> The dataset. </param>
///
/// <returns> The ostream. </returns>
template <typename ExampleType>
std::ostream& operator<<(std::ostream& os, const Dataset<ExampleType>& dataset);
/// <summary> Helper function that creates a dataset from an example iterator. </summary>
///
/// <typeparam name="ExampleType"> The example type. </typeparam>
/// <param name="exampleIterator"> The example iterator. </param>
///
/// <returns> A Dataset. </returns>
template <typename ExampleType>
Dataset<ExampleType> MakeDataset(ExampleIterator<ExampleType> exampleIterator);
} // namespace data
} // namespace ell
#pragma region implementation
#include <utilities/include/Exception.h>
#include <utilities/include/Logger.h>
#include <algorithm>
#include <random>
#include <stdexcept>
namespace ell
{
namespace data
{
using namespace logging;
template <typename ExampleType>
ExampleIterator<ExampleType> AnyDataset::GetExampleIterator() const
{
auto fromIndex = _fromIndex;
auto size = _size;
auto getExampleIterator = [fromIndex, size](const auto* pDataset) { return pDataset->template GetExampleIterator<ExampleType>(fromIndex, size); };
// all Dataset types for which GetAnyDataset() is called must be listed below, in the variadic template argument.
using Invoker = utilities::AbstractInvoker<DatasetBase,
Dataset<data::AutoSupervisedExample>,
Dataset<data::DenseSupervisedExample>>;
return Invoker::Invoke<ExampleIterator<ExampleType>>(getExampleIterator, _pDataset);
}
template <typename DatasetExampleType>
template <typename IteratorExampleType>
Dataset<DatasetExampleType>::DatasetExampleIterator<IteratorExampleType>::DatasetExampleIterator(InternalIteratorType begin, InternalIteratorType end) :
_current(begin),
_end(end)
{
}
template <typename DatasetExampleType>
Dataset<DatasetExampleType>::Dataset(ExampleIterator<DatasetExampleType> exampleIterator)
{
while (exampleIterator.IsValid())
{
AddExample(exampleIterator.Get());
exampleIterator.Next();
}
}
template <typename DatasetExampleType>
Dataset<DatasetExampleType>::Dataset(const AnyDataset& anyDataset) :
Dataset(anyDataset.GetExampleIterator<DatasetExampleType>())
{
}
template <typename DatasetExampleType>
void Dataset<DatasetExampleType>::Swap(Dataset& other)
{
std::swap(_examples, other._examples);
std::swap(_numFeatures, other._numFeatures);
}
template <typename DatasetExampleType>
DatasetExampleType& Dataset<DatasetExampleType>::GetExample(size_t index)
{
return _examples[index];
}
template <typename DatasetExampleType>
const DatasetExampleType& Dataset<DatasetExampleType>::GetExample(size_t index) const
{
return _examples[index];
}
template <typename DatasetExampleType>
DatasetExampleType& Dataset<DatasetExampleType>::operator[](size_t index)
{
return _examples[index];
}
template <typename DatasetExampleType>
const DatasetExampleType& Dataset<DatasetExampleType>::operator[](size_t index) const
{
return _examples[index];
}
template <typename DatasetExampleType>
template <typename IteratorExampleType>
ExampleIterator<IteratorExampleType> Dataset<DatasetExampleType>::GetExampleIterator(size_t fromIndex, size_t size) const
{
size = CorrectRangeSize(fromIndex, size);
return ExampleIterator<IteratorExampleType>(std::make_unique<DatasetExampleIterator<IteratorExampleType>>(_examples.cbegin() + fromIndex, _examples.cbegin() + fromIndex + size));
}
template <typename DatasetExampleType>
auto Dataset<DatasetExampleType>::GetExampleReferenceIterator(size_t fromIndex, size_t size) const -> ExampleReferenceIterator<DatasetExampleType>
{
size = CorrectRangeSize(fromIndex, size);
return ExampleReferenceIterator<DatasetExampleType>(_examples.cbegin() + fromIndex, _examples.cbegin() + fromIndex + size);
}
template <typename DatasetExampleType>
void Dataset<DatasetExampleType>::AddExample(DatasetExampleType example)
{
size_t numFeatures = example.GetDataVector().PrefixLength();
_examples.push_back(std::move(example));
if (_numFeatures < numFeatures)
{
_numFeatures = numFeatures;
}
}
template <typename DatasetExampleType>
template <typename otherExampleType>
Dataset<otherExampleType> Dataset<DatasetExampleType>::Transform(std::function<otherExampleType(const DatasetExampleType&)> transformationFunction)
{
Dataset<otherExampleType> dataset;
for (auto& example : _examples)
{
dataset.AddExample(transformationFunction(example));
}
return dataset;
}
template <typename DatasetExampleType>
void Dataset<DatasetExampleType>::Reset()
{
_examples.clear();
_numFeatures = 0;
}
template <typename DatasetExampleType>
void Dataset<DatasetExampleType>::RandomPermute(std::default_random_engine& rng, size_t prefixSize)
{
prefixSize = CorrectRangeSize(0, prefixSize);
for (size_t i = 0; i < prefixSize; ++i)
{
RandomSwap(rng, i, i, _examples.size() - i);
}
}
template <typename DatasetExampleType>
void Dataset<DatasetExampleType>::RandomPermute(std::default_random_engine& rng, size_t rangeFirstIndex, size_t rangeSize, size_t prefixSize)
{
rangeSize = CorrectRangeSize(rangeFirstIndex, rangeSize);
if (prefixSize > rangeSize || prefixSize == 0)
{
prefixSize = rangeSize;
}
for (size_t s = 0; s < prefixSize; ++s)
{
size_t index = rangeFirstIndex + s;
RandomSwap(rng, index, index, rangeSize - s);
}
}
template <typename DatasetExampleType>
void Dataset<DatasetExampleType>::RandomSwap(std::default_random_engine& rng, size_t targetExampleIndex, size_t rangeFirstIndex, size_t rangeSize)
{
using std::swap;
rangeSize = CorrectRangeSize(rangeFirstIndex, rangeSize);
if (targetExampleIndex > _examples.size())
{
throw utilities::InputException(utilities::InputExceptionErrors::indexOutOfRange);
}
std::uniform_int_distribution<size_t> dist(rangeFirstIndex, rangeFirstIndex + rangeSize - 1);
size_t j = dist(rng);
swap(_examples[targetExampleIndex], _examples[j]);
}
template <typename DatasetExampleType>
template <typename SortKeyType>
void Dataset<DatasetExampleType>::Sort(SortKeyType sortKey, size_t fromIndex, size_t size)
{
size = CorrectRangeSize(fromIndex, size);
std::sort(_examples.begin() + fromIndex,
_examples.begin() + fromIndex + size,
[&](const DatasetExampleType& a, const DatasetExampleType& b) -> bool {
return sortKey(a) < sortKey(b);
});
}
template <typename DatasetExampleType>
template <typename PartitionKeyType>
void Dataset<DatasetExampleType>::Partition(PartitionKeyType partitionKey, size_t fromIndex, size_t size)
{
size = CorrectRangeSize(fromIndex, size);
std::partition(_examples.begin() + fromIndex, _examples.begin() + fromIndex + size, partitionKey);
}
template <typename DatasetExampleType>
void Dataset<DatasetExampleType>::Print(std::ostream& os, size_t tabs, size_t fromIndex, size_t size) const
{
size = CorrectRangeSize(fromIndex, size);
for (size_t index = fromIndex; index < fromIndex + size; ++index)
{
os << std::string(tabs * 4, ' ');
_examples[index].Print(os);
os << EOL;
}
}
template <typename DatasetExampleType>
std::ostream& operator<<(std::ostream& os, const Dataset<DatasetExampleType>& dataset)
{
dataset.Print(os);
return os;
}
template <typename DatasetExampleType>
size_t Dataset<DatasetExampleType>::CorrectRangeSize(size_t fromIndex, size_t size) const
{
if (size == 0 || fromIndex + size > _examples.size())
{
return _examples.size() - fromIndex;
}
return size;
}
template <typename ExampleType>
Dataset<ExampleType> MakeDataset(ExampleIterator<ExampleType> exampleIterator)
{
return Dataset<ExampleType>(std::move(exampleIterator));
}
} // namespace data
} // namespace ell
#pragma endregion implementation
| 8,115 |
2,085 | <reponame>Jette16/spacy-course
from spacy.lang.de import German
from spacy.tokens import Doc
nlp = German()
# Definiere die Getter-Funktion
def get_has_number(doc):
# Gebe zurück, ob einer der Tokens im Doc True für token.like_num zurückgibt
return any(token.like_num for token in doc)
# Registriere die Doc-Erweiterung "has_number" mit Getter-Funktion get_has_number
Doc.set_extension("has_number", getter=get_has_number)
# Verarbeite den Text und drucke den Wert des Attributs has_number
doc = nlp("Das Museum war ab 2012 fünf Jahre lang geschlossen.")
print("has_number:", doc._.has_number)
| 228 |
1,140 | # -*- coding: utf-8 -*-
"""
flaskbb.utils.views
~~~~~~~~~~~~~~~~~~~
This module contains some helpers for creating views.
:copyright: (c) 2016 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
from flaskbb.utils.helpers import render_template
from flask.views import View
class RenderableView(View):
def __init__(self, template, view):
self.template = template
self.view = view
def dispatch_request(self, *args, **kwargs):
view_model = self.view(*args, **kwargs)
return render_template(self.template, **view_model)
| 216 |
1,144 | /*
* Copyright (C) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*/
extern int pib_init(void);
| 75 |
1,178 | /*
* Copyright 2020 Makani Technologies LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIB_HDF5_TO_PCAP_H5LOG_READER_H_
#define LIB_HDF5_TO_PCAP_H5LOG_READER_H_
#include <stddef.h>
#include <stdint.h>
#include <hdf5.h>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "avionics/network/aio_node.h"
#include "avionics/network/message_type.h"
#include "common/macros.h"
#include "lib/hdf5_to_pcap/type_info.h"
#include "lib/pcap_to_hdf5/capture_info.h"
namespace h5log_reader {
// This class provides a simple HDF5 file interface abstraction.
class File {
public:
File() : file_id_(-1) {}
~File() { Close(); }
bool IsOpen() const { return file_id_ >= 0; }
bool Open(const std::string &file);
void Close();
// Determine if an HDF5 dataset exists within the file.
bool DatasetExists(const std::string &dataset_path) const;
// Export the file_id descriptor for the Dataset class.
hid_t file_id() const { return file_id_; }
private:
hid_t file_id_; // Valid when >= 0.
// We do not support copying HDF5 descriptors.
DISALLOW_COPY_AND_ASSIGN(File);
};
// This class stores a dataset in the data format described within the HDF5
// file. This format may not correspond to that of avionics_messages.h. When
// we read the HDF5 file, we convert all types to native types (e.g., little
// or big endian, depending on the host architecture).
class Dataset {
public:
Dataset()
: fields_(),
types_(),
data_(nullptr),
num_objects_(0),
object_size_(0) {}
~Dataset() { Clear(); }
// Read the fields, number of objects, and object size.
bool ReadTableOfContents(const File &file, const std::string &path);
// Read the entire dataset.
bool ReadData(const File &file, const std::string &path);
// Determine if a field exists in the dataset. Call ReadTableOfContents or
// ReadData first.
bool FieldExists(const std::string &field_path) const;
// Get total number of objects (product of all dimensions) in dataset. Call
// ReadTableOfContents or ReadData first.
int64_t GetNumObjects() const { return num_objects_; }
// Get the number of bytes in each object. Call ReadTableOfContents or
// ReadData first.
size_t GetObjectSize() const { return object_size_; }
// Export the packed HDF5 data, from the original file version, to an unpacked
// data structure of the current version. Unknown fields are set to zero.
template <typename T>
std::vector<T> Export() const {
std::vector<T> v(num_objects_);
ExportData(GetTypeInfo<T>(), v.size(), v.data());
return v;
}
// Export the packed HDF5 data, from the original file version, to an unpacked
// data structure of the current version. Unknown fields are set to zero.
template <typename T>
int64_t Export(int64_t count, T objects[]) const {
memset(objects, 0, count * sizeof(*objects));
return ExportData(GetTypeInfo<T>(), count, objects);
}
// Export the packed HDF5 data, from the original file version, to an unpacked
// data structure of the current version. Unknown fields are set to zero.
std::unique_ptr<uint8_t> Export(const TypeInfo *type_info) const;
private:
// Container to store information about each field.
struct FieldInfo {
public:
FieldInfo() : type_id(0), offset(0) {}
FieldInfo(hid_t field_type_id, size_t field_offset)
: type_id(field_type_id), offset(field_offset) {}
hid_t type_id;
size_t offset;
};
// This structure maps a flattened field path to the FieldInfo structure.
typedef std::map<std::string, FieldInfo> FieldInfoMap;
// Open/close a dataset.
hid_t Open(const File &file, const std::string &path);
void Close(hid_t dataset_id) const;
// Clear stored memory associated with the dataset.
void Clear();
// Read information from an open dataset.
int64_t ReadNumObjects(hid_t dataset_id) const;
size_t ReadObjectSize(hid_t dataset_id) const;
bool ReadTableOfContents(hid_t dataset_id);
bool ReadData(hid_t dataset_id);
// These functions create the fields_ map by recursively iterating
// through the HDF5 dataset types.
void AppendType(hid_t type_id, const std::string &path, size_t offset);
void AppendCompound(hid_t type_id, const std::string &path, size_t offset);
void AppendArray(hid_t type_id, const std::string &path, size_t offset);
void AppendArrayDim(hid_t type_id, const std::string &path, size_t offset,
size_t size, const hsize_t *dims, int32_t ndims);
// Helper function to export packed data from the original file version to an
// unpacked data structure of the current version.
int64_t ExportData(const TypeInfo *type_info, int64_t count,
void *data) const;
// Store a mapping of field paths to HDF5 types. We use this map to determine
// if fields exist and to understand their type when exporting to another
// type.
FieldInfoMap fields_;
// Store custom HDF5 types. Call H5Tclose() to free each type.
std::list<hid_t> types_;
// Data stored with original data structure in native format.
std::unique_ptr<uint8_t> data_;
int64_t num_objects_;
size_t object_size_;
// We do not support copying HDF5 descriptors.
DISALLOW_COPY_AND_ASSIGN(Dataset);
};
// This class stores arrays of the CaptureHeader, AioHeader, and message in
// the current message structure as defined in avionics_messages.h.
class MessageLog {
public:
MessageLog() :
aio_node_(), message_type_(), capture_header_(), aio_header_(),
message_(), message_info_(), num_messages_(0) {}
~MessageLog() {}
bool LoadDataset(AioNode aio_node, MessageType message_type,
const Dataset &dataset);
AioNode GetAioNode(void) const { return aio_node_; }
MessageType GetMessageType(void) const { return message_type_; }
int64_t GetNumMessages(void) const { return num_messages_; }
size_t GetPackedSize(void) const { return message_info_.pack_size; }
size_t GetUnpackedSize(void) const { return message_info_.unpack_size; }
const CaptureHeader *GetCaptureHeader(int64_t index) const;
const AioHeader *GetAioHeader(int64_t index) const;
const uint8_t *GetMessageData(int64_t index) const;
size_t PackMessageData(int64_t index, uint8_t *out) const;
private:
AioNode aio_node_;
MessageType message_type_;
std::vector<CaptureHeader> capture_header_;
std::vector<AioHeader> aio_header_;
std::shared_ptr<uint8_t> message_;
TypeInfo message_info_;
int64_t num_messages_;
};
// Get dataset group path.
// /messages/kAioNodeFcA/kMessageTypeFlightComputerSensor.
std::string GetDatasetPath(AioNode aio_node, MessageType message_type);
// Read an HDF5 file. Sets nodes and messages specify the AioNodes and
// MessageTypes to process, each represented as strings. To process all
// nodes or messages, specify an empty set. The return value contains
// a list of message logs, each representing a single dataset within the
// HDF5 file. Each dataset contains an array of messages.
typedef std::list<MessageLog> MessageLogs;
MessageLogs ReadFile(const std::string &file,
const std::set<std::string> &nodes,
const std::set<std::string> &messages);
} // namespace h5log_reader
#endif // LIB_HDF5_TO_PCAP_H5LOG_READER_H_
| 2,631 |
372 | /*
*
* (c) Copyright 1993 OPEN SOFTWARE FOUNDATION, INC.
* (c) Copyright 1993 HEWLETT-PACKARD COMPANY
* (c) Copyright 1993 DIGITAL EQUIPMENT CORPORATION
* To anyone who acknowledges that this file is provided "AS IS"
* without any express or implied warranty:
* permission to use, copy, modify, and distribute this
* file for any purpose is hereby granted without fee, provided that
* the above copyright notices and this notice appears in all source
* code copies, and that none of the names of Open Software
* Foundation, Inc., Hewlett-Packard Company, or Digital Equipment
* Corporation be used in advertising or publicity pertaining to
* distribution of the software without specific, written prior
* permission. Neither Open Software Foundation, Inc., Hewlett-
* Packard Company, nor Digital Equipment Corporation makes any
* representations about the suitability of this software for any
* purpose.
*/
/*
**
** NAME
**
** MESSAGE.C
**
** FACILITY:
**
** Interface Definition Language (IDL) Compiler
** UUID Generator Tool
**
** ABSTRACT:
**
** International error message primitive routines.
**
** VERSION: DCE 1.0
**
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef UUIDGEN /* Building for uuidgen, so include whatever's needed from nidl.h. */
# include <limits.h>
# include <stdlib.h>
# include <uuidmsg.h>
# define MESSAGE_VERSION UUIDGEN_MESSAGE_VERSION
# define MESSAGE_VERSION_USED UUIDGEN_MESSAGE_VERSION_USED
# define MESSAGE_CATALOG_DIR "/usr/bin/"
# define NLSCATVER UUIDGEN_NLSCATVER
# define NLSWRONG UUIDGEN_NLSWRONG
# ifdef _AIX
# define NL_VFPRINTF NLvfprintf
# else
# define NL_VFPRINTF vfprintf
# endif
# define BRANCHCHAR '/'
#else /* Building for nidl. */
# include <nidl.h>
# include <nidlmsg.h>
# define MESSAGE_VERSION NIDL_MESSAGE_VERSION
# define MESSAGE_VERSION_USED NIDL_MESSAGE_VERSION_USED
# define NLSCATVER NIDL_NLSCATVER
# define NLSWRONG NIDL_NLSWRONG
#endif
#include <stdio.h>
#include <string.h>
#ifdef VMS
# include <descrip.h>
# define MAX_MSG_IDENT 32 /* Max size of message identifier */
# define MAX_MSG_TEXT 256 /* Max size of VMS message text */
# define MAX_FMT_TEXT 512 /* Max size of formatted output string */
# define MSG_OPTS 0xF /* %FACIL-S-IDENT, Text */
#else
# define MAX_FMT_TEXT 512 /* Max size of formatted output string */
# ifdef HAVE_NL_TYPES_H
# include <nl_types.h>
# else
# warning Message catalog support disabled
# endif
# include <stdarg.h> /* New! Improved! Method */
# define VA_START(L, A, T) va_start(L, A)
#ifdef UUIDGEN
# ifndef PATH_MAX
# define PATH_MAX 256
# endif
#endif
#ifdef HAVE_NL_TYPES_H
static nl_catd cat_handle;
#endif /* HAVE_NL_TYPES_H */
/*
** Declare an array to hold the default messages. The text of the messages is
** read from a file generated from the message catalog.
*/
char *default_messages[] = {
"Internal idl compiler error: Invalid message number",
#include <default_msg.h>
};
static long max_message_number /* Compute number of messages. */
= (long)(sizeof(default_messages)/sizeof(char *) - 1);
# define def_message(id) \
default_messages[(id<0||id>max_message_number)?0:id]
#endif
#include <message.h>
static char msg_prefix[PATH_MAX+3];
/*
* m e s s a g e _ o p e n
*
* Function: Opens message database.
*/
void message_open
(
char *image_name __attribute__((unused))
)
#ifdef VMS
/* m e s s a g e _ o p e n (VMS) */
{
struct dsc$descriptor
ctrstr, /* Descriptor for stored text of message */
outbuf; /* Descriptor for formatted text of message */
long flags; /* Message flags */
unsigned short outlen; /* Length of formatted message */
long status;
char version_text[MAX_MSG_TEXT];
ctrstr.dsc$w_length = sizeof(version_text)-1;
ctrstr.dsc$b_dtype = DSC$K_DTYPE_T; /* Text */
ctrstr.dsc$b_class = DSC$K_CLASS_S; /* Static */
ctrstr.dsc$a_pointer = version_text; /* Point at local buffer */
strncpy(msg_prefix,image_name,PATH_MAX);
strcat(msg_prefix,": ");
#ifdef DUMPERS
status = SYS$GETMSG(MESSAGE_VERSION, &ctrstr.dsc$w_length, &ctrstr, 1, 0);
if ((status & 1) == 0)
fprintf(stderr, "%sError in error message processing!\n",msg_prefix);
version_text[ctrstr.dsc$w_length] = '\0';
if (atoi(version_text) != MESSAGE_VERSION_USED)
fprintf(stderr, "%sMessage catalog version mismatch, Expected: \"%d\", Actual: \"%s\"\n",
msg_prefix, MESSAGE_VERSION_USED, version_text );
#endif
return;
}
#else
/* m e s s a g e _ o p e n (non-VMS) */
{
#ifdef HAVE_NL_TYPES_H
char cat_name[PATH_MAX] = CATALOG_DIR "idl.cat";
strcpy(msg_prefix, "idl: ");
/*
* Open the message catalog using the image name.
*/
#ifdef AIX32
setlocale(LC_ALL, "");
#endif
cat_handle = catopen(cat_name, 0);
/* Sucessful open, check version information */
if (cat_handle != (nl_catd)-1)
{
char *version_text;
version_text = catgets(cat_handle,CAT_SET,MESSAGE_VERSION,NULL);
if (version_text != NULL && atoi(version_text) != MESSAGE_VERSION_USED)
{
fprintf(stderr, def_message(NLSCATVER),
msg_prefix, cat_name, MESSAGE_VERSION_USED, version_text);
fprintf(stderr, "\n");
fprintf(stderr, def_message(NLSWRONG), msg_prefix);
fprintf(stderr, "\n");
}
}
#endif /* HAVE_NL_TYPES_H */
return;
}
#endif /* !VMS */
/*
* m e s s a g e _ c l o s e
*
* Function: Closes message database.
*/
void message_close
(
void
)
#ifdef VMS
/* m e s s a g e _ c l o s e (VMS) */
{
return;
}
#else
/* m e s s a g e _ c l o s e (non-VMS) */
{
#ifdef HAVE_NL_TYPES_H
if (cat_handle != (nl_catd)-1) catclose(cat_handle);
#endif
return;
}
#endif
/*
* m e s s a g e _ p r i n t
*
* Function: Fetches message from database, then formats and prints message.
*
* Inputs: msgid - message ID
* [arg1,...,arg5] - Optional arguments for message formatting
*
* Outputs: message printed to stderr.
* On VAX/VMS systems, the message is output to
* SYS$ERROR/SYS$OUTPUT following the VAX/VMS conventions.
*/
void message_printv
(
long msgid,
va_list args
)
{
va_list arglist;
char format[MAX_FMT_TEXT]; /* Format string */
va_copy(arglist, args);
#ifdef HAVE_NL_TYPES_H
/*
* Output message prefix on all errors that identify the input file,
* or on every line for UUIDGEN
*/
format[0]='\0';
switch (msgid)
{
#ifndef UUIDGEN
case NIDL_EOF:
case NIDL_EOFNEAR:
case NIDL_SYNTAXNEAR:
case NIDL_FILESOURCE:
case NIDL_LINEFILE:
#else
default:
#endif
strcpy(format, msg_prefix);
}
strcat(format,catgets(cat_handle, CAT_SET, msgid, def_message(msgid)));
strcat(format,"\n");
#else
snprintf(format, sizeof(format), "%s%s\n", msg_prefix, def_message(msgid));
#endif /* HAVE_NL_TYPES_H */
NL_VFPRINTF(stderr, format, arglist);
va_end(arglist);
}
void message_print
(
long msgid,
...
)
{
va_list arglist;
va_start(arglist, msgid);
message_printv(msgid, arglist);
va_end(arglist);
}
#ifndef UUIDGEN
/*
* m e s s a g e _ s p r i n t
*
* Function: Fetches message from database and formats message.
*
* Inputs: str - Address of buffer for formatted message
* msgid - message ID
* [arg1,...,arg5] - Optional arguments for message formatting
*
* Outputs: str
*/
void message_sprint
(
char *str,
long msgid,
char *arg1,
char *arg2,
char *arg3,
char *arg4,
char *arg5
)
#ifdef VMS
/* m e s s a g e _ s p r i n t (VMS) */
{
struct dsc$descriptor
ctrstr, /* Descriptor for stored text of message */
outbuf; /* Descriptor for formatted text of message */
long flags; /* Message flags */
unsigned short outlen; /* Length of formatted message */
long status;
char msg_text[MAX_MSG_TEXT];
ctrstr.dsc$w_length = sizeof(msg_text)-1;
ctrstr.dsc$b_dtype = DSC$K_DTYPE_T; /* Text */
ctrstr.dsc$b_class = DSC$K_CLASS_S; /* Static */
ctrstr.dsc$a_pointer = msg_text; /* Point at local buffer */
flags = MSG_OPTS; /* %FAC-S-IDENT, Text */
status = SYS$GETMSG(msgid, &ctrstr.dsc$w_length, &ctrstr, flags, 0);
if ((status & 1) == 0)
fprintf(stderr, "Error in error message processing!\n");
outbuf.dsc$w_length = MAX_FMT_TEXT-1; /* Assume user buf fits max */
outbuf.dsc$b_dtype = DSC$K_DTYPE_T; /* Text */
outbuf.dsc$b_class = DSC$K_CLASS_S; /* Static */
outbuf.dsc$a_pointer = str; /* Point at user buffer */
status = SYS$FAO(&ctrstr, &outlen, &outbuf, arg1, arg2, arg3, arg4, arg5);
if ((status & 1) == 0)
fprintf(stderr, "Error in error message processing!\n");
str[outlen] = '\0';
}
#else
/* m e s s a g e _ s p r i n t (non-VMS) */
{
char *msg_text; /* Ptr to message text (storage owned by catgets) */
#ifdef HAVE_NL_TYPES_H
msg_text = catgets(cat_handle, CAT_SET, msgid, def_message(msgid));
#else
msg_text = def_message(msgid);
#endif /* HAVE_NL_TYPES_H */
/*
* Output message prefix on all errors that identify the input file
*/
switch (msgid)
{
case NIDL_EOF:
case NIDL_EOFNEAR:
case NIDL_SYNTAXNEAR:
case NIDL_FILESOURCE:
case NIDL_LINEFILE:
strcpy(str,msg_prefix); /* Add prefix to messages */
str += strlen(msg_prefix);
break;
}
NL_SPRINTF(str, msg_text, arg1, arg2, arg3, arg4, arg5);
}
#endif
/*
* m e s s a g e _ f p r i n t
*
* Function: Fetches message from database, then formats and prints message.
*
* Inputs: fid - file handle of file for output message
* msgid - message ID
* [arg1,...,arg5] - Optional arguments for message formatting
*
* Outputs: message printed to file indicated by fid not including
* any system-dependant prefix information such as the compiler
* executable name, facility, severity, etc.
*/
void message_fprint
(
FILE *fid,
long msgid,
char *arg1,
char *arg2,
char *arg3,
char *arg4,
char *arg5
)
#ifdef VMS
/* m e s s a g e _ f p r i n t (VMS) */
{
char str[MAX_FMT_TEXT]; /* Formatted message text */
struct dsc$descriptor
ctrstr, /* Descriptor for stored text of message */
outbuf; /* Descriptor for formatted text of message */
long flags; /* Message flags */
unsigned short outlen; /* Length of formatted message */
long status;
char msg_text[MAX_MSG_TEXT];
ctrstr.dsc$w_length = sizeof(msg_text)-1;
ctrstr.dsc$b_dtype = DSC$K_DTYPE_T; /* Text */
ctrstr.dsc$b_class = DSC$K_CLASS_S; /* Static */
ctrstr.dsc$a_pointer = msg_text; /* Point at local buffer */
flags = 1; /* Text Only, No facility or severity prefix */
status = SYS$GETMSG(msgid, &ctrstr.dsc$w_length, &ctrstr, flags, 0);
if ((status & 1) == 0)
fprintf(stderr, "Error in error message processing!\n");
outbuf.dsc$w_length = MAX_FMT_TEXT-1; /* Assume user buf fits max */
outbuf.dsc$b_dtype = DSC$K_DTYPE_T; /* Text */
outbuf.dsc$b_class = DSC$K_CLASS_S; /* Static */
outbuf.dsc$a_pointer = str; /* Point at user buffer */
status = SYS$FAO(&ctrstr, &outlen, &outbuf, arg1, arg2, arg3, arg4, arg5);
if ((status & 1) == 0)
fprintf(stderr, "Error in error message processing!\n");
str[outlen] = '\0';
fprintf(fid, "%s\n", str);
}
#else
/* m e s s a g e _ f p r i n t (non-VMS) */
{
char str[MAX_FMT_TEXT]; /* Formatted message text */
char *msg_text; /* Ptr to message text (storage owned by catgets) */
#ifdef HAVE_NL_TYPES_H
msg_text = catgets(cat_handle, CAT_SET, msgid, def_message(msgid));
#else
msg_text = def_message(msgid);
#endif /* HAVE_NL_TYPES_H */
NL_SPRINTF(str, msg_text, arg1, arg2, arg3, arg4, arg5);
fprintf(fid, "%s\n", str);
}
#endif
#endif
| 5,923 |
4,081 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.cli;
import java.util.List;
import java.util.Map;
/**
* A container class for the validation results.
*/
public class ValidationResults {
private Map<ValidationUtils.State, List<ValidationTaskResult>> mResult;
/**
* Set validation results.
*
* @param result validation result
*/
public void setResult(Map<ValidationUtils.State, List<ValidationTaskResult>> result) {
mResult = result;
}
/**
* Get Validation Result.
*
* @return validation result
*/
public Map<ValidationUtils.State, List<ValidationTaskResult>> getResult() {
return mResult;
}
}
| 328 |
778 | //
// Project Name: KratosContactMechanicsApplication $
// Created by: $Author: JMCarbonell $
// Last modified by: $Co-Author: $
// Date: $Date: July 2016 $
// Revision: $Revision: 0.0 $
//
//
// System includes
// External includes
// Project includes
#include "custom_meshers/contact_domain_3D_mesher.hpp"
#include "contact_mechanics_application_variables.h"
namespace Kratos
{
//*******************************************************************************************
//*******************************************************************************************
void ContactDomain3DMesher::SetNodes(ModelPart& rModelPart,
MeshingParametersType& rMeshingVariables)
{
KRATOS_TRY
const unsigned int dimension = rModelPart.ConditionsBegin()->GetGeometry().WorkingSpaceDimension();
//*********************************************************************
//writing the points coordinates in a vector and reordening the Id's from an initial id
ModelPart::NodesContainerType::iterator nodes_begin = rModelPart.NodesBegin();
const array_1d<double,3> ZeroOffset(3,0.0);
double nodal_h_min = std::numeric_limits<double>::max();
double nodal_h = 0;
for(unsigned int i = 0; i<rModelPart.Nodes().size(); i++)
{
noalias((nodes_begin + i)->FastGetSolutionStepValue(OFFSET)) = ZeroOffset;
nodal_h = (nodes_begin + i)->FastGetSolutionStepValue(NODAL_H);
if(nodal_h_min>nodal_h)
nodal_h_min=nodal_h;
}
double hnodal_offset_conversion = 0.30;
if( rMeshingVariables.OffsetFactor > nodal_h_min*hnodal_offset_conversion || rMeshingVariables.OffsetFactor < nodal_h_min*0.01){
rMeshingVariables.OffsetFactor = nodal_h_min*hnodal_offset_conversion;
}
std::cout<<" Minimum Nodal_h "<<nodal_h_min<<" OffsetFactor "<<rMeshingVariables.OffsetFactor<<std::endl;
std::vector<PointType> BoxVertices;
BoxVertices.resize(0);
//*********************************************************************
if(rMeshingVariables.Options.Is(MesherUtilities::CONSTRAINED)){
//std::cout<<" Constrained Contact Meshing "<<std::endl;
//PART 1: node list
double extra_radius = rMeshingVariables.OffsetFactor*3.0;
SpatialBoundingBox DomainBox (rModelPart, extra_radius);
ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo();
DomainBox.GetVertices( BoxVertices, CurrentProcessInfo[TIME], dimension );
}
//input mesh: NODES
MesherUtilities::MeshContainer& InMesh = rMeshingVariables.InMesh;
InMesh.CreatePointList(rModelPart.NumberOfNodes() + BoxVertices.size(), dimension);
double* PointList = InMesh.GetPointList();
int& NumberOfPoints = InMesh.GetNumberOfPoints();
if(!rMeshingVariables.InputInitializedFlag){
rMeshingVariables.NodeMaxId = 0;
if((int)rMeshingVariables.NodalPreIds.size() != NumberOfPoints+1)
rMeshingVariables.NodalPreIds.resize(NumberOfPoints+1);
std::fill( rMeshingVariables.NodalPreIds.begin(), rMeshingVariables.NodalPreIds.end(), 0 );
}
//writing the points coordinates in a vector and reordening the Id's
int base = 0;
int direct = 1;
double Shrink = 0;
array_1d<double, 3> Offset;
for(unsigned int i = 0; i<rModelPart.NumberOfNodes(); i++)
{
//std::cout<<" Node ID "<<(nodes_begin + i)->Id()<<std::endl;
//from now on it is consecutive
if(!rMeshingVariables.InputInitializedFlag){
rMeshingVariables.NodalPreIds[direct]=(nodes_begin + i)->Id();
(nodes_begin + i)->SetId(direct);
if( rMeshingVariables.NodalPreIds[direct] > (int)rMeshingVariables.NodeMaxId )
rMeshingVariables.NodeMaxId = rMeshingVariables.NodalPreIds[direct];
}
array_1d<double, 3>& Coordinates = (nodes_begin + i)->Coordinates();
array_1d<double, 3>& Normal = (nodes_begin + i)->FastGetSolutionStepValue(NORMAL); //BOUNDARY_NORMAL must be set as nodal variable
Shrink = (nodes_begin + i)->FastGetSolutionStepValue(SHRINK_FACTOR); //SHRINK_FACTOR must be set as nodal variable
Normal /= norm_2(Normal);
for(unsigned int j=0; j<dimension; j++){
Offset[j] = ( (-1) * Normal[j] * Shrink * rMeshingVariables.OffsetFactor);
}
for(unsigned int j=0; j<dimension; j++){
PointList[base+j] = Coordinates[j] + Offset[j];
}
//std::cout<<" BodyNodes ["<<i<<"]= ("<<PointList[base]<<", "<<PointList[base+1]<<", "<<PointList[base+2]<<"). Id = "<<direct<<" Pre: "<<rMeshingVariables.NodalPreIds[direct]<<std::endl;
base+=dimension;
direct+=1;
}
if(BoxVertices.size() !=0 ){
std::vector<int> vertices_ids;
for(unsigned int i = 0; i<BoxVertices.size(); i++)
{
rMeshingVariables.NodalPreIds[direct] = -1;
vertices_ids.push_back(direct);
for(unsigned int j=0; j<dimension; j++){
PointList[base+j] = BoxVertices[i][j];
}
//std::cout<<" BoxVertices ["<<i<<"]= ("<<BoxVertices[i][0]<<", "<<BoxVertices[i][1]<<", "<<BoxVertices[i][2]<<"). Id = "<<vertices_ids[i]<<std::endl;
base+=dimension;
direct+=1;
}
}
//InMesh.SetPointList(PointList);
KRATOS_CATCH( "" )
}
//*******************************************************************************************
//*******************************************************************************************
void ContactDomain3DMesher::SetFaces(ModelPart& rModelPart,
MeshingParametersType& rMeshingVariables,
tetgenio& in)
{
KRATOS_TRY
//Set faces and facets
const unsigned int dimension = rModelPart.ConditionsBegin()->GetGeometry().WorkingSpaceDimension();
//*********************************************************************
// if(in.facetlist){
// delete [] in.facetlist;
// in.numberoffacets = 0;
// }
// if(in.facetmarkerlist){
// delete [] in.facetmarkerlist;
// }
// if(in.holelist){
// delete [] in.holelist;
// in.numberofholes = 0;
// }
// if(in.regionlist){
// delete [] in.regionlist;
// in.numberofregions = 0;
// }
//PART 2: facet list (we can have holes in facets != volume holes)
std::vector<PointType> BoxVertices;
BoxVertices.resize(0);
double extra_radius = rMeshingVariables.OffsetFactor*4;
SpatialBoundingBox DomainBox (rModelPart, extra_radius);
ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo();
DomainBox.GetVertices( BoxVertices, CurrentProcessInfo[TIME], dimension );
DenseMatrix<unsigned int> Faces(6,4);
DomainBox.GetQuadrilateralFaces(Faces, dimension);
//DenseMatrix<unsigned int> Faces(12,3);
//DomainBox.GetTriangularFaces(Faces, dimension);
in.numberoffacets = rModelPart.NumberOfConditions() + Faces.size1();
in.facetmarkerlist = new int[in.numberoffacets];
in.facetlist = new tetgenio::facet[in.numberoffacets];
ModelPart::ConditionsContainerType::iterator conditions_begin = rModelPart.ConditionsBegin();
//std::cout<<" Number of facets "<<in.numberoffacets<<std::endl;
//facets
tetgenio::facet *f;
tetgenio::polygon *p;
for(unsigned int fc=0; fc<rModelPart.NumberOfConditions(); fc++)
{
f = &in.facetlist[fc];
f->numberofpolygons = 1;
f->polygonlist = new tetgenio::polygon[f->numberofpolygons];
f->numberofholes = 0;
f->holelist = NULL;
p = &f->polygonlist[0];
p->numberofvertices = 3; //face is a triangle
p->vertexlist = new int[p->numberofvertices];
if( (conditions_begin + fc)->Is(TO_ERASE) )
std::cout<<" ERROR: condition to erase present "<<std::endl;
Geometry< Node<3> >& rGeometry = (conditions_begin + fc)->GetGeometry();
//std::cout<<" Facet["<<fc<<"]: (";
for (int nd=0;nd<p->numberofvertices;nd++)
{
p->vertexlist[nd] = rGeometry[nd].Id();
//std::cout<<" "<<p->vertexlist[nd];
}
//std::cout<<" )"<<std::endl;
in.facetmarkerlist[fc] = 0; //boundary marker to preserve facets
}
//BoundaryBox facets
MesherUtilities::MeshContainer& InMesh = rMeshingVariables.InMesh;
int& NumberOfPoints = InMesh.GetNumberOfPoints();
int ids = NumberOfPoints - BoxVertices.size() + 1;
int counter = 0;
for(int fc=rModelPart.NumberOfConditions(); fc<in.numberoffacets; fc++) //3d (prismatic box of 12 triangular sides)
{
f = &in.facetlist[fc];
f->numberofpolygons = 1;
f->polygonlist = new tetgenio::polygon[f->numberofpolygons];
f->numberofholes = 0;
f->holelist = NULL;
p = &f->polygonlist[0];
p->numberofvertices = Faces.size2(); //vertices of the face
p->vertexlist = new int[p->numberofvertices];
//std::cout<<" Facet["<<fc<<"]: (";
for (int nd=0;nd<p->numberofvertices;nd++)
{
p->vertexlist[nd] = ids + Faces(counter,nd);
//std::cout<<" "<<p->vertexlist[nd];
}
//std::cout<<" )"<<std::endl;
in.facetmarkerlist[fc] = -1; // boundary marker to release facets
counter++;
}
//PART 3: (volume) hole list
std::vector<BoundedVector<double, 3> >& Holes = rMeshingVariables.GetHoles();
//holes
in.numberofholes = Holes.size();
in.holelist = new REAL[in.numberofholes * 3];
for(unsigned int hl=0; hl<Holes.size();hl++)
{
//std::cout<<" BoxHoles ["<<hl<<"]= ("<<Holes[hl][0]<<", "<<Holes[hl][1]<<", "<<Holes[hl][2]<<")"<<std::endl;
//inside point of the hole:
in.holelist[hl*3+0] = Holes[hl][0];
in.holelist[hl*3+1] = Holes[hl][1];
in.holelist[hl*3+2] = Holes[hl][2];
}
//PART 4: region attributes list
//in.numberofregions = 2;
//in.regionlist = new REAL[in.numberofregions * 5];
KRATOS_CATCH( "" )
}
} // Namespace Kratos
| 3,960 |
4,329 | <filename>packages/flab/package.json
{
"name": "flab",
"version": "1.0.0-alpha.2",
"description": "Future Loading and Blocking JS",
"main": "index.js",
"files": [
"index.js",
"string"
],
"scripts": {
"prepublish": "npm run build",
"build": "mkdir -p string && npm run build-src && npm run build-min",
"build-src": "node stringify.js < LAB.src.js > string/src.js",
"build-min": "node minify.js < LAB.src.js | node stringify.js > string/min.js",
"clean": "rimraf string",
"lint": "eslint .",
"test": "echo \"No tests yet...\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/redfin/react-server.git"
},
"keywords": [
"loading",
"blocking",
"js",
"asynchronous",
"loader"
],
"author": "<NAME>",
"license": "MIT",
"bugs": {
"url": "https://github.com/redfin/react-server/issues"
},
"homepage": "https://github.com/redfin/react-server#readme"
}
| 409 |
32,544 | package com.baeldung.conditionalonproperty;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import com.baeldung.conditionalonproperty.config.NotificationConfig;
import com.baeldung.conditionalonproperty.service.EmailNotification;
import com.baeldung.conditionalonproperty.service.NotificationSender;
public class NotificationUnitTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner();
@Test
public void whenValueSetToEmail_thenCreateEmailNotification() {
this.contextRunner.withPropertyValues("notification.service=email")
.withUserConfiguration(NotificationConfig.class)
.run(context -> {
assertThat(context).hasBean("emailNotification");
NotificationSender notificationSender = context.getBean(EmailNotification.class);
assertThat(notificationSender.send("Hello From Baeldung!")).isEqualTo("Email Notification: Hello From Baeldung!");
assertThat(context).doesNotHaveBean("smsNotification");
});
}
}
| 440 |
1,091 | /*
* Copyright 2014-present Open Networking Foundation
*
* 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.onlab.osgi;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.ComponentInstance;
import java.util.Dictionary;
import java.util.Enumeration;
/**
* Adapter implementation of OSGI component context.
*/
public class ComponentContextAdapter implements ComponentContext {
private static class MockDictionary extends Dictionary {
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Enumeration keys() {
return null;
}
@Override
public Enumeration elements() {
return null;
}
@Override
public Object get(Object key) {
return null;
}
@Override
public Object put(Object key, Object value) {
return null;
}
@Override
public Object remove(Object key) {
return null;
}
}
@Override
public Dictionary getProperties() {
return new MockDictionary();
}
@Override
public Object locateService(String name) {
return null;
}
@Override
public Object locateService(String name, ServiceReference reference) {
return null;
}
@Override
public Object[] locateServices(String name) {
return new Object[0];
}
@Override
public BundleContext getBundleContext() {
return null;
}
@Override
public Bundle getUsingBundle() {
return null;
}
@Override
public ComponentInstance getComponentInstance() {
return null;
}
@Override
public void enableComponent(String name) {
}
@Override
public void disableComponent(String name) {
}
@Override
public ServiceReference getServiceReference() {
return null;
}
}
| 977 |
716 | <reponame>thanhndv212/pinocchio
//
// Copyright (c) 2019-2020 INRIA
//
#ifndef __pinocchio_autodiff_casadi_math_matrix_hpp__
#define __pinocchio_autodiff_casadi_math_matrix_hpp__
#include "pinocchio/math/matrix.hpp"
namespace pinocchio
{
namespace internal
{
template<typename Scalar>
struct CallCorrectMatrixInverseAccordingToScalar< ::casadi::Matrix<Scalar> >
{
typedef ::casadi::Matrix<Scalar> SX;
template<typename MatrixIn, typename MatrixOut>
static void run(const Eigen::MatrixBase<MatrixIn> & mat,
const Eigen::MatrixBase<MatrixOut> & dest)
{
SX cs_mat(mat.rows(),mat.cols());
casadi::copy(mat.derived(),cs_mat);
SX cs_mat_inv = SX::inv(cs_mat);
MatrixOut & dest_ = PINOCCHIO_EIGEN_CONST_CAST(MatrixOut,dest);
casadi::copy(cs_mat_inv,dest_);
}
};
}
} // namespace pinocchio
#endif // ifndef __pinocchio_autodiff_casadi_math_matrix_hpp__
| 450 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-54vf-jrm9-p98w",
"modified": "2021-12-02T00:01:08Z",
"published": "2021-12-01T00:00:39Z",
"aliases": [
"CVE-2020-7879"
],
"details": "This issue was discovered when the ipTIME C200 IP Camera was synchronized with the ipTIME NAS. It is necessary to extract value for ipTIME IP camera because the ipTIME NAS send ans setCookie('[COOKIE]') . The value is transferred to the --header option in wget binary, and there is no validation check. This vulnerability allows remote attackers to execute remote command.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2020-7879"
},
{
"type": "WEB",
"url": "https://www.boho.or.kr/krcert/secNoticeView.do?bulletin_writing_sequence=36365"
}
],
"database_specific": {
"cwe_ids": [
"CWE-78"
],
"severity": "CRITICAL",
"github_reviewed": false
}
} | 400 |
1,511 | /*
* Copyright (C) 2010 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* or (at your option) any later version, as published by the Free
* Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef SIMON_DIALOGBOUNDVALUES_H_4B4956DCAE204C49977297D20CB81F09
#define SIMON_DIALOGBOUNDVALUES_H_4B4956DCAE204C49977297D20CB81F09
#include "simondialogengine_export.h"
#include <QList>
#include <QString>
#include <QDomElement>
#include <QAbstractItemModel>
class BoundValue;
class SIMONDIALOGENGINE_EXPORT DialogBoundValues : public QAbstractItemModel
{
private:
QList<BoundValue*> boundValues;
public:
DialogBoundValues();
Qt::ItemFlags flags(const QModelIndex &index) const;
QVariant headerData(int, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
QObject* parent() { return QObject::parent(); }
QModelIndex parent(const QModelIndex &index) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QModelIndex index(int row, int column,const QModelIndex &parent = QModelIndex()) const;
virtual QVariant data(const QModelIndex &index, int role) const;
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
static DialogBoundValues* createInstance(const QDomElement& elem);
QDomElement serialize(QDomDocument *doc);
bool deSerialize(const QDomElement& elem);
bool addBoundValue(BoundValue *value);
bool removeBoundValue(BoundValue *value);
//BoundValue* getBoundValue(const QString& name);
QVariant getBoundValue(const QString& name);
~DialogBoundValues();
void setArguments(const QStringList& arguments);
};
#endif
| 754 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.