max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
9,959 |
<reponame>aoztaskin/lombok
//version 8:
public class WithByInAnonymousClass {
Object annonymous = new Object() {
class Inner {
private Inner(String string) {
}
private String string;
@java.lang.SuppressWarnings("all")
public Inner withStringBy(final java.util.function.Function<? super String, ? extends String> transformer) {
return new Inner(transformer.apply(this.string));
}
}
};
}
| 146 |
722 |
import pytest
ignored_warnings = [
"ignore:Could not log computational graph since",
"ignore:The dataloader, val dataloader",
"ignore:The dataloader, train dataloader",
]
pytestmark = pytest.mark.filterwarnings(*ignored_warnings)
| 88 |
1,483 |
<reponame>Mu-L/Lealone
/*
* Copyright Lealone Database Group.
* Licensed under the Server Side Public License, v 1.
* Initial Developer: zhh
*/
package org.lealone.storage.replication;
import java.util.List;
import org.lealone.db.CommandParameter;
import org.lealone.db.value.Value;
public class ReplicationCommandParameter implements CommandParameter {
private final int index;
private final int size;
List<CommandParameter> commandParameters;
public ReplicationCommandParameter(int index, List<CommandParameter> commandParameters) {
this.index = index;
this.size = commandParameters.size();
this.commandParameters = commandParameters;
}
@Override
public int getIndex() {
return index;
}
@Override
public void setValue(Value newValue, boolean closeOld) {
for (int i = 0; i < size; i++) {
commandParameters.get(i).setValue(newValue, closeOld);
}
}
@Override
public void setValue(Value value) {
for (int i = 0; i < size; i++) {
commandParameters.get(i).setValue(value);
}
}
@Override
public Value getValue() {
return commandParameters.get(0).getValue();
}
@Override
public void checkSet() {
for (int i = 0; i < size; i++) {
commandParameters.get(i).checkSet();
}
}
@Override
public boolean isValueSet() {
return commandParameters.get(0).isValueSet();
}
@Override
public int getType() {
return commandParameters.get(0).getType();
}
@Override
public long getPrecision() {
return commandParameters.get(0).getPrecision();
}
@Override
public int getScale() {
return commandParameters.get(0).getScale();
}
@Override
public int getNullable() {
return commandParameters.get(0).getNullable();
}
}
| 729 |
636 |
<filename>modules/chempy/mmd.py
#A* -------------------------------------------------------------------
#B* This file contains source code for the PyMOL computer program
#C* copyright 1998-2000 by <NAME> of DeLano Scientific.
#D* -------------------------------------------------------------------
#E* It is unlawful to modify or remove this copyright notice.
#F* -------------------------------------------------------------------
#G* Please see the accompanying LICENSE file for further information.
#H* -------------------------------------------------------------------
#I* Additional authors of this source file include:
#-*
#-*
#-*
#Z* -------------------------------------------------------------------
from chempy.models import Indexed,Connected
from chempy import Storage,Atom,Bond
import copy
class MMD(Storage):
#---------------------------------------------------------------------------------
def fromList(self,MMODList):
model = Connected()
# get header information
nAtom = int(MMODList[0][1:6])
model.molecule.title = MMODList[0][8:].strip()
irec = 1
# loop through atoms
cnt = 0
for a in range(nAtom):
model.bond.append([])
for a in range(nAtom):
at = Atom()
at.numeric_type = int(MMODList[irec][1:4])
# extract connectivity information
tokens = MMODList[irec][5:52].split()
at.neighbor = []
at.bondorder = []
for i in range(6):
if tokens[2*i] != "0":
a2 = int(tokens[2*i])-1
if (a2>cnt):
b = Bond()
b.index = [cnt,a2]
b.order = int(tokens[2*i+1])
model.bond[b.index[0]].append(b) # note two refs to same object
model.bond[b.index[1]].append(b) # note two refs to same object
else:
break
# extract other information
at.coord = [float(MMODList[irec][53:64]),
float(MMODList[irec][65:76]), float(MMODList[irec][77:88])]
at.resi = MMODList[irec][89:94].strip()
at.resi_number = int(at.resi)
resn_code = MMODList[irec][94:95].strip()
if len(resn_code): at.resn_code = resn_code
color_code = MMODList[irec][96:100].strip()
if color_code!='':
at.color_code = int(color_code)
else:
at.color_code = 0
chain = MMODList[irec][95:96].strip()
if len(chain): at.chain = chain
at.partial_charge = float(MMODList[irec][100:109])
at.resn = MMODList[irec][119:123]
name = MMODList[irec][124:128].strip()
if len(name): at.name = name
model.atom.append(at)
irec = irec + 1
cnt = cnt + 1
# fill in remaining datatypes
cnt = 1
for a in model.atom:
a.text_type = MMOD_atom_data[a.numeric_type][0]
a.symbol = MMOD_atom_data[a.numeric_type][1]
a.formal_charge = MMOD_atom_data[a.numeric_type][4]
cnt = cnt + 1
return(model.convert_to_indexed())
#---------------------------------------------------------------------------------
def updateFromList(self,model,list): # updates charges and coordinates
nAtom = int(list[0][1:6])
try:
model.molecule.energy = float(list[0][58:68])/4.184 # convert to kcal
except:
if hasattr(model.molecule,'energy'):
del model.molecule.energy
if nAtom!=model.nAtom:
raise RuntimeError(" mmd: atom count mismatch")
c = 0
for a in list[1:]:
mac = model.atom[c]
mac.coord = [float(a[53:64]),
float(a[65:76]), float(a[77:88])]
mac.partial_charge = float(a[100:109])
c = c + 1
#---------------------------------------------------------------------------------
def toList(self,model,no_blank_names=1):
conn = copy.deepcopy(model)
conn = conn.convert_to_connected()
MMODList = []
MMODList.append(" %5d %-70s\n" %(conn.nAtom,conn.molecule.title))
c = 0
neighbors_len = 6
for i in conn.atom:
# construct neighbor list
neighbors = [0] * neighbors_len
bondorders = [0] * neighbors_len
for j, b in enumerate(conn.bond[c]):
if j >= neighbors_len:
print(" Warning: too many bonds")
break
n = b.index[0]
if n == c:
n = b.index[1]
neighbors[j] = n + 1
bondorders[j] = b.order
# assemble output line
if i.numeric_type>0:
tline = " %3d" % (i.numeric_type)
else:
tline = " %3d" % 64
for j in range(neighbors_len):
tline = tline + " %5d %1d" % (neighbors[j], bondorders[j])
tline = tline + " %11.6f %11.6f %11.6f " % (i.coord[0],
i.coord[1], i.coord[2])
name = i.name
if not len(name):
if no_blank_names:
name = "%s%d" % (i.symbol,c+1)
name = name[0:4]
tline = tline + "%5d%1s%1s%4d%9.5f%9.5f %-4s %4s\n" % \
(i.resi_number,i.resn_code, i.chain, i.color_code,
i.partial_charge, i.partial_charge, i.resn, name)
MMODList.append(tline)
c = c + 1
return(MMODList)
#---------------------------------------------------------------------------------
'#Ntype Atype Elem Hybr Att Chg\n',
MMOD_atom_data = {
1: ['C1','C' ,'sp' , 2, 0],
2: ['C2','C' ,'sp2', 3, 0],
3: ['C3','C' ,'sp3', 4, 0],
4: ['CA','C' ,'sp3', 3, 0],
5: ['CB','C' ,'sp3', 2, 0],
6: ['CC','C' ,'sp3', 1, 0],
7: ['CD','C' ,'sp2', 2, 0],
8: ['CE','C' ,'sp2', 1, 0],
9: ['CF','C' ,'sp' , 1, 0],
10: ['CM','C' ,'unk',-1,-1],
11: ['CP','C' ,'unk',-1, 1],
12: ['CR','C' ,'unk',-1, 0],
14: ['C0','C' ,'unk',-1, 0],
15: ['O2','O' ,'sp2', 1, 0],
16: ['O3','O' ,'sp3', 2, 0],
17: ['OA','O' ,'sp3', 1, 0],
18: ['OM','O' ,'sp3', 1,-1],
19: ['OW','O' ,'sp3', 0, 0],
20: ['OP','O' ,'sp2', 2, 1],
21: ['OQ','O' ,'sp3', 3, 1],
23: ['O0','O' ,'unk',-1, 0],
24: ['N1','N' ,'sp' , 1, 0],
25: ['N2','N' ,'sp2', 2, 0],
26: ['N3','N' ,'sp3', 3, 0],
27: ['NA','N' ,'sp3', 2, 0],
28: ['NB','N' ,'sp3', 1, 0],
29: ['NC','N' ,'sp3', 0, 0],
30: ['ND','N' ,'sp2', 1, 0],
31: ['N4','N' ,'sp2', 3, 1],
32: ['N5','N' ,'sp3', 4, 1],
33: ['NE','N' ,'sp3', 3, 1],
34: ['NF','N' ,'sp3', 2, 1],
35: ['NG','N' ,'sp3', 1, 1],
36: ['NH','N' ,'sp2', 2, 1],
37: ['NI','N' ,'sp2', 1, 1],
40: ['N0','N' ,'unk',-1, 0],
41: ['H1','H' ,'s' , 1, 0],
42: ['H2','H' ,'s' , 1, 0],
43: ['H3','H' ,'s' , 1, 0],
44: ['H4','H' ,'s' , 0, 0],
45: ['H5','H' ,'s' , 0, 0],
48: ['H0','H' ,'s' ,-1, 0],
49: ['S1','S' ,'sp3', 2, 0],
50: ['SA','S' ,'sp3', 1, 0],
51: ['SM','S' ,'sp3', 0,-1],
52: ['S0','S' ,'unk',-1, 0],
53: ['P0','P' ,'unk',-1, 0],
54: ['B2','B' ,'sp2', 2, 0],
55: ['B3','B' ,'sp3', 3, 0],
56: ['F0','F' ,'sp3', 1, 0],
57: ['Cl','Cl','sp3', 1, 0],
58: ['Br','Br','sp3', 1, 0],
59: ['I0','I' ,'sp3', 1, 0],
60: ['Si','Si','unk',-1, 0],
61: ['Du','Du','unk',-1, 0],
62: ['Du','Du','unk',-1, 0],
63: ['Lp','Lp','unk', 1, 0],
64: ['Du','Du','unk',-1, 0]};
| 3,943 |
326 |
<filename>scripts/dev_setup.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import sys
import os
from subprocess import check_call, CalledProcessError
root_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), '..', '..'))
extension_dir = os.path.join(root_dir,'azure-devops')
azure_dir = os.getenv('AZURE_CONFIG_DIR', None) or os.path.expanduser(os.path.join('~', '.azure'))
print('Running dev setup...')
print('Root directory \'{}\'\n'.format(root_dir))
print('Extension directory \'{}\'\n'.format(extension_dir))
print('Azure root directory \'{}\'\n'.format(azure_dir))
def exec_command(command):
try:
print('Executing: ' + command)
check_call(command.split(), cwd=root_dir)
print()
except CalledProcessError as err:
print(err, file=sys.stderr)
sys.exit(1)
# install general requirements and azure-cli
exec_command('python -m pip install --upgrade pip')
# install to edge build of azure-cli
exec_command('pip install --pre azure-cli --extra-index-url https://azurecliprod.blob.core.windows.net/edge --no-cache-dir')
os.environ['AZURE_EXTENSION_DIR'] = os.path.join(azure_dir,'devcliextensions')
exec_command('pip install -e {}'.format(extension_dir))
exec_command('pip install --upgrade --target {0}/devcliextensions/azure-devops {1}'.format(azure_dir, extension_dir))
print('Finished dev setup.')
| 543 |
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.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include <platform.h>
#include "AnimUtils.h"
#include "ICryAnimation.h"
void AnimUtils::StartAnimation(ICharacterInstance* pCharacter, const char* pAnimName)
{
CryCharAnimationParams params(0);
ISkeletonAnim* pISkeletonAnim = (pCharacter ? pCharacter->GetISkeletonAnim() : 0);
if (pISkeletonAnim)
{
pISkeletonAnim->StopAnimationsAllLayers();
}
params.m_nFlags |= (CA_MANUAL_UPDATE | CA_REPEAT_LAST_KEY);
if (pISkeletonAnim)
{
pISkeletonAnim->StartAnimation(pAnimName, params);
}
}
void AnimUtils::SetAnimationTime(ICharacterInstance* pCharacter, float fNormalizedTime)
{
assert(fNormalizedTime >= 0.0f && fNormalizedTime <= 1.0f);
ISkeletonAnim* pISkeletonAnim = (pCharacter ? pCharacter->GetISkeletonAnim() : 0);
float timeToSet = max(0.0f, fNormalizedTime);
if (pISkeletonAnim)
{
pISkeletonAnim->SetLayerNormalizedTime(0, timeToSet);
}
}
void AnimUtils::StopAnimations(ICharacterInstance* pCharacter)
{
ISkeletonAnim* pISkeletonAnim = (pCharacter ? pCharacter->GetISkeletonAnim() : 0);
if (pISkeletonAnim)
{
pISkeletonAnim->StopAnimationsAllLayers();
}
}
| 615 |
672 |
/*
* Copyright (c) 2011 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#include <string.h>
#include <mach-o/loader.h>
#include <sys/types.h>
#define DEBUG_ASSERT_COMPONENT_NAME_STRING "kxld"
#include <AssertMacros.h>
#include "kxld_util.h"
#include "kxld_versionmin.h"
/*******************************************************************************
*******************************************************************************/
void
kxld_versionmin_init_from_macho(KXLDversionmin *versionmin, struct version_min_command *src)
{
check(versionmin);
check(src);
check((src->cmd == LC_VERSION_MIN_MACOSX) || (src->cmd == LC_VERSION_MIN_IPHONEOS) || (src->cmd == LC_VERSION_MIN_TVOS) || (src->cmd == LC_VERSION_MIN_WATCHOS));
switch (src->cmd) {
case LC_VERSION_MIN_MACOSX:
versionmin->platform = kKxldVersionMinMacOSX;
break;
case LC_VERSION_MIN_IPHONEOS:
versionmin->platform = kKxldVersionMiniPhoneOS;
break;
case LC_VERSION_MIN_TVOS:
versionmin->platform = kKxldVersionMinAppleTVOS;
break;
case LC_VERSION_MIN_WATCHOS:
versionmin->platform = kKxldVersionMinWatchOS;
break;
}
versionmin->version = src->version;
versionmin->has_versionmin = TRUE;
}
void
kxld_versionmin_init_from_build_cmd(KXLDversionmin *versionmin, struct build_version_command *src)
{
check(versionmin);
check(src);
switch (src->platform) {
case PLATFORM_MACOS:
versionmin->platform = kKxldVersionMinMacOSX;
break;
case PLATFORM_IOS:
versionmin->platform = kKxldVersionMiniPhoneOS;
break;
case PLATFORM_TVOS:
versionmin->platform = kKxldVersionMinAppleTVOS;
break;
case PLATFORM_WATCHOS:
versionmin->platform = kKxldVersionMinWatchOS;
break;
default:
return;
}
versionmin->version = src->minos;
versionmin->has_versionmin = TRUE;
}
/*******************************************************************************
*******************************************************************************/
void
kxld_versionmin_clear(KXLDversionmin *versionmin)
{
bzero(versionmin, sizeof(*versionmin));
}
/*******************************************************************************
*******************************************************************************/
u_long
kxld_versionmin_get_macho_header_size(__unused const KXLDversionmin *versionmin)
{
/* TODO: eventually we can just use struct build_version_command */
return sizeof(struct version_min_command);
}
/*******************************************************************************
*******************************************************************************/
kern_return_t
kxld_versionmin_export_macho(const KXLDversionmin *versionmin, u_char *buf,
u_long *header_offset, u_long header_size)
{
kern_return_t rval = KERN_FAILURE;
struct version_min_command *versionminhdr = NULL;
check(versionmin);
check(buf);
check(header_offset);
require_action(sizeof(*versionminhdr) <= header_size - *header_offset, finish,
rval=KERN_FAILURE);
versionminhdr = (struct version_min_command *) ((void *) (buf + *header_offset));
bzero(versionminhdr, sizeof(*versionminhdr));
*header_offset += sizeof(*versionminhdr);
switch (versionmin->platform) {
case kKxldVersionMinMacOSX:
versionminhdr->cmd = LC_VERSION_MIN_MACOSX;
break;
case kKxldVersionMiniPhoneOS:
versionminhdr->cmd = LC_VERSION_MIN_IPHONEOS;
break;
case kKxldVersionMinAppleTVOS:
versionminhdr->cmd = LC_VERSION_MIN_TVOS;
break;
case kKxldVersionMinWatchOS:
versionminhdr->cmd = LC_VERSION_MIN_WATCHOS;
break;
default:
goto finish;
}
versionminhdr->cmdsize = (uint32_t) sizeof(*versionminhdr);
versionminhdr->version = versionmin->version;
versionminhdr->sdk = 0;
rval = KERN_SUCCESS;
finish:
return rval;
}
| 1,911 |
507 |
<filename>terrascript/data/tencentcloud.py<gh_stars>100-1000
# terrascript/data/tencentcloud.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:28:28 UTC)
#
# For imports without namespace, e.g.
#
# >>> import terrascript.data.tencentcloud
#
# instead of
#
# >>> import terrascript.data.tencentcloudstack.tencentcloud
#
# This is only available for 'official' and 'partner' providers.
from terrascript.data.tencentcloudstack.tencentcloud import *
| 154 |
715 |
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from federatedml.feature.feature_selection.model_adapter import isometric_model
from federatedml.feature.feature_selection.model_adapter.adapter_base import BaseAdapter
from federatedml.util import consts
class PearsonMetricInfo(object):
def __init__(self, local_corr, col_names, corr=None, host_col_names=None, parties=None):
self.local_corr = local_corr
self.col_names = col_names
self.corr = corr
self.host_col_names = host_col_names
self.parties = parties
@property
def host_party_id(self):
assert isinstance(self.parties, list) and len(self.parties) == 2
return self.parties[1][1]
class PearsonAdapter(BaseAdapter):
def convert(self, model_meta, model_param):
local_vif = model_param.local_vif
col_names = list(model_param.names)
local_corr = np.array(model_param.local_corr).reshape(model_param.shape, model_param.shape)
from federatedml.util import LOGGER
for idx in range(local_corr.shape[0]):
corr_col = local_corr[idx, :]
# LOGGER.debug(f"local_col_idx: {idx}, corr_col: {corr_col}")
if model_param.corr:
corr = np.array(model_param.corr).reshape(*model_param.shapes)
for idx in range(corr.shape[1]):
corr_col = corr[:, idx]
# LOGGER.debug(f"col_idx: {idx}, corr_col: {corr_col}")
host_names = list(list(model_param.all_names)[1].names)
parties = list(model_param.parties)
else:
corr = None
host_names = None
parties = None
pearson_metric = PearsonMetricInfo(local_corr=local_corr, col_names=col_names,
corr=corr, host_col_names=host_names, parties=parties)
single_info = isometric_model.SingleMetricInfo(
values=local_vif,
col_names=col_names
)
result = isometric_model.IsometricModel()
result.add_metric_value(metric_name=consts.VIF, metric_info=single_info)
result.add_metric_value(metric_name=consts.PEARSON, metric_info=pearson_metric)
return result
| 1,186 |
1,875 |
<reponame>imran631/teavm
/*
* Copyright 2019 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.teavm.model.optimization;
import java.util.HashMap;
import java.util.Map;
import org.teavm.model.InliningInfo;
class InliningInfoMerger {
private InliningInfo parent;
Map<InliningInfo, InliningInfo> inliningInfoCache = new HashMap<>();
InliningInfoMerger(InliningInfo parent) {
this.parent = parent;
}
InliningInfo merge(InliningInfo inliningInfo) {
if (inliningInfo == null) {
return parent;
}
InliningInfo result = inliningInfoCache.get(inliningInfo);
if (result == null) {
result = new InliningInfo(inliningInfo.getMethod(), inliningInfo.getFileName(), inliningInfo.getLine(),
merge(inliningInfo.getParent()));
inliningInfoCache.put(inliningInfo, result);
}
return result;
}
}
| 522 |
14,668 |
// Copyright (c) 2012 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/common/safe_browsing/download_type_util.h"
#include <algorithm>
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/strings/string_util.h"
#include "components/safe_browsing/content/common/file_type_policies.h"
#include "components/safe_browsing/core/common/features.h"
namespace safe_browsing {
namespace download_type_util {
ClientDownloadRequest::DownloadType GetDownloadType(
const base::FilePath& file) {
// TODO(nparker): Put all of this logic into the FileTypePolicies
// protobuf.
if (file.MatchesExtension(FILE_PATH_LITERAL(".apk")))
return ClientDownloadRequest::ANDROID_APK;
else if (file.MatchesExtension(FILE_PATH_LITERAL(".crx")))
return ClientDownloadRequest::CHROME_EXTENSION;
else if (file.MatchesExtension(FILE_PATH_LITERAL(".zip")))
// DownloadProtectionService doesn't send a ClientDownloadRequest for ZIP
// files unless they contain either executables or archives. The resulting
// DownloadType is either ZIPPED_EXECUTABLE or ZIPPED_ARCHIVE respectively.
// This function will return ZIPPED_EXECUTABLE for ZIP files as a
// placeholder. The correct DownloadType will be determined based on the
// result of analyzing the ZIP file.
return ClientDownloadRequest::ZIPPED_EXECUTABLE;
else if (file.MatchesExtension(FILE_PATH_LITERAL(".rar")))
// See the comment for .zip files.
return ClientDownloadRequest::RAR_COMPRESSED_EXECUTABLE;
else if (file.MatchesExtension(FILE_PATH_LITERAL(".dmg")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".img")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".iso")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".pkg")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".mpkg")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".smi")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".app")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".cdr")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".dmgpart")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".dvdr")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".dart")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".dc42")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".diskcopy42")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".imgpart")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".ndif")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".udif")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".toast")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".sparsebundle")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".sparseimage")))
return ClientDownloadRequest::MAC_EXECUTABLE;
else if (FileTypePolicies::GetInstance()->IsArchiveFile(file))
return ClientDownloadRequest::ARCHIVE;
else if (file.MatchesExtension(FILE_PATH_LITERAL(".pdf")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".doc")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".docx")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".docm")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".docb")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".dot")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".dotm")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".dotx")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xls")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xlsb")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xlt")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xlm")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xlsx")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xldm")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xltx")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xltm")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xla")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xlam")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xll")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".xlw")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".ppt")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".pot")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".pps")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".pptx")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".pptm")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".potx")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".potm")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".ppam")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".ppsx")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".ppsm")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".sldx")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".rtf")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".wll")))
return ClientDownloadRequest::DOCUMENT;
return ClientDownloadRequest::WIN_EXECUTABLE;
}
} // namespace download_type_util
} // namespace safe_browsing
| 2,235 |
5,169 |
{
"name": "CJNetwork",
"version": "0.7.0-beta.5",
"summary": "一个AFNetworking应用的封装(支持加解密、缓存、并发数控制)",
"homepage": "https://github.com/dvlproad/CJNetwork",
"license": "MIT",
"authors": {
"dvlproad": "<EMAIL>"
},
"description": "- CJNetwork/CJNetworkCommon:AFN请求过程中需要的几个公共方法(包含请求前获取缓存、请求后成功与失败操作)\n- CJNetwork/AFNetworkingSerializerEncrypt:AFN的请求方法(加解密方法卸载Method方法中)\n- CJNetwork/AFNetworkingMethodEncrypt:AFN的请求方法(加解密方法卸载Method方法中)\n- CJNetwork/AFNetworkingUploadComponent:AFN的上传请求方法\n- CJNetwork/CJNetworkClient:网络请求的管理类,其他NetworkClient可通过本CJNetworkClient继承,也可自己再实现\n- CJNetwork/CJRequestUtil:原生(非AFN)的请求\n- CJNetwork/CJCacheManager:自己实现的非第三方的缓存机制\n\n\n A longer description of CJNetwork in Markdown format.\n\n * Think: Why did you write this? What is the focus? What does it do?\n * CocoaPods will be using this to generate tags, and improve search results.\n * Try to keep it short, snappy and to the point.\n * Finally, don't worry about the indent, CocoaPods strips it!",
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/dvlproad/CJNetwork.git",
"tag": "CJNetwork_0.7.0-beta.5"
},
"source_files": "CJNetwork/*.{h,m}",
"frameworks": "UIKit",
"requires_arc": true,
"subspecs": [
{
"name": "CJNetworkCommon",
"source_files": "CJNetwork/CJNetworkCommon/**/*.{h,m}",
"dependencies": {
"AFNetworking": [
],
"YYCache": [
],
"MJExtension": [
]
}
},
{
"name": "AFNetworkingSerializerEncrypt",
"source_files": "CJNetwork/AFNetworkingSerializerEncrypt/**/*.{h,m}",
"dependencies": {
"CJNetwork/CJNetworkCommon": [
]
}
},
{
"name": "AFNetworkingMethodEncrypt",
"source_files": "CJNetwork/AFNetworkingMethodEncrypt/**/*.{h,m}",
"dependencies": {
"CJNetwork/CJNetworkCommon": [
]
}
},
{
"name": "AFNetworkingUploadComponent",
"source_files": "CJNetwork/AFNetworkingUploadComponent/**/*.{h,m}",
"dependencies": {
"CJNetwork/CJNetworkCommon": [
]
}
},
{
"name": "CJNetworkClient",
"source_files": "CJNetwork/CJNetworkClient/**/*.{h,m}",
"dependencies": {
"CJNetwork/AFNetworkingSerializerEncrypt": [
],
"CJNetwork/AFNetworkingUploadComponent": [
]
}
},
{
"name": "CJRequestUtil",
"source_files": "CJNetwork/CJRequestUtil/**/*.{h,m}",
"dependencies": {
"CJNetwork/CJNetworkCommon": [
]
}
},
{
"name": "CJCacheManager",
"source_files": "CJCacheManager/**/*.{h,m}"
}
]
}
| 1,457 |
397 |
//
// UITextField+Chat.h
// samplechat
//
// Created by Injoit on 1/24/20.
// Copyright © 2020 Quickblox. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UITextField (Chat)
- (void)setPadding:(CGFloat)padding isLeft:(Boolean)isLeft;
- (void)addShadowToTextFieldWithColor:(UIColor *)color cornerRadius:(CGFloat)cornerRadius;
@end
NS_ASSUME_NONNULL_END
| 162 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-8936-4f3c-vg7r",
"modified": "2022-05-01T23:33:50Z",
"published": "2022-05-01T23:33:50Z",
"aliases": [
"CVE-2008-0856"
],
"details": "Multiple SQL injection vulnerabilities in e-Vision CMS 2.02 allow remote attackers to execute arbitrary SQL commands via the id parameter to (1) iframe.php and (2) print.php. NOTE: the provenance of this information is unknown; the details are obtained solely from third party information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2008-0856"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/40859"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/27816"
}
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"severity": "HIGH",
"github_reviewed": false
}
}
| 417 |
7,482 |
/*!
* @file apm32f10x_emmc.c
*
* @brief This file provides all the EMMC firmware functions
*
* @version V1.0.1
*
* @date 2021-03-23
*
*/
#include "apm32f10x_emmc.h"
#include "apm32f10x_rcm.h"
/** @addtogroup Peripherals_Library Standard Peripheral Library
@{
*/
/** @addtogroup EMMC_Driver EMMC Driver
@{
*/
/** @addtogroup EMMC_Fuctions Fuctions
@{
*/
/*!
* @brief Rest the EMMMC NOR/SRAM Banks registers
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK1_NORSRAM_1: EMMC Bank1 NOR/SRAM1
* @arg EMMC_BANK1_NORSRAM_2: EMMC Bank1 NOR/SRAM2
* @arg EMMC_BANK1_NORSRAM_3: EMMC Bank1 NOR/SRAM3
* @arg EMMC_BANK1_NORSRAM_4: EMMC Bank1 NOR/SRAM4
*
* @retval None
*/
void EMMC_ResetNORSRAM(EMMC_BANK1_NORSRAM_T bank)
{
/** EMMC_BANK1_NORSRAM_1 */
if(bank == EMMC_BANK1_NORSRAM_1)
{
EMMC_Bank1->SNCTRL_T[bank] = 0x000030DB;
}
/** EMMC_BANK1_NORSRAM_2, EMMC_BANK1_NORSRAM_3 or EMMC_BANK1_NORSRAM_4 */
else
{
EMMC_Bank1->SNCTRL_T[bank] = 0x000030D2;
}
EMMC_Bank1->SNCTRL_T[bank + 1] = 0x0FFFFFFF;
EMMC_Bank1E->WRTTIM[bank] = 0x0FFFFFFF;
}
/*!
* @brief Rest the EMMMC NAND Banks registers
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND: FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND: FSMC Bank3 NAND
*
* @retval None
*/
void EMMC_ResetNAND(EMMC_BANK_NAND_T bank)
{
if(bank == EMMC_BANK2_NAND)
{
/** Set the EMMC_Bank2 registers to their reset values */
EMMC_Bank2->CTRL2 = 0x00000018;
EMMC_Bank2->STSINT2 = 0x00000040;
EMMC_Bank2->CMSTIM2 = 0xFCFCFCFC;
EMMC_Bank2->AMSTIM2 = 0xFCFCFCFC;
}
/** EMMC_BANK3_NAND */
else
{
/* Set the EMMC_Bank3 registers to their reset values */
EMMC_Bank3->CTRL3 = 0x00000018;
EMMC_Bank3->STSINT3 = 0x00000040;
EMMC_Bank3->CMSTIM3 = 0xFCFCFCFC;
EMMC_Bank3->AMSTIM3 = 0xFCFCFCFC;
}
}
/*!
* @brief Reset the EMMMC PCCARD Banks registers
*
* @param None
*
* @retval None
*/
void EMMC_ResetPCCard(void)
{
/** Set the EMMC_Bank4 registers to their reset values */
EMMC_Bank4->CTRL4 = 0x00000018;
EMMC_Bank4->STSINT4 = 0x00000040;
EMMC_Bank4->CMSTIM4 = 0xFCFCFCFC;
EMMC_Bank4->AMSTIM4 = 0xFCFCFCFC;
EMMC_Bank4->IOSTIM4 = 0xFCFCFCFC;
}
/*!
* @brief Config the EMMC NOR/SRAM Banks according to the specified parameters in the emmcNORSRAMConfig.
*
* @param emmcNORSRAMConfig: Point to a EMMC_NORSRAMConfig_T structure
*
* @retval None
*/
void EMMC_ConfigNORSRAM(EMMC_NORSRAMConfig_T* emmcNORSRAMConfig)
{
/* Bank1 NOR/SRAM control register configuration */
EMMC_Bank1->SNCTRL_T[emmcNORSRAMConfig->bank] =
(uint32_t)emmcNORSRAMConfig->dataAddressMux |
emmcNORSRAMConfig->memoryType |
emmcNORSRAMConfig->memoryDataWidth |
emmcNORSRAMConfig->burstAcceesMode |
emmcNORSRAMConfig->asynchronousWait |
emmcNORSRAMConfig->waitSignalPolarity |
emmcNORSRAMConfig->wrapMode |
emmcNORSRAMConfig->waitSignalActive |
emmcNORSRAMConfig->writeOperation |
emmcNORSRAMConfig->waiteSignal |
emmcNORSRAMConfig->extendedMode |
emmcNORSRAMConfig->writeBurst;
if(emmcNORSRAMConfig->memoryType == EMMC_MEMORY_TYPE_NOR)
{
EMMC_Bank1->SNCTRL_T[emmcNORSRAMConfig->bank] |= 0x00000040;
}
/* Bank1 NOR/SRAM timing register configuration */
EMMC_Bank1->SNCTRL_T[emmcNORSRAMConfig->bank + 1] =
(uint32_t)emmcNORSRAMConfig->readWriteTimingStruct->addressSetupTime |
(emmcNORSRAMConfig->readWriteTimingStruct->addressHodeTime << 4) |
(emmcNORSRAMConfig->readWriteTimingStruct->dataSetupTime << 8) |
(emmcNORSRAMConfig->readWriteTimingStruct->busTurnaroundTime << 16) |
(emmcNORSRAMConfig->readWriteTimingStruct->clockDivision << 20) |
(emmcNORSRAMConfig->readWriteTimingStruct->dataLatency << 24) |
emmcNORSRAMConfig->readWriteTimingStruct->accessMode;
/* Bank1 NOR/SRAM timing register for write configuration, if extended mode is used */
if(emmcNORSRAMConfig->extendedMode == EMMC_EXTENDEN_MODE_ENABLE)
{
EMMC_Bank1E->WRTTIM[emmcNORSRAMConfig->bank] =
(uint32_t)emmcNORSRAMConfig->writeTimingStruct->addressSetupTime |
(emmcNORSRAMConfig->writeTimingStruct->addressHodeTime << 4) |
(emmcNORSRAMConfig->writeTimingStruct->dataSetupTime << 8) |
(emmcNORSRAMConfig->writeTimingStruct->clockDivision << 20) |
(emmcNORSRAMConfig->writeTimingStruct->dataLatency << 24) |
emmcNORSRAMConfig->writeTimingStruct->accessMode;
}
else
{
EMMC_Bank1E->WRTTIM[emmcNORSRAMConfig->bank] = 0x0FFFFFFF;
}
}
/*!
* @brief Config the EMMC NAND Banks according to the specified parameters in the emmcNANDConfig.
*
* @param emmcNANDConfig : Point to a EMMC_NANDConfig_T structure.
*
* @retval None
*/
void EMMC_ConfigNAND(EMMC_NANDConfig_T* emmcNANDConfig)
{
uint32_t tmppcr = 0x00000000, tmppmem = 0x00000000, tmppatt = 0x00000000;
/* Set the tmppcr value according to EMMC_NANDInitStruct parameters */
tmppcr = (uint32_t)emmcNANDConfig->waitFeature | 0x00000008 |
emmcNANDConfig->memoryDataWidth |
emmcNANDConfig->ECC |
emmcNANDConfig->ECCPageSize |
(emmcNANDConfig->TCLRSetupTime << 9) |
(emmcNANDConfig->TARSetupTime << 13);
/* Set tmppmem value according to EMMC_CommonSpaceTimingStructure parameters */
tmppmem = (uint32_t)emmcNANDConfig->commonSpaceTimingStruct->setupTime |
(emmcNANDConfig->commonSpaceTimingStruct->waitSetupTime << 8) |
(emmcNANDConfig->commonSpaceTimingStruct->holdSetupTime << 16) |
(emmcNANDConfig->commonSpaceTimingStruct->HiZSetupTime << 24);
/* Set tmppatt value according to EMMC_AttributeSpaceTimingStructure parameters */
tmppatt = (uint32_t)emmcNANDConfig->attributeSpaceTimingStruct->setupTime |
(emmcNANDConfig->attributeSpaceTimingStruct->waitSetupTime << 8) |
(emmcNANDConfig->attributeSpaceTimingStruct->holdSetupTime << 16) |
(emmcNANDConfig->attributeSpaceTimingStruct->HiZSetupTime << 24);
if(emmcNANDConfig->bank == EMMC_BANK2_NAND)
{
/* EMMC_BANK2_NAND registers configuration */
EMMC_Bank2->CTRL2 = tmppcr;
EMMC_Bank2->CMSTIM2 = tmppmem;
EMMC_Bank2->AMSTIM2 = tmppatt;
}
else
{
/* EMMC_BANK3_NAND registers configuration */
EMMC_Bank3->CTRL3 = tmppcr;
EMMC_Bank3->CMSTIM3 = tmppmem;
EMMC_Bank3->AMSTIM3 = tmppatt;
}
}
/*!
* @brief Config the EMMC PCCARD according to the specified parameters in the emmcPCCardConfig.
*
* @param emmcPCCardConfig: Point to a EMMC_PCCARDConfig_T structure.
*
* @retval None
*/
void EMMC_ConfigPCCard(EMMC_PCCARDConfig_T* emmcPCCardConfig)
{
/* Set the PCR4 register value according to EMMC_PCCARDInitStruct parameters */
EMMC_Bank4->CTRL4 = (uint32_t)emmcPCCardConfig->waitFeature | EMMC_MEMORY_DATA_WIDTH_16BIT |
(emmcPCCardConfig->TCLRSetupTime << 9) |
(emmcPCCardConfig->TARSetupTime << 13);
/* Set PMEM4 register value according to EMMC_CommonSpaceTimingStructure parameters */
EMMC_Bank4->CMSTIM4 = (uint32_t)emmcPCCardConfig->commonSpaceTimingStruct->setupTime |
(emmcPCCardConfig->commonSpaceTimingStruct->waitSetupTime << 8) |
(emmcPCCardConfig->commonSpaceTimingStruct->holdSetupTime << 16) |
(emmcPCCardConfig->commonSpaceTimingStruct->HiZSetupTime << 24);
/* Set PATT4 register value according to EMMC_AttributeSpaceTimingStructure parameters */
EMMC_Bank4->AMSTIM4 = (uint32_t)emmcPCCardConfig->attributeSpaceTimingStruct->setupTime |
(emmcPCCardConfig->attributeSpaceTimingStruct->waitSetupTime << 8) |
(emmcPCCardConfig->attributeSpaceTimingStruct->holdSetupTime << 16) |
(emmcPCCardConfig->attributeSpaceTimingStruct->HiZSetupTime << 24);
/* Set PIO4 register value according to EMMC_IOSpaceTimingStructure parameters */
EMMC_Bank4->IOSTIM4 = (uint32_t)emmcPCCardConfig->IOSpaceTimingStruct->setupTime |
(emmcPCCardConfig->IOSpaceTimingStruct->waitSetupTime << 8) |
(emmcPCCardConfig->IOSpaceTimingStruct->holdSetupTime << 16) |
(emmcPCCardConfig->IOSpaceTimingStruct->HiZSetupTime << 24);
}
/*!
* @brief Fills each emmcNORSRAMConfig member with its default value.
*
* @param emmcNORSRAMConfig : Point to a EMMC_NORSRAMConfig_T structure.
*
* @retval None
*/
void EMMC_ConfigNORSRAMStructInit(EMMC_NORSRAMConfig_T* emmcNORSRAMConfig)
{
/* Reset NOR/SRAM Init structure parameters values */
emmcNORSRAMConfig->bank = EMMC_BANK1_NORSRAM_1;
emmcNORSRAMConfig->dataAddressMux = EMMC_DATA_ADDRESS_MUX_ENABLE;
emmcNORSRAMConfig->memoryType = EMMC_MEMORY_TYPE_SRAM;
emmcNORSRAMConfig->memoryDataWidth = EMMC_MEMORY_DATA_WIDTH_8BIT;
emmcNORSRAMConfig->burstAcceesMode = EMMC_BURST_ACCESS_MODE_DISABLE;
emmcNORSRAMConfig->asynchronousWait = EMMC_ASYNCHRONOUS_WAIT_DISABLE;
emmcNORSRAMConfig->waitSignalPolarity = EMMC_WAIT_SIGNAL_POLARITY_LOW;
emmcNORSRAMConfig->wrapMode = EMMC_WRAP_MODE_DISABLE;
emmcNORSRAMConfig->waitSignalActive = EMMC_WAIT_SIGNAL_ACTIVE_BEFORE_WAIT;
emmcNORSRAMConfig->writeOperation = EMMC_WRITE_OPERATION_ENABLE;
emmcNORSRAMConfig->waiteSignal = EMMC_WAITE_SIGNAL_ENABLE;
emmcNORSRAMConfig->extendedMode = EMMC_EXTENDEN_MODE_DISABLE;
emmcNORSRAMConfig->writeBurst = EMMC_WRITE_BURST_DISABLE;
emmcNORSRAMConfig->readWriteTimingStruct->addressSetupTime = 0xF;
emmcNORSRAMConfig->readWriteTimingStruct->addressHodeTime = 0xF;
emmcNORSRAMConfig->readWriteTimingStruct->dataSetupTime = 0xFF;
emmcNORSRAMConfig->readWriteTimingStruct->busTurnaroundTime = 0xF;
emmcNORSRAMConfig->readWriteTimingStruct->clockDivision = 0xF;
emmcNORSRAMConfig->readWriteTimingStruct->dataLatency = 0xF;
emmcNORSRAMConfig->readWriteTimingStruct->accessMode = EMMC_ACCESS_MODE_A;
emmcNORSRAMConfig->writeTimingStruct->addressSetupTime = 0xF;
emmcNORSRAMConfig->writeTimingStruct->addressHodeTime = 0xF;
emmcNORSRAMConfig->writeTimingStruct->dataSetupTime = 0xFF;
emmcNORSRAMConfig->writeTimingStruct->busTurnaroundTime = 0xF;
emmcNORSRAMConfig->writeTimingStruct->clockDivision = 0xF;
emmcNORSRAMConfig->writeTimingStruct->dataLatency = 0xF;
emmcNORSRAMConfig->writeTimingStruct->accessMode = EMMC_ACCESS_MODE_A;
}
/*!
* @brief Fills each emmcNANDConfig member with its default value.
*
* @param emmcNANDConfig : Point to a EMMC_NANDConfig_T structure.
*
* @retval None
*/
void EMMC_ConfigNANDStructInit(EMMC_NANDConfig_T* emmcNANDConfig)
{
/* Reset NAND Init structure parameters values */
emmcNANDConfig->bank = EMMC_BANK2_NAND;
emmcNANDConfig->waitFeature = EMMC_WAIT_FEATURE_DISABLE;
emmcNANDConfig->memoryDataWidth = EMMC_MEMORY_DATA_WIDTH_8BIT;
emmcNANDConfig->ECC = EMMC_ECC_DISABLE;
emmcNANDConfig->ECCPageSize = EMMC_ECC_PAGE_SIZE_BYTE_256;
emmcNANDConfig->TCLRSetupTime = 0x0;
emmcNANDConfig->TARSetupTime = 0x0;
emmcNANDConfig->commonSpaceTimingStruct->setupTime = 0xFC;
emmcNANDConfig->commonSpaceTimingStruct->waitSetupTime = 0xFC;
emmcNANDConfig->commonSpaceTimingStruct->holdSetupTime = 0xFC;
emmcNANDConfig->commonSpaceTimingStruct->HiZSetupTime = 0xFC;
emmcNANDConfig->attributeSpaceTimingStruct->setupTime = 0xFC;
emmcNANDConfig->attributeSpaceTimingStruct->waitSetupTime = 0xFC;
emmcNANDConfig->attributeSpaceTimingStruct->holdSetupTime = 0xFC;
emmcNANDConfig->attributeSpaceTimingStruct->HiZSetupTime = 0xFC;
}
/*!
* @brief Fills each emmcPCCardConfig member with its default value.
*
* @param emmcPCCardConfig : Point to a EMMC_PCCARDConfig_T structure.
*
* @retval None
*/
void EMMC_ConfigPCCardStructInit(EMMC_PCCARDConfig_T* emmcPCCardConfig)
{
/* Reset PCCARD Init structure parameters values */
emmcPCCardConfig->waitFeature = EMMC_WAIT_FEATURE_DISABLE;
emmcPCCardConfig->TCLRSetupTime = 0x0;
emmcPCCardConfig->TARSetupTime = 0x0;
emmcPCCardConfig->commonSpaceTimingStruct->setupTime = 0xFC;
emmcPCCardConfig->commonSpaceTimingStruct->waitSetupTime = 0xFC;
emmcPCCardConfig->commonSpaceTimingStruct->holdSetupTime = 0xFC;
emmcPCCardConfig->commonSpaceTimingStruct->HiZSetupTime = 0xFC;
emmcPCCardConfig->attributeSpaceTimingStruct->setupTime = 0xFC;
emmcPCCardConfig->attributeSpaceTimingStruct->waitSetupTime = 0xFC;
emmcPCCardConfig->attributeSpaceTimingStruct->holdSetupTime = 0xFC;
emmcPCCardConfig->attributeSpaceTimingStruct->HiZSetupTime = 0xFC;
emmcPCCardConfig->IOSpaceTimingStruct->setupTime = 0xFC;
emmcPCCardConfig->IOSpaceTimingStruct->waitSetupTime = 0xFC;
emmcPCCardConfig->IOSpaceTimingStruct->holdSetupTime = 0xFC;
emmcPCCardConfig->IOSpaceTimingStruct->HiZSetupTime = 0xFC;
}
/*!
* @brief Enables the specified NOR/SRAM Memory Bank.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK1_NORSRAM_1: EMMC Bank1 NOR/SRAM1
* @arg EMMC_BANK1_NORSRAM_2: EMMC Bank1 NOR/SRAM2
* @arg EMMC_BANK1_NORSRAM_3: EMMC Bank1 NOR/SRAM3
* @arg EMMC_BANK1_NORSRAM_4: EMMC Bank1 NOR/SRAM4
*
* @retval None
*/
void EMMC_EnableNORSRAM(EMMC_BANK1_NORSRAM_T bank)
{
EMMC_Bank1->SNCTRL_T[bank] |= 0x00000001;
}
/*!
* @brief Disbles the specified NOR/SRAM Memory Bank.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK1_NORSRAM_1: EMMC Bank1 NOR/SRAM1
* @arg EMMC_BANK1_NORSRAM_2: EMMC Bank1 NOR/SRAM2
* @arg EMMC_BANK1_NORSRAM_3: EMMC Bank1 NOR/SRAM3
* @arg EMMC_BANK1_NORSRAM_4: EMMC Bank1 NOR/SRAM4
*
* @retval None
*/
void EMMC_DisableNORSRAM(EMMC_BANK1_NORSRAM_T bank)
{
EMMC_Bank1->SNCTRL_T[bank] &= 0x000FFFFE;
}
/*!
* @brief Enables the specified NAND Memory Bank.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND: FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND: FSMC Bank3 NAND
*
* @retval None
*/
void EMMC_EnableNAND(EMMC_BANK_NAND_T bank)
{
if(bank == EMMC_BANK2_NAND)
{
EMMC_Bank2->CTRL2_B.MBKEN = BIT_SET;
}
else
{
EMMC_Bank3->CTRL3_B.MBKEN = BIT_SET;
}
}
/*!
* @brief Disbles the specified NAND Memory Bank.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND: FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND: FSMC Bank3 NAND
*
* @retval None
*/
void EMMC_DisableNAND(EMMC_BANK_NAND_T bank)
{
if(bank == EMMC_BANK2_NAND)
{
EMMC_Bank2->CTRL2_B.MBKEN = BIT_RESET;
}
else
{
EMMC_Bank3->CTRL3_B.MBKEN = BIT_RESET;
}
}
/*!
* @brief Enables the specified PC Card Memory Bank.
*
* @param None
*
* @retval None
*/
void EMMC_EnablePCCARD(void)
{
EMMC_Bank4->CTRL4_B.MBKEN = BIT_SET;
}
/*!
* @brief Disables the specified PC Card Memory Bank.
*
* @param None
*
* @retval None
*/
void EMMC_DisablePCCARD(void)
{
EMMC_Bank4->CTRL4_B.MBKEN = BIT_RESET;
}
/*!
* @brief Enbles the EMMC NAND ECC feature.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND: FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND: FSMC Bank3 NAND
*
* @retval None
*/
void EMMC_EnableNANDECC(EMMC_BANK_NAND_T bank)
{
if(bank == EMMC_BANK2_NAND)
{
EMMC_Bank2->CTRL2 |= 0x00000040;
}
else
{
EMMC_Bank3->CTRL3 |= 0x00000040;
}
}
/*!
* @brief Disbles or disables the EMMC NAND ECC feature.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND: FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND: FSMC Bank3 NAND
*
* @retval None
*
* @note
*/
void EMMC_DisableNANDECC(EMMC_BANK_NAND_T bank)
{
if(bank == EMMC_BANK2_NAND)
{
EMMC_Bank2->CTRL2 &= 0x000FFFBF;
}
else
{
EMMC_Bank3->CTRL3 &= 0x000FFFBF;
}
}
/*!
* @brief Read the error correction code register value.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND: FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND: FSMC Bank3 NAND
*
* @retval The value of Error Correction Code (ECC).
*/
uint32_t EMMC_ReadECC(EMMC_BANK_NAND_T bank)
{
uint32_t eccval = 0x00000000;
if(bank == EMMC_BANK2_NAND)
{
eccval = EMMC_Bank2->ECCRS2;
}
else
{
eccval = EMMC_Bank3->ECCRS3;
}
return eccval;
}
/*!
* @brief Enables the specified EMMC interrupts.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND : FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND : FSMC Bank3 NAND
* @arg EMMC_BANK4_PCCARD: FSMC Bank4 PCCARD
*
* @param interrupt: Select the EMMC interrupt sources.
* This parameter can be any combination of the following values:
* @arg EMMC_INT_EDGE_RISING : Rising edge detection interrupt.
* @arg EMMC_INT_LEVEL_HIGH : High level detection interrupt.
* @arg EMMC_INT_EDGE_FALLING: Falling edge detection interrupt.
*
* @retval None
*/
void EMMC_EnableInterrupt(EMMC_BANK_NAND_T bank, uint32_t interrupt)
{
if(bank == EMMC_BANK2_NAND)
{
EMMC_Bank2->STSINT2 |= interrupt;
}
else if(bank == EMMC_BANK3_NAND)
{
EMMC_Bank3->STSINT3 |= interrupt;
}
else
{
EMMC_Bank4->STSINT4 |= interrupt;
}
}
/*!
* @brief Enables the specified EMMC interrupts.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND : FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND : FSMC Bank3 NAND
* @arg EMMC_BANK4_PCCARD: FSMC Bank4 PCCARD
*
* @param interrupt: Select the EMMC interrupt sources.
* This parameter can be any combination of the following values:
* @arg EMMC_INT_EDGE_RISING : Rising edge detection interrupt.
* @arg EMMC_INT_LEVEL_HIGH : High level edge detection interrupt.
* @arg EMMC_INT_EDGE_FALLING: Falling edge detection interrupt.
*
* @retval None
*/
void EMMC_DisableInterrupt(EMMC_BANK_NAND_T bank, uint32_t interrupt)
{
if(bank == EMMC_BANK2_NAND)
{
EMMC_Bank2->STSINT2 &= ~interrupt;
}
else if(bank == EMMC_BANK3_NAND)
{
EMMC_Bank3->STSINT3 &= ~interrupt;
}
else
{
EMMC_Bank4->STSINT4 &= ~interrupt;
}
}
/*!
* @brief Read the status of specified EMMC flag.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND : FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND : FSMC Bank3 NAND
* @arg EMMC_BANK4_PCCARD: FSMC Bank4 PCCARD
*
* @param flag: Select the EMMC interrupt sources.
* This parameter can be one of the following values:
* @arg EMMC_FLAG_EDGE_RISING : Rising egde detection Flag.
* @arg EMMC_FLAG_LEVEL_HIGH : High level detection Flag.
* @arg EMMC_FLAG_EDGE_FALLING: Falling egde detection Flag.
* @arg EMMC_FLAG_FIFO_EMPTY : FIFO empty Flag.
*
* @retval SET or RESET
*
* @note
*/
uint8_t EMMC_ReadStatusFlag(EMMC_BANK_NAND_T bank, EMMC_FLAG_T flag)
{
uint32_t tmpsr = 0x00000000;
if(bank == EMMC_BANK2_NAND)
{
tmpsr = EMMC_Bank2->STSINT2;
}
else if(bank == EMMC_BANK3_NAND)
{
tmpsr = EMMC_Bank3->STSINT3;
}
else
{
tmpsr = EMMC_Bank4->STSINT4;
}
/* Get the flag status */
if((tmpsr & flag) != RESET)
{
return SET;
}
else
{
return RESET;
}
}
/*!
* @brief Clears the EMMC's pending flags.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND : FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND : FSMC Bank3 NAND
* @arg EMMC_BANK4_PCCARD: FSMC Bank4 PCCARD
*
* @param flag: Select the EMMC interrupt sources.
* This parameter can be any combination of the following values:
* @arg EMMC_FLAG_EDGE_RISING : Rising egde detection Flag.
* @arg EMMC_FLAG_LEVEL_HIGH : High level detection Flag.
* @arg EMMC_FLAG_EDGE_FALLING: Falling egde detection Flag.
*
* @retval None
*/
void EMMC_ClearStatusFlag(EMMC_BANK_NAND_T bank, uint32_t flag)
{
if(bank == EMMC_BANK2_NAND)
{
EMMC_Bank2->STSINT2 &= ~flag;
}
else if(bank == EMMC_BANK3_NAND)
{
EMMC_Bank3->STSINT3 &= ~flag;
}
else
{
EMMC_Bank4->STSINT4 &= ~flag;
}
}
/*!
* @brief Read the specified EMMC interrupt has occurred or not.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND : FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND : FSMC Bank3 NAND
* @arg EMMC_BANK4_PCCARD: FSMC Bank4 PCCARD
*
* @param interrupt: Select the EMMC interrupt source.
* This parameter can be one of the following values:
* @arg EMMC_INT_EDGE_RISING : Rising edge detection interrupt.
* @arg EMMC_INT_LEVEL_HIGH : High level edge detection interrupt.
* @arg EMMC_INT_EDGE_FALLING: Falling edge detection interrupt.
*
* @retval The status of specified EMMC interrupt source.
*/
uint8_t EMMC_ReadIntFlag(EMMC_BANK_NAND_T bank, EMMC_INT_T flag)
{
uint32_t tmpsr = 0x0, itstatus = 0x0, itenable = 0x0;
if(bank == EMMC_BANK2_NAND)
{
tmpsr = EMMC_Bank2->STSINT2;
}
else if(bank == EMMC_BANK3_NAND)
{
tmpsr = EMMC_Bank3->STSINT3;
}
else
{
tmpsr = EMMC_Bank4->STSINT4;
}
itstatus = tmpsr & flag;
itenable = tmpsr & (flag >> 3);
if((itstatus != RESET) && (itenable != RESET))
{
return SET;
}
else
{
return RESET;
}
}
/*!
* @brief Clears the EMMC's interrupt Flag.
*
* @param bank: Selects the EMMMC Bank.
* The parameter can be one of following values:
* @arg EMMC_BANK2_NAND : FSMC Bank2 NAND
* @arg EMMC_BANK3_NAND : FSMC Bank3 NAND
* @arg EMMC_BANK4_PCCARD: FSMC Bank4 PCCARD
*
* @param interrupt: Select the EMMC interrupt sources.
* This parameter can be any combination of the following values:
* @arg EMMC_INT_EDGE_RISING : Rising edge detection interrupt.
* @arg EMMC_INT_LEVEL_HIGH : High level edge detection interrupt.
* @arg EMMC_INT_EDGE_FALLING: Falling edge detection interrupt.
*
* @retval None
*/
void EMMC_ClearIntFlag(EMMC_BANK_NAND_T bank, uint32_t flag)
{
if(bank == EMMC_BANK2_NAND)
{
EMMC_Bank2->STSINT2 &= ~(flag >> 3);
}
else if(bank == EMMC_BANK3_NAND)
{
EMMC_Bank3->STSINT3 &= ~(flag >> 3);
}
else
{
EMMC_Bank4->STSINT4 &= ~(flag >> 3);
}
}
/**@} end of group EMMC_Fuctions*/
/**@} end of group EMMC_Driver*/
/**@} end of group Peripherals_Library*/
| 11,710 |
1,197 |
<gh_stars>1000+
/**
* Copyright (c) 2014 ControlsFX
* 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 ControlsFX, any associated website, 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 CONTROLSFX BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.controlsfx.dialog;
import static impl.org.controlsfx.i18n.Localization.asKey;
import static impl.org.controlsfx.i18n.Localization.localize;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import javafx.application.Platform;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.transformation.FilteredList;
import javafx.geometry.Pos;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.util.Callback;
public class FontSelectorDialog extends Dialog<Font> {
private FontPanel fontPanel;
public FontSelectorDialog(Font defaultFont) {
fontPanel = new FontPanel();
fontPanel.setFont(defaultFont);
setResultConverter(dialogButton -> dialogButton == ButtonType.OK ? fontPanel.getFont() : null);
final DialogPane dialogPane = getDialogPane();
setTitle(localize(asKey("font.dlg.title"))); //$NON-NLS-1$
dialogPane.setHeaderText(localize(asKey("font.dlg.header"))); //$NON-NLS-1$
dialogPane.getStyleClass().add("font-selector-dialog"); //$NON-NLS-1$
dialogPane.getStylesheets().add(FontSelectorDialog.class.getResource("dialogs.css").toExternalForm()); //$NON-NLS-1$
dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
dialogPane.setContent(fontPanel);
}
/**************************************************************************
*
* Support classes
*
**************************************************************************/
/**
* Font style as combination of font weight and font posture.
* Weight does not have to be there (represented by null)
* Posture is required, null posture is converted to REGULAR
*/
private static class FontStyle implements Comparable<FontStyle> {
private FontPosture posture;
private FontWeight weight;
public FontStyle( FontWeight weight, FontPosture posture ) {
this.posture = posture == null? FontPosture.REGULAR: posture;
this.weight = weight;
}
public FontStyle() {
this( null, null);
}
public FontStyle(String styles) {
this();
String[] fontStyles = (styles == null? "": styles.trim().toUpperCase()).split(" "); //$NON-NLS-1$ //$NON-NLS-2$
for ( String style: fontStyles) {
FontWeight w = FontWeight.findByName(style);
if ( w != null ) {
weight = w;
} else {
FontPosture p = FontPosture.findByName(style);
if ( p != null ) posture = p;
}
}
}
public FontStyle(Font font) {
this( font.getStyle());
}
public FontPosture getPosture() {
return posture;
}
public FontWeight getWeight() {
return weight;
}
@Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((posture == null) ? 0 : posture.hashCode());
result = prime * result + ((weight == null) ? 0 : weight.hashCode());
return result;
}
@Override public boolean equals(Object that) {
if (this == that)
return true;
if (that == null)
return false;
if (getClass() != that.getClass())
return false;
FontStyle other = (FontStyle) that;
if (posture != other.posture)
return false;
if (weight != other.weight)
return false;
return true;
}
private static String makePretty(Object o) {
String s = o == null? "": o.toString(); //$NON-NLS-1$
if ( !s.isEmpty()) {
s = s.replace("_", " "); //$NON-NLS-1$ //$NON-NLS-2$
s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
return s;
}
@Override public String toString() {
return String.format("%s %s", makePretty(weight), makePretty(posture) ).trim(); //$NON-NLS-1$
}
private <T extends Enum<T>> int compareEnums( T e1, T e2) {
if ( e1 == e2 ) return 0;
if ( e1 == null ) return -1;
if ( e2 == null ) return 1;
return e1.compareTo(e2);
}
@Override public int compareTo(FontStyle fs) {
int result = compareEnums(weight,fs.weight);
return ( result != 0 )? result: compareEnums(posture,fs.posture);
}
}
private static class FontPanel extends GridPane {
private static final double HGAP = 10;
private static final double VGAP = 5;
private static final Predicate<Object> MATCH_ALL = new Predicate<Object>() {
@Override public boolean test(Object t) {
return true;
}
};
private static final Double[] fontSizes = new Double[] {8d,9d,11d,12d,14d,16d,18d,20d,22d,24d,26d,28d,36d,48d,72d};
private static List<FontStyle> getFontStyles( String fontFamily ) {
Set<FontStyle> set = new HashSet<>();
for (String f : Font.getFontNames(fontFamily)) {
set.add(new FontStyle(f.replace(fontFamily, ""))); //$NON-NLS-1$
}
List<FontStyle> result = new ArrayList<>(set);
Collections.sort(result);
return result;
}
private final FilteredList<String> filteredFontList = new FilteredList<>(FXCollections.observableArrayList(Font.getFamilies()), MATCH_ALL);
private final FilteredList<FontStyle> filteredStyleList = new FilteredList<>(FXCollections.<FontStyle>observableArrayList(), MATCH_ALL);
private final FilteredList<Double> filteredSizeList = new FilteredList<>(FXCollections.observableArrayList(fontSizes), MATCH_ALL);
private final ListView<String> fontListView = new ListView<>(filteredFontList);
private final ListView<FontStyle> styleListView = new ListView<>(filteredStyleList);
private final ListView<Double> sizeListView = new ListView<>(filteredSizeList);
private final Text sample = new Text(localize(asKey("font.dlg.sample.text"))); //$NON-NLS-1$
public FontPanel() {
setHgap(HGAP);
setVgap(VGAP);
setPrefSize(500, 300);
setMinSize(500, 300);
ColumnConstraints c0 = new ColumnConstraints();
c0.setPercentWidth(60);
ColumnConstraints c1 = new ColumnConstraints();
c1.setPercentWidth(25);
ColumnConstraints c2 = new ColumnConstraints();
c2.setPercentWidth(15);
getColumnConstraints().addAll(c0, c1, c2);
RowConstraints r0 = new RowConstraints();
r0.setVgrow(Priority.NEVER);
RowConstraints r1 = new RowConstraints();
r1.setVgrow(Priority.NEVER);
RowConstraints r2 = new RowConstraints();
r2.setFillHeight(true);
r2.setVgrow(Priority.NEVER);
RowConstraints r3 = new RowConstraints();
r3.setPrefHeight(250);
r3.setVgrow(Priority.NEVER);
getRowConstraints().addAll(r0, r1, r2, r3);
// layout hello.dialog
add(new Label(localize(asKey("font.dlg.font.label"))), 0, 0); //$NON-NLS-1$
// fontSearch.setMinHeight(Control.USE_PREF_SIZE);
// add( fontSearch, 0, 1);
add(fontListView, 0, 1);
fontListView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override public ListCell<String> call(ListView<String> listview) {
return new ListCell<String>() {
@Override protected void updateItem(String family, boolean empty) {
super.updateItem(family, empty);
if (! empty) {
setFont(Font.font(family));
setText(family);
} else {
setText(null);
}
}
};
}
});
ChangeListener<Object> sampleRefreshListener = new ChangeListener<Object>() {
@Override public void changed(ObservableValue<? extends Object> arg0, Object arg1, Object arg2) {
refreshSample();
}
};
fontListView.selectionModelProperty().get().selectedItemProperty().addListener( new ChangeListener<String>() {
@Override public void changed(ObservableValue<? extends String> arg0, String arg1, String arg2) {
String fontFamily = listSelection(fontListView);
styleListView.setItems(FXCollections.<FontStyle>observableArrayList(getFontStyles(fontFamily)));
refreshSample();
}});
add( new Label(localize(asKey("font.dlg.style.label"))), 1, 0); //$NON-NLS-1$
// postureSearch.setMinHeight(Control.USE_PREF_SIZE);
// add( postureSearch, 1, 1);
add(styleListView, 1, 1);
styleListView.selectionModelProperty().get().selectedItemProperty().addListener(sampleRefreshListener);
add( new Label(localize(asKey("font.dlg.size.label"))), 2, 0); //$NON-NLS-1$
// sizeSearch.setMinHeight(Control.USE_PREF_SIZE);
// add( sizeSearch, 2, 1);
add(sizeListView, 2, 1);
sizeListView.selectionModelProperty().get().selectedItemProperty().addListener(sampleRefreshListener);
final double height = 45;
final DoubleBinding sampleWidth = new DoubleBinding() {
{
bind(fontListView.widthProperty(), styleListView.widthProperty(), sizeListView.widthProperty());
}
@Override protected double computeValue() {
return fontListView.getWidth() + styleListView.getWidth() + sizeListView.getWidth() + 3 * HGAP;
}
};
StackPane sampleStack = new StackPane(sample);
sampleStack.setAlignment(Pos.CENTER_LEFT);
sampleStack.setMinHeight(height);
sampleStack.setPrefHeight(height);
sampleStack.setMaxHeight(height);
sampleStack.prefWidthProperty().bind(sampleWidth);
Rectangle clip = new Rectangle(0, height);
clip.widthProperty().bind(sampleWidth);
sampleStack.setClip(clip);
add(sampleStack, 0, 3, 1, 3);
}
public void setFont(final Font font) {
final Font _font = font == null ? Font.getDefault() : font;
if (_font != null) {
selectInList( fontListView, _font.getFamily() );
selectInList( styleListView, new FontStyle(_font));
selectInList( sizeListView, _font.getSize() );
}
}
public Font getFont() {
try {
FontStyle style = listSelection(styleListView);
if ( style == null ) {
return Font.font(
listSelection(fontListView),
listSelection(sizeListView));
} else {
return Font.font(
listSelection(fontListView),
style.getWeight(),
style.getPosture(),
listSelection(sizeListView));
}
} catch( Throwable ex ) {
return null;
}
}
private void refreshSample() {
sample.setFont(getFont());
}
private <T> void selectInList( final ListView<T> listView, final T selection ) {
Platform.runLater(new Runnable() {
@Override public void run() {
listView.scrollTo(selection);
listView.getSelectionModel().select(selection);
}
});
}
private <T> T listSelection(final ListView<T> listView) {
return listView.selectionModelProperty().get().getSelectedItem();
}
}
}
| 6,769 |
1,443 |
<filename>users/ruucm.json
{
"copyright": "ruucm, http://ruucm.work",
"url": "http://ruucm.work",
"email": "<EMAIL>",
"gravatar": true
}
| 66 |
3,714 |
"""
---
title: Layer Normalization
summary: >
A PyTorch implementation/tutorial of layer normalization.
---
# Layer Normalization
This is a [PyTorch](https://pytorch.org) implementation of
[Layer Normalization](https://papers.labml.ai/paper/1607.06450).
### Limitations of [Batch Normalization](../batch_norm/index.html)
* You need to maintain running means.
* Tricky for RNNs. Do you need different normalizations for each step?
* Doesn't work with small batch sizes;
large NLP models are usually trained with small batch sizes.
* Need to compute means and variances across devices in distributed training.
## Layer Normalization
Layer normalization is a simpler normalization method that works
on a wider range of settings.
Layer normalization transforms the inputs to have zero mean and unit variance
across the features.
*Note that batch normalization fixes the zero mean and unit variance for each element.*
Layer normalization does it for each batch across all elements.
Layer normalization is generally used for NLP tasks.
We have used layer normalization in most of the
[transformer implementations](../../transformers/gpt/index.html).
"""
from typing import Union, List
import torch
from torch import nn, Size
from labml_helpers.module import Module
class LayerNorm(Module):
r"""
## Layer Normalization
Layer normalization $\text{LN}$ normalizes the input $X$ as follows:
When input $X \in \mathbb{R}^{B \times C}$ is a batch of embeddings,
where $B$ is the batch size and $C$ is the number of features.
$\gamma \in \mathbb{R}^{C}$ and $\beta \in \mathbb{R}^{C}$.
$$\text{LN}(X) = \gamma
\frac{X - \underset{C}{\mathbb{E}}[X]}{\sqrt{\underset{C}{Var}[X] + \epsilon}}
+ \beta$$
When input $X \in \mathbb{R}^{L \times B \times C}$ is a batch of a sequence of embeddings,
where $B$ is the batch size, $C$ is the number of channels, $L$ is the length of the sequence.
$\gamma \in \mathbb{R}^{C}$ and $\beta \in \mathbb{R}^{C}$.
$$\text{LN}(X) = \gamma
\frac{X - \underset{C}{\mathbb{E}}[X]}{\sqrt{\underset{C}{Var}[X] + \epsilon}}
+ \beta$$
When input $X \in \mathbb{R}^{B \times C \times H \times W}$ is a batch of image representations,
where $B$ is the batch size, $C$ is the number of channels, $H$ is the height and $W$ is the width.
This is not a widely used scenario.
$\gamma \in \mathbb{R}^{C \times H \times W}$ and $\beta \in \mathbb{R}^{C \times H \times W}$.
$$\text{LN}(X) = \gamma
\frac{X - \underset{C, H, W}{\mathbb{E}}[X]}{\sqrt{\underset{C, H, W}{Var}[X] + \epsilon}}
+ \beta$$
"""
def __init__(self, normalized_shape: Union[int, List[int], Size], *,
eps: float = 1e-5,
elementwise_affine: bool = True):
"""
* `normalized_shape` $S$ is the shape of the elements (except the batch).
The input should then be
$X \in \mathbb{R}^{* \times S[0] \times S[1] \times ... \times S[n]}$
* `eps` is $\epsilon$, used in $\sqrt{Var[X] + \epsilon}$ for numerical stability
* `elementwise_affine` is whether to scale and shift the normalized value
We've tried to use the same names for arguments as PyTorch `LayerNorm` implementation.
"""
super().__init__()
self.normalized_shape = normalized_shape
self.eps = eps
self.elementwise_affine = elementwise_affine
# Create parameters for $\gamma$ and $\beta$ for gain and bias
if self.elementwise_affine:
self.gain = nn.Parameter(torch.ones(normalized_shape))
self.bias = nn.Parameter(torch.zeros(normalized_shape))
def forward(self, x: torch.Tensor):
"""
`x` is a tensor of shape `[*, S[0], S[1], ..., S[n]]`.
`*` could be any number of dimensions.
For example, in an NLP task this will be
`[seq_len, batch_size, features]`
"""
# Sanity check to make sure the shapes match
assert self.normalized_shape == x.shape[-len(self.normalized_shape):]
# The dimensions to calculate the mean and variance on
dims = [-(i + 1) for i in range(len(self.normalized_shape))]
# Calculate the mean of all elements;
# i.e. the means for each element $\mathbb{E}[X]$
mean = x.mean(dim=dims, keepdim=True)
# Calculate the squared mean of all elements;
# i.e. the means for each element $\mathbb{E}[X^2]$
mean_x2 = (x ** 2).mean(dim=dims, keepdim=True)
# Variance of all element $Var[X] = \mathbb{E}[X^2] - \mathbb{E}[X]^2$
var = mean_x2 - mean ** 2
# Normalize $$\hat{X} = \frac{X - \mathbb{E}[X]}{\sqrt{Var[X] + \epsilon}}$$
x_norm = (x - mean) / torch.sqrt(var + self.eps)
# Scale and shift $$\text{LN}(x) = \gamma \hat{X} + \beta$$
if self.elementwise_affine:
x_norm = self.gain * x_norm + self.bias
#
return x_norm
def _test():
"""
Simple test
"""
from labml.logger import inspect
x = torch.zeros([2, 3, 2, 4])
inspect(x.shape)
ln = LayerNorm(x.shape[2:])
x = ln(x)
inspect(x.shape)
inspect(ln.gain.shape)
#
if __name__ == '__main__':
_test()
| 2,110 |
1,893 |
<reponame>neuml/txtai
"""
Version string
"""
__version__ = "4.0.0"
| 31 |
1,473 |
<gh_stars>1000+
/*
* Central Repository
*
* Copyright 2021 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.centralrepository.datamodel;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.sleuthkit.datamodel.CaseDbSchemaVersionNumber;
/**
* This class updates CR schema to 1.6
*
*/
public class CentralRepoDbUpgrader15To16 implements CentralRepoDbUpgrader {
@Override
public void upgradeSchema(CaseDbSchemaVersionNumber dbSchemaVersion, Connection connection) throws CentralRepoException, SQLException {
if (dbSchemaVersion.compareTo(new CaseDbSchemaVersionNumber(1, 6)) < 0) {
try (Statement statement = connection.createStatement();) {
CentralRepoPlatforms selectedPlatform = CentralRepoDbManager.getSavedDbChoice().getDbPlatform();
for (CorrelationAttributeInstance.Type type : CorrelationAttributeInstance.getDefaultCorrelationTypes()) {
String instance_type_dbname = CentralRepoDbUtil.correlationTypeToInstanceTableName(type);
if ((type.getId() == CorrelationAttributeInstance.INSTALLED_PROGS_TYPE_ID) ||
(type.getId() == CorrelationAttributeInstance.OSACCOUNT_TYPE_ID)){
// these are new Correlation types - new tables need to be created
statement.execute(String.format(RdbmsCentralRepoFactory.getCreateAccountInstancesTableTemplate(selectedPlatform), instance_type_dbname, instance_type_dbname));
statement.execute(String.format(RdbmsCentralRepoFactory.getAddCaseIdIndexTemplate(), instance_type_dbname, instance_type_dbname));
statement.execute(String.format(RdbmsCentralRepoFactory.getAddDataSourceIdIndexTemplate(), instance_type_dbname, instance_type_dbname));
statement.execute(String.format(RdbmsCentralRepoFactory.getAddValueIndexTemplate(), instance_type_dbname, instance_type_dbname));
statement.execute(String.format(RdbmsCentralRepoFactory.getAddKnownStatusIndexTemplate(), instance_type_dbname, instance_type_dbname));
statement.execute(String.format(RdbmsCentralRepoFactory.getAddObjectIdIndexTemplate(), instance_type_dbname, instance_type_dbname));
// add new correlation type
CentralRepoDbUtil.insertCorrelationType(connection, type);
}
}
}
}
}
}
| 1,170 |
634 |
<filename>modules/base/platform-impl/src/main/java/com/intellij/ui/HideableDetailsUnderSeparator.java<gh_stars>100-1000
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import consulo.awt.TargetAWT;
import consulo.ui.image.Image;
import javax.annotation.Nonnull;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: Irina.Chernushina
* Date: 8/22/11
* Time: 2:54 PM
*/
public abstract class HideableDetailsUnderSeparator extends AbstractTitledSeparatorWithIcon {
public HideableDetailsUnderSeparator(@Nonnull Image icon,
@Nonnull Image iconOpen,
@Nonnull String text) {
super(icon, iconOpen, text);
}
public void on() {
initDetails();
myLabel.setIcon(TargetAWT.to(myIconOpen));
myWrapper.add(myDetailsComponent.getPanel(), BorderLayout.CENTER);
myOn = true;
revalidate();
repaint();
}
public void off() {
myLabel.setIcon(TargetAWT.to(myIcon));
myWrapper.removeAll();
myOn = false;
revalidate();
repaint();
}
}
| 594 |
848 |
<filename>misc/config_tools/config_app/acrn_configurator.py<gh_stars>100-1000
# Copyright (C) 2019 Intel Corporation.
# SPDX-License-Identifier: BSD-3-Clause
"""Entry for config app.
"""
import os
import sys
import threading
import webbrowser
# flask: Copyright 2010 Pallets
# SPDX-License-Identifier: BSD-3-Clause
# Refer to https://github.com/pallets/flask/blob/master/LICENSE.rst for the permission notice.
from flask import Flask
# flask: Copyright (c) 2013, <NAME>
# SPDX-License-Identifier: BSD-3-Clause
# Refer to https://pypi.org/project/Flask-Bootstrap/ for the permission notice.
from flask_bootstrap import Bootstrap
import configs
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'library'))
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..',
'board_config'))
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..',
'scenario_config'))
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..',
'launch_config'))
from views import CONFIG_APP
APP = Flask(__name__)
APP.config.from_object(configs)
APP.register_blueprint(CONFIG_APP)
APP.jinja_env.add_extension('jinja2.ext.do')
Bootstrap(app=APP)
if __name__ == '__main__':
URL = "http://127.0.0.1:5001/scenario"
threading.Timer(1, lambda: webbrowser.open(URL)).start()
APP.run(port=5001, debug=False)
| 647 |
988 |
<reponame>Gegy/DataFixerUpper
package com.mojang.datafixers.util;
import java.util.function.BiFunction;
import java.util.function.Function;
public interface Function10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R> {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10);
default Function<T1, Function9<T2, T3, T4, T5, T6, T7, T8, T9, T10, R>> curry() {
return t1 -> (t2, t3, t4, t5, t6, t7, t8, t9, t10) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
default BiFunction<T1, T2, Function8<T3, T4, T5, T6, T7, T8, T9, T10, R>> curry2() {
return (t1, t2) -> (t3, t4, t5, t6, t7, t8, t9, t10) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
default Function3<T1, T2, T3, Function7<T4, T5, T6, T7, T8, T9, T10, R>> curry3() {
return (t1, t2, t3) -> (t4, t5, t6, t7, t8, t9, t10) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
default Function4<T1, T2, T3, T4, Function6<T5, T6, T7, T8, T9, T10, R>> curry4() {
return (t1, t2, t3, t4) -> (t5, t6, t7, t8, t9, t10) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
default Function5<T1, T2, T3, T4, T5, Function5<T6, T7, T8, T9, T10, R>> curry5() {
return (t1, t2, t3, t4, t5) -> (t6, t7, t8, t9, t10) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
default Function6<T1, T2, T3, T4, T5, T6, Function4<T7, T8, T9, T10, R>> curry6() {
return (t1, t2, t3, t4, t5, t6) -> (t7, t8, t9, t10) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
default Function7<T1, T2, T3, T4, T5, T6, T7, Function3<T8, T9, T10, R>> curry7() {
return (t1, t2, t3, t4, t5, t6, t7) -> (t8, t9, t10) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
default Function8<T1, T2, T3, T4, T5, T6, T7, T8, BiFunction<T9, T10, R>> curry8() {
return (t1, t2, t3, t4, t5, t6, t7, t8) -> (t9, t10) -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
default Function9<T1, T2, T3, T4, T5, T6, T7, T8, T9, Function<T10, R>> curry9() {
return (t1, t2, t3, t4, t5, t6, t7, t8, t9) -> t10 -> apply(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
}
}
| 1,285 |
572 |
<reponame>wbaby/DebugViewPP<filename>Libraries/PropertyGrid/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by PropertyControlTest.rc
//
#define IDD_ABOUTBOX 100
#define IDR_MAINFRAME 128
#define IDD_MAINDLG 129
#define IDS_TRUE 129
#define IDS_FALSE 130
#define IDB_PROPERTYTREE 201
#define IDC_LIST1 1000
#define IDC_TREE1 1002
#define IDC_LISTVIEW1 1003
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 202
#define _APS_NEXT_COMMAND_VALUE 32772
#define _APS_NEXT_CONTROL_VALUE 1004
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 281 |
1,444 |
<reponame>amc8391/mage
package org.mage.test.cards.abilities.other;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import mage.counters.CounterType;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
* @author JayDi85
*/
public class OathOfKayaTest extends CardTestPlayerBase {
@Test
public void test_AttackingPlayer() {
// Whenever an opponent attacks a planeswalker you control with one or more creatures,
// Oath of Kaya deals 2 damage to that player and you gain 2 life.
addCard(Zone.BATTLEFIELD, playerB, "Oath of Kaya", 1);
//
addCard(Zone.BATTLEFIELD, playerA, "Grizzly Bears", 2); // 2/2
addCard(Zone.BATTLEFIELD, playerB, "Liliana, Dreadhorde General", 1);
attack(1, playerA, "Grizzly Bears", playerB);
setStrictChooseMode(true);
setStopAt(1, PhaseStep.END_TURN);
execute();
assertAllCommandsUsed();
assertCounterCount(playerB, "Liliana, Dreadhorde General", CounterType.LOYALTY, 6);
assertLife(playerA, 20);
assertLife(playerB, 20 - 2);
}
@Test
public void test_AttackingPlaneswalker() {
// Whenever an opponent attacks a planeswalker you control with one or more creatures,
// Oath of Kaya deals 2 damage to that player and you gain 2 life.
addCard(Zone.BATTLEFIELD, playerB, "Oath of Kaya", 1);
//
addCard(Zone.BATTLEFIELD, playerA, "Grizzly Bears", 2); // 2/2
addCard(Zone.BATTLEFIELD, playerB, "Liliana, Dreadhorde General", 1);
attack(1, playerA, "Grizzly Bears", "Liliana, Dreadhorde General");
attack(1, playerA, "Grizzly Bears", "Liliana, Dreadhorde General");
setStrictChooseMode(true);
setStopAt(1, PhaseStep.END_TURN);
execute();
assertAllCommandsUsed();
assertCounterCount(playerB, "Liliana, Dreadhorde General", CounterType.LOYALTY, 6 - 2 * 2);
assertLife(playerA, 20 - 2);
assertLife(playerB, 20 + 2);
}
@Test
public void test_AttackingTwoPlaneswalkers() {
// Whenever an opponent attacks a planeswalker you control with one or more creatures,
// Oath of Kaya deals 2 damage to that player and you gain 2 life.
addCard(Zone.BATTLEFIELD, playerB, "Oath of Kaya", 1);
//
addCard(Zone.BATTLEFIELD, playerA, "Grizzly Bears", 2); // 2/2
addCard(Zone.BATTLEFIELD, playerB, "Liliana, Dreadhorde General", 1);
addCard(Zone.BATTLEFIELD, playerB, "Vivien, Champion of the Wilds", 1);
attack(1, playerA, "Grizzly Bears", "Liliana, Dreadhorde General");
attack(1, playerA, "Grizzly Bears", "Vivien, Champion of the Wilds");
setStrictChooseMode(true);
setStopAt(1, PhaseStep.END_TURN);
execute();
assertAllCommandsUsed();
assertCounterCount(playerB, "Liliana, Dreadhorde General", CounterType.LOYALTY, 6 - 2);
assertCounterCount(playerB, "Vivien, Champion of the Wilds", CounterType.LOYALTY, 4 - 2);
assertLife(playerA, 20 - 2);
assertLife(playerB, 20 + 2);
}
}
| 1,274 |
1,787 |
<reponame>jagjeetsm/cloud-custodian
{
"status_code": 400,
"data": {
"Error": {
"Message": "Repository policy does not exist for the repository with name 'nginx' in the registry with id '644160558196'",
"Code": "RepositoryPolicyNotFoundException"
},
"ResponseMetadata": {},
"message": "Repository policy does not exist for the repository with name 'nginx' in the registry with id '644160558196'"
}
}
| 187 |
573 |
// Copyright 2015, VIXL authors
// 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 ARM Limited 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 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.
// ---------------------------------------------------------------------
// This file is auto generated using tools/generate_simulator_traces.py.
//
// PLEASE DO NOT EDIT.
// ---------------------------------------------------------------------
#ifndef VIXL_SIM_SDOT_4S_TRACE_AARCH64_H_
#define VIXL_SIM_SDOT_4S_TRACE_AARCH64_H_
const uint32_t kExpected_NEON_sdot_4S[] = {
0x0000a16f, 0x0000fc07, 0x000064bf, 0x0000002e,
0x0000b678, 0x00007c09, 0x00003d30, 0x00000028,
0x000041c0, 0x00006857, 0x00001cc2, 0x00000022,
0xffffc643, 0x00004441, 0x0000055c, 0x0000001c,
0xffff72c6, 0x00000aba, 0x00000259, 0x00000011,
0xffff4149, 0xfffff4c9, 0x0000014a, 0xffffffd7,
0xffff5580, 0xffffecae, 0x0000003b, 0xffffff4d,
0xffff79cf, 0xffffff05, 0xffffff04, 0xfffffe60,
0xffffad37, 0x00000003, 0xfffffba1, 0xfffffda9,
0xffffd838, 0xffffff05, 0xffffef54, 0xfffffd2e,
0xfffff089, 0xfffffe07, 0xffffd5cc, 0xfffffe28,
0xfffffbf1, 0xfffffa93, 0xffffad39, 0x00000022,
0xfffffe40, 0xffffe26e, 0xffff8ef3, 0x0000031c,
0xffffffc3, 0xffffb9dc, 0xffff82d9, 0x00000316,
0x00000146, 0xffff82c8, 0xffffb5ca, 0x000002ea,
0x0000053f, 0xffff72c7, 0x00000abb, 0x00000277,
0x00001ddf, 0xffff6ea8, 0x000086ac, 0x00000192,
0x000045cb, 0xffffff03, 0x0000846d, 0x000000cf,
0x0000798e, 0x00007d05, 0x00007a9e, 0x00000040,
0x0000b678, 0x00007c09, 0x00003d30, 0x00000028,
0x0000d647, 0x0000fa0f, 0x000027bf, 0x00000026,
0x00006609, 0x0000e587, 0x00001338, 0x00000024,
0xffffe9d8, 0x0000c0bc, 0x00000361, 0x00000027,
0xffff6ea7, 0x000086ab, 0x00000174, 0x0000004f,
0xffff1b76, 0x00004a34, 0x000000df, 0x00000069,
0xffff301f, 0x0000206d, 0x0000004a, 0x0000005a,
0xffff5501, 0x000006f7, 0xffffffa6, 0xffffffe3,
0xffff8ef1, 0x000002fd, 0xfffffe6b, 0xffffff78,
0xffffc4a1, 0x00000103, 0xfffffb1f, 0xfffffe28,
0xffffe85c, 0xffffff09, 0xffffeed7, 0xfffffe26,
0xfffffa66, 0xfffffa9e, 0xffffd83a, 0xffffff24,
0xfffffd89, 0xffffe1ac, 0xffffc4a3, 0x00000122,
0xffffff58, 0xffffb86e, 0xffffb9f4, 0x00000146,
0x00000127, 0xffff7bd5, 0xffffc15f, 0x00000165,
0x00000571, 0xffff414a, 0xfffff4ca, 0x00000168,
0x00001e8c, 0xffff1b77, 0x00004a35, 0x000000fd,
0x000047d7, 0xffff82fd, 0x0000492e, 0x0000008e,
0x00008368, 0xffffff03, 0x00004706, 0x00000032,
0x000041c0, 0x00006857, 0x00001cc2, 0x00000022,
0x00006609, 0x0000e587, 0x00001338, 0x00000024,
0x0000fa0e, 0x0000d6f3, 0x00000adf, 0x00000026,
0x00007c08, 0x0000b77f, 0x000001c2, 0x00000032,
0xffffff02, 0x0000846c, 0x000000b1, 0x0000008d,
0xffff82fc, 0x0000492d, 0x00000070, 0x000000fb,
0xffff70f6, 0x00001fe0, 0x0000002f, 0x00000167,
0xffff744a, 0x000006c3, 0xffffffe4, 0x00000166,
0xffff82d7, 0x000002f7, 0xffffff40, 0x00000147,
0xffffb9f2, 0x00000127, 0xfffffe17, 0xffffff22,
0xffffe22f, 0xffffff57, 0xfffffad1, 0xfffffe24,
0xfffffa20, 0xfffffbd9, 0xfffff08b, 0xfffffe26,
0xfffffd0e, 0xffffe97c, 0xffffe85e, 0xffffff28,
0xfffffe08, 0xffffc59e, 0xffffe231, 0xffffff76,
0xffffff02, 0xffff8f70, 0xffffe4f0, 0xffffffe0,
0xfffffd7c, 0xffff5581, 0xffffecaf, 0x00000059,
0xffffebf1, 0xffff3020, 0x0000206e, 0x00000068,
0xfffff3b7, 0xffff70f7, 0x00001fe1, 0x0000004d,
0x000008ad, 0xffffec27, 0x00001eec, 0x00000024,
0xffffc643, 0x00004441, 0x0000055c, 0x0000001c,
0xffffe9d8, 0x0000c0bc, 0x00000361, 0x00000027,
0x00007c08, 0x0000b77f, 0x000001c2, 0x00000032,
0x0000fc06, 0x0000a282, 0x00000050, 0x00000065,
0x00007d04, 0x00007a9d, 0x00000022, 0x000001ca,
0xffffff02, 0x00004705, 0x00000014, 0x00000336,
0xffffec26, 0x00001eeb, 0x00000006, 0x000004e5,
0xffffc8c5, 0x00000648, 0xfffffff3, 0x0000055f,
0xffffb5c8, 0x000002cb, 0xffffffb1, 0x00000591,
0xffffc15d, 0x00000146, 0xffffff1f, 0xfffffd9c,
0xffffe4ee, 0xffffffc1, 0xfffffe02, 0xfffffba7,
0xfffffc12, 0xfffffd38, 0xfffffbf3, 0xfffffab2,
0xfffffe08, 0xfffff17d, 0xfffffa68, 0xfffffabd,
0xfffffe06, 0xffffd8b7, 0xfffffa22, 0xfffffbf8,
0xfffffe04, 0xffffad38, 0xfffffc14, 0xfffffd57,
0xfffffb87, 0xffff79d0, 0xffffff06, 0xffffff22,
0xffffe42f, 0xffff5502, 0x000006f8, 0xffffffc4,
0xffffc149, 0xffff744b, 0x000006c4, 0x00000002,
0xffffb4ba, 0xffffc8c6, 0x00000649, 0x00000011,
0xffff72c6, 0x00000aba, 0x00000259, 0x00000011,
0xffff6ea7, 0x000086ab, 0x00000174, 0x0000004f,
0xffffff02, 0x0000846c, 0x000000b1, 0x0000008d,
0x00007d04, 0x00007a9d, 0x00000022, 0x000001ca,
0x0000fc06, 0x000064be, 0x00000010, 0x00000a8e,
0x00007c08, 0x00003d2f, 0x0000000a, 0x000012b9,
0x00006856, 0x00001cc1, 0x00000004, 0x00001c1d,
0x00004440, 0x0000055b, 0xfffffffe, 0x00001dff,
0x00000ab9, 0x00000258, 0xfffffff3, 0x00001eac,
0xfffff4c8, 0x00000149, 0xffffffb9, 0xffffec11,
0xffffecad, 0x0000003a, 0xffffff2f, 0xffffe44f,
0xffffff04, 0xffffff03, 0xfffffe42, 0xffffe28d,
0x00000002, 0xfffffba0, 0xfffffd8b, 0xffffe1cb,
0xffffff04, 0xffffef53, 0xfffffd10, 0xffffe99b,
0xfffffe06, 0xffffd5cb, 0xfffffe0a, 0xfffff19c,
0xfffffa92, 0xffffad38, 0x00000004, 0xfffffbbf,
0xffffe26d, 0xffff8ef2, 0x000002fe, 0xfffffe89,
0xffffb9db, 0xffff82d8, 0x000002f8, 0xffffff5e,
0xffff82c7, 0xffffb5c9, 0x000002cc, 0xffffffcf,
0xffff4149, 0xfffff4c9, 0x0000014a, 0xffffffd7,
0xffff1b76, 0x00004a34, 0x000000df, 0x00000069,
0xffff82fc, 0x0000492d, 0x00000070, 0x000000fb,
0xffffff02, 0x00004705, 0x00000014, 0x00000336,
0x00007c08, 0x00003d2f, 0x0000000a, 0x000012b9,
0x0000fa0e, 0x000027be, 0x00000008, 0x000026c6,
0x0000e586, 0x00001337, 0x00000006, 0x00003c38,
0x0000c0bb, 0x00000360, 0x00000009, 0x000045eb,
0x000086aa, 0x00000173, 0x00000031, 0x000047f7,
0x00004a33, 0x000000de, 0x0000004b, 0xfffff3d7,
0x0000206c, 0x00000049, 0x0000003c, 0xffffc169,
0x000006f6, 0xffffffa5, 0xffffffc5, 0xffffb9fb,
0x000002fc, 0xfffffe6a, 0xffffff5a, 0xffffb88d,
0x00000102, 0xfffffb1e, 0xfffffe0a, 0xffffc5bd,
0xffffff08, 0xffffeed6, 0xfffffe08, 0xffffd8d6,
0xfffffa9d, 0xffffd839, 0xffffff06, 0xffffef72,
0xffffe1ab, 0xffffc4a2, 0x00000104, 0xfffffb3d,
0xffffb86d, 0xffffb9f3, 0x00000128, 0xfffffe35,
0xffff7bd4, 0xffffc15e, 0x00000147, 0xffffff3d,
0xffff5580, 0xffffecae, 0x0000003b, 0xffffff4d,
0xffff301f, 0x0000206d, 0x0000004a, 0x0000005a,
0xffff70f6, 0x00001fe0, 0x0000002f, 0x00000167,
0xffffec26, 0x00001eeb, 0x00000006, 0x000004e5,
0x00006856, 0x00001cc1, 0x00000004, 0x00001c1d,
0x0000e586, 0x00001337, 0x00000006, 0x00003c38,
0x0000d6f2, 0x00000ade, 0x00000008, 0x000063cb,
0x0000b77e, 0x000001c1, 0x00000014, 0x000079ae,
0x0000846b, 0x000000b0, 0x0000006f, 0x00008388,
0x0000492c, 0x0000006f, 0x000000dd, 0x000008cd,
0x00001fdf, 0x0000002e, 0x00000149, 0xffffb4da,
0x000006c2, 0xffffffe3, 0x00000148, 0xffff82e7,
0x000002f6, 0xffffff3f, 0x00000129, 0xffff7bf4,
0x00000126, 0xfffffe16, 0xffffff04, 0xffff8f8f,
0xffffff56, 0xfffffad0, 0xfffffe06, 0xffffad57,
0xfffffbd8, 0xfffff08a, 0xfffffe08, 0xffffd5ea,
0xffffe97b, 0xffffe85d, 0xffffff0a, 0xffffeef5,
0xffffc59d, 0xffffe230, 0xffffff58, 0xfffffaef,
0xffff8f6f, 0xffffe4ef, 0xffffffc2, 0xfffffe20,
0xffff79cf, 0xffffff05, 0xffffff04, 0xfffffe60,
0xffff5501, 0x000006f7, 0xffffffa6, 0xffffffe3,
0xffff744a, 0x000006c3, 0xffffffe4, 0x00000166,
0xffffc8c5, 0x00000648, 0xfffffff3, 0x0000055f,
0x00004440, 0x0000055b, 0xfffffffe, 0x00001dff,
0x0000c0bb, 0x00000360, 0x00000009, 0x000045eb,
0x0000b77e, 0x000001c1, 0x00000014, 0x000079ae,
0x0000a281, 0x0000004f, 0x00000047, 0x0000a18f,
0x00007a9c, 0x00000021, 0x000001ac, 0x0000b698,
0x00004704, 0x00000013, 0x00000318, 0x000041e0,
0x00001eea, 0x00000005, 0x000004c7, 0xffffc663,
0x00000647, 0xfffffff2, 0x00000541, 0xffff72e6,
0x000002ca, 0xffffffb0, 0x00000573, 0xffff4169,
0x00000145, 0xffffff1e, 0xfffffd7e, 0xffff55a0,
0xffffffc0, 0xfffffe01, 0xfffffb89, 0xffff79ef,
0xfffffd37, 0xfffffbf2, 0xfffffa94, 0xffffad57,
0xfffff17c, 0xfffffa67, 0xfffffa9f, 0xffffd858,
0xffffd8b6, 0xfffffa21, 0xfffffbda, 0xfffff0a9,
0xffffad37, 0xfffffc13, 0xfffffd39, 0xfffffc11,
0xffffad37, 0x00000003, 0xfffffba1, 0xfffffda9,
0xffff8ef1, 0x000002fd, 0xfffffe6b, 0xffffff78,
0xffff82d7, 0x000002f7, 0xffffff40, 0x00000147,
0xffffb5c8, 0x000002cb, 0xffffffb1, 0x00000591,
0x00000ab9, 0x00000258, 0xfffffff3, 0x00001eac,
0x000086aa, 0x00000173, 0x00000031, 0x000047f7,
0x0000846b, 0x000000b0, 0x0000006f, 0x00008388,
0x00007a9c, 0x00000021, 0x000001ac, 0x0000b698,
0x000064bd, 0x0000000f, 0x00000a70, 0x0000d667,
0x00003d2e, 0x00000009, 0x0000129b, 0x00006629,
0x00001cc0, 0x00000003, 0x00001bff, 0xffffe9f8,
0x0000055a, 0xfffffffd, 0x00001de1, 0xffff6ec7,
0x00000257, 0xfffffff2, 0x00001e8e, 0xffff1b96,
0x00000148, 0xffffffb8, 0xffffebf3, 0xffff303f,
0x00000039, 0xffffff2e, 0xffffe431, 0xffff5521,
0xffffff02, 0xfffffe41, 0xffffe26f, 0xffff8f11,
0xfffffb9f, 0xfffffd8a, 0xffffe1ad, 0xffffc4c1,
0xffffef52, 0xfffffd0f, 0xffffe97d, 0xffffe87c,
0xffffd5ca, 0xfffffe09, 0xfffff17e, 0xfffffa86,
0xffffd838, 0xffffff05, 0xffffef54, 0xfffffd2e,
0xffffc4a1, 0x00000103, 0xfffffb1f, 0xfffffe28,
0xffffb9f2, 0x00000127, 0xfffffe17, 0xffffff22,
0xffffc15d, 0x00000146, 0xffffff1f, 0xfffffd9c,
0xfffff4c8, 0x00000149, 0xffffffb9, 0xffffec11,
0x00004a33, 0x000000de, 0x0000004b, 0xfffff3d7,
0x0000492c, 0x0000006f, 0x000000dd, 0x000008cd,
0x00004704, 0x00000013, 0x00000318, 0x000041e0,
0x00003d2e, 0x00000009, 0x0000129b, 0x00006629,
0x000027bd, 0x00000007, 0x000026a8, 0x0000fa2e,
0x00001336, 0x00000005, 0x00003c1a, 0x00007c28,
0x0000035f, 0x00000008, 0x000045cd, 0xffffff22,
0x00000172, 0x00000030, 0x000047d9, 0xffff831c,
0x000000dd, 0x0000004a, 0xfffff3b9, 0xffff7116,
0x00000048, 0x0000003b, 0xffffc14b, 0xffff746a,
0xffffffa4, 0xffffffc4, 0xffffb9dd, 0xffff82f7,
0xfffffe69, 0xffffff59, 0xffffb86f, 0xffffba12,
0xfffffb1d, 0xfffffe09, 0xffffc59f, 0xffffe24f,
0xffffeed5, 0xfffffe07, 0xffffd8b8, 0xfffffa40,
0xfffff089, 0xfffffe07, 0xffffd5cc, 0xfffffe28,
0xffffe85c, 0xffffff09, 0xffffeed7, 0xfffffe26,
0xffffe22f, 0xffffff57, 0xfffffad1, 0xfffffe24,
0xffffe4ee, 0xffffffc1, 0xfffffe02, 0xfffffba7,
0xffffecad, 0x0000003a, 0xffffff2f, 0xffffe44f,
0x0000206c, 0x00000049, 0x0000003c, 0xffffc169,
0x00001fdf, 0x0000002e, 0x00000149, 0xffffb4da,
0x00001eea, 0x00000005, 0x000004c7, 0xffffc663,
0x00001cc0, 0x00000003, 0x00001bff, 0xffffe9f8,
0x00001336, 0x00000005, 0x00003c1a, 0x00007c28,
0x00000add, 0x00000007, 0x000063ad, 0x0000fc26,
0x000001c0, 0x00000013, 0x00007990, 0x00007d24,
0x000000af, 0x0000006e, 0x0000836a, 0xffffff22,
0x0000006e, 0x000000dc, 0x000008af, 0xffffec46,
0x0000002d, 0x00000148, 0xffffb4bc, 0xffffc8e5,
0xffffffe2, 0x00000147, 0xffff82c9, 0xffffb5e8,
0xffffff3e, 0x00000128, 0xffff7bd6, 0xffffc17d,
0xfffffe15, 0xffffff03, 0xffff8f71, 0xffffe50e,
0xfffffacf, 0xfffffe05, 0xffffad39, 0xfffffc32,
0xfffffbf1, 0xfffffa93, 0xffffad39, 0x00000022,
0xfffffa66, 0xfffffa9e, 0xffffd83a, 0xffffff24,
0xfffffa20, 0xfffffbd9, 0xfffff08b, 0xfffffe26,
0xfffffc12, 0xfffffd38, 0xfffffbf3, 0xfffffab2,
0xffffff04, 0xffffff03, 0xfffffe42, 0xffffe28d,
0x000006f6, 0xffffffa5, 0xffffffc5, 0xffffb9fb,
0x000006c2, 0xffffffe3, 0x00000148, 0xffff82e7,
0x00000647, 0xfffffff2, 0x00000541, 0xffff72e6,
0x0000055a, 0xfffffffd, 0x00001de1, 0xffff6ec7,
0x0000035f, 0x00000008, 0x000045cd, 0xffffff22,
0x000001c0, 0x00000013, 0x00007990, 0x00007d24,
0x0000004e, 0x00000046, 0x0000a171, 0x0000fc26,
0x00000020, 0x000001ab, 0x0000b67a, 0x00007c28,
0x00000012, 0x00000317, 0x000041c2, 0x00006876,
0x00000004, 0x000004c6, 0xffffc645, 0x00004460,
0xfffffff1, 0x00000540, 0xffff72c8, 0x00000ad9,
0xffffffaf, 0x00000572, 0xffff414b, 0xfffff4e8,
0xffffff1d, 0xfffffd7d, 0xffff5582, 0xffffeccd,
0xfffffe00, 0xfffffb88, 0xffff79d1, 0xffffff24,
0xfffffe40, 0xffffe26e, 0xffff8ef3, 0x0000031c,
0xfffffd89, 0xffffe1ac, 0xffffc4a3, 0x00000122,
0xfffffd0e, 0xffffe97c, 0xffffe85e, 0xffffff28,
0xfffffe08, 0xfffff17d, 0xfffffa68, 0xfffffabd,
0x00000002, 0xfffffba0, 0xfffffd8b, 0xffffe1cb,
0x000002fc, 0xfffffe6a, 0xffffff5a, 0xffffb88d,
0x000002f6, 0xffffff3f, 0x00000129, 0xffff7bf4,
0x000002ca, 0xffffffb0, 0x00000573, 0xffff4169,
0x00000257, 0xfffffff2, 0x00001e8e, 0xffff1b96,
0x00000172, 0x00000030, 0x000047d9, 0xffff831c,
0x000000af, 0x0000006e, 0x0000836a, 0xffffff22,
0x00000020, 0x000001ab, 0x0000b67a, 0x00007c28,
0x0000000e, 0x00000a6f, 0x0000d649, 0x0000fa2e,
0x00000008, 0x0000129a, 0x0000660b, 0x0000e5a6,
0x00000002, 0x00001bfe, 0xffffe9da, 0x0000c0db,
0xfffffffc, 0x00001de0, 0xffff6ea9, 0x000086ca,
0xfffffff1, 0x00001e8d, 0xffff1b78, 0x00004a53,
0xffffffb7, 0xffffebf2, 0xffff3021, 0x0000208c,
0xffffff2d, 0xffffe430, 0xffff5503, 0x00000716,
0xffffffc3, 0xffffb9dc, 0xffff82d9, 0x00000316,
0xffffff58, 0xffffb86e, 0xffffb9f4, 0x00000146,
0xfffffe08, 0xffffc59e, 0xffffe231, 0xffffff76,
0xfffffe06, 0xffffd8b7, 0xfffffa22, 0xfffffbf8,
0xffffff04, 0xffffef53, 0xfffffd10, 0xffffe99b,
0x00000102, 0xfffffb1e, 0xfffffe0a, 0xffffc5bd,
0x00000126, 0xfffffe16, 0xffffff04, 0xffff8f8f,
0x00000145, 0xffffff1e, 0xfffffd7e, 0xffff55a0,
0x00000148, 0xffffffb8, 0xffffebf3, 0xffff303f,
0x000000dd, 0x0000004a, 0xfffff3b9, 0xffff7116,
0x0000006e, 0x000000dc, 0x000008af, 0xffffec46,
0x00000012, 0x00000317, 0x000041c2, 0x00006876,
0x00000008, 0x0000129a, 0x0000660b, 0x0000e5a6,
0x00000006, 0x000026a7, 0x0000fa10, 0x0000d712,
0x00000004, 0x00003c19, 0x00007c0a, 0x0000b79e,
0x00000007, 0x000045cc, 0xffffff04, 0x0000848b,
0x0000002f, 0x000047d8, 0xffff82fe, 0x0000494c,
0x00000049, 0xfffff3b8, 0xffff70f8, 0x00001fff,
0x0000003a, 0xffffc14a, 0xffff744c, 0x000006e2,
0x00000146, 0xffff82c8, 0xffffb5ca, 0x000002ea,
0x00000127, 0xffff7bd5, 0xffffc15f, 0x00000165,
0xffffff02, 0xffff8f70, 0xffffe4f0, 0xffffffe0,
0xfffffe04, 0xffffad38, 0xfffffc14, 0xfffffd57,
0xfffffe06, 0xffffd5cb, 0xfffffe0a, 0xfffff19c,
0xffffff08, 0xffffeed6, 0xfffffe08, 0xffffd8d6,
0xffffff56, 0xfffffad0, 0xfffffe06, 0xffffad57,
0xffffffc0, 0xfffffe01, 0xfffffb89, 0xffff79ef,
0x00000039, 0xffffff2e, 0xffffe431, 0xffff5521,
0x00000048, 0x0000003b, 0xffffc14b, 0xffff746a,
0x0000002d, 0x00000148, 0xffffb4bc, 0xffffc8e5,
0x00000004, 0x000004c6, 0xffffc645, 0x00004460,
0x00000002, 0x00001bfe, 0xffffe9da, 0x0000c0db,
0x00000004, 0x00003c19, 0x00007c0a, 0x0000b79e,
0x00000006, 0x000063ac, 0x0000fc08, 0x0000a2a1,
0x00000012, 0x0000798f, 0x00007d06, 0x00007abc,
0x0000006d, 0x00008369, 0xffffff04, 0x00004724,
0x000000db, 0x000008ae, 0xffffec28, 0x00001f0a,
0x00000147, 0xffffb4bb, 0xffffc8c7, 0x00000667,
0x0000053f, 0xffff72c7, 0x00000abb, 0x00000277,
0x00000571, 0xffff414a, 0xfffff4ca, 0x00000168,
0xfffffd7c, 0xffff5581, 0xffffecaf, 0x00000059,
0xfffffb87, 0xffff79d0, 0xffffff06, 0xffffff22,
0xfffffa92, 0xffffad38, 0x00000004, 0xfffffbbf,
0xfffffa9d, 0xffffd839, 0xffffff06, 0xffffef72,
0xfffffbd8, 0xfffff08a, 0xfffffe08, 0xffffd5ea,
0xfffffd37, 0xfffffbf2, 0xfffffa94, 0xffffad57,
0xffffff02, 0xfffffe41, 0xffffe26f, 0xffff8f11,
0xffffffa4, 0xffffffc4, 0xffffb9dd, 0xffff82f7,
0xffffffe2, 0x00000147, 0xffff82c9, 0xffffb5e8,
0xfffffff1, 0x00000540, 0xffff72c8, 0x00000ad9,
0xfffffffc, 0x00001de0, 0xffff6ea9, 0x000086ca,
0x00000007, 0x000045cc, 0xffffff04, 0x0000848b,
0x00000012, 0x0000798f, 0x00007d06, 0x00007abc,
0x00000045, 0x0000a170, 0x0000fc08, 0x000064dd,
0x000001aa, 0x0000b679, 0x00007c0a, 0x00003d4e,
0x00000316, 0x000041c1, 0x00006858, 0x00001ce0,
0x000004c5, 0xffffc644, 0x00004442, 0x0000057a,
0x00001ddf, 0xffff6ea8, 0x000086ac, 0x00000192,
0x00001e8c, 0xffff1b77, 0x00004a35, 0x000000fd,
0xffffebf1, 0xffff3020, 0x0000206e, 0x00000068,
0xffffe42f, 0xffff5502, 0x000006f8, 0xffffffc4,
0xffffe26d, 0xffff8ef2, 0x000002fe, 0xfffffe89,
0xffffe1ab, 0xffffc4a2, 0x00000104, 0xfffffb3d,
0xffffe97b, 0xffffe85d, 0xffffff0a, 0xffffeef5,
0xfffff17c, 0xfffffa67, 0xfffffa9f, 0xffffd858,
0xfffffb9f, 0xfffffd8a, 0xffffe1ad, 0xffffc4c1,
0xfffffe69, 0xffffff59, 0xffffb86f, 0xffffba12,
0xffffff3e, 0x00000128, 0xffff7bd6, 0xffffc17d,
0xffffffaf, 0x00000572, 0xffff414b, 0xfffff4e8,
0xfffffff1, 0x00001e8d, 0xffff1b78, 0x00004a53,
0x0000002f, 0x000047d8, 0xffff82fe, 0x0000494c,
0x0000006d, 0x00008369, 0xffffff04, 0x00004724,
0x000001aa, 0x0000b679, 0x00007c0a, 0x00003d4e,
0x00000a6e, 0x0000d648, 0x0000fa10, 0x000027dd,
0x00001299, 0x0000660a, 0x0000e588, 0x00001356,
0x00001bfd, 0xffffe9d9, 0x0000c0bd, 0x0000037f,
0x000045cb, 0xffffff03, 0x0000846d, 0x000000cf,
0x000047d7, 0xffff82fd, 0x0000492e, 0x0000008e,
0xfffff3b7, 0xffff70f7, 0x00001fe1, 0x0000004d,
0xffffc149, 0xffff744b, 0x000006c4, 0x00000002,
0xffffb9db, 0xffff82d8, 0x000002f8, 0xffffff5e,
0xffffb86d, 0xffffb9f3, 0x00000128, 0xfffffe35,
0xffffc59d, 0xffffe230, 0xffffff58, 0xfffffaef,
0xffffd8b6, 0xfffffa21, 0xfffffbda, 0xfffff0a9,
0xffffef52, 0xfffffd0f, 0xffffe97d, 0xffffe87c,
0xfffffb1d, 0xfffffe09, 0xffffc59f, 0xffffe24f,
0xfffffe15, 0xffffff03, 0xffff8f71, 0xffffe50e,
0xffffff1d, 0xfffffd7d, 0xffff5582, 0xffffeccd,
0xffffffb7, 0xffffebf2, 0xffff3021, 0x0000208c,
0x00000049, 0xfffff3b8, 0xffff70f8, 0x00001fff,
0x000000db, 0x000008ae, 0xffffec28, 0x00001f0a,
0x00000316, 0x000041c1, 0x00006858, 0x00001ce0,
0x00001299, 0x0000660a, 0x0000e588, 0x00001356,
0x000026a6, 0x0000fa0f, 0x0000d6f4, 0x00000afd,
0x00003c18, 0x00007c09, 0x0000b780, 0x000001e0,
0x0000798e, 0x00007d05, 0x00007a9e, 0x00000040,
0x00008368, 0xffffff03, 0x00004706, 0x00000032,
0x000008ad, 0xffffec27, 0x00001eec, 0x00000024,
0xffffb4ba, 0xffffc8c6, 0x00000649, 0x00000011,
0xffff82c7, 0xffffb5c9, 0x000002cc, 0xffffffcf,
0xffff7bd4, 0xffffc15e, 0x00000147, 0xffffff3d,
0xffff8f6f, 0xffffe4ef, 0xffffffc2, 0xfffffe20,
0xffffad37, 0xfffffc13, 0xfffffd39, 0xfffffc11,
0xffffd5ca, 0xfffffe09, 0xfffff17e, 0xfffffa86,
0xffffeed5, 0xfffffe07, 0xffffd8b8, 0xfffffa40,
0xfffffacf, 0xfffffe05, 0xffffad39, 0xfffffc32,
0xfffffe00, 0xfffffb88, 0xffff79d1, 0xffffff24,
0xffffff2d, 0xffffe430, 0xffff5503, 0x00000716,
0x0000003a, 0xffffc14a, 0xffff744c, 0x000006e2,
0x00000147, 0xffffb4bb, 0xffffc8c7, 0x00000667,
0x000004c5, 0xffffc644, 0x00004442, 0x0000057a,
0x00001bfd, 0xffffe9d9, 0x0000c0bd, 0x0000037f,
0x00003c18, 0x00007c09, 0x0000b780, 0x000001e0,
0x000063ab, 0x0000fc07, 0x0000a283, 0x0000006e,
};
const unsigned kExpectedCount_NEON_sdot_4S = 361;
#endif // VIXL_SIM_SDOT_4S_TRACE_AARCH64_H_
| 10,469 |
2,816 |
<filename>third_party/snowball/src_c/stem_UTF_8_spanish.cpp
/* Generated by Snowball 2.0.0 - https://snowballstem.org/ */
#include "../runtime/header.h"
#ifdef __cplusplus
extern "C" {
#endif
extern int spanish_UTF_8_stem(struct SN_env * z);
#ifdef __cplusplus
}
#endif
static int r_residual_suffix(struct SN_env * z);
static int r_verb_suffix(struct SN_env * z);
static int r_y_verb_suffix(struct SN_env * z);
static int r_standard_suffix(struct SN_env * z);
static int r_attached_pronoun(struct SN_env * z);
static int r_R2(struct SN_env * z);
static int r_R1(struct SN_env * z);
static int r_RV(struct SN_env * z);
static int r_mark_regions(struct SN_env * z);
static int r_postlude(struct SN_env * z);
#ifdef __cplusplus
extern "C" {
#endif
extern struct SN_env * spanish_UTF_8_create_env(void);
extern void spanish_UTF_8_close_env(struct SN_env * z);
#ifdef __cplusplus
}
#endif
static const symbol s_0_1[2] = { 0xC3, 0xA1 };
static const symbol s_0_2[2] = { 0xC3, 0xA9 };
static const symbol s_0_3[2] = { 0xC3, 0xAD };
static const symbol s_0_4[2] = { 0xC3, 0xB3 };
static const symbol s_0_5[2] = { 0xC3, 0xBA };
static const struct among a_0[6] =
{
{ 0, 0, -1, 6, 0},
{ 2, s_0_1, 0, 1, 0},
{ 2, s_0_2, 0, 2, 0},
{ 2, s_0_3, 0, 3, 0},
{ 2, s_0_4, 0, 4, 0},
{ 2, s_0_5, 0, 5, 0}
};
static const symbol s_1_0[2] = { 'l', 'a' };
static const symbol s_1_1[4] = { 's', 'e', 'l', 'a' };
static const symbol s_1_2[2] = { 'l', 'e' };
static const symbol s_1_3[2] = { 'm', 'e' };
static const symbol s_1_4[2] = { 's', 'e' };
static const symbol s_1_5[2] = { 'l', 'o' };
static const symbol s_1_6[4] = { 's', 'e', 'l', 'o' };
static const symbol s_1_7[3] = { 'l', 'a', 's' };
static const symbol s_1_8[5] = { 's', 'e', 'l', 'a', 's' };
static const symbol s_1_9[3] = { 'l', 'e', 's' };
static const symbol s_1_10[3] = { 'l', 'o', 's' };
static const symbol s_1_11[5] = { 's', 'e', 'l', 'o', 's' };
static const symbol s_1_12[3] = { 'n', 'o', 's' };
static const struct among a_1[13] =
{
{ 2, s_1_0, -1, -1, 0},
{ 4, s_1_1, 0, -1, 0},
{ 2, s_1_2, -1, -1, 0},
{ 2, s_1_3, -1, -1, 0},
{ 2, s_1_4, -1, -1, 0},
{ 2, s_1_5, -1, -1, 0},
{ 4, s_1_6, 5, -1, 0},
{ 3, s_1_7, -1, -1, 0},
{ 5, s_1_8, 7, -1, 0},
{ 3, s_1_9, -1, -1, 0},
{ 3, s_1_10, -1, -1, 0},
{ 5, s_1_11, 10, -1, 0},
{ 3, s_1_12, -1, -1, 0}
};
static const symbol s_2_0[4] = { 'a', 'n', 'd', 'o' };
static const symbol s_2_1[5] = { 'i', 'e', 'n', 'd', 'o' };
static const symbol s_2_2[5] = { 'y', 'e', 'n', 'd', 'o' };
static const symbol s_2_3[5] = { 0xC3, 0xA1, 'n', 'd', 'o' };
static const symbol s_2_4[6] = { 'i', 0xC3, 0xA9, 'n', 'd', 'o' };
static const symbol s_2_5[2] = { 'a', 'r' };
static const symbol s_2_6[2] = { 'e', 'r' };
static const symbol s_2_7[2] = { 'i', 'r' };
static const symbol s_2_8[3] = { 0xC3, 0xA1, 'r' };
static const symbol s_2_9[3] = { 0xC3, 0xA9, 'r' };
static const symbol s_2_10[3] = { 0xC3, 0xAD, 'r' };
static const struct among a_2[11] =
{
{ 4, s_2_0, -1, 6, 0},
{ 5, s_2_1, -1, 6, 0},
{ 5, s_2_2, -1, 7, 0},
{ 5, s_2_3, -1, 2, 0},
{ 6, s_2_4, -1, 1, 0},
{ 2, s_2_5, -1, 6, 0},
{ 2, s_2_6, -1, 6, 0},
{ 2, s_2_7, -1, 6, 0},
{ 3, s_2_8, -1, 3, 0},
{ 3, s_2_9, -1, 4, 0},
{ 3, s_2_10, -1, 5, 0}
};
static const symbol s_3_0[2] = { 'i', 'c' };
static const symbol s_3_1[2] = { 'a', 'd' };
static const symbol s_3_2[2] = { 'o', 's' };
static const symbol s_3_3[2] = { 'i', 'v' };
static const struct among a_3[4] =
{
{ 2, s_3_0, -1, -1, 0},
{ 2, s_3_1, -1, -1, 0},
{ 2, s_3_2, -1, -1, 0},
{ 2, s_3_3, -1, 1, 0}
};
static const symbol s_4_0[4] = { 'a', 'b', 'l', 'e' };
static const symbol s_4_1[4] = { 'i', 'b', 'l', 'e' };
static const symbol s_4_2[4] = { 'a', 'n', 't', 'e' };
static const struct among a_4[3] =
{
{ 4, s_4_0, -1, 1, 0},
{ 4, s_4_1, -1, 1, 0},
{ 4, s_4_2, -1, 1, 0}
};
static const symbol s_5_0[2] = { 'i', 'c' };
static const symbol s_5_1[4] = { 'a', 'b', 'i', 'l' };
static const symbol s_5_2[2] = { 'i', 'v' };
static const struct among a_5[3] =
{
{ 2, s_5_0, -1, 1, 0},
{ 4, s_5_1, -1, 1, 0},
{ 2, s_5_2, -1, 1, 0}
};
static const symbol s_6_0[3] = { 'i', 'c', 'a' };
static const symbol s_6_1[5] = { 'a', 'n', 'c', 'i', 'a' };
static const symbol s_6_2[5] = { 'e', 'n', 'c', 'i', 'a' };
static const symbol s_6_3[5] = { 'a', 'd', 'o', 'r', 'a' };
static const symbol s_6_4[3] = { 'o', 's', 'a' };
static const symbol s_6_5[4] = { 'i', 's', 't', 'a' };
static const symbol s_6_6[3] = { 'i', 'v', 'a' };
static const symbol s_6_7[4] = { 'a', 'n', 'z', 'a' };
static const symbol s_6_8[6] = { 'l', 'o', 'g', 0xC3, 0xAD, 'a' };
static const symbol s_6_9[4] = { 'i', 'd', 'a', 'd' };
static const symbol s_6_10[4] = { 'a', 'b', 'l', 'e' };
static const symbol s_6_11[4] = { 'i', 'b', 'l', 'e' };
static const symbol s_6_12[4] = { 'a', 'n', 't', 'e' };
static const symbol s_6_13[5] = { 'm', 'e', 'n', 't', 'e' };
static const symbol s_6_14[6] = { 'a', 'm', 'e', 'n', 't', 'e' };
static const symbol s_6_15[6] = { 'a', 'c', 'i', 0xC3, 0xB3, 'n' };
static const symbol s_6_16[6] = { 'u', 'c', 'i', 0xC3, 0xB3, 'n' };
static const symbol s_6_17[3] = { 'i', 'c', 'o' };
static const symbol s_6_18[4] = { 'i', 's', 'm', 'o' };
static const symbol s_6_19[3] = { 'o', 's', 'o' };
static const symbol s_6_20[7] = { 'a', 'm', 'i', 'e', 'n', 't', 'o' };
static const symbol s_6_21[7] = { 'i', 'm', 'i', 'e', 'n', 't', 'o' };
static const symbol s_6_22[3] = { 'i', 'v', 'o' };
static const symbol s_6_23[4] = { 'a', 'd', 'o', 'r' };
static const symbol s_6_24[4] = { 'i', 'c', 'a', 's' };
static const symbol s_6_25[6] = { 'a', 'n', 'c', 'i', 'a', 's' };
static const symbol s_6_26[6] = { 'e', 'n', 'c', 'i', 'a', 's' };
static const symbol s_6_27[6] = { 'a', 'd', 'o', 'r', 'a', 's' };
static const symbol s_6_28[4] = { 'o', 's', 'a', 's' };
static const symbol s_6_29[5] = { 'i', 's', 't', 'a', 's' };
static const symbol s_6_30[4] = { 'i', 'v', 'a', 's' };
static const symbol s_6_31[5] = { 'a', 'n', 'z', 'a', 's' };
static const symbol s_6_32[7] = { 'l', 'o', 'g', 0xC3, 0xAD, 'a', 's' };
static const symbol s_6_33[6] = { 'i', 'd', 'a', 'd', 'e', 's' };
static const symbol s_6_34[5] = { 'a', 'b', 'l', 'e', 's' };
static const symbol s_6_35[5] = { 'i', 'b', 'l', 'e', 's' };
static const symbol s_6_36[7] = { 'a', 'c', 'i', 'o', 'n', 'e', 's' };
static const symbol s_6_37[7] = { 'u', 'c', 'i', 'o', 'n', 'e', 's' };
static const symbol s_6_38[6] = { 'a', 'd', 'o', 'r', 'e', 's' };
static const symbol s_6_39[5] = { 'a', 'n', 't', 'e', 's' };
static const symbol s_6_40[4] = { 'i', 'c', 'o', 's' };
static const symbol s_6_41[5] = { 'i', 's', 'm', 'o', 's' };
static const symbol s_6_42[4] = { 'o', 's', 'o', 's' };
static const symbol s_6_43[8] = { 'a', 'm', 'i', 'e', 'n', 't', 'o', 's' };
static const symbol s_6_44[8] = { 'i', 'm', 'i', 'e', 'n', 't', 'o', 's' };
static const symbol s_6_45[4] = { 'i', 'v', 'o', 's' };
static const struct among a_6[46] =
{
{ 3, s_6_0, -1, 1, 0},
{ 5, s_6_1, -1, 2, 0},
{ 5, s_6_2, -1, 5, 0},
{ 5, s_6_3, -1, 2, 0},
{ 3, s_6_4, -1, 1, 0},
{ 4, s_6_5, -1, 1, 0},
{ 3, s_6_6, -1, 9, 0},
{ 4, s_6_7, -1, 1, 0},
{ 6, s_6_8, -1, 3, 0},
{ 4, s_6_9, -1, 8, 0},
{ 4, s_6_10, -1, 1, 0},
{ 4, s_6_11, -1, 1, 0},
{ 4, s_6_12, -1, 2, 0},
{ 5, s_6_13, -1, 7, 0},
{ 6, s_6_14, 13, 6, 0},
{ 6, s_6_15, -1, 2, 0},
{ 6, s_6_16, -1, 4, 0},
{ 3, s_6_17, -1, 1, 0},
{ 4, s_6_18, -1, 1, 0},
{ 3, s_6_19, -1, 1, 0},
{ 7, s_6_20, -1, 1, 0},
{ 7, s_6_21, -1, 1, 0},
{ 3, s_6_22, -1, 9, 0},
{ 4, s_6_23, -1, 2, 0},
{ 4, s_6_24, -1, 1, 0},
{ 6, s_6_25, -1, 2, 0},
{ 6, s_6_26, -1, 5, 0},
{ 6, s_6_27, -1, 2, 0},
{ 4, s_6_28, -1, 1, 0},
{ 5, s_6_29, -1, 1, 0},
{ 4, s_6_30, -1, 9, 0},
{ 5, s_6_31, -1, 1, 0},
{ 7, s_6_32, -1, 3, 0},
{ 6, s_6_33, -1, 8, 0},
{ 5, s_6_34, -1, 1, 0},
{ 5, s_6_35, -1, 1, 0},
{ 7, s_6_36, -1, 2, 0},
{ 7, s_6_37, -1, 4, 0},
{ 6, s_6_38, -1, 2, 0},
{ 5, s_6_39, -1, 2, 0},
{ 4, s_6_40, -1, 1, 0},
{ 5, s_6_41, -1, 1, 0},
{ 4, s_6_42, -1, 1, 0},
{ 8, s_6_43, -1, 1, 0},
{ 8, s_6_44, -1, 1, 0},
{ 4, s_6_45, -1, 9, 0}
};
static const symbol s_7_0[2] = { 'y', 'a' };
static const symbol s_7_1[2] = { 'y', 'e' };
static const symbol s_7_2[3] = { 'y', 'a', 'n' };
static const symbol s_7_3[3] = { 'y', 'e', 'n' };
static const symbol s_7_4[5] = { 'y', 'e', 'r', 'o', 'n' };
static const symbol s_7_5[5] = { 'y', 'e', 'n', 'd', 'o' };
static const symbol s_7_6[2] = { 'y', 'o' };
static const symbol s_7_7[3] = { 'y', 'a', 's' };
static const symbol s_7_8[3] = { 'y', 'e', 's' };
static const symbol s_7_9[4] = { 'y', 'a', 'i', 's' };
static const symbol s_7_10[5] = { 'y', 'a', 'm', 'o', 's' };
static const symbol s_7_11[3] = { 'y', 0xC3, 0xB3 };
static const struct among a_7[12] =
{
{ 2, s_7_0, -1, 1, 0},
{ 2, s_7_1, -1, 1, 0},
{ 3, s_7_2, -1, 1, 0},
{ 3, s_7_3, -1, 1, 0},
{ 5, s_7_4, -1, 1, 0},
{ 5, s_7_5, -1, 1, 0},
{ 2, s_7_6, -1, 1, 0},
{ 3, s_7_7, -1, 1, 0},
{ 3, s_7_8, -1, 1, 0},
{ 4, s_7_9, -1, 1, 0},
{ 5, s_7_10, -1, 1, 0},
{ 3, s_7_11, -1, 1, 0}
};
static const symbol s_8_0[3] = { 'a', 'b', 'a' };
static const symbol s_8_1[3] = { 'a', 'd', 'a' };
static const symbol s_8_2[3] = { 'i', 'd', 'a' };
static const symbol s_8_3[3] = { 'a', 'r', 'a' };
static const symbol s_8_4[4] = { 'i', 'e', 'r', 'a' };
static const symbol s_8_5[3] = { 0xC3, 0xAD, 'a' };
static const symbol s_8_6[5] = { 'a', 'r', 0xC3, 0xAD, 'a' };
static const symbol s_8_7[5] = { 'e', 'r', 0xC3, 0xAD, 'a' };
static const symbol s_8_8[5] = { 'i', 'r', 0xC3, 0xAD, 'a' };
static const symbol s_8_9[2] = { 'a', 'd' };
static const symbol s_8_10[2] = { 'e', 'd' };
static const symbol s_8_11[2] = { 'i', 'd' };
static const symbol s_8_12[3] = { 'a', 's', 'e' };
static const symbol s_8_13[4] = { 'i', 'e', 's', 'e' };
static const symbol s_8_14[4] = { 'a', 's', 't', 'e' };
static const symbol s_8_15[4] = { 'i', 's', 't', 'e' };
static const symbol s_8_16[2] = { 'a', 'n' };
static const symbol s_8_17[4] = { 'a', 'b', 'a', 'n' };
static const symbol s_8_18[4] = { 'a', 'r', 'a', 'n' };
static const symbol s_8_19[5] = { 'i', 'e', 'r', 'a', 'n' };
static const symbol s_8_20[4] = { 0xC3, 0xAD, 'a', 'n' };
static const symbol s_8_21[6] = { 'a', 'r', 0xC3, 0xAD, 'a', 'n' };
static const symbol s_8_22[6] = { 'e', 'r', 0xC3, 0xAD, 'a', 'n' };
static const symbol s_8_23[6] = { 'i', 'r', 0xC3, 0xAD, 'a', 'n' };
static const symbol s_8_24[2] = { 'e', 'n' };
static const symbol s_8_25[4] = { 'a', 's', 'e', 'n' };
static const symbol s_8_26[5] = { 'i', 'e', 's', 'e', 'n' };
static const symbol s_8_27[4] = { 'a', 'r', 'o', 'n' };
static const symbol s_8_28[5] = { 'i', 'e', 'r', 'o', 'n' };
static const symbol s_8_29[5] = { 'a', 'r', 0xC3, 0xA1, 'n' };
static const symbol s_8_30[5] = { 'e', 'r', 0xC3, 0xA1, 'n' };
static const symbol s_8_31[5] = { 'i', 'r', 0xC3, 0xA1, 'n' };
static const symbol s_8_32[3] = { 'a', 'd', 'o' };
static const symbol s_8_33[3] = { 'i', 'd', 'o' };
static const symbol s_8_34[4] = { 'a', 'n', 'd', 'o' };
static const symbol s_8_35[5] = { 'i', 'e', 'n', 'd', 'o' };
static const symbol s_8_36[2] = { 'a', 'r' };
static const symbol s_8_37[2] = { 'e', 'r' };
static const symbol s_8_38[2] = { 'i', 'r' };
static const symbol s_8_39[2] = { 'a', 's' };
static const symbol s_8_40[4] = { 'a', 'b', 'a', 's' };
static const symbol s_8_41[4] = { 'a', 'd', 'a', 's' };
static const symbol s_8_42[4] = { 'i', 'd', 'a', 's' };
static const symbol s_8_43[4] = { 'a', 'r', 'a', 's' };
static const symbol s_8_44[5] = { 'i', 'e', 'r', 'a', 's' };
static const symbol s_8_45[4] = { 0xC3, 0xAD, 'a', 's' };
static const symbol s_8_46[6] = { 'a', 'r', 0xC3, 0xAD, 'a', 's' };
static const symbol s_8_47[6] = { 'e', 'r', 0xC3, 0xAD, 'a', 's' };
static const symbol s_8_48[6] = { 'i', 'r', 0xC3, 0xAD, 'a', 's' };
static const symbol s_8_49[2] = { 'e', 's' };
static const symbol s_8_50[4] = { 'a', 's', 'e', 's' };
static const symbol s_8_51[5] = { 'i', 'e', 's', 'e', 's' };
static const symbol s_8_52[5] = { 'a', 'b', 'a', 'i', 's' };
static const symbol s_8_53[5] = { 'a', 'r', 'a', 'i', 's' };
static const symbol s_8_54[6] = { 'i', 'e', 'r', 'a', 'i', 's' };
static const symbol s_8_55[5] = { 0xC3, 0xAD, 'a', 'i', 's' };
static const symbol s_8_56[7] = { 'a', 'r', 0xC3, 0xAD, 'a', 'i', 's' };
static const symbol s_8_57[7] = { 'e', 'r', 0xC3, 0xAD, 'a', 'i', 's' };
static const symbol s_8_58[7] = { 'i', 'r', 0xC3, 0xAD, 'a', 'i', 's' };
static const symbol s_8_59[5] = { 'a', 's', 'e', 'i', 's' };
static const symbol s_8_60[6] = { 'i', 'e', 's', 'e', 'i', 's' };
static const symbol s_8_61[6] = { 'a', 's', 't', 'e', 'i', 's' };
static const symbol s_8_62[6] = { 'i', 's', 't', 'e', 'i', 's' };
static const symbol s_8_63[4] = { 0xC3, 0xA1, 'i', 's' };
static const symbol s_8_64[4] = { 0xC3, 0xA9, 'i', 's' };
static const symbol s_8_65[6] = { 'a', 'r', 0xC3, 0xA9, 'i', 's' };
static const symbol s_8_66[6] = { 'e', 'r', 0xC3, 0xA9, 'i', 's' };
static const symbol s_8_67[6] = { 'i', 'r', 0xC3, 0xA9, 'i', 's' };
static const symbol s_8_68[4] = { 'a', 'd', 'o', 's' };
static const symbol s_8_69[4] = { 'i', 'd', 'o', 's' };
static const symbol s_8_70[4] = { 'a', 'm', 'o', 's' };
static const symbol s_8_71[7] = { 0xC3, 0xA1, 'b', 'a', 'm', 'o', 's' };
static const symbol s_8_72[7] = { 0xC3, 0xA1, 'r', 'a', 'm', 'o', 's' };
static const symbol s_8_73[8] = { 'i', 0xC3, 0xA9, 'r', 'a', 'm', 'o', 's' };
static const symbol s_8_74[6] = { 0xC3, 0xAD, 'a', 'm', 'o', 's' };
static const symbol s_8_75[8] = { 'a', 'r', 0xC3, 0xAD, 'a', 'm', 'o', 's' };
static const symbol s_8_76[8] = { 'e', 'r', 0xC3, 0xAD, 'a', 'm', 'o', 's' };
static const symbol s_8_77[8] = { 'i', 'r', 0xC3, 0xAD, 'a', 'm', 'o', 's' };
static const symbol s_8_78[4] = { 'e', 'm', 'o', 's' };
static const symbol s_8_79[6] = { 'a', 'r', 'e', 'm', 'o', 's' };
static const symbol s_8_80[6] = { 'e', 'r', 'e', 'm', 'o', 's' };
static const symbol s_8_81[6] = { 'i', 'r', 'e', 'm', 'o', 's' };
static const symbol s_8_82[7] = { 0xC3, 0xA1, 's', 'e', 'm', 'o', 's' };
static const symbol s_8_83[8] = { 'i', 0xC3, 0xA9, 's', 'e', 'm', 'o', 's' };
static const symbol s_8_84[4] = { 'i', 'm', 'o', 's' };
static const symbol s_8_85[5] = { 'a', 'r', 0xC3, 0xA1, 's' };
static const symbol s_8_86[5] = { 'e', 'r', 0xC3, 0xA1, 's' };
static const symbol s_8_87[5] = { 'i', 'r', 0xC3, 0xA1, 's' };
static const symbol s_8_88[3] = { 0xC3, 0xAD, 's' };
static const symbol s_8_89[4] = { 'a', 'r', 0xC3, 0xA1 };
static const symbol s_8_90[4] = { 'e', 'r', 0xC3, 0xA1 };
static const symbol s_8_91[4] = { 'i', 'r', 0xC3, 0xA1 };
static const symbol s_8_92[4] = { 'a', 'r', 0xC3, 0xA9 };
static const symbol s_8_93[4] = { 'e', 'r', 0xC3, 0xA9 };
static const symbol s_8_94[4] = { 'i', 'r', 0xC3, 0xA9 };
static const symbol s_8_95[3] = { 'i', 0xC3, 0xB3 };
static const struct among a_8[96] =
{
{ 3, s_8_0, -1, 2, 0},
{ 3, s_8_1, -1, 2, 0},
{ 3, s_8_2, -1, 2, 0},
{ 3, s_8_3, -1, 2, 0},
{ 4, s_8_4, -1, 2, 0},
{ 3, s_8_5, -1, 2, 0},
{ 5, s_8_6, 5, 2, 0},
{ 5, s_8_7, 5, 2, 0},
{ 5, s_8_8, 5, 2, 0},
{ 2, s_8_9, -1, 2, 0},
{ 2, s_8_10, -1, 2, 0},
{ 2, s_8_11, -1, 2, 0},
{ 3, s_8_12, -1, 2, 0},
{ 4, s_8_13, -1, 2, 0},
{ 4, s_8_14, -1, 2, 0},
{ 4, s_8_15, -1, 2, 0},
{ 2, s_8_16, -1, 2, 0},
{ 4, s_8_17, 16, 2, 0},
{ 4, s_8_18, 16, 2, 0},
{ 5, s_8_19, 16, 2, 0},
{ 4, s_8_20, 16, 2, 0},
{ 6, s_8_21, 20, 2, 0},
{ 6, s_8_22, 20, 2, 0},
{ 6, s_8_23, 20, 2, 0},
{ 2, s_8_24, -1, 1, 0},
{ 4, s_8_25, 24, 2, 0},
{ 5, s_8_26, 24, 2, 0},
{ 4, s_8_27, -1, 2, 0},
{ 5, s_8_28, -1, 2, 0},
{ 5, s_8_29, -1, 2, 0},
{ 5, s_8_30, -1, 2, 0},
{ 5, s_8_31, -1, 2, 0},
{ 3, s_8_32, -1, 2, 0},
{ 3, s_8_33, -1, 2, 0},
{ 4, s_8_34, -1, 2, 0},
{ 5, s_8_35, -1, 2, 0},
{ 2, s_8_36, -1, 2, 0},
{ 2, s_8_37, -1, 2, 0},
{ 2, s_8_38, -1, 2, 0},
{ 2, s_8_39, -1, 2, 0},
{ 4, s_8_40, 39, 2, 0},
{ 4, s_8_41, 39, 2, 0},
{ 4, s_8_42, 39, 2, 0},
{ 4, s_8_43, 39, 2, 0},
{ 5, s_8_44, 39, 2, 0},
{ 4, s_8_45, 39, 2, 0},
{ 6, s_8_46, 45, 2, 0},
{ 6, s_8_47, 45, 2, 0},
{ 6, s_8_48, 45, 2, 0},
{ 2, s_8_49, -1, 1, 0},
{ 4, s_8_50, 49, 2, 0},
{ 5, s_8_51, 49, 2, 0},
{ 5, s_8_52, -1, 2, 0},
{ 5, s_8_53, -1, 2, 0},
{ 6, s_8_54, -1, 2, 0},
{ 5, s_8_55, -1, 2, 0},
{ 7, s_8_56, 55, 2, 0},
{ 7, s_8_57, 55, 2, 0},
{ 7, s_8_58, 55, 2, 0},
{ 5, s_8_59, -1, 2, 0},
{ 6, s_8_60, -1, 2, 0},
{ 6, s_8_61, -1, 2, 0},
{ 6, s_8_62, -1, 2, 0},
{ 4, s_8_63, -1, 2, 0},
{ 4, s_8_64, -1, 1, 0},
{ 6, s_8_65, 64, 2, 0},
{ 6, s_8_66, 64, 2, 0},
{ 6, s_8_67, 64, 2, 0},
{ 4, s_8_68, -1, 2, 0},
{ 4, s_8_69, -1, 2, 0},
{ 4, s_8_70, -1, 2, 0},
{ 7, s_8_71, 70, 2, 0},
{ 7, s_8_72, 70, 2, 0},
{ 8, s_8_73, 70, 2, 0},
{ 6, s_8_74, 70, 2, 0},
{ 8, s_8_75, 74, 2, 0},
{ 8, s_8_76, 74, 2, 0},
{ 8, s_8_77, 74, 2, 0},
{ 4, s_8_78, -1, 1, 0},
{ 6, s_8_79, 78, 2, 0},
{ 6, s_8_80, 78, 2, 0},
{ 6, s_8_81, 78, 2, 0},
{ 7, s_8_82, 78, 2, 0},
{ 8, s_8_83, 78, 2, 0},
{ 4, s_8_84, -1, 2, 0},
{ 5, s_8_85, -1, 2, 0},
{ 5, s_8_86, -1, 2, 0},
{ 5, s_8_87, -1, 2, 0},
{ 3, s_8_88, -1, 2, 0},
{ 4, s_8_89, -1, 2, 0},
{ 4, s_8_90, -1, 2, 0},
{ 4, s_8_91, -1, 2, 0},
{ 4, s_8_92, -1, 2, 0},
{ 4, s_8_93, -1, 2, 0},
{ 4, s_8_94, -1, 2, 0},
{ 3, s_8_95, -1, 2, 0}
};
static const symbol s_9_0[1] = { 'a' };
static const symbol s_9_1[1] = { 'e' };
static const symbol s_9_2[1] = { 'o' };
static const symbol s_9_3[2] = { 'o', 's' };
static const symbol s_9_4[2] = { 0xC3, 0xA1 };
static const symbol s_9_5[2] = { 0xC3, 0xA9 };
static const symbol s_9_6[2] = { 0xC3, 0xAD };
static const symbol s_9_7[2] = { 0xC3, 0xB3 };
static const struct among a_9[8] =
{
{ 1, s_9_0, -1, 1, 0},
{ 1, s_9_1, -1, 2, 0},
{ 1, s_9_2, -1, 1, 0},
{ 2, s_9_3, -1, 1, 0},
{ 2, s_9_4, -1, 1, 0},
{ 2, s_9_5, -1, 2, 0},
{ 2, s_9_6, -1, 1, 0},
{ 2, s_9_7, -1, 1, 0}
};
static const unsigned char g_v[] = { 17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 17, 4, 10 };
static const symbol s_0[] = { 'a' };
static const symbol s_1[] = { 'e' };
static const symbol s_2[] = { 'i' };
static const symbol s_3[] = { 'o' };
static const symbol s_4[] = { 'u' };
static const symbol s_5[] = { 'i', 'e', 'n', 'd', 'o' };
static const symbol s_6[] = { 'a', 'n', 'd', 'o' };
static const symbol s_7[] = { 'a', 'r' };
static const symbol s_8[] = { 'e', 'r' };
static const symbol s_9[] = { 'i', 'r' };
static const symbol s_10[] = { 'i', 'c' };
static const symbol s_11[] = { 'l', 'o', 'g' };
static const symbol s_12[] = { 'u' };
static const symbol s_13[] = { 'e', 'n', 't', 'e' };
static const symbol s_14[] = { 'a', 't' };
static const symbol s_15[] = { 'a', 't' };
static int r_mark_regions(struct SN_env * z) {
z->I[2] = z->l;
z->I[1] = z->l;
z->I[0] = z->l;
{ int c1 = z->c;
{ int c2 = z->c;
if (in_grouping_U(z, g_v, 97, 252, 0)) goto lab2;
{ int c3 = z->c;
if (out_grouping_U(z, g_v, 97, 252, 0)) goto lab4;
{
int ret = out_grouping_U(z, g_v, 97, 252, 1);
if (ret < 0) goto lab4;
z->c += ret;
}
goto lab3;
lab4:
z->c = c3;
if (in_grouping_U(z, g_v, 97, 252, 0)) goto lab2;
{
int ret = in_grouping_U(z, g_v, 97, 252, 1);
if (ret < 0) goto lab2;
z->c += ret;
}
}
lab3:
goto lab1;
lab2:
z->c = c2;
if (out_grouping_U(z, g_v, 97, 252, 0)) goto lab0;
{ int c4 = z->c;
if (out_grouping_U(z, g_v, 97, 252, 0)) goto lab6;
{
int ret = out_grouping_U(z, g_v, 97, 252, 1);
if (ret < 0) goto lab6;
z->c += ret;
}
goto lab5;
lab6:
z->c = c4;
if (in_grouping_U(z, g_v, 97, 252, 0)) goto lab0;
{ int ret = skip_utf8(z->p, z->c, 0, z->l, 1);
if (ret < 0) goto lab0;
z->c = ret;
}
}
lab5:
;
}
lab1:
z->I[2] = z->c;
lab0:
z->c = c1;
}
{ int c5 = z->c;
{
int ret = out_grouping_U(z, g_v, 97, 252, 1);
if (ret < 0) goto lab7;
z->c += ret;
}
{
int ret = in_grouping_U(z, g_v, 97, 252, 1);
if (ret < 0) goto lab7;
z->c += ret;
}
z->I[1] = z->c;
{
int ret = out_grouping_U(z, g_v, 97, 252, 1);
if (ret < 0) goto lab7;
z->c += ret;
}
{
int ret = in_grouping_U(z, g_v, 97, 252, 1);
if (ret < 0) goto lab7;
z->c += ret;
}
z->I[0] = z->c;
lab7:
z->c = c5;
}
return 1;
}
static int r_postlude(struct SN_env * z) {
int among_var;
while(1) {
int c1 = z->c;
z->bra = z->c;
if (z->c + 1 >= z->l || z->p[z->c + 1] >> 5 != 5 || !((67641858 >> (z->p[z->c + 1] & 0x1f)) & 1)) among_var = 6; else
among_var = find_among(z, a_0, 6);
if (!(among_var)) goto lab0;
z->ket = z->c;
switch (among_var) {
case 1:
{ int ret = slice_from_s(z, 1, s_0);
if (ret < 0) return ret;
}
break;
case 2:
{ int ret = slice_from_s(z, 1, s_1);
if (ret < 0) return ret;
}
break;
case 3:
{ int ret = slice_from_s(z, 1, s_2);
if (ret < 0) return ret;
}
break;
case 4:
{ int ret = slice_from_s(z, 1, s_3);
if (ret < 0) return ret;
}
break;
case 5:
{ int ret = slice_from_s(z, 1, s_4);
if (ret < 0) return ret;
}
break;
case 6:
{ int ret = skip_utf8(z->p, z->c, 0, z->l, 1);
if (ret < 0) goto lab0;
z->c = ret;
}
break;
}
continue;
lab0:
z->c = c1;
break;
}
return 1;
}
static int r_RV(struct SN_env * z) {
if (!(z->I[2] <= z->c)) return 0;
return 1;
}
static int r_R1(struct SN_env * z) {
if (!(z->I[1] <= z->c)) return 0;
return 1;
}
static int r_R2(struct SN_env * z) {
if (!(z->I[0] <= z->c)) return 0;
return 1;
}
static int r_attached_pronoun(struct SN_env * z) {
int among_var;
z->ket = z->c;
if (z->c - 1 <= z->lb || z->p[z->c - 1] >> 5 != 3 || !((557090 >> (z->p[z->c - 1] & 0x1f)) & 1)) return 0;
if (!(find_among_b(z, a_1, 13))) return 0;
z->bra = z->c;
if (z->c - 1 <= z->lb || (z->p[z->c - 1] != 111 && z->p[z->c - 1] != 114)) return 0;
among_var = find_among_b(z, a_2, 11);
if (!(among_var)) return 0;
{ int ret = r_RV(z);
if (ret <= 0) return ret;
}
switch (among_var) {
case 1:
z->bra = z->c;
{ int ret = slice_from_s(z, 5, s_5);
if (ret < 0) return ret;
}
break;
case 2:
z->bra = z->c;
{ int ret = slice_from_s(z, 4, s_6);
if (ret < 0) return ret;
}
break;
case 3:
z->bra = z->c;
{ int ret = slice_from_s(z, 2, s_7);
if (ret < 0) return ret;
}
break;
case 4:
z->bra = z->c;
{ int ret = slice_from_s(z, 2, s_8);
if (ret < 0) return ret;
}
break;
case 5:
z->bra = z->c;
{ int ret = slice_from_s(z, 2, s_9);
if (ret < 0) return ret;
}
break;
case 6:
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
break;
case 7:
if (z->c <= z->lb || z->p[z->c - 1] != 'u') return 0;
z->c--;
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
break;
}
return 1;
}
static int r_standard_suffix(struct SN_env * z) {
int among_var;
z->ket = z->c;
if (z->c - 2 <= z->lb || z->p[z->c - 1] >> 5 != 3 || !((835634 >> (z->p[z->c - 1] & 0x1f)) & 1)) return 0;
among_var = find_among_b(z, a_6, 46);
if (!(among_var)) return 0;
z->bra = z->c;
switch (among_var) {
case 1:
{ int ret = r_R2(z);
if (ret <= 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
break;
case 2:
{ int ret = r_R2(z);
if (ret <= 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
{ int m1 = z->l - z->c; (void)m1;
z->ket = z->c;
if (!(eq_s_b(z, 2, s_10))) { z->c = z->l - m1; goto lab0; }
z->bra = z->c;
{ int ret = r_R2(z);
if (ret == 0) { z->c = z->l - m1; goto lab0; }
if (ret < 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
lab0:
;
}
break;
case 3:
{ int ret = r_R2(z);
if (ret <= 0) return ret;
}
{ int ret = slice_from_s(z, 3, s_11);
if (ret < 0) return ret;
}
break;
case 4:
{ int ret = r_R2(z);
if (ret <= 0) return ret;
}
{ int ret = slice_from_s(z, 1, s_12);
if (ret < 0) return ret;
}
break;
case 5:
{ int ret = r_R2(z);
if (ret <= 0) return ret;
}
{ int ret = slice_from_s(z, 4, s_13);
if (ret < 0) return ret;
}
break;
case 6:
{ int ret = r_R1(z);
if (ret <= 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
{ int m2 = z->l - z->c; (void)m2;
z->ket = z->c;
if (z->c - 1 <= z->lb || z->p[z->c - 1] >> 5 != 3 || !((4718616 >> (z->p[z->c - 1] & 0x1f)) & 1)) { z->c = z->l - m2; goto lab1; }
among_var = find_among_b(z, a_3, 4);
if (!(among_var)) { z->c = z->l - m2; goto lab1; }
z->bra = z->c;
{ int ret = r_R2(z);
if (ret == 0) { z->c = z->l - m2; goto lab1; }
if (ret < 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
switch (among_var) {
case 1:
z->ket = z->c;
if (!(eq_s_b(z, 2, s_14))) { z->c = z->l - m2; goto lab1; }
z->bra = z->c;
{ int ret = r_R2(z);
if (ret == 0) { z->c = z->l - m2; goto lab1; }
if (ret < 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
break;
}
lab1:
;
}
break;
case 7:
{ int ret = r_R2(z);
if (ret <= 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
{ int m3 = z->l - z->c; (void)m3;
z->ket = z->c;
if (z->c - 3 <= z->lb || z->p[z->c - 1] != 101) { z->c = z->l - m3; goto lab2; }
if (!(find_among_b(z, a_4, 3))) { z->c = z->l - m3; goto lab2; }
z->bra = z->c;
{ int ret = r_R2(z);
if (ret == 0) { z->c = z->l - m3; goto lab2; }
if (ret < 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
lab2:
;
}
break;
case 8:
{ int ret = r_R2(z);
if (ret <= 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
{ int m4 = z->l - z->c; (void)m4;
z->ket = z->c;
if (z->c - 1 <= z->lb || z->p[z->c - 1] >> 5 != 3 || !((4198408 >> (z->p[z->c - 1] & 0x1f)) & 1)) { z->c = z->l - m4; goto lab3; }
if (!(find_among_b(z, a_5, 3))) { z->c = z->l - m4; goto lab3; }
z->bra = z->c;
{ int ret = r_R2(z);
if (ret == 0) { z->c = z->l - m4; goto lab3; }
if (ret < 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
lab3:
;
}
break;
case 9:
{ int ret = r_R2(z);
if (ret <= 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
{ int m5 = z->l - z->c; (void)m5;
z->ket = z->c;
if (!(eq_s_b(z, 2, s_15))) { z->c = z->l - m5; goto lab4; }
z->bra = z->c;
{ int ret = r_R2(z);
if (ret == 0) { z->c = z->l - m5; goto lab4; }
if (ret < 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
lab4:
;
}
break;
}
return 1;
}
static int r_y_verb_suffix(struct SN_env * z) {
{ int mlimit1;
if (z->c < z->I[2]) return 0;
mlimit1 = z->lb; z->lb = z->I[2];
z->ket = z->c;
if (!(find_among_b(z, a_7, 12))) { z->lb = mlimit1; return 0; }
z->bra = z->c;
z->lb = mlimit1;
}
if (z->c <= z->lb || z->p[z->c - 1] != 'u') return 0;
z->c--;
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
return 1;
}
static int r_verb_suffix(struct SN_env * z) {
int among_var;
{ int mlimit1;
if (z->c < z->I[2]) return 0;
mlimit1 = z->lb; z->lb = z->I[2];
z->ket = z->c;
among_var = find_among_b(z, a_8, 96);
if (!(among_var)) { z->lb = mlimit1; return 0; }
z->bra = z->c;
z->lb = mlimit1;
}
switch (among_var) {
case 1:
{ int m2 = z->l - z->c; (void)m2;
if (z->c <= z->lb || z->p[z->c - 1] != 'u') { z->c = z->l - m2; goto lab0; }
z->c--;
{ int m_test3 = z->l - z->c;
if (z->c <= z->lb || z->p[z->c - 1] != 'g') { z->c = z->l - m2; goto lab0; }
z->c--;
z->c = z->l - m_test3;
}
lab0:
;
}
z->bra = z->c;
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
break;
case 2:
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
break;
}
return 1;
}
static int r_residual_suffix(struct SN_env * z) {
int among_var;
z->ket = z->c;
among_var = find_among_b(z, a_9, 8);
if (!(among_var)) return 0;
z->bra = z->c;
switch (among_var) {
case 1:
{ int ret = r_RV(z);
if (ret <= 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
break;
case 2:
{ int ret = r_RV(z);
if (ret <= 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
{ int m1 = z->l - z->c; (void)m1;
z->ket = z->c;
if (z->c <= z->lb || z->p[z->c - 1] != 'u') { z->c = z->l - m1; goto lab0; }
z->c--;
z->bra = z->c;
{ int m_test2 = z->l - z->c;
if (z->c <= z->lb || z->p[z->c - 1] != 'g') { z->c = z->l - m1; goto lab0; }
z->c--;
z->c = z->l - m_test2;
}
{ int ret = r_RV(z);
if (ret == 0) { z->c = z->l - m1; goto lab0; }
if (ret < 0) return ret;
}
{ int ret = slice_del(z);
if (ret < 0) return ret;
}
lab0:
;
}
break;
}
return 1;
}
extern int spanish_UTF_8_stem(struct SN_env * z) {
{ int ret = r_mark_regions(z);
if (ret < 0) return ret;
}
z->lb = z->c; z->c = z->l;
{ int m1 = z->l - z->c; (void)m1;
{ int ret = r_attached_pronoun(z);
if (ret < 0) return ret;
}
z->c = z->l - m1;
}
{ int m2 = z->l - z->c; (void)m2;
{ int m3 = z->l - z->c; (void)m3;
{ int ret = r_standard_suffix(z);
if (ret == 0) goto lab2;
if (ret < 0) return ret;
}
goto lab1;
lab2:
z->c = z->l - m3;
{ int ret = r_y_verb_suffix(z);
if (ret == 0) goto lab3;
if (ret < 0) return ret;
}
goto lab1;
lab3:
z->c = z->l - m3;
{ int ret = r_verb_suffix(z);
if (ret == 0) goto lab0;
if (ret < 0) return ret;
}
}
lab1:
lab0:
z->c = z->l - m2;
}
{ int m4 = z->l - z->c; (void)m4;
{ int ret = r_residual_suffix(z);
if (ret < 0) return ret;
}
z->c = z->l - m4;
}
z->c = z->lb;
{ int c5 = z->c;
{ int ret = r_postlude(z);
if (ret < 0) return ret;
}
z->c = c5;
}
return 1;
}
extern struct SN_env * spanish_UTF_8_create_env(void) { return SN_create_env(0, 3); }
extern void spanish_UTF_8_close_env(struct SN_env * z) { SN_close_env(z, 0); }
| 20,932 |
6,457 |
<gh_stars>1000+
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020 Intel Corporation. All Rights Reserved.
//#cmake:add-file log-common.h
#include "log-common.h"
TEST_CASE( "Logging C++ DEBUG", "[log]" ) {
size_t n_callbacks = 0;
auto callback = [&]( rs2_log_severity severity, rs2::log_message const& msg )
{
++n_callbacks;
TRACE( severity << ' ' << msg.filename() << '+' << msg.line_number() << ": " << msg.raw() );
};
rs2::log_to_callback( RS2_LOG_SEVERITY_DEBUG, callback );
REQUIRE( !n_callbacks );
log_all();
REQUIRE( n_callbacks == 4 );
}
| 254 |
1,624 |
from openselfsup.utils import build_from_cfg
from .registry import HOOKS
def build_hook(cfg, default_args=None):
return build_from_cfg(cfg, HOOKS, default_args)
| 59 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-6x9q-xfp2-gxg6",
"modified": "2022-04-30T18:20:02Z",
"published": "2022-04-30T18:20:02Z",
"aliases": [
"CVE-2002-0852"
],
"details": "Buffer overflows in Cisco Virtual Private Network (VPN) Client 3.5.4 and earlier allows remote attackers to cause a denial of service via (1) an Internet Key Exchange (IKE) with a large Security Parameter Index (SPI) payload, or (2) an IKE packet with a large number of valid payloads.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2002-0852"
},
{
"type": "WEB",
"url": "http://www.cisco.com/warp/public/707/vpnclient-multiple-vuln-pub.shtml"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 379 |
482 |
<filename>code/framework/api/src/main/java/io/cattle/platform/api/auth/impl/OptionCallback.java
package io.cattle.platform.api.auth.impl;
public interface OptionCallback {
String getOption();
}
| 66 |
5,813 |
/*
* 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.druid.server.http;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import com.sun.jersey.spi.container.ResourceFilters;
import org.apache.druid.client.DataSourcesSnapshot;
import org.apache.druid.client.ImmutableDruidDataSource;
import org.apache.druid.guice.annotations.Json;
import org.apache.druid.indexing.overlord.IndexerMetadataStorageCoordinator;
import org.apache.druid.indexing.overlord.Segments;
import org.apache.druid.metadata.SegmentsMetadataManager;
import org.apache.druid.server.JettyUtils;
import org.apache.druid.server.http.security.DatasourceResourceFilter;
import org.apache.druid.server.security.AuthorizationUtils;
import org.apache.druid.server.security.AuthorizerMapper;
import org.apache.druid.server.security.ResourceAction;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.SegmentId;
import org.apache.druid.timeline.SegmentWithOvershadowedStatus;
import org.joda.time.Interval;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
*/
@Path("/druid/coordinator/v1/metadata")
public class MetadataResource
{
private final SegmentsMetadataManager segmentsMetadataManager;
private final IndexerMetadataStorageCoordinator metadataStorageCoordinator;
private final AuthorizerMapper authorizerMapper;
@Inject
public MetadataResource(
SegmentsMetadataManager segmentsMetadataManager,
IndexerMetadataStorageCoordinator metadataStorageCoordinator,
AuthorizerMapper authorizerMapper,
@Json ObjectMapper jsonMapper
)
{
this.segmentsMetadataManager = segmentsMetadataManager;
this.metadataStorageCoordinator = metadataStorageCoordinator;
this.authorizerMapper = authorizerMapper;
}
@GET
@Path("/datasources")
@Produces(MediaType.APPLICATION_JSON)
public Response getDataSources(
@QueryParam("full") final String full,
@Context final UriInfo uriInfo,
@Context final HttpServletRequest req
)
{
final boolean includeUnused = JettyUtils.getQueryParam(uriInfo, "includeUnused", "includeDisabled") != null;
Collection<ImmutableDruidDataSource> druidDataSources = null;
final TreeSet<String> dataSourceNamesPreAuth;
if (includeUnused) {
dataSourceNamesPreAuth = new TreeSet<>(segmentsMetadataManager.retrieveAllDataSourceNames());
} else {
druidDataSources = segmentsMetadataManager.getImmutableDataSourcesWithAllUsedSegments();
dataSourceNamesPreAuth = druidDataSources
.stream()
.map(ImmutableDruidDataSource::getName)
.collect(Collectors.toCollection(TreeSet::new));
}
final TreeSet<String> dataSourceNamesPostAuth = new TreeSet<>();
Function<String, Iterable<ResourceAction>> raGenerator = datasourceName ->
Collections.singletonList(AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(datasourceName));
Iterables.addAll(
dataSourceNamesPostAuth,
AuthorizationUtils.filterAuthorizedResources(
req,
dataSourceNamesPreAuth,
raGenerator,
authorizerMapper
)
);
// Cannot do both includeUnused and full, let includeUnused take priority
// Always use dataSourceNamesPostAuth to determine the set of returned dataSources
if (full != null && !includeUnused) {
return Response.ok().entity(
Collections2.filter(druidDataSources, dataSource -> dataSourceNamesPostAuth.contains(dataSource.getName()))
).build();
} else {
return Response.ok().entity(dataSourceNamesPostAuth).build();
}
}
@GET
@Path("/segments")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllUsedSegments(
@Context final HttpServletRequest req,
@QueryParam("datasources") final @Nullable Set<String> dataSources,
@QueryParam("includeOvershadowedStatus") final @Nullable String includeOvershadowedStatus
)
{
if (includeOvershadowedStatus != null) {
return getAllUsedSegmentsWithOvershadowedStatus(req, dataSources);
}
Collection<ImmutableDruidDataSource> dataSourcesWithUsedSegments =
segmentsMetadataManager.getImmutableDataSourcesWithAllUsedSegments();
if (dataSources != null && !dataSources.isEmpty()) {
dataSourcesWithUsedSegments = dataSourcesWithUsedSegments
.stream()
.filter(dataSourceWithUsedSegments -> dataSources.contains(dataSourceWithUsedSegments.getName()))
.collect(Collectors.toList());
}
final Stream<DataSegment> usedSegments = dataSourcesWithUsedSegments
.stream()
.flatMap(t -> t.getSegments().stream());
final Function<DataSegment, Iterable<ResourceAction>> raGenerator = segment -> Collections.singletonList(
AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSource()));
final Iterable<DataSegment> authorizedSegments =
AuthorizationUtils.filterAuthorizedResources(req, usedSegments::iterator, raGenerator, authorizerMapper);
Response.ResponseBuilder builder = Response.status(Response.Status.OK);
return builder.entity(authorizedSegments).build();
}
private Response getAllUsedSegmentsWithOvershadowedStatus(
HttpServletRequest req,
@Nullable Set<String> dataSources
)
{
DataSourcesSnapshot dataSourcesSnapshot = segmentsMetadataManager.getSnapshotOfDataSourcesWithAllUsedSegments();
Collection<ImmutableDruidDataSource> dataSourcesWithUsedSegments =
dataSourcesSnapshot.getDataSourcesWithAllUsedSegments();
if (dataSources != null && !dataSources.isEmpty()) {
dataSourcesWithUsedSegments = dataSourcesWithUsedSegments
.stream()
.filter(dataSourceWithUsedSegments -> dataSources.contains(dataSourceWithUsedSegments.getName()))
.collect(Collectors.toList());
}
final Stream<DataSegment> usedSegments = dataSourcesWithUsedSegments
.stream()
.flatMap(t -> t.getSegments().stream());
final Set<SegmentId> overshadowedSegments = dataSourcesSnapshot.getOvershadowedSegments();
final Stream<SegmentWithOvershadowedStatus> usedSegmentsWithOvershadowedStatus = usedSegments
.map(segment -> new SegmentWithOvershadowedStatus(segment, overshadowedSegments.contains(segment.getId())));
final Function<SegmentWithOvershadowedStatus, Iterable<ResourceAction>> raGenerator = segment -> Collections
.singletonList(AuthorizationUtils.DATASOURCE_READ_RA_GENERATOR.apply(segment.getDataSegment().getDataSource()));
final Iterable<SegmentWithOvershadowedStatus> authorizedSegments = AuthorizationUtils.filterAuthorizedResources(
req,
usedSegmentsWithOvershadowedStatus::iterator,
raGenerator,
authorizerMapper
);
Response.ResponseBuilder builder = Response.status(Response.Status.OK);
return builder.entity(authorizedSegments).build();
}
/**
* The difference of this method from {@link #getUsedSegmentsInDataSource} is that the latter returns only a list of
* segments, while this method also includes the properties of data source, such as the time when it was created.
*/
@GET
@Path("/datasources/{dataSourceName}")
@Produces(MediaType.APPLICATION_JSON)
@ResourceFilters(DatasourceResourceFilter.class)
public Response getDataSourceWithUsedSegments(@PathParam("dataSourceName") final String dataSourceName)
{
ImmutableDruidDataSource dataSource =
segmentsMetadataManager.getImmutableDataSourceWithUsedSegments(dataSourceName);
if (dataSource == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.status(Response.Status.OK).entity(dataSource).build();
}
@GET
@Path("/datasources/{dataSourceName}/segments")
@Produces(MediaType.APPLICATION_JSON)
@ResourceFilters(DatasourceResourceFilter.class)
public Response getUsedSegmentsInDataSource(
@PathParam("dataSourceName") String dataSourceName,
@QueryParam("full") @Nullable String full
)
{
ImmutableDruidDataSource dataSource =
segmentsMetadataManager.getImmutableDataSourceWithUsedSegments(dataSourceName);
if (dataSource == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
Response.ResponseBuilder builder = Response.status(Response.Status.OK);
if (full != null) {
return builder.entity(dataSource.getSegments()).build();
}
return builder.entity(Collections2.transform(dataSource.getSegments(), DataSegment::getId)).build();
}
/**
* This is a {@link POST} method to pass the list of intervals in the body,
* see https://github.com/apache/druid/pull/2109#issuecomment-182191258
*/
@POST
@Path("/datasources/{dataSourceName}/segments")
@Produces(MediaType.APPLICATION_JSON)
@ResourceFilters(DatasourceResourceFilter.class)
public Response getUsedSegmentsInDataSourceForIntervals(
@PathParam("dataSourceName") String dataSourceName,
@QueryParam("full") @Nullable String full,
List<Interval> intervals
)
{
Collection<DataSegment> segments = metadataStorageCoordinator
.retrieveUsedSegmentsForIntervals(dataSourceName, intervals, Segments.INCLUDING_OVERSHADOWED);
Response.ResponseBuilder builder = Response.status(Response.Status.OK);
if (full != null) {
return builder.entity(segments).build();
}
return builder.entity(Collections2.transform(segments, DataSegment::getId)).build();
}
@GET
@Path("/datasources/{dataSourceName}/segments/{segmentId}")
@Produces(MediaType.APPLICATION_JSON)
@ResourceFilters(DatasourceResourceFilter.class)
public Response isSegmentUsed(
@PathParam("dataSourceName") String dataSourceName,
@PathParam("segmentId") String segmentId
)
{
ImmutableDruidDataSource dataSource = segmentsMetadataManager.getImmutableDataSourceWithUsedSegments(dataSourceName);
if (dataSource == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
for (SegmentId possibleSegmentId : SegmentId.iteratePossibleParsingsWithDataSource(dataSourceName, segmentId)) {
DataSegment segment = dataSource.getSegment(possibleSegmentId);
if (segment != null) {
return Response.status(Response.Status.OK).entity(segment).build();
}
}
return Response.status(Response.Status.NOT_FOUND).build();
}
}
| 3,982 |
14,668 |
<filename>components/segmentation_platform/internal/execution/model_execution_manager_factory.cc
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/segmentation_platform/internal/execution/model_execution_manager_factory.h"
#include <memory>
#include <vector>
#include "base/bind.h"
#include "base/task/sequenced_task_runner.h"
#include "components/optimization_guide/machine_learning_tflite_buildflags.h"
#include "components/optimization_guide/proto/models.pb.h"
#include "components/segmentation_platform/internal/execution/feature_aggregator.h"
#include "components/segmentation_platform/internal/execution/model_execution_manager.h"
#if BUILDFLAG(BUILD_WITH_TFLITE_LIB)
#include "components/segmentation_platform/internal/execution/model_execution_manager_impl.h"
#include "components/segmentation_platform/internal/execution/segmentation_model_handler.h"
#else
#include "components/segmentation_platform/internal/execution/dummy_model_execution_manager.h"
#endif // BUILDFLAG(BUILD_WITH_TFLITE_LIB)
namespace base {
class Clock;
} // namespace base
namespace optimization_guide {
class OptimizationGuideModelProvider;
} // namespace optimization_guide
namespace segmentation_platform {
class FeatureAggregator;
class SegmentInfoDatabase;
class SignalDatabase;
#if BUILDFLAG(BUILD_WITH_TFLITE_LIB)
// CreateModelHandler makes it possible to pass in any creator of the
// SegmentationModelHandler, which makes it possible to create mock versions.
std::unique_ptr<SegmentationModelHandler> CreateModelHandler(
optimization_guide::OptimizationGuideModelProvider* model_provider,
scoped_refptr<base::SequencedTaskRunner> background_task_runner,
optimization_guide::proto::OptimizationTarget optimization_target,
const SegmentationModelHandler::ModelUpdatedCallback&
model_updated_callback) {
return std::make_unique<SegmentationModelHandler>(
model_provider, background_task_runner, optimization_target,
model_updated_callback);
}
#endif // BUILDFLAG(BUILD_WITH_TFLITE_LIB)
std::unique_ptr<ModelExecutionManager> CreateModelExecutionManager(
optimization_guide::OptimizationGuideModelProvider* model_provider,
scoped_refptr<base::SequencedTaskRunner> background_task_runner,
base::flat_set<optimization_guide::proto::OptimizationTarget> segment_ids,
base::Clock* clock,
SegmentInfoDatabase* segment_database,
SignalDatabase* signal_database,
std::unique_ptr<FeatureAggregator> feature_aggregator,
const ModelExecutionManager::SegmentationModelUpdatedCallback&
model_updated_callback) {
#if BUILDFLAG(BUILD_WITH_TFLITE_LIB)
return std::make_unique<ModelExecutionManagerImpl>(
segment_ids,
base::BindRepeating(&CreateModelHandler, model_provider,
background_task_runner),
clock, segment_database, signal_database, std::move(feature_aggregator),
model_updated_callback);
#else
return std::make_unique<DummyModelExecutionManager>();
#endif // BUILDFLAG(BUILD_WITH_TFLITE_LIB)
}
} // namespace segmentation_platform
| 1,033 |
455 |
<gh_stars>100-1000
package netflix.karyon.server.interceptor;
import io.reactivex.netty.channel.Handler;
import rx.Observable;
import rx.functions.Action0;
/**
* @author <NAME>
*/
class TestableRequestRouter<I, O> implements Handler<I, O> {
private volatile boolean called;
private volatile boolean unsubscribed;
public boolean isReceivedACall() {
return called;
}
public boolean isUnsubscribed() {
return unsubscribed;
}
@Override
public Observable<Void> handle(I input, O output) {
called = true;
return Observable.<Void>empty().doOnUnsubscribe(new Action0() {
@Override
public void call() {
unsubscribed = true;
}
});
}
}
| 315 |
2,996 |
<filename>engine/src/main/java/org/terasology/engine/world/OnChangedBlock.java<gh_stars>1000+
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.world;
import org.joml.Vector3i;
import org.joml.Vector3ic;
import org.terasology.engine.entitySystem.event.Event;
import org.terasology.engine.world.block.Block;
/**
* Event when a block has changed
*
*/
public class OnChangedBlock implements Event {
private Block oldType;
private Block newType;
private Vector3i blockPosition;
public OnChangedBlock(Vector3ic pos, Block newType, Block oldType) {
this.blockPosition = new Vector3i(pos);
this.oldType = oldType;
this.newType = newType;
}
public Vector3i getBlockPosition() {
return blockPosition;
}
public Block getOldType() {
return oldType;
}
public Block getNewType() {
return newType;
}
}
| 350 |
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.versioning.util;
import java.awt.Dimension;
import javax.swing.JPanel;
/**
* Panel whose maximum height is equal to the preferred height.
* The effect of this is that if it is put to a panel layed out vertically by
* a {@code BoxLayout}, its height remains unchanged when the panel is
* being vertically resized.
*
* @author <NAME>
*/
public class VerticallyNonResizingPanel extends JPanel {
@Override
public Dimension getMaximumSize() {
Dimension origPref = super.getPreferredSize();
Dimension origMax = super.getMaximumSize();
return new Dimension(origMax.width, origPref.height);
}
}
| 402 |
312 |
<filename>app/src/main/java/kale/easydialog/MainActivity.java
package kale.easydialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import kale.ui.view.dialog.EasyDialog;
/**
* 关于更多对话框的设置请参考:http://www.cnblogs.com/tianzhijiexian/p/3867731.html
*/
public class MainActivity extends AppCompatActivity implements DialogInterface.OnClickListener {
public final String TAG = getClass().getSimpleName();
private BottomSheetBehavior behavior;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViews();
// new Handler().postDelayed(() -> ((App) getApplication()).showDialog("全局弹窗", "可在任意时机弹出一个dialog"), 5000);
}
private void setViews() {
findViewById(R.id.dayNight_btn).setOnClickListener(
v -> startActivity(new Intent(this, MyStyleActivity.class)));
// 得到 Bottom Sheet 的视图对象所对应的 BottomSheetBehavior 对象
behavior = BottomSheetBehavior.from(findViewById(R.id.ll_sheet_root));
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
}
});
}
public EasyDialog easyDialog;
public void simpleDialog(View v) {
final android.support.v4.app.FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
EasyDialog.Builder builder = EasyDialog.builder(this);
builder.setTitle("Title")
.setIcon(R.drawable.saber)
.setMessage(R.string.hello_world)
.setOnCancelListener(dialog -> Log.d(TAG, "onCancel"))
.setOnDismissListener(dialog -> Log.d(TAG, "onDismiss"))
// .setNeutralButton("know", null)
// 设置对话框上的按钮 ok->dismiss
.setPositiveButton("ok", (dialog, which) -> {
Log.d(TAG, "onClick ok");
ft.remove(easyDialog);
ft.addToBackStack(null);
EasyDialog.builder(MainActivity.this)
.setTitle("Stack Dialog")
.setMessage("Please press back button")
.build()
.show(ft, "stackDialog");
})
// cancel -> dismiss
.setNegativeButton("cancel", (dialog, which) -> dialog.dismiss())
.setNeutralButton("ignore", this)
.setCancelable(true);
easyDialog = builder.build();
easyDialog.showAllowingStateLoss(getSupportFragmentManager());
// easyDialog.show(getSupportFragmentManager());
// findViewById(R.id.coordinatorlayout).setVisibility(View.INVISIBLE);
}
public void listDialog(View v) {
EasyDialog.builder(this)
.setItems(R.array.country, (dialog, which) -> showToast("click " + which))
.setRetainInstance(true)
.setPositiveButton("yes", (dialog, which) -> showToast("yes"))
.setNegativeButton("no", this)
.build()
.show(getSupportFragmentManager());
}
/**
* 支持单选列表的对话框
*/
public void singleChoiceDialog(View v) {
EasyDialog dialog = EasyDialog.builder(this)
.setTitle("Single Choice Dialog")
.setSingleChoiceItems(new String[]{"Android", "ios", "wp"}, 1,
(dialog1, position) -> {
Log.d(TAG, "onItemClick pos = " + position);
dialog1.dismiss();
})// 设置单选列表的数据和监听
.setPositiveButton("ok", null)
.build();
dialog.setCancelable(false);
dialog.show(getSupportFragmentManager(), TAG);
}
/**
* 支持多选列表的对话框
*/
public void multiChoiceDialog(View v) {
EasyDialog.builder(this)
// 设置数据和默认选中的选项
.setMultiChoiceItems(
new String[]{"Android", "ios", "wp"}, new boolean[]{true, false, true},
(dialog, which, isChecked) -> showToast("onClick pos = " + which + " , isChecked = " + isChecked)) // 设置监听器
.build()
.show(getSupportFragmentManager(), TAG);
}
private InputDialog dialog;
/**
* 可以输入文字的dialog,拥有自定义布局
*/
public void inputDialog(View v) {
dialog = new InputDialog.Builder(this)
.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.kale))
.setInputText("", "hint")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface ignore, int which) {
String text = dialog.getInputTextEt().getText().toString();
if (!TextUtils.isEmpty(text)) {
showToast(text);
}
}
})
.build();
dialog.show(getSupportFragmentManager()); // 一个参数的show()
}
public void imageDialog(View v) {
EasyDialog.builder(this, ImageDialog.class)
.setPositiveButton("弹出动态设置样式的Dialog", (dialog, which) -> {
})
.build()
.show(getSupportFragmentManager());
}
/**
* 显示在顶部的dialog,背景透明
*/
public void topDialog(View v) {
TopDialog.Builder builder = EasyDialog.builder(this, TopDialog.class);
builder.setTitle("标题");
builder.setPositiveButton("设置了宽高", null);
builder.setNegativeButton("位置在顶部", null);
builder.build().show(getSupportFragmentManager());
}
/**
* 自定一个dialog的builder
*/
public void myBuilderDialog(View v) {
new MyBuilderDialog.Builder(this)
.setTitle("Custom Builder Dialog")
.setMessage("message")
.setName("kale")
.setAge(31)
.build()
.show(getSupportFragmentManager());
}
/**
* 从底部弹出的对话框
*/
public void bottomDialog(View v) {
BottomDialog.Builder builder = EasyDialog.builder(this, BottomDialog.class);
builder.setMessage("click me");
builder.setIsBottomDialog(true); // 设置后则会变成从底部弹出,否则为正常模式
// 监听点空白处cancel的事件
builder.setOnCancelListener(d -> showToast("cancel"));
builder.setOnDismissListener(d -> showToast("dismiss"));
EasyDialog dialog = builder.build();
dialog.show(getSupportFragmentManager(), "dialog");
// 如果设置了,那么底部dialog就不支持手势关闭和空白处关闭
dialog.setCancelable(false);
}
/**
* Activity中的可以从底部拉出的dialog
*/
public void bottomDialogInActivity(View v) {
if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
} else {
behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
}
}
public void showToast(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (this != ((App) getApplication()).getCurActivity()) {
throw new RuntimeException("leak");
}
showToast("handle event in activity, is finish ? " + isDestroyed());
}
}
| 4,156 |
14,668 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "extensions/shell/test/shell_apitest.h"
using BluetoothShellApiTest = extensions::ShellApiTest;
// TODO(crbug.com/1165955): this test flakes on Mac ASAN
#if defined(OS_MAC)
#define MAYBE_ApiSanityCheck DISABLED_ApiSanityCheck
#else
#define MAYBE_ApiSanityCheck ApiSanityCheck
#endif
IN_PROC_BROWSER_TEST_F(BluetoothShellApiTest, MAYBE_ApiSanityCheck) {
ASSERT_TRUE(RunAppTest("api_test/bluetooth"));
}
| 217 |
60,067 |
<filename>benchmarks/distributed/rpc/parameter_server/trainer/iteration_steps.py
def basic_iteration_step(self, ddp_model, criterion, optimizer, hook_state, epoch, index, batch):
r"""
A function that performs an iteration of training.
Args:
ddp_model (nn.Module): distributed data parallel model
criterion (nn.Module): loss function to measure model
optimizer (optim.Optimizer): updates model parameters
hook_state (object): ddp communication hook state object
epoch (int): index of pass through the data
index (int): iteration number - 1 in current batch
batch (list): training examples
"""
hook_state.next_batch()
self.record_batch_start(self.epoch_key(epoch, index))
optimizer.zero_grad()
self.record_forward_start(self.epoch_key(epoch, index))
loss = criterion(ddp_model(batch[0]), batch[1])
self.record_forward_end(self.epoch_key(epoch, index))
self.record_backward_start(self.epoch_key(epoch, index))
loss.backward()
self.record_backward_end(self.epoch_key(epoch, index))
optimizer.step()
self.record_batch_end(self.epoch_key(epoch, index))
| 428 |
602 |
package org.corfudb.runtime.object;
import org.corfudb.annotations.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by mwei on 6/22/16.
*/
@CorfuObject(objectType = ObjectType.SMR,
constructorType = ConstructorType.RUNTIME,
stateSource = StateSource.SELF
)
public class TestClassUsingAnnotation implements ICorfuSMR<TestClassUsingAnnotation> {
AtomicInteger a1;
public TestClassUsingAnnotation() {
a1 = new AtomicInteger();
}
@PassThrough
public boolean testFn1() {
return true;
}
@MutatorAccessor(name = "testIncrement")
public boolean testIncrement() {
return a1.incrementAndGet() != 0;
}
@Accessor
public int getValue() {
return a1.get();
}
@Mutator(name = "reset")
public void reset() {
a1.set(0);
}
/**
* {@inheritDoc}
*/
@Override
public TestClassUsingAnnotation getContext(ICorfuExecutionContext.Context context) {
return this;
}
}
| 414 |
854 |
<gh_stars>100-1000
__________________________________________________________________________________________________
sample 116 ms submission
import string
class WordDictionary(dict):
allowed = {*string.ascii_lowercase}
def __init__(self):
"""
Initialize your data structure here.
"""
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
self.setdefault(len(word),[]).append(word)
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
l = len(word)
if l not in self:
return False
elif word in self[l]:
return True
else:
cands = self[l].copy()
for i,c in enumerate(word):
if c=='.':
continue
cands = [cand for cand in cands if cand[i]==c]
if not cands:
return False
return True
__________________________________________________________________________________________________
sample 21984 kb submission
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = {}
return
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
node = self.trie
for w in word:
if(w not in node):
node[w] = {}
node = node[w]
node['EOW'] = word
return
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
node = self.trie
found = self.rsearch(node,word,0)
return found
def rsearch(self,node,word,i):
if(i==len(word)):
if('EOW' in node):
return True
return False
found = False
if(word[i]=='.'):
for k in node.keys():
if(k != 'EOW'):
found = self.rsearch(node[k],word,i+1)
if(found):
return found
else:
w = word[i]
if(w in node):
found = self.rsearch(node[w],word,i+1)
return found
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
__________________________________________________________________________________________________
| 1,330 |
778 |
// ==============================================================================
// KratosShapeOptimizationApplication
//
// License: BSD License
// license: ShapeOptimizationApplication/license.txt
//
// Main authors: <NAME>, https://github.com/armingeiser
//
// ==============================================================================
// ------------------------------------------------------------------------------
// System includes
// ------------------------------------------------------------------------------
#include <iostream>
#include <string>
// ------------------------------------------------------------------------------
// Project includes
// ------------------------------------------------------------------------------
#include "includes/define.h"
#include "includes/model_part.h"
#include "utilities/parallel_utilities.h"
#include "shape_optimization_application.h"
#include "symmetry_base.h"
#include "symmetry_plane.h"
// ==============================================================================
namespace Kratos
{
SymmetryPlane::SymmetryPlane(ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart, Parameters Settings)
: SymmetryBase(rOriginModelPart, rDestinationModelPart, Settings)
{
mPlanePoint = mSettings["point"].GetVector();
mPlaneNormal = mSettings["normal"].GetVector();
KRATOS_ERROR_IF(norm_2(mPlaneNormal) < std::numeric_limits<double>::epsilon()) << "SymmetryPlane: 'normal' vector norm is 0!" << std::endl;
mPlaneNormal /= norm_2(mPlaneNormal);
mReflectionMatrix = IdentityMatrix(3) - (2*outer_prod(mPlaneNormal, mPlaneNormal));
mOriginNodes.resize(mrOriginModelPart.Nodes().size());
block_for_each(mrOriginModelPart.Nodes(), [&](ModelPart::NodeType& rNode) {
const int mapping_id = rNode.GetValue(MAPPING_ID);
mOriginNodes[mapping_id] = &rNode;
});
mDestinationNodes.resize(mrDestinationModelPart.Nodes().size());
block_for_each(mrDestinationModelPart.Nodes(), [&](ModelPart::NodeType& rNode) {
const int mapping_id = rNode.GetValue(MAPPING_ID);
mDestinationNodes[mapping_id] = &rNode;
});
}
SymmetryPlane::NodeVectorType& SymmetryPlane::GetOriginSearchNodes() {
return mOriginNodes;
}
std::vector<std::pair<SymmetryPlane::array_3d, bool>> SymmetryPlane::GetDestinationSearchNodes(const size_t MappingId) {
return {
std::make_pair(mDestinationNodes[MappingId]->Coordinates(), false),
std::make_pair(ReflectPoint(mDestinationNodes[MappingId]->Coordinates()), true),
};
}
void SymmetryPlane::TransformationMatrix(const size_t DestinationMappingId, const size_t OriginMappingId, BoundedMatrix<double, 3, 3>& Matrix) const
{
noalias(Matrix) = mReflectionMatrix;
return;
}
SymmetryPlane::array_3d SymmetryPlane::ReflectPoint(const array_3d& Coords) const {
array_3d tmp = Coords - mPlanePoint;
tmp = prod(mReflectionMatrix, tmp);
return tmp + mPlanePoint;
}
} // namespace Kratos.
| 964 |
327 |
<reponame>yosianonymous31/MobileGuard<gh_stars>100-1000
package com.ittianyu.mobileguard.activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ittianyu.mobileguard.BuildConfig;
import com.ittianyu.mobileguard.R;
import com.ittianyu.mobileguard.activity.base.BaseActivityFullScreen;
import com.ittianyu.mobileguard.constant.Constant;
import com.ittianyu.mobileguard.domain.VersionBean;
import com.ittianyu.mobileguard.utils.ProgressDownloadUtils;
import com.ittianyu.mobileguard.utils.ProgressResponseBody;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* start activity
*/
public class SplashActivity extends BaseActivityFullScreen {
// constants
private static final String VERSION_URL = "http://10.0.2.2/mobileguardversion.json";
private static final String NEW_VERSION_APK = "MobileGuardNew.apk";
// animation time
private static final int ANIMATION_DURATION = 700;
// show time
private static final int LOGO_SHOW_TIME = 500;
// result code
private static final int REQUEST_CODE_INSTALL_NEW_VERSION = 1;
private static final int TIMEOUT = 3;
// data
private OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(TIMEOUT, TimeUnit.SECONDS)
.readTimeout(TIMEOUT, TimeUnit.SECONDS)
.build();
private boolean autoUpdate;
/**
* changet init order
*/
@Override
protected void init() {
initData();
initView();
initEvent();
}
/**
* 1
*/
@Override
protected void initData() {
// get auto update cinfig
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
autoUpdate = sp.getBoolean(Constant.KEY_CB_AUTO_UPDATE, true);
// System.out.println("autoUpdate:" + autoUpdate);
}
/**
* 2
*/
@Override
protected void initView() {
setContentView(R.layout.activity_splash);
// set animation
setAnimation();
// get local version
// getAppVersionInfo();// now replace by the word on image
// auto update check
if(autoUpdate) {
// get latest version info
getVersionInfo();
}// if not update, it will start main activity on animation end
}
/**
* 3
*/
@Override
protected void initEvent() {
}
/**
* check version.
* Need run on UI thread
* Showing a dialog to query user whether to update app, if local version code < latest version code
*
* @param latestVersionInfo the latest version bean
*/
private void checkVersion(final VersionBean latestVersionInfo) {
if (null == latestVersionInfo || BuildConfig.VERSION_CODE >= latestVersionInfo.getVersion()) {
startMainActivity();
return;
}
// show dialog to query whether to update
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(R.string.update_tips)
.setMessage(getString(R.string.update_description) + latestVersionInfo.getDescription())
// .setCancelable(false)// can't be canceled by esc or touch other position
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
startMainActivity();
}
})
.setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
updateApp(latestVersionInfo.getUrl());
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startMainActivity();
}
})
.create();
dialog.show();
}
/**
* download the new apk and install
*
* @param url
*/
private void updateApp(final String url) {
// download apk, the install will be started after download success
downloadNewVersion(url);
}
/**
* 安装新版本
*
* @param file the apk
*/
private void installNewVersion(final File file) throws FileNotFoundException {
/*
<activity android:name=".PackageInstallerActivity"
android:configChanges="orientation|keyboardHidden"
android:theme="@style/TallTitleBarTheme">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="content" />
<data android:scheme="file" />
<data android:mimeType="application/vnd.android.package-archive" />
</intent-filter>
</activity>
*/
if (null == file)
throw new NullPointerException("file can't be null");
if (!file.exists())
throw new FileNotFoundException("file " + file.getAbsolutePath() + " can't be found");
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivityForResult(intent, REQUEST_CODE_INSTALL_NEW_VERSION);
}
/**
* on the started activity return result
* will start the main activity
*
* @param requestCode request code
* @param resultCode result code
* @param data data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_INSTALL_NEW_VERSION:
startMainActivity();
break;
}
}
/**
* download the new apk
*
* @param url the url of new version
*/
private void downloadNewVersion(final String url) {
/* Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(SplashActivity.this, R.string.failed_to_download, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream in = response.body().byteStream();
FileUtils.saveFileWithStream(new File(Environment.getExternalStorageDirectory(), NEW_VERSION_APK), in);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(SplashActivity.this, R.string.success_to_download, Toast.LENGTH_SHORT).show();
// install apk
try {
installNewVersion(new File(Environment.getExternalStorageDirectory(), NEW_VERSION_APK));
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, R.string.failed_to_install_new_version, Toast.LENGTH_SHORT).show();
}
}
});
}
});*/
// show progress dialog
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle(R.string.download);
progressDialog.setMessage(getString(R.string.download_tips));
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
startMainActivity();
}
});
progressDialog.setIndeterminate(false);// show progress bar
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.show();
// download
ProgressDownloadUtils downloadUtils = new ProgressDownloadUtils(url, new File(Environment.getExternalStorageDirectory(), NEW_VERSION_APK), new ProgressResponseBody.ProgressListener() {
@Override
public void onPreExecute(long contentLength) {
// set the max, change contentLength from b to kb
progressDialog.setMax((int) (contentLength / 1024));
}
@Override
public void update(long totalBytes, boolean done) {
// set the progress, change contentLength from b to kb
progressDialog.setProgress((int) (totalBytes / 1024));
// download success
if (done) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.cancel();// if not call, will cause "Activity has leaked window"
Toast.makeText(SplashActivity.this, R.string.success_to_download, Toast.LENGTH_SHORT).show();
// install apk
try {
installNewVersion(new File(Environment.getExternalStorageDirectory(), NEW_VERSION_APK));
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, R.string.failed_to_install_new_version, Toast.LENGTH_SHORT).show();
}
}
});
}
}
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(SplashActivity.this, R.string.failed_to_download, Toast.LENGTH_SHORT).show();
startMainActivity();
}
});
}
});
downloadUtils.download(0L);
}
/**
* start the main activity
*/
private void startMainActivity() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
/**
* get the version info in gradle and set to TextView
*/
private void getAppVersionInfo() {
// TextView tvVersionName = (TextView) findViewById(R.id.tv_splash_version_name);
// tvVersionName.setText(BuildConfig.VERSION_NAME);
}
/**
* get latest version info
* the result will show at least ANIMATION_DURATION millisecond.
* It means that the result will be show until animation finish
*/
private void getVersionInfo() {
// get the start time
final long startTime = System.currentTimeMillis();
// send request
Request request = new Request.Builder().get()
.url(VERSION_URL)
.build();
client.newCall(request).enqueue(new Callback() {
// failed
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(SplashActivity.this, R.string.failed_to_connect_internet, Toast.LENGTH_SHORT).show();
}
});
// wait for animation and check version
waitForAnimationFinishAndCheckVersion(startTime, null);
}
// parse json
@Override
public void onResponse(Call call, Response response) throws IOException {
String jsonString = response.body().string();
System.out.println(jsonString);
Gson gson = new Gson();
VersionBean latestVersionInfo = null;
try {
latestVersionInfo = gson.fromJson(jsonString, VersionBean.class);
} catch (JsonSyntaxException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(SplashActivity.this, R.string.json_parse_error, Toast.LENGTH_SHORT).show();
}
});
}
System.out.println(latestVersionInfo);
// wait for animation and check version
waitForAnimationFinishAndCheckVersion(startTime, latestVersionInfo);
}
});
}
/**
* wait for animation finish.
* Need run on child thread
* and check version will run on ui thread
*
* @param startTime the time at the begin of getVersionInfo
* @param latestVersionInfo the latest version bean
*/
private void waitForAnimationFinishAndCheckVersion(final long startTime, final VersionBean latestVersionInfo) {
// wait for animation finish
long endTime = System.currentTimeMillis();
long interval = ANIMATION_DURATION + LOGO_SHOW_TIME - (endTime - startTime);
if (interval > 0) {
SystemClock.sleep(interval);
}
// check version
runOnUiThread(new Runnable() {
@Override
public void run() {
checkVersion(latestVersionInfo);
}
});
}
/**
* set animation
* alpha freom 0 to 1 in 3s
*/
private void setAnimation() {
// alpha
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(ANIMATION_DURATION);
// alphaAnimation.setFillAfter(true);
// rotate
RotateAnimation rotateAnimation = new RotateAnimation(180, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation.setDuration(ANIMATION_DURATION);
// rotateAnimation.setFillAfter(true);
// scale
ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(ANIMATION_DURATION);
// scaleAnimation.setFillAfter(true);
// animation set
AnimationSet animationSet = new AnimationSet(true);
animationSet.addAnimation(alphaAnimation);
animationSet.addAnimation(rotateAnimation);
animationSet.addAnimation(scaleAnimation);
// set animation listener
// when animation finish, start main activity if autoUpdate equal false
if(!autoUpdate) {
animationSet.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
System.out.println("onAnimationEnd:startMainActivity");
// wait for LOGO_SHOW_TIME then start main activity
new Thread(){
@Override
public void run() {
SystemClock.sleep(LOGO_SHOW_TIME);
runOnUiThread(new Runnable() {
@Override
public void run() {
startMainActivity();
}
});
}
}.start();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
// get root view of activity
View vRoot = findViewById(R.id.activity_splash);
// start animation
vRoot.startAnimation(animationSet);
}
}
| 7,875 |
5,823 |
<filename>shell/platform/fuchsia/flutter/software_surface.h<gh_stars>1000+
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <fuchsia/sysmem/cpp/fidl.h>
#include <fuchsia/ui/composition/cpp/fidl.h>
#include <lib/async/cpp/wait.h>
#include <lib/ui/scenic/cpp/id.h>
#include <lib/ui/scenic/cpp/resources.h>
#include <lib/zx/event.h>
#include <lib/zx/vmo.h>
#include <array>
#include <cstdint>
#include <memory>
#include "flutter/fml/macros.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "surface_producer.h"
namespace flutter_runner {
class SoftwareSurface final : public SurfaceProducerSurface {
public:
SoftwareSurface(fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
scenic::Session* session,
const SkISize& size);
~SoftwareSurface() override;
size_t GetAllocationSize() const { return surface_size_bytes_; }
// |SurfaceProducerSurface|
size_t AdvanceAndGetAge() override;
// |SurfaceProducerSurface|
bool FlushSessionAcquireAndReleaseEvents() override;
// |SurfaceProducerSurface|
bool IsValid() const override;
// |SurfaceProducerSurface|
SkISize GetSize() const override;
// |SurfaceProducerSurface|
void SignalWritesFinished(
const std::function<void(void)>& on_surface_read_finished) override;
// |SurfaceProducerSurface|
void SetImageId(uint32_t image_id) override;
// |SurfaceProducerSurface|
uint32_t GetImageId() override;
// |SurfaceProducerSurface|
sk_sp<SkSurface> GetSkiaSurface() const override;
// |SurfaceProducerSurface|
fuchsia::ui::composition::BufferCollectionImportToken
GetBufferCollectionImportToken() override;
// |SurfaceProducerSurface|
zx::event GetAcquireFence() override;
// |SurfaceProducerSurface|
zx::event GetReleaseFence() override;
// |SurfaceProducerSurface|
void SetReleaseImageCallback(
ReleaseImageCallback release_image_callback) override;
private:
void OnSurfaceReadFinished(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal_t* signal);
bool SetupSkiaSurface(
fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
const SkISize& size);
bool CreateFences();
void Reset();
static uint32_t sNextBufferId; // For legacy gfx; counter for `buffer_id_`.
scenic::Session* session_; // Legacy gfx API endpoint.
scenic::ResourceId image_id_{0}; // Legacy gfx image ID.
sk_sp<SkSurface> sk_surface_;
// This is associated with `release_event_` and allows detection of when
// scenic has finished reading from the surface (and thus it is safe to re-use
// for writing).
async::WaitMethod<SoftwareSurface, &SoftwareSurface::OnSurfaceReadFinished>
wait_for_surface_read_finished_;
// Called when scenic has finished reading from the surface, to allow
// `SoftwareSurfaceProducer` to re-use the surface.
std::function<void()> surface_read_finished_callback_;
// Called when the surface is destroyed, to allow
// `FlatlandExternalViewEmbedder` to release the associated Flatland image.
ReleaseImageCallback release_image_callback_;
// Allows Flatland to associate this surface with a Flatland Image.
fuchsia::ui::composition::BufferCollectionImportToken import_token_;
uint32_t buffer_id_{0}; // Legacy gfx version of the import_token_.
zx::event acquire_event_; // Signals to scenic that writing is finished.
zx::event release_event_; // Signalled by scenic that reading is finished.
zx::vmo surface_vmo_; // VMO that is backing the surface memory.
uint32_t surface_size_bytes_; // Size of the surface memory, in bytes.
size_t age_{0}; // Number of frames since surface was last written to.
bool needs_cache_clean_{false};
bool valid_{false};
FML_DISALLOW_COPY_AND_ASSIGN(SoftwareSurface);
};
} // namespace flutter_runner
| 1,508 |
852 |
<gh_stars>100-1000
# cfi file to produce the L1 GT keys for records managed via RUN SETTINGS
import FWCore.ParameterSet.Config as cms
l1GtRsObjectKeysOnline = cms.ESProducer("L1GtRsObjectKeysOnlineProd",
onlineAuthentication = cms.string('.'),
subsystemLabel = cms.string(''),
onlineDB = cms.string('oracle://CMS_OMDS_LB/CMS_TRG_R'),
#
PartitionNumber = cms.int32(0),
EnableL1GtPrescaleFactorsAlgoTrig = cms.bool( True ),
EnableL1GtPrescaleFactorsTechTrig = cms.bool( True ),
EnableL1GtTriggerMaskAlgoTrig = cms.bool( True ),
EnableL1GtTriggerMaskTechTrig = cms.bool( True ),
EnableL1GtTriggerMaskVetoTechTrig = cms.bool( True )
)
| 276 |
595 |
<filename>lib/sw_apps/imgsel/src/xis_qspi.c
/******************************************************************************
* Copyright (c) 2020 Xilinx, Inc. All rights reserved.
* SPDX-License-Identifier: MIT
******************************************************************************/
/*****************************************************************************/
/**
* @file xis_qspi.c
*
* This is the main file which will contain the qspi initialization,
* Erase,read and write fucntions
*
* @note
*
* None.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- ---- -------- ---------------------------------------------------------
* 1.00 Ana 18/06/20 First release
*
* </pre>
*
******************************************************************************/
/***************************** Include Files *********************************/
#include "xis_main.h"
#ifdef XIS_UPDATE_A_B_MECHANISM
/************************** Constant Definitions *****************************/
/*
* The following constants map to the XPAR parameters created in the
* xparameters.h file. They are defined here such that a user can easily
* change all the needed parameters in one place.
*/
#define QSPI_DEVICE_ID XPAR_XQSPIPSU_0_DEVICE_ID
/**************************** Type Definitions *******************************/
/***************** Macros (Inline Functions) Definitions *********************/
/************************** Function Prototypes ******************************/
static int XIs_FlashReadID(XQspiPsu *QspiPsuPtr);
static int XIs_MacronixEnable4B(XQspiPsu *QspiPsuPtr);
static int XIs_MacronixEnableQPIMode(XQspiPsu *QspiPsuPtr, int Enable);
static int XIs_QspiFlashErase(u32 Address, u32 ByteCount);
static int XIs_QspiWriteData(u32 Address, u8 *WriteBfrPtr, u32 ByteCount);
/************************** Variable Definitions *****************************/
static XQspiPsu QspiPsuInstance;
static u32 ReadCommand = 0U;
static u32 StatusCmd = 0U;
static XQspiPsu_Msg FlashMsg[5U];
static FlashInfo Flash_Config;
static u8 FSRFlag;
static u8 CmdBfr[8U];
static u8 TxBfrPtr __attribute__ ((aligned(32U)));
static u8 ReadDataBuffer[10U] __attribute__ ((aligned(32U)));
static u8 WriteDataBuffer[10U] __attribute__ ((aligned(32U)));
static u32 MacronixFlash = 0U;
static u32 PageSize = 0U;
/************************** Function Definitions *****************************/
/******************************************************************************
*
* This function reads serial FLASH ID connected to the SPI interface.
* It then deduces the make and size of the flash and obtains the
* connection mode to point to corresponding parameters in the flash
* configuration table. The flash driver will function based on this and
* it presently supports Micron and Spansion - 128, 256 and 512Mbit and
* Winbond 128Mbit
*
* @param QspiPsuPtr Pointer to QSPI instance.
*
* @return XST_SUCCESS if read id, otherwise XST_FAILURE.
*
******************************************************************************/
static int XIs_FlashReadID(XQspiPsu *QspiPsuPtr)
{
int Status = XST_FAILURE;
/*
* Read ID
*/
TxBfrPtr = READ_ID_CMD;
FlashMsg[0U].TxBfrPtr = &TxBfrPtr;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
FlashMsg[1U].TxBfrPtr = NULL;
FlashMsg[1U].RxBfrPtr = ReadDataBuffer;
FlashMsg[1U].ByteCount = 4U;
FlashMsg[1U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[1U].Flags = XQSPIPSU_MSG_FLAG_RX;
Status = XQspiPsu_PolledTransfer(QspiPsuPtr, &FlashMsg[0U], 2U);
if (Status != XIS_SUCCESS) {
Status = XST_FAILURE;
goto END;
}
XIs_Printf(DEBUG_GENERAL, "FlashID=0x%x 0x%x 0x%x\n\r",
ReadDataBuffer[0U], ReadDataBuffer[1U], ReadDataBuffer[2U]);
/*
* Deduce flash make
*/
MacronixFlash = 0U;
if (ReadDataBuffer[0U] == MICRON_ID) {
Flash_Config.QspiFlashMake = MICRON_ID;
XIs_Printf(DEBUG_INFO, "MICRON ");
} else if(ReadDataBuffer[0U] == SPANSION_ID) {
Flash_Config.QspiFlashMake = SPANSION_ID;
XIs_Printf(DEBUG_INFO, "SPANSION ");
} else if(ReadDataBuffer[0U] == WINBOND_ID) {
Flash_Config.QspiFlashMake = WINBOND_ID;
XIs_Printf(DEBUG_INFO, "WINBOND ");
} else if(ReadDataBuffer[0U] == MACRONIX_ID) {
Flash_Config.QspiFlashMake = MACRONIX_ID;
XIs_Printf(DEBUG_INFO, "MACRONIX ");
MacronixFlash = 1U;
} else if(ReadDataBuffer[0U] == ISSI_ID) {
Flash_Config.QspiFlashMake = ISSI_ID;
XIs_Printf(DEBUG_INFO, "ISSI\r\n");
} else {
Status = XIS_UNSUPPORTED_QSPI_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_UNSUPPORTED_QSPI_ERROR\r\n");
goto END;
}
/*
* Deduce flash Size
*/
if (ReadDataBuffer[2U] == FLASH_SIZE_ID_8M) {
XIs_Printf(DEBUG_INFO, "8M Bits\r\n");
Flash_Config.QspiFlashSize = FLASH_SIZE_8M;
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_256;
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
Flash_Config.SectSize = SECTOR_SIZE_128K;
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_512;
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
} else if (ReadDataBuffer[2U] == FLASH_SIZE_ID_16M) {
Flash_Config.QspiFlashSize = FLASH_SIZE_16M;
XIs_Printf(DEBUG_INFO, "16M Bits\r\n");
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_256;
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
Flash_Config.SectSize = SECTOR_SIZE_128K;
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_512;
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
} else if (ReadDataBuffer[2U] == FLASH_SIZE_ID_32M) {
Flash_Config.QspiFlashSize = FLASH_SIZE_32M;
XIs_Printf(DEBUG_INFO, "32M Bits\r\n");
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_256;
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
Flash_Config.SectSize = SECTOR_SIZE_128K;
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_512;
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
} else if (ReadDataBuffer[2U] == FLASH_SIZE_ID_64M) {
Flash_Config.QspiFlashSize = FLASH_SIZE_64M;
XIs_Printf(DEBUG_INFO, "64M Bits\r\n");
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 1U;
if(Flash_Config.QspiFlashMake == SPANSION_ID) {
Flash_Config.PageSize = PAGE_SIZE_512;
} else {
Flash_Config.PageSize = PAGE_SIZE_256;
}
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
Flash_Config.SectSize = SECTOR_SIZE_128K;
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 1U;
if(Flash_Config.QspiFlashMake == SPANSION_ID) {
Flash_Config.PageSize = PAGE_SIZE_1024;
} else {
Flash_Config.PageSize = PAGE_SIZE_512;
}
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
} else if (ReadDataBuffer[2U] == FLASH_SIZE_ID_128M) {
Flash_Config.QspiFlashSize = FLASH_SIZE_128M;
XIs_Printf(DEBUG_INFO, "128M Bits\r\n");
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_256;
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
Flash_Config.SectSize = SECTOR_SIZE_128K;
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_512;
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
} else if ((ReadDataBuffer[2U] == FLASH_SIZE_ID_256M)
|| (ReadDataBuffer[2U] == MACRONIX_FLASH_1_8_V_MX25_ID_256)) {
Flash_Config.QspiFlashSize = FLASH_SIZE_256M;
XIs_Printf(DEBUG_INFO, "256M Bits\r\n");
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_256;
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
Flash_Config.SectSize = SECTOR_SIZE_128K;
if(Flash_Config.QspiFlashMake == ISSI_ID) {
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
}
else {
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
}
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_512;
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
} else if ((ReadDataBuffer[2U] == FLASH_SIZE_ID_512M)
|| (ReadDataBuffer[2U] == MACRONIX_FLASH_SIZE_ID_512M)
|| (ReadDataBuffer[2U] == MACRONIX_FLASH_1_8_V_MX66_ID_512)) {
Flash_Config.QspiFlashSize = FLASH_SIZE_512M;
XIs_Printf(DEBUG_INFO, "512M Bits\r\n");
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
if(Flash_Config.QspiFlashMake == SPANSION_ID) {
Flash_Config.SectSize = SECTOR_SIZE_256K;
Flash_Config.SectMask = FLASH_SPANSION_SINGLE_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_512;
}
else {
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 2U;
Flash_Config.PageSize = PAGE_SIZE_256;
}
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
if(Flash_Config.QspiFlashMake == SPANSION_ID) {
Flash_Config.SectSize = SECTOR_SIZE_512K;
Flash_Config.SectMask = FALSH_SPANSION_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 1U;
Flash_Config.PageSize = PAGE_SIZE_1024;
}
else {
Flash_Config.SectSize = SECTOR_SIZE_128K;
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 2U;
Flash_Config.PageSize = PAGE_SIZE_512;
}
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
} else if ((ReadDataBuffer[2U] == FLASH_SIZE_ID_1G)
|| (ReadDataBuffer[2U] == MACRONIX_FLASH_SIZE_ID_1G)
|| (ReadDataBuffer[2U] == MACRONIX_FLASH_1_8_V_SIZE_ID_1G)) {
Flash_Config.QspiFlashSize = FLASH_SIZE_1G;
XIs_Printf(DEBUG_INFO, "1G Bits\r\n");
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 4U;
Flash_Config.PageSize = PAGE_SIZE_256;
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
Flash_Config.SectSize = SECTOR_SIZE_128K;
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 4U;
Flash_Config.PageSize = PAGE_SIZE_512;
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
} else if ((ReadDataBuffer[2U] == FLASH_SIZE_ID_2G)
|| (ReadDataBuffer[2U] == MACRONIX_FLASH_SIZE_ID_2G)
|| (ReadDataBuffer[2U] == MACRONIX_FLASH_1_8_V_SIZE_ID_2G)) {
Flash_Config.QspiFlashSize = FLASH_SIZE_2G;
XIs_Printf(DEBUG_INFO, "2G Bits\r\n");
switch(QspiPsuPtr->Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
case XQSPIPSU_CONNECTION_MODE_STACKED:
Flash_Config.SectSize = SECTOR_SIZE_64K;
Flash_Config.SectMask = FLASH_SINGLE_STACK_MODE_MASK;
Flash_Config.NumDie = 4U;
Flash_Config.PageSize = PAGE_SIZE_256;
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
Flash_Config.SectSize = SECTOR_SIZE_128K;
Flash_Config.SectMask = FLASH_PARALLEL_MODE_MASK;
Flash_Config.NumDie = 4U;
Flash_Config.PageSize = PAGE_SIZE_512;
break;
default:
Status = XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_UNSUPPORTED_QSPI_CONN_MODE_ERROR\r\n");
}
if (Status != XST_SUCCESS) {
goto END;
}
}else {
Status = XIS_UNSUPPORTED_QSPI_ERROR;
XIs_Printf(DEBUG_GENERAL,"XIS_UNSUPPORTED_QSPI_ERROR\r\n");
goto END;
}
if ((Flash_Config.NumDie > 1U) &&
(Flash_Config.QspiFlashMake == MICRON_ID)) {
StatusCmd = READ_FLAG_STATUS_CMD;
FSRFlag = 1U;
} else {
StatusCmd = READ_STATUS_CMD;
FSRFlag = 0U;
}
END:
return Status;
}
/******************************************************************************
*
* This functions translates the address based on the type of interconnection.
* In case of stacked, this function asserts the corresponding slave select.
*
* @param Address which is to be accessed
*
* @return QspiAddr is the actual flash address to be accessed - for single
* it is unchanged; for stacked, the lower flash size is subtracted;
* for parallel the address is divided by 2.
*
******************************************************************************/
static u32 XIs_GetQspiAddr(u32 Address)
{
u32 RealAddr;
switch(QspiPsuInstance.Config.ConnectionMode) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
XQspiPsu_SelectFlash(&QspiPsuInstance,
XQSPIPSU_SELECT_FLASH_CS_LOWER,
XQSPIPSU_SELECT_FLASH_BUS_LOWER);
RealAddr = Address;
break;
case XQSPIPSU_CONNECTION_MODE_STACKED:
/*
* Select lower or upper Flash based on sector address
*/
if(Address >= (Flash_Config.QspiFlashSize / 2U)) {
XQspiPsu_SelectFlash(&QspiPsuInstance,
XQSPIPSU_SELECT_FLASH_CS_UPPER,
XQSPIPSU_SELECT_FLASH_BUS_LOWER);
/*
* Subtract first flash size when accessing second flash
*/
RealAddr = Address - (Flash_Config.QspiFlashSize / 2U);
}else{
/*
* Set selection to L_PAGE
*/
XQspiPsu_SelectFlash(&QspiPsuInstance,
XQSPIPSU_SELECT_FLASH_CS_LOWER,
XQSPIPSU_SELECT_FLASH_BUS_LOWER);
RealAddr = Address;
}
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
/*
* The effective address in each flash is the actual
* address / 2
*/
XQspiPsu_SelectFlash(&QspiPsuInstance,
XQSPIPSU_SELECT_FLASH_CS_BOTH, XQSPIPSU_SELECT_FLASH_BUS_BOTH);
RealAddr = Address / 2U;
break;
default:
/*
* We should never reach here as error will be triggered during
* QSPI Init for invalid connection mode. Hence, assign a value (0)
* to RealAddr, to avoid warning.
*/
RealAddr = 0U;
break;
}
return RealAddr;
}
/*****************************************************************************/
/**
* This function is used to initialize the qspi controller and driver
*
* @param PageSize which is used to write data to flash
*
* @return None
*
*****************************************************************************/
int XIs_QspiInit(void)
{
int Status = XST_FAILURE;
XQspiPsu_Config *QspiConfig;
u32 QspiMode;
/**
* Initialize the QSPI driver so that it's ready to use
*/
QspiConfig = XQspiPsu_LookupConfig(QSPI_DEVICE_ID);
if (NULL == QspiConfig) {
Status = XIS_QSPI_CONFIG_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_CONFIG_ERROR\r\n");
goto END;
}
Status = XQspiPsu_CfgInitialize(&QspiPsuInstance, QspiConfig,
QspiConfig->BaseAddress);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_CONFIG_INIT_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_CONFIG_INIT_ERROR\r\n");
goto END;
}
/*
* Set Manual Start
*/
Status = XQspiPsu_SetOptions(&QspiPsuInstance, XQSPIPSU_MANUAL_START_OPTION);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_MANUAL_START_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_MANUAL_START_ERROR\r\n");
goto END;
}
/*
* Set the pre-scaler for QSPI clock
*/
Status = XQspiPsu_SetClkPrescaler(&QspiPsuInstance, XQSPIPSU_CLK_PRESCALE_8);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_PRESCALER_CLK_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_PRESCALER_CLK_ERROR\r\n");
goto END;
}
XQspiPsu_SelectFlash(&QspiPsuInstance,
XQSPIPSU_SELECT_FLASH_CS_LOWER, XQSPIPSU_SELECT_FLASH_BUS_LOWER);
/*
* Configure the qspi in linear mode if running in XIP
* TBD
*/
switch ((u32)XPAR_PSU_QSPI_0_QSPI_MODE) {
case XQSPIPSU_CONNECTION_MODE_SINGLE:
XIs_Printf(DEBUG_INFO, "QSPI is in single flash connection\r\n");
break;
case XQSPIPSU_CONNECTION_MODE_PARALLEL:
XIs_Printf(DEBUG_INFO, "QSPI is in Dual Parallel connection\r\n");
break;
case XQSPIPSU_CONNECTION_MODE_STACKED:
XIs_Printf(DEBUG_INFO, "QSPI is in Dual Stack connection\r\n");
break;
default:
Status = XIS_INVALID_QSPI_CONNECTION_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_INVALID_QSPI_CONNECTION_ERROR\r\n");
break;
}
if(Status != XIS_SUCCESS) {
goto END;
}
switch (QspiPsuInstance.Config.BusWidth) {
case XIS_QSPI_BUSWIDTH_ONE:
XIs_Printf(DEBUG_INFO, "QSPI is using 1 bit bus\r\n");
ReadCommand = FAST_READ_CMD_32BIT;
break;
case XIS_QSPI_BUSWIDTH_TWO:
XIs_Printf(DEBUG_INFO, "QSPI is using 2 bit bus\r\n");
ReadCommand = DUAL_READ_CMD_32BIT;
break;
case XIS_QSPI_BUSWIDTH_FOUR:
XIs_Printf(DEBUG_INFO, "QSPI is using 4 bit bus\r\n");
ReadCommand = QUAD_READ_CMD_32BIT;
break;
default:
Status = XIS_INVALID_QSPI_CONNECTION_ERROR;
XIs_Printf(DEBUG_GENERAL,
"XIS_INVALID_QSPI_CONNECTION_ERROR\r\n");
break;
}
if(Status != XIS_SUCCESS) {
goto END;
}
/**
* Read Flash ID and extract Manufacture and Size information
*/
Status = XIs_FlashReadID(&QspiPsuInstance);
if (Status != XIS_SUCCESS) {
goto END;
}
if (MacronixFlash == 1U) {
if (QspiPsuInstance.Config.BusWidth == XIS_QSPI_BUSWIDTH_FOUR) {
ReadCommand = QUAD_READ_CMD_24BIT2;
}
if (QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_PARALLEL) {
XQspiPsu_SelectFlash(&QspiPsuInstance,
XQSPIPSU_SELECT_FLASH_CS_BOTH,
XQSPIPSU_SELECT_FLASH_BUS_BOTH);
Status = XIs_MacronixEnable4B(&QspiPsuInstance);
if (Status != XIS_SUCCESS) {
Status = XST_FAILURE;
goto END;
}
} else {
XQspiPsu_SelectFlash(&QspiPsuInstance,
XQSPIPSU_SELECT_FLASH_CS_LOWER,
XQSPIPSU_SELECT_FLASH_BUS_LOWER);
Status = XIs_MacronixEnable4B(&QspiPsuInstance);
if (Status != XIS_SUCCESS) {
Status = XST_FAILURE;
goto END;
}
if (QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_STACKED) {
XQspiPsu_SelectFlash(&QspiPsuInstance,
XQSPIPSU_SELECT_FLASH_CS_UPPER,
XQSPIPSU_SELECT_FLASH_BUS_LOWER);
Status = XIs_MacronixEnable4B(&QspiPsuInstance);
if (Status != XIS_SUCCESS) {
Status = XST_FAILURE;
goto END;
}
}
}
}
/**
* Add code: For a Stacked connection, read second Flash ID
*/
QspiMode = QspiPsuInstance.Config.ConnectionMode;
if ((QspiMode ==
(u32)(XQSPIPSU_CONNECTION_MODE_PARALLEL)) ||
(QspiMode ==
(u32)(XQSPIPSU_CONNECTION_MODE_STACKED)) ) {
Flash_Config.QspiFlashSize = 2U * Flash_Config.QspiFlashSize;
}
PageSize = Flash_Config.PageSize;
END:
return Status;
}
/******************************************************************************
*
* Static API used for Macronix flash to enable 4BYTE mode
*
* @param QspiPsuPtr Pointer to QSPI instance.
*
* @return XIS_SUCCESS if success, otherwise XST_FAILURE.
*
******************************************************************************/
static int XIs_MacronixEnable4B(XQspiPsu *QspiPsuPtr)
{
int Status = XST_FAILURE;
XIs_Printf(DEBUG_GENERAL, "MACRONIX_FLASH_MODE\r\n");
/*Enable register write*/
TxBfrPtr = WRITE_ENABLE_CMD;
FlashMsg[0U].TxBfrPtr = &TxBfrPtr;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
Status = XQspiPsu_PolledTransfer(QspiPsuPtr, &FlashMsg[0U], 1U);
if (Status != XIS_SUCCESS) {
goto END;
}
/*Enable 4 byte mode*/
TxBfrPtr = 0xB7U;
FlashMsg[0U].TxBfrPtr = &TxBfrPtr;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
Status = XQspiPsu_PolledTransfer(QspiPsuPtr, &FlashMsg[0U], 1U);
if (Status != XIS_SUCCESS) {
goto END;
}
XIs_Printf(DEBUG_GENERAL, "MACRONIX_ENABLE_4BYTE_DONE\r\n");
END:
return Status;
}
/******************************************************************************
*
* Static API used for Macronix flash to enable or disable QPI mode
*
* @param QspiPsuPtr Pointer to QSPI instance.
* @param Enable valid values are 0 (disable) and 1 (enable).
*
* @return XIS_SUCCESS if success, otherwise XIS_QSPI_READ_ERROR.
*
******************************************************************************/
static int XIs_MacronixEnableQPIMode(XQspiPsu *QspiPsuPtr, int Enable)
{
int Status = XST_FAILURE;
/*Enable register write*/
TxBfrPtr = WRITE_ENABLE_CMD;
FlashMsg[0U].TxBfrPtr = &TxBfrPtr;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
if (Enable == ENABLE_QPI) {
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
} else {
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_QUADSPI;
}
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, &FlashMsg[0U], 1U);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_READ_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_READ_ERROR\r\n");
goto END;
}
if (Enable == ENABLE_QPI) {
TxBfrPtr = 0x35U;
} else {
TxBfrPtr = 0xF5U;
}
FlashMsg[0U].TxBfrPtr = &TxBfrPtr;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
if (Enable == ENABLE_QPI) {
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
} else {
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_QUADSPI;
}
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, &FlashMsg[0U], 1U);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_READ_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_READ_ERROR\r\n");
goto END;
}
END:
return Status;
}
/*****************************************************************************/
/**
* This function is used to copy the data from QSPI flash to destination
* address
*
* @param SrcAddress is the address of the QSPI flash where copy should
* start from
* @param DestAddress is the address of the destination where it
* should copy to
* @param Length Length of the bytes to be copied
*
* @return XIS_SUCCESS for successful copy
* errors as mentioned in xis_error.h
*
*****************************************************************************/
int XIs_QspiRead(u32 SrcAddress, u8* DestAddress, u32 Length)
{
int Status = XST_FAILURE;
u32 QspiAddr;
u32 RemainingBytes;
u32 TransferBytes;
u32 DiscardByteCnt;
XIs_Printf(DEBUG_INFO, "QSPI Reading Src 0x%0lx, Dest %0lx,"
"Length %0lx\r\n", SrcAddress, DestAddress, Length);
/**
* Check the read length with Qspi flash size
*/
if ((SrcAddress + Length) > Flash_Config.QspiFlashSize) {
Status = XIS_QSPI_LENGTH_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_LENGTH_ERROR\r\n");
goto END;
}
/**
* Update no of bytes to be copied
*/
RemainingBytes = Length;
while(RemainingBytes > 0U) {
if (RemainingBytes > DMA_DATA_TRAN_SIZE) {
TransferBytes = DMA_DATA_TRAN_SIZE;
} else {
TransferBytes = RemainingBytes;
}
/*
* Translate address based on type of connection
* If stacked assert the slave select based on address
*/
QspiAddr = XIs_GetQspiAddr((u32 )SrcAddress);
XIs_Printf(DEBUG_INFO,".");
XIs_Printf(DEBUG_DETAILED,
"QSPI Read Src 0x%0lx, Dest %0lx, Length %0lx\r\n",
QspiAddr, DestAddress, TransferBytes);
/*
* Setup the read command with the specified address and data for the
* Flash
*/
if ((MacronixFlash == 1U) &&
(QspiPsuInstance.Config.BusWidth == XIS_QSPI_BUSWIDTH_FOUR)) {
/* Enable QPI mode */
Status = XIs_MacronixEnableQPIMode(&QspiPsuInstance, ENABLE_QPI);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_4BYTE_ENETER_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_4BYTE_ENETER_ERROR\r\n");
goto END;
}
/*Command*/
WriteDataBuffer[COMMAND_OFFSET] = (u8)ReadCommand;
DiscardByteCnt = 1U;
/*MACRONIX is in QPI MODE 4-4-4*/
FlashMsg[0U].TxBfrPtr = WriteDataBuffer;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = DiscardByteCnt;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_QUADSPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
/*Address*/
WriteDataBuffer[ADDRESS_1_OFFSET] =
(u8)((QspiAddr & 0xFF000000U) >> 24U);
WriteDataBuffer[ADDRESS_2_OFFSET] =
(u8)((QspiAddr & 0xFF0000U) >> 16U);
WriteDataBuffer[ADDRESS_3_OFFSET] =
(u8)((QspiAddr & 0xFF00U) >> 8U);
WriteDataBuffer[ADDRESS_4_OFFSET] =
(u8)(QspiAddr & 0xFFU);
DiscardByteCnt = 4U;
FlashMsg[1U].TxBfrPtr = &WriteDataBuffer[ADDRESS_1_OFFSET];
FlashMsg[1U].RxBfrPtr = NULL;
FlashMsg[1U].ByteCount = DiscardByteCnt;
FlashMsg[1U].BusWidth = XQSPIPSU_SELECT_MODE_QUADSPI;
FlashMsg[1U].Flags = XQSPIPSU_MSG_FLAG_TX;
/*Dummy*/
/*Default Dummy is 6 when QPI READ MODE(ECH)*/
FlashMsg[2U].TxBfrPtr = NULL;
FlashMsg[2U].RxBfrPtr = NULL;
FlashMsg[2U].ByteCount = DUMMY_CLOCKS_MACRONIX;
FlashMsg[2U].BusWidth = XQSPIPSU_SELECT_MODE_QUADSPI;
FlashMsg[2U].Flags = 0U;
/*Data*/
FlashMsg[3U].TxBfrPtr = NULL;
FlashMsg[3U].RxBfrPtr = (u8 *)DestAddress;
FlashMsg[3U].ByteCount = TransferBytes;
FlashMsg[3U].BusWidth = XQSPIPSU_SELECT_MODE_QUADSPI;
FlashMsg[3U].Flags = XQSPIPSU_MSG_FLAG_RX;
if(QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_PARALLEL){
FlashMsg[3U].Flags |= XQSPIPSU_MSG_FLAG_STRIPE;
}
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, &FlashMsg[0U], 4U);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_READ_ERROR;
XIs_Printf(DEBUG_GENERAL,"XIS_QSPI_READ_ERROR\r\n");
goto END;
}
/* Disable QPI mode */
Status = XIs_MacronixEnableQPIMode(&QspiPsuInstance, DISABLE_QPI);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_4BYTE_ENETER_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_4BYTE_ENETER_ERROR\r\n");
goto END;
}
} else {
WriteDataBuffer[COMMAND_OFFSET] = (u8)ReadCommand;
WriteDataBuffer[ADDRESS_1_OFFSET] =
(u8)((QspiAddr & 0xFF000000U) >> 24U);
WriteDataBuffer[ADDRESS_2_OFFSET] =
(u8)((QspiAddr & 0xFF0000U) >> 16U);
WriteDataBuffer[ADDRESS_3_OFFSET] =
(u8)((QspiAddr & 0xFF00U) >> 8U);
WriteDataBuffer[ADDRESS_4_OFFSET] =
(u8)(QspiAddr & 0xFFU);
DiscardByteCnt = 5U;
FlashMsg[0U].TxBfrPtr = WriteDataBuffer;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = DiscardByteCnt;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
/*
* It is recommended to have a separate entry for dummy
*/
if ((ReadCommand == FAST_READ_CMD_32BIT) ||
(ReadCommand == DUAL_READ_CMD_32BIT) ||
(ReadCommand == QUAD_READ_CMD_32BIT)) {
/*
* It is recommended that Bus width value during dummy
* phase should be same as data phase
*/
if (ReadCommand == FAST_READ_CMD_32BIT) {
FlashMsg[1U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
}
if (ReadCommand == DUAL_READ_CMD_32BIT) {
FlashMsg[1U].BusWidth = XQSPIPSU_SELECT_MODE_DUALSPI;
}
if (ReadCommand == QUAD_READ_CMD_32BIT) {
FlashMsg[1U].BusWidth = XQSPIPSU_SELECT_MODE_QUADSPI;
}
FlashMsg[1U].TxBfrPtr = NULL;
FlashMsg[1U].RxBfrPtr = NULL;
FlashMsg[1U].ByteCount = DUMMY_CLOCKS;
FlashMsg[1U].Flags = 0U;
}
if (ReadCommand == FAST_READ_CMD_32BIT) {
FlashMsg[2U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
}
if (ReadCommand == DUAL_READ_CMD_32BIT) {
FlashMsg[2U].BusWidth = XQSPIPSU_SELECT_MODE_DUALSPI;
}
if (ReadCommand == QUAD_READ_CMD_32BIT) {
FlashMsg[2U].BusWidth = XQSPIPSU_SELECT_MODE_QUADSPI;
}
FlashMsg[2U].TxBfrPtr = NULL;
FlashMsg[2U].RxBfrPtr = (u8 *)DestAddress;
FlashMsg[2U].ByteCount = TransferBytes;
FlashMsg[2U].Flags = XQSPIPSU_MSG_FLAG_RX;
if(QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_PARALLEL){
FlashMsg[2U].Flags |= XQSPIPSU_MSG_FLAG_STRIPE;
}
/*
* Send the read command to the Flash to read the specified number
* of bytes from the Flash, send the read command and address and
* receive the specified number of bytes of data in the data buffer
*/
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, &FlashMsg[0U], 3U);
if (Status != XIS_SUCCESS) {
Status = XIS_QSPI_READ_ERROR;
XIs_Printf(DEBUG_GENERAL, "XIS_QSPI_READ_ERROR\r\n");
goto END;
}
}
/*
* Update the variables
*/
RemainingBytes -= TransferBytes;
DestAddress += TransferBytes;
SrcAddress += TransferBytes;
}
END:
return Status;
}
/*****************************************************************************/
/**
*
* This function writes to the serial Flash connected to the QSPIPSU interface.
* All the data put into the buffer must be in the same page of the device with
* page boundaries being on 256 byte boundaries.
*
* @param Address contains the address to write data to in the Flash.
* @param Pointer to the write buffer (which is to be transmitted)
* @param ByteCount contains the number of bytes to write.
*
* @return XST_SUCCESS if successful, else XST_FAILURE.
*
******************************************************************************/
static int XIs_QspiWriteData(u32 Address, u8 *WriteBfrPtr, u32 ByteCount)
{
int Status = XST_FAILURE;
u8 WriteEnableCmd;
u8 ReadStatusCmd;
u8 FlashStatus[2U];
u8 WriteCmd[5U];
u32 RealAddr;
u32 CmdByteCount;
WriteEnableCmd = WRITE_ENABLE_CMD;
/*
* Translate address based on type of connection
* If stacked assert the slave select based on address
*/
RealAddr = XIs_GetQspiAddr(Address);
/*
* Send the write enable command to the Flash so that it can be
* written to, this needs to be sent as a separate transfer before
* the write
*/
FlashMsg[0U].TxBfrPtr = &WriteEnableCmd;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, FlashMsg, 1);
if (Status != XST_SUCCESS) {
goto END;
}
WriteCmd[COMMAND_OFFSET] = WRITE_CMD;
WriteCmd[ADDRESS_1_OFFSET] =
(u8)((RealAddr & 0xFF000000U) >> 24U);
WriteCmd[ADDRESS_2_OFFSET] =
(u8)((RealAddr & 0xFF0000U) >> 16U);
WriteCmd[ADDRESS_3_OFFSET] =
(u8)((RealAddr & 0xFF00U) >> 8U);
WriteCmd[ADDRESS_4_OFFSET] =
(u8)(RealAddr & 0xFFU);
CmdByteCount = 5U;
FlashMsg[0U].TxBfrPtr = WriteCmd;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = CmdByteCount;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
FlashMsg[1U].TxBfrPtr = WriteBfrPtr;
FlashMsg[1U].RxBfrPtr = NULL;
FlashMsg[1U].ByteCount = ByteCount;
FlashMsg[1U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[1U].Flags = XQSPIPSU_MSG_FLAG_TX;
if (QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_PARALLEL) {
FlashMsg[1U].Flags |= XQSPIPSU_MSG_FLAG_STRIPE;
}
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, FlashMsg, 2U);
if (Status != XST_SUCCESS) {
goto END;
}
/*
* Wait for the write command to the Flash to be completed, it takes
* some time for the data to be written
*/
while (1U) {
ReadStatusCmd = StatusCmd;
FlashMsg[0U].TxBfrPtr = &ReadStatusCmd;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
FlashMsg[1U].TxBfrPtr = NULL;
FlashMsg[1U].RxBfrPtr = FlashStatus;
FlashMsg[1U].ByteCount = 2U;
FlashMsg[1U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[1U].Flags = XQSPIPSU_MSG_FLAG_RX;
if (QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_PARALLEL) {
FlashMsg[1U].Flags |= XQSPIPSU_MSG_FLAG_STRIPE;
}
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, FlashMsg, 2U);
if (Status != XST_SUCCESS) {
goto END;
}
if (QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_PARALLEL) {
if (FSRFlag) {
FlashStatus[1U] &= FlashStatus[0U];
} else {
FlashStatus[1U] |= FlashStatus[0U];
}
}
if (FSRFlag != 0U) {
if ((FlashStatus[1U] & 0x80U) != 0U) {
break;
}
}
else {
if ((FlashStatus[1U] & 0x01U) == 0U) {
break;
}
}
}
END:
return Status;
}
/*****************************************************************************/
/**
*
* This function erases the sectors in the serial Flash connected to the
* QSPIPSU interface.
*
* @param Address contains the address of the first sector which needs to
* be erased.
* @param ByteCount contains the total size to be erased.
* @param Pointer to the write buffer (which is to be transmitted)
*
* @return XST_SUCCESS if successful, else XST_FAILURE.
*
*****************************************************************************/
static int XIs_QspiFlashErase(u32 Address, u32 ByteCount)
{
int Status = XST_FAILURE;
u8 WriteEnableCmd;
u8 ReadStatusCmd;
u8 FlashStatus[2U];
int Sector;
u32 RealAddr;
u32 NumSect;
u8 *WriteBfrPtr = CmdBfr;
WriteEnableCmd = WRITE_ENABLE_CMD;
/*
* If the erase size is less than the total size of the flash, use
* sector erase command
*
* Calculate no. of sectors to erase based on byte count
*/
NumSect = (ByteCount / (Flash_Config.SectSize)) + 1U;
/*
* If ByteCount to k sectors,
* but the address range spans from N to N+k+1 sectors, then
* increment no. of sectors to be erased
*/
if (((Address + ByteCount) & Flash_Config.SectMask) ==
((Address + (NumSect * Flash_Config.SectSize)) &
Flash_Config.SectMask)) {
NumSect++;
}
for (Sector = 0U; Sector < NumSect; Sector++) {
/*
* Translate address based on type of connection
* If stacked assert the slave select based on address
*/
RealAddr = XIs_GetQspiAddr(Address);
/*
* Send the write enable command to the Flash so that it can be
* written to, this needs to be sent as a separate
* transfer before the write
*/
FlashMsg[0U].TxBfrPtr = &WriteEnableCmd;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, FlashMsg, 1U);
if (Status != XST_SUCCESS) {
Status = XIS_POLLED_TRANSFER_ERROR;
goto END;
}
WriteBfrPtr[COMMAND_OFFSET] = SPINOR_OP_BE_4K_4B;
/*
* To be used only if 4B address sector erase cmd is
* supported by flash
*/
WriteBfrPtr[ADDRESS_1_OFFSET] =
(u8)((RealAddr & 0xFF000000U) >> 24U);
WriteBfrPtr[ADDRESS_2_OFFSET] =
(u8)((RealAddr & 0xFF0000U) >> 16U);
WriteBfrPtr[ADDRESS_3_OFFSET] =
(u8)((RealAddr & 0xFF00U) >> 8U);
WriteBfrPtr[ADDRESS_4_OFFSET] =
(u8)(RealAddr & 0xFFU);
FlashMsg[0U].ByteCount = 5U;
FlashMsg[0U].TxBfrPtr = WriteBfrPtr;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance, FlashMsg, 1U);
if (Status != XST_SUCCESS) {
Status = XIS_POLLED_TRANSFER_ERROR;
goto END;
}
/*
* Wait for the erase command to be completed
*/
while (1U) {
ReadStatusCmd = StatusCmd;
FlashMsg[0U].TxBfrPtr = &ReadStatusCmd;
FlashMsg[0U].RxBfrPtr = NULL;
FlashMsg[0U].ByteCount = 1U;
FlashMsg[0U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[0U].Flags = XQSPIPSU_MSG_FLAG_TX;
FlashMsg[1U].TxBfrPtr = NULL;
FlashMsg[1U].RxBfrPtr = FlashStatus;
FlashMsg[1U].ByteCount = 2U;
FlashMsg[1U].BusWidth = XQSPIPSU_SELECT_MODE_SPI;
FlashMsg[1U].Flags = XQSPIPSU_MSG_FLAG_RX;
if (QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_PARALLEL) {
FlashMsg[1U].Flags |= XQSPIPSU_MSG_FLAG_STRIPE;
}
Status = XQspiPsu_PolledTransfer(&QspiPsuInstance,
FlashMsg, 2U);
if (Status != XST_SUCCESS) {
Status = XIS_POLLED_TRANSFER_ERROR;
goto END;
}
if (QspiPsuInstance.Config.ConnectionMode ==
XQSPIPSU_CONNECTION_MODE_PARALLEL) {
if (FSRFlag) {
FlashStatus[1U] &= FlashStatus[0U];
}
else {
FlashStatus[1U] |= FlashStatus[0U];
}
}
if (FSRFlag != 0U) {
if ((FlashStatus[1U] & 0x80U) != 0U) {
break;
}
}
else {
if ((FlashStatus[1U] & 0x01U) == 0U) {
break;
}
}
}
Address += Flash_Config.SectSize;
}
END:
return Status;
}
/*****************************************************************************/
/**
*
* This function writes to the serial Flash connected to the QSPIPSU interface.
* All the data put into the buffer must be in the same page of the device with
* page boundaries being on 256 byte boundaries.
*
* @param Address contains the address to write data to in the Flash.
* @param WriteDataBuffer to the write buffer (which is to be transmitted)
* @param ByteCount contains the number of bytes to write.
*
* @return XST_SUCCESS if successful, else XST_FAILURE.
*
******************************************************************************/
int XIs_QspiWrite(u32 Address, u8 *WriteDataBuffer, u32 ByteCount)
{
int Status = XST_FAILURE;
u32 PageIndex;
u32 PageCount;
PageCount = (ByteCount / PageSize);
Status = XIs_QspiFlashErase(Address, ByteCount);
if (Status != XST_SUCCESS) {
XIs_Printf(DEBUG_GENERAL, "QSPI Erase Flash failed\r\n");
goto END;
}
for(PageIndex = 0; PageIndex < PageCount; PageIndex++) {
Status = XIs_QspiWriteData(Address,
(u8 *)(WriteDataBuffer + (PageIndex * PageSize)),
PageSize);
if (Status != XST_SUCCESS) {
XIs_Printf(DEBUG_GENERAL, "QSPI Write Failed\r\n");
goto END;
}
}
END:
return Status;
}
#endif
| 17,479 |
348 |
<filename>docs/data/leg-t1/973/97302304.json
{"nom":"Kourou","circ":"2ème circonscription","dpt":"Guyane","inscrits":9788,"abs":7126,"votants":2662,"blancs":88,"nuls":43,"exp":2531,"res":[{"nuance":"REG","nom":"<NAME>","voix":699},{"nuance":"DVG","nom":"<NAME>","voix":661},{"nuance":"REM","nom":"<NAME>","voix":454},{"nuance":"DVG","nom":"Mme <NAME>","voix":279},{"nuance":"LR","nom":"Mme <NAME>","voix":209},{"nuance":"FI","nom":"<NAME>","voix":114},{"nuance":"DIV","nom":"<NAME>","voix":61},{"nuance":"DVG","nom":"<NAME>","voix":54}]}
| 217 |
2,206 |
<reponame>YunLemon/speedment<filename>runtime-parent/runtime-compute/src/test/java/com/speedment/runtime/compute/ToEnumTest.java
/*
*
* Copyright (c) 2006-2020, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.runtime.compute;
import static com.speedment.runtime.compute.expression.ExpressionType.ENUM;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.speedment.runtime.compute.util.Pair;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
final class ToEnumTest {
private static final ToEnum<String, TestEnum> DEFAULT_TO = ToEnum.of(TestEnum.class, TestEnum::valueOf);
@Test
void enumClass() {
assertEquals(TestEnum.class, DEFAULT_TO.enumClass());
}
@Test
void expressionType() {
assertEquals(ENUM, DEFAULT_TO.expressionType());
}
@ParameterizedTest
@ValueSource(strings = {"FIRST", "SECOND"})
void apply(String input) {
assertEquals(TestEnum.valueOf(input), DEFAULT_TO.apply(input));
}
@ParameterizedTest
@ValueSource(strings = {"FIRST", "SECOND"})
void asOrdinal(String input) {
ToInt<String> ordinal = DEFAULT_TO.asOrdinal();
assertEquals(TestEnum.valueOf(input).ordinal(), ordinal.applyAsInt(input));
}
@ParameterizedTest
@ValueSource(strings = {"FIRST", "SECOND"})
void asName(String input) {
ToString<String> name = DEFAULT_TO.asName();
assertEquals(TestEnum.valueOf(input).name(), name.apply(input));
}
@ParameterizedTest
@ValueSource(strings = {"FIRST", "SECOND"})
void map(String input) {
ToEnum<String, TestEnum> toEnum = DEFAULT_TO.map(clazz -> clazz);
assertEquals(DEFAULT_TO.apply(input), toEnum.apply(input));
}
@ParameterizedTest
@ValueSource(strings = {"FIRST", "SECOND"})
void hash(String input) {
assertNotEquals(0, DEFAULT_TO.hash(input));
}
@Test
void compare() {
Pair<String, String> pair1 = new Pair<>("FIRST", "FIRST");
Pair<String, String> pair2 = new Pair<>("FIRST", "SECOND");
Pair<String, String> pair3 = new Pair<>("SECOND", "FIRST");
Pair<String, String> pair4 = new Pair<>("SECOND", "SECOND");
assertEquals(0, DEFAULT_TO.compare(pair1.getFirst(), pair1.getSecond()));
assertEquals(-1, DEFAULT_TO.compare(pair2.getFirst(), pair2.getSecond()));
assertEquals(1, DEFAULT_TO.compare(pair3.getFirst(), pair3.getSecond()));
assertEquals(0, DEFAULT_TO.compare(pair4.getFirst(), pair4.getSecond()));
}
@Test
void compose() {
assertThrows(NullPointerException.class, () -> DEFAULT_TO.compose(null));
ToEnumNullable<String, TestEnum> composed = DEFAULT_TO.compose(Object::toString);
assertNotNull(composed);
}
private enum TestEnum {
FIRST,
SECOND
}
}
| 1,394 |
494 |
/**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.serializers;
import java.nio.ByteBuffer;
import com.netflix.astyanax.Serializer;
/**
* A serializer that dynamically delegates to a proper serializer based on the
* value passed
*
* @author <NAME>
*
* @param <T>
* type
*/
public class TypeInferringSerializer<T> extends AbstractSerializer<T> implements Serializer<T> {
@SuppressWarnings("rawtypes")
private static final TypeInferringSerializer instance = new TypeInferringSerializer();
@SuppressWarnings("unchecked")
public static <T> TypeInferringSerializer<T> get() {
return instance;
}
@Override
public ByteBuffer toByteBuffer(T obj) {
return SerializerTypeInferer.getSerializer(obj).toByteBuffer(obj);
}
@Override
public T fromByteBuffer(ByteBuffer byteBuffer) {
throw new IllegalStateException(
"The type inferring serializer can only be used for data going to the database, and not data coming from the database");
}
}
| 504 |
771 |
from setuptools import setup, find_packages
def build_native(spec):
# Step 1: build the rust library
build = spec.add_external_build(
cmd=['cargo', 'build', '--release'],
path='./rust'
)
# Step 2: add a cffi module based on the dylib we built
#
# We use lambdas here for dylib and header_filename so that those are
# only called after the external build finished.
spec.add_cffi_module(
module_path='example._native',
dylib=lambda: build.find_dylib('example', in_path='target/release'),
header_filename=lambda: build.find_header('example.h', in_path='.'),
rtld_flags=['NOW', 'NODELETE']
)
setup(
name='example',
version='0.0.1',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
platforms='any',
install_requires=[
'milksnake',
],
milksnake_tasks=[
build_native,
]
)
| 390 |
14,668 |
<filename>extensions/browser/api/declarative_net_request/rules_count_pair.h<gh_stars>1000+
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_RULES_COUNT_PAIR_H_
#define EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_RULES_COUNT_PAIR_H_
#include <cstddef>
namespace extensions {
namespace declarative_net_request {
// Represents the pair of total rule count and regex rule count for a ruleset.
struct RulesCountPair {
RulesCountPair();
RulesCountPair(size_t rule_count, size_t regex_rule_count);
RulesCountPair& operator+=(const RulesCountPair& that);
// This CHECKs that counts in |that| are smaller than or equal to the one in
// |this|.
RulesCountPair& operator-=(const RulesCountPair& that);
size_t rule_count = 0;
size_t regex_rule_count = 0;
};
RulesCountPair operator+(const RulesCountPair& lhs, const RulesCountPair& rhs);
// This CHECKs that counts in |rhs| are smaller than or equal to the one in
// |lhs|.
RulesCountPair operator-(const RulesCountPair& lhs, const RulesCountPair& rhs);
bool operator==(const RulesCountPair& lhs, const RulesCountPair& rhs);
} // namespace declarative_net_request
} // namespace extensions
#endif // EXTENSIONS_BROWSER_API_DECLARATIVE_NET_REQUEST_RULES_COUNT_PAIR_H_
| 484 |
1,273 |
<filename>external/tf_approxmatch.cpp<gh_stars>1000+
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include <algorithm>
#include <vector>
#include <math.h>
using namespace tensorflow;
REGISTER_OP("ApproxMatch")
.Input("xyz1: float32")
.Input("xyz2: float32")
.Output("match: float32");
REGISTER_OP("MatchCost")
.Input("xyz1: float32")
.Input("xyz2: float32")
.Input("match: float32")
.Output("cost: float32");
REGISTER_OP("MatchCostGrad")
.Input("xyz1: float32")
.Input("xyz2: float32")
.Input("match: float32")
.Output("grad1: float32")
.Output("grad2: float32");
void approxmatch_cpu(int b,int n,int m,const float * xyz1,const float * xyz2,float * match){
for (int i=0;i<b;i++){
int factorl=std::max(n,m)/n;
int factorr=std::max(n,m)/m;
std::vector<double> saturatedl(n,double(factorl)),saturatedr(m,double(factorr));
std::vector<double> weight(n*m);
for (int j=0;j<n*m;j++)
match[j]=0;
for (int j=8;j>=-2;j--){
//printf("i=%d j=%d\n",i,j);
double level=-powf(4.0,j);
if (j==-2)
level=0;
for (int k=0;k<n;k++){
double x1=xyz1[k*3+0];
double y1=xyz1[k*3+1];
double z1=xyz1[k*3+2];
for (int l=0;l<m;l++){
double x2=xyz2[l*3+0];
double y2=xyz2[l*3+1];
double z2=xyz2[l*3+2];
weight[k*m+l]=expf(level*((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2)))*saturatedr[l];
}
}
std::vector<double> ss(m,1e-9);
for (int k=0;k<n;k++){
double s=1e-9;
for (int l=0;l<m;l++){
s+=weight[k*m+l];
}
for (int l=0;l<m;l++){
weight[k*m+l]=weight[k*m+l]/s*saturatedl[k];
}
for (int l=0;l<m;l++)
ss[l]+=weight[k*m+l];
}
for (int l=0;l<m;l++){
double s=ss[l];
double r=std::min(saturatedr[l]/s,1.0);
ss[l]=r;
}
std::vector<double> ss2(m,0);
for (int k=0;k<n;k++){
double s=0;
for (int l=0;l<m;l++){
weight[k*m+l]*=ss[l];
s+=weight[k*m+l];
ss2[l]+=weight[k*m+l];
}
saturatedl[k]=std::max(saturatedl[k]-s,0.0);
}
for (int k=0;k<n*m;k++)
match[k]+=weight[k];
for (int l=0;l<m;l++){
saturatedr[l]=std::max(saturatedr[l]-ss2[l],0.0);
}
}
xyz1+=n*3;
xyz2+=m*3;
match+=n*m;
}
}
void matchcost_cpu(int b,int n,int m,const float * xyz1,const float * xyz2,const float * match,float * cost){
for (int i=0;i<b;i++){
double s=0;
for (int j=0;j<n;j++)
for (int k=0;k<m;k++){
float x1=xyz1[j*3+0];
float y1=xyz1[j*3+1];
float z1=xyz1[j*3+2];
float x2=xyz2[k*3+0];
float y2=xyz2[k*3+1];
float z2=xyz2[k*3+2];
float d=sqrtf((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1))*match[j*m+k];
s+=d;
}
cost[0]=s;
xyz1+=n*3;
xyz2+=m*3;
match+=n*m;
cost+=1;
}
}
void matchcostgrad_cpu(int b,int n,int m,const float * xyz1,const float * xyz2,const float * match,float * grad1,float * grad2){
for (int i=0;i<b;i++){
for (int j=0;j<n;j++)
grad1[j*3+0]=0;
for (int j=0;j<m;j++){
float sx=0,sy=0,sz=0;
for (int k=0;k<n;k++){
float x2=xyz2[j*3+0];
float y2=xyz2[j*3+1];
float z2=xyz2[j*3+2];
float x1=xyz1[k*3+0];
float y1=xyz1[k*3+1];
float z1=xyz1[k*3+2];
float d=std::max(sqrtf((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1)),1e-20f);
float dx=match[k*m+j]*((x2-x1)/d);
float dy=match[k*m+j]*((y2-y1)/d);
float dz=match[k*m+j]*((z2-z1)/d);
grad1[k*3+0]-=dx;
grad1[k*3+1]-=dy;
grad1[k*3+2]-=dz;
sx+=dx;
sy+=dy;
sz+=dz;
}
grad2[j*3+0]=sx;
grad2[j*3+1]=sy;
grad2[j*3+2]=sz;
}
xyz1+=n*3;
xyz2+=m*3;
match+=n*m;
grad1+=n*3;
grad2+=m*3;
}
}
void approxmatchLauncher(int b,int n,int m,const float * xyz1,const float * xyz2,float * match,float * temp);
void matchcostLauncher(int b,int n,int m,const float * xyz1,const float * xyz2,const float * match,float * out);
void matchcostgradLauncher(int b,int n,int m,const float * xyz1,const float * xyz2,const float * match,float * grad1,float * grad2);
class ApproxMatchGpuOp: public OpKernel{
public:
explicit ApproxMatchGpuOp(OpKernelConstruction* context):OpKernel(context){}
void Compute(OpKernelContext * context)override{
const Tensor& xyz1_tensor=context->input(0);
OP_REQUIRES(context,xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3,errors::InvalidArgument("ApproxMatch expects (batch_size,num_points,3) xyz1 shape"));
auto xyz1_flat=xyz1_tensor.flat<float>();
const float * xyz1=&(xyz1_flat(0));
int b=xyz1_tensor.shape().dim_size(0);
int n=xyz1_tensor.shape().dim_size(1);
//OP_REQUIRES(context,n<=4096,errors::InvalidArgument("ApproxMatch handles at most 4096 dataset points"));
const Tensor& xyz2_tensor=context->input(1);
OP_REQUIRES(context,xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3 && xyz2_tensor.shape().dim_size(0)==b,errors::InvalidArgument("ApproxMatch expects (batch_size,num_points,3) xyz2 shape, and batch_size must match"));
int m=xyz2_tensor.shape().dim_size(1);
//OP_REQUIRES(context,m<=1024,errors::InvalidArgument("ApproxMatch handles at most 1024 query points"));
auto xyz2_flat=xyz2_tensor.flat<float>();
const float * xyz2=&(xyz2_flat(0));
Tensor * match_tensor=NULL;
OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,m,n},&match_tensor));
auto match_flat=match_tensor->flat<float>();
float * match=&(match_flat(0));
Tensor temp_tensor;
OP_REQUIRES_OK(context,context->allocate_temp(DataTypeToEnum<float>::value,TensorShape{b,(n+m)*2},&temp_tensor));
auto temp_flat=temp_tensor.flat<float>();
float * temp=&(temp_flat(0));
approxmatchLauncher(b,n,m,xyz1,xyz2,match,temp);
}
};
REGISTER_KERNEL_BUILDER(Name("ApproxMatch").Device(DEVICE_GPU), ApproxMatchGpuOp);
class ApproxMatchOp: public OpKernel{
public:
explicit ApproxMatchOp(OpKernelConstruction* context):OpKernel(context){}
void Compute(OpKernelContext * context)override{
const Tensor& xyz1_tensor=context->input(0);
OP_REQUIRES(context,xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3,errors::InvalidArgument("ApproxMatch expects (batch_size,num_points,3) xyz1 shape"));
auto xyz1_flat=xyz1_tensor.flat<float>();
const float * xyz1=&(xyz1_flat(0));
int b=xyz1_tensor.shape().dim_size(0);
int n=xyz1_tensor.shape().dim_size(1);
//OP_REQUIRES(context,n<=4096,errors::InvalidArgument("ApproxMatch handles at most 4096 dataset points"));
const Tensor& xyz2_tensor=context->input(1);
OP_REQUIRES(context,xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3 && xyz2_tensor.shape().dim_size(0)==b,errors::InvalidArgument("ApproxMatch expects (batch_size,num_points,3) xyz2 shape, and batch_size must match"));
int m=xyz2_tensor.shape().dim_size(1);
//OP_REQUIRES(context,m<=1024,errors::InvalidArgument("ApproxMatch handles at most 1024 query points"));
auto xyz2_flat=xyz2_tensor.flat<float>();
const float * xyz2=&(xyz2_flat(0));
Tensor * match_tensor=NULL;
OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,m,n},&match_tensor));
auto match_flat=match_tensor->flat<float>();
float * match=&(match_flat(0));
approxmatch_cpu(b,n,m,xyz1,xyz2,match);
}
};
REGISTER_KERNEL_BUILDER(Name("ApproxMatch").Device(DEVICE_CPU), ApproxMatchOp);
class MatchCostGpuOp: public OpKernel{
public:
explicit MatchCostGpuOp(OpKernelConstruction* context):OpKernel(context){}
void Compute(OpKernelContext * context)override{
const Tensor& xyz1_tensor=context->input(0);
OP_REQUIRES(context,xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3,errors::InvalidArgument("MatchCost expects (batch_size,num_points,3) xyz1 shape"));
auto xyz1_flat=xyz1_tensor.flat<float>();
const float * xyz1=&(xyz1_flat(0));
int b=xyz1_tensor.shape().dim_size(0);
int n=xyz1_tensor.shape().dim_size(1);
const Tensor& xyz2_tensor=context->input(1);
OP_REQUIRES(context,xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3 && xyz2_tensor.shape().dim_size(0)==b,errors::InvalidArgument("MatchCost expects (batch_size,num_points,3) xyz2 shape, and batch_size must match"));
int m=xyz2_tensor.shape().dim_size(1);
auto xyz2_flat=xyz2_tensor.flat<float>();
const float * xyz2=&(xyz2_flat(0));
const Tensor& match_tensor=context->input(2);
OP_REQUIRES(context,match_tensor.dims()==3 && match_tensor.shape().dim_size(0)==b && match_tensor.shape().dim_size(1)==m && match_tensor.shape().dim_size(2)==n,errors::InvalidArgument("MatchCost expects (batch_size,#query,#dataset) match shape"));
auto match_flat=match_tensor.flat<float>();
const float * match=&(match_flat(0));
Tensor * cost_tensor=NULL;
OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b},&cost_tensor));
auto cost_flat=cost_tensor->flat<float>();
float * cost=&(cost_flat(0));
matchcostLauncher(b,n,m,xyz1,xyz2,match,cost);
}
};
REGISTER_KERNEL_BUILDER(Name("MatchCost").Device(DEVICE_GPU), MatchCostGpuOp);
class MatchCostOp: public OpKernel{
public:
explicit MatchCostOp(OpKernelConstruction* context):OpKernel(context){}
void Compute(OpKernelContext * context)override{
const Tensor& xyz1_tensor=context->input(0);
OP_REQUIRES(context,xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3,errors::InvalidArgument("MatchCost expects (batch_size,num_points,3) xyz1 shape"));
auto xyz1_flat=xyz1_tensor.flat<float>();
const float * xyz1=&(xyz1_flat(0));
int b=xyz1_tensor.shape().dim_size(0);
int n=xyz1_tensor.shape().dim_size(1);
const Tensor& xyz2_tensor=context->input(1);
OP_REQUIRES(context,xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3 && xyz2_tensor.shape().dim_size(0)==b,errors::InvalidArgument("MatchCost expects (batch_size,num_points,3) xyz2 shape, and batch_size must match"));
int m=xyz2_tensor.shape().dim_size(1);
auto xyz2_flat=xyz2_tensor.flat<float>();
const float * xyz2=&(xyz2_flat(0));
const Tensor& match_tensor=context->input(2);
OP_REQUIRES(context,match_tensor.dims()==3 && match_tensor.shape().dim_size(0)==b && match_tensor.shape().dim_size(1)==m && match_tensor.shape().dim_size(2)==n,errors::InvalidArgument("MatchCost expects (batch_size,#query,#dataset) match shape"));
auto match_flat=match_tensor.flat<float>();
const float * match=&(match_flat(0));
Tensor * cost_tensor=NULL;
OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b},&cost_tensor));
auto cost_flat=cost_tensor->flat<float>();
float * cost=&(cost_flat(0));
matchcost_cpu(b,n,m,xyz1,xyz2,match,cost);
}
};
REGISTER_KERNEL_BUILDER(Name("MatchCost").Device(DEVICE_CPU), MatchCostOp);
class MatchCostGradGpuOp: public OpKernel{
public:
explicit MatchCostGradGpuOp(OpKernelConstruction* context):OpKernel(context){}
void Compute(OpKernelContext * context)override{
const Tensor& xyz1_tensor=context->input(0);
OP_REQUIRES(context,xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3,errors::InvalidArgument("MatchCostGrad expects (batch_size,num_points,3) xyz1 shape"));
auto xyz1_flat=xyz1_tensor.flat<float>();
const float * xyz1=&(xyz1_flat(0));
int b=xyz1_tensor.shape().dim_size(0);
int n=xyz1_tensor.shape().dim_size(1);
const Tensor& xyz2_tensor=context->input(1);
OP_REQUIRES(context,xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3 && xyz2_tensor.shape().dim_size(0)==b,errors::InvalidArgument("MatchCostGrad expects (batch_size,num_points,3) xyz2 shape, and batch_size must match"));
int m=xyz2_tensor.shape().dim_size(1);
auto xyz2_flat=xyz2_tensor.flat<float>();
const float * xyz2=&(xyz2_flat(0));
const Tensor& match_tensor=context->input(2);
OP_REQUIRES(context,match_tensor.dims()==3 && match_tensor.shape().dim_size(0)==b && match_tensor.shape().dim_size(1)==m && match_tensor.shape().dim_size(2)==n,errors::InvalidArgument("MatchCost expects (batch_size,#query,#dataset) match shape"));
auto match_flat=match_tensor.flat<float>();
const float * match=&(match_flat(0));
Tensor * grad1_tensor=NULL;
OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,n,3},&grad1_tensor));
auto grad1_flat=grad1_tensor->flat<float>();
float * grad1=&(grad1_flat(0));
Tensor * grad2_tensor=NULL;
OP_REQUIRES_OK(context,context->allocate_output(1,TensorShape{b,m,3},&grad2_tensor));
auto grad2_flat=grad2_tensor->flat<float>();
float * grad2=&(grad2_flat(0));
matchcostgradLauncher(b,n,m,xyz1,xyz2,match,grad1,grad2);
}
};
REGISTER_KERNEL_BUILDER(Name("MatchCostGrad").Device(DEVICE_GPU), MatchCostGradGpuOp);
class MatchCostGradOp: public OpKernel{
public:
explicit MatchCostGradOp(OpKernelConstruction* context):OpKernel(context){}
void Compute(OpKernelContext * context)override{
const Tensor& xyz1_tensor=context->input(0);
OP_REQUIRES(context,xyz1_tensor.dims()==3 && xyz1_tensor.shape().dim_size(2)==3,errors::InvalidArgument("MatchCost expects (batch_size,num_points,3) xyz1 shape"));
auto xyz1_flat=xyz1_tensor.flat<float>();
const float * xyz1=&(xyz1_flat(0));
int b=xyz1_tensor.shape().dim_size(0);
int n=xyz1_tensor.shape().dim_size(1);
const Tensor& xyz2_tensor=context->input(1);
OP_REQUIRES(context,xyz2_tensor.dims()==3 && xyz2_tensor.shape().dim_size(2)==3 && xyz2_tensor.shape().dim_size(0)==b,errors::InvalidArgument("MatchCost expects (batch_size,num_points,3) xyz2 shape, and batch_size must match"));
int m=xyz2_tensor.shape().dim_size(1);
auto xyz2_flat=xyz2_tensor.flat<float>();
const float * xyz2=&(xyz2_flat(0));
const Tensor& match_tensor=context->input(2);
OP_REQUIRES(context,match_tensor.dims()==3 && match_tensor.shape().dim_size(0)==b && match_tensor.shape().dim_size(1)==m && match_tensor.shape().dim_size(2)==n,errors::InvalidArgument("MatchCost expects (batch_size,#query,#dataset) match shape"));
auto match_flat=match_tensor.flat<float>();
const float * match=&(match_flat(0));
Tensor * grad1_tensor=NULL;
OP_REQUIRES_OK(context,context->allocate_output(0,TensorShape{b,n,3},&grad1_tensor));
auto grad1_flat=grad1_tensor->flat<float>();
float * grad1=&(grad1_flat(0));
Tensor * grad2_tensor=NULL;
OP_REQUIRES_OK(context,context->allocate_output(1,TensorShape{b,m,3},&grad2_tensor));
auto grad2_flat=grad2_tensor->flat<float>();
float * grad2=&(grad2_flat(0));
matchcostgrad_cpu(b,n,m,xyz1,xyz2,match,grad1,grad2);
}
};
REGISTER_KERNEL_BUILDER(Name("MatchCostGrad").Device(DEVICE_CPU), MatchCostGradOp);
| 6,814 |
466 |
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CXformImplementTVFNoArgs.h
//
// @doc:
// Implement logical TVF with a physical TVF with no arguments
//---------------------------------------------------------------------------
#ifndef GPOPT_CXformImplementTVFNoArgs_H
#define GPOPT_CXformImplementTVFNoArgs_H
#include "gpos/base.h"
#include "gpopt/xforms/CXformImplementTVF.h"
namespace gpopt
{
using namespace gpos;
//---------------------------------------------------------------------------
// @class:
// CXformImplementTVFNoArgs
//
// @doc:
// Implement TVF with no arguments
//
//---------------------------------------------------------------------------
class CXformImplementTVFNoArgs : public CXformImplementTVF
{
private:
// private copy ctor
CXformImplementTVFNoArgs(const CXformImplementTVFNoArgs &);
public:
// ctor
explicit CXformImplementTVFNoArgs(CMemoryPool *mp);
// dtor
virtual ~CXformImplementTVFNoArgs()
{
}
// ident accessors
virtual EXformId
Exfid() const
{
return ExfImplementTVFNoArgs;
}
// return a string for xform name
virtual const CHAR *
SzId() const
{
return "CXformImplementTVFNoArgs";
}
}; // class CXformImplementTVFNoArgs
} // namespace gpopt
#endif // !GPOPT_CXformImplementTVFNoArgs_H
// EOF
| 451 |
507 |
<filename>terrascript/fortimanager/r.py
# terrascript/fortimanager/r.py
# Automatically generated by tools/makecode.py ()
import warnings
warnings.warn(
"using the 'legacy layout' is deprecated", DeprecationWarning, stacklevel=2
)
import terrascript
class fortimanager_dvm_cmd_add_device(terrascript.Resource):
pass
class fortimanager_dvm_cmd_del_device(terrascript.Resource):
pass
class fortimanager_dvm_cmd_update_device(terrascript.Resource):
pass
class fortimanager_dvmdb_adom(terrascript.Resource):
pass
class fortimanager_dvmdb_group(terrascript.Resource):
pass
class fortimanager_dvmdb_revision(terrascript.Resource):
pass
class fortimanager_dvmdb_script(terrascript.Resource):
pass
class fortimanager_dvmdb_script_execute(terrascript.Resource):
pass
class fortimanager_exec_workspace_action(terrascript.Resource):
pass
class fortimanager_fmupdate_analyzer_virusreport(terrascript.Resource):
pass
class fortimanager_fmupdate_avips_advancedlog(terrascript.Resource):
pass
class fortimanager_fmupdate_avips_webproxy(terrascript.Resource):
pass
class fortimanager_fmupdate_customurllist(terrascript.Resource):
pass
class fortimanager_fmupdate_diskquota(terrascript.Resource):
pass
class fortimanager_fmupdate_fctservices(terrascript.Resource):
pass
class fortimanager_fmupdate_fdssetting(terrascript.Resource):
pass
class fortimanager_fmupdate_fdssetting_pushoverride(terrascript.Resource):
pass
class fortimanager_fmupdate_fdssetting_pushoverridetoclient(terrascript.Resource):
pass
class fortimanager_fmupdate_fdssetting_serveroverride(terrascript.Resource):
pass
class fortimanager_fmupdate_fdssetting_updateschedule(terrascript.Resource):
pass
class fortimanager_fmupdate_fwmsetting(terrascript.Resource):
pass
class fortimanager_fmupdate_multilayer(terrascript.Resource):
pass
class fortimanager_fmupdate_publicnetwork(terrascript.Resource):
pass
class fortimanager_fmupdate_serveraccesspriorities(terrascript.Resource):
pass
class fortimanager_fmupdate_serveroverridestatus(terrascript.Resource):
pass
class fortimanager_fmupdate_service(terrascript.Resource):
pass
class fortimanager_fmupdate_webspam_fgdsetting(terrascript.Resource):
pass
class fortimanager_fmupdate_webspam_webproxy(terrascript.Resource):
pass
class fortimanager_json_generic_api(terrascript.Resource):
pass
class fortimanager_object_adom_options(terrascript.Resource):
pass
class fortimanager_object_antivirus_mmschecksum(terrascript.Resource):
pass
class fortimanager_object_antivirus_notification(terrascript.Resource):
pass
class fortimanager_object_antivirus_profile(terrascript.Resource):
pass
class fortimanager_object_application_categories(terrascript.Resource):
pass
class fortimanager_object_application_custom(terrascript.Resource):
pass
class fortimanager_object_application_group(terrascript.Resource):
pass
class fortimanager_object_application_list(terrascript.Resource):
pass
class fortimanager_object_authentication_scheme(terrascript.Resource):
pass
class fortimanager_object_certificate_template(terrascript.Resource):
pass
class fortimanager_object_cifs_profile(terrascript.Resource):
pass
class fortimanager_object_cli_template(terrascript.Resource):
pass
class fortimanager_object_cli_templategroup(terrascript.Resource):
pass
class fortimanager_object_credentialstore_domaincontroller(terrascript.Resource):
pass
class fortimanager_object_dlp_filepattern(terrascript.Resource):
pass
class fortimanager_object_dlp_sensitivity(terrascript.Resource):
pass
class fortimanager_object_dlp_sensor(terrascript.Resource):
pass
class fortimanager_object_dnsfilter_domainfilter(terrascript.Resource):
pass
class fortimanager_object_dnsfilter_profile(terrascript.Resource):
pass
class fortimanager_object_dynamic_address(terrascript.Resource):
pass
class fortimanager_object_dynamic_certificate_local(terrascript.Resource):
pass
class fortimanager_object_dynamic_interface(terrascript.Resource):
pass
class fortimanager_object_dynamic_ippool(terrascript.Resource):
pass
class fortimanager_object_dynamic_multicast_interface(terrascript.Resource):
pass
class fortimanager_object_dynamic_vip(terrascript.Resource):
pass
class fortimanager_object_dynamic_vpntunnel(terrascript.Resource):
pass
class fortimanager_object_emailfilter_blockallowlist(terrascript.Resource):
pass
class fortimanager_object_emailfilter_bwl(terrascript.Resource):
pass
class fortimanager_object_emailfilter_bword(terrascript.Resource):
pass
class fortimanager_object_emailfilter_dnsbl(terrascript.Resource):
pass
class fortimanager_object_emailfilter_fortishield(terrascript.Resource):
pass
class fortimanager_object_emailfilter_iptrust(terrascript.Resource):
pass
class fortimanager_object_emailfilter_mheader(terrascript.Resource):
pass
class fortimanager_object_emailfilter_options(terrascript.Resource):
pass
class fortimanager_object_emailfilter_profile(terrascript.Resource):
pass
class fortimanager_object_extendercontroller_dataplan(terrascript.Resource):
pass
class fortimanager_object_extendercontroller_sim_profile(terrascript.Resource):
pass
class fortimanager_object_extendercontroller_template(terrascript.Resource):
pass
class fortimanager_object_filefilter_profile(terrascript.Resource):
pass
class fortimanager_object_firewall_accessproxy(terrascript.Resource):
pass
class fortimanager_object_firewall_accessproxy_move(terrascript.Resource):
pass
class fortimanager_object_firewall_address(terrascript.Resource):
pass
class fortimanager_object_firewall_address6(terrascript.Resource):
pass
class fortimanager_object_firewall_address6template(terrascript.Resource):
pass
class fortimanager_object_firewall_addrgrp(terrascript.Resource):
pass
class fortimanager_object_firewall_addrgrp6(terrascript.Resource):
pass
class fortimanager_object_firewall_carrierendpointbwl(terrascript.Resource):
pass
class fortimanager_object_firewall_decryptedtrafficmirror(terrascript.Resource):
pass
class fortimanager_object_firewall_identitybasedroute(terrascript.Resource):
pass
class fortimanager_object_firewall_internetservice(terrascript.Resource):
pass
class fortimanager_object_firewall_internetserviceaddition(terrascript.Resource):
pass
class fortimanager_object_firewall_internetservicecustom(terrascript.Resource):
pass
class fortimanager_object_firewall_internetservicecustomgroup(terrascript.Resource):
pass
class fortimanager_object_firewall_internetservicegroup(terrascript.Resource):
pass
class fortimanager_object_firewall_internetservicename(terrascript.Resource):
pass
class fortimanager_object_firewall_ippool(terrascript.Resource):
pass
class fortimanager_object_firewall_ippool6(terrascript.Resource):
pass
class fortimanager_object_firewall_ldbmonitor(terrascript.Resource):
pass
class fortimanager_object_firewall_mmsprofile(terrascript.Resource):
pass
class fortimanager_object_firewall_multicastaddress(terrascript.Resource):
pass
class fortimanager_object_firewall_multicastaddress6(terrascript.Resource):
pass
class fortimanager_object_firewall_profilegroup(terrascript.Resource):
pass
class fortimanager_object_firewall_profileprotocoloptions(terrascript.Resource):
pass
class fortimanager_object_firewall_proxyaddress(terrascript.Resource):
pass
class fortimanager_object_firewall_proxyaddrgrp(terrascript.Resource):
pass
class fortimanager_object_firewall_schedule_group(terrascript.Resource):
pass
class fortimanager_object_firewall_schedule_onetime(terrascript.Resource):
pass
class fortimanager_object_firewall_schedule_recurring(terrascript.Resource):
pass
class fortimanager_object_firewall_service_category(terrascript.Resource):
pass
class fortimanager_object_firewall_service_custom(terrascript.Resource):
pass
class fortimanager_object_firewall_service_group(terrascript.Resource):
pass
class fortimanager_object_firewall_shaper_peripshaper(terrascript.Resource):
pass
class fortimanager_object_firewall_shaper_trafficshaper(terrascript.Resource):
pass
class fortimanager_object_firewall_ssh_localca(terrascript.Resource):
pass
class fortimanager_object_firewall_sslsshprofile(terrascript.Resource):
pass
class fortimanager_object_firewall_trafficclass(terrascript.Resource):
pass
class fortimanager_object_firewall_vip(terrascript.Resource):
pass
class fortimanager_object_firewall_vip46(terrascript.Resource):
pass
class fortimanager_object_firewall_vip6(terrascript.Resource):
pass
class fortimanager_object_firewall_vip64(terrascript.Resource):
pass
class fortimanager_object_firewall_vipgrp(terrascript.Resource):
pass
class fortimanager_object_firewall_vipgrp46(terrascript.Resource):
pass
class fortimanager_object_firewall_vipgrp6(terrascript.Resource):
pass
class fortimanager_object_firewall_vipgrp64(terrascript.Resource):
pass
class fortimanager_object_firewall_wildcardfqdn_custom(terrascript.Resource):
pass
class fortimanager_object_firewall_wildcardfqdn_group(terrascript.Resource):
pass
class fortimanager_object_fsp_vlan(terrascript.Resource):
pass
class fortimanager_object_icap_profile(terrascript.Resource):
pass
class fortimanager_object_icap_server(terrascript.Resource):
pass
class fortimanager_object_ips_custom(terrascript.Resource):
pass
class fortimanager_object_ips_sensor(terrascript.Resource):
pass
class fortimanager_object_log_customfield(terrascript.Resource):
pass
class fortimanager_object_sshfilter_profile(terrascript.Resource):
pass
class fortimanager_object_switchcontroller_customcommand(terrascript.Resource):
pass
class fortimanager_object_switchcontroller_lldpprofile(terrascript.Resource):
pass
class fortimanager_object_switchcontroller_qos_dot1pmap(terrascript.Resource):
pass
class fortimanager_object_switchcontroller_qos_ipdscpmap(terrascript.Resource):
pass
class fortimanager_object_switchcontroller_qos_qospolicy(terrascript.Resource):
pass
class fortimanager_object_switchcontroller_qos_queuepolicy(terrascript.Resource):
pass
class fortimanager_object_switchcontroller_securitypolicy_8021x(terrascript.Resource):
pass
class fortimanager_object_system_customlanguage(terrascript.Resource):
pass
class fortimanager_object_system_dhcp_server(terrascript.Resource):
pass
class fortimanager_object_system_externalresource(terrascript.Resource):
pass
class fortimanager_object_system_fortiguard(terrascript.Resource):
pass
class fortimanager_object_system_geoipcountry(terrascript.Resource):
pass
class fortimanager_object_system_geoipoverride(terrascript.Resource):
pass
class fortimanager_object_system_meta(terrascript.Resource):
pass
class fortimanager_object_system_objecttagging(terrascript.Resource):
pass
class fortimanager_object_system_replacemsggroup(terrascript.Resource):
pass
class fortimanager_object_system_replacemsgimage(terrascript.Resource):
pass
class fortimanager_object_system_sdnconnector(terrascript.Resource):
pass
class fortimanager_object_system_smsserver(terrascript.Resource):
pass
class fortimanager_object_system_virtualwirepair(terrascript.Resource):
pass
class fortimanager_object_user_adgrp(terrascript.Resource):
pass
class fortimanager_object_user_clearpass(terrascript.Resource):
pass
class fortimanager_object_user_device(terrascript.Resource):
pass
class fortimanager_object_user_domaincontroller(terrascript.Resource):
pass
class fortimanager_object_user_exchange(terrascript.Resource):
pass
class fortimanager_object_user_fortitoken(terrascript.Resource):
pass
class fortimanager_object_user_fsso(terrascript.Resource):
pass
class fortimanager_object_user_fssopolling(terrascript.Resource):
pass
class fortimanager_object_user_group(terrascript.Resource):
pass
class fortimanager_object_user_krbkeytab(terrascript.Resource):
pass
class fortimanager_object_user_ldap(terrascript.Resource):
pass
class fortimanager_object_user_local(terrascript.Resource):
pass
class fortimanager_object_user_nsx(terrascript.Resource):
pass
class fortimanager_object_user_passwordpolicy(terrascript.Resource):
pass
class fortimanager_object_user_peer(terrascript.Resource):
pass
class fortimanager_object_user_peergrp(terrascript.Resource):
pass
class fortimanager_object_user_pop3(terrascript.Resource):
pass
class fortimanager_object_user_pxgrid(terrascript.Resource):
pass
class fortimanager_object_user_radius(terrascript.Resource):
pass
class fortimanager_object_user_saml(terrascript.Resource):
pass
class fortimanager_object_user_securityexemptlist(terrascript.Resource):
pass
class fortimanager_object_user_tacacs(terrascript.Resource):
pass
class fortimanager_object_user_vcenter(terrascript.Resource):
pass
class fortimanager_object_videofilter_profile(terrascript.Resource):
pass
class fortimanager_object_videofilter_youtubechannelfilter(terrascript.Resource):
pass
class fortimanager_object_voip_profile(terrascript.Resource):
pass
class fortimanager_object_vpn_certificate_ca(terrascript.Resource):
pass
class fortimanager_object_vpn_certificate_ocspserver(terrascript.Resource):
pass
class fortimanager_object_vpn_certificate_remote(terrascript.Resource):
pass
class fortimanager_object_vpn_ssl_web_hostchecksoftware(terrascript.Resource):
pass
class fortimanager_object_vpn_ssl_web_portal(terrascript.Resource):
pass
class fortimanager_object_vpn_ssl_web_realm(terrascript.Resource):
pass
class fortimanager_object_vpnmgr_node(terrascript.Resource):
pass
class fortimanager_object_waf_mainclass(terrascript.Resource):
pass
class fortimanager_object_waf_profile(terrascript.Resource):
pass
class fortimanager_object_waf_signature(terrascript.Resource):
pass
class fortimanager_object_waf_subclass(terrascript.Resource):
pass
class fortimanager_object_wanopt_authgroup(terrascript.Resource):
pass
class fortimanager_object_wanopt_peer(terrascript.Resource):
pass
class fortimanager_object_wanopt_profile(terrascript.Resource):
pass
class fortimanager_object_webfilter_categories(terrascript.Resource):
pass
class fortimanager_object_webfilter_content(terrascript.Resource):
pass
class fortimanager_object_webfilter_contentheader(terrascript.Resource):
pass
class fortimanager_object_webfilter_ftgdlocalcat(terrascript.Resource):
pass
class fortimanager_object_webfilter_ftgdlocalrating(terrascript.Resource):
pass
class fortimanager_object_webfilter_profile(terrascript.Resource):
pass
class fortimanager_object_webfilter_urlfilter(terrascript.Resource):
pass
class fortimanager_object_webproxy_forwardserver(terrascript.Resource):
pass
class fortimanager_object_webproxy_forwardservergroup(terrascript.Resource):
pass
class fortimanager_object_webproxy_profile(terrascript.Resource):
pass
class fortimanager_object_webproxy_wisp(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_bleprofile(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_hotspot20_anqp3gppcellular(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_anqpipaddresstype(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_anqpnairealm(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_anqpnetworkauthtype(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_anqproamingconsortium(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_anqpvenuename(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_h2qpconncapability(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_h2qpoperatorname(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_h2qposuprovider(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_h2qpwanmetric(
terrascript.Resource
):
pass
class fortimanager_object_wirelesscontroller_hotspot20_hsprofile(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_hotspot20_qosmap(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_mpskprofile(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_qosprofile(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_utmprofile(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_vap(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_vapgroup(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_wagprofile(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_widsprofile(terrascript.Resource):
pass
class fortimanager_object_wirelesscontroller_wtpprofile(terrascript.Resource):
pass
class fortimanager_packages_authentication_rule(terrascript.Resource):
pass
class fortimanager_packages_authentication_setting(terrascript.Resource):
pass
class fortimanager_packages_firewall_centralsnatmap(terrascript.Resource):
pass
class fortimanager_packages_firewall_centralsnatmap_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_consolidated_policy(terrascript.Resource):
pass
class fortimanager_packages_firewall_consolidated_policy_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_dospolicy(terrascript.Resource):
pass
class fortimanager_packages_firewall_dospolicy6(terrascript.Resource):
pass
class fortimanager_packages_firewall_dospolicy6_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_dospolicy_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_interfacepolicy(terrascript.Resource):
pass
class fortimanager_packages_firewall_interfacepolicy6(terrascript.Resource):
pass
class fortimanager_packages_firewall_interfacepolicy6_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_interfacepolicy_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_localinpolicy(terrascript.Resource):
pass
class fortimanager_packages_firewall_localinpolicy6(terrascript.Resource):
pass
class fortimanager_packages_firewall_localinpolicy6_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_localinpolicy_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_multicastpolicy(terrascript.Resource):
pass
class fortimanager_packages_firewall_multicastpolicy6(terrascript.Resource):
pass
class fortimanager_packages_firewall_multicastpolicy6_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_multicastpolicy_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_policy(terrascript.Resource):
pass
class fortimanager_packages_firewall_policy46(terrascript.Resource):
pass
class fortimanager_packages_firewall_policy46_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_policy6(terrascript.Resource):
pass
class fortimanager_packages_firewall_policy64(terrascript.Resource):
pass
class fortimanager_packages_firewall_policy64_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_policy6_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_policy_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_proxypolicy(terrascript.Resource):
pass
class fortimanager_packages_firewall_proxypolicy_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_securitypolicy(terrascript.Resource):
pass
class fortimanager_packages_firewall_securitypolicy_move(terrascript.Resource):
pass
class fortimanager_packages_firewall_shapingpolicy(terrascript.Resource):
pass
class fortimanager_packages_firewall_shapingpolicy_move(terrascript.Resource):
pass
class fortimanager_packages_global_footer_consolidated_policy(terrascript.Resource):
pass
class fortimanager_packages_global_footer_policy(terrascript.Resource):
pass
class fortimanager_packages_global_footer_policy6(terrascript.Resource):
pass
class fortimanager_packages_global_footer_shapingpolicy(terrascript.Resource):
pass
class fortimanager_packages_global_header_consolidated_policy(terrascript.Resource):
pass
class fortimanager_packages_global_header_policy(terrascript.Resource):
pass
class fortimanager_packages_global_header_policy6(terrascript.Resource):
pass
class fortimanager_packages_global_header_shapingpolicy(terrascript.Resource):
pass
class fortimanager_packages_pkg(terrascript.Resource):
pass
class fortimanager_securityconsole_abort(terrascript.Resource):
pass
class fortimanager_securityconsole_install_device(terrascript.Resource):
pass
class fortimanager_securityconsole_install_package(terrascript.Resource):
pass
class fortimanager_securityconsole_install_preview(terrascript.Resource):
pass
class fortimanager_securityconsole_package_cancel_install(terrascript.Resource):
pass
class fortimanager_securityconsole_package_clone(terrascript.Resource):
pass
class fortimanager_securityconsole_package_commit(terrascript.Resource):
pass
class fortimanager_securityconsole_package_move(terrascript.Resource):
pass
class fortimanager_securityconsole_pblock_clone(terrascript.Resource):
pass
class fortimanager_securityconsole_reinstall_package(terrascript.Resource):
pass
class fortimanager_securityconsole_sign_certificate_template(terrascript.Resource):
pass
class fortimanager_system_admin_group(terrascript.Resource):
pass
class fortimanager_system_admin_ldap(terrascript.Resource):
pass
class fortimanager_system_admin_profile(terrascript.Resource):
pass
class fortimanager_system_admin_radius(terrascript.Resource):
pass
class fortimanager_system_admin_setting(terrascript.Resource):
pass
class fortimanager_system_admin_tacacs(terrascript.Resource):
pass
class fortimanager_system_admin_user(terrascript.Resource):
pass
class fortimanager_system_alertconsole(terrascript.Resource):
pass
class fortimanager_system_alertemail(terrascript.Resource):
pass
class fortimanager_system_alertevent(terrascript.Resource):
pass
class fortimanager_system_autodelete(terrascript.Resource):
pass
class fortimanager_system_autodelete_dlpfilesautodeletion(terrascript.Resource):
pass
class fortimanager_system_autodelete_logautodeletion(terrascript.Resource):
pass
class fortimanager_system_autodelete_quarantinefilesautodeletion(terrascript.Resource):
pass
class fortimanager_system_autodelete_reportautodeletion(terrascript.Resource):
pass
class fortimanager_system_backup_allsettings(terrascript.Resource):
pass
class fortimanager_system_certificate_ca(terrascript.Resource):
pass
class fortimanager_system_certificate_crl(terrascript.Resource):
pass
class fortimanager_system_certificate_local(terrascript.Resource):
pass
class fortimanager_system_certificate_oftp(terrascript.Resource):
pass
class fortimanager_system_certificate_remote(terrascript.Resource):
pass
class fortimanager_system_certificate_ssh(terrascript.Resource):
pass
class fortimanager_system_connector(terrascript.Resource):
pass
class fortimanager_system_dm(terrascript.Resource):
pass
class fortimanager_system_dns(terrascript.Resource):
pass
class fortimanager_system_docker(terrascript.Resource):
pass
class fortimanager_system_fips(terrascript.Resource):
pass
class fortimanager_system_fortiview_autocache(terrascript.Resource):
pass
class fortimanager_system_fortiview_setting(terrascript.Resource):
pass
class fortimanager_system_global(terrascript.Resource):
pass
class fortimanager_system_guiact(terrascript.Resource):
pass
class fortimanager_system_ha(terrascript.Resource):
pass
class fortimanager_system_ha_peer(terrascript.Resource):
pass
class fortimanager_system_interface(terrascript.Resource):
pass
class fortimanager_system_locallog_disk_filter(terrascript.Resource):
pass
class fortimanager_system_locallog_disk_setting(terrascript.Resource):
pass
class fortimanager_system_locallog_fortianalyzer2_filter(terrascript.Resource):
pass
class fortimanager_system_locallog_fortianalyzer2_setting(terrascript.Resource):
pass
class fortimanager_system_locallog_fortianalyzer3_filter(terrascript.Resource):
pass
class fortimanager_system_locallog_fortianalyzer3_setting(terrascript.Resource):
pass
class fortimanager_system_locallog_fortianalyzer_filter(terrascript.Resource):
pass
class fortimanager_system_locallog_fortianalyzer_setting(terrascript.Resource):
pass
class fortimanager_system_locallog_memory_filter(terrascript.Resource):
pass
class fortimanager_system_locallog_memory_setting(terrascript.Resource):
pass
class fortimanager_system_locallog_setting(terrascript.Resource):
pass
class fortimanager_system_locallog_syslogd2_filter(terrascript.Resource):
pass
class fortimanager_system_locallog_syslogd2_setting(terrascript.Resource):
pass
class fortimanager_system_locallog_syslogd3_filter(terrascript.Resource):
pass
class fortimanager_system_locallog_syslogd3_setting(terrascript.Resource):
pass
class fortimanager_system_locallog_syslogd_filter(terrascript.Resource):
pass
class fortimanager_system_locallog_syslogd_setting(terrascript.Resource):
pass
class fortimanager_system_log_alert(terrascript.Resource):
pass
class fortimanager_system_log_devicedisable(terrascript.Resource):
pass
class fortimanager_system_log_interfacestats(terrascript.Resource):
pass
class fortimanager_system_log_ioc(terrascript.Resource):
pass
class fortimanager_system_log_maildomain(terrascript.Resource):
pass
class fortimanager_system_log_ratelimit(terrascript.Resource):
pass
class fortimanager_system_log_ratelimit_device(terrascript.Resource):
pass
class fortimanager_system_log_settings(terrascript.Resource):
pass
class fortimanager_system_log_settings_rollinganalyzer(terrascript.Resource):
pass
class fortimanager_system_log_settings_rollinglocal(terrascript.Resource):
pass
class fortimanager_system_log_settings_rollingregular(terrascript.Resource):
pass
class fortimanager_system_logfetch_clientprofile(terrascript.Resource):
pass
class fortimanager_system_logfetch_serversettings(terrascript.Resource):
pass
class fortimanager_system_mail(terrascript.Resource):
pass
class fortimanager_system_metadata_admins(terrascript.Resource):
pass
class fortimanager_system_ntp(terrascript.Resource):
pass
class fortimanager_system_ntp_ntpserver(terrascript.Resource):
pass
class fortimanager_system_passwordpolicy(terrascript.Resource):
pass
class fortimanager_system_report_autocache(terrascript.Resource):
pass
class fortimanager_system_report_estbrowsetime(terrascript.Resource):
pass
class fortimanager_system_report_setting(terrascript.Resource):
pass
class fortimanager_system_route(terrascript.Resource):
pass
class fortimanager_system_route6(terrascript.Resource):
pass
class fortimanager_system_saml(terrascript.Resource):
pass
class fortimanager_system_saml_fabricidp(terrascript.Resource):
pass
class fortimanager_system_saml_serviceproviders(terrascript.Resource):
pass
class fortimanager_system_sniffer(terrascript.Resource):
pass
class fortimanager_system_snmp_community(terrascript.Resource):
pass
class fortimanager_system_snmp_sysinfo(terrascript.Resource):
pass
class fortimanager_system_snmp_user(terrascript.Resource):
pass
class fortimanager_system_socfabric(terrascript.Resource):
pass
class fortimanager_system_sql(terrascript.Resource):
pass
class fortimanager_system_sql_customindex(terrascript.Resource):
pass
class fortimanager_system_sql_customskipidx(terrascript.Resource):
pass
class fortimanager_system_sql_tsindexfield(terrascript.Resource):
pass
class fortimanager_system_syslog(terrascript.Resource):
pass
class fortimanager_system_workflow_approvalmatrix(terrascript.Resource):
pass
| 9,805 |
746 |
<gh_stars>100-1000
package proton.inject;
import javax.inject.Inject;
import android.accounts.AccountManager;
import android.app.Application;
import android.test.AndroidTestCase;
public class AccountManagerInjectionTest extends AndroidTestCase {
private Injector mInjector;
@Override
protected void setUp() throws Exception {
super.setUp();
Proton.initialize((Application) getContext().getApplicationContext());
mInjector = Proton.getInjector(getContext());
}
@Override
protected void tearDown() throws Exception {
Proton.destroy();
super.tearDown();
}
public void testInject() {
Client c = mInjector.inject(new Client());
assertNotNull(c.accountManager);
}
public static class Client {
@Inject
private AccountManager accountManager;
}
}
| 252 |
339 |
<filename>convlab2/dst/comer/multiwoz/__init__.py
from convlab2.dst.comer.multiwoz.comer import ComerTracker as COMER
| 49 |
566 |
try:
from importlib.metadata import PackageNotFoundError, version
except ImportError:
from importlib_metadata import PackageNotFoundError, version
try:
__version__ = version("django-configurations")
except PackageNotFoundError:
# package is not installed
__version__ = None
| 85 |
1,213 |
/*
* Copyright (c) 2021. https://github.com/geemion
* 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 <sstream>
#include "beacon_req.h"
#include "teamrpc.pb.h"
#include "taskdata.pb.h"
extern const std::string MSGID_NAME[c2::MSGID_ARRAYSIZE] = { "PUBKEY_REQ","PUBKEY_RSP","AUTH_REQ","AUTH_RSP",
"HOST_INFO_REQ","HOST_INFO_RSP","HEAT_BEAT_REQ","PROCESS_INFO","PROCESS_KILL","PROCESS_INJECT","DISK_LIST","FILE_LIST",
"DOWNLOAD_FILE","UPLOAD_FILE","EXEC_FILE", "CMD_COMMAND","ERROR_RSP","DELETE_FILE" };
beacon_req::beacon_req(PolyM::Queue* mq, log_func func) :req_mq_(mq), log_out_(func)
{
}
void beacon_req::send_get_host_info(const std::string& beacon_id)
{
return put_cmd_req(beacon_id, c2::HOST_INFO_REQ);
}
void beacon_req::send_get_process_list(const std::string& beacon_id)
{
return put_cmd_req(beacon_id, c2::PROCESS_INFO);
}
void beacon_req::send_kill_process(const std::string& beacon_id, int pid)
{
c2::IntParam param;
param.set_param(pid);
std::vector<char> data(param.ByteSizeLong());
param.SerializeToArray(data.data(), data.size());
return put_cmd_req(beacon_id, c2::PROCESS_KILL, data.data(), data.size());
}
void beacon_req::send_get_disk_list(const std::string& beacon_id)
{
return put_cmd_req(beacon_id, c2::DISK_LIST);
}
void beacon_req::send_get_file_list(const std::string& beacon_id, const std::string& dir)
{
return put_strparam_req(beacon_id, c2::FILE_LIST, dir);
}
void beacon_req::send_upload_file(const std::string& beacon_id, const std::string& upload_dir, const std::string& file_name, const QByteArray& file_data)
{
c2::UploadFile upload_data;
upload_data.set_upload_dir(upload_dir);
upload_data.set_file_name(file_name);
upload_data.set_file_data(file_data.data(), file_data.size());
std::vector<char> data(upload_data.ByteSizeLong());
upload_data.SerializeToArray(data.data(), data.size());
return put_cmd_req(beacon_id, c2::UPLOAD_FILE, data.data(), data.size());
}
void beacon_req::send_delete_file(const std::string& beacon_id, const std::string& file_path)
{
return put_strparam_req(beacon_id, c2::DELETE_FILE, file_path);
}
void beacon_req::send_download_file(const std::string& beacon_id, const std::string& file_path)
{
return put_strparam_req(beacon_id, c2::DOWNLOAD_FILE, file_path);
}
void beacon_req::send_exec_file(const std::string& beacon_id, const std::string& file_path)
{
return put_strparam_req(beacon_id, c2::EXEC_FILE, file_path);
}
void beacon_req::send_shell_cmd(const std::string& beacon_id, const std::string& path, const std::string& cmd)
{
c2::CMDPARAM param;
param.set_current_dir(path);
param.set_cmd(cmd);
std::vector<char> data(param.ByteSizeLong());
param.SerializeToArray(data.data(), data.size());
return put_cmd_req(beacon_id, c2::CMD_COMMAND, data.data(), data.size());
}
void beacon_req::put_strparam_req(const std::string& beacon_id, int msg_id, const std::string str_param)
{
c2::StrParam param;
param.set_param(str_param);
std::vector<char> data(param.ByteSizeLong());
param.SerializeToArray(data.data(), data.size());
return put_cmd_req(beacon_id, msg_id, data.data(), data.size());
}
void beacon_req::put_cmd_req(const std::string& beacon_id, int msg_id, const void* byte_value/*=nullptr*/, size_t byte_value_size/*=0*/)
{
c2::CommandReq req;
req.set_beacon_id(beacon_id);
req.set_msg_id(msg_id);
if (byte_value != nullptr && byte_value_size != 0)
req.set_byte_value(byte_value, byte_value_size);
std::ostringstream log_stream;
log_stream << "[*] " << "send command:" << beacon_id << " " << MSGID_NAME[msg_id] << "(" << msg_id << ")" << std::endl;
log_out_(log_stream.str());
auto size = req.ByteSizeLong();
std::vector<char> data(size);
req.SerializePartialToArray(data.data(), size);
req_mq_->put(PolyM::DataMsg<std::vector<char>>(1, data));
}
| 1,628 |
5,169 |
<filename>Specs/0/9/8/GYCalendar/1.1.1/GYCalendar.podspec.json
{
"name": "GYCalendar",
"version": "1.1.1",
"summary": "A little kit of calendar which you can custom-made",
"homepage": "https://github.com/ShinyG",
"license": "MIT",
"authors": {
"ShinyG": "<EMAIL>"
},
"source": {
"git": "https://github.com/ShinyG/GYCalendar.git",
"tag": "1.1.1"
},
"platforms": {
"ios": "6.0"
},
"source_files": "GYCalendar/*.{h,m,xib}",
"resources": "GYCalendar/*.xib"
}
| 227 |
14,668 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_INTERRUPT_REASONS_H_
#define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_INTERRUPT_REASONS_H_
#include <string>
#include "components/download/public/common/download_export.h"
namespace download {
enum DownloadInterruptReason {
DOWNLOAD_INTERRUPT_REASON_NONE = 0,
#define INTERRUPT_REASON(name, value) DOWNLOAD_INTERRUPT_REASON_##name = value,
#include "components/download/public/common/download_interrupt_reason_values.h"
#undef INTERRUPT_REASON
};
std::string COMPONENTS_DOWNLOAD_EXPORT
DownloadInterruptReasonToString(DownloadInterruptReason error);
} // namespace download
#endif // COMPONENTS_DOWNLOAD_PUBLIC_COMMON_DOWNLOAD_INTERRUPT_REASONS_H_
| 302 |
3,142 |
<filename>tests/rest_api/utils/dump_objects.py<gh_stars>1000+
import os
import requests
import json
import config
with requests.Session() as session:
session.auth = ('admin1', config.USER_PASS)
for obj in ['user', 'project', 'task', 'job', 'organization', 'membership',
'invitation']:
response = session.get(f'http://localhost:8080/api/v1/{obj}s?page_size=all')
with open(os.path.join(config.ASSETS_DIR, f'{obj}s.json'), 'w') as f:
json.dump(response.json(), f, indent=2, sort_keys=True)
| 214 |
879 |
<filename>header/src/main/java/org/zstack/header/network/l2/APIAttachL2NetworkToClusterEvent.java
package org.zstack.header.network.l2;
import org.zstack.header.message.APIEvent;
import org.zstack.header.rest.RestResponse;
/**
* @apiResult api event for message :ref:`APIAttachL2NetworkToClusterMsg`
* @category l2network
* @example {
* "org.zstack.header.network.l2.APIAttachL2NetworkToClusterEvent": {
* "inventory": {
* "uuid": "a766f7dec6e5477f9842289950b51e63",
* "name": "TestL2Network",
* "description": "Test",
* "zoneUuid": "48c5febd96024e33809cc98035d79277",
* "physicalInterface": "eth0",
* "type": "L2NoVlanNetwork",
* "createDate": "May 3, 2014 9:19:08 PM",
* "lastOpDate": "May 3, 2014 9:19:08 PM",
* "attachedClusterUuids": [
* "cb97e076b2e7497d9d4018fb4b4cfcea"
* ]
* },
* "success": true
* }
* }
* @since 0.1.0
*/
@RestResponse(allTo = "inventory")
public class APIAttachL2NetworkToClusterEvent extends APIEvent {
/**
* @desc see :ref:`L2NetworkInventory`
*/
private L2NetworkInventory inventory;
public APIAttachL2NetworkToClusterEvent(String apiId) {
super(apiId);
}
public APIAttachL2NetworkToClusterEvent() {
super(null);
}
public L2NetworkInventory getInventory() {
return inventory;
}
public void setInventory(L2NetworkInventory inventory) {
this.inventory = inventory;
}
public static APIAttachL2NetworkToClusterEvent __example__() {
APIAttachL2NetworkToClusterEvent event = new APIAttachL2NetworkToClusterEvent();
L2VlanNetworkInventory net = new L2VlanNetworkInventory();
net.setName("Test-Net");
net.setVlan(10);
net.setDescription("Test");
net.setZoneUuid(uuid());
net.setPhysicalInterface("eth0");
net.setType("L2VlanNetwork");
event.setInventory(net);
return event;
}
}
| 790 |
2,406 |
<reponame>monroid/openvino
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "default_opset.hpp"
#include "ngraph/node.hpp"
#include "onnx_import/core/node.hpp"
#include "utils/variadic.hpp"
namespace ngraph {
namespace onnx_import {
namespace op {
namespace set_1 {
inline OutputVector min(const Node& node) {
return variadic::make_ng_variadic_op<default_opset::Minimum>(node, ngraph::op::AutoBroadcastSpec::NONE);
}
} // namespace set_1
namespace set_8 {
inline OutputVector min(const Node& node) {
return variadic::make_ng_variadic_op<default_opset::Minimum>(node);
}
} // namespace set_8
} // namespace op
} // namespace onnx_import
} // namespace ngraph
| 275 |
421 |
//<Snippet1>
// This example demonstrates a thread-safe method that adds to a
// running total. It cannot be run directly. You can compile it
// as a library, or add the class to a project.
#using <system.dll>
using namespace System::Threading;
public ref class ThreadSafe
{
private:
// totalValue contains a running total that can be updated
// by multiple threads. It must be protected from unsynchronized
// access.
int totalValue;
public:
property int Total
{
// The Total property returns the running total.
int get()
{
return totalValue;
}
}
// AddToTotal safely adds a value to the running total.
int AddToTotal( int addend )
{
int initialValue;
int computedValue;
do
{
// Save the current running total in a local variable.
initialValue = totalValue;
// Add the new value to the running total.
computedValue = initialValue + addend;
// CompareExchange compares totalValue to initialValue. If
// they are not equal, then another thread has updated the
// running total since this loop started. CompareExchange
// does not update totalValue. CompareExchange returns the
// contents of totalValue, which do not equal initialValue,
// so the loop executes again.
}
while ( initialValue != Interlocked::CompareExchange( totalValue, computedValue, initialValue ) );
// If no other thread updated the running total, then
// totalValue and initialValue are equal when CompareExchange
// compares them, and computedValue is stored in totalValue.
// CompareExchange returns the value that was in totalValue
// before the update, which is equal to initialValue, so the
// loop ends.
// The function returns computedValue, not totalValue, because
// totalValue could be changed by another thread between
// the time the loop ends and the function returns.
return computedValue;
}
};
//</Snippet1>
| 786 |
428 |
<reponame>sjoner/AnoleFix
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dodola.anole.lib;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.objectweb.asm.tree.analysis.Analyzer;
import org.objectweb.asm.tree.analysis.AnalyzerException;
import org.objectweb.asm.tree.analysis.BasicInterpreter;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.Frame;
import org.objectweb.asm.tree.analysis.Value;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Utilities to detect and manipulate constructor methods.
* <p>
* A constructor of a non static inner class usually has the form:
* <p>
* ALOAD_0 // push this to the stack
* ... // Code to set up $this
* ALOAD_0 // push this to the stack
* ... // Code to set up the arguments (aka "args") for the delegation
* ... // via super() or this(). Note that here we can have INVOKESPECIALS
* ... // for all the new calls here.
* INVOKESPECIAL <init> // super() or this() call
* ... // the "body" of the constructor goes here.
* <p>
* This class has the utilities to detect which instruction is the right INVOKESPECIAL call before
* the "body".
*/
public class ConstructorDelegationDetector {
/**
* A specialized value used to track the first local variable (this) on the
* constructor.
*/
public static class LocalValue extends BasicValue {
public LocalValue(Type type) {
super(type);
}
@Override
public String toString() {
return "*";
}
}
/**
* A deconstructed constructor, split up in the parts mentioned above.
*/
static class Constructor {
/**
* The last LOAD_0 instruction of the original code, before the call to the delegated
* constructor.
*/
public final VarInsnNode loadThis;
/**
* Line number of LOAD_0. Used to set the line number in the generated constructor call
* so that a break point may be set at this(...) or super(...)
*/
public final int lineForLoad;
/**
* The "args" part of the constructor. Described above.
*/
public final MethodNode args;
/**
* The INVOKESPECIAL instruction of the original code that calls the delegation.
*/
public final MethodInsnNode delegation;
/**
* A copy of the body of the constructor.
*/
public final MethodNode body;
Constructor(VarInsnNode loadThis, int lineForLoad, MethodNode args, MethodInsnNode delegation, MethodNode body) {
this.loadThis = loadThis;
this.lineForLoad = lineForLoad;
this.args = args;
this.delegation = delegation;
this.body = body;
}
}
/**
* Deconstruct a constructor into its components and adds the necessary code to link the components
* later. The generated bytecode does not correspond exactly to this code, but in essence, for
* a constructor of this form:
* <p/>
* <code>
* <init>(int x) {
* super(x = 1, expr2() ? 3 : 7)
* doSomething(x)
* }
* </code>
* <p/>
* it creates the two parts:
* <code>
* Object[] init$args(Object[] locals, int x) {
* Object[] args = new Object[2];
* args[0] = (x = 1)
* args[1] = expr2() ? 3 : 7;
* locals[0] = x;
* return new Object[] {"myclass.<init>(I;I;)V", args};
* }
* <p>
* void init$body(int x) {
* doSomething(x);
* }
* </code>
*
* @param owner the owning class.
* @param method the constructor method.
*/
public static Constructor deconstruct(String owner, MethodNode method) {
// Basic interpreter uses BasicValue.REFERENCE_VALUE for all object types. However
// we need to distinguish one in particular. The value of the local variable 0, ie. the
// uninitialized this. By doing it this way we ensure that whenever there is a ALOAD_0
// a LocalValue instance will be on the stack.
BasicInterpreter interpreter = new BasicInterpreter() {
boolean done = false;
@Override
// newValue is called first to initialize the frame values of all the local variables
// we intercept the first one to create our own special value.
public BasicValue newValue(Type type) {
if (type == null) {
return BasicValue.UNINITIALIZED_VALUE;
} else if (type.getSort() == Type.VOID) {
return null;
} else {
// If this is the first value created (i.e. the first local variable)
// we use a special marker.
BasicValue ret = done ? super.newValue(type) : new LocalValue(type);
done = true;
return ret;
}
}
};
Analyzer analyzer = new Analyzer(interpreter);
AbstractInsnNode[] instructions = method.instructions.toArray();
try {
Frame[] frames = analyzer.analyze(owner, method);
if (frames.length != instructions.length) {
// Should never happen.
throw new IllegalStateException(
"The number of frames is not equals to the number of instructions");
}
VarInsnNode lastThis = null;
int stackAtThis = -1;
boolean poppedThis = false;
// Records the most recent line number encountered. For javac, there should always be
// a line number node before the call of interest to this(...) or super(...). For robustness,
// -1 is recorded as a sentinel to indicate this assumption didn't hold. Upstream consumers
// should check for -1 and recover in a reasonable way (for example, don't set the line
// number in generated code).
int recentLine = -1;
for (int i = 0; i < instructions.length; i++) {
AbstractInsnNode insn = instructions[i];
Frame frame = frames[i];
if (frame.getStackSize() < stackAtThis) {
poppedThis = true;
}
if (insn instanceof MethodInsnNode) {
// TODO: Do we need to check that the stack is empty after this super call?
MethodInsnNode methodhInsn = (MethodInsnNode) insn;
Type[] types = Type.getArgumentTypes(methodhInsn.desc);
Value value = frame.getStack(frame.getStackSize() - types.length - 1);
if (value instanceof LocalValue && methodhInsn.name.equals("<init>")) {
if (poppedThis) {
throw new IllegalStateException("Unexpected constructor structure.");
}
return split(owner, method, lastThis, methodhInsn, recentLine);
}
} else if (insn instanceof VarInsnNode) {
VarInsnNode var = (VarInsnNode) insn;
if (var.var == 0) {
lastThis = var;
stackAtThis = frame.getStackSize();
poppedThis = false;
}
} else if (insn instanceof LineNumberNode) {
// Record the most recent line number encountered so that call to this(...)
// or super(...) has line number information. Ultimately used to emit a line
// number in the generated code.
LineNumberNode lineNumberNode = (LineNumberNode) insn;
recentLine = lineNumberNode.line;
}
}
throw new IllegalStateException("Unexpected constructor structure.");
} catch (AnalyzerException e) {
throw new IllegalStateException(e);
}
}
/**
* Splits the constructor in two methods, the "set up" and the "body" parts (see above).
*/
private static Constructor split(String owner, MethodNode method, VarInsnNode loadThis, MethodInsnNode delegation, int loadThisLine) {
String[] exceptions = ((List<String>) method.exceptions).toArray(new String[method.exceptions.size()]);
String newDesc = method.desc.replaceAll("\\((.*)\\)V", "([Ljava/lang/Object;$1)Ljava/lang/Object;");
MethodNode initArgs = new MethodNode(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "init$args", newDesc, null, exceptions);
AbstractInsnNode insn = loadThis.getNext();
while (insn != delegation) {
insn.accept(initArgs);
insn = insn.getNext();
}
LabelNode labelBefore = new LabelNode();
labelBefore.accept(initArgs);
GeneratorAdapter mv = new GeneratorAdapter(initArgs, initArgs.access, initArgs.name, initArgs.desc);
// Copy the arguments back to the argument array
// The init_args part cannot access the "this" object and can have side effects on the
// local variables. Because of this we use the first argument (which we want to keep
// so all the other arguments remain unchanged) as a reference to the array where to
// return the values of the modified local variables.
Type[] types = Type.getArgumentTypes(initArgs.desc);
int stack = 1; // Skip the first one which is a reference to the local array.
for (int i = 1; i < types.length; i++) {
Type type = types[i];
// This is not this, but the array of local arguments final values.
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.push(i);
mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), stack);
mv.box(type);
mv.arrayStore(Type.getType(Object.class));
stack += type.getSize();
}
// Create the args array with the values to send to the delegated constructor
Type[] returnTypes = Type.getArgumentTypes(delegation.desc);
// The extra element for the qualified name of the constructor.
mv.push(returnTypes.length + 1);
mv.newArray(Type.getType(Object.class));
int args = mv.newLocal(Type.getType("[Ljava/lang/Object;"));
mv.storeLocal(args);
for (int i = returnTypes.length - 1; i >= 0; i--) {
Type type = returnTypes[i];
mv.loadLocal(args);
mv.swap(type, Type.getType(Object.class));
mv.push(i + 1);
mv.swap(type, Type.INT_TYPE);
mv.box(type);
mv.arrayStore(Type.getType(Object.class));
}
// Store the qualified name of the constructor in the first element of the array.
mv.loadLocal(args);
mv.push(0);
mv.push(delegation.owner + "." + delegation.desc); // Name of the constructor to be called.
mv.arrayStore(Type.getType(Object.class));
mv.loadLocal(args);
mv.returnValue();
newDesc = method.desc.replace("(", "(L" + owner + ";");
MethodNode body = new MethodNode(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
"init$body", newDesc, null, exceptions);
LabelNode labelAfter = new LabelNode();
labelAfter.accept(body);
Set<LabelNode> bodyLabels = new HashSet<LabelNode>();
insn = delegation.getNext();
while (insn != null) {
if (insn instanceof LabelNode) {
bodyLabels.add((LabelNode) insn);
}
insn.accept(body);
insn = insn.getNext();
}
// manually transfer the exception table from the existing constructor to the new
// "init$body" method. The labels were transferred just above so we can reuse them.
//noinspection unchecked
for (TryCatchBlockNode tryCatch : (List<TryCatchBlockNode>) method.tryCatchBlocks) {
tryCatch.accept(body);
}
//noinspection unchecked
for (LocalVariableNode variable : (List<LocalVariableNode>) method.localVariables) {
boolean startsInBody = bodyLabels.contains(variable.start);
boolean endsInBody = bodyLabels.contains(variable.end);
if (!startsInBody && !endsInBody) {
if (variable.index != 0) { // '#0' on init$args is not 'this'
variable.accept(initArgs);
}
} else if (startsInBody && endsInBody) {
variable.accept(body);
} else if (!startsInBody && endsInBody) {
// The variable spans from the args to the end of the method, create two:
if (variable.index != 0) { // '#0' on init$args is not 'this'
LocalVariableNode var0 = new LocalVariableNode(variable.name,
variable.desc, variable.signature,
variable.start, labelBefore, variable.index);
var0.accept(initArgs);
}
LocalVariableNode var1 = new LocalVariableNode(variable.name,
variable.desc, variable.signature,
labelAfter, variable.end, variable.index);
var1.accept(body);
} else {
throw new IllegalStateException("Local variable starts after it ends.");
}
}
return new Constructor(loadThis, loadThisLine, initArgs, delegation, body);
}
}
| 6,268 |
852 |
import FWCore.ParameterSet.Config as cms
ct2ct = cms.EDProducer("CaloTowersReCreator",
# Weighting factor for EB
EBWeight = cms.double(1.0),
HBGrid = cms.vdouble(0.0, 2.0, 4.0, 5.0, 9.0,
20.0, 30.0, 50.0, 100.0, 1000.0),
# energy scale for each subdetector (only Eb-Ee-Hb-He interpolations are available for now)
HBEScale = cms.double(50.0),
EEWeights = cms.vdouble(0.51, 1.39, 1.71, 2.37, 2.32,
2.2, 2.1, 1.98, 1.8),
HF2Weights = cms.vdouble(1.0, 1.0, 1.0, 1.0, 1.0),
HOWeights = cms.vdouble(1.0, 1.0, 1.0, 1.0, 1.0),
EEGrid = cms.vdouble(2.0, 4.0, 5.0, 9.0, 20.0,
30.0, 50.0, 100.0, 300.0),
# Weighting factor for HE 10-degree cells
HEDWeight = cms.double(1.0),
# Weighting factor for EE
EEWeight = cms.double(1.0),
HBWeights = cms.vdouble(2.0, 1.86, 1.69, 1.55, 1.37,
1.19, 1.13, 1.11, 1.09, 1.0),
# Weighting factor for HF long-fiber readouts
HF1Weight = cms.double(1.0),
HF2Grid = cms.vdouble(-1.0, 1.0, 10.0, 100.0, 1000.0),
HEDWeights = cms.vdouble(1.7, 1.57, 1.54, 1.49, 1.41,
1.26, 1.19, 1.15, 1.12, 1.0),
HF1Grid = cms.vdouble(-1.0, 1.0, 10.0, 100.0, 1000.0),
EBWeights = cms.vdouble(0.86, 1.47, 1.66, 2.01, 1.98,
1.86, 1.83, 1.74, 1.65),
# Weighting factor for HO
HOWeight = cms.double(1.0),
# Weighting factor for HE 5-degree cells
HESWeight = cms.double(1.0),
# Weighting factor for HF short-fiber readouts
HF2Weight = cms.double(1.0),
# Label of input CaloTowerCollection to use
caloLabel = cms.InputTag("calotowermaker"),
HF1Weights = cms.vdouble(1.0, 1.0, 1.0, 1.0, 1.0),
HESEScale = cms.double(50.0),
HESGrid = cms.vdouble(0.0, 2.0, 4.0, 5.0, 9.0,
20.0, 30.0, 50.0, 100.0, 1000.0),
HEDEScale = cms.double(50.0),
HESWeights = cms.vdouble(1.7, 1.57, 1.54, 1.49, 1.41,
1.26, 1.19, 1.15, 1.12, 1.0),
HEDGrid = cms.vdouble(0.0, 2.0, 4.0, 5.0, 9.0,
20.0, 30.0, 50.0, 100.0, 1000.0),
EBEScale = cms.double(50.0),
# Weighting factor for HB
HBWeight = cms.double(1.0),
EEEScale = cms.double(50.0),
HOGrid = cms.vdouble(-1.0, 1.0, 10.0, 100.0, 1000.0),
# Energy dependent weights and energy scale to be used
EBGrid = cms.vdouble(2.0, 4.0, 5.0, 9.0, 20.0,
30.0, 50.0, 100.0, 300.0),
# momentum assignment
# Method for momentum reconstruction
MomConstrMethod = cms.int32(1),
# Depth, fraction of the respective calorimeter [0,1]
MomHBDepth = cms.double(0.2),
MomHEDepth = cms.double(0.4),
MomEBDepth = cms.double(0.3),
MomEEDepth = cms.double(0.0),
HcalPhase = cms.int32(0)
)
from Configuration.Eras.Modifier_run2_HE_2018_cff import run2_HE_2018
run2_HE_2018.toModify(ct2ct, HcalPhase = 1)
| 1,485 |
777 |
<reponame>google-ar/chromium<filename>components/sync/model/entity_change.h
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_MODEL_ENTITY_CHANGE_H_
#define COMPONENTS_SYNC_MODEL_ENTITY_CHANGE_H_
#include <string>
#include <vector>
#include "components/sync/model/entity_data.h"
namespace syncer {
class EntityChange {
public:
enum ChangeType { ACTION_ADD, ACTION_UPDATE, ACTION_DELETE };
static EntityChange CreateAdd(const std::string& storage_key,
EntityDataPtr data);
static EntityChange CreateUpdate(const std::string& storage_key,
EntityDataPtr data);
static EntityChange CreateDelete(const std::string& storage_key);
EntityChange(const EntityChange& other);
virtual ~EntityChange();
std::string storage_key() const { return storage_key_; }
ChangeType type() const { return type_; }
const EntityData& data() const { return data_.value(); }
private:
EntityChange(const std::string& storage_key,
ChangeType type,
EntityDataPtr data);
std::string storage_key_;
ChangeType type_;
EntityDataPtr data_;
};
typedef std::vector<EntityChange> EntityChangeList;
} // namespace syncer
#endif // COMPONENTS_SYNC_MODEL_ENTITY_CHANGE_H_
| 504 |
656 |
<filename>InvenTree/common/migrations/0002_auto_20190902_2304.py
# Generated by Django 2.2.4 on 2019-09-02 23:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('common', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='currency',
options={'verbose_name_plural': 'Currencies'},
),
]
| 177 |
356 |
/**
* This sample package shows an example for how to integrate Proctor with Spring MVC
*/
package com.indeed.proctor.integration.sample;
| 37 |
668 |
/**
* 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.fineract.integrationtests.common;
import com.google.gson.Gson;
public class CurrencyDomain implements Comparable<CurrencyDomain> {
public static final class Builder {
private String code;
private String name;
private int decimalPlaces;
private String displaySymbol;
private String nameCode;
private String displayLabel;
private Builder(final String code, final String name, final int decimalPlaces, final String displaySymbol, final String nameCode,
final String displayLabel) {
this.code = code;
this.name = name;
this.decimalPlaces = decimalPlaces;
this.displaySymbol = displaySymbol;
this.nameCode = nameCode;
this.displayLabel = displayLabel;
}
public CurrencyDomain build() {
return new CurrencyDomain(this.code, this.name, this.decimalPlaces, this.displaySymbol, this.nameCode, this.displayLabel);
}
}
private String code;
private String name;
private int decimalPlaces;
private String displaySymbol;
private String nameCode;
private String displayLabel;
CurrencyDomain() {
}
private CurrencyDomain(final String code, final String name, final int decimalPlaces, final String displaySymbol, final String nameCode,
final String displayLabel) {
this.code = code;
this.name = name;
this.decimalPlaces = decimalPlaces;
this.displaySymbol = displaySymbol;
this.nameCode = nameCode;
this.displayLabel = displayLabel;
}
public String getCode() {
return this.code;
}
public int getDecimalPlaces() {
return this.decimalPlaces;
}
public String getDisplaySymbol() {
return this.displaySymbol;
}
public String getNameCode() {
return this.nameCode;
}
public String getDisplayLabel() {
return this.displayLabel;
}
public String getName() {
return this.name;
}
public String toJSON() {
return new Gson().toJson(this);
}
public static CurrencyDomain fromJSON(final String jsonData) {
return new Gson().fromJson(jsonData, CurrencyDomain.class);
}
public static Builder create(final String code, final String name, final int decimalPlaces, final String displaySymbol,
final String nameCode, final String displayLabel) {
return new Builder(code, name, decimalPlaces, displaySymbol, nameCode, displayLabel);
}
@Override
public int hashCode() {
int hash = 1;
if (this.name != null) {
hash += this.name.hashCode();
}
if (this.code != null) {
hash += this.code.hashCode();
}
if (this.decimalPlaces >= 0) {
hash += this.decimalPlaces;
}
if (this.displaySymbol != null) {
hash += this.displaySymbol.hashCode();
}
if (this.nameCode != null) {
hash += this.nameCode.hashCode();
}
if (this.displayLabel != null) {
hash += this.displayLabel.hashCode();
}
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CurrencyDomain)) {
return false;
}
CurrencyDomain cd = (CurrencyDomain) obj;
if (this.name.equals(cd.name) && this.code.equals(cd.code) && this.decimalPlaces == cd.decimalPlaces
&& this.displaySymbol.equals(cd.displaySymbol) && this.nameCode.equals(cd.nameCode)
&& this.displayLabel.equals(cd.displayLabel)) {
return true;
}
return false;
}
@Override
public int compareTo(CurrencyDomain cd) {
return this.name.compareTo(cd.getName());
}
}
| 1,826 |
852 |
<filename>TrackingTools/TrackAssociator/src/TAMuonSegmentMatch.cc<gh_stars>100-1000
#include "TrackingTools/TrackAssociator/interface/TAMuonSegmentMatch.h"
#include "DataFormats/MuonDetId/interface/DTChamberId.h"
#include "DataFormats/MuonDetId/interface/CSCDetId.h"
#include "DataFormats/MuonDetId/interface/RPCDetId.h"
#include "DataFormats/MuonDetId/interface/GEMDetId.h"
#include "DataFormats/MuonDetId/interface/ME0DetId.h"
| 167 |
486 |
/*
* ARX: Powerful Data Anonymization
* Copyright 2012 - 2021 <NAME> and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deidentifier.arx.gui.view.impl.common.table;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.IUniqueIndexLayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
/**
* The body layer.
*
* @author <NAME>
*/
public class LayerBody extends CTLayer {
/** Selection layer. */
private final SelectionLayer selectionLayer;
/** Data layer. */
private final DataLayer dataLayer;
/** Viewport layer. */
private final LayerViewport viewportLayer;
/**
* Creates a new instance.
*
* @param dataProvider
* @param config
* @param context
*/
public LayerBody(IDataProvider dataProvider, CTConfiguration config, CTContext context) {
super(config, context);
dataLayer = new DataLayer(dataProvider);
selectionLayer = new LayerSelection(dataLayer, config);
selectionLayer.addConfiguration(new StyleConfigurationSelection(config));
IUniqueIndexLayer layer = selectionLayer;
switch(config.getColumnHeaderLayout()){
case CTConfiguration.COLUMN_HEADER_LAYOUT_FILL:
layer = new LayerColumnFillLayout(layer, config, context);
break;
case CTConfiguration.COLUMN_HEADER_LAYOUT_FILL_EQUAL:
layer = new LayerColumnFillLayout(layer, config, context, true);
break;
}
switch(config.getRowHeaderLayout()){
case CTConfiguration.ROW_HEADER_LAYOUT_FILL:
layer = new LayerRowFillLayout(layer, config, context);
break;
}
viewportLayer = new LayerViewport(layer, context);
setUnderlyingLayer(viewportLayer);
}
/**
* Returns the data layer.
*
* @return
*/
public DataLayer getDataLayer() {
return dataLayer;
}
/**
* Returns the selection layer.
*
* @return
*/
public SelectionLayer getSelectionLayer() {
return selectionLayer;
}
/**
* Returns the viewport layer.
*
* @return
*/
public LayerViewport getViewportLayer() {
return viewportLayer;
}
}
| 1,247 |
382 |
/*
* Copyright 2018 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.spinnaker.clouddriver.artifacts.embedded;
import com.netflix.spinnaker.credentials.CredentialsRepository;
import com.netflix.spinnaker.credentials.MapBackedCredentialsRepository;
import com.netflix.spinnaker.credentials.NoopCredentialsLifecycleHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@RequiredArgsConstructor
@Slf4j
class EmbeddedArtifactConfiguration {
@Bean
public CredentialsRepository<EmbeddedArtifactCredentials>
embeddedArtifactCredentialsRepository() {
CredentialsRepository<EmbeddedArtifactCredentials> repository =
new MapBackedCredentialsRepository<>(
EmbeddedArtifactCredentials.CREDENTIALS_TYPE, new NoopCredentialsLifecycleHandler<>());
repository.save(new EmbeddedArtifactCredentials(new EmbeddedArtifactAccount()));
return repository;
}
}
| 482 |
393 |
#ifndef INCLUDED_PORTAUDIO_CPPFUNCALLBACKSTREAM_HXX
#define INCLUDED_PORTAUDIO_CPPFUNCALLBACKSTREAM_HXX
// ---------------------------------------------------------------------------------------
#include "portaudio.h"
#include "portaudiocpp/CallbackStream.hxx"
// ---------------------------------------------------------------------------------------
// Forward declaration(s):
namespace portaudio
{
class StreamParameters;
}
// ---------------------------------------------------------------------------------------
// Declaration(s):
namespace portaudio
{
namespace impl
{
extern "C"
{
int cppCallbackToPaCallbackAdapter(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags,
void *userData);
} // extern "C"
}
// -----------------------------------------------------------------------------------
//////
/// @brief Callback stream using a C++ function (either a free function or a static function)
/// callback.
//////
class FunCallbackStream : public CallbackStream
{
public:
typedef int (*CallbackFunPtr)(const void *inputBuffer, void *outputBuffer, unsigned long numFrames,
const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags,
void *userData);
// -------------------------------------------------------------------------------
//////
/// @brief Simple structure containing a function pointer to the C++ callback function and a
/// (void) pointer to the user supplied data.
//////
struct CppToCCallbackData
{
CppToCCallbackData();
CppToCCallbackData(CallbackFunPtr funPtr, void *userData);
void init(CallbackFunPtr funPtr, void *userData);
CallbackFunPtr funPtr;
void *userData;
};
// -------------------------------------------------------------------------------
FunCallbackStream();
FunCallbackStream(const StreamParameters ¶meters, CallbackFunPtr funPtr, void *userData);
~FunCallbackStream();
void open(const StreamParameters ¶meters, CallbackFunPtr funPtr, void *userData);
private:
FunCallbackStream(const FunCallbackStream &); // non-copyable
FunCallbackStream &operator=(const FunCallbackStream &); // non-copyable
CppToCCallbackData adapterData_;
void open(const StreamParameters ¶meters);
};
} // portaudio
// ---------------------------------------------------------------------------------------
#endif // INCLUDED_PORTAUDIO_CPPFUNCALLBACKSTREAM_HXX
| 881 |
4,403 |
<gh_stars>1000+
package cn.hutool.extra.expression.engine.jfireel;
import cn.hutool.extra.expression.ExpressionEngine;
import com.jfirer.jfireel.expression.Expression;
import java.util.Map;
/**
* JfireEL引擎封装<br>
* 见:https://gitee.com/eric_ds/jfireEL
*
* @since 5.5.0
* @author looly
*/
public class JfireELEngine implements ExpressionEngine {
/**
* 构造
*/
public JfireELEngine(){
}
@Override
public Object eval(String expression, Map<String, Object> context) {
return Expression.parse(expression).calculate(context);
}
}
| 216 |
437 |
<reponame>tayueliuxiang/spring-learning<gh_stars>100-1000
package com.brianway.learning.spring.ioc.beanfactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* Created by Brian on 2016/5/13.
* BeanPostProcessor 实现类
* 在该类中,通过过滤条件只对 car Bean 进行处理,对其他 Bean 不管
* 对配置文件提供的属性设置值实行进行判断和操作
*/
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("car")) {
Car car = (Car) bean;
if (car.getColor() == null) {
System.out.println("调用BeanPostProcessor.postProcessBeforeInitialization(),color为空,设置为默认黑色");
car.setColor("黑色");
}
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanName.equals("car")) {
Car car = (Car) bean;
if (car.getMaxSpeed() >= 200) {
System.out.println("调用BeanPostProcessor.postProcessAfterInitialization(),将maxSpeed调整为200");
car.setMaxSpeed(200);
}
}
return bean;
}
}
| 658 |
489 |
<filename>NMSSHTests/NMSSHSessionTests.h
#import <XCTest/XCTest.h>
@interface NMSSHSessionTests : XCTestCase
@end
| 48 |
354 |
<filename>pyKriging/utilities.py<gh_stars>100-1000
__author__ = 'chrispaulson'
import dill as pickle
import numpy as np
from copy import deepcopy
def norm(x):
# x = np.array(x, dtype=float)
# return ((x-min(x))/(max(x)-min(x)))
x = ((x)/(max(x)-min(x)))
return x-min(x)
def saveModel(model, filePath):
pickle.dump(model, open(filePath, 'w'), byref=True)
def loadModel(filePath):
return pickle.load(open(filePath,'r'))
def splitArrays(krigeModel, q=5):
ind = np.arange(krigeModel.n)
np.random.shuffle(ind)
test = np.array_split(ind,q)
for i in test:
newX = deepcopy(krigeModel.X)
newy = deepcopy(krigeModel.y)
testX = newX[i]
testy = newy[i]
trainX = np.delete(newX,i,axis=0)
trainy = np.delete(newy,i,axis=0)
yield trainX, trainy, testX, testy
def mse(actual, predicted):
return ((actual - predicted) ** 2)
| 427 |
923 |
package core.cli;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import core.cli.client.handlers.CliActionProcessor;
import core.cli.client.handlers.SharedVariablesCliActionHandler;
import core.cli.client.handlers.TaskCliActionHandler;
import core.config.CliConfig;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparsers;
import utilities.HttpClient;
public class MainCli {
private static final Logger LOGGER = Logger.getLogger(MainCli.class.getName());
private Map<String, CliActionProcessor> processors;
public MainCli() {
processors = new HashMap<>();
processors.put("variable", new SharedVariablesCliActionHandler());
processors.put("task", new TaskCliActionHandler());
}
private ArgumentParser setupParser() {
ArgumentParser parser = ArgumentParsers.newFor("Repeat").build()
.defaultHelp(true)
.description("Execute Repeat operations in the terminal.");
parser.addArgument("-s", "--host").type(String.class)
.setDefault("localhost")
.help("Specify a custom host at which the Repeat server is running.");
parser.addArgument("-p", "--port").type(Integer.class)
.help("Specify a custom port at which the Repeat server is running."
+ "If not specified, port value is read from config file.");
Subparsers subParsers = parser.addSubparsers().help("Help for each individual command.");
for (CliActionProcessor processor : processors.values()) {
processor.addArguments(subParsers);
}
return parser;
}
public void process(String[] args) {
ArgumentParser parser = setupParser();
Namespace namespace = null;
try {
namespace = parser.parseArgs(args);
} catch (ArgumentParserException e) {
parser.handleError(e);
CliExitCodes.INVALID_ARGUMENTS.exit();
}
CliConfig config = new CliConfig();
config.loadConfig(null);
// Override port if provided.
Integer customPort = namespace.getInt("port");
if (customPort != null) {
config.setServerPort(customPort);
}
String serverAddress = String.format("%s:%s", namespace.getString("host"), config.getServerPort());
HttpClient client = new HttpClient(serverAddress, HttpClient.Config.of());
for (CliActionProcessor processor : processors.values()) {
processor.setHttpClient(client);
}
String action = namespace.get("module");
CliActionProcessor processor = processors.get(action);
if (processor == null) {
LOGGER.log(Level.SEVERE, "Unknown action " + action);
CliExitCodes.UNKNOWN_ACTION.exit();
}
processor.handle(namespace);
}
}
| 1,075 |
1,056 |
<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.websvc.wsitmodelext.rm;
import org.netbeans.modules.websvc.wsitmodelext.rm.impl.*;
import org.netbeans.modules.xml.wsdl.model.WSDLComponent;
import org.netbeans.modules.xml.wsdl.model.spi.ElementFactory;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.netbeans.modules.websvc.wsitmodelext.versioning.ConfigVersion;
public class RMFactories {
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class RMAssertionFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
HashSet<QName> set = new HashSet<QName>();
for (ConfigVersion cfgVersion : ConfigVersion.values()) {
set.add(RMQName.RMASSERTION.getQName(cfgVersion));
}
return Collections.unmodifiableSet(set);
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new RMAssertionImpl(context.getModel(), element);
}
}
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class AcknowledgementIntervalFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
return Collections.singleton(RMQName.ACKNOWLEDGEMENTINTERVAL.getQName(ConfigVersion.CONFIG_1_0));
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new AcknowledgementIntervalImpl(context.getModel(), element);
}
}
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class DeliveryAssuranceFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
return Collections.singleton(RMQName.DELIVERYASSURANCE.getQName(ConfigVersion.CONFIG_1_3));
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new DeliveryAssuranceImpl(context.getModel(), element);
}
}
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class ExactlyOnceFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
return Collections.singleton(RMQName.EXACTLYONCE.getQName(ConfigVersion.CONFIG_1_3));
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new ExactlyOnceImpl(context.getModel(), element);
}
}
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class AtMostOnceFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
return Collections.singleton(RMQName.ATMOSTONCE.getQName(ConfigVersion.CONFIG_1_3));
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new AtMostOnceImpl(context.getModel(), element);
}
}
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class AtLeastOnceFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
return Collections.singleton(RMQName.ATLEASTONCE.getQName(ConfigVersion.CONFIG_1_3));
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new AtLeastOnceImpl(context.getModel(), element);
}
}
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class InOrderFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
return Collections.singleton(RMQName.INORDER.getQName(ConfigVersion.CONFIG_1_3));
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new InOrderImpl(context.getModel(), element);
}
}
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class SequenceSTRFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
return Collections.singleton(RMQName.SEQUENCESTR.getQName(ConfigVersion.CONFIG_1_3));
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new SequenceSTRImpl(context.getModel(), element);
}
}
@org.openide.util.lookup.ServiceProvider(service=org.netbeans.modules.xml.wsdl.model.spi.ElementFactory.class)
public static class SequenceTransportSecurityFactory extends ElementFactory {
@Override
public Set<QName> getElementQNames() {
return Collections.singleton(RMQName.SEQUENCETRANSPORTSECURITY.getQName(ConfigVersion.CONFIG_1_3));
}
@Override
public WSDLComponent create(WSDLComponent context, Element element) {
return new SequenceTransportSecurityImpl(context.getModel(), element);
}
}
}
| 2,420 |
314 |
/*
* Copyright (c) <NAME> 2016. All Rights Reserved.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.joaquimley.avenging.ui.character;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.joaquimley.avenging.R;
import com.joaquimley.avenging.ui.comic.ComicAdapter;
import com.joaquimley.avenging.ui.comic.ComicFragment;
import com.joaquimley.avenging.util.widgets.ComicFrameWrapper;
import com.joaquimley.avenging.util.widgets.DescriptionFrameWrapper;
import com.joaquimley.avenging.util.widgets.UrlFrameWrapper;
import com.joaquimley.core.data.DataManager;
import com.joaquimley.core.data.model.CharacterMarvel;
import com.joaquimley.core.data.model.Comic;
import com.joaquimley.core.ui.character.CharacterContract;
import com.joaquimley.core.ui.character.CharacterPresenter;
import com.squareup.picasso.Picasso;
import java.util.List;
public class CharacterFragment extends Fragment implements CharacterContract.CharacterView,
ComicAdapter.InteractionListener {
private static final String ARG_CHARACTER = "argCharacter";
private CharacterPresenter mCharacterPresenter;
private CharacterMarvel mCharacterMarvel;
private AppCompatActivity mActivity;
private LinearLayout mContentFrame;
private ProgressBar mContentLoadingProgress;
private DescriptionFrameWrapper mDescriptionWrapper;
private ComicFrameWrapper mComicWrapper;
private ComicFrameWrapper mSeriesWrapper;
private ComicFrameWrapper mStoriesWrapper;
private ComicFrameWrapper mEventsWrapper;
private View mMessageLayout;
private ImageView mMessageImage;
private TextView mMessageText;
private Button mMessageButton;
public static CharacterFragment newInstance(CharacterMarvel characterMarvel) {
Bundle args = new Bundle();
args.putParcelable(ARG_CHARACTER, characterMarvel);
CharacterFragment fragment = new CharacterFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onActivityCreated(Bundle onSavedInstanceState) {
super.onActivityCreated(onSavedInstanceState);
getActivity().supportStartPostponedEnterTransition();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mCharacterPresenter = new CharacterPresenter(DataManager.getInstance());
if (savedInstanceState != null) {
mCharacterMarvel = savedInstanceState.getParcelable(ARG_CHARACTER);
} else if (getArguments() != null) {
mCharacterMarvel = getArguments().getParcelable(ARG_CHARACTER);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(ARG_CHARACTER, mCharacterMarvel);
super.onSaveInstanceState(outState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_character, container, false);
mCharacterPresenter.attachView(this);
initViews(view);
mCharacterPresenter.onCharacterRequested(mCharacterMarvel.getId());
return view;
}
private void initViews(View view) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle(mCharacterMarvel != null ? mCharacterMarvel.getName()
: mActivity.getString(R.string.character_details));
mActivity = (AppCompatActivity) getActivity();
mActivity.setSupportActionBar(toolbar);
ActionBar actionBar = mActivity.getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
Picasso.with(mActivity)
.load(mCharacterMarvel.getImageUrl())
.centerCrop()
.fit()
.into((ImageView) view.findViewById(R.id.iv_header));
mContentFrame = (LinearLayout) view.findViewById(R.id.details_content_frame);
if (!mCharacterMarvel.getDescription().isEmpty()) {
mDescriptionWrapper = new DescriptionFrameWrapper(mActivity,
mActivity.getResources().getString(R.string.description),
mCharacterMarvel.getDescription());
mContentFrame.addView(mDescriptionWrapper);
}
mContentLoadingProgress = (ProgressBar) view.findViewById(R.id.progress);
mMessageLayout = view.findViewById(R.id.message_layout);
mMessageImage = (ImageView) view.findViewById(R.id.iv_message);
mMessageText = (TextView) view.findViewById(R.id.tv_message);
mMessageButton = (Button) view.findViewById(R.id.btn_try_again);
mMessageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCharacterPresenter.onCharacterRequested(mCharacterMarvel.getId());
}
});
}
@Override
public void showCharacter(CharacterMarvel character) {
mCharacterMarvel = character;
if (mDescriptionWrapper == null && !mCharacterMarvel.getDescription().isEmpty()) {
mDescriptionWrapper = new DescriptionFrameWrapper(mActivity,
mActivity.getResources().getString(R.string.description),
mCharacterMarvel.getDescription());
mContentFrame.addView(mDescriptionWrapper);
}
List<Comic> characterComics = character.getComics().getItems();
if (!characterComics.isEmpty()) {
mComicWrapper = new ComicFrameWrapper(mActivity, getString(R.string.comics), characterComics, this);
mContentFrame.addView(mComicWrapper);
mCharacterPresenter.onCharacterComicsRequested(character.getId(), characterComics.size());
}
List<Comic> characterSeries = character.getSeries().getItems();
if (!characterSeries.isEmpty()) {
mSeriesWrapper = new ComicFrameWrapper(mActivity, getString(R.string.series), characterSeries, this);
mContentFrame.addView(mSeriesWrapper);
mCharacterPresenter.onCharacterSeriesRequested(character.getId(), characterSeries.size());
}
List<Comic> characterStories = character.getStories().getItems();
if (!characterStories.isEmpty()) {
mStoriesWrapper = new ComicFrameWrapper(mActivity, getString(R.string.stories), characterStories, this);
mContentFrame.addView(mStoriesWrapper);
mCharacterPresenter.onCharacterStoriesRequested(character.getId(), characterStories.size());
}
List<Comic> characterEvents = character.getEvents().getItems();
if (!characterEvents.isEmpty()) {
mEventsWrapper = new ComicFrameWrapper(mActivity, getString(R.string.events), characterEvents, this);
mContentFrame.addView(mEventsWrapper);
mCharacterPresenter.onCharacterEventsRequested(character.getId(), characterEvents.size());
}
if (!character.getUrls().isEmpty()) {
mContentFrame.addView(new UrlFrameWrapper(mActivity,
mActivity.getResources().getString(R.string.related_links), character.getUrls()));
}
TextView copyRightTextView = new TextView(mActivity);
copyRightTextView.setText(getString(R.string.marvel_copyright_notice));
mContentFrame.addView(copyRightTextView);
}
@Override
public void onComicClick(List<Comic> comicList, ImageView sharedImageView, int clickedPosition) {
if (mActivity.getSupportFragmentManager().findFragmentByTag(ComicFragment.TAG) == null) {
mActivity.getSupportFragmentManager()
.beginTransaction()
.add(R.id.character_container, ComicFragment.newInstance(comicList, clickedPosition))
.addSharedElement(sharedImageView, ViewCompat.getTransitionName(sharedImageView))
.addToBackStack(ComicFragment.TAG)
.commit();
}
}
@Override
public void showProgress() {
if (mContentLoadingProgress.getVisibility() != View.VISIBLE) {
mContentLoadingProgress.setVisibility(View.VISIBLE);
}
mContentFrame.setVisibility(View.GONE);
}
@Override
public void hideProgress() {
mContentLoadingProgress.setVisibility(View.GONE);
mContentFrame.setVisibility(View.VISIBLE);
}
@Override
public void showUnauthorizedError() {
mMessageImage.setImageResource(R.drawable.ic_error_list);
mMessageText.setText(getString(R.string.error_generic_server_error, "Unauthorized"));
mMessageButton.setText(getString(R.string.action_try_again));
showMessageLayout(true);
}
@Override
public void showError(String errorMessage) {
mMessageImage.setImageResource(R.drawable.ic_error_list);
mMessageText.setText(getString(R.string.error_generic_server_error, errorMessage));
mMessageButton.setText(getString(R.string.action_try_again));
showMessageLayout(true);
}
@Override
public void showEmpty() {
mMessageImage.setImageResource(R.drawable.ic_clear);
mMessageText.setText(getString(R.string.error_no_char_info_to_display));
mMessageButton.setText(getString(R.string.action_check_again));
showMessageLayout(true);
}
@Override
public void showMessageLayout(boolean show) {
mMessageLayout.setVisibility(show ? View.VISIBLE : View.GONE);
mContentFrame.setVisibility(show ? View.GONE : View.VISIBLE);
}
@Override
public void showComicList(final List<Comic> comicList) {
mComicWrapper.loadImages(comicList);
}
@Override
public void showSeriesList(List<Comic> seriesList) {
mSeriesWrapper.loadImages(seriesList);
}
@Override
public void showStoriesList(List<Comic> storiesList) {
mStoriesWrapper.loadImages(storiesList);
}
@Override
public void showEventsList(List<Comic> eventsList) {
mEventsWrapper.loadImages(eventsList);
}
@Override
public void onDestroy() {
mCharacterPresenter.detachView();
super.onDestroy();
}
}
| 4,303 |
1,018 |
<gh_stars>1000+
/*
* Copyright 2013-2017 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 org.glowroot.tests;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.openqa.selenium.WebDriver;
class App {
private final WebDriver driver;
private final String baseUrl;
private final String queryString;
App(WebDriver driver, String baseUrl) throws UnknownHostException {
this.driver = driver;
this.baseUrl = baseUrl;
if (WebDriverSetup.useCentral) {
this.queryString = "?agent-id=" + InetAddress.getLocalHost().getHostName();
} else {
this.queryString = "";
}
}
void open() throws IOException {
driver.get(baseUrl);
if (WebDriverSetup.useCentral) {
// this will add the agent-id query string
open("/transaction/average");
}
}
void open(String path) {
driver.get(getBaseUrl() + path + queryString);
}
String getBaseUrl() {
if (driver.getCurrentUrl().contains("/#!/")) {
return baseUrl + "/#!";
} else {
return baseUrl;
}
}
}
| 633 |
9,136 |
<filename>examples/Importers/ImportMeshUtility/b3ImportMeshUtility.h<gh_stars>1000+
#ifndef B3_IMPORT_MESH_UTILITY_H
#define B3_IMPORT_MESH_UTILITY_H
#include <string>
enum b3ImportMeshDataFlags
{
B3_IMPORT_MESH_HAS_RGBA_COLOR=1,
B3_IMPORT_MESH_HAS_SPECULAR_COLOR=2,
};
struct b3ImportMeshData
{
struct GLInstanceGraphicsShape* m_gfxShape;
unsigned char* m_textureImage1; //in 3 component 8-bit RGB data
bool m_isCached;
int m_textureWidth;
int m_textureHeight;
double m_rgbaColor[4];
double m_specularColor[4];
int m_flags;
b3ImportMeshData()
:m_gfxShape(0),
m_textureImage1(0),
m_isCached(false),
m_textureWidth(0),
m_textureHeight(0),
m_flags(0)
{
}
};
class b3ImportMeshUtility
{
public:
static bool loadAndRegisterMeshFromFileInternal(const std::string& fileName, b3ImportMeshData& meshData, struct CommonFileIOInterface* fileIO);
};
#endif //B3_IMPORT_MESH_UTILITY_H
| 382 |
458 |
<reponame>zijianjoy/ml-metadata
/* Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef ML_METADATA_GOOGLE_QUERY_FILTER_QUERY_BUILDER_H
#define ML_METADATA_GOOGLE_QUERY_FILTER_QUERY_BUILDER_H
#include "zetasql/resolved_ast/sql_builder.h"
#include "absl/container/btree_map.h"
#include "absl/status/status.h"
namespace ml_metadata {
// FilterQueryBuilder is a ZetaSQL AST Visitor. It walks through a ZetaSQL
// boolean expression AST parsed from a filtering query string and generates
// FROM clauses and WHERE clauses which can be used by MLMD query executors. It
// can be instantiated with MLMD nodes types: Artifact, Execution and Context.
template <typename T>
class FilterQueryBuilder : public zetasql::SQLBuilder {
public:
FilterQueryBuilder();
// Not copyable or movable
FilterQueryBuilder(const FilterQueryBuilder&) = delete;
FilterQueryBuilder& operator=(const FilterQueryBuilder&) = delete;
// Returns the SQL string that can be used in MLMD node listing WHERE clause.
std::string GetWhereClause();
// Returns the SQL string that can be used in MLMD node listing FROM clause.
std::string GetFromClause();
// The alias for the node table used in the query builder implementation.
static constexpr absl::string_view kBaseTableAlias = "table_0";
// Test-use only: to share the join rule details in the implementation.
// Returns part of the join clause depending on the neighborhood.
static std::string GetBaseNodeTable(absl::string_view base_alias);
static std::string GetTypeJoinTable(absl::string_view base_alias,
absl::string_view type_alias);
static std::string GetContextJoinTable(absl::string_view base_alias,
absl::string_view context_alias);
static std::string GetPropertyJoinTable(absl::string_view base_alias,
absl::string_view property_alias,
absl::string_view property_name);
static std::string GetParentContextJoinTable(
absl::string_view base_alias, absl::string_view parent_context_alias);
static std::string GetChildContextJoinTable(
absl::string_view base_alias, absl::string_view child_context_alias);
static std::string GetCustomPropertyJoinTable(
absl::string_view base_alias, absl::string_view property_alias,
absl::string_view property_name);
static std::string GetEventJoinTable(absl::string_view base_alias,
absl::string_view event_alias);
protected:
// Implementation details. API users need not look below.
//
// When navigating to the AST ExpressionColumn nodes, we generate a SQL query
// segmentation by rewriting the parsed node name with proper alias, which is
// later used in FROM clauses against the physical schema.
//
// In filtering query, the expression columns could be
// a) node attributes of the main node
// b) node neighborhood, such as other nodes, events, properties.
//
// For case a), we simply decorate the expression column with the main table
// alias, for b) and c), we follow different rules by adding prefix to the
// the join temporary tables.
//
// For example, the following AST ExpressionColumn node is about an attribute
//
// +-FunctionCall(ZetaSQL:$equal(INT64, INT64) -> BOOL)
// | +-ExpressionColumn(type=INT64, name="type_id")
// | +-Literal(type=INT64, value=6)
//
// The function rewrites `type_id` to `table_0.type_id`, where table_0 is the
// table reference in the physical schema.
//
// For case b), the AST ExpressionColumn node is about a neighbor context:
//
// +-FunctionCall(ZetaSQL:$equal(STRING, STRING) -> BOOL)
// | +-GetStructField
// | | +-type=STRING
// | | +-expr=
// | | | +-ExpressionColumn(type=STRUCT<id INT64, name STRING, type STRING>,
// name="contexts_pipeline")
// | | +-field_idx=1
// | +-Literal(type=STRING, value="taxi")
//
// The function substitutes the contexts_pipelines.type to table_1.type on
// the context table to be joined.
//
// Returns UnimplementedError if any Struct of unknown neighbor is visited.
absl::Status VisitResolvedExpressionColumn(
const zetasql::ResolvedExpressionColumn* node) final;
private:
// For each mentioned expression column, we maintain a mapping of unique
// table alias, which are used for FROM and WHERE clause query generation.
enum class AtomType {
ATTRIBUTE,
CONTEXT,
PROPERTY,
CUSTOM_PROPERTY,
PARENT_CONTEXT,
CHILD_CONTEXT,
EVENT
};
using JoinTableAlias =
absl::btree_map<AtomType, absl::btree_map<std::string, std::string>>;
// A routine maintains the mentioned_alias when constructing the query. It
// auto-increase the alias_index_ when a `atom_type` and `concept_name` is
// first seen when walking through the AST.
std::string GetTableAlias(AtomType atom_type, absl::string_view concept_name);
// The alias names of mentioned tables.
JoinTableAlias mentioned_alias_;
// Auto increased indices used as suffix of different table alias.
// Should always be modified by using GetTableAlias.
int alias_index_ = 0;
};
} // namespace ml_metadata
#endif // ML_METADATA_GOOGLE_QUERY_FILTER_QUERY_BUILDER_H
| 1,916 |
794 |
/******************************************************************************
* Author: <NAME> *
* Contact: <EMAIL> *
* License: Copyright (c) 2013 <NAME>, ANU. 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 ANU 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 ANU OR THE CONTRIBUTORS BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY *
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *
* SUCH DAMAGE. *
******************************************************************************/
#include <opengv/absolute_pose/modules/gpnp1/modules.hpp>
void
opengv::absolute_pose::modules::gpnp1::init(
Eigen::Matrix<double,5,3> & groebnerMatrix,
const Eigen::Matrix<double,12,1> & a,
Eigen::Matrix<double,12,1> & n,
Eigen::Vector3d & c0,
Eigen::Vector3d & c1,
Eigen::Vector3d & c2,
Eigen::Vector3d & c3 )
{
Eigen::Vector3d temp = c0-c1;
double c01w = temp.norm()*temp.norm();
temp = c0-c2;
double c02w = temp.norm()*temp.norm();
temp = c0-c3;
double c03w = temp.norm()*temp.norm();
groebnerMatrix(0,0) = -2*n(0,0)*n(3,0)-2*n(1,0)*n(4,0)-2*n(2,0)*n(5,0)+pow(n(0,0),2)+pow(n(3,0),2)+pow(n(1,0),2)+pow(n(4,0),2)+pow(n(2,0),2)+pow(n(5,0),2);
groebnerMatrix(0,1) = 2*a(0,0)*n(0,0)-2*a(0,0)*n(3,0)-2*n(0,0)*a(3,0)+2*a(3,0)*n(3,0)+2*a(1,0)*n(1,0)-2*a(1,0)*n(4,0)-2*n(1,0)*a(4,0)+2*a(4,0)*n(4,0)+2*a(2,0)*n(2,0)-2*a(2,0)*n(5,0)-2*n(2,0)*a(5,0)+2*a(5,0)*n(5,0);
groebnerMatrix(0,2) = -c01w+pow(a(0,0),2)-2*a(0,0)*a(3,0)+pow(a(3,0),2)+pow(a(1,0),2)-2*a(1,0)*a(4,0)+pow(a(4,0),2)+pow(a(2,0),2)-2*a(2,0)*a(5,0)+pow(a(5,0),2);
groebnerMatrix(1,0) = -2*n(0,0)*n(6,0)-2*n(1,0)*n(7,0)-2*n(2,0)*n(8,0)+pow(n(0,0),2)+pow(n(1,0),2)+pow(n(2,0),2)+pow(n(6,0),2)+pow(n(7,0),2)+pow(n(8,0),2);
groebnerMatrix(1,1) = 2*a(0,0)*n(0,0)+2*a(1,0)*n(1,0)+2*a(2,0)*n(2,0)-2*a(0,0)*n(6,0)-2*n(0,0)*a(6,0)+2*a(6,0)*n(6,0)-2*a(1,0)*n(7,0)-2*n(1,0)*a(7,0)+2*a(7,0)*n(7,0)-2*a(2,0)*n(8,0)-2*n(2,0)*a(8,0)+2*a(8,0)*n(8,0);
groebnerMatrix(1,2) = -c02w+pow(a(0,0),2)+pow(a(1,0),2)+pow(a(2,0),2)-2*a(0,0)*a(6,0)+pow(a(6,0),2)-2*a(1,0)*a(7,0)+pow(a(7,0),2)-2*a(2,0)*a(8,0)+pow(a(8,0),2);
groebnerMatrix(2,0) = -2*n(0,0)*n(9,0)-2*n(1,0)*n(10,0)-2*n(2,0)*n(11,0)+pow(n(0,0),2)+pow(n(1,0),2)+pow(n(2,0),2)+pow(n(9,0),2)+pow(n(10,0),2)+pow(n(11,0),2);
groebnerMatrix(2,1) = 2*a(0,0)*n(0,0)+2*a(1,0)*n(1,0)+2*a(2,0)*n(2,0)-2*a(0,0)*n(9,0)-2*n(0,0)*a(9,0)+2*a(9,0)*n(9,0)-2*a(1,0)*n(10,0)-2*n(1,0)*a(10,0)+2*a(10,0)*n(10,0)-2*a(2,0)*n(11,0)-2*n(2,0)*a(11,0)+2*a(11,0)*n(11,0);
groebnerMatrix(2,2) = -c03w+pow(a(0,0),2)+pow(a(1,0),2)+pow(a(2,0),2)-2*a(0,0)*a(9,0)+pow(a(9,0),2)-2*a(1,0)*a(10,0)+pow(a(10,0),2)-2*a(2,0)*a(11,0)+pow(a(11,0),2);
}
| 2,501 |
925 |
#include "argparse.h"
#include <iostream>
#include <sstream>
#include "completion.h"
#include "globals.h"
using std::endl;
using std::function;
using std::pair;
using std::string;
using std::stringstream;
/**
* @brief try to parse the positional arguments and as many flags
* as possible. When the last positional argument has been read
* then flags are still read until the first unknown token.
* If unknown tokens at the end of input should be regarded as
* an error, use parsingAllFails()
* @param input
* @param output
* @return return whether there has been an error (true = error, false = no error)
*/
bool ArgParse::parsingFails(Input& input, Output& output)
{
size_t mandatoryArguments = 0;
size_t optionalArguments = 0;
for (const auto& arg : arguments_) {
if (arg.optional_) {
optionalArguments++;
} else {
mandatoryArguments++;
}
}
optionalArguments += flags_.size();
if (input.size() < mandatoryArguments) {
output.error() << output.command() << ": Expected ";
if (optionalArguments) {
output.error()
<< "between " << mandatoryArguments
<< " and " << (optionalArguments + mandatoryArguments)
<< " arguments";
} else if (mandatoryArguments == 1) {
output.error() << "one argument";
} else {
output.error() << mandatoryArguments << " arguments";
}
output.error() << ", but got only " << input.size() << " arguments." << endl;
errorCode_ = HERBST_NEED_MORE_ARGS;
return true;
}
// the number of optional arguments that are provided by 'input':
size_t optionalArgumentsRemaining = input.size() - mandatoryArguments;
for (const auto& arg : arguments_) {
if (arg.optional_ && optionalArgumentsRemaining == 0) {
continue;
}
string valueString;
input >> valueString;
// try to parse this token as a flag
while (optionalArgumentsRemaining) {
try {
if (!tryParseFlag(valueString)) {
// if it is not a flag, then break, i.e
// continue with positional args
break;
}
} catch (std::exception& e) {
// if there is a parse error however, then
// stop entire parsing process
output.perror() << "Cannot parse flag \""
<< valueString << "\": " << e.what() << "\n";
errorCode_ = HERBST_INVALID_ARGUMENT;
return true;
}
optionalArgumentsRemaining--;
// if this token was the last optional argument
if (optionalArgumentsRemaining == 0 && arg.optional_) {
// then skip this 'arg'
continue;
}
// otherwise, there is room for another optional
// argument or 'arg' is mandatory. So get another
// token from the input, and parse it to the
// current 'arg'
input >> valueString;
}
// in any case, we have this here:
// assert (!arg.optional_ || optionalArgumentsRemaining > 0);
if (arg.optional_) {
optionalArgumentsRemaining--;
}
try {
arg.tryParse_(valueString);
} catch (std::exception& e) {
output.perror() << "Cannot parse argument \""
<< valueString << "\": " << e.what() << "\n";
errorCode_ = HERBST_INVALID_ARGUMENT;
return true;
}
}
// try to parse more flags after the positional arguments
while (!input.empty()) {
// only consume tokens if they are recognized flags
try {
if (tryParseFlag(input.front())) {
input.shift();
} else {
break;
}
} catch (std::exception& e) {
output.perror() << "Cannot parse flag \""
<< input.front() << "\": " << e.what() << "\n";
errorCode_ = HERBST_INVALID_ARGUMENT;
return true;
}
}
// if all arguments were parsed, then we report that there were
// no errors. It's ok if there are remaining elements in 'input' that
// have not been parsed.
return false;
}
/**
* @brief run parsingFails() and assert that there are no unknown
* tokens left in the input.
* @param input
* @param output
* @return whether there is an unparsable flag or unexpected argument at the end
*/
bool ArgParse::parsingAllFails(Input& input, Output& output)
{
if (parsingFails(input, output)) {
return true;
}
if (unparsedTokens(input, output)) {
output.perror() << "too many arguments" << endl;
return true;
}
return false;
}
bool ArgParse::unparsedTokens(Input& input, Output& output)
{
string extraToken;
if (input >> extraToken) {
output.perror()
<< "Unknown argument or flag \""
<< extraToken << "\" given.\n";
errorCode_ = HERBST_INVALID_ARGUMENT;
return true;
}
return false;
}
/**
* @brief Accept boolean flags (e.g. --all --horizontal ...) at
* any position between the (mandatory or optional) positional arguments
* @param a list of flags
* @return
*/
ArgParse& ArgParse::flags(std::initializer_list<Flag> flagTable)
{
for (auto& it : flagTable) {
// the usual array-style assignment does not work
// because Flag has no parameterless constructor.
// hence, we explicitly call 'insert':
flags_.insert(pair<string, Flag>(it.name_, it));
}
return *this;
}
void ArgParse::command(CallOrComplete invocation, function<int(Output)> command)
{
if (invocation.complete_) {
completion(*(invocation.complete_));
}
if (invocation.inputOutput_) {
int status = 0;
if (parsingAllFails(invocation.inputOutput_->first,
invocation.inputOutput_->second)) {
status = exitCode();
} else {
// if parsing did not fail
status = command(invocation.inputOutput_->second);
}
if (invocation.exitCode_) {
*(invocation.exitCode_) = status;
}
}
}
/**
* @brief Wrapper for commands that use argparse for the first
* arguments, but then do something more complicated with the not
* yet parsed tokens after the positional arguments and flags.
* @param invocation
* @param the completion function for the later tokens
* @param the command, taking unparsed tokens
*/
void ArgParse::command(CallOrComplete invocation,
function<void (Completion&)> complete,
function<int (ArgList, Output)> command)
{
if (invocation.complete_) {
completion(*(invocation.complete_));
// for the nested completion, we first try to parse
// as many arguments, and then parse the remaining tokens
// to the nested 'complete':
// step 1: try to parse tokens
// we don't know the command name at this point,
// but it does not matter, so let us pick "argparse"
Input input { "argparse", invocation.complete_->args_.toVector()};
stringstream dummyStream;
OutputChannels discardOutputChannels("argparse", dummyStream, dummyStream);
size_t tokensBeforeParsing = input.size();
if (!parsingFails(input, discardOutputChannels)) {
// if parsing does not fail, then let the nested
// completion function decide if further parameters are expected,
// so unset the flag:
invocation.complete_->noParameterExpected_ = false;
// step 2: create a new completion object by dropping the
// successfully parsed tokens:
size_t tokensAfterParsing = input.size();
HSAssert(tokensAfterParsing <= tokensBeforeParsing);
size_t tokensParsed = tokensBeforeParsing - tokensAfterParsing;
if (invocation.complete_->index() >= tokensParsed) {
// if we are asked to complete an argument that comes
// after the already parsed tokens.
// step 3: pass the remaining tokens to the custom completion:
Completion shifted = invocation.complete_->shifted(tokensParsed);
complete(shifted);
invocation.complete_->mergeResultsFrom(shifted);
}
}
}
if (invocation.inputOutput_) {
int status = 0;
if (parsingFails(invocation.inputOutput_->first,
invocation.inputOutput_->second)) {
status = exitCode();
} else {
// if parsing did not fail, extract the remaining tokens:
ArgList remainingTokens = {
invocation.inputOutput_->first.begin(),
invocation.inputOutput_->first.end()
};
status = command(remainingTokens, invocation.inputOutput_->second);
}
if (invocation.exitCode_) {
*(invocation.exitCode_) = status;
}
}
}
void ArgParse::completion(Completion& complete)
{
size_t completionIndex = complete.index();
std::set<Flag*> flagsPassedSoFar;
for (size_t i = 0; i < completionIndex; i++) {
Flag* flag = findFlag(complete[i]);
if (flag) {
flagsPassedSoFar.insert(flag);
}
}
if (completionIndex - flagsPassedSoFar.size() > arguments_.size()) {
// if there were too many arguments passed
// already, then don't allow further arguments
complete.none();
return;
}
bool argsStillPossible = false;
// complete the unused flags:
for (auto& it : flags_) {
if (flagsPassedSoFar.find(&(it.second)) == flagsPassedSoFar.end()) {
// complete names of flags that were not mentioned so far
it.second.complete(complete);
argsStillPossible = true;
}
}
// the index of the current argument when neglecting
// the flags
size_t positionalIndex = completionIndex - flagsPassedSoFar.size();
// we iterate through all arguments_ to determine which of them
// might be possible at positionalIndex
size_t minPossibleIdx = 0;
size_t maxPossibleIdx = 0;
for (const auto& arg : arguments_) {
if (minPossibleIdx <= positionalIndex
&& positionalIndex <= maxPossibleIdx)
{
arg.complete_(complete);
for (const auto& suggestion : arg.completionSuggestions_) {
complete.full(suggestion);
}
argsStillPossible = true;
}
maxPossibleIdx++;
if (!arg.optional_) {
minPossibleIdx++;
}
}
if (!argsStillPossible) {
complete.none();
}
}
/**
* @brief try to parse a flag, possibly throwing an exception
* on a parse error.
* @param argument token from a Input object
* @return whether the token was a flag
*/
bool ArgParse::tryParseFlag(const string& inputToken)
{
Flag* flag = findFlag(inputToken);
if (!flag) {
// stop parsing flags on the first non-flag
return false;
}
string parameter = "";
if (inputToken.size() != flag->name_.size()) {
parameter = inputToken.substr(flag->name_.size());
}
flag->callback_(parameter);
return true;
}
/**
* @brief Find a flag that is appropriate for a given inputToken
* @param the token
* @return A flag or a nullptr
*/
ArgParse::Flag* ArgParse::findFlag(const string& inputToken)
{
string needle = inputToken;
size_t separatorPos = inputToken.find("=");
if (separatorPos != string::npos) {
needle = inputToken.substr(0, separatorPos + 1);
}
auto flag = flags_.find(needle);
if (flag == flags_.end()) {
return nullptr;
} else {
return &(flag->second);
}
}
void ArgParse::Flag::complete(Completion& completion)
{
if (!name_.empty() && *name_.rbegin() == '=') {
// complete partially with argument
completion.partial(name_);
// use completion
completion.withPrefix(name_, parameterTypeCompletion_);
} else {
// ordinary flag that is either present or absent:
completion.full(name_);
}
}
| 5,209 |
322 |
<gh_stars>100-1000
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2019-2020, LAAS-CNRS, University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#ifndef CROCODDYL_MULTIBODY_NUMDIFF_COST_HPP_
#define CROCODDYL_MULTIBODY_NUMDIFF_COST_HPP_
#include "crocoddyl/core/utils/deprecate.hpp"
CROCODDYL_PRAGMA_DEPRECATED_HEADER("crocoddyl/multibody/numdiff/cost-sum.hpp", "crocoddyl/core/numdiff/cost-sum.hpp")
#include "crocoddyl/core/numdiff/cost.hpp"
#endif // CROCODDYL_MULTIBODY_NUMDIFF_COST_HPP_
| 242 |
1,303 |
<reponame>oWASDo/OpenglEngine
/****************************************************************************************
Copyright (C) 2015 Autodesk, Inc.
All rights reserved.
Use of this software is subject to the terms of the Autodesk license agreement
provided at the time of installation or download, or which otherwise accompanies
this software in either electronic or hard copy form.
****************************************************************************************/
//! \file fbxplugin.h
#ifndef _FBXSDK_CORE_PLUGIN_H_
#define _FBXSDK_CORE_PLUGIN_H_
#include <fbxsdk/fbxsdk_def.h>
#ifndef FBXSDK_ENV_WINSTORE
#include <fbxsdk/core/fbxobject.h>
#include <fbxsdk/core/fbxmodule.h>
#include <fbxsdk/core/fbxlistener.h>
#include <fbxsdk/fbxsdk_nsbegin.h>
class FbxManager;
class FbxPluginContainer;
//! Plug-in declaration macro that must to be used when defining new FbxPlugin objects.
#define FBXSDK_PLUGIN_DECLARE(Plugin)\
FBXSDK_FRIEND_NEW();\
public:\
static Plugin * Create(const FbxPluginDef& pDefinition, FbxModule pModuleHandle);\
void Destroy();
//! Plug-in implementation macro that must be used when implementing new FbxPlugin objects.
#define FBXSDK_PLUGIN_IMPLEMENT(Plugin)\
Plugin* Plugin::Create(const FbxPluginDef& pDefinition, FbxModule pModuleHandle){ return FbxNew<Plugin>(pDefinition, pModuleHandle); }\
void Plugin::Destroy(){ FbxDelete(this); }
/** Structure used by plug-ins for identification purposes.
* \note To avoid confusions in the system, it is recommended to choose an appropriate unique identifier string name when
* defining your plug-in, as well as incrementing the version string to a correct value whenever something changes in the
* implementation of the plug-in. Both of these string are used when comparing plug-ins for searches, as well as
* identification in FBX files.
*/
struct FBXSDK_DLL FbxPluginDef
{
//! Constructor
FbxPluginDef() :
mName("Unknown Name"),
mVersion("Unknown Version")
{
}
FbxString mName; //!< The identifier name string of the plug-in. If the name is already used by another plug-in, the plug-in will still register.
FbxString mVersion; //!< The version string of the plug-in.
};
/** Data used to communicate information between an application and the plug-in.
*/
struct FBXSDK_DLL FbxPluginData
{
//! Constructor
FbxPluginData() :
mQueryEmitter(NULL),
mSDKManager(NULL),
mPluginContainer(NULL)
{
}
//! Copy Constructor
explicit FbxPluginData(const FbxPluginData& pOther) :
mQueryEmitter(pOther.mQueryEmitter),
mSDKManager(pOther.mSDKManager),
mPluginContainer(pOther.mPluginContainer)
{
}
FbxEmitter* mQueryEmitter; //!< The emitter on which the plug-in can listen to receive events.
FbxManager* mSDKManager; //!< The FBX SDK Manager on which the plug-in was instanced.
FbxPluginContainer* mPluginContainer; //!< The container which will have the ownership of the plug-in.
};
/** The base class to inherit from when creating new plug-ins for the FBX SDK. Plug-ins for the FBX SDK are extremely flexible
* allowing a wide-range of possibilities. For example, one can write his own plug-in to add new readers/writers to the current list
* of supported I/O formats, or add new dynamic classes to instantiate custom objects that can later be stored in FBX files. We also use the same
* interface for plug-ins written using the FBX Extension SDK, which allow additional callbacks for other various Autodesk products
* enabling greater interoperability with multiple various SDKs.
*
* Here is typical implementation of an FBX SDK plug-in that doesn't do anything else than just registering itself:
* \code
* class MyPlugin : public FbxPlugin
* {
* FBXSDK_PLUGIN_DECLARE(MyPlugin); //This macro is mandatory for any plug-in definition
*
* protected:
* explicit MyPlugin(const FbxPluginDef& pDefinition, FbxModule pModuleHandle) : FbxPlugin(pDefinition, pModuleHandle)
* {
* }
*
* //Abstract functions that *must* be implemented
* virtual bool SpecificInitialize()
* {
* //For example, here we could register as many new I/O readers/writers as we would like, or classes, etc.
* return true;
* }
*
* virtual bool SpecificTerminate()
* {
* //Here we would have to unregister whatever we registered to the FBX SDK
* return true;
* }
* };
*
* FBXSDK_PLUGIN_IMPLEMENT(MyPlugin); //This macro is mandatory for any plug-in implementation
*
* //Standard C export needed for any new FBX SDK plug-in
* extern "C"
* {
* static MyPlugin* sMyPluginInstance = NULL; //The module is owner of the plug-in
*
* //This function will be called when an application will request the plug-in
* #ifdef FBXSDK_ENV_WIN
* __declspec(dllexport) void FBXPluginRegistration(FbxPluginContainer& pContainer, FbxModule pModuleHandle)
* #else
* void FBXPluginRegistration(FbxPluginContainer& pContainer, FbxModule pModuleHandle)
* #endif
* {
* if( sPlugin == NULL )
* {
* //Create the plug-in definition which contains the information about the plug-in
* FbxPluginDef sPluginDef;
* sPluginDef.mName = "My Plugin";
* sPluginDef.mVersion = "1.0";
*
* //Create an instance of the plug-in
* sMyPluginInstance = MyPlugin::Create(sPluginDef, pLibHandle);
*
* //Register the plug-in with the FBX SDK
* pContainer.Register(*sPlugin);
* }
* }
* }
* \endcode
* \see FbxPluginDef, FbxPluginData
*/
class FBXSDK_DLL FbxPlugin : public FbxListener
{
FBXSDK_INTRUSIVE_LIST_NODE(FbxPlugin, 1);
public:
/** Abstract function called once at the end of the plug-in construction. At that moment, plug-in data have been properly initialized.
* This function must be implemented by anyone who writes a new plug-in for the FBX SDK.
*/
virtual bool SpecificInitialize()=0;
/** Abstract function called once at the beginning of the plug-in destruction. At that moment, plug-in data is fully available.
* This function must be implemented by anyone who writes a new plug-in for the FBX SDK.
*/
virtual bool SpecificTerminate()=0;
/** Virtual function called once when the FBX SDK is about to write an FBX file. Users can re-implement it in their plug-in if they need
* to perform tasks at that moment. The scene provided in parameter can be altered. If not re-implemented, this function does nothing.
* \param pScene The scene that is about to be written in the FBX file.
*/
virtual void WriteBegin(FbxScene& pScene);
/** Virtual function called once when the FBX SDK is about to write plug-in's parameters. Users can re-implement it in their plug-in if they need
* to store properties in the FBX file for their own usage. The object in parameter is used to store those properties.
* If not re-implemented, this function does nothing.
* \param pParams An abstract object that can be used as a property container, to allow the plug-in to store properties about the plug-in.
*/
virtual void WriteParameters(FbxObject& pParams);
/** Virtual function called once after the FBX SDK wrote an FBX file. Users can re-implement it in their plug-in if they need
* to perform tasks at that moment. The scene provided in parameter can be altered, but the changes will not appear in the FBX file.
* If not re-implemented, this function does nothing.
* \param pScene The scene that was written in the FBX file.
*/
virtual void WriteEnd(FbxScene& pScene);
/** Virtual function called once when the FBX SDK is about to read an FBX file. Users can re-implement it in their plug-in if they need
* to perform tasks at that moment. The scene provided in parameter can be altered. If not re-implemented, this function does nothing.
* \param pScene The scene that is about to be read in the FBX file.
*/
virtual void ReadBegin(FbxScene& pScene);
/** Virtual function called once after the FBX SDK reads the plug-in's parameters. Users can re-implement it in their plug-in if they need
* to retrieve properties for their own usage. The object in parameter is used to retrieve those properties.
* If not re-implemented, this function does nothing.
* \param pParams An abstract object that can be used as a property container, to allow the plug-in to read properties about the plug-in.
*/
virtual void ReadParameters(FbxObject& pParams);
/** Virtual function called once after the FBX SDK read an FBX file. Users can re-implement it in their plug-in if they need
* to perform tasks at that moment. The scene provided in parameter can be altered. If not re-implemented, this function does nothing.
* \param pScene The scene that was read in the FBX file.
*/
virtual void ReadEnd(FbxScene& pScene);
/** Accessor to the plug-in definition structure that contains basic information on the plug-in like its name or version. This is
* the only method available to differentiate plug-ins.
* \return The definition structure for this plug-in.
*/
const FbxPluginDef& GetDefinition() const;
/** Retrieve the module address pointer for this plug-in. With this module instance handle, for example someone can query procedures addresses,
* allowing more complex interactions, as well as other operating system module specific functions.
*/
FbxModule GetModuleHdl();
protected:
/** Use the Create() and Destroy() methods declared and implemented in the FBXSDK_PLUGIN_DECLARE and FBXSDK_PLUGIN_IMPLEMENT macros to construct and destroy FbxPlugin objects.
* \param pDefinition The definition associated with this plug-in. Each plug-in must have its own definition to differentiate it with other plug-ins.
* \param pModuleHandle A pointer to the plug-in module address.
*/
explicit FbxPlugin(const FbxPluginDef& pDefinition, FbxModule pModuleHandle);
/** Accessor to the plug-in private data.
* \return The data for the current plug-in.
*/
FbxPluginData& GetData();
/** Const accessor to the plug-in private data.
* \return The const data for the current plug-in.
*/
const FbxPluginData& GetData() const;
/*****************************************************************************************************************************
** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! **
*****************************************************************************************************************************/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
public:
inline FbxObject& GetPluginSettings() { return *mPluginSettings; }
inline const FbxObject& GetPluginSettings() const { return *mPluginSettings; }
template <typename EventType, typename ListernerType> inline FbxEventHandler* Bind(void (ListernerType::*pFunc)(const EventType*))
{
return FbxListener::Bind<EventType,ListernerType>(*(GetData().mQueryEmitter), pFunc );
}
virtual void Destroy() = 0;
protected:
virtual ~FbxPlugin();
private:
bool Initialize(const FbxPluginData& pData);
bool Terminate();
bool mInitialized;
FbxPluginData mData;
FbxPluginDef mDefinition;
FbxModule mModuleHandle;
FbxObject* mPluginSettings;
friend class FbxLoadingStrategy;
#endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/
};
#include <fbxsdk/fbxsdk_nsend.h>
#endif /* !FBXSDK_ENV_WINSTORE */
#endif /* _FBXSDK_CORE_PLUGIN_H_ */
| 3,633 |
1,169 |
<gh_stars>1000+
package com.zhengsr.viewpagerlib.bean;
/**
* @author by zhengshaorui on 2019/10/8
* Describe: RectIndicator 的自定义属性
*/
public class RectBean {
/**
* 圆点默认颜色
*/
public int normalColor = -2;
/**
* 圆点选中颜色
*/
public int selectedColor = -2;
/**
* 矩形之间的margin
*/
public int horizonMargin;
/**
* 是否可以移动的,默认为true
*/
public boolean isCanMove = true;
/**
* 矩形的宽度
*/
public int width;
/**
* 矩形的高度
*/
public int height;
/**
* 矩形的圆角
*/
public int roundRadius;
}
| 370 |
484 |
<filename>doc/src/snippets/boost-only/asio_integration.cpp
/* Example of Outcome
(C) 2017-2019 <NAME> <http://www.nedproductions.biz/> (3 commits)
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 in the accompanying file
Licence.txt or 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.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file Licence.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/asio/async_result.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/experimental.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/outcome.hpp>
#include <vector>
namespace asio = boost::asio;
namespace outcome = boost::outcome_v2;
using byte = char;
using boost::system::error_code;
void old(asio::ip::tcp::socket skt)
{
//! [old-use-case]
// Dynamically allocate a buffer to read into. This must be move-only
// so it can be attached to the completion handler, hence the unique_ptr.
auto buffer = std::make_unique<std::vector<byte>>(1024);
// Begin an asynchronous socket read, upon completion invoke
// the lambda function specified
skt.async_read_some(asio::buffer(buffer->data(), buffer->size()),
// Retain lifetime of the i/o buffer until completion
[buffer = std::move(buffer)](const error_code &ec, size_t bytes) {
// Handle the buffer read
if(ec)
{
std::cerr << "Buffer read failed with " << ec << std::endl;
return;
}
std::cout << "Read " << bytes << " bytes into buffer" << std::endl;
// buffer will be dynamically freed now
});
//! [old-use-case]
}
asio::experimental::awaitable<void> new_(asio::ip::tcp::socket skt)
{
//! [new-use-case]
// As coroutines suspend the calling thread whilst an asynchronous
// operation executes, we can use stack allocation instead of dynamic
// allocation
char buffer[1024];
// Get an ASIO completion token for the current coroutine (requires
// Coroutines TS)
asio::experimental::await_token token = //
co_await asio::experimental::this_coro::token();
// Asynchronously read data, suspending this coroutine until completion,
// returning the bytes of the data read into the result.
try
{
size_t bytesread = //
co_await skt.async_read_some(asio::buffer(buffer), token);
std::cout << "Read " << bytesread << " bytes into buffer" << std::endl;
}
catch(const std::system_error &e)
{
std::cerr << "Buffer read failed with " << e.what() << std::endl;
}
//! [new-use-case]
}
//! [as_result]
namespace detail
{
// Type sugar for wrapping an external completion token
template <class CompletionToken> struct as_result_t
{
CompletionToken token;
};
} // namespace detail
// Factory function for wrapping a third party completion token with
// our type sugar
template <class CompletionToken> //
inline auto as_result(CompletionToken &&token)
{
return detail::as_result_t<std::decay_t<CompletionToken>>{std::forward<CompletionToken>(token)};
};
//! [as_result]
//! [async_result1]
// Tell ASIO about a new kind of completion token, the kind returned
// from our as_result() factory function. This implementation is
// for functions with handlers void(error_code, T) only.
template <class CompletionToken, class T> //
struct asio::async_result<detail::as_result_t<CompletionToken>, //
void(error_code, T)> //
// NOTE we subclass for an async result taking an outcome::result
// as its completion handler. We will mangle the void(error_code, T)
// completion handler into this completion handler below.
: public asio::async_result<CompletionToken, void(outcome::result<T, error_code>)>
{
// The result type we shall return
using result_type = outcome::result<T, error_code>;
using _base = asio::async_result<CompletionToken, void(result_type)>;
// The awaitable type to be returned by the initiating function,
// the co_await of which will yield a result_type
using return_type = typename _base::return_type;
// Get what would be the completion handler for the async_result
// whose completion handler is void(result_type)
using result_type_completion_handler_type = //
typename _base::completion_handler_type;
//! [async_result1]
//! [async_result2]
// Wrap that completion handler with void(error_code, T) converting
// handler
struct completion_handler_type
{
// Pass through unwrapped completion token
template <class U>
completion_handler_type(::detail::as_result_t<U> &&ch)
: _handler(std::forward<U>(ch.token))
{
}
// Our completion handler spec
void operator()(error_code ec, T v)
{
// Call the underlying completion handler, whose
// completion function is void(result_type)
if(ec)
{
// Complete with a failed result
_handler(result_type(outcome::failure(ec)));
return;
}
// Complete with a successful result
_handler(result_type(outcome::success(v)));
}
result_type_completion_handler_type _handler;
};
// Initialise base with the underlying completion handler
async_result(completion_handler_type &h)
: _base(h._handler)
{
}
using _base::get;
};
//! [async_result2]
asio::experimental::awaitable<void> outcome_(asio::ip::tcp::socket skt)
{
char buffer[1024];
asio::experimental::await_token token = co_await asio::experimental::this_coro::token();
#if 0
{ // debug
using my_result_t = decltype(as_result(token));
asio::async_result<my_result_t, void(error_code, size_t)>::completion_handler_type handler(as_result(token));
asio::async_result<my_result_t, void(error_code, size_t)> result(handler);
error_code ec;
handler(ec, 5);
outcome::result<size_t, error_code> r = co_await result.get();
}
#endif
#if 1
//! [outcome-use-case]
// Asynchronously read data, suspending this coroutine until completion,
// returning the bytes of the data read into the result, or any failure.
outcome::result<size_t, error_code> bytesread = //
co_await skt.async_read_some(asio::buffer(buffer), as_result(token));
// Usage is exactly like ordinary Outcome. Note the lack of exception throw!
if(bytesread.has_error())
{
std::cerr << "Buffer read failed with " << bytesread.error() << std::endl;
return;
}
std::cout << "Read " << bytesread.value() << " bytes into buffer" << std::endl;
//! [outcome-use-case]
#endif
}
int main(void)
{
return 0;
}
| 2,580 |
3,083 |
<gh_stars>1000+
/*
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.disassembly.types;
import static org.junit.Assert.assertEquals;
import com.google.common.base.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* This class contains tests related to {@link RawTypeMember raw type members}.
*/
@RunWith(JUnit4.class)
public class RawTypeMemberTests {
private static final int ID = 1;
private static final String NAME = "test_raw_type_member";
private static final int BASE_TYPE_ID = 2;
private static final Integer PARENT_ID = 3;
private static final Integer OFFSET = 20;
private static final Integer ARGUMENT = 30;
private static final int NUMBER_OF_ELEMENTS = 100;
@Test
public void testConstruction() {
final RawTypeMember rawMember =
new RawTypeMember(ID, NAME, BASE_TYPE_ID, PARENT_ID, OFFSET, null, NUMBER_OF_ELEMENTS);
assertEquals(ID, rawMember.getId());
assertEquals(NAME, rawMember.getName());
assertEquals(BASE_TYPE_ID, rawMember.getBaseTypeId());
assertEquals(PARENT_ID, rawMember.getParentId());
assertEquals(Optional.<Integer> of(OFFSET), rawMember.getOffset());
assertEquals(Optional.<Integer> absent(), rawMember.getArgumentIndex());
assertEquals(Optional.<Integer> of(NUMBER_OF_ELEMENTS), rawMember.getNumberOfElements());
}
@Test(expected = NullPointerException.class)
public void testInvalidConstruction0() {
new RawTypeMember(ID, null, BASE_TYPE_ID, PARENT_ID, OFFSET, ARGUMENT, NUMBER_OF_ELEMENTS);
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidConstruction1() {
new RawTypeMember(ID, NAME, BASE_TYPE_ID, PARENT_ID, -10, ARGUMENT, NUMBER_OF_ELEMENTS);
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidConstruction2() {
new RawTypeMember(ID, NAME, BASE_TYPE_ID, PARENT_ID, OFFSET, ARGUMENT, -1);
}
}
| 802 |
1,083 |
<filename>core/src/main/java/org/apache/carbondata/core/scan/collector/impl/AbstractScannedResultCollector.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.carbondata.core.scan.collector.impl;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.apache.carbondata.core.datastore.page.ColumnPage;
import org.apache.carbondata.core.metadata.datatype.DataType;
import org.apache.carbondata.core.metadata.datatype.DataTypes;
import org.apache.carbondata.core.metadata.schema.table.column.CarbonMeasure;
import org.apache.carbondata.core.scan.collector.ScannedResultCollector;
import org.apache.carbondata.core.scan.executor.infos.BlockExecutionInfo;
import org.apache.carbondata.core.scan.executor.infos.DimensionInfo;
import org.apache.carbondata.core.scan.executor.infos.MeasureInfo;
import org.apache.carbondata.core.scan.model.ProjectionMeasure;
import org.apache.carbondata.core.scan.result.BlockletScannedResult;
import org.apache.carbondata.core.scan.result.vector.CarbonColumnarBatch;
import org.apache.carbondata.core.stats.QueryStatisticsModel;
import org.apache.carbondata.core.util.DataTypeUtil;
/**
* It is not a collector it is just a scanned result holder.
*/
public abstract class AbstractScannedResultCollector implements ScannedResultCollector {
/**
* table block execution infos
*/
BlockExecutionInfo executionInfo;
/**
* maintains the measure information like datatype, ordinal, measure existence
*/
MeasureInfo measureInfo;
/**
* maintains the dimension information like datatype, ordinal, measure existence
*/
DimensionInfo dimensionInfo;
/**
* model object to be used for collecting query statistics during normal query execution,
* compaction and other flows that uses the query flow
*/
QueryStatisticsModel queryStatisticsModel;
AbstractScannedResultCollector(BlockExecutionInfo blockExecutionInfos) {
this.executionInfo = blockExecutionInfos;
measureInfo = blockExecutionInfos.getMeasureInfo();
dimensionInfo = blockExecutionInfos.getDimensionInfo();
this.queryStatisticsModel = blockExecutionInfos.getQueryStatisticsModel();
}
protected void fillMeasureData(Object[] msrValues, int offset,
BlockletScannedResult scannedResult) {
int measureExistIndex = 0;
for (short i = 0; i < measureInfo.getMeasureDataTypes().length; i++) {
// if measure exists is block then pass measure column
// data chunk to the collector
if (measureInfo.getMeasureExists()[i]) {
ProjectionMeasure queryMeasure = executionInfo.getProjectionMeasures()[measureExistIndex];
msrValues[i + offset] = getMeasureData(
scannedResult.getMeasureChunk(measureInfo.getMeasureOrdinals()[measureExistIndex]),
scannedResult.getCurrentRowId(), queryMeasure.getMeasure());
measureExistIndex++;
} else {
// if not then get the default value and use that value in aggregation
Object defaultValue = measureInfo.getDefaultValues()[i];
if (null != defaultValue && DataTypes.isDecimal(measureInfo.getMeasureDataTypes()[i])) {
// convert data type as per the computing engine
defaultValue =
DataTypeUtil.getDataTypeConverter().convertFromBigDecimalToDecimal(defaultValue);
}
msrValues[i + offset] = defaultValue;
}
}
}
/**
* This method will be used to fill measure data column wise
*
* @param rows
* @param offset
* @param scannedResult
*/
protected void fillMeasureDataBatch(List<Object[]> rows, int offset,
BlockletScannedResult scannedResult) {
int measureExistIndex = 0;
for (short i = 0; i < measureInfo.getMeasureDataTypes().length; i++) {
// if measure exists is block then pass measure column
// data chunk to the collector
if (measureInfo.getMeasureExists()[i]) {
ProjectionMeasure queryMeasure = executionInfo.getProjectionMeasures()[measureExistIndex];
ColumnPage measureChunk =
scannedResult.getMeasureChunk(measureInfo.getMeasureOrdinals()[measureExistIndex]);
for (short j = 0; j < rows.size(); j++) {
Object[] rowValues = rows.get(j);
rowValues[i + offset] =
getMeasureData(measureChunk, scannedResult.getValidRowIds().get(j),
queryMeasure.getMeasure());
}
measureExistIndex++;
} else {
// if not then get the default value and use that value in aggregation
Object defaultValue = measureInfo.getDefaultValues()[i];
if (null != defaultValue && DataTypes.isDecimal(measureInfo.getMeasureDataTypes()[i])) {
// convert data type as per the computing engine
defaultValue =
DataTypeUtil.getDataTypeConverter().convertFromBigDecimalToDecimal(defaultValue);
}
for (Object[] rowValues : rows) {
rowValues[i + offset] = defaultValue;
}
}
}
}
Object getMeasureData(ColumnPage dataChunk, int index, CarbonMeasure carbonMeasure) {
if (!dataChunk.getNullBits().get(index)) {
DataType dataType = carbonMeasure.getDataType();
if (dataType == DataTypes.BOOLEAN) {
return dataChunk.getBoolean(index);
} else if (dataType == DataTypes.SHORT) {
return (short) dataChunk.getLong(index);
} else if (dataType == DataTypes.INT) {
return (int) dataChunk.getLong(index);
} else if (dataType == DataTypes.LONG) {
return dataChunk.getLong(index);
} else if (dataType == DataTypes.FLOAT) {
return dataChunk.getFloat(index);
} else if (dataType == DataTypes.BYTE) {
return dataChunk.getByte(index);
} else if (DataTypes.isDecimal(dataType)) {
BigDecimal bigDecimalMsrValue = dataChunk.getDecimal(index);
if (null != bigDecimalMsrValue && carbonMeasure.getScale() > bigDecimalMsrValue.scale()) {
bigDecimalMsrValue =
bigDecimalMsrValue.setScale(carbonMeasure.getScale(), RoundingMode.HALF_UP);
}
// convert data type as per the computing engine
return DataTypeUtil.getDataTypeConverter().convertFromBigDecimalToDecimal(
bigDecimalMsrValue);
} else {
return dataChunk.getDouble(index);
}
}
return null;
}
@Override
public void collectResultInColumnarBatch(BlockletScannedResult scannedResult,
CarbonColumnarBatch columnarBatch) {
throw new UnsupportedOperationException("Works only for batch collectors");
}
}
| 2,535 |
778 |
<gh_stars>100-1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.api;
import static org.testng.Assert.fail;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.impl.ProducerBuilderImpl;
import org.apache.pulsar.client.impl.ProducerImpl;
import org.apache.pulsar.common.naming.TopicDomain;
import org.apache.pulsar.common.naming.TopicName;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@Test(groups = "broker-api")
public class ProducerCreationTest extends ProducerConsumerBase {
@BeforeMethod
@Override
protected void setup() throws Exception {
super.internalSetup();
super.producerBaseSetup();
}
@AfterMethod(alwaysRun = true)
@Override
protected void cleanup() throws Exception {
super.internalCleanup();
}
@DataProvider(name = "topicDomainProvider")
public Object[][] topicDomainProvider() {
return new Object[][] {
{ TopicDomain.persistent },
{ TopicDomain.non_persistent }
};
}
@Test(dataProvider = "topicDomainProvider")
public void testExactlyOnceWithProducerNameSpecified(TopicDomain domain) throws PulsarClientException {
Producer<byte[]> producer1 = pulsarClient.newProducer()
.topic(TopicName.get(domain.value(), "public", "default", "testExactlyOnceWithProducerNameSpecified").toString())
.producerName("p-name-1")
.create();
Assert.assertNotNull(producer1);
Producer<byte[]> producer2 = pulsarClient.newProducer()
.topic("testExactlyOnceWithProducerNameSpecified")
.producerName("p-name-2")
.create();
Assert.assertNotNull(producer2);
try {
pulsarClient.newProducer()
.topic("testExactlyOnceWithProducerNameSpecified")
.producerName("p-name-2")
.create();
Assert.fail("should be failed");
} catch (PulsarClientException.ProducerBusyException e) {
//ok here
}
}
@Test(dataProvider = "topicDomainProvider")
public void testGeneratedNameProducerReconnect(TopicDomain domain) throws PulsarClientException, InterruptedException {
ProducerImpl<byte[]> producer = (ProducerImpl<byte[]>) pulsarClient.newProducer()
.topic(TopicName.get(domain.value(), "public", "default", "testGeneratedNameProducerReconnect").toString())
.create();
Assert.assertTrue(producer.isConnected());
//simulate create producer timeout.
Thread.sleep(3000);
producer.getConnectionHandler().connectionClosed(producer.getConnectionHandler().cnx());
Assert.assertFalse(producer.isConnected());
Thread.sleep(3000);
Assert.assertEquals(producer.getConnectionHandler().getEpoch(), 1);
Assert.assertTrue(producer.isConnected());
}
@Test(dataProvider = "topicDomainProvider")
public void testInitialSubscriptionCreation(TopicDomain domain) throws PulsarClientException, PulsarAdminException {
final String initialSubscriptionName = "init-sub";
final TopicName topic = TopicName.get(domain.value(), "public", "default", "testInitialSubscriptionCreation");
// Should not create initial subscription when the initialSubscriptionName is null or empty
Producer<byte[]> nullInitSubProducer = ((ProducerBuilderImpl<byte[]>) pulsarClient.newProducer())
.initialSubscriptionName(null)
.topic(topic.toString())
.create();
nullInitSubProducer.close();
Assert.assertFalse(admin.topics().getSubscriptions(topic.toString()).contains(initialSubscriptionName));
Producer<byte[]> emptyInitSubProducer = ((ProducerBuilderImpl<byte[]>) pulsarClient.newProducer())
.initialSubscriptionName("")
.topic(topic.toString())
.create();
emptyInitSubProducer.close();
Assert.assertFalse(admin.topics().getSubscriptions(topic.toString()).contains(initialSubscriptionName));
Producer<byte[]> producer = ((ProducerBuilderImpl<byte[]>) pulsarClient.newProducer())
.initialSubscriptionName(initialSubscriptionName)
.topic(topic.toString())
.create();
producer.close();
// Initial subscription will only be created if the topic is persistent
Assert.assertEquals(topic.isPersistent(),
admin.topics().getSubscriptions(topic.toString()).contains(initialSubscriptionName));
// Existing subscription should not fail the producer creation.
Producer<byte[]> otherProducer = ((ProducerBuilderImpl<byte[]>) pulsarClient.newProducer())
.initialSubscriptionName(initialSubscriptionName)
.topic(topic.toString())
.create();
otherProducer.close();
Assert.assertEquals(topic.isPersistent(),
admin.topics().getSubscriptions(topic.toString()).contains(initialSubscriptionName));
}
@Test
public void testCreateInitialSubscriptionOnPartitionedTopic() throws PulsarAdminException, PulsarClientException {
final TopicName topic =
TopicName.get("persistent", "public", "default", "testCreateInitialSubscriptionOnPartitionedTopic");
final String initialSubscriptionName = "init-sub";
admin.topics().createPartitionedTopic(topic.toString(), 10);
Producer<byte[]> producer = ((ProducerBuilderImpl<byte[]>) pulsarClient.newProducer())
.initialSubscriptionName(initialSubscriptionName)
.topic(topic.toString())
.create();
producer.close();
Assert.assertTrue(admin.topics().getSubscriptions(topic.toString()).contains(initialSubscriptionName));
}
@Test
public void testCreateInitialSubscriptionWhenExisting() throws PulsarClientException, PulsarAdminException {
final TopicName topic =
TopicName.get("persistent", "public", "default", "testCreateInitialSubscriptionWhenExisting");
final String initialSubscriptionName = "init-sub";
admin.topics().createNonPartitionedTopic(topic.toString());
admin.topics().createSubscription(topic.toString(), initialSubscriptionName, MessageId.earliest);
Producer<byte[]> producer = ((ProducerBuilderImpl<byte[]>) pulsarClient.newProducer())
.initialSubscriptionName(initialSubscriptionName)
.topic(topic.toString())
.create();
producer.close();
Assert.assertTrue(admin.topics().getSubscriptions(topic.toString()).contains(initialSubscriptionName));
}
@Test
public void testInitialSubscriptionCreationWithAutoCreationDisable()
throws PulsarAdminException, PulsarClientException {
pulsar.getConfiguration().setAllowAutoSubscriptionCreation(false);
final TopicName topic =
TopicName.get("persistent", "public", "default",
"testInitialSubscriptionCreationWithAutoCreationDisable");
final String initialSubscriptionName = "init-sub";
admin.topics().createNonPartitionedTopic(topic.toString());
try {
Producer<byte[]> producer = ((ProducerBuilderImpl<byte[]>) pulsarClient.newProducer())
.initialSubscriptionName(initialSubscriptionName)
.topic(topic.toString())
.create();
fail("Should not pass");
} catch (PulsarClientException.NotAllowedException exception) {
// ok
}
Assert.assertFalse(admin.topics().getSubscriptions(topic.toString()).contains(initialSubscriptionName));
}
}
| 3,313 |
6,958 |
//
// ShapeReshape.cpp
// MNN
//
// Created by MNN on 2019/01/10.
// Copyright © 2018, Alibaba Group Holding Limited
//
#include "shape/SizeComputer.hpp"
#include "core/Macro.h"
#include "core/TensorUtils.hpp"
namespace MNN {
class FlattenComputer : public SizeComputer {
public:
// Ref: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Flatten
virtual bool onComputeSize(const MNN::Op* op, const std::vector<Tensor*>& inputs,
const std::vector<Tensor*>& outputs) const override {
auto flatten = op->main_as_Flatten();
if (nullptr == flatten || inputs.empty() || outputs.empty()) {
return false;
}
auto axis = flatten->axis();
auto dim = inputs[0]->dimensions();
if (axis < 0) {
axis += dim;
}
int inside = 1;
int outside = 1;
for (int i=0; i<axis; ++i) {
outside *= inputs[0]->length(i);
}
for (int i=axis; i<dim; ++i) {
inside *= inputs[0]->length(i);
}
outputs[0]->buffer().dimensions = 2;
outputs[0]->setLength(0, outside);
outputs[0]->setLength(1, inside);
outputs[0]->buffer().type = inputs[0]->getType();
TensorUtils::getDescribe(outputs[0])->dimensionFormat = TensorUtils::getDescribe(inputs[0])->dimensionFormat;
return true;
}
};
class ReshapeComputer : public SizeComputer {
public:
virtual bool onComputeSize(const MNN::Op* op, const std::vector<Tensor*>& inputs,
const std::vector<Tensor*>& outputs) const override {
MNN_ASSERT(1 == inputs.size() || 2 == inputs.size());
MNN_ASSERT(1 == outputs.size());
auto input = inputs[0];
auto output = outputs[0];
outputs[0]->buffer().type = inputs[0]->buffer().type;
int dimSize = 0;
int shapes[MNN_MAX_TENSOR_DIM];
auto inputFormat = TensorUtils::getDescribe(inputs[0])->dimensionFormat;
bool fromTf = false;
auto mainType = op->main_type();
if (1 == inputs.size()) {
// Const shape
if (OpParameter_Reshape == mainType) {
auto shape = op->main_as_Reshape()->dims();
dimSize = shape->size();
for (int i = 0; i < dimSize; ++i) {
shapes[i] = shape->data()[i];
}
} else {
// For old model compability
auto shape = op->main_as_QuantizedReshape()->dims();
dimSize = shape->size();
for (int i = 0; i < dimSize; ++i) {
shapes[i] = shape->data()[i];
}
}
} else {
// shape which is getted at the runtime
auto inputShape = inputs[1];
// For the modle convert from tensorflow, the format is NHWC, otherwise NCHW
fromTf = TensorUtils::getDescribe(inputShape)->dimensionFormat == MNN_DATA_FORMAT_NHWC;
dimSize = inputShape->elementSize();
auto dim = inputShape->host<int32_t>();
auto dimType = MNN_DATA_FORMAT_NHWC;
if (OpParameter_Reshape == mainType) {
dimType = op->main_as_Reshape()->dimType();
}
if ((inputFormat == MNN_DATA_FORMAT_NC4HW4) && dimType == MNN_DATA_FORMAT_NHWC) {
//NCHW / NC4HW4
//NHWC -> NCHW
shapes[0] = dim[0];
shapes[1] = dim[3];
shapes[2] = dim[1];
shapes[3] = dim[2];
} else {
for (int i = 0; i < dimSize; ++i) {
shapes[i] = dim[i];
}
}
}
output->buffer().dimensions = dimSize;
int totalSizeInput = 1;
for (int i = 0; i < input->buffer().dimensions; ++i) {
auto l = input->length(i);
if (l != 0) {
totalSizeInput *= l;
}
}
int determinAxis = -1;
for (int i = 0; i < dimSize; ++i) {
int reshapeDim = shapes[i];
if (reshapeDim == -1) {
determinAxis = i;
output->buffer().dim[i].extent = 1;
continue;
}
// Keep input dimension if reshape dimension is 0 and the element
// count of the input does not equal to 0.
// TODO: Reshape 0 is not allowed if the input element count is not
// 0 for TensorFlow.
if (reshapeDim == 0 && (!fromTf)) {
output->buffer().dim[i].extent = input->buffer().dim[i].extent;
} else {
output->buffer().dim[i].extent = reshapeDim;
}
}
int totalSizeOutput = 1;
for (int i = 0; i < dimSize; ++i) {
if (output->buffer().dim[i].extent != 0) {
totalSizeOutput *= output->buffer().dim[i].extent;
}
}
if (determinAxis >= 0) {
output->buffer().dim[determinAxis].extent = totalSizeInput / totalSizeOutput;
totalSizeOutput *= output->buffer().dim[determinAxis].extent;
}
if (totalSizeInput != totalSizeOutput) {
MNN_PRINT("Reshape error: %d -> %d\n", totalSizeInput, totalSizeOutput);
return false;
}
TensorUtils::getDescribe(output)->dimensionFormat = TensorUtils::getDescribe(input)->dimensionFormat;
return true;
}
};
REGISTER_SHAPE_INPUTS(ReshapeComputer, OpType_Reshape, {1});
REGISTER_SHAPE_INPUTS(ReshapeComputer, OpType_QuantizedReshape, {1});
REGISTER_SHAPE(FlattenComputer, OpType_Flatten);
} // namespace MNN
| 2,963 |
916 |
#
# Author: <EMAIL>
# Date: 01/25/2019
#
import os
import csv
import copy
from collections import OrderedDict,defaultdict,Sequence,Counter
import numpy as np
from ...utils import get_logger
from ...utils import xtqdm as tqdm
from ...data import example_to_feature
from .metrics import *
from ..models import SequenceClassificationModel
logger=get_logger()
__all__ = ['EvalData', 'Task']
class EvalData:
def __init__(self, name, examples, metrics_fn=None, predict_fn=None, ignore_metric=False, critial_metrics=None):
def accuracy_fn(logits, labels):
return OrderedDict(accuracy= metric_accuracy(logits, labels))
def default_pred_fn(logits, output_dir, name, prefix):
output=os.path.join(output_dir, 'submit-{}-{}.tsv'.format(name, prefix))
preds = np.argmax(logits, axis=-1)
with open(output, 'w', encoding='utf-8') as fs:
fs.write('index\tpredictions\n')
for i,p in enumerate(preds):
fs.write('{}\t{}\n'.format(i, p))
self.name = name
self.data = examples
self.ignore_metric = ignore_metric
self.critial_metrics = critial_metrics
self.metrics_fn = metrics_fn if metrics_fn is not None else accuracy_fn
self.predict_fn = predict_fn if predict_fn is not None else default_pred_fn
def __repr__(self):
return f'{self.name}, {type(self.data)}: {len(self.data)}, {self.predict_fn}, {self.metrics_fn}'
class Task():
_meta={}
def __init__(self, tokenizer, args, **kwargs):
self.tokenizer = tokenizer
self.args = args
def eval_data(self, **kwargs):
raise NotImplementedError('Eval_data method not implemented yet.')
def train_data(self, **kwargs):
raise NotImplementedError('Eval_data method not implemented yet.')
def test_data(self, **kwargs):
raise NotImplementedError('Eval_data method not implemented yet.')
def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
def label2id(self, labelstr):
label_dict = {l:i for i,l in enumerate(self.get_labels())}
return label_dict[labelstr] if labelstr in label_dict else -1
def get_metrics_fn(self):
"""Calcuate metrics based on prediction results"""
def metrics_fn(logits, labels):
return OrderedDict(accuracy= metric_accuracy(logits, labels))
return metrics_fn
def get_predict_fn(self):
"""Calcuate metrics based on prediction results"""
def predict_fn(logits, output_dir, name, prefix):
output=os.path.join(output_dir, 'submit-{}-{}.tsv'.format(name, prefix))
preds = np.argmax(logits, axis=-1)
labels = self.get_labels()
with open(output, 'w', encoding='utf-8') as fs:
fs.write('index\tpredictions\n')
for i,p in enumerate(preds):
fs.write('{}\t{}\n'.format(i, labels[p]))
return predict_fn
@classmethod
def _read_tsv(cls, input_file, quotechar=None):
"""Reads a tab separated value file."""
with open(input_file, "r", encoding='utf-8') as f:
reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
lines = []
for line in reader:
lines.append(line)
return lines
def get_feature_fn(self, max_seq_len = 512, mask_gen = None, label_type='int', training=False):
tokenizer = self.tokenizer
def _example_to_feature(example, rng=None, ext_params=None, **kwargs):
return example_to_feature(tokenizer, example, max_seq_len = max_seq_len, \
rng = rng, mask_generator = mask_gen, ext_params = ext_params, label_type=label_type, **kwargs)
return _example_to_feature
def get_model_class_fn(self):
return SequenceClassificationModel.load_model
@classmethod
def add_arguments(cls, parser):
"""Add task specific arguments
e.g. parser.add_argument('--data_dir', type=str, help='The path of data directory.')
"""
parser.add_argument('--task_example_arg', type=str, default=None, help='An example task specific argument')
return parser
| 1,505 |
1,505 |
import pandas as pd
from fklearn.training.calibration import (isotonic_calibration_learner,
find_thresholds_with_same_risk)
def test_isotonic_calibration_learner():
df_train = pd.DataFrame({
'id': ["id1", "id2", "id3", "id4"],
"pred": [0.25, 0.64, 0.12, 0.9],
'y': [0, 1, 0, 1]
})
df_test = pd.DataFrame({
'id': ["id4", "id4", "id5", "id6", "id7"],
"pred": [0.55, 0.12, 0.13, 0.9, 0.95],
'y': [1, 0, 0, 1, 1]
})
learner = isotonic_calibration_learner(prediction_column="pred", target_column="y")
predict_fn, pred_train, log = learner(df_train)
pred_test = predict_fn(df_test)
assert "calibrated_prediction" in pred_train.columns.values
assert "calibrated_prediction" in pred_test.columns.values
assert pred_test.calibrated_prediction.max() <= 1
assert pred_test.calibrated_prediction.min() >= 0
assert pred_test.calibrated_prediction.isnull().max() == 0
def test_find_thresholds_with_same_risk():
df_with_ecdf = pd.DataFrame([["group_1", 0.0, 416, 3],
["group_2", 0.0, 328, 2],
["group_2", 0.0, 670, 4],
["group_2", 0.0, 105, 1],
["group_2", 0.0, 427, 3],
["group_1", 1.0, 672, 4],
["group_1", 0.0, 635, 4],
[None, 0.0, 158, 1],
["group_2", 0.0, 152, 4],
["group_1", 0.0, 305, 2]],
columns=["sensitive_factor", "target",
"prediction_ecdf", "unfair_band"])
df_expected = df_with_ecdf.copy()
df_expected["fair"] = pd.Series([2, 3, 4, 1, 4, 4, 3, None, 2, 1])
fair_thresholds = {'group_2': [-1, 105.0, 152.0, 328.0, 670.0],
'group_1': [-1, 305.0, 416.0, 635.0, 672.0]}
learner = find_thresholds_with_same_risk(sensitive_factor="sensitive_factor", unfair_band_column="unfair_band",
model_prediction_output="prediction_ecdf")
predict_fn, pred_df, log = learner(df_with_ecdf)
df_with_ecdf["fair"] = pred_df
assert fair_thresholds == log["find_thresholds_with_same_risk"]["fair_thresholds"]
pd.util.testing.assert_frame_equal(df_expected, df_with_ecdf)
| 1,368 |
6,304 |
/*
* Copyright 2019 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "modules/particles/include/SkParticleEffect.h"
// Doesn't do anything important; just exists to show we can use modules/particles without the GPU
// backend being available.
int main(int argc, char** argv) {
// Register types for serialization
SkParticleEffect::RegisterParticleTypes();
return 0;
}
| 135 |
19,046 |
/*
* 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.
*/
#include <folly/futures/ManualTimekeeper.h>
#include <chrono>
#include <folly/portability/GTest.h>
using namespace std::literals;
namespace folly {
class ManualTimekeeperTest : public ::testing::Test {};
TEST_F(ManualTimekeeperTest, Basic) {
auto timekeeper = folly::ManualTimekeeper{};
auto future = timekeeper.after(100s);
timekeeper.advance(100s);
EXPECT_TRUE(future.isReady());
}
TEST_F(ManualTimekeeperTest, AdvanceWithoutAnyFutures) {
auto timekeeper = folly::ManualTimekeeper{};
timekeeper.advance(100s);
auto future = timekeeper.after(100s);
EXPECT_FALSE(future.isReady());
timekeeper.advance(100s);
EXPECT_TRUE(future.isReady());
}
TEST_F(ManualTimekeeperTest, AdvanceWithManyFutures) {
auto timekeeper = folly::ManualTimekeeper{};
auto one = timekeeper.after(100s);
auto two = timekeeper.after(200s);
auto three = timekeeper.after(300s);
EXPECT_FALSE(one.isReady());
EXPECT_FALSE(two.isReady());
EXPECT_FALSE(three.isReady());
timekeeper.advance(100s);
EXPECT_TRUE(one.isReady());
EXPECT_FALSE(two.isReady());
EXPECT_FALSE(three.isReady());
timekeeper.advance(100s);
EXPECT_TRUE(one.isReady());
EXPECT_TRUE(two.isReady());
EXPECT_FALSE(three.isReady());
timekeeper.advance(100s);
EXPECT_TRUE(one.isReady());
EXPECT_TRUE(two.isReady());
EXPECT_TRUE(three.isReady());
timekeeper.advance(100s);
EXPECT_TRUE(one.isReady());
EXPECT_TRUE(two.isReady());
EXPECT_TRUE(three.isReady());
auto four = timekeeper.after(100s);
EXPECT_FALSE(four.isReady());
timekeeper.advance(100s);
EXPECT_TRUE(one.isReady());
EXPECT_TRUE(two.isReady());
EXPECT_TRUE(three.isReady());
EXPECT_TRUE(four.isReady());
}
} // namespace folly
| 810 |
628 |
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
template <class T> int size(const T &x) { return x.size(); }
const int INF = 2147483647;
#define rep(i,a,b) for (__typeof(a) i=(a); i<(b); ++i)
#define iter(it,c) for (__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it)
int n;
vector<int> number;
void generate(int k) {
if (k > 0) {
stringstream ss;
for (int i = 0; i < k; i++) {
ss << number[i];
}
int x;
ss >> x;
if (x % k != 0) {
return;
}
}
if (k == n) {
for (int i = 0; i < n; i++) {
cout << number[i];
}
cout << endl;
} else {
for (int d = 0; d <= 9; d++) {
if (k == 0 && d == 0) {
continue;
}
number.push_back(d);
generate(k+1);
number.pop_back();
}
}
}
int main() {
cin >> n;
generate(0);
return 0;
}
| 577 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.