max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,235 | #include <iostream>
using namespace std;
int main()
{
// In union, all members share the same memory location.
//
// Unions can save us memory with different objects
// sharing the memory location at different times.
//
union exampleUnion {
int num;
char c;
// data can be either int or char
};
// or }myUnion
exampleUnion myUnion;
myUnion.num = 10;
myUnion.c = 'A';
// myUnion.c overwrites num
cout << myUnion.num << endl; // 65
cout << myUnion.c << endl; // A
}
| 175 |
1,603 | import os
import tornado.ioloop
import tornado.httpserver
from tornado.web import RequestHandler
from tornado.gen import coroutine
from react.render import render_component
comments = []
class IndexHandler(RequestHandler):
@coroutine
def get(self):
rendered = render_component(
os.path.join(os.getcwd(), 'static', 'js', 'CommentBox.jsx'),
{
'comments': comments,
'url': '/comments',
'xsrf':self.xsrf_token
},
to_static_markup=False,
)
self.render('index.html', rendered=rendered)
class CommentHandler(RequestHandler):
@coroutine
def post(self):
comments.append({
'author': self.get_argument('author'),
'text': self.get_argument('text'),
})
self.redirect('/')
urls = [
(r"/", IndexHandler),
(r"/comments", CommentHandler),
(r"/(.*)", tornado.web.StaticFileHandler, {"path":r"{0}".format(os.path.join(os.path.dirname(__file__),"static"))}),
]
settings = dict({
"template_path": os.path.join(os.path.dirname(__file__),"templates"),
"static_path": os.path.join(os.path.dirname(__file__),"static"),
"cookie_secret": os.urandom(12),
"xsrf_cookies": True,
"debug": True,
"compress_response": True
})
application = tornado.web.Application(urls,**settings)
if __name__ == "__main__":
server = tornado.httpserver.HTTPServer(application)
server.listen(8000)
tornado.ioloop.IOLoop.instance().start()
| 610 |
335 | <filename>S/Subsidiary_adjective.json
{
"word": "Subsidiary",
"definitions": [
"Less important than but related or supplementary to something.",
"(of a company) controlled by a holding or parent company."
],
"parts-of-speech": "Adjective"
} | 100 |
1,306 | <reponame>CanPisces/DexHunter
/*
* Copyright (C) 2011 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.
*/
#include "dex/compiler_ir.h"
#include "dex/compiler_internals.h"
#include "dex/quick/mir_to_lir-inl.h"
#include "invoke_type.h"
namespace art {
/* This file contains target-independent codegen and support. */
/*
* Load an immediate value into a fixed or temp register. Target
* register is clobbered, and marked in_use.
*/
LIR* Mir2Lir::LoadConstant(int r_dest, int value) {
if (IsTemp(r_dest)) {
Clobber(r_dest);
MarkInUse(r_dest);
}
return LoadConstantNoClobber(r_dest, value);
}
/*
* Temporary workaround for Issue 7250540. If we're loading a constant zero into a
* promoted floating point register, also copy a zero into the int/ref identity of
* that sreg.
*/
void Mir2Lir::Workaround7250540(RegLocation rl_dest, int zero_reg) {
if (rl_dest.fp) {
int pmap_index = SRegToPMap(rl_dest.s_reg_low);
if (promotion_map_[pmap_index].fp_location == kLocPhysReg) {
// Now, determine if this vreg is ever used as a reference. If not, we're done.
bool used_as_reference = false;
int base_vreg = mir_graph_->SRegToVReg(rl_dest.s_reg_low);
for (int i = 0; !used_as_reference && (i < mir_graph_->GetNumSSARegs()); i++) {
if (mir_graph_->SRegToVReg(mir_graph_->reg_location_[i].s_reg_low) == base_vreg) {
used_as_reference |= mir_graph_->reg_location_[i].ref;
}
}
if (!used_as_reference) {
return;
}
int temp_reg = zero_reg;
if (temp_reg == INVALID_REG) {
temp_reg = AllocTemp();
LoadConstant(temp_reg, 0);
}
if (promotion_map_[pmap_index].core_location == kLocPhysReg) {
// Promoted - just copy in a zero
OpRegCopy(promotion_map_[pmap_index].core_reg, temp_reg);
} else {
// Lives in the frame, need to store.
StoreBaseDisp(TargetReg(kSp), SRegOffset(rl_dest.s_reg_low), temp_reg, kWord);
}
if (zero_reg == INVALID_REG) {
FreeTemp(temp_reg);
}
}
}
}
/* Load a word at base + displacement. Displacement must be word multiple */
LIR* Mir2Lir::LoadWordDisp(int rBase, int displacement, int r_dest) {
return LoadBaseDisp(rBase, displacement, r_dest, kWord,
INVALID_SREG);
}
LIR* Mir2Lir::StoreWordDisp(int rBase, int displacement, int r_src) {
return StoreBaseDisp(rBase, displacement, r_src, kWord);
}
/*
* Load a Dalvik register into a physical register. Take care when
* using this routine, as it doesn't perform any bookkeeping regarding
* register liveness. That is the responsibility of the caller.
*/
void Mir2Lir::LoadValueDirect(RegLocation rl_src, int r_dest) {
rl_src = UpdateLoc(rl_src);
if (rl_src.location == kLocPhysReg) {
OpRegCopy(r_dest, rl_src.low_reg);
} else if (IsInexpensiveConstant(rl_src)) {
LoadConstantNoClobber(r_dest, mir_graph_->ConstantValue(rl_src));
} else {
DCHECK((rl_src.location == kLocDalvikFrame) ||
(rl_src.location == kLocCompilerTemp));
LoadWordDisp(TargetReg(kSp), SRegOffset(rl_src.s_reg_low), r_dest);
}
}
/*
* Similar to LoadValueDirect, but clobbers and allocates the target
* register. Should be used when loading to a fixed register (for example,
* loading arguments to an out of line call.
*/
void Mir2Lir::LoadValueDirectFixed(RegLocation rl_src, int r_dest) {
Clobber(r_dest);
MarkInUse(r_dest);
LoadValueDirect(rl_src, r_dest);
}
/*
* Load a Dalvik register pair into a physical register[s]. Take care when
* using this routine, as it doesn't perform any bookkeeping regarding
* register liveness. That is the responsibility of the caller.
*/
void Mir2Lir::LoadValueDirectWide(RegLocation rl_src, int reg_lo,
int reg_hi) {
rl_src = UpdateLocWide(rl_src);
if (rl_src.location == kLocPhysReg) {
OpRegCopyWide(reg_lo, reg_hi, rl_src.low_reg, rl_src.high_reg);
} else if (IsInexpensiveConstant(rl_src)) {
LoadConstantWide(reg_lo, reg_hi, mir_graph_->ConstantValueWide(rl_src));
} else {
DCHECK((rl_src.location == kLocDalvikFrame) ||
(rl_src.location == kLocCompilerTemp));
LoadBaseDispWide(TargetReg(kSp), SRegOffset(rl_src.s_reg_low),
reg_lo, reg_hi, INVALID_SREG);
}
}
/*
* Similar to LoadValueDirect, but clobbers and allocates the target
* registers. Should be used when loading to a fixed registers (for example,
* loading arguments to an out of line call.
*/
void Mir2Lir::LoadValueDirectWideFixed(RegLocation rl_src, int reg_lo,
int reg_hi) {
Clobber(reg_lo);
Clobber(reg_hi);
MarkInUse(reg_lo);
MarkInUse(reg_hi);
LoadValueDirectWide(rl_src, reg_lo, reg_hi);
}
RegLocation Mir2Lir::LoadValue(RegLocation rl_src, RegisterClass op_kind) {
rl_src = EvalLoc(rl_src, op_kind, false);
if (IsInexpensiveConstant(rl_src) || rl_src.location != kLocPhysReg) {
LoadValueDirect(rl_src, rl_src.low_reg);
rl_src.location = kLocPhysReg;
MarkLive(rl_src.low_reg, rl_src.s_reg_low);
}
return rl_src;
}
void Mir2Lir::StoreValue(RegLocation rl_dest, RegLocation rl_src) {
/*
* Sanity checking - should never try to store to the same
* ssa name during the compilation of a single instruction
* without an intervening ClobberSReg().
*/
if (kIsDebugBuild) {
DCHECK((live_sreg_ == INVALID_SREG) ||
(rl_dest.s_reg_low != live_sreg_));
live_sreg_ = rl_dest.s_reg_low;
}
LIR* def_start;
LIR* def_end;
DCHECK(!rl_dest.wide);
DCHECK(!rl_src.wide);
rl_src = UpdateLoc(rl_src);
rl_dest = UpdateLoc(rl_dest);
if (rl_src.location == kLocPhysReg) {
if (IsLive(rl_src.low_reg) ||
IsPromoted(rl_src.low_reg) ||
(rl_dest.location == kLocPhysReg)) {
// Src is live/promoted or Dest has assigned reg.
rl_dest = EvalLoc(rl_dest, kAnyReg, false);
OpRegCopy(rl_dest.low_reg, rl_src.low_reg);
} else {
// Just re-assign the registers. Dest gets Src's regs
rl_dest.low_reg = rl_src.low_reg;
Clobber(rl_src.low_reg);
}
} else {
// Load Src either into promoted Dest or temps allocated for Dest
rl_dest = EvalLoc(rl_dest, kAnyReg, false);
LoadValueDirect(rl_src, rl_dest.low_reg);
}
// Dest is now live and dirty (until/if we flush it to home location)
MarkLive(rl_dest.low_reg, rl_dest.s_reg_low);
MarkDirty(rl_dest);
ResetDefLoc(rl_dest);
if (IsDirty(rl_dest.low_reg) &&
oat_live_out(rl_dest.s_reg_low)) {
def_start = last_lir_insn_;
StoreBaseDisp(TargetReg(kSp), SRegOffset(rl_dest.s_reg_low),
rl_dest.low_reg, kWord);
MarkClean(rl_dest);
def_end = last_lir_insn_;
if (!rl_dest.ref) {
// Exclude references from store elimination
MarkDef(rl_dest, def_start, def_end);
}
}
}
RegLocation Mir2Lir::LoadValueWide(RegLocation rl_src, RegisterClass op_kind) {
DCHECK(rl_src.wide);
rl_src = EvalLoc(rl_src, op_kind, false);
if (IsInexpensiveConstant(rl_src) || rl_src.location != kLocPhysReg) {
LoadValueDirectWide(rl_src, rl_src.low_reg, rl_src.high_reg);
rl_src.location = kLocPhysReg;
MarkLive(rl_src.low_reg, rl_src.s_reg_low);
MarkLive(rl_src.high_reg, GetSRegHi(rl_src.s_reg_low));
}
return rl_src;
}
void Mir2Lir::StoreValueWide(RegLocation rl_dest, RegLocation rl_src) {
/*
* Sanity checking - should never try to store to the same
* ssa name during the compilation of a single instruction
* without an intervening ClobberSReg().
*/
if (kIsDebugBuild) {
DCHECK((live_sreg_ == INVALID_SREG) ||
(rl_dest.s_reg_low != live_sreg_));
live_sreg_ = rl_dest.s_reg_low;
}
LIR* def_start;
LIR* def_end;
DCHECK_EQ(IsFpReg(rl_src.low_reg), IsFpReg(rl_src.high_reg));
DCHECK(rl_dest.wide);
DCHECK(rl_src.wide);
if (rl_src.location == kLocPhysReg) {
if (IsLive(rl_src.low_reg) ||
IsLive(rl_src.high_reg) ||
IsPromoted(rl_src.low_reg) ||
IsPromoted(rl_src.high_reg) ||
(rl_dest.location == kLocPhysReg)) {
// Src is live or promoted or Dest has assigned reg.
rl_dest = EvalLoc(rl_dest, kAnyReg, false);
OpRegCopyWide(rl_dest.low_reg, rl_dest.high_reg,
rl_src.low_reg, rl_src.high_reg);
} else {
// Just re-assign the registers. Dest gets Src's regs
rl_dest.low_reg = rl_src.low_reg;
rl_dest.high_reg = rl_src.high_reg;
Clobber(rl_src.low_reg);
Clobber(rl_src.high_reg);
}
} else {
// Load Src either into promoted Dest or temps allocated for Dest
rl_dest = EvalLoc(rl_dest, kAnyReg, false);
LoadValueDirectWide(rl_src, rl_dest.low_reg, rl_dest.high_reg);
}
// Dest is now live and dirty (until/if we flush it to home location)
MarkLive(rl_dest.low_reg, rl_dest.s_reg_low);
MarkLive(rl_dest.high_reg, GetSRegHi(rl_dest.s_reg_low));
MarkDirty(rl_dest);
MarkPair(rl_dest.low_reg, rl_dest.high_reg);
ResetDefLocWide(rl_dest);
if ((IsDirty(rl_dest.low_reg) ||
IsDirty(rl_dest.high_reg)) &&
(oat_live_out(rl_dest.s_reg_low) ||
oat_live_out(GetSRegHi(rl_dest.s_reg_low)))) {
def_start = last_lir_insn_;
DCHECK_EQ((mir_graph_->SRegToVReg(rl_dest.s_reg_low)+1),
mir_graph_->SRegToVReg(GetSRegHi(rl_dest.s_reg_low)));
StoreBaseDispWide(TargetReg(kSp), SRegOffset(rl_dest.s_reg_low),
rl_dest.low_reg, rl_dest.high_reg);
MarkClean(rl_dest);
def_end = last_lir_insn_;
MarkDefWide(rl_dest, def_start, def_end);
}
}
/* Utilities to load the current Method* */
void Mir2Lir::LoadCurrMethodDirect(int r_tgt) {
LoadValueDirectFixed(mir_graph_->GetMethodLoc(), r_tgt);
}
RegLocation Mir2Lir::LoadCurrMethod() {
return LoadValue(mir_graph_->GetMethodLoc(), kCoreReg);
}
} // namespace art
| 4,378 |
2,151 | <filename>ios/chrome/browser/search_engines/search_engines_util.cc
// Copyright 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 "ios/chrome/browser/search_engines/search_engines_util.h"
#include <stddef.h>
#include <memory>
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "components/prefs/pref_service.h"
#include "components/search_engines/search_engines_pref_names.h"
#include "components/search_engines/template_url_prepopulate_data.h"
#include "components/search_engines/template_url_service.h"
#include "components/search_engines/template_url_service_observer.h"
namespace {
// Id of the google id in template_url_prepopulate_data.cc.
static const int kGoogleEnginePrepopulatedId = 1;
// Update the search engine of the given service to the default ones for the
// current locale.
void UpdateSearchEngine(TemplateURLService* service) {
DCHECK(service);
DCHECK(service->loaded());
std::vector<TemplateURL*> old_engines = service->GetTemplateURLs();
size_t default_engine;
std::vector<std::unique_ptr<TemplateURLData>> new_engines =
TemplateURLPrepopulateData::GetPrepopulatedEngines(nullptr,
&default_engine);
DCHECK(default_engine == 0);
DCHECK(new_engines[0]->prepopulate_id == kGoogleEnginePrepopulatedId);
// The aim is to replace the old search engines with the new ones.
// It is not possible to remove all of them, because removing the current
// selected engine is not allowed.
// It is not possible to add all the new ones first, because the service gets
// confused when a prepopulated engine is there more than once.
// Instead, this will in a first pass makes google as the default engine. In
// a second pass, it will remove all other search engines. At last, in a third
// pass, it will add all new engines but google.
for (auto* engine : old_engines) {
if (engine->prepopulate_id() == kGoogleEnginePrepopulatedId)
service->SetUserSelectedDefaultSearchProvider(engine);
}
for (auto* engine : old_engines) {
if (engine->prepopulate_id() != kGoogleEnginePrepopulatedId)
service->Remove(engine);
}
for (const auto& engine : new_engines) {
if (engine->prepopulate_id != kGoogleEnginePrepopulatedId)
service->Add(std::make_unique<TemplateURL>(*engine));
}
}
// Observer class that allows to wait for the TemplateURLService to be loaded.
// This class will delete itself as soon as the TemplateURLService is loaded.
class LoadedObserver : public TemplateURLServiceObserver {
public:
explicit LoadedObserver(TemplateURLService* service) : service_(service) {
DCHECK(service_);
DCHECK(!service_->loaded());
service_->AddObserver(this);
service_->Load();
}
~LoadedObserver() override { service_->RemoveObserver(this); }
void OnTemplateURLServiceChanged() override {
service_->RemoveObserver(this);
UpdateSearchEngine(service_);
// Only delete this class when this callback is finished.
base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}
private:
TemplateURLService* service_;
};
} // namespace
namespace search_engines {
void UpdateSearchEnginesIfNeeded(PrefService* preferences,
TemplateURLService* service) {
if (!preferences->HasPrefPath(prefs::kCountryIDAtInstall)) {
// No search engines were ever installed, just return.
return;
}
int old_country_id = preferences->GetInteger(prefs::kCountryIDAtInstall);
int country_id = TemplateURLPrepopulateData::GetCurrentCountryID();
if (country_id == old_country_id) {
// User's locale did not change, just return.
return;
}
preferences->SetInteger(prefs::kCountryIDAtInstall, country_id);
// If the current search engine is managed by policy then we can't set the
// default search engine, which is required by UpdateSearchEngine(). This
// isn't a problem as long as the default search engine is enforced via
// policy, because it can't be changed by the user anyway; if the policy is
// removed then the engines can be updated again.
if (!service || service->is_default_search_managed())
return;
if (service->loaded())
UpdateSearchEngine(service);
else
new LoadedObserver(service); // The observer manages its own lifetime.
}
} // namespace search_engines
| 1,455 |
432 | #include <sys/stat.h>
#include <signal.h>
#include <stdlib.h>
#include <math.h>
#include "fbg_fbdev.h"
int keep_running = 1;
void int_handler(int dummy) {
keep_running = 0;
}
struct _fbg_img *flags_texture;
struct _fragment_user_data {
float xmotion;
float ymotion;
};
void *fragmentStart(struct _fbg *fbg) {
struct _fragment_user_data *user_data = (struct _fragment_user_data *)calloc(1, sizeof(struct _fragment_user_data));
user_data->xmotion = 0.0f;
user_data->ymotion = 0.0f;
return user_data;
}
void fragmentStop(struct _fbg *fbg, void *data) {
struct _fragment_user_data *ud = (struct _fragment_user_data *)data;
free(ud);
}
void fragment(struct _fbg *fbg, void *user_data) {
struct _fragment_user_data *ud = (struct _fragment_user_data *)user_data;
fbg_clear(fbg, 0);
// https://www.openprocessing.org/sketch/560394
int xoff = 64;
int yoff = 128;
int rect_size = 1;
float x_step_size = 2;
float x_end = fbg->width - xoff;
float y_end = fbg->height - yoff;
for (int y = fbg->task_id + 1; y < y_end; y += (fbg->parallel_tasks + 1)) {
float ys = (y_end - yoff);
float yo = (y - yoff);
float yy = yo / ys;
int yyd = ((int)(yy * flags_texture->height) % flags_texture->height) * flags_texture->width;
float yyy = yy - 0.5;
for (int x = xoff; x < x_end; x += x_step_size) {
float xs = (x_end - xoff);
float xo = (x - xoff);
float xx = xo / xs;
float xxd = xx * flags_texture->width;
int cl = (int)(xxd + yyd) * fbg->components;
int r = flags_texture->data[cl];
int g = flags_texture->data[cl + 1];
int b = flags_texture->data[cl + 2];
float xxx = xx - 0.5;
fbg_rect(fbg, _FBG_MAX(_FBG_MIN(x + cosf(xxx*yyy * M_PI * 4 + ud->xmotion) * 24, fbg->width - rect_size), 0), _FBG_MAX(_FBG_MIN(y + yoff / 2 + sinf(xxx*yyy * M_PI * 7 + ud->ymotion) * 24, fbg->height - rect_size), 0), rect_size, rect_size, r, g, b);
}
}
ud->xmotion += 0.0075;
ud->ymotion += 0.05;
}
void selectiveMixing(struct _fbg *fbg, unsigned char *buffer, int task_id) {
int j = 0;
for (j = 0; j < fbg->size; j += 1) {
fbg->back_buffer[j] = (fbg->back_buffer[j] > buffer[j]) ? fbg->back_buffer[j] : buffer[j];
}
}
int main(int argc, char* argv[]) {
struct _fbg *fbg = fbg_fbdevInit();
if (fbg == NULL) {
return 0;
}
signal(SIGINT, int_handler);
flags_texture = fbg_loadPNG(fbg, "flags.png");
struct _fbg_img *bbimg = fbg_loadPNG(fbg, "bbmode1_8x8.png");
struct _fbg_font *bbfont = fbg_createFont(fbg, bbimg, 8, 8, 33);
fbg_createFragment(fbg, fragmentStart, fragment, fragmentStop, 3);
struct _fragment_user_data *user_data = fragmentStart(fbg);
do {
fragment(fbg, user_data);
fbg_draw(fbg, selectiveMixing);
fbg_write(fbg, "FBGraphics: Flags of the world", 4, 2);
fbg_write(fbg, "FPS", 4, 12+8);
fbg_write(fbg, "#0 (Main): ", 4, 22+8);
fbg_write(fbg, "#1: ", 4, 32+8);
fbg_write(fbg, "#2: ", 4, 32+8+2+8);
fbg_write(fbg, "#3: ", 4, 32+16+4+8);
fbg_drawFramerate(fbg, NULL, 0, 4 + 32 + 48 + 8, 22 + 8, 255, 255, 255);
fbg_drawFramerate(fbg, NULL, 1, 4+32, 32+8, 255, 255, 255);
fbg_drawFramerate(fbg, NULL, 2, 4+32, 32+8+2+8, 255, 255, 255);
fbg_drawFramerate(fbg, NULL, 3, 4+32, 32+16+4+8, 255, 255, 255);
fbg_flip(fbg);
} while (keep_running);
fragmentStop(fbg, user_data);
fbg_close(fbg);
fbg_freeImage(flags_texture);
fbg_freeImage(bbimg);
fbg_freeFont(bbfont);
return 0;
}
| 1,897 |
3,986 | /*
* Copyright (C) 2020 xuexiangjys(<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.xuexiang.xuidemo.fragment.components.refresh.sticky;
import androidx.recyclerview.widget.RecyclerView;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xuidemo.DemoDataProvider;
import com.xuexiang.xuidemo.R;
import com.xuexiang.xuidemo.adapter.StickyListAdapter;
import com.xuexiang.xuidemo.base.BaseFragment;
import com.xuexiang.xuidemo.utils.Utils;
import butterknife.BindView;
/**
* @author xuexiang
* @since 2020/4/25 1:09 AM
*/
@Page(name = "StickyNestedScrollView\n粘顶嵌套滚动布局")
public class StickyNestedScrollViewFragment extends BaseFragment {
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
private StickyListAdapter mAdapter;
@Override
protected int getLayoutId() {
return R.layout.fragment_sticky_nested_scrollview;
}
@Override
protected void initViews() {
// 注意,这里使用StickyNestedScrollView嵌套RecyclerView会导致RecyclerView复用机制失效,
// 在数据量大的情况下,加载容易卡顿
recyclerView.setNestedScrollingEnabled(false);
WidgetUtils.initRecyclerView(recyclerView, 0);
recyclerView.setAdapter(mAdapter = new StickyListAdapter());
mAdapter.refresh(DemoDataProvider.getStickyDemoData());
}
@Override
protected void initListeners() {
mAdapter.setOnItemClickListener((itemView, item, position) -> {
if (item != null && item.getNewInfo() != null) {
Utils.goWeb(getContext(), item.getNewInfo().getDetailUrl());
}
});
}
}
| 883 |
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.segment.virtual;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.math.expr.Expr;
import org.apache.druid.math.expr.ExpressionType;
import org.apache.druid.math.expr.vector.ExprVectorProcessor;
import org.apache.druid.segment.DimensionDictionarySelector;
import org.apache.druid.segment.IdLookup;
import org.apache.druid.segment.vector.SingleValueDimensionVectorSelector;
import javax.annotation.Nullable;
/**
* A {@link SingleValueDimensionVectorSelector} decorator that directly exposes the underlying dictionary ids in
* {@link #getRowVector}, saving expression computation until {@link #lookupName} is called. This allows for
* performing operations like grouping on the native dictionary ids, and deferring expression evaluation until
* after, which can dramatically reduce the total number of evaluations.
*
* @see ExpressionVectorSelectors for details on how expression vector selectors are constructed.
*
* @see SingleStringInputDeferredEvaluationExpressionDimensionSelector for the non-vectorized version of this selector.
*/
public class SingleStringInputDeferredEvaluationExpressionDimensionVectorSelector
implements SingleValueDimensionVectorSelector
{
private final SingleValueDimensionVectorSelector selector;
private final ExprVectorProcessor<String[]> stringProcessor;
private final StringLookupVectorInputBindings inputBinding;
public SingleStringInputDeferredEvaluationExpressionDimensionVectorSelector(
SingleValueDimensionVectorSelector selector,
Expr expression
)
{
// Verify selector has a working dictionary.
if (selector.getValueCardinality() == DimensionDictionarySelector.CARDINALITY_UNKNOWN
|| !selector.nameLookupPossibleInAdvance()) {
throw new ISE(
"Selector of class[%s] does not have a dictionary, cannot use it.",
selector.getClass().getName()
);
}
this.selector = selector;
this.inputBinding = new StringLookupVectorInputBindings();
this.stringProcessor = expression.buildVectorized(inputBinding);
}
@Override
public int getValueCardinality()
{
return CARDINALITY_UNKNOWN;
}
@Nullable
@Override
public String lookupName(int id)
{
inputBinding.currentValue[0] = selector.lookupName(id);
return stringProcessor.evalVector(inputBinding).values()[0];
}
@Override
public boolean nameLookupPossibleInAdvance()
{
return true;
}
@Nullable
@Override
public IdLookup idLookup()
{
return null;
}
@Override
public int[] getRowVector()
{
return selector.getRowVector();
}
@Override
public int getMaxVectorSize()
{
return selector.getMaxVectorSize();
}
@Override
public int getCurrentVectorSize()
{
return selector.getCurrentVectorSize();
}
/**
* Special single element vector input bindings used for processing the string value for {@link #lookupName(int)}
*
* Vector size is fixed to 1 because {@link #lookupName} operates on a single dictionary value at a time. If a
* bulk lookup method is ever added, these vector bindings should be modified to process the results with actual
* vectors.
*/
private static final class StringLookupVectorInputBindings implements Expr.VectorInputBinding
{
private final String[] currentValue = new String[1];
@Nullable
@Override
public ExpressionType getType(String name)
{
return ExpressionType.STRING;
}
@Override
public int getMaxVectorSize()
{
return 1;
}
@Override
public int getCurrentVectorSize()
{
return 1;
}
@Override
public int getCurrentVectorId()
{
return -1;
}
@Override
public <T> T[] getObjectVector(String name)
{
return (T[]) currentValue;
}
@Override
public long[] getLongVector(String name)
{
throw new UnsupportedOperationException("attempt to get long[] from string[] only scalar binding");
}
@Override
public double[] getDoubleVector(String name)
{
throw new UnsupportedOperationException("attempt to get double[] from string[] only scalar binding");
}
@Nullable
@Override
public boolean[] getNullVector(String name)
{
throw new UnsupportedOperationException("attempt to get boolean[] null vector from string[] only scalar binding");
}
}
}
| 1,599 |
1,671 | <reponame>rohankumardubey/ambry
/**
* Copyright 2020 LinkedIn Corp. 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.
*/
package com.github.ambry.store;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* The {@link CompactionPolicy} info to determine when to use which {@link CompactionPolicy}.
*/
@JsonPropertyOrder({"lastCompactionTime", "nextRoundIsCompactAllPolicy"})
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class CompactionPolicySwitchInfo {
private long lastCompactAllTime;
private boolean nextRoundIsCompactAllPolicy;
/**
* Constructor to create {@link CompactionPolicySwitchInfo} object.
* @param lastCompactAllTime last time when {@link CompactAllPolicy} has been selected.
* @param nextRoundIsCompactAllPolicy {@code True} if the next round of compaction policy is compactAll. {@code False} Otherwise.
*/
CompactionPolicySwitchInfo(long lastCompactAllTime, boolean nextRoundIsCompactAllPolicy) {
this.lastCompactAllTime = lastCompactAllTime;
this.nextRoundIsCompactAllPolicy = nextRoundIsCompactAllPolicy;
}
/**
* make sure objectMapper can work correctly
*/
CompactionPolicySwitchInfo() {
}
/**
* Get the last time when {@link CompactAllPolicy} has been selected.
* @return the last time when {@link CompactAllPolicy} has been selected.
*/
long getLastCompactAllTime() {
return this.lastCompactAllTime;
}
/**
* Set the last time when {@link CompactAllPolicy} has been selected.
* @param lastCompactAllTime last time when {@link CompactAllPolicy} has been selected.
*/
void setLastCompactAllTime(long lastCompactAllTime) {
this.lastCompactAllTime = lastCompactAllTime;
}
/**
* @return {@code True} if the next round of compaction policy is compactAll. {@code False} Otherwise.
*/
boolean isNextRoundCompactAllPolicy() {
return this.nextRoundIsCompactAllPolicy;
}
/**
* Set the nextRoundIsCompactAllPolicy to {@code True} if the next round of compaction policy is compactAll.
*/
void setNextRoundIsCompactAllPolicy(boolean isNextRoundCompactAllPolicy) {
this.nextRoundIsCompactAllPolicy = isNextRoundCompactAllPolicy;
}
}
| 812 |
1,333 | /*
* MIT License
*
* Copyright (c) 2020 International Business Machines
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef SRC_HELAYERS_HELIBCKKSCIPHER_H_
#define SRC_HELAYERS_HELIBCKKSCIPHER_H_
#include "HelibCiphertext.h"
#include "HelibCkksContext.h"
namespace helayers {
///@brief A concrete implementation of CTile API for Helib's CKKS scheme.
class HelibCkksCiphertext : public HelibCiphertext
{
private:
HelibCkksContext& he;
HelibCkksCiphertext(const HelibCkksCiphertext& src) = default;
std::shared_ptr<AbstractCiphertext> doClone() const override;
friend class HelibCkksEncoder;
public:
HelibCkksCiphertext(HelibCkksContext& h) : HelibCiphertext(h), he(h) {}
~HelibCkksCiphertext() override;
std::shared_ptr<HelibCkksCiphertext> clone() const
{
return std::static_pointer_cast<HelibCkksCiphertext>(doClone());
}
void addPlainRaw(const AbstractPlaintext& plain) override;
void subPlainRaw(const AbstractPlaintext& plain) override;
void multiplyPlainRaw(const AbstractPlaintext& plain) override;
void addScalar(int scalar) override;
void addScalar(double scalar) override;
void multiplyScalar(int scalar) override;
void multiplyScalar(double scalar) override;
void multiplyByChangingScale(double factor) override;
void setScale(double val) override;
double getScale() const override;
void conjugate() override;
void conjugateRaw() override;
// rotate right
void rotate(int n) override;
void negate() override;
int slotCount() const override;
};
} // namespace helayers
#endif /* SRC_HELAYERS_HELIBCKKSCIPHER_H_ */
| 815 |
310 | <gh_stars>100-1000
package org.ofbiz.order.shoppinglist;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.webapp.control.LoginWorker;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;
public class ShoppingListCookieInfo { // SCIPIO
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
public static final String AUTO_SAVE_LIST = "autoSave"; // "guest"
public static final String ANON_WISH_LIST = "anonWish";
public static final int COOKIE_MAX_AGE_DEFAULT = 60 * 60 * 24 * 30; // 1 month
private final String shoppingListId;
private final String authToken;
private final Cookie cookie; // may be null if not exist yet
private ShoppingListCookieInfo(String shoppingListId, String authToken, Cookie cookie) {
this.shoppingListId = shoppingListId;
this.authToken = UtilValidate.nullIfEmpty(authToken);
this.cookie = cookie;
}
public static ShoppingListCookieInfo fromFields(String shoppingListId, String authToken, Cookie cookie) {
if (UtilValidate.isEmpty(shoppingListId)) {
return null;
}
return new ShoppingListCookieInfo(shoppingListId, authToken, cookie);
}
public static ShoppingListCookieInfo fromFields(String shoppingListId, String authToken) {
return fromFields(shoppingListId, authToken, null);
}
public static ShoppingListCookieInfo fromFields(Map<String, ?> fields) {
if (fields == null) {
return null;
}
return fromFields((String) fields.get("shoppingListId"), (String) fields.get("shoppingListAuthToken"), null);
}
private static ShoppingListCookieInfo fromStringRepr(String value, Cookie cookie) {
if (value == null) {
return null;
}
String[] parts = value.split("::", 2);
if (parts.length >= 2 && UtilValidate.isNotEmpty(parts[0])) {
return new ShoppingListCookieInfo(parts[0], parts[1], cookie);
}
return null;
}
public static ShoppingListCookieInfo fromStringRepr(String value) {
return fromStringRepr(value, null);
}
public static ShoppingListCookieInfo fromCookie(Cookie cookie) {
return fromStringRepr(cookie != null ? cookie.getValue() : null, cookie);
}
public static ShoppingListCookieInfo fromCookie(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie: cookies) {
if (cookie.getName().equals(cookieName)) {
return ShoppingListCookieInfo.fromCookie(cookie);
}
}
}
return null;
}
public String getShoppingListId() { return shoppingListId; }
public String getAuthToken() { return authToken; }
public Cookie getCookie() { return cookie; }
// NOTE: DON'T use toString - potential security issue
public String toValueString() {
return toValueString(getShoppingListId(), getAuthToken());
}
@Override
public String toString() {
return toValueString(getShoppingListId(), getAuthToken() != null ? "[auth-token]" : null);
}
public boolean valueEquals(String shoppingListId, String authToken) {
return (Objects.equals(getShoppingListId(), shoppingListId) && Objects.equals(getAuthToken(), authToken));
}
public boolean valueEquals(ShoppingListCookieInfo other) {
return (other != null && valueEquals(other.getShoppingListId(), other.getAuthToken()));
}
public Map<String, Object> toFields(Map<String, Object> fields) {
fields.put("shoppingListId", getShoppingListId());
fields.put("shoppingListAuthToken", getAuthToken());
return fields;
}
public static String toValueString(String autoSaveListId, String shoppingListAuthToken) { // shoppingListId::shoppingListAuthToken
if (UtilValidate.isEmpty(autoSaveListId)) {
return null;
}
if (UtilValidate.isEmpty(shoppingListAuthToken)) {
return autoSaveListId;
}
return autoSaveListId + "::" + shoppingListAuthToken;
}
public static String getShoppingListCookieName(HttpServletRequest request, String listType) {
String defaultNamePat = AUTO_SAVE_LIST.equals(listType) ? "GuestShoppingListId_${sysName}" : (ANON_WISH_LIST.equals(listType) ? "AnonShoppingListId_${sysName}" : null);
String namePat = EntityUtilProperties.getPropertyValue("order", "shoppinglist." + listType + ".cookie.name", defaultNamePat, (Delegator) request.getAttribute("delegator"));
if (UtilValidate.isEmpty(namePat)) {
Debug.logError("Cannot get shopping list cookie name for list type (order.properties): " + listType, module);
return "";
}
return LoginWorker.expandCookieName(request, namePat);
}
public static int getShoppingListCookieMaxAge(HttpServletRequest request, String listType) {
return EntityUtilProperties.getPropertyAsInteger("order", "shoppinglist." + listType + ".cookie.maxAge", COOKIE_MAX_AGE_DEFAULT, (Delegator) request.getAttribute("delegator"));
}
public static String getAutoSaveShoppingListCookieName(HttpServletRequest request) {
return getShoppingListCookieName(request, AUTO_SAVE_LIST);
}
public static ShoppingListCookieInfo getAutoSaveShoppingListCookieInfo(HttpServletRequest request) {
return fromCookie(request, getShoppingListCookieName(request, AUTO_SAVE_LIST));
}
public static String getAnonShoppingListCookieName(HttpServletRequest request) {
return getShoppingListCookieName(request, ANON_WISH_LIST);
}
public static ShoppingListCookieInfo getAnonShoppingListCookieInfo(HttpServletRequest request) { // SCIPIO
return fromCookie(request, getShoppingListCookieName(request, ANON_WISH_LIST));
}
public static void createShoppingListCookie(HttpServletRequest request, HttpServletResponse response, String listType, String cookieName, ShoppingListCookieInfo cookieInfo) { // SCIPIO: refactored from createGuestShoppingListCookies
createShoppingListCookie(request, response, listType, new Cookie(cookieName, cookieInfo.toValueString()));
}
public static void createShoppingListCookie(HttpServletRequest request, HttpServletResponse response, String listType, String cookieName, String shoppingListId, String authToken) { // SCIPIO: refactored from createGuestShoppingListCookies
createShoppingListCookie(request, response, listType, new Cookie(cookieName, toValueString(shoppingListId, authToken)));
}
public static void createShoppingListCookie(HttpServletRequest request, HttpServletResponse response, String listType, Cookie guestShoppingListCookie) { // SCIPIO: refactored from createGuestShoppingListCookies
guestShoppingListCookie.setMaxAge(getShoppingListCookieMaxAge(request, listType));
guestShoppingListCookie.setPath("/");
guestShoppingListCookie.setSecure(true);
guestShoppingListCookie.setHttpOnly(true);
response.addCookie(guestShoppingListCookie);
}
public static void clearShoppingListCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) { // SCIPIO: refactored from clearGuestShoppingListCookies
Cookie cookie = new Cookie(cookieName, null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
public static void refreshShoppingListCookie(HttpServletRequest request, HttpServletResponse response, String listType,
String cookieName, String shoppingListId, String authToken) {
ShoppingListCookieInfo oldCookieInfo = fromCookie(request, cookieName);
if (oldCookieInfo != null && oldCookieInfo.valueEquals(shoppingListId, authToken)) {
return;
}
ShoppingListCookieInfo.createShoppingListCookie(request, response, listType, cookieName, shoppingListId, authToken);
}
}
| 3,017 |
528 | /******************************************************************************
Copyright 2020 <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.
*******************************************************************************
FILE: Test/EventWrappers.hpp
Emitter and Recever wrappers for events testing.
******************************************************************************/
#include <catch2/catch.hpp>
#include <Methane/Data/Emitter.hpp>
#include <functional>
namespace Methane::Data
{
struct ITestEvents
{
using CallFunc = std::function<void(size_t /*receiver_id*/)>;
virtual void Foo() = 0;
virtual void Bar(int a, bool b, float c) = 0;
virtual void Call(const CallFunc& f) = 0;
virtual ~ITestEvents() = default;
};
class TestEmitter : public Emitter<ITestEvents>
{
public:
void EmitFoo()
{
Emit(&ITestEvents::Foo);
}
void EmitBar(int a, bool b, float c)
{
Emit(&ITestEvents::Bar, a, b, c);
}
void EmitCall(const ITestEvents::CallFunc& f)
{
Emit(&ITestEvents::Call, f);
}
using Emitter<ITestEvents>::GetConnectedReceiversCount;
};
class TestReceiver
: protected Receiver<ITestEvents> //NOSONAR
{
public:
TestReceiver() = default;
explicit TestReceiver(size_t id) : m_id(id) { }
void Bind(TestEmitter& emitter)
{
emitter.Connect(*this);
}
void Unbind(TestEmitter& emitter)
{
emitter.Disconnect(*this);
}
void CheckBind(TestEmitter& emitter, bool new_connection = true)
{
const size_t connected_receivers_count = emitter.GetConnectedReceiversCount();
const size_t connected_emitters_count = GetConnectedEmittersCount();
CHECK_NOTHROW(Bind(emitter));
CHECK(emitter.GetConnectedReceiversCount() == connected_receivers_count + static_cast<size_t>(new_connection));
CHECK(GetConnectedEmittersCount() == connected_emitters_count + static_cast<size_t>(new_connection));
}
void CheckUnbind(TestEmitter& emitter, bool existing_connection = true)
{
const size_t connected_receivers_count = emitter.GetConnectedReceiversCount();
const size_t connected_emitters_count = GetConnectedEmittersCount();
CHECK_NOTHROW(Unbind(emitter));
CHECK(emitter.GetConnectedReceiversCount() == connected_receivers_count - static_cast<size_t>(existing_connection));
CHECK(GetConnectedEmittersCount() == connected_emitters_count - static_cast<size_t>(existing_connection));
}
size_t GetId() const { return m_id; }
bool IsFooCalled() const { return m_foo_call_count > 0U; }
uint32_t GetFooCallCount() const { return m_foo_call_count; }
bool IsBarCalled() const { return m_bar_call_count > 0U; }
uint32_t GetBarCallCount() const { return m_bar_call_count; }
uint32_t GetFuncCallCount() const { return m_func_call_count; }
int GetBarA() const { return m_bar_a; }
bool GetBarB() const { return m_bar_b; }
float GetBarC() const { return m_bar_c; }
using Receiver<ITestEvents>::GetConnectedEmittersCount;
protected:
// ITestEvent implementation
void Foo() override
{
m_foo_call_count++;
}
void Bar(int a, bool b, float c) override
{
m_bar_call_count++;
m_bar_a = a;
m_bar_b = b;
m_bar_c = c;
}
void Call(const CallFunc& f) override
{
m_func_call_count++;
f(m_id);
}
private:
const size_t m_id = 0;
uint32_t m_foo_call_count = 0U;
uint32_t m_bar_call_count = 0U;
uint32_t m_func_call_count = 0U;
int m_bar_a = 0;
bool m_bar_b = false;
float m_bar_c = 0.f;
};
constexpr int g_bar_a = 1;
constexpr bool g_bar_b = true;
constexpr float g_bar_c = 2.3F;
} // namespace Methane::Data | 1,745 |
451 | <filename>applis/OLD-Apero-OLD/cChoixImagesMicMac.cpp
/*Header-MicMac-eLiSe-25/06/2007
MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation
eLiSe : ELements of an Image Software Environnement
www.micmac.ign.fr
Copyright : Institut Geographique National
Author : <NAME>
Contributors : <NAME>, <NAME>.
[1] <NAME>, <NAME>.
"A multiresolution and optimization-based image matching approach:
An application to surface reconstruction from SPOT5-HRS stereo imagery."
In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space
(With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006.
[2] <NAME>, "MicMac, un lociel de mise en correspondance
d'images, adapte au contexte geograhique" to appears in
Bulletin d'information de l'Institut Geographique National, 2007.
Francais :
MicMac est un logiciel de mise en correspondance d'image adapte
au contexte de recherche en information geographique. Il s'appuie sur
la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la
licences Cecill-B. Voir en bas de fichier et http://www.cecill.info.
English :
MicMac is an open source software specialized in image matching
for research in geographic information. MicMac is built on the
eLiSe image library. MicMac is governed by the "Cecill-B licence".
See below and http://www.cecill.info.
Header-MicMac-eLiSe-25/06/2007*/
#include "general/all.h"
#include "Apero.h"
#include "im_tpl/algo_filter_exp.h"
namespace NS_ParamApero
{
// Lorsque l'on veut ponderer des observation ponctuelle dans le plan,
// si elles tombe toute au meme endroit, chacune doit avoir un poid proportionnel
// a l'inverse du nombre d'observation;
// Ici cela est gere avec une certaine incertitude, les observation etant suposee
// etre localisees selon une gaussienne
class cImDePonderH
{
public :
cImDePonderH(Pt2di aSz,double aDZ,double aDistAttenRel); // aDistAttenRel est donnee pur DZ=1
void Add(cObsLiaisonMultiple *);
void AddPt(const Pt2dr & aP);
void Compile();
// n'a de sens que lorsque c'est un des points ayant ete utilises pour
// pondere
double GetPds(const Pt2dr & aP)
{
return 1/mTImP.getproj(ToLocInd(aP));
}
Pt2di ToLocInd(const Pt2dr & aP) const {return round_ni(aP/mDZ);}
private :
Pt2di mSzR1;
double mDZ;
double mDAtt;
Pt2di mSzRed;
Im2D_REAL4 mImP;
TIm2D<REAL4,REAL8> mTImP;
};
cImDePonderH::cImDePonderH
(
Pt2di aSz,
double aDZ,
double aDistAtten
) :
mSzR1 (aSz),
mDZ (aDZ),
mDAtt (aDistAtten),
mSzRed (round_up(Pt2dr(mSzR1)/aDZ)),
mImP (mSzRed.x,mSzRed.y,0.0),
mTImP (mImP)
{
}
void cImDePonderH::Compile()
{
FilterGauss(mImP,mDAtt/mDZ);
}
cImDePonderH * NewImDePonderH(cObsLiaisonMultiple * anOLM,double aDZ,double aDAR)
{
Pt2di aSz = anOLM->Pose1()->Calib()->SzIm();
const std::vector<cOnePtsMult *> & aVPM = anOLM->VPMul();
int aNbPts = aVPM.size();
cImDePonderH * aRes = new cImDePonderH(aSz,aDZ,aDAR * std::sqrt((double)(aSz.x*aSz.y)/aNbPts));
for (int aKPt=0 ; aKPt<aNbPts ;aKPt++)
{
aRes->AddPt(aVPM[aKPt]->P0());
}
aRes->Compile();
return aRes;
}
void cImDePonderH::AddPt(const Pt2dr & aP)
{
mTImP.incr(ToLocInd(aP),1.0);
}
// ==================================================================================
// ==================================================================================
class cCmpImOnGainHom
{
public :
bool operator()(cPoseCam* aPC1,cPoseCam * aPC2)
{
return aPC1->MMNbPts()*aPC1->MMGainAng() > aPC2->MMNbPts()*aPC2->MMGainAng();
}
};
class cCmpImOnAngle
{
public :
bool operator()(cPoseCam* aPC1,cPoseCam * aPC2)
{
return aPC1->MMAngle() < aPC2->MMAngle();
}
};
// A Angle , O Optimum
// La formule est faite pour que
// * on ait un gain proportionnel a l'angle en 0
// * un maximum pour Opt avec une derivee nulle
// *
double GainAngle(double A,double Opt)
{
if (A <= Opt)
return 2*A*Opt - A*A;
return (Opt * Opt) / (1+ 2*pow(A/Opt-1,2));
}
void cAppliApero::ExportImSecMM(const cChoixImMM & aCIM,cPoseCam* aPC0)
{
cObsLiaisonMultiple * anOLM = PackMulOfIndAndNale (aCIM.IdBdl(),aPC0->Name());
const std::vector<cOnePtsMult *> & aVPM = anOLM->VPMul();
Pt3dr aPt0 = anOLM->CentreNuage();
const CamStenope & aCS0 = *(aPC0->CurCam());
aPC0->MMDir() = vunit(aCS0.PseudoOpticalCenter() - aPt0);
Pt3dr aDir0 = aPC0->MMDir();
// On remet a zero les gains
for(int aKP=0 ; aKP<int(mVecPose.size()) ;aKP++)
{
cPoseCam* aPC2 = mVecPose[aKP];
aPC2->MMNbPts() =0;
}
// On compte le nombre de points de liaisons
for (int aKPt=0 ; aKPt<int(aVPM.size()) ;aKPt++)
{
cOnePtsMult & aPMul = *(aVPM[aKPt]);
if (aPMul.MemPds() >0)
{
cOneCombinMult * anOCM = aPMul.OCM();
const std::vector<cPoseCam *> & aVP = anOCM->VP();
for (int aKPos=1 ; aKPos<int(aVP.size()) ;aKPos++)
{
aVP[aKPos]->MMNbPts()++;
}
}
}
aPC0->MMNbPts() = 0;
ELISE_ASSERT(false,"METTRE AU MOINS NbMaxPresel \n");
ELISE_ASSERT(false,"METTRE AU MOINS NbMaxPresel \n");
ELISE_ASSERT(false,"METTRE AU MOINS NbMaxPresel \n");
ELISE_ASSERT(false,"METTRE AU MOINS NbMaxPresel \n");
std::vector<cPoseCam*> aVPPres;
for(int aKP=0 ; aKP<int(mVecPose.size()) ;aKP++)
{
cPoseCam* aPC2 = mVecPose[aKP];
if ((aPC2 != aPC0) && (aPC2->MMNbPts()>aCIM.NbMinPtsHom().Val()))
{
aPC2->MMDir() = vunit(aPC2->CurCam()->PseudoOpticalCenter() - aPt0);
double anAngle = euclid(aDir0-aPC2->MMDir());
aPC2->MMAngle() = anAngle;
aPC2->MMGainAng() = GainAngle(anAngle,aCIM.TetaOpt().Val());
aVPPres.push_back(aPC2);
}
}
// On reduit au nombre Max de Presel
cCmpImOnGainHom aCmpGH;
std::sort(aVPPres.begin(),aVPPres.end(),aCmpGH);
while (int(aVPPres.size()) > aCIM.NbMaxPresel().Val())
aVPPres.pop_back();
// On supprime les angles trop fort en gardant au NbMin
cCmpImOnAngle aCmpAngle;
std::sort(aVPPres.begin(),aVPPres.end(),aCmpAngle);
while (
(int(aVPPres.size()) > aCIM.NbMinPresel().Val()) &&
(aVPPres.back()->MMAngle() > aCIM.TetaMaxPreSel().Val())
)
aVPPres.pop_back();
cImDePonderH * aImPond = NewImDePonderH (anOLM,10,1.0);
std::cout << aPC0->Name() << "\n";
for(int aKP=0 ; aKP<int(aVPPres.size()) ;aKP++)
{
aVPPres[aKP]->MMSelected() = false;
std::cout << " " << aVPPres[aKP]->Name() << " " << aVPPres[aKP]->MMAngle() << " " << aVPPres[aKP]->MMNbPts() << "\n";
}
std::cout << "=================================================\n";
#if(0)
while (! Ok)
{
for(int aKP1=0 ; aKP1<int(mVecPose.size()) ;aKP1++)
{
if (! mVecPose[aKPos]->MMSelected())
{
// double aG = ;
}
// mVecPose[aKPos]->MMGain() = 0.0;
}
}
bool Ok = false;
while (! Ok)
{
for(int aKPos=0 ; aKPos<int(mVecPose.size()) ;aKPos++)
{
if (! mVecPose[aKPos]->MMSelected())
mVecPose[aKPos]->MMGain() = 0.0;
}
int aNbNN=0;
for(int aKPt=0 ; aKPt<int(aVPM.size()) ;aKPt++)
{
cOnePtsMult & aPMul = *(aVPM[aKPt]);
if(aPMul.MemPds() >0)
{
aNbNN ++;
/*
cOneCombinMult * anOCM = aPMul->OCM();
const std::vector<cPoseCam *> & aVP = anOCM->VP();
for(int aKPos=1 ; aKPos<int(mVecPose.size()) ;aKPos++)
{
cPoseCam * aPC = aVP[aKPos];
if (! aPC->MMSelected())
{
}
}
*/
}
}
ELISE_ASSERT(aNbNN>0,"ExportImSecMM : probably no iteration !!");
}
#endif
delete aImPond;
std::cout << "OLM " << aVPM.size() << "\n";
}
void cAppliApero::ExportImMM(const cChoixImMM & aCIM)
{
cSetName * aSelector = mICNM->KeyOrPatSelector(aCIM.PatternSel());
for(int aKP=0 ; aKP<int(mVecPose.size()) ;aKP++)
{
cPoseCam* aPC = mVecPose[aKP];
if (aSelector->IsSetIn(aPC->Name()))
{
ExportImSecMM(aCIM,aPC);
}
}
}
};
/*Footer-MicMac-eLiSe-25/06/2007
Ce logiciel est un programme informatique servant à la mise en
correspondances d'images pour la reconstruction du relief.
Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
termes.
Footer-MicMac-eLiSe-25/06/2007*/
| 5,163 |
32,544 | <gh_stars>1000+
package com.baeldung.domain;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
@Document(collection = "STUDENT")
public class Student implements Serializable {
@Id
private String id;
@NotNull
private String firstName;
private String lastName;
@NotNull
private String phoneNumber;
private String email;
public Student(String firstName, String lastName, String phoneNumber, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.email = email;
}
public String getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", email='" + email + '\'' +
'}';
}
}
| 698 |
6,304 | <gh_stars>1000+
// Copyright 2020 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "tools/fiddle/examples.h"
REG_FIDDLE(radial_gradient_test, 256, 256, false, 0) {
void draw(SkCanvas* canvas) {
#define SIZE 121
SkScalar half = SIZE * 0.5f;
const SkColor preColor = 0xFFFF0000; // clamp color before start
const SkColor postColor = 0xFF0000FF; // clamp color after end
const SkColor color0 = 0xFF000000;
const SkColor color1 = 0xFF00FF00;
SkColor cs[] = {preColor, color0, color1, postColor};
SkScalar pos[] = {0, 0, 1, 1};
auto s = SkGradientShader::MakeRadial({half, half}, half - 10, cs, pos, 4,
SkTileMode::kClamp);
SkPaint p;
const SkRect rect = SkRect::MakeWH(SIZE, SIZE);
p.setShader(s);
canvas->drawRect(rect, p);
}
} // END FIDDLE
| 378 |
307 | <filename>plotoptix/install/__main__.py
"""
Install scripts for PlotOptiX extras.
Documentation: https://plotoptix.rnd.team
"""
import sys
def main():
if len(sys.argv) > 1:
if sys.argv[1] == "denoiser":
from plotoptix.install.denoiser import install_denoiser
result = install_denoiser()
elif sys.argv[1] == "examples":
from plotoptix.install.project import install_project
result = install_project("examples.zip", "1Bdq7SnvI3fA12_-LoaF31h-d5E67T_32")
elif sys.argv[1] == "moon":
from plotoptix.install.project import install_project
result = install_project("moon.zip", "1yUZMskZzKiAQmjW7E3scGy-b_rUVdoa4")
else:
print("Unknown package name %s." % sys.argv[1])
if not result:
print("Package not installed.")
exit(0)
print("Usage: python -m plotoptix.install [package].")
if __name__ == '__main__':
main()
| 449 |
611 | package fr.adrienbrault.idea.symfony2plugin.tests.translation.parser;
import fr.adrienbrault.idea.symfony2plugin.translation.dict.DomainFileMap;
import fr.adrienbrault.idea.symfony2plugin.translation.parser.DomainMappings;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Collection;
/**
* @author <NAME> <<EMAIL>>
*/
public class DomainMappingsTest extends Assert {
@Test
public void testParser() throws FileNotFoundException {
File testFile = new File("src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/translation/parser/appDevDebugProjectContainer.xml");
DomainMappings domainMappings = new DomainMappings();
domainMappings.parser(new FileInputStream(testFile));
Collection<DomainFileMap> domainFileMaps = domainMappings.getDomainFileMaps();
assertEquals(14, domainFileMaps.size());
DomainFileMap craueFormFlowBundle = domainFileMaps.stream().filter(domainFileMap -> domainFileMap.getDomain().equals("CraueFormFlowBundle")).findFirst().get();
assertEquals("CraueFormFlowBundle", craueFormFlowBundle.getDomain());
assertEquals("de", craueFormFlowBundle.getLanguageKey());
assertEquals("yml", craueFormFlowBundle.getLoader());
assertTrue(craueFormFlowBundle.getPath().endsWith("CraueFormFlowBundle.de.yml"));
DomainFileMap foobarDomain1 = domainFileMaps.stream().filter(domainFileMap -> domainFileMap.getDomain().equals("foobar_domain1")).findFirst().get();
assertEquals("foobar_domain1", foobarDomain1.getDomain());
assertEquals("af", foobarDomain1.getLanguageKey());
assertEquals("xlf", foobarDomain1.getLoader());
assertTrue(foobarDomain1.getPath().endsWith("foobar_domain1.af.xlf"));
assertNotNull(domainFileMaps.stream().filter(domainFileMap -> domainFileMap.getDomain().equals("foobar_domain2")).findFirst().get());
assertNotNull(domainFileMaps.stream().filter(domainFileMap -> domainFileMap.getDomain().equals("foobar_domain3")).findFirst().get());
assertNotNull(domainFileMaps.stream().filter(domainFileMap -> domainFileMap.getDomain().equals("foobar_domain4")).findFirst().get());
}
}
| 793 |
362 | /*
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.common.testing.accessibility.framework.checks;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheck.Category;
import com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheckResult.AccessibilityCheckResultType;
import com.google.android.apps.common.testing.accessibility.framework.AccessibilityHierarchyCheck;
import com.google.android.apps.common.testing.accessibility.framework.AccessibilityHierarchyCheckResult;
import com.google.android.apps.common.testing.accessibility.framework.HashMapResultMetadata;
import com.google.android.apps.common.testing.accessibility.framework.Parameters;
import com.google.android.apps.common.testing.accessibility.framework.ResultMetadata;
import com.google.android.apps.common.testing.accessibility.framework.ViewHierarchyElementUtils;
import com.google.android.apps.common.testing.accessibility.framework.replacements.TextUtils;
import com.google.android.apps.common.testing.accessibility.framework.strings.StringManager;
import com.google.android.apps.common.testing.accessibility.framework.uielement.AccessibilityHierarchy;
import com.google.android.apps.common.testing.accessibility.framework.uielement.ViewHierarchyElement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* If two Views in a hierarchy have the same speakable text, that could be confusing for users. Two
* Views with the same text, and at least one of them is clickable we warn in that situation. If we
* find two non-clickable Views with the same speakable text, we report that fact as info. If no
* Views in the hierarchy have any speakable text, we report that the test was not run.
*/
public class DuplicateSpeakableTextCheck extends AccessibilityHierarchyCheck {
/** Result when two clickable views have the same speakable text. */
public static final int RESULT_ID_CLICKABLE_SAME_SPEAKABLE_TEXT = 1;
/** Result when two non-clickable views have the same speakable text. */
public static final int RESULT_ID_NON_CLICKABLE_SAME_SPEAKABLE_TEXT = 2;
/** [Legacy] Info result containing a clickable view's speakable text. */
public static final int RESULT_ID_CLICKABLE_SPEAKABLE_TEXT = 3;
/** [Legacy] Info result containing a non-clickable view's speakable text. */
public static final int RESULT_ID_NON_CLICKABLE_SPEAKABLE_TEXT = 4;
/** Result metadata key for a view's speakable text {@link String} */
public static final String KEY_SPEAKABLE_TEXT = "KEY_SPEAKABLE_TEXT";
/** Result metadata key for the {@code int} number of other views with the same speakable text. */
public static final String KEY_CONFLICTING_VIEW_COUNT = "KEY_CONFLICTING_VIEW_COUNT";
@Override
protected String getHelpTopic() {
return "7102513"; // Duplicate descriptions
}
@Override
public Category getCategory() {
return Category.CONTENT_LABELING;
}
@Override
public List<AccessibilityHierarchyCheckResult> runCheckOnHierarchy(
AccessibilityHierarchy hierarchy,
@Nullable ViewHierarchyElement fromRoot,
@Nullable Parameters parameters) {
List<AccessibilityHierarchyCheckResult> results = new ArrayList<>();
/* Find all text and the views that have that text throughout the full hierarchy */
Map<String, List<ViewHierarchyElement>> textToViewMap = getSpeakableTextToViewMap(
hierarchy.getActiveWindow().getAllViews());
/* Deal with any duplicated text */
for (String speakableText : textToViewMap.keySet()) {
if (textToViewMap.get(speakableText).size() < 2) {
continue; // Text is not duplicated
}
// We've found duplicated text. Sort the Views into clickable and non-clickable if they're
// within scope for evaluation.
List<ViewHierarchyElement> clickableViews = new ArrayList<>();
List<ViewHierarchyElement> nonClickableViews = new ArrayList<>();
List<? extends ViewHierarchyElement> viewsToEval =
(fromRoot != null) ? fromRoot.getSelfAndAllDescendants() : null;
for (ViewHierarchyElement view : textToViewMap.get(speakableText)) {
if ((viewsToEval == null) || viewsToEval.contains(view)) {
if (Boolean.TRUE.equals(view.isClickable())) {
clickableViews.add(view);
} else {
nonClickableViews.add(view);
}
}
}
if (!clickableViews.isEmpty()) {
/* Display warning */
ResultMetadata resultMetadata = new HashMapResultMetadata();
resultMetadata.putString(
KEY_SPEAKABLE_TEXT, speakableText);
resultMetadata.putInt(KEY_CONFLICTING_VIEW_COUNT,
(clickableViews.size() + nonClickableViews.size() - 1));
results.add(new AccessibilityHierarchyCheckResult(
this.getClass(),
AccessibilityCheckResultType.WARNING,
clickableViews.get(0),
RESULT_ID_CLICKABLE_SAME_SPEAKABLE_TEXT,
resultMetadata));
clickableViews.remove(0);
} else if (!nonClickableViews.isEmpty()) {
/* Only duplication is on non-clickable views */
ResultMetadata resultMetadata = new HashMapResultMetadata();
resultMetadata.putString(
KEY_SPEAKABLE_TEXT, speakableText);
resultMetadata.putInt(KEY_CONFLICTING_VIEW_COUNT,
(clickableViews.size() + nonClickableViews.size() - 1));
results.add(new AccessibilityHierarchyCheckResult(
this.getClass(),
AccessibilityCheckResultType.INFO,
nonClickableViews.get(0),
RESULT_ID_NON_CLICKABLE_SAME_SPEAKABLE_TEXT,
resultMetadata));
nonClickableViews.remove(0);
}
}
return results;
}
@Override
public String getMessageForResultData(
Locale locale, int resultId, @Nullable ResultMetadata metadata) {
// For each of the following result IDs, metadata will have been set on the result.
checkNotNull(metadata);
switch (resultId) {
case RESULT_ID_CLICKABLE_SAME_SPEAKABLE_TEXT:
return String.format(locale,
StringManager.getString(locale, "result_message_same_speakable_text"),
StringManager.getString(locale, "clickable"),
metadata.getString(KEY_SPEAKABLE_TEXT),
metadata.getInt(KEY_CONFLICTING_VIEW_COUNT));
case RESULT_ID_NON_CLICKABLE_SAME_SPEAKABLE_TEXT:
return String.format(locale,
StringManager.getString(locale, "result_message_same_speakable_text"),
StringManager.getString(locale, "non_clickable"),
metadata.getString(KEY_SPEAKABLE_TEXT),
metadata.getInt(KEY_CONFLICTING_VIEW_COUNT));
// Legacy
case RESULT_ID_CLICKABLE_SPEAKABLE_TEXT:
return String.format(locale,
StringManager.getString(locale, "result_message_speakable_text"),
StringManager.getString(locale, "clickable"),
metadata.getString(KEY_SPEAKABLE_TEXT));
case RESULT_ID_NON_CLICKABLE_SPEAKABLE_TEXT:
return String.format(locale,
StringManager.getString(locale, "result_message_speakable_text"),
StringManager.getString(locale, "non_clickable"),
metadata.getString(KEY_SPEAKABLE_TEXT));
default:
throw new IllegalStateException("Unsupported result id");
}
}
@Override
public String getShortMessageForResultData(
Locale locale, int resultId, @Nullable ResultMetadata metadata) {
switch (resultId) {
case RESULT_ID_CLICKABLE_SAME_SPEAKABLE_TEXT:
case RESULT_ID_NON_CLICKABLE_SAME_SPEAKABLE_TEXT:
case RESULT_ID_CLICKABLE_SPEAKABLE_TEXT:
case RESULT_ID_NON_CLICKABLE_SPEAKABLE_TEXT:
return StringManager.getString(locale, "result_message_brief_same_speakable_text");
default:
throw new IllegalStateException("Unsupported result id");
}
}
/**
* Calculates a secondary priority for a duplicate speakable text result.
*
* <p>The result is the number of other views with the same text. Thus, the greater the number of
* repetitions, the higher the priority.
*/
@Override
public @Nullable Double getSecondaryPriority(AccessibilityHierarchyCheckResult result) {
ResultMetadata metadata = result.getMetadata();
switch (result.getResultId()) {
case RESULT_ID_CLICKABLE_SAME_SPEAKABLE_TEXT:
case RESULT_ID_NON_CLICKABLE_SAME_SPEAKABLE_TEXT:
return (double) checkNotNull(metadata).getInt(KEY_CONFLICTING_VIEW_COUNT, 0);
default:
return null;
}
}
@Override
public String getTitleMessage(Locale locale) {
return StringManager.getString(locale, "check_title_duplicate_speakable_text");
}
/**
* @param allViews Set of views to index by their speakable text
* @return map from speakable text to all views with that speakable text
*/
private Map<String, List<ViewHierarchyElement>> getSpeakableTextToViewMap(
Collection<? extends ViewHierarchyElement> allViews) {
Map<String, List<ViewHierarchyElement>> textToViewMap = new HashMap<>();
for (ViewHierarchyElement view : allViews) {
if (!ViewHierarchyElementUtils.shouldFocusView(view)) {
// If the screen reader won't focus the control, the description is unimportant
continue;
}
String speakableText =
ViewHierarchyElementUtils.getSpeakableTextForElement(view).toString().trim();
if (TextUtils.isEmpty(speakableText)) {
continue;
}
if (!textToViewMap.containsKey(speakableText)) {
textToViewMap.put(speakableText, new ArrayList<ViewHierarchyElement>());
}
textToViewMap.get(speakableText).add(view);
}
return textToViewMap;
}
}
| 3,772 |
669 | <gh_stars>100-1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/graph/node_attr_utils.h"
#include "core/common/common.h"
#include "core/framework/tensorprotoutils.h"
using namespace ONNX_NAMESPACE;
namespace onnxruntime::utils {
static void SetNameAndType(std::string attr_name, AttributeProto_AttributeType attr_type, AttributeProto& a) {
a.set_name(std::move(attr_name));
a.set_type(attr_type);
}
#define MAKE_BASIC_ATTR_IMPL(type, enumType, field) \
AttributeProto MakeAttribute(std::string attr_name, type value) { \
AttributeProto a; \
a.set_##field(std::move(value)); \
SetNameAndType(std::move(attr_name), enumType, a); \
return a; \
}
#define MAKE_ATTR_IMPL(type, enumType, field) \
AttributeProto MakeAttribute(std::string attr_name, type value) { \
AttributeProto a; \
*(a.mutable_##field()) = std::move(value); \
SetNameAndType(std::move(attr_name), enumType, a); \
return a; \
}
#define MAKE_LIST_ATTR_IMPL(type, enumType, field) \
AttributeProto MakeAttribute(std::string attr_name, gsl::span<const type> values) { \
AttributeProto a; \
auto* mutable_field = a.mutable_##field(); \
for (const auto& val : values) { \
*(mutable_field->Add()) = val; \
} \
SetNameAndType(std::move(attr_name), enumType, a); \
return a; \
}
MAKE_BASIC_ATTR_IMPL(int64_t, AttributeProto_AttributeType::AttributeProto_AttributeType_INT, i)
MAKE_LIST_ATTR_IMPL(int64_t, AttributeProto_AttributeType::AttributeProto_AttributeType_INTS, ints)
MAKE_BASIC_ATTR_IMPL(float, AttributeProto_AttributeType::AttributeProto_AttributeType_FLOAT, f)
MAKE_LIST_ATTR_IMPL(float, AttributeProto_AttributeType::AttributeProto_AttributeType_FLOATS, floats)
MAKE_ATTR_IMPL(std::string, AttributeProto_AttributeType::AttributeProto_AttributeType_STRING, s)
MAKE_LIST_ATTR_IMPL(std::string, AttributeProto_AttributeType::AttributeProto_AttributeType_STRINGS, strings)
MAKE_ATTR_IMPL(TensorProto, AttributeProto_AttributeType::AttributeProto_AttributeType_TENSOR, t)
MAKE_LIST_ATTR_IMPL(TensorProto, AttributeProto_AttributeType::AttributeProto_AttributeType_TENSORS, tensors)
#if !defined(DISABLE_SPARSE_TENSORS)
MAKE_ATTR_IMPL(SparseTensorProto, AttributeProto_AttributeType::AttributeProto_AttributeType_SPARSE_TENSOR,
sparse_tensor)
MAKE_LIST_ATTR_IMPL(SparseTensorProto, AttributeProto_AttributeType::AttributeProto_AttributeType_SPARSE_TENSORS,
sparse_tensors)
#endif
MAKE_ATTR_IMPL(TypeProto, AttributeProto_AttributeType::AttributeProto_AttributeType_TYPE_PROTO, tp)
MAKE_LIST_ATTR_IMPL(TypeProto, AttributeProto_AttributeType::AttributeProto_AttributeType_TYPE_PROTOS, type_protos)
MAKE_ATTR_IMPL(GraphProto, AttributeProto_AttributeType::AttributeProto_AttributeType_GRAPH, g)
MAKE_LIST_ATTR_IMPL(GraphProto, AttributeProto_AttributeType::AttributeProto_AttributeType_GRAPHS, graphs)
#undef MAKE_BASIC_ATTR_IMPL
#undef MAKE_ATTR_IMPL
#undef MAKE_LIST_ATTR_IMPL
std::pair<NodeAttributes::iterator, bool> SetNodeAttribute(AttributeProto attribute,
NodeAttributes& node_attributes) {
ORT_ENFORCE(utils::HasName(attribute), "AttributeProto must have a name.");
std::string name = attribute.name();
return node_attributes.insert_or_assign(std::move(name), std::move(attribute));
}
} // namespace onnxruntime::utils
| 2,081 |
1,695 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.plugin.deltalake.transactionlog;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.trino.parquet.ParquetReaderOptions;
import io.trino.plugin.deltalake.transactionlog.checkpoint.CheckpointEntryIterator;
import io.trino.plugin.deltalake.transactionlog.checkpoint.CheckpointSchemaManager;
import io.trino.plugin.deltalake.transactionlog.checkpoint.LastCheckpoint;
import io.trino.plugin.deltalake.transactionlog.checkpoint.TransactionLogTail;
import io.trino.plugin.hive.FileFormatDataSourceStats;
import io.trino.plugin.hive.HdfsEnvironment;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.type.TypeManager;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import static com.google.common.collect.Streams.stream;
import static io.trino.plugin.deltalake.DeltaLakeErrorCode.DELTA_LAKE_BAD_DATA;
import static io.trino.plugin.deltalake.DeltaLakeErrorCode.DELTA_LAKE_INVALID_SCHEMA;
import static io.trino.plugin.deltalake.transactionlog.TransactionLogParser.readLastCheckpoint;
import static io.trino.plugin.deltalake.transactionlog.TransactionLogUtil.getTransactionLogDir;
import static io.trino.plugin.deltalake.transactionlog.checkpoint.CheckpointEntryIterator.EntryType.ADD;
import static io.trino.plugin.deltalake.transactionlog.checkpoint.CheckpointEntryIterator.EntryType.METADATA;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
/**
* The current state of a Delta table. It's defined by its latest checkpoint and the subsequent transactions
* not included in the checkpoint.
*/
public class TableSnapshot
{
private final Optional<LastCheckpoint> lastCheckpoint;
private final SchemaTableName table;
private final TransactionLogTail logTail;
private final Path tableLocation;
private final ParquetReaderOptions parquetReaderOptions;
private final boolean checkpointRowStatisticsWritingEnabled;
private Optional<MetadataEntry> cachedMetadata = Optional.empty();
private TableSnapshot(
SchemaTableName table,
Optional<LastCheckpoint> lastCheckpoint,
TransactionLogTail logTail,
Path tableLocation,
ParquetReaderOptions parquetReaderOptions,
boolean checkpointRowStatisticsWritingEnabled)
{
this.table = requireNonNull(table, "table is null");
this.lastCheckpoint = requireNonNull(lastCheckpoint, "lastCheckpoint is null");
this.logTail = requireNonNull(logTail, "logTail is null");
this.tableLocation = requireNonNull(tableLocation, "tableLocation is null");
this.parquetReaderOptions = requireNonNull(parquetReaderOptions, "parquetReaderOptions is null");
this.checkpointRowStatisticsWritingEnabled = checkpointRowStatisticsWritingEnabled;
}
public static TableSnapshot load(
SchemaTableName table,
FileSystem fileSystem,
Path tableLocation,
ParquetReaderOptions parquetReaderOptions,
boolean checkpointRowStatisticsWritingEnabled)
throws IOException
{
Optional<LastCheckpoint> lastCheckpoint = readLastCheckpoint(fileSystem, tableLocation);
Optional<Long> lastCheckpointVersion = lastCheckpoint.map(LastCheckpoint::getVersion);
TransactionLogTail transactionLogTail = TransactionLogTail.loadNewTail(fileSystem, tableLocation, lastCheckpointVersion);
return new TableSnapshot(
table,
lastCheckpoint,
transactionLogTail,
tableLocation,
parquetReaderOptions,
checkpointRowStatisticsWritingEnabled);
}
public Optional<TableSnapshot> getUpdatedSnapshot(FileSystem fileSystem)
throws IOException
{
Optional<LastCheckpoint> lastCheckpoint = readLastCheckpoint(fileSystem, tableLocation);
long lastCheckpointVersion = lastCheckpoint.map(LastCheckpoint::getVersion).orElse(0L);
long cachedLastCheckpointVersion = getLastCheckpointVersion().orElse(0L);
Optional<TransactionLogTail> updatedLogTail;
if (cachedLastCheckpointVersion == lastCheckpointVersion) {
updatedLogTail = logTail.getUpdatedTail(fileSystem, tableLocation);
}
else {
updatedLogTail = Optional.of(TransactionLogTail.loadNewTail(fileSystem, tableLocation, Optional.of(lastCheckpointVersion)));
}
return updatedLogTail.map(transactionLogTail -> new TableSnapshot(
table,
lastCheckpoint,
transactionLogTail,
tableLocation,
parquetReaderOptions,
checkpointRowStatisticsWritingEnabled));
}
public long getVersion()
{
return logTail.getVersion();
}
public SchemaTableName getTable()
{
return table;
}
public Optional<MetadataEntry> getCachedMetadata()
{
return cachedMetadata;
}
public Path getTableLocation()
{
return tableLocation;
}
public void setCachedMetadata(Optional<MetadataEntry> cachedMetadata)
{
this.cachedMetadata = cachedMetadata;
}
public List<DeltaLakeTransactionLogEntry> getJsonTransactionLogEntries()
{
return logTail.getFileEntries();
}
public Stream<DeltaLakeTransactionLogEntry> getCheckpointTransactionLogEntries(
ConnectorSession session,
Set<CheckpointEntryIterator.EntryType> entryTypes,
CheckpointSchemaManager checkpointSchemaManager,
TypeManager typeManager,
FileSystem fileSystem,
HdfsEnvironment hdfsEnvironment,
FileFormatDataSourceStats stats)
throws IOException
{
if (lastCheckpoint.isEmpty()) {
return Stream.empty();
}
LastCheckpoint checkpoint = lastCheckpoint.get();
// Add entries contain statistics. When struct statistics are used the format of the Parquet file depends on the schema. It is important to use the schema at the time
// of the Checkpoint creation, in case the schema has evolved since it was written.
Optional<MetadataEntry> metadataEntry = entryTypes.contains(ADD) ?
Optional.of(getCheckpointMetadataEntry(
session,
checkpointSchemaManager,
typeManager,
fileSystem,
hdfsEnvironment,
stats,
checkpoint)) :
Optional.empty();
Stream<DeltaLakeTransactionLogEntry> resultStream = Stream.empty();
for (Path checkpointPath : getCheckpointPartPaths(checkpoint)) {
resultStream = Stream.concat(
resultStream,
getCheckpointTransactionLogEntries(
session,
entryTypes,
metadataEntry,
checkpointSchemaManager,
typeManager,
fileSystem,
hdfsEnvironment,
stats,
checkpoint,
checkpointPath));
}
return resultStream;
}
public Optional<Long> getLastCheckpointVersion()
{
return lastCheckpoint.map(LastCheckpoint::getVersion);
}
private Stream<DeltaLakeTransactionLogEntry> getCheckpointTransactionLogEntries(
ConnectorSession session,
Set<CheckpointEntryIterator.EntryType> entryTypes,
Optional<MetadataEntry> metadataEntry,
CheckpointSchemaManager checkpointSchemaManager,
TypeManager typeManager,
FileSystem fileSystem,
HdfsEnvironment hdfsEnvironment,
FileFormatDataSourceStats stats,
LastCheckpoint checkpoint,
Path checkpointPath)
throws IOException
{
FileStatus fileStatus;
try {
fileStatus = fileSystem.getFileStatus(checkpointPath);
}
catch (FileNotFoundException e) {
throw new TrinoException(DELTA_LAKE_INVALID_SCHEMA, format("%s mentions a non-existent checkpoint file for table: %s", checkpoint, table));
}
Iterator<DeltaLakeTransactionLogEntry> checkpointEntryIterator = new CheckpointEntryIterator(
checkpointPath,
session,
fileStatus.getLen(),
checkpointSchemaManager,
typeManager,
entryTypes,
metadataEntry,
hdfsEnvironment,
stats,
parquetReaderOptions,
checkpointRowStatisticsWritingEnabled);
return stream(checkpointEntryIterator);
}
private MetadataEntry getCheckpointMetadataEntry(
ConnectorSession session,
CheckpointSchemaManager checkpointSchemaManager,
TypeManager typeManager,
FileSystem fileSystem,
HdfsEnvironment hdfsEnvironment,
FileFormatDataSourceStats stats,
LastCheckpoint checkpoint)
throws IOException
{
for (Path checkpointPath : getCheckpointPartPaths(checkpoint)) {
Stream<DeltaLakeTransactionLogEntry> metadataEntries = getCheckpointTransactionLogEntries(
session,
ImmutableSet.of(METADATA),
Optional.empty(),
checkpointSchemaManager,
typeManager,
fileSystem,
hdfsEnvironment,
stats,
checkpoint,
checkpointPath);
Optional<DeltaLakeTransactionLogEntry> metadataEntry = metadataEntries.findFirst();
if (metadataEntry.isPresent()) {
return metadataEntry.get().getMetaData();
}
}
throw new TrinoException(DELTA_LAKE_BAD_DATA, "Checkpoint found without metadata entry: " + checkpoint);
}
private List<Path> getCheckpointPartPaths(LastCheckpoint checkpoint)
{
Path transactionLogDir = getTransactionLogDir(tableLocation);
ImmutableList.Builder<Path> paths = ImmutableList.builder();
if (checkpoint.getParts().isEmpty()) {
paths.add(new Path(transactionLogDir, format("%020d.checkpoint.parquet", checkpoint.getVersion())));
}
else {
int partsCount = checkpoint.getParts().get();
for (int i = 1; i <= partsCount; i++) {
paths.add(new Path(transactionLogDir, format("%020d.checkpoint.%010d.%010d.parquet", checkpoint.getVersion(), i, partsCount)));
}
}
return paths.build();
}
}
| 4,839 |
2,690 | <reponame>NoahR02/Odin<gh_stars>1000+
template <typename T>
struct PriorityQueue {
Array<T> queue;
int (* cmp) (T *q, isize i, isize j);
void (* swap)(T *q, isize i, isize j);
};
template <typename T>
bool priority_queue_shift_down(PriorityQueue<T> *pq, isize i0, isize n) {
// O(n log n)
isize i = i0;
isize j, j1, j2;
if (0 > i || i > n) return false;
for (;;) {
j1 = 2*i + 1;
if (0 > j1 || j1 >= n) break;
j = j1;
j2 = j1 + 1;
if (j2 < n && pq->cmp(&pq->queue[0], j2, j1) < 0) {
j = j2;
}
if (pq->cmp(&pq->queue[0], j, i) >= 0) break;
pq->swap(&pq->queue[0], i, j);
i = j;
}
return i > i0;
}
template <typename T>
void priority_queue_shift_up(PriorityQueue<T> *pq, isize j) {
while (0 <= j && j < pq->queue.count) {
isize i = (j-1)/2;
if (i == j || pq->cmp(&pq->queue[0], j, i) >= 0) {
break;
}
pq->swap(&pq->queue[0], i, j);
j = i;
}
}
// NOTE(bill): When an element at index `i0` has changed its value, this will fix the
// the heap ordering. This using a basic "heapsort" with shift up and a shift down parts.
template <typename T>
void priority_queue_fix(PriorityQueue<T> *pq, isize i) {
if (!priority_queue_shift_down(pq, i, pq->queue.count)) {
priority_queue_shift_up(pq, i);
}
}
template <typename T>
void priority_queue_push(PriorityQueue<T> *pq, T const &value) {
array_add(&pq->queue, value);
priority_queue_shift_up(pq, pq->queue.count-1);
}
template <typename T>
T priority_queue_pop(PriorityQueue<T> *pq) {
GB_ASSERT(pq->queue.count > 0);
isize n = pq->queue.count - 1;
pq->swap(&pq->queue[0], 0, n);
priority_queue_shift_down(pq, 0, n);
return array_pop(&pq->queue);
}
template <typename T>
T priority_queue_remove(PriorityQueue<T> *pq, isize i) {
GB_ASSERT(0 <= i && i < pq->queue.count);
isize n = pq->queue.count - 1;
if (n != i) {
pq->swap(&pq->queue[0], i, n);
priority_queue_shift_down(pq, i, n);
priority_queue_shift_up(pq, i);
}
return array_pop(&pq->queue);
}
template <typename T>
PriorityQueue<T> priority_queue_create(Array<T> queue,
int (* cmp) (T *q, isize i, isize j),
void (* swap)(T *q, isize i, isize j)) {
PriorityQueue<T> pq = {};
pq.queue = queue;
pq.cmp = cmp;
pq.swap = swap;
isize n = pq.queue.count;
for (isize i = n/2 - 1; i >= 0; i--) {
priority_queue_shift_down(&pq, i, n);
}
return pq;
}
| 1,172 |
3,380 | <reponame>TysonHeart/dynomite
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include "dyn_conf.h"
#include "dyn_core.h"
#include "dyn_node_snitch.h"
#include "dyn_string.h"
#include "dyn_util.h"
static unsigned char *broadcast_address = NULL;
static char *public_hostname = NULL;
static char *public_ip4 = NULL;
static char *private_ip4 = NULL;
static bool is_aws_env(struct server_pool *sp) {
return dn_strncmp(&sp->env.data, CONF_DEFAULT_ENV, 3);
}
static unsigned char *hostname_to_ip(char *hostname) {
struct hostent *he;
struct in_addr **addr_list;
int i;
if ((he = gethostbyname(hostname)) == NULL) {
return NULL;
}
addr_list = (struct in_addr **)he->h_addr_list;
for (i = 0; addr_list[i] != NULL; i++)
;
unsigned char *ip = dn_alloc(i);
for (i = 0; addr_list[i] != NULL; i++) {
// Return the first one;
strcpy(ip, inet_ntoa(*(0 + addr_list[i])));
return ip;
}
return NULL;
}
unsigned char *get_broadcast_address(struct server_pool *sp) {
if (broadcast_address != NULL) return broadcast_address;
if (is_aws_env(sp)) {
broadcast_address = getenv("EC2_PUBLIC_HOSTNAME");
if (broadcast_address != NULL) return broadcast_address;
} else {
broadcast_address = getenv("PUBLIC_HOSTNAME");
if (broadcast_address != NULL) return broadcast_address;
}
struct node *peer = *(struct node **)array_get(&sp->peers, 0);
broadcast_address = (char *)peer->name.data;
return broadcast_address;
}
char *get_public_hostname(struct server_pool *sp) {
if (public_hostname != NULL) return public_hostname;
if (is_aws_env(sp)) {
public_hostname = getenv("EC2_PUBLIC_HOSTNAME");
if (public_hostname != NULL) return public_hostname;
} else {
public_hostname = getenv("PUBLIC_HOSTNAME");
if (public_hostname != NULL) return public_hostname;
}
struct node *peer = *(struct node **)array_get(&sp->peers, 0);
if ((peer != NULL) && (peer->name.data != NULL)) {
char c = (char)peer->name.data[0];
if (!isdigit(c)) {
public_hostname = (char *)peer->name.data;
return public_hostname;
}
}
return NULL;
}
char *get_public_ip4(struct server_pool *sp) {
if (public_ip4 != NULL) return public_ip4;
if (is_aws_env(sp)) {
public_ip4 = getenv("EC2_PUBLIC_IPV4");
if (public_ip4 != NULL) return public_ip4;
} else {
public_ip4 = getenv("PUBLIC_IPV4");
if (public_ip4 != NULL) return public_ip4;
}
struct node *peer = *(struct node **)array_get(&sp->peers, 0);
if ((peer != NULL) && (peer->name.data != NULL)) {
char c = (char)peer->name.data[0];
if (isdigit(c)) return (char *)peer->name.data;
}
return NULL;
}
char *get_private_ip4(struct server_pool *sp) {
if (private_ip4 != NULL) return private_ip4;
if (is_aws_env(sp)) {
private_ip4 = getenv("EC2_LOCAL_IPV4");
if (private_ip4 != NULL) return private_ip4;
} else {
private_ip4 = getenv("LOCAL_IPV4");
if (private_ip4 != NULL) return private_ip4;
}
return NULL;
}
unsigned char *hostname_to_private_ip4(char *hostname) {
return hostname_to_ip(hostname);
}
| 1,293 |
577 | <reponame>CyberFlameGO/exposure-notifications-android
/*
* 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.
*
*/
package com.google.android.apps.exposurenotification.nearby;
import android.content.Context;
import com.google.android.apps.exposurenotification.logging.AnalyticsLogger;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.exposurenotification.ExposureNotificationClient;
import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.android.qualifiers.ApplicationContext;
import dagger.hilt.components.SingletonComponent;
import javax.inject.Singleton;
@Module
@InstallIn(SingletonComponent.class)
public class ExposureNotificationsClientModule {
@Provides
public ExposureNotificationClient provideExposureNotificationClient(
@ApplicationContext Context context) {
return Nearby.getExposureNotificationClient(context);
}
@Provides
@Singleton
public ExposureNotificationClientWrapper provideExposureNotificationClientWrapper(
ExposureNotificationClient exposureNotificationClient,
AnalyticsLogger logger) {
return new ExposureNotificationClientWrapper(exposureNotificationClient, logger);
}
}
| 488 |
861 | <reponame>scotthufeng/spring-cloud-gray<gh_stars>100-1000
package cn.springcloud.gray.server.resources.rest;
import cn.springcloud.gray.api.ApiRes;
import cn.springcloud.gray.server.module.user.UserModule;
import cn.springcloud.gray.server.module.user.domain.UserInfo;
import cn.springcloud.gray.server.module.user.domain.UserQuery;
import cn.springcloud.gray.server.oauth2.Oauth2Service;
import cn.springcloud.gray.server.oauth2.TokenRequestInfo;
import cn.springcloud.gray.server.resources.domain.fo.LoginFO;
import cn.springcloud.gray.server.resources.domain.fo.ResetPasswordFO;
import cn.springcloud.gray.server.resources.domain.fo.UpdatePasswordFO;
import cn.springcloud.gray.server.resources.domain.fo.UserRegisterFO;
import cn.springcloud.gray.server.utils.ApiResHelper;
import cn.springcloud.gray.server.utils.PaginationUtils;
import com.google.common.collect.ImmutableBiMap;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RequestMapping("/gray/user")
@RestController
public class UserResource {
private static final Logger log = LoggerFactory.getLogger(UserResource.class);
@Autowired
private Oauth2Service oauth2Service;
@Autowired
private UserModule userModule;
@PostMapping(value = "/login")
public ApiRes<Map<String, String>> login(@RequestBody LoginFO fo) {
UserInfo userInfo = userModule.login(fo.getUsername(), fo.getPassword());
if (userInfo == null) {
return ApiRes.<Map<String, String>>builder()
.code("1")
.message("用户名或密码不正确")
.build();
}
List<GrantedAuthority> authorities = new ArrayList<>();
for (String role : userInfo.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role));
}
User user = new User(fo.getUsername(), fo.getPassword(), authorities);
OAuth2AccessToken oAuth2AccessToken = oauth2Service.getAccessToken(
TokenRequestInfo.builder().userDetails(user).build());
return ApiResHelper.successData(ImmutableBiMap.of("token", oAuth2AccessToken.getValue()));
}
@RequestMapping(value = "/info", method = {RequestMethod.OPTIONS, RequestMethod.GET})
public ApiRes<UserInfo> info() {
UserInfo userInfo = userModule.getUserInfo(userModule.getCurrentUserId());
if (userInfo == null) {
return ApiResHelper.notFound();
}
return ApiResHelper.successData(userInfo);
}
@PostMapping(value = "/logout")
public ApiRes<Map<String, String>> logout() {
return ApiResHelper.successData(ImmutableBiMap.of());
}
@GetMapping(value = "/page")
public ResponseEntity<ApiRes<List<UserInfo>>> page(
@RequestParam(value = "key", required = false) String key,
@RequestParam(value = "status", required = false) Integer status,
@ApiParam @PageableDefault(sort = "createTime", direction = Sort.Direction.DESC) Pageable pageable) {
UserQuery userQuery = UserQuery.builder()
.key(key)
.status(ObjectUtils.defaultIfNull(status, -1))
.build();
Page<UserInfo> userInfoPage = userModule.query(userQuery, pageable);
HttpHeaders headers = PaginationUtils.generatePaginationHttpHeaders(userInfoPage);
return new ResponseEntity<>(
ApiResHelper.successData(userInfoPage.getContent()),
headers,
HttpStatus.OK);
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public ApiRes<UserInfo> addUser(@RequestBody UserRegisterFO fo) {
UserInfo currentUser = userModule.getCurrentUserInfo();
if (currentUser == null || !currentUser.isAdmin()) {
return ApiResHelper.notAuthority();
}
UserInfo newUserInfo = userModule.register(fo.toUserInfo(), fo.getPassword());
return ApiResHelper.successData(newUserInfo);
}
@RequestMapping(value = "/", method = RequestMethod.PUT)
public ApiRes<UserInfo> updateUser(@RequestBody UserInfo userInfo) {
UserInfo currentUser = userModule.getCurrentUserInfo();
if (currentUser == null || !currentUser.isAdmin()) {
return ApiResHelper.notAuthority();
}
userInfo.setOperator(userModule.getCurrentUserId());
UserInfo newUserInfo = userModule.updateUserInfo(userInfo);
if (newUserInfo == null) {
ApiResHelper.notFound();
}
return ApiResHelper.successData(newUserInfo);
}
@RequestMapping(value = "/resetPassword", method = RequestMethod.PUT)
public ApiRes<Void> resetPassword(@RequestBody ResetPasswordFO fo) {
UserInfo currentUser = userModule.getCurrentUserInfo();
if (currentUser == null || !currentUser.isAdmin()) {
return ApiResHelper.notAuthority();
}
userModule.resetPassword(fo.getUserId(), fo.getPassword());
return ApiResHelper.success();
}
@RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
public ApiRes<Void> updatePassword(@RequestBody UpdatePasswordFO fo) {
boolean result = userModule.resetPassword(
userModule.getCurrentUserId(), fo.getOldPassword(), fo.getNewPassword());
return result ? ApiResHelper.success() : ApiResHelper.failed();
}
}
| 2,376 |
511 | <filename>os/arch/arm/src/tiva/chip/lm4f_syscontrol.h
/****************************************************************************
*
* Copyright 2017 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/********************************************************************************************
* arch/arm/src/tiva/chip/lm4f_syscontrol.h
*
* Copyright (C) 2009-2010, 2013 <NAME>. All rights reserved.
* Author: <NAME> <<EMAIL>>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
********************************************************************************************/
#ifndef __ARCH_ARM_SRC_TIVA_CHIP_LM4F_SYSCONTROL_H
#define __ARCH_ARM_SRC_TIVA_CHIP_LM4F_SYSCONTROL_H
/********************************************************************************************
* Included Files
********************************************************************************************/
#include <tinyara/config.h>
/********************************************************************************************
* Pre-processor Definitions
********************************************************************************************/
/* System Control Register Offsets **********************************************************/
#define TIVA_SYSCON_DID0_OFFSET 0x000 /* Device Identification 0 */
#define TIVA_SYSCON_DID1_OFFSET 0x004 /* Device Identification 1 */
#define TIVA_SYSCON_PBORCTL_OFFSET 0x030 /* Brown-Out Reset Control */
#define TIVA_SYSCON_RIS_OFFSET 0x050 /* Raw Interrupt Status */
#define TIVA_SYSCON_IMC_OFFSET 0x054 /* Interrupt Mask Control */
#define TIVA_SYSCON_MISC_OFFSET 0x058 /* Masked Interrupt Status and Clear */
#define TIVA_SYSCON_RESC_OFFSET 0x05c /* Reset Cause */
#define TIVA_SYSCON_RCC_OFFSET 0x060 /* Run-Mode Clock Configuration */
#define TIVA_SYSCON_GPIOHBCTL_OFFSET 0x06c /* GPIO High-Performance Bus Control */
#define TIVA_SYSCON_RCC2_OFFSET 0x070 /* Run-Mode Clock Configuration 2 */
#define TIVA_SYSCON_MOSCCTL_OFFSET 0x07c /* Main Oscillator Control */
#define TIVA_SYSCON_DSLPCLKCFG_OFFSET 0x144 /* Deep Sleep Clock Configuration */
#define TIVA_SYSCON_SYSPROP_OFFSET 0x14c /* System Properties */
#define TIVA_SYSCON_PIOSCCAL_OFFSET 0x150 /* Precision Internal Oscillator Calibration */
#define TIVA_SYSCON_PIOSCSTAT_OFFSET 0x154 /* Precision Internal Oscillator Statistics */
#define TIVA_SYSCON_PLLFREQ0_OFFSET 0x160 /* PLL 0 Frequency */
#define TIVA_SYSCON_PLLFREQ1_OFFSET 0x164 /* PLL 1 Frequency */
#define TIVA_SYSCON_PLLSTAT_OFFSET 0x168 /* PLL Status */
#define TIVA_SYSCON_PPWD_OFFSET 0x300 /* Watchdog Timer Peripheral Present */
#define TIVA_SYSCON_PPTIMER_OFFSET 0x304 /* 16/32-Bit Timer Peripheral Present */
#define TIVA_SYSCON_PPGPIO_OFFSET 0x308 /* GPIO Peripheral Present */
#define TIVA_SYSCON_PPDMA_OFFSET 0x30c /* uDMA Peripheral Present */
#define TIVA_SYSCON_PPHIB_OFFSET 0x314 /* Hibernation Peripheral Present */
#define TIVA_SYSCON_PPUART_OFFSET 0x318 /* UART Present */
#define TIVA_SYSCON_PPSSI_OFFSET 0x31c /* SSI Peripheral Present */
#define TIVA_SYSCON_PPI2C_OFFSET 0x320 /* I2C Peripheral Present */
#define TIVA_SYSCON_PPUSB_OFFSET 0x328 /* USB Peripheral Present */
#define TIVA_SYSCON_PPCAN_OFFSET 0x334 /* CAN Peripheral Present */
#define TIVA_SYSCON_PPADC_OFFSET 0x338 /* ADC Peripheral Present */
#define TIVA_SYSCON_PPACMP_OFFSET 0x33c /* Analog Comparator Peripheral Present */
#define TIVA_SYSCON_PPPWM_OFFSET 0x340 /* Pulse Width Modulator Peripheral Present */
#define TIVA_SYSCON_PPQEI_OFFSET 0x344 /* Quadrature Encoder Peripheral Present */
#define TIVA_SYSCON_PPEEPROM_OFFSET 0x358 /* EEPROM Peripheral Present */
#define TIVA_SYSCON_PPWTIMER_OFFSET 0x35c /* 32/64-Bit Wide Timer Peripheral Present */
#define TIVA_SYSCON_SRWD_OFFSET 0x500 /* Watchdog Timer Software Reset */
#define TIVA_SYSCON_SRTIMER_OFFSET 0x504 /* 16/32-Bit Timer Software Reset */
#define TIVA_SYSCON_SRGPIO_OFFSET 0x508 /* GPIO Software Reset */
#define TIVA_SYSCON_SRDMA_OFFSET 0x50c /* uDMA Software Reset */
#define TIVA_SYSCON_SRHIB_OFFSET 0x514 /* Hibernation Software Reset */
#define TIVA_SYSCON_SRUART_OFFSET 0x518 /* UART Software Reset */
#define TIVA_SYSCON_SRSSI_OFFSET 0x51c /* SSI Software Reset */
#define TIVA_SYSCON_SRI2C_OFFSET 0x520 /* I2C Software Reset */
#define TIVA_SYSCON_SRUSB_OFFSET 0x528 /* USB Software Reset */
#define TIVA_SYSCON_SRCAN_OFFSET 0x534 /* CAN Software Reset */
#define TIVA_SYSCON_SRADC_OFFSET 0x538 /* ADC Software Reset */
#define TIVA_SYSCON_SRACMP_OFFSET 0x53c /* Analog Comparator Software Reset */
#define TIVA_SYSCON_SREEPROM_OFFSET 0x558 /* EEPROM Software Reset */
#define TIVA_SYSCON_SRWTIMER_OFFSET 0x55c /* 32/64-Bit Wide Timer Software Reset */
#define TIVA_SYSCON_RCGCWD_OFFSET 0x600 /* Watchdog Timer Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCTIMER_OFFSET 0x604 /* 16/32-Bit Timer Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCGPIO_OFFSET 0x608 /* GPIO Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCDMA_OFFSET 0x60c /* uDMA Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCHIB_OFFSET 0x614 /* Hibernation Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCUART_OFFSET 0x618 /* UART Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCSSI_OFFSET 0x61c /* SSI Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCI2C_OFFSET 0x620 /* I2C Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCUSB_OFFSET 0x628 /* USB Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCCAN_OFFSET 0x634 /* CAN Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCADC_OFFSET 0x638 /* ADC Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCACMP_OFFSET 0x63c /* Analog Comparator Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCEEPROM_OFFSET 0x658 /* EEPROM Run Mode Clock Gating Control */
#define TIVA_SYSCON_RCGCWTIMER_OFFSET 0x65c /* 32/64-BitWide Timer Run Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCWD_OFFSET 0x700 /* Watchdog Timer Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCTIMER_OFFSET 0x704 /* 16/32-Bit Timer Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCGPIO_OFFSET 0x708 /* GPIO Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCDMA_OFFSET 0x70c /* uDMA Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCHIB_OFFSET 0x714 /* Hibernation Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCUART_OFFSET 0x718 /* UART Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCSSI_OFFSET 0x71c /* SSI Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCI2C_OFFSET 0x720 /* I2C Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCUSB_OFFSET 0x728 /* USB Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCCAN_OFFSET 0x734 /* CAN Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCADC_OFFSET 0x738 /* ADC Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCACMP_OFFSET 0x73c /* Analog Comparator Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCEEPROM_OFFSET 0x758 /* EEPROM Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_SCGCWTIMER_OFFSET 0x75c /* 32/64-BitWide Timer Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCWD_OFFSET 0x800 /* Watchdog Timer Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCTIMER_OFFSET 0x804 /* Clock Gating Control */
#define TIVA_SYSCON_DCGCGPIO_OFFSET 0x808 /* GPIO Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCDMA_OFFSET 0x80c /* uDMA Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCHIB_OFFSET 0x814 /* Hibernation Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCUART_OFFSET 0x818 /* UART Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCSSI_OFFSET 0x81c /* SSI Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCI2C_OFFSET 0x820 /* I2C Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCUSB_OFFSET 0x828 /* USB Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCCAN_OFFSET 0x834 /* CAN Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCADC_OFFSET 0x838 /* ADC Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCACMP_OFFSET 0x83c /* Analog Comparator Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCEEPROM_OFFSET 0x858 /* EEPROM Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_DCGCWTIMER_OFFSET 0x85c /* 32/64-BitWide Timer Deep-Sleep Mode Clock Gating Control */
#define TIVA_SYSCON_PRWD_OFFSET 0xa00 /* Watchdog Timer Peripheral Ready */
#define TIVA_SYSCON_PRTIMER_OFFSET 0xa04 /* 16/32-Bit Timer Peripheral Ready */
#define TIVA_SYSCON_PRGPIO_OFFSET 0xa08 /* GPIO Peripheral Ready */
#define TIVA_SYSCON_PRDMA_OFFSET 0xa0c /* uDMA Peripheral Ready */
#define TIVA_SYSCON_PRHIB_OFFSET 0xa14 /* Hibernation Peripheral Ready */
#define TIVA_SYSCON_PRUART_OFFSET 0xa18 /* UART Peripheral Ready */
#define TIVA_SYSCON_PRSSI_OFFSET 0xa1c /* SSI Peripheral Ready */
#define TIVA_SYSCON_PRI2C_OFFSET 0xa20 /* I2C Peripheral Ready */
#define TIVA_SYSCON_PRUSB_OFFSET 0xa28 /* USB Peripheral Ready */
#define TIVA_SYSCON_PRCAN_OFFSET 0xa34 /* CAN Peripheral Ready */
#define TIVA_SYSCON_PRADC_OFFSET 0xa38 /* ADC Peripheral Ready */
#define TIVA_SYSCON_PRACMP_OFFSET 0xa3c /* Analog Comparator Peripheral Ready */
#define TIVA_SYSCON_PREEPROM_OFFSET 0xa58 /* EEPROM Peripheral Ready */
#define TIVA_SYSCON_PRWTIMER_OFFSET 0xa5c /* 2/64-BitWide Timer Peripheral Ready */
/* System Control Legacy Register Offsets ***************************************************/
#define TIVA_SYSCON_DC0_OFFSET 0x008 /* Device Capabilities 0 */
#define TIVA_SYSCON_DC1_OFFSET 0x010 /* Device Capabilities 1 */
#define TIVA_SYSCON_DC2_OFFSET 0x014 /* Device Capabilities 2 */
#define TIVA_SYSCON_DC3_OFFSET 0x018 /* Device Capabilities 3 */
#define TIVA_SYSCON_DC4_OFFSET 0x01c /* Device Capabilities 4 */
#define TIVA_SYSCON_DC5_OFFSET 0x020 /* Device Capabilities 5 */
#define TIVA_SYSCON_DC6_OFFSET 0x024 /* Device Capabilities 6 */
#define TIVA_SYSCON_DC7_OFFSET 0x028 /* Device Capabilities 7 */
#define TIVA_SYSCON_DC8_OFFSET 0x02c /* Device Capabilities 8 */
#define TIVA_SYSCON_SRCR0_OFFSET 0x040 /* Software Reset Control 0 */
#define TIVA_SYSCON_SRCR1_OFFSET 0x044 /* Software Reset Control 1 */
#define TIVA_SYSCON_SRCR2_OFFSET 0x048 /* Software Reset Control 2 */
#define TIVA_SYSCON_RCGC0_OFFSET 0x100 /* Run Mode Clock Gating Control Register 0 */
#define TIVA_SYSCON_RCGC1_OFFSET 0x104 /* Run Mode Clock Gating Control Register 1 */
#define TIVA_SYSCON_RCGC2_OFFSET 0x108 /* Run Mode Clock Gating Control Register 2 */
#define TIVA_SYSCON_SCGC0_OFFSET 0x110 /* Sleep Mode Clock Gating Control Register 0 */
#define TIVA_SYSCON_SCGC1_OFFSET 0x114 /* Sleep Mode Clock Gating Control Register 1 */
#define TIVA_SYSCON_SCGC2_OFFSET 0x118 /* Sleep Mode Clock Gating Control Register 2 */
#define TIVA_SYSCON_DCGC0_OFFSET 0x120 /* Deep Sleep Mode Clock Gating Control Register 0 */
#define TIVA_SYSCON_DCGC1_OFFSET 0x124 /* Deep Sleep Mode Clock Gating Control Register 1 */
#define TIVA_SYSCON_DCGC2_OFFSET 0x128 /* Deep Sleep Mode Clock Gating Control Register 2 */
#define TIVA_SYSCON_DC9_OFFSET 0x190 /* Device Capabilities */
#define TIVA_SYSCON_NVMSTAT_OFFSET 0x1a0 /* Non-Volatile Memory Information */
/* System Control Register Addresses ********************************************************/
#define TIVA_SYSCON_DID0 (TIVA_SYSCON_BASE + TIVA_SYSCON_DID0_OFFSET)
#define TIVA_SYSCON_DID1 (TIVA_SYSCON_BASE + TIVA_SYSCON_DID1_OFFSET)
#define TIVA_SYSCON_PBORCTL (TIVA_SYSCON_BASE + TIVA_SYSCON_PBORCTL_OFFSET)
#define TIVA_SYSCON_RIS (TIVA_SYSCON_BASE + TIVA_SYSCON_RIS_OFFSET)
#define TIVA_SYSCON_IMC (TIVA_SYSCON_BASE + TIVA_SYSCON_IMC_OFFSET)
#define TIVA_SYSCON_MISC (TIVA_SYSCON_BASE + TIVA_SYSCON_MISC_OFFSET)
#define TIVA_SYSCON_RESC (TIVA_SYSCON_BASE + TIVA_SYSCON_RESC_OFFSET)
#define TIVA_SYSCON_RCC (TIVA_SYSCON_BASE + TIVA_SYSCON_RCC_OFFSET)
#define TIVA_SYSCON_GPIOHBCTL (TIVA_SYSCON_BASE + TIVA_SYSCON_GPIOHBCTL_OFFSET)
#define TIVA_SYSCON_RCC2 (TIVA_SYSCON_BASE + TIVA_SYSCON_RCC2_OFFSET)
#define TIVA_SYSCON_MOSCCTL (TIVA_SYSCON_BASE + TIVA_SYSCON_MOSCCTL_OFFSET)
#define TIVA_SYSCON_DSLPCLKCFG (TIVA_SYSCON_BASE + TIVA_SYSCON_DSLPCLKCFG_OFFSET)
#define TIVA_SYSCON_SYSPROP (TIVA_SYSCON_BASE + TIVA_SYSCON_SYSPROP_OFFSET)
#define TIVA_SYSCON_PIOSCCAL (TIVA_SYSCON_BASE + TIVA_SYSCON_PIOSCCAL_OFFSET)
#define TIVA_SYSCON_PIOSCSTAT (TIVA_SYSCON_BASE + TIVA_SYSCON_PIOSCSTAT_OFFSET)
#define TIVA_SYSCON_PLLFREQ0 (TIVA_SYSCON_BASE + TIVA_SYSCON_PLLFREQ0_OFFSET)
#define TIVA_SYSCON_PLLFREQ1 (TIVA_SYSCON_BASE + TIVA_SYSCON_PLLFREQ1_OFFSET)
#define TIVA_SYSCON_PLLSTAT (TIVA_SYSCON_BASE + TIVA_SYSCON_PLLSTAT_OFFSET)
#define TIVA_SYSCON_PPWD (TIVA_SYSCON_BASE + TIVA_SYSCON_PPWD_OFFSET)
#define TIVA_SYSCON_PPTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_PPTIMER_OFFSET)
#define TIVA_SYSCON_PPGPIO (TIVA_SYSCON_BASE + TIVA_SYSCON_PPGPIO_OFFSET)
#define TIVA_SYSCON_PPDMA (TIVA_SYSCON_BASE + TIVA_SYSCON_PPDMA_OFFSET)
#define TIVA_SYSCON_PPHIB (TIVA_SYSCON_BASE + TIVA_SYSCON_PPHIB_OFFSET)
#define TIVA_SYSCON_PPUART (TIVA_SYSCON_BASE + TIVA_SYSCON_PPUART_OFFSET)
#define TIVA_SYSCON_PPSSI (TIVA_SYSCON_BASE + TIVA_SYSCON_PPSSI_OFFSET)
#define TIVA_SYSCON_PPI2C (TIVA_SYSCON_BASE + TIVA_SYSCON_PPI2C_OFFSET)
#define TIVA_SYSCON_PPUSB (TIVA_SYSCON_BASE + TIVA_SYSCON_PPUSB_OFFSET)
#define TIVA_SYSCON_PPCAN (TIVA_SYSCON_BASE + TIVA_SYSCON_PPCAN_OFFSET)
#define TIVA_SYSCON_PPADC (TIVA_SYSCON_BASE + TIVA_SYSCON_PPADC_OFFSET)
#define TIVA_SYSCON_PPACMP (TIVA_SYSCON_BASE + TIVA_SYSCON_PPACMP_OFFSET)
#define TIVA_SYSCON_PPPWM (TIVA_SYSCON_BASE + TIVA_SYSCON_PPPWM_OFFSET)
#define TIVA_SYSCON_PPQEI (TIVA_SYSCON_BASE + TIVA_SYSCON_PPQEI_OFFSET)
#define TIVA_SYSCON_PPEEPROM (TIVA_SYSCON_BASE + TIVA_SYSCON_PPEEPROM_OFFSET)
#define TIVA_SYSCON_PPWTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_PPWTIMER_OFFSET)
#define TIVA_SYSCON_SRWD (TIVA_SYSCON_BASE + TIVA_SYSCON_SRWD_OFFSET)
#define TIVA_SYSCON_SRTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_SRTIMER_OFFSET)
#define TIVA_SYSCON_SRGPIO (TIVA_SYSCON_BASE + TIVA_SYSCON_SRGPIO_OFFSET)
#define TIVA_SYSCON_SRDMA (TIVA_SYSCON_BASE + TIVA_SYSCON_SRDMA_OFFSET)
#define TIVA_SYSCON_SRHIB (TIVA_SYSCON_BASE + TIVA_SYSCON_SRHIB_OFFSET)
#define TIVA_SYSCON_SRUART (TIVA_SYSCON_BASE + TIVA_SYSCON_SRUART_OFFSET)
#define TIVA_SYSCON_SRSSI (TIVA_SYSCON_BASE + TIVA_SYSCON_SRSSI_OFFSET)
#define TIVA_SYSCON_SRI2C (TIVA_SYSCON_BASE + TIVA_SYSCON_SRI2C_OFFSET)
#define TIVA_SYSCON_SRUSB (TIVA_SYSCON_BASE + TIVA_SYSCON_SRUSB_OFFSET)
#define TIVA_SYSCON_SRCAN (TIVA_SYSCON_BASE + TIVA_SYSCON_SRCAN_OFFSET)
#define TIVA_SYSCON_SRADC (TIVA_SYSCON_BASE + TIVA_SYSCON_SRADC_OFFSET)
#define TIVA_SYSCON_SRACMP (TIVA_SYSCON_BASE + TIVA_SYSCON_SRACMP_OFFSET)
#define TIVA_SYSCON_SREEPROM (TIVA_SYSCON_BASE + TIVA_SYSCON_SREEPROM_OFFSET)
#define TIVA_SYSCON_SRWTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_SRWTIMER_OFFSET)
#define TIVA_SYSCON_RCGCWD (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCWD_OFFSET)
#define TIVA_SYSCON_RCGCTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCTIMER_OFFSET)
#define TIVA_SYSCON_RCGCGPIO (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCGPIO_OFFSET)
#define TIVA_SYSCON_RCGCDMA (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCDMA_OFFSET)
#define TIVA_SYSCON_RCGCHIB (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCHIB_OFFSET)
#define TIVA_SYSCON_RCGCUART (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCUART_OFFSET)
#define TIVA_SYSCON_RCGCSSI (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCSSI_OFFSET)
#define TIVA_SYSCON_RCGCI2C (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCI2C_OFFSET)
#define TIVA_SYSCON_RCGCUSB (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCUSB_OFFSET)
#define TIVA_SYSCON_RCGCCAN (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCCAN_OFFSET)
#define TIVA_SYSCON_RCGCADC (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCADC_OFFSET)
#define TIVA_SYSCON_RCGCACMP (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCACMP_OFFSET)
#define TIVA_SYSCON_RCGCEEPROM (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCEEPROM_OFFSET)
#define TIVA_SYSCON_RCGCWTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGCWTIMER_OFFSET)
#define TIVA_SYSCON_SCGCWD (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCWD_OFFSET)
#define TIVA_SYSCON_SCGCTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCTIMER_OFFSET)
#define TIVA_SYSCON_SCGCGPIO (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCGPIO_OFFSET)
#define TIVA_SYSCON_SCGCDMA (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCDMA_OFFSET)
#define TIVA_SYSCON_SCGCHIB (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCHIB_OFFSET)
#define TIVA_SYSCON_SCGCUART (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCUART_OFFSET)
#define TIVA_SYSCON_SCGCSSI (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCSSI_OFFSET)
#define TIVA_SYSCON_SCGCI2C (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCI2C_OFFSET)
#define TIVA_SYSCON_SCGCUSB (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCUSB_OFFSET)
#define TIVA_SYSCON_SCGCCAN (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCCAN_OFFSET)
#define TIVA_SYSCON_SCGCADC (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCADC_OFFSET)
#define TIVA_SYSCON_SCGCACMP (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCACMP_OFFSET)
#define TIVA_SYSCON_SCGCEEPROM (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCEEPROM_OFFSET)
#define TIVA_SYSCON_SCGCWTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGCWTIMER_OFFSET)
#define TIVA_SYSCON_DCGCWD (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCWD_OFFSET)
#define TIVA_SYSCON_DCGCTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCTIMER_OFFSET)
#define TIVA_SYSCON_DCGCGPIO (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCGPIO_OFFSET)
#define TIVA_SYSCON_DCGCDMA (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCDMA_OFFSET)
#define TIVA_SYSCON_DCGCHIB (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCHIB_OFFSET)
#define TIVA_SYSCON_DCGCUART (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCUART_OFFSET)
#define TIVA_SYSCON_DCGCSSI (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCSSI_OFFSET)
#define TIVA_SYSCON_DCGCI2C (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCI2C_OFFSET)
#define TIVA_SYSCON_DCGCUSB (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCUSB_OFFSET)
#define TIVA_SYSCON_DCGCCAN (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCCAN_OFFSET)
#define TIVA_SYSCON_DCGCADC (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCADC_OFFSET)
#define TIVA_SYSCON_DCGCACMP (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCACMP_OFFSET)
#define TIVA_SYSCON_DCGCEEPROM (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCEEPROM_OFFSET)
#define TIVA_SYSCON_DCGCWTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGCWTIMER_OFFSET)
#define TIVA_SYSCON_PRWD (TIVA_SYSCON_BASE + TIVA_SYSCON_PRWD_OFFSET)
#define TIVA_SYSCON_PRTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_PRTIMER_OFFSET)
#define TIVA_SYSCON_PRGPIO (TIVA_SYSCON_BASE + TIVA_SYSCON_PRGPIO_OFFSET)
#define TIVA_SYSCON_PRDMA (TIVA_SYSCON_BASE + TIVA_SYSCON_PRDMA_OFFSET)
#define TIVA_SYSCON_PRHIB (TIVA_SYSCON_BASE + TIVA_SYSCON_PRHIB_OFFSET)
#define TIVA_SYSCON_PRUART (TIVA_SYSCON_BASE + TIVA_SYSCON_PRUART_OFFSET)
#define TIVA_SYSCON_PRSSI (TIVA_SYSCON_BASE + TIVA_SYSCON_PRSSI_OFFSET)
#define TIVA_SYSCON_PRI2C (TIVA_SYSCON_BASE + TIVA_SYSCON_PRI2C_OFFSET)
#define TIVA_SYSCON_PRUSB (TIVA_SYSCON_BASE + TIVA_SYSCON_PRUSB_OFFSET)
#define TIVA_SYSCON_PRCAN (TIVA_SYSCON_BASE + TIVA_SYSCON_PRCAN_OFFSET)
#define TIVA_SYSCON_PRADC (TIVA_SYSCON_BASE + TIVA_SYSCON_PRADC_OFFSET)
#define TIVA_SYSCON_PRACMP (TIVA_SYSCON_BASE + TIVA_SYSCON_PRACMP_OFFSET)
#define TIVA_SYSCON_PREEPROM (TIVA_SYSCON_BASE + TIVA_SYSCON_PREEPROM_OFFSET)
#define TIVA_SYSCON_PRWTIMER (TIVA_SYSCON_BASE + TIVA_SYSCON_PRWTIMER_OFFSET)
/* System Control Legacy Register Addresses *************************************************/
#define TIVA_SYSCON_DC0 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC0_OFFSET)
#define TIVA_SYSCON_DC1 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC1_OFFSET)
#define TIVA_SYSCON_DC2 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC2_OFFSET)
#define TIVA_SYSCON_DC3 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC3_OFFSET)
#define TIVA_SYSCON_DC4 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC4_OFFSET)
#define TIVA_SYSCON_DC5 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC5_OFFSET)
#define TIVA_SYSCON_DC6 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC6_OFFSET)
#define TIVA_SYSCON_DC7 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC7_OFFSET)
#define TIVA_SYSCON_DC8 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC8_OFFSET)
#define TIVA_SYSCON_SRCR0 (TIVA_SYSCON_BASE + TIVA_SYSCON_SRCR0_OFFSET)
#define TIVA_SYSCON_SRCR1 (TIVA_SYSCON_BASE + TIVA_SYSCON_SRCR1_OFFSET)
#define TIVA_SYSCON_SRCR2 (TIVA_SYSCON_BASE + TIVA_SYSCON_SRCR2_OFFSET)
#define TIVA_SYSCON_RCGC0 (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGC0_OFFSET)
#define TIVA_SYSCON_RCGC1 (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGC1_OFFSET)
#define TIVA_SYSCON_RCGC2 (TIVA_SYSCON_BASE + TIVA_SYSCON_RCGC2_OFFSET)
#define TIVA_SYSCON_SCGC0 (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGC0_OFFSET)
#define TIVA_SYSCON_SCGC1 (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGC1_OFFSET)
#define TIVA_SYSCON_SCGC2 (TIVA_SYSCON_BASE + TIVA_SYSCON_SCGC2_OFFSET)
#define TIVA_SYSCON_DCGC0 (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGC0_OFFSET)
#define TIVA_SYSCON_DCGC1 (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGC1_OFFSET)
#define TIVA_SYSCON_DCGC2 (TIVA_SYSCON_BASE + TIVA_SYSCON_DCGC2_OFFSET)
#define TIVA_SYSCON_DC9 (TIVA_SYSCON_BASE + TIVA_SYSCON_DC9_OFFSET)
#define TIVA_SYSCON_NVMSTAT (TIVA_SYSCON_BASE + TIVA_SYSCON_NVMSTAT_OFFSET)
/* System Control Register Bit Definitions **************************************************/
/* Device Identification 0 */
#define SYSCON_DID0_MINOR_SHIFT 0 /* Bits 7-0: Minor Revision of the device */
#define SYSCON_DID0_MINOR_MASK (0xff << SYSCON_DID0_MINOR_SHIFT)
#define SYSCON_DID0_MAJOR_SHIFT 8 /* Bits 15-8: Major Revision of the device */
#define SYSCON_DID0_MAJOR_MASK (0xff << SYSCON_DID0_MAJOR_SHIFT)
#define SYSCON_DID0_CLASS_SHIFT 16 /* Bits 23-16: Device Class */
#define SYSCON_DID0_CLASS_MASK (0xff << SYSCON_DID0_CLASS_SHIFT)
#define SYSCON_DID0_VER_SHIFT 28 /* Bits 30-28: DID0 Version */
#define SYSCON_DID0_VER_MASK (7 << SYSCON_DID0_VER_SHIFT)
/* Device Identification 1 */
#define SYSCON_DID1_QUAL_SHIFT 0 /* Bits 1-0: Qualification Status */
#define SYSCON_DID1_QUAL_MASK (0x03 << SYSCON_DID1_QUAL_SHIFT)
#define SYSCON_DID1_ROHS (1 << 2) /* Bit 2: RoHS-Compliance */
#define SYSCON_DID1_PKG_SHIFT 3 /* Bits 4-3: Package Type */
#define SYSCON_DID1_PKG_MASK (0x03 << SYSCON_DID1_PKG_SHIFT)
#define SYSCON_DID1_TEMP_SHIFT 5 /* Bits 7-5: Temperature Range */
#define SYSCON_DID1_TEMP_MASK (0x07 << SYSCON_DID1_TEMP_SHIFT)
#define SYSCON_DID1_PINCOUNT_SHIFT 13 /* Bits 15-13: Package Pin Count */
#define SYSCON_DID1_PINCOUNT_MASK (0x07 << SYSCON_DID1_PINCOUNT_SHIFT)
#define SYSCON_DID1_PARTNO_SHIFT 16 /* Bits 23-16: Part Number */
#define SYSCON_DID1_PARTNO_MASK (0xff << SYSCON_DID1_PARTNO_SHIFT)
#define SYSCON_DID1_FAM_SHIFT 24 /* Bits 27-24: Family */
#define SYSCON_DID1_FAM_MASK (0x0f << SYSCON_DID1_FAM_SHIFT)
#define SYSCON_DID1_VER_SHIFT 28 /* Bits 31-28: DID1 Version */
#define SYSCON_DID1_VER_MASK (0x0f << SYSCON_DID1_VER_SHIFT)
/* Brown-Out Reset Control */
#define SYSCON_PBORCTL_BORI1 (1 << 1) /* Bit 1: VDD under BOR1 Event Action */
#define SYSCON_PBORCTL_BORI0 (1 << 2) /* Bit 2: VDD under BOR0 Event Action */
/* Raw Interrupt Status */
#define SYSCON_RIS_BORR1RIS (1 << 1) /* Bit 1: VDD under BOR1 Raw Interrupt Status */
#define SYSCON_RIS_MOFRIS (1 << 3) /* Bit 3: Main Oscillator Failure Raw Interrupt Status */
#define SYSCON_RIS_PLLLRIS (1 << 6) /* Bit 6: PLL Lock Raw Interrupt Status */
#define SYSCON_RIS_USBPLLLRIS (1 << 7) /* Bit 7: USB PLL Lock Raw Interrupt Status */
#define SYSCON_RIS_MOSCPUPRIS (1 << 8) /* Bit 8: MOSC Power Up Raw Interrupt Status */
#define SYSCON_RIS_VDDARIS (1 << 10) /* Bit 10: VDDA Power OK Event Raw Interrupt Status */
#define SYSCON_RIS_BOR0RIS (1 << 11) /* Bit 11: VDD under BOR0 Raw Interrupt Status */
/* Interrupt Mask Control */
#define SYSCON_IMC_BORR1RIM (1 << 1) /* Bit 1: VDD under BOR1 Raw Interrupt Mask */
#define SYSCON_IMC_MOFRIM (1 << 3) /* Bit 3: Main Oscillator Failure Raw Interrupt Mask */
#define SYSCON_IMC_PLLLRIM (1 << 6) /* Bit 6: PLL Lock Raw Interrupt Mask */
#define SYSCON_IMC_USBPLLLRIM (1 << 7) /* Bit 7: USB PLL Lock Raw Interrupt Mask */
#define SYSCON_IMC_MOSCPUPRIM (1 << 8) /* Bit 8: MOSC Power Up Raw Interrupt Mask */
#define SYSCON_IMC_VDDARIM (1 << 10) /* Bit 10: VDDA Power OK Event Raw Interrupt Mask */
#define SYSCON_IMC_BOR0RIM (1 << 11) /* Bit 11: VDD under BOR0 Raw Interrupt Mask */
/* Masked Interrupt Status and Clear */
#define SYSCON_MISC_BORR1MIS (1 << 1) /* Bit 1: VDD under BOR1 Masked Interrupt Status */
#define SYSCON_MISC_MOFMIS (1 << 3) /* Bit 3: Main Oscillator Failure Masked Interrupt Status */
#define SYSCON_MISC_PLLLMIS (1 << 6) /* Bit 6: PLL Lock Masked Interrupt Status */
#define SYSCON_MISC_USBPLLLMIS (1 << 7) /* Bit 7: USB PLL Lock Masked Interrupt Status */
#define SYSCON_MISC_MOSCPUPMIS (1 << 8) /* Bit 8: MOSC Power Up Masked Interrupt Status */
#define SYSCON_MISC_VDDAMIS (1 << 10) /* Bit 10: VDDA Power OK Event Masked Interrupt Status */
#define SYSCON_MISC_BOR0MIS (1 << 11) /* Bit 11: VDD under BOR0 Masked Interrupt Status */
/* Reset Cause */
#define SYSCON_RESC_EXT (1 << 0) /* Bit 0: External Reset */
#define SYSCON_RESC_POR (1 << 1) /* Bit 1: Power-On Reset */
#define SYSCON_RESC_BOR (1 << 2) /* Bit 2: Brown-Out Reset */
#define SYSCON_RESC_WDT0 (1 << 3) /* Bit 3: Watchdog Timer 0 Reset */
#define SYSCON_RESC_SW (1 << 4) /* Bit 4: Software Reset */
#define SYSCON_RESC_WDT1 (1 << 5) /* Bit 5: Watchdog Timer 1 Reset */
#define SYSCON_RESC_MOSCFAIL (1 << 16) /* Bit 16: MOSC Failure Reset */
/* Run-Mode Clock Configuration */
#define SYSCON_RCC_MOSCDIS (1 << 0) /* Bit 0: Main Oscillator Disable */
#define SYSCON_RCC_OSCSRC_SHIFT 4 /* Bits 5-4: Oscillator Source */
#define SYSCON_RCC_OSCSRC_MASK (0x03 << SYSCON_RCC_OSCSRC_SHIFT)
#define SYSCON_RCC_OSCSRC_MOSC (0 << SYSCON_RCC_OSCSRC_SHIFT) /* Main oscillator */
#define SYSCON_RCC_OSCSRC_PIOSC (1 << SYSCON_RCC_OSCSRC_SHIFT) /* Precision internal oscillator (reset) */
#define SYSCON_RCC_OSCSRC_PIOSC4 (2 << SYSCON_RCC_OSCSRC_SHIFT) /* Precision internal oscillator / 4 */
#define SYSCON_RCC_OSCSRC_LFIOSC (3 << SYSCON_RCC_OSCSRC_SHIFT) /* Low-frequency internal oscillator */
#define SYSCON_RCC_XTAL_SHIFT 6 /* Bits 10-6: Crystal Value */
#define SYSCON_RCC_XTAL_MASK (31 << SYSCON_RCC_XTAL_SHIFT)
#define SYSCON_RCC_XTAL4000KHZ (6 << SYSCON_RCC_XTAL_SHIFT) /* 4 MHz (NO PLL) */
#define SYSCON_RCC_XTAL4096KHZ (7 << SYSCON_RCC_XTAL_SHIFT) /* 4.096 MHz (NO PLL) */
#define SYSCON_RCC_XTAL4915p2KHZ (8 << SYSCON_RCC_XTAL_SHIFT) /* 4.9152 MHz (NO PLL) */
#define SYSCON_RCC_XTAL5000KHZ (9 << SYSCON_RCC_XTAL_SHIFT) /* 5 MHz (USB) */
#define SYSCON_RCC_XTAL5120KHZ (10 << SYSCON_RCC_XTAL_SHIFT) /* 5.12 MHz */
#define SYSCON_RCC_XTAL6000KHZ (11 << SYSCON_RCC_XTAL_SHIFT) /* 6 MHz (USB) */
#define SYSCON_RCC_XTAL6144KHZ (12 << SYSCON_RCC_XTAL_SHIFT) /* 6.144 MHz */
#define SYSCON_RCC_XTAL7372p8KHZ (13 << SYSCON_RCC_XTAL_SHIFT) /* 7.3728 MHz */
#define SYSCON_RCC_XTAL8000KHZ (14 << SYSCON_RCC_XTAL_SHIFT) /* 8 MHz (USB) */
#define SYSCON_RCC_XTAL8192KHZ (15 << SYSCON_RCC_XTAL_SHIFT) /* 8.192 MHz */
#define SYSCON_RCC_XTAL10000KHZ (16 << SYSCON_RCC_XTAL_SHIFT) /* 10.0 MHz (USB) */
#define SYSCON_RCC_XTAL12000KHZ (17 << SYSCON_RCC_XTAL_SHIFT) /* 12.0 MHz (USB) */
#define SYSCON_RCC_XTAL12288KHZ (18 << SYSCON_RCC_XTAL_SHIFT) /* 12.288 MHz */
#define SYSCON_RCC_XTAL13560KHZ (19 << SYSCON_RCC_XTAL_SHIFT) /* 13.56 MHz */
#define SYSCON_RCC_XTAL14318p18KHZ (20 << SYSCON_RCC_XTAL_SHIFT) /* 14.31818 MHz */
#define SYSCON_RCC_XTAL16000KHZ (21 << SYSCON_RCC_XTAL_SHIFT) /* 16.0 MHz (USB) */
#define SYSCON_RCC_XTAL16384KHZ (22 << SYSCON_RCC_XTAL_SHIFT) /* 16.384 MHz */
#define SYSCON_RCC_XTAL18000KHZ (23 << SYSCON_RCC_XTAL_SHIFT) /* 18.0 MHz (USB) */
#define SYSCON_RCC_XTAL20000KHZ (24 << SYSCON_RCC_XTAL_SHIFT) /* 20.0 MHz (USB) */
#define SYSCON_RCC_XTAL24000KHZ (25 << SYSCON_RCC_XTAL_SHIFT) /* 24.0 MHz (USB) */
#define SYSCON_RCC_XTAL25000KHZ (26 << SYSCON_RCC_XTAL_SHIFT) /* 25.0 MHz (USB) */
#define SYSCON_RCC_BYPASS (1 << 11) /* Bit 11: PLL Bypass */
#define SYSCON_RCC_PWRDN (1 << 13) /* Bit 13: PLL Power Down */
#define SYSCON_RCC_USESYSDIV (1 << 22) /* Bit 22: Enable System Clock Divider */
#define SYSCON_RCC_SYSDIV_SHIFT 23 /* Bits 26-23: System Clock Divisor */
#define SYSCON_RCC_SYSDIV_MASK (0x0f << SYSCON_RCC_SYSDIV_SHIFT)
#define SYSCON_RCC_SYSDIV(n) (((n)-1) << SYSCON_RCC_SYSDIV_SHIFT)
#define SYSCON_RCC_ACG (1 << 27) /* Bit 27: Auto Clock Gating */
/* GPIO High-Performance Bus Control */
#define SYSCON_GPIOHBCTL_PORTA (1 << 0) /* Bit 0: Port A Advanced High-Performance Bus */
#define SYSCON_GPIOHBCTL_PORTB (1 << 1) /* Bit 1: Port B Advanced High-Performance Bus */
#define SYSCON_GPIOHBCTL_PORTC (1 << 2) /* Bit 2: Port C Advanced High-Performance Bus */
#define SYSCON_GPIOHBCTL_PORTD (1 << 3) /* Bit 3: Port D Advanced High-Performance Bus */
#define SYSCON_GPIOHBCTL_PORTE (1 << 4) /* Bit 4: Port E Advanced High-Performance Bus */
#define SYSCON_GPIOHBCTL_PORTF (1 << 5) /* Bit 5: Port F Advanced High-Performance Bus */
/* Run-Mode Clock Configuration 2 */
#define SYSCON_RCC2_OSCSRC2_SHIFT 4 /* Bits 6-4: Oscillator Source */
#define SYSCON_RCC2_OSCSRC2_MASK (7 << SYSCON_RCC2_OSCSRC2_SHIFT)
#define SYSCON_RCC2_OSCSRC2_MOSC (0 << SYSCON_RCC2_OSCSRC2_SHIFT) /* Main oscillator */
#define SYSCON_RCC2_OSCSRC2_PIOSC (1 << SYSCON_RCC2_OSCSRC2_SHIFT) /* Precision internal oscillator (reset) */
#define SYSCON_RCC2_OSCSRC2_PIOSC4 (2 << SYSCON_RCC2_OSCSRC2_SHIFT) /* Precision internal oscillator / 4 */
#define SYSCON_RCC2_OSCSRC2_LFIOSC (4 << SYSCON_RCC2_OSCSRC2_SHIFT) /* Low-frequency internal oscillator */
#define SYSCON_RCC2_OSCSRC2_32768HZ (7 << SYSCON_RCC2_OSCSRC2_SHIFT) /* 32.768KHz external oscillator */
#define SYSCON_RCC2_BYPASS2 (1 << 11) /* Bit 11: Bypass PLL */
#define SYSCON_RCC2_PWRDN2 (1 << 13) /* Bit 13: Power-Down PLL */
#define SYSCON_RCC2_USBPWRDN (1 << 14) /* Bit 14: Power-Down USB PLL */
#define SYSCON_RCC2_SYSDIV2LSB (1 << 22) /* Bit 22: Additional LSB for SYSDIV2 */
#define SYSCON_RCC2_SYSDIV2_SHIFT 23 /* Bits 28-23: System Clock Divisor */
#define SYSCON_RCC2_SYSDIV2_MASK (0x3f << SYSCON_RCC2_SYSDIV2_SHIFT)
#define SYSCON_RCC2_SYSDIV(n) ((n-1) << SYSCON_RCC2_SYSDIV2_SHIFT)
#define SYSCON_RCC2_SYSDIV_DIV400(n) (((n-1) >> 1) << SYSCON_RCC2_SYSDIV2_SHIFT)
#define SYSCON_RCC2_DIV400 (1 << 30) /* Bit 30: Divide PLL as 400 MHz vs. 200 MHz */
#define SYSCON_RCC2_USERCC2 (1 << 31) /* Bit 31: Use RCC2 When set */
/* Main Oscillator Control */
#define SYSCON_MOSCCTL_CVAL (1 << 0) /* Bit 0: Clock Validation for MOSC */
#define SYSCON_MOSCCTL_MOSCIM (1 << 1) /* Bit 1: MOSC Failure Action */
#define SYSCON_MOSCCTL_NOXTAL (1 << 2) /* Bit 2: No Crystal Connected */
/* Deep Sleep Clock Configuration */
#define SYSCON_DSLPCLKCFG_DSOSCSRC_SHIFT 4 /* Bits 6-4: Clock Source */
#define SYSCON_DSLPCLKCFG_DSOSCSRC_MASK (7 << SYSCON_DSLPCLKCFG_DSOSCSRC_SHIFT)
#define SYSCON_DSLPCLKCFG_DSOSCSRC_MOSC (0 << SYSCON_DSLPCLKCFG_DSOSCSRC_SHIFT) /* Main oscillator */
#define SYSCON_DSLPCLKCFG_DSOSCSRC_PIOSC (1 << SYSCON_DSLPCLKCFG_DSOSCSRC_SHIFT) /* Precision internal oscillator (reset) */
#define SYSCON_DSLPCLKCFG_DSOSCSRC_PIOSC4 (2 << SYSCON_DSLPCLKCFG_DSOSCSRC_SHIFT) /* Precision internal oscillator / 4 */
#define SYSCON_DSLPCLKCFG_DSOSCSRC_LFIOSC (4 << SYSCON_DSLPCLKCFG_DSOSCSRC_SHIFT) /* Low-frequency internal oscillator */
#define SYSCON_DSLPCLKCFG_DSOSCSRC_32768KHZ (7 << SYSCON_DSLPCLKCFG_DSOSCSRC_SHIFT) /* 32.768KHz external oscillator */
#define SYSCON_DSLPCLKCFG_DSDIVORIDE_SHIFT 23 /* Bits 28-23: Divider Field Override */
#define SYSCON_DSLPCLKCFG_DSDIVORIDE_MASK (0x3f << SYSCON_DSLPCLKCFG_DSDIVORIDE_SHIFT)
#define SYSCON_DSLPCLKCFG_DSDIVORIDE(b) (((n)-1) << SYSCON_DSLPCLKCFG_DSDIVORIDE_SHIFT)
/* System Properties */
#define SYSCON_SYSPROP_FPU (1 << 0) /* Bit 0: FPU Present */
/* Precision Internal Oscillator Calibration */
#define SYSCON_PIOSCCAL_UT_SHIFT (0) /* Bits 0-6: User Trim Value */
#define SYSCON_PIOSCCAL_UT_MASK (0x7f << SYSCON_PIOSCCAL_UT_SHIFT)
#define SYSCON_PIOSCCAL_UPDATE (1 << 8) /* Bit 8: Update Trim */
#define SYSCON_PIOSCCAL_CAL (1 << 9) /* Bit 9: Start Calibration */
#define SYSCON_PIOSCCAL_UTEN (1 << 31) /* Bit 31: Use User Trim Value */
/* Precision Internal Oscillator Statistics */
#define SYSCON_PIOSCSTAT_CT_SHIFT (0) /* Bits 0-6: Calibration Trim Value */
#define SYSCON_PIOSCSTAT_CT_MASK (0x7f << SYSCON_PIOSCSTAT_CT_SHIFT)
#define SYSCON_PIOSCSTAT_RESULT_SHIFT (8) /* Bits 8-9: Calibration Result */
#define SYSCON_PIOSCSTAT_RESULT_MASK (3 << SYSCON_PIOSCSTAT_RESULT_SHIFT)
#define SYSCON_PIOSCSTAT_DT_SHIFT (16) /* Bits 16-22: Default Trim Value */
#define SYSCON_PIOSCSTAT_DT_MASK (0x7f << SYSCON_PIOSCSTAT_DT_SHIFT)
/* PLL0 Frequency */
#define SYSCON_PLLFREQ0_MINT_SHIFT (0) /* Bits 0-9: PLL M Integer Value */
#define SYSCON_PLLFREQ0_MINT_MASK (0x3ff << SYSCON_PLLFREQ0_MINT_SHIFT)
#define SYSCON_PLLFREQ0_MFRAC_SHIFT (10) /* Bits 10-19: PLL M Fractional Value */
#define SYSCON_PLLFREQ0_MFRAC_MASK (0x3ff << SYSCON_PLLFREQ0_MFRAC_SHIFT)
/* PLL1 Frequency */
#define SYSCON_PLLFREQ1_N_SHIFT (0) /* Bits 0-4: PLL N Value */
#define SYSCON_PLLFREQ1_N_MASK (31 << SYSCON_PLLFREQ1_N_SHIFT)
#define SYSCON_PLLFREQ1_Q_SHIFT (8) /* Bits 8-12: PLL Q Value */
#define SYSCON_PLLFREQ1_Q_MASK (31 << SYSCON_PLLFREQ1_Q_SHIFT)
/* PLL Status */
#define SYSCON_PLLSTAT_LOCK (1 << 0) /* Bit 0: PLL Lock */
/* Watchdog Timer Peripheral Present */
#define SYSCON_PPWD(n) (1 << (n)) /* Bit n: WDTn present */
#define SYSCON_PPWD_P0 (1 << 0) /* Bit 0: WDT0 present */
#define SYSCON_PPWD_P1 (1 << 1) /* Bit 1: WDT1 present */
/* 16/32-Bit Timer Peripheral Present */
#define SYSCON_PPTIMER(n) (1 << (n)) /* Bit n: 16/32-Bit General-Purpose Timer n Present */
#define SYSCON_PPTIMER_P0 (1 << 0) /* Bit 0: 16/32-Bit General-Purpose Timer 0 Present */
#define SYSCON_PPTIMER_P1 (1 << 1) /* Bit 1: 16/32-Bit General-Purpose Timer 0 Present */
#define SYSCON_PPTIMER_P2 (1 << 2) /* Bit 2: 16/32-Bit General-Purpose Timer 0 Present */
#define SYSCON_PPTIMER_P3 (1 << 3) /* Bit 3: 16/32-Bit General-Purpose Timer 0 Present */
#define SYSCON_PPTIMER_P4 (1 << 4) /* Bit 4: 16/32-Bit General-Purpose Timer 0 Present */
#define SYSCON_PPTIMER_P5 (1 << 5) /* Bit 5: 16/32-Bit General-Purpose Timer 0 Present */
/* GPIO Peripheral Present */
#define SYSCON_PPGPIO(n) (1 << (n)) /* Bit n: GPIO Port n Present */
#define SYSCON_PPGPIO_P0 (1 << 0) /* Bit 0: GPIO Port A Present */
#define SYSCON_PPGPIO_P1 (1 << 1) /* Bit 1: GPIO Port B Present */
#define SYSCON_PPGPIO_P2 (1 << 2) /* Bit 2: GPIO Port C Present */
#define SYSCON_PPGPIO_P3 (1 << 3) /* Bit 3: GPIO Port D Present */
#define SYSCON_PPGPIO_P4 (1 << 4) /* Bit 4: GPIO Port E Present */
#define SYSCON_PPGPIO_P5 (1 << 5) /* Bit 5: GPIO Port F Present */
#define SYSCON_PPGPIO_P6 (1 << 6) /* Bit 6: GPIO Port G Present */
#define SYSCON_PPGPIO_P7 (1 << 7) /* Bit 7: GPIO Port H Present */
#define SYSCON_PPGPIO_P8 (1 << 8) /* Bit 8: GPIO Port J Present */
#define SYSCON_PPGPIO_P9 (1 << 9) /* Bit 9: GPIO Port K Present */
#define SYSCON_PPGPIO_P10 (1 << 10) /* Bit 10: GPIO Port L Present */
#define SYSCON_PPGPIO_P11 (1 << 11) /* Bit 11: GPIO Port M Present */
#define SYSCON_PPGPIO_P12 (1 << 12) /* Bit 12: GPIO Port N Present */
#define SYSCON_PPGPIO_P13 (1 << 13) /* Bit 13: GPIO Port P Present */
#define SYSCON_PPGPIO_P14 (1 << 14) /* Bit 14: GPIO Port Q Present */
/* uDMA Peripheral Present */
#define SYSCON_PPDMA_P0 (1 << 0) /* Bit 0: μDMA Module Present */
/* Hibernation Peripheral Present */
#define SYSCON_PPHIB_P0 (1 << 0) /* Bit 0: Hibernation Module Present */
/* UART Present */
#define SYSCON_PPUART(n) (1 << (n)) /* Bit n: UART Module n Present */
#define SYSCON_PPUART_P0 (1 << 0) /* Bit 0: UART Module 0 Present */
#define SYSCON_PPUART_P1 (1 << 1) /* Bit 1: UART Module 1 Present */
#define SYSCON_PPUART_P2 (1 << 2) /* Bit 2: UART Module 2 Present */
#define SYSCON_PPUART_P3 (1 << 3) /* Bit 3: UART Module 3 Present */
#define SYSCON_PPUART_P4 (1 << 4) /* Bit 4: UART Module 4 Present */
#define SYSCON_PPUART_P5 (1 << 5) /* Bit 5: UART Module 5 Present */
#define SYSCON_PPUART_P6 (1 << 6) /* Bit 6: UART Module 6 Present */
#define SYSCON_PPUART_P7 (1 << 7) /* Bit 7: UART Module 7 Present */
/* SSI Peripheral Present */
#define SYSCON_PPSSI(n) (1 << (n)) /* Bit n: SSI Module n Present */
#define SYSCON_PPSSI_P0 (1 << 0) /* Bit 0: SSI Module 0 Present */
#define SYSCON_PPSSI_P1 (1 << 1) /* Bit 1: SSI Module 1 Present */
#define SYSCON_PPSSI_P2 (1 << 2) /* Bit 2: SSI Module 2 Present */
#define SYSCON_PPSSI_P3 (1 << 3) /* Bit 3: SSI Module 3 Present */
/* I2C Peripheral Present */
#define SYSCON_PPI2C(n) (1 << (n)) /* Bit n: I2C Module n Present */
#define SYSCON_PPI2C_P0 (1 << 0) /* Bit 0: I2C Module 0 Present */
#define SYSCON_PPI2C_P1 (1 << 1) /* Bit 1: I2C Module 1 Present */
#define SYSCON_PPI2C_P2 (1 << 2) /* Bit 2: I2C Module 2 Present */
#define SYSCON_PPI2C_P3 (1 << 3) /* Bit 3: I2C Module 3 Present */
#define SYSCON_PPI2C_P4 (1 << 4) /* Bit 4: I2C Module 4 Present */
#define SYSCON_PPI2C_P5 (1 << 5) /* Bit 5: I2C Module 5 Present */
/* USB Peripheral Present */
#define SYSCON_PPUSB_P0 (1 << 0) /* USB Module Present */
/* CAN Peripheral Present */
#define SYSCON_PPCAN(n) (1 << (n)) /* Bit n: CAN Module n Present */
#define SYSCON_PPCAN_P0 (1 << 0) /* Bit 0: CAN Module 0 Present */
#define SYSCON_PPCAN_P1 (1 << 1) /* Bit 1: CAN Module 1 Present */
/* ADC Peripheral Present */
#define SYSCON_PPADC(n) (1 << (n)) /* Bit n: ADC Module n Present */
#define SYSCON_PPADC_P0 (1 << 0) /* Bit 0: ADC Module 0 Present */
#define SYSCON_PPADC_P1 (1 << 1) /* Bit 1: ADC Module 1 Present */
/* Analog Comparator Peripheral Present */
#define SYSCON_PPACMP_P0 (1 << 0) /* Bit 0: Analog Comparator Module Present */
/* Pulse Width Modulator Peripheral Present */
#define SYSCON_PPWM(n) (1 << (n)) /* Bit n: PWM Module n Present */
#define SYSCON_PPWM_P0 (1 << 0) /* Bit 0: PWM Module 0 Present */
#define SYSCON_PPWM_P1 (1 << 1) /* Bit 1: PWM Module 1 Present */
/* Quadrature Encoder Peripheral Present */
#define SYSCON_PPQEI(n) (1 << (n)) /* Bit n: QEI Module n Present */
#define SYSCON_PPQEI_P0 (1 << 0) /* Bit 0: QEI Module 0 Present */
#define SYSCON_PPUART_P1 (1 << 1) /* Bit 1: QEI Module 1 Present */
/* EEPROM Peripheral Present */
#define SYSCON_PPEEPROM_P0 (1 << 0) /* Bit 0: EEPROM Module Present */
/* 32/64-Bit Wide Timer Peripheral Present */
#define SYSCON_PPWTIMER(n) (1 << (n)) /* Bit n: 32/64-Bit Wide General-Purpose Timer n Present */
#define SYSCON_PPWTIMER_P0 (1 << 0) /* Bit 0: 32/64-Bit Wide General-Purpose Timer 0 Present */
#define SYSCON_PPWTIMER_P1 (1 << 1) /* Bit 1: 32/64-Bit Wide General-Purpose Timer 1 Present */
#define SYSCON_PPWTIMER_P2 (1 << 2) /* Bit 2: 32/64-Bit Wide General-Purpose Timer 2 Present */
#define SYSCON_PPWTIMER_P3 (1 << 3) /* Bit 3: 32/64-Bit Wide General-Purpose Timer 3 Present */
#define SYSCON_PPWTIMER_P4 (1 << 4) /* Bit 4: 32/64-Bit Wide General-Purpose Timer 4 Present */
#define SYSCON_PPWTIMER_P5 (1 << 5) /* Bit 5: 32/64-Bit Wide General-Purpose Timer 5 Present */
/* Watchdog Timer Software Reset */
#define SYSCON_SPWD(n) (1 << (n)) /* Bit n: Watchdog Timer n Software Reset */
#define SYSCON_SPWD_R0 (1 << 0) /* Bit 0: Watchdog Timer 0 Software Reset */
#define SYSCON_SPWD_R1 (1 << 1) /* Bit 1: Watchdog Timer 1 Software Reset */
/* 16/32-Bit Timer Software Reset */
#define SYSCON_SRTIMER(n) (1 << (n)) /* Bit n: 16/32-Bit General-Purpose Timer n Software Reset */
#define SYSCON_SRTIMER_R0 (1 << 0) /* Bit 0: 16/32-Bit General-Purpose Timer 0 Software Reset */
#define SYSCON_SRTIMER_R1 (1 << 1) /* Bit 1: 16/32-Bit General-Purpose Timer 1 Software Reset */
#define SYSCON_SRTIMER_R2 (1 << 2) /* Bit 2: 16/32-Bit General-Purpose Timer 2 Software Reset */
#define SYSCON_SRTIMER_R3 (1 << 3) /* Bit 3: 16/32-Bit General-Purpose Timer 3 Software Reset */
#define SYSCON_SRTIMER_R4 (1 << 4) /* Bit 4: 16/32-Bit General-Purpose Timer 4 Software Reset */
#define SYSCON_SRTIMER_R5 (1 << 5) /* Bit 5: 16/32-Bit General-Purpose Timer 5 Software Reset */
/* GPIO Software Reset */
#define SYSCON_SRGPIO(n) (1 << (n)) /* Bit n: GPIO Port n Software Reset */
#define SYSCON_SRGPIO_R0 (1 << 0) /* Bit 0: GPIO Port A Software Reset */
#define SYSCON_SRGPIO_R1 (1 << 1) /* Bit 1: GPIO Port B Software Reset */
#define SYSCON_SRGPIO_R2 (1 << 2) /* Bit 2: GPIO Port C Software Reset */
#define SYSCON_SRGPIO_R3 (1 << 3) /* Bit 3: GPIO Port D Software Reset */
#define SYSCON_SRGPIO_R4 (1 << 4) /* Bit 4: GPIO Port E Software Reset */
#define SYSCON_SRPGIO_R5 (1 << 5) /* Bit 5: GPIO Port F Software Reset */
/* uDMA Software Reset */
#define SYSCON_SRDMA_R0 (1 << 0) /* Bit 0: μDMA Module Software Reset */
/* Hibernation Software Reset */
#define SYSCON_SRHIB_R0 (1 << 0) /* Bit 0: Hibernation Module Software Reset */
/* UART Software Reset*/
#define SYSCON_SRUARTR(n) (1 << (n)) /* Bit n: UART Module n Software Reset */
#define SYSCON_SRUARTR_R0 (1 << 0) /* Bit 0: UART Module 0 Software Reset */
#define SYSCON_SRUARTR_R1 (1 << 1) /* Bit 1: UART Module 1 Software Reset */
#define SYSCON_SRUARTR_R2 (1 << 2) /* Bit 2: UART Module 2 Software Reset */
#define SYSCON_SRUARTR_R3 (1 << 3) /* Bit 3: UART Module 3 Software Reset */
#define SYSCON_SRUARTR_R4 (1 << 4) /* Bit 4: UART Module 4 Software Reset */
#define SYSCON_SRUARTR_R5 (1 << 5) /* Bit 5: UART Module 5 Software Reset */
#define SYSCON_SRUARTR_R6 (1 << 6) /* Bit 6: UART Module 6 Software Reset */
#define SYSCON_SRUARTR_R7 (1 << 7) /* Bit 7: UART Module 7 Software Reset */
/* SSI Software Reset */
#define SYSCON_SRSSI(n) (1 << (n)) /* Bit n: SSI Module n Software Reset */
#define SYSCON_SRSSI_R0 (1 << 0) /* Bit 0: SSI Module 0 Software Reset */
#define SYSCON_SRSSI_R1 (1 << 1) /* Bit 1: SSI Module 1 Software Reset */
#define SYSCON_SRSSI_R2 (1 << 2) /* Bit 2: SSI Module 2 Software Reset */
#define SYSCON_SRSSI_R3 (1 << 3) /* Bit 3: SSI Module 3 Software Reset */
/* I2C Software Reset */
#define SYSCON_SRI2C(n) (1 << (n)) /* Bit n: I2C Module n Software Reset */
#define SYSCON_SRI2C_R0 (1 << 0) /* Bit 0: I2C Module 0 Software Reset */
#define SYSCON_SRI2C_R1 (1 << 1) /* Bit 1: I2C Module 1 Software Reset */
#define SYSCON_SRI2C_R2 (1 << 2) /* Bit 2: I2C Module 2 Software Reset */
#define SYSCON_SRI2C_R3 (1 << 3) /* Bit 3: I2C Module 3 Software Reset */
/* USB Software Reset */
#define SYSCON_SRUSB_R0 (1 << 0) /* Bit 0: USB Module Software Reset */
/* CAN Software Reset */
#define SYSCON_SRCAN_R0 (1 << 0) /* Bit 0: CAN Module 0 Software Reset */
/* ADC Software Reset */
#define SYSCON_SRADC(n) (1 << (n)) /* Bit n: ADC Module n Software Reset */
#define SYSCON_SRADC_R0 (1 << 0) /* Bit 0: ADC Module 0 Software Reset */
#define SYSCON_SRADC_R1 (1 << 1) /* Bit 1: ADC Module 1 Software Reset */
/* Analog Comparator Software Reset */
#define SYSCON_SRACMP_R0 (1 << 0) /* Bit 0: Analog Comparator Module 0 Software Reset */
/* EEPROM Software Reset */
#define SYSCON_SREEPROM_R0 (1 << 0) /* Bit 0: EEPROM Module Software Reset */
/* 32/64-Bit Wide Timer Software Reset */
#define SYSCON_SRWTIMER(n) (1 << (n)) /* Bit n: 32/64-Bit Wide General-Purpose Timer n Software Reset */
#define SYSCON_SRWTIMER_R0 (1 << 0) /* Bit 0: 32/64-Bit Wide General-Purpose Timer 0 Software Reset */
#define SYSCON_SRWTIMER_R1 (1 << 1) /* Bit 1: 32/64-Bit Wide General-Purpose Timer 1 Software Reset */
#define SYSCON_SRWTIMER_R2 (1 << 2) /* Bit 2: 32/64-Bit Wide General-Purpose Timer 2 Software Reset */
#define SYSCON_SRWTIMER_R3 (1 << 3) /* Bit 3: 32/64-Bit Wide General-Purpose Timer 3 Software Reset */
#define SYSCON_SRWTIMER_R4 (1 << 4) /* Bit 4: 32/64-Bit Wide General-Purpose Timer 4 Software Reset */
#define SYSCON_SRWTIMER_R5 (1 << 5) /* Bit 5: 32/64-Bit Wide General-Purpose Timer 5 Software Reset */
#define SYSCON_SRWTIMER_R6 (1 << 6) /* Bit 6: 32/64-Bit Wide General-Purpose Timer 6 Software Reset */
/* Watchdog Timer Run Mode Clock Gating Control */
#define SYSCON_RCGCWD(n) (1 << (n)) /* Bit n: Watchdog Timer n Run Mode Clock Gating Control */
#define SYSCON_RCGCWD_R0 (1 << 0) /* Bit 0: Watchdog Timer 0 Run Mode Clock Gating Control */
#define SYSCON_RCGCWD_R1 (1 << 1) /* Bit 1: Watchdog Timer 1 Run Mode Clock Gating Control */
/* 16/32-Bit Timer Run Mode Clock Gating Control */
#define SYSCON_RCGCTIMER(n) (1 << (n)) /* Bit n: 16/32-Bit General-Purpose Timer n Run Mode Clock Gating Control */
#define SYSCON_RCGCTIMER_R0 (1 << 0) /* Bit 0: 16/32-Bit General-Purpose Timer 0 Run Mode Clock Gating Control */
#define SYSCON_RCGCTIMER_R1 (1 << 1) /* Bit 1: 16/32-Bit General-Purpose Timer 1 Run Mode Clock Gating Control */
#define SYSCON_RCGCTIMER_R2 (1 << 2) /* Bit 2: 16/32-Bit General-Purpose Timer 2 Run Mode Clock Gating Control */
#define SYSCON_RCGCTIMER_R3 (1 << 3) /* Bit 3: 16/32-Bit General-Purpose Timer 3 Run Mode Clock Gating Control */
#define SYSCON_RCGCTIMER_R4 (1 << 4) /* Bit 4: 16/32-Bit General-Purpose Timer 4 Run Mode Clock Gating Control */
#define SYSCON_RCGCTIMER_R5 (1 << 5) /* Bit 5: 16/32-Bit General-Purpose Timer 5 Run Mode Clock Gating Control */
/* GPIO Run Mode Clock Gating Control*/
#define SYSCON_RCGCGPIO(n) (1 << (n)) /* Bit n: 16/32-Bit GPIO Port n Run Mode Clock Gating Control */
#define SYSCON_RCGCGPIO_R0 (1 << 0) /* Bit 0: 16/32-Bit GPIO Port A Run Mode Clock Gating Control */
#define SYSCON_RCGCGPIO_R1 (1 << 1) /* Bit 1: 16/32-Bit GPIO Port B Run Mode Clock Gating Control */
#define SYSCON_RCGCGPIO_R2 (1 << 2) /* Bit 2: 16/32-Bit GPIO Port C Run Mode Clock Gating Control */
#define SYSCON_RCGCGPIO_R3 (1 << 3) /* Bit 3: 16/32-Bit GPIO Port D Run Mode Clock Gating Control */
#define SYSCON_RCGCGPIO_R4 (1 << 4) /* Bit 4: 16/32-Bit GPIO Port E Run Mode Clock Gating Control */
#define SYSCON_RCGCGPIO_R5 (1 << 5) /* Bit 5: 16/32-Bit GPIO Port F Run Mode Clock Gating Control */
/* uDMA Run Mode Clock Gating Control*/
#define SYSCON_RCGCDMA_R0 (1 << 0) /* Bit 0: μDMA Module Run Mode Clock Gating Control */
/* Hibernation Run Mode Clock Gating Control */
#define SYSCON_RCGCHIB_R0 (1 << 0) /* Bit 0: Hibernation Module Run Mode Clock Gating Control */
/* UART Run Mode Clock Gating Control*/
#define SYSCON_RCGCUART(n) (1 << (n)) /* Bit n: UART Module n Run Mode Clock Gating Control */
#define SYSCON_RCGCUART_R0 (1 << 0) /* Bit 0: UART Module 0 Run Mode Clock Gating Control */
#define SYSCON_RCGCUART_R1 (1 << 1) /* Bit 1: UART Module 1 Run Mode Clock Gating Control */
#define SYSCON_RCGCUART_R2 (1 << 2) /* Bit 2: UART Module 2 Run Mode Clock Gating Control */
#define SYSCON_RCGCUART_R3 (1 << 3) /* Bit 3: UART Module 3 Run Mode Clock Gating Control */
#define SYSCON_RCGCUART_R4 (1 << 4) /* Bit 4: UART Module 4 Run Mode Clock Gating Control */
#define SYSCON_RCGCUART_R5 (1 << 5) /* Bit 5: UART Module 5 Run Mode Clock Gating Control */
#define SYSCON_RCGCUART_R6 (1 << 6) /* Bit 6: UART Module 6 Run Mode Clock Gating Control */
#define SYSCON_RCGCUART_R7 (1 << 7) /* Bit 7: UART Module 7 Run Mode Clock Gating Control */
/* SSI Run Mode Clock Gating Control*/
#define SYSCON_RCGCSSI(n) (1 << (n)) /* Bit n: SSI Module n Run Mode Clock Gating Control */
#define SYSCON_RCGCSSI_R0 (1 << 0) /* Bit 0: SSI Module 0 Run Mode Clock Gating Control */
#define SYSCON_RCGCSSI_R1 (1 << 1) /* Bit 1: SSI Module 1 Run Mode Clock Gating Control */
#define SYSCON_RCGCSSI_R2 (1 << 2) /* Bit 2: SSI Module 2 Run Mode Clock Gating Control */
#define SYSCON_RCGCSSI_R3 (1 << 3) /* Bit 3: SSI Module 3 Run Mode Clock Gating Control */
/* I2C Run Mode Clock Gating Control */
#define SYSCON_RCGCI2C(n) (1 << (n)) /* Bit n: I2C Module n Run Mode Clock Gating Control */
#define SYSCON_RCGCI2C_R0 (1 << 0) /* Bit 0: I2C Module 0 Run Mode Clock Gating Control */
#define SYSCON_RCGCI2C_R1 (1 << 1) /* Bit 1: I2C Module 1 Run Mode Clock Gating Control */
#define SYSCON_RCGCI2C_R2 (1 << 2) /* Bit 2: I2C Module 2 Run Mode Clock Gating Control */
#define SYSCON_RCGCI2C_R3 (1 << 3) /* Bit 3: I2C Module 3 Run Mode Clock Gating Control */
/* USB Run Mode Clock Gating Control */
#define SYSCON_RCGCUSB_R0 (1 << 0) /* Bit 0: USB Module Run Mode Clock Gating Control */
/* CAN Run Mode Clock Gating Control */
#define SYSCON_RCGCCAN_R0 (1 << 0) /* Bit 0: CAN Module 0 Run Mode Clock Gating Control */
/* ADC Run Mode Clock Gating Control */
#define SYSCON_RCGCADC(n) (1 << (n)) /* Bit n: ADC Module n Run Mode Clock Gating Control */
#define SYSCON_RCGCADC_R0 (1 << 0) /* Bit 0: ADC Module 0 Run Mode Clock Gating Control */
#define SYSCON_RCGCADC_R1 (1 << 1) /* Bit 1: ADC Module 1 Run Mode Clock Gating Control */
/* Analog Comparator Run Mode Clock Gating Control */
#define SYSCON_RCGCACMP_R0 (1 << 0) /* Bit 0: Analog Comparator Module 0 Run Mode Clock Gating Control */
/* EEPROM Run Mode Clock Gating Control */
#define SYSCON_RCGCEEPROM_R0 (1 << 0) /* Bit 0: EEPROM Module Run Mode Clock Gating Control */
/* 32/64-BitWide Timer Run Mode Clock Gating Control */
#define SYSCON_RCGCWTIMER(n) (1 << (n)) /* Bit n: 32/64-Bit Wide General-Purpose Timer n Run Mode Clock Gating Control */
#define SYSCON_RCGCWTIMER_R0 (1 << 0) /* Bit 0: 32/64-Bit Wide General-Purpose Timer 0 Run Mode Clock Gating Control */
#define SYSCON_RCGCWTIMER_R1 (1 << 1) /* Bit 1: 32/64-Bit Wide General-Purpose Timer 1 Run Mode Clock Gating Control */
#define SYSCON_RCGCWTIMER_R2 (1 << 2) /* Bit 2: 32/64-Bit Wide General-Purpose Timer 2 Run Mode Clock Gating Control */
#define SYSCON_RCGCWTIMER_R3 (1 << 3) /* Bit 3: 32/64-Bit Wide General-Purpose Timer 3 Run Mode Clock Gating Control */
#define SYSCON_RCGCWTIMER_R4 (1 << 4) /* Bit 4: 32/64-Bit Wide General-Purpose Timer 4 Run Mode Clock Gating Control */
#define SYSCON_RCGCWTIMER_R5 (1 << 5) /* Bit 5: 32/64-Bit Wide General-Purpose Timer 5 Run Mode Clock Gating Control */
/* Watchdog Timer Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD(n) (1 << (n)) /* Bit n: Watchdog Timer n Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD_S0 (1 << 0) /* Bit 0: Watchdog Timer 0 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD_S1 (1 << 1) /* Bit 1: Watchdog Timer 1 Sleep Mode Clock Gating Control */
/* 16/32-Bit Timer Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD(n) (1 << (n)) /* Bit n: 16/32-Bit General-Purpose Timer n Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD_S0 (1 << 0) /* Bit 0: 16/32-Bit General-Purpose Timer 0 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD_S1 (1 << 1) /* Bit 1: 16/32-Bit General-Purpose Timer 1 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD_S2 (1 << 2) /* Bit 2: 16/32-Bit General-Purpose Timer 2 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD_S3 (1 << 3) /* Bit 3: 16/32-Bit General-Purpose Timer 3 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD_S4 (1 << 4) /* Bit 4: 16/32-Bit General-Purpose Timer 4 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWD_S5 (1 << 5) /* Bit 5: 16/32-Bit General-Purpose Timer 5 Sleep Mode Clock Gating Control */
/* GPIO Sleep Mode Clock Gating Control */
#define SYSCON_SCGCGPIO(n) (1 << (n)) /* Bit n: GPIO Port n Sleep Mode Clock Gating Control */
#define SYSCON_SCGCGPIO_S0 (1 << 0) /* Bit 0: GPIO Port A Sleep Mode Clock Gating Control */
#define SYSCON_SCGCGPIO_S1 (1 << 1) /* Bit 1: GPIO Port B Sleep Mode Clock Gating Control */
#define SYSCON_SCGCGPIO_S2 (1 << 2) /* Bit 2: GPIO Port C Sleep Mode Clock Gating Control */
#define SYSCON_SCGCGPIO_S3 (1 << 3) /* Bit 3: GPIO Port D Sleep Mode Clock Gating Control */
#define SYSCON_SCGCGPIO_S4 (1 << 4) /* Bit 4: GPIO Port E Sleep Mode Clock Gating Control */
#define SYSCON_SCGCGPIO_S5 (1 << 5) /* Bit 5: GPIO Port F Sleep Mode Clock Gating Control */
/* uDMA Sleep Mode Clock Gating Control */
#define SYSCON_SCGCDMA_S0 (1 << 0) /* Bit 0: μDMA Module Sleep Mode Clock Gating Control */
/* Hibernation Sleep Mode Clock Gating Control */
#define SYSCON_SCGCHIB_S0 (1 << 0) /* Bit 0: Hibernation Module Sleep Mode Clock Gating Control */
/* UART Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART(n) (1 << (n)) /* Bit n: UART Module n Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART_S0 (1 << 0) /* Bit 0: UART Module 0 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART_S1 (1 << 1) /* Bit 1: UART Module 1 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART_S2 (1 << 2) /* Bit 2: UART Module 2 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART_S3 (1 << 3) /* Bit 3: UART Module 3 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART_S4 (1 << 4) /* Bit 4: UART Module 4 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART_S5 (1 << 5) /* Bit 5: UART Module 5 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART_S6 (1 << 6) /* Bit 6: UART Module 6 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUART_S7 (1 << 7) /* Bit 7: UART Module 7 Sleep Mode Clock Gating Control */
/* SSI Sleep Mode Clock Gating Control */
#define SYSCON_SCGCSSI(n) (1 << (n)) /* Bit n: SSI Module n Sleep Mode Clock Gating Control */
#define SYSCON_SCGCSSI_S0 (1 << 0) /* Bit 0: SSI Module 0 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCSSI_S1 (1 << 1) /* Bit 1: SSI Module 1 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCSSI_S2 (1 << 2) /* Bit 2: SSI Module 2 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCSSI_S3 (1 << 3) /* Bit 3: SSI Module 3 Sleep Mode Clock Gating Control */
/* I2C Sleep Mode Clock Gating Control */
#define SYSCON_SCGCI2C(n) (1 << (n)) /* Bit n: I2C Module n Sleep Mode Clock Gating Control */
#define SYSCON_SCGCI2C_S0 (1 << 0) /* Bit 0: I2C Module 0 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCI2C_S1 (1 << 1) /* Bit 1: I2C Module 1 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCI2C_S2 (1 << 2) /* Bit 2: I2C Module 2 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCI2C_S3 (1 << 3) /* Bit 3: I2C Module 3 Sleep Mode Clock Gating Control */
/* USB Sleep Mode Clock Gating Control */
#define SYSCON_SCGCUSB_S0 (1 << 0) /* Bit 0: USB Module Sleep Mode Clock Gating Control */
/* CAN Sleep Mode Clock Gating Control */
#define SYSCON_SCGCCAN_S0 (1 << 0) /* Bit 0: CAN Module 0 Sleep Mode Clock Gating Control */
/* ADC Sleep Mode Clock Gating Control */
#define SYSCON_SCGCADC(n) (1 << (n)) /* Bit n: ADC Module n Sleep Mode Clock Gating Control */
#define SYSCON_SCGCADC_S0 (1 << 0) /* Bit 0: ADC Module 0 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCADC_S1 (1 << 1) /* Bit 1: ADC Module 1 Sleep Mode Clock Gating Control */
/* Analog Comparator Sleep Mode Clock Gating Control */
#define SYSCON_SCGCACMP_S0 (1 << 0) /* Bit 0: Analog Comparator Module 0 Sleep Mode Clock Gating Control */
/* EEPROM Sleep Mode Clock Gating Control */
#define SYSCON_SCGCEEPROM_S0 (1 << 0) /* Bit 0: EEPROM Module Sleep Mode Clock Gating Control */
/* 32/64-BitWide Timer Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWTIMER(n) (1 << (n)) /* Bit n: 32/64-Bit Wide General-Purpose Timer n Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWTIMER_S0 (1 << 0) /* Bit 0: 32/64-Bit Wide General-Purpose Timer 0 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWTIMER_S1 (1 << 1) /* Bit 1: 32/64-Bit Wide General-Purpose Timer 1 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWTIMER_S2 (1 << 2) /* Bit 2: 32/64-Bit Wide General-Purpose Timer 2 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWTIMER_S3 (1 << 3) /* Bit 3: 32/64-Bit Wide General-Purpose Timer 3 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWTIMER_S4 (1 << 4) /* Bit 4: 32/64-Bit Wide General-Purpose Timer 4 Sleep Mode Clock Gating Control */
#define SYSCON_SCGCWTIMER_S5 (1 << 5) /* Bit 5: 32/64-Bit Wide General-Purpose Timer 5 Sleep Mode Clock Gating Control */
/* Watchdog Timer Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWD(n) (1 << (n)) /* Bit n: Watchdog Timer n Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWD_D0 (1 << 0) /* Bit 0: Watchdog Timer 0 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWD_D1 (1 << 1) /* Bit 1: Watchdog Timer 1 Deep-Sleep Mode Clock Gating Control */
/* Clock Gating Control */
#define SYSCON_DCGCTIMER(n) (1 << (n)) /* Bit n: 16/32-Bit General-Purpose Timer n Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCTIMER_D0 (1 << 0) /* Bit 0: 16/32-Bit General-Purpose Timer 0 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCTIMER_D1 (1 << 1) /* Bit 1: 16/32-Bit General-Purpose Timer 1 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCTIMER_D2 (1 << 2) /* Bit 2: 16/32-Bit General-Purpose Timer 2 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCTIMER_D3 (1 << 3) /* Bit 3: 16/32-Bit General-Purpose Timer 3 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCTIMER_D4 (1 << 4) /* Bit 4: 16/32-Bit General-Purpose Timer 4 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCTIMER_D5 (1 << 5) /* Bit 5: 16/32-Bit General-Purpose Timer 5 Deep-Sleep Mode Clock Gating Control */
/* GPIO Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCGPIO(n) (1 << (n)) /* Bit n: GPIO Port F Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCGPIO_D0 (1 << 0) /* Bit 0: GPIO Port A Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCGPIO_D1 (1 << 1) /* Bit 1: GPIO Port B Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCGPIO_D2 (1 << 2) /* Bit 2: GPIO Port C Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCGPIO_D3 (1 << 3) /* Bit 3: GPIO Port D Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCGPIO_D4 (1 << 4) /* Bit 4: GPIO Port E Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCGPIO_D5 (1 << 5) /* Bit 5: GPIO Port F Deep-Sleep Mode Clock Gating Control */
/* uDMA Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCDMA_D0 (1 << 0) /* Bit 0: μDMA Module Deep-Sleep Mode Clock Gating Control */
/* Hibernation Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCHIB_D0 (1 << 0) /* Bit 0: Hibernation Module Deep-Sleep Mode Clock Gating Control */
/* UART Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART(n) (1 << (n)) /* Bit n: UART Module n Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART_D0 (1 << 0) /* Bit 0: UART Module 0 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART_D1 (1 << 1) /* Bit 1: UART Module 1 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART_D2 (1 << 2) /* Bit 2: UART Module 2 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART_D3 (1 << 3) /* Bit 3: UART Module 3 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART_D4 (1 << 4) /* Bit 4: UART Module 4 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART_D5 (1 << 5) /* Bit 5: UART Module 5 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART_D6 (1 << 6) /* Bit 6: UART Module 6 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUART_D7 (1 << 7) /* Bit 7: UART Module 7 Deep-Sleep Mode Clock Gating Control */
/* SSI Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCSSI(n) (1 << (n)) /* Bit n: SSI Module n Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCSSI_D0 (1 << 0) /* Bit 0: SSI Module 0 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCSSI_D1 (1 << 1) /* Bit 1: SSI Module 1 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCSSI_D2 (1 << 2) /* Bit 2: SSI Module 2 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCSSI_D3 (1 << 3) /* Bit 3: SSI Module 3 Deep-Sleep Mode Clock Gating Control */
/* I2C Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCI2C(n) (1 << (n)) /* Bit n: I2C Module n Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCI2C_D0 (1 << 0) /* Bit 0: I2C Module 0 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCI2C_D1 (1 << 1) /* Bit 1: I2C Module 1 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCI2C_D2 (1 << 2) /* Bit 2: I2C Module 2 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCI2C_D3 (1 << 3) /* Bit 3: I2C Module 3 Deep-Sleep Mode Clock Gating Control */
/* USB Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCUSB_D0 (1 << 0) /* Bit 0: USB Module Deep-Sleep Mode Clock Gating Control */
/* CAN Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCCAN_D0 (1 << 0) /* Bit 0: CAN Module 0 Deep-Sleep Mode Clock Gating Control */
/* ADC Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCADC(n) (1 << (n)) /* Bit n: ADC Module n Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCADC_D0 (1 << 0) /* Bit 0: ADC Module 0 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCADC_D1 (1 << 1) /* Bit 1: ADC Module 1 Deep-Sleep Mode Clock Gating Control */
/* Analog Comparator Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCACMP_D0 (1 << 0) /* Bit 0: Analog Comparator Module 0 Deep-Sleep Mode Clock Gating Control */
/* EEPROM Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCEEPROM_D0 (1 << 0) /* Bit 0: EEPROM Module Deep-Sleep Mode Clock Gating Control */
/* 32/64-BitWide Timer Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWTIMER(n) (1 << (n)) /* Bit n: UART Module n Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWTIMER_D0 (1 << 0) /* Bit 0: UART Module 0 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWTIMER_D1 (1 << 1) /* Bit 1: UART Module 1 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWTIMER_D2 (1 << 2) /* Bit 2: UART Module 2 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWTIMER_D3 (1 << 3) /* Bit 3: UART Module 3 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWTIMER_D4 (1 << 4) /* Bit 4: UART Module 4 Deep-Sleep Mode Clock Gating Control */
#define SYSCON_DCGCWTIMER_D5 (1 << 5) /* Bit 5: UART Module 5 Deep-Sleep Mode Clock Gating Control */
/* Watchdog Timer Peripheral Ready */
#define SYSCON_PRWD(n) (1 << (n)) /* Bit n: Watchdog Timer n Peripheral Ready */
#define SYSCON_PRWD_R0 (1 << 0) /* Bit 0: Watchdog Timer 0 Peripheral Ready */
#define SYSCON_PRWD_R1 (1 << 1) /* Bit 1: Watchdog Timer 1 Peripheral Ready */
/* 16/32-Bit Timer Peripheral Ready */
#define SYSCON_PRTIMER(n) (1 << (n)) /* Bit n: 16/32-Bit General-Purpose Timer n Peripheral Ready */
#define SYSCON_PRTIMER_R0 (1 << 0) /* Bit 0: 16/32-Bit General-Purpose Timer 0 Peripheral Ready */
#define SYSCON_PRTIMER_R1 (1 << 1) /* Bit 1: 16/32-Bit General-Purpose Timer 1 Peripheral Ready */
#define SYSCON_PRTIMER_R2 (1 << 2) /* Bit 2: 16/32-Bit General-Purpose Timer 2 Peripheral Ready */
#define SYSCON_PRTIMER_R3 (1 << 3) /* Bit 3: 16/32-Bit General-Purpose Timer 3 Peripheral Ready */
#define SYSCON_PRTIMER_R4 (1 << 4) /* Bit 4: 16/32-Bit General-Purpose Timer 4 Peripheral Ready */
#define SYSCON_PRTIMER_R5 (1 << 5) /* Bit 5: 16/32-Bit General-Purpose Timer 5 Peripheral Ready */
/* GPIO Peripheral Ready */
#define SYSCON_PRGPIO(n) (1 << (n)) /* Bit n: GPIO Port F Peripheral Ready */
#define SYSCON_PRGPIO_R0 (1 << 0) /* Bit 0: GPIO Port A Peripheral Ready */
#define SYSCON_PRGPIO_R1 (1 << 1) /* Bit 1: GPIO Port B Peripheral Ready */
#define SYSCON_PRGPIO_R2 (1 << 2) /* Bit 2: GPIO Port C Peripheral Ready */
#define SYSCON_PRGPIO_R3 (1 << 3) /* Bit 3: GPIO Port D Peripheral Ready */
#define SYSCON_PRGPIO_R4 (1 << 4) /* Bit 4: GPIO Port E Peripheral Ready */
#define SYSCON_PRGPIO_R5 (1 << 5) /* Bit 5: GPIO Port F Peripheral Ready */
/* uDMA Peripheral Ready */
#define SYSCON_PRDMA_R0 (1 << 0) /* Bit 0: μDMA Module Peripheral Ready */
/* Hibernation Peripheral Ready */
#define SYSCON_PRHIB_R0 (1 << 0) /* Bit 0: Hibernation Module Peripheral Ready */
/* UART Peripheral Ready */
#define SYSCON_PRUART(n) (1 << (n)) /* Bit n: UART Module n Peripheral Ready */
#define SYSCON_PRUART_R0 (1 << 0) /* Bit 0: UART Module 0 Peripheral Ready */
#define SYSCON_PRUART_R1 (1 << 1) /* Bit 1: UART Module 1 Peripheral Ready */
#define SYSCON_PRUART_R2 (1 << 2) /* Bit 2: UART Module 2 Peripheral Ready */
#define SYSCON_PRUART_R3 (1 << 3) /* Bit 3: UART Module 3 Peripheral Ready */
#define SYSCON_PRUART_R4 (1 << 4) /* Bit 4: UART Module 4 Peripheral Ready */
#define SYSCON_PRUART_R5 (1 << 5) /* Bit 5: UART Module 5 Peripheral Ready */
#define SYSCON_PRUART_R6 (1 << 6) /* Bit 6: UART Module 6 Peripheral Ready */
#define SYSCON_PRUART_R7 (1 << 7) /* Bit 7: UART Module 7 Peripheral Ready */
/* SSI Peripheral Ready */
#define SYSCON_PRSSI(n) (1 << (n)) /* Bit n: SSI Module n Peripheral Ready */
#define SYSCON_PRSSI_R0 (1 << 0) /* Bit 0: SSI Module 0 Peripheral Ready */
#define SYSCON_PRSSI_R1 (1 << 1) /* Bit 1: SSI Module 1 Peripheral Ready */
#define SYSCON_PRSSI_R2 (1 << 2) /* Bit 2: SSI Module 2 Peripheral Ready */
#define SYSCON_PRSSI_R3 (1 << 3) /* Bit 3: SSI Module 3 Peripheral Ready */
/* I2C Peripheral Ready */
#define SYSCON_PRI2C(n) (1 << (n)) /* Bit n: I2C Module n Peripheral Ready */
#define SYSCON_PRI2C_R0 (1 << 0) /* Bit 0: I2C Module 0 Peripheral Ready */
#define SYSCON_PRI2C_R1 (1 << 1) /* Bit 1: I2C Module 1 Peripheral Ready */
#define SYSCON_PRI2C_R2 (1 << 2) /* Bit 2: I2C Module 2 Peripheral Ready */
#define SYSCON_PRI2C_R3 (1 << 3) /* Bit 3: I2C Module 3 Peripheral Ready */
/* USB Peripheral Ready */
#define SYSCON_PRUSB_R0 (1 << 0) /* Bit 0: USB Module Peripheral Ready */
/* CAN Peripheral Ready */
#define SYSCON_PRCAN_R0 (1 << 0) /* Bit 0: CAN Module 0 Peripheral Ready */
/* ADC Peripheral Ready */
#define SYSCON_PRADC(n) (1 << (n)) /* Bit n: ADC Module n Peripheral Ready */
#define SYSCON_PRADC_R0 (1 << 0) /* Bit 0: ADC Module 0 Peripheral Ready */
#define SYSCON_PRADC_R1 (1 << 1) /* Bit 1: ADC Module 1 Peripheral Ready */
/* Analog Comparator Peripheral Ready */
#define SYSCON_PRACMP_R0 (1 << 0) /* Bit 0: Analog Comparator Module 0 Peripheral Ready */
/* EEPROM Peripheral Ready */
#define SYSCON_PREEPROM_0 (1 << 0) /* Bit 0: EEPROM Module Peripheral Ready */
/* 2/64-BitWide Timer Peripheral Ready */
#define SYSCON_PRWTIMER(n) (1 << (n)) /* Bit n: 32/64-Bit Wide General-Purpose Timer n Peripheral Ready */
#define SYSCON_PRWTIMER_R0 (1 << 0) /* Bit 0: 32/64-Bit Wide General-Purpose Timer 0 Peripheral Ready */
#define SYSCON_PRWTIMER_R1 (1 << 1) /* Bit 1: 32/64-Bit Wide General-Purpose Timer 1 Peripheral Ready */
#define SYSCON_PRWTIMER_R2 (1 << 2) /* Bit 2: 32/64-Bit Wide General-Purpose Timer 2 Peripheral Ready */
#define SYSCON_PRWTIMER_R3 (1 << 3) /* Bit 3: 32/64-Bit Wide General-Purpose Timer 3 Peripheral Ready */
#define SYSCON_PRWTIMER_R4 (1 << 4) /* Bit 4: 32/64-Bit Wide General-Purpose Timer 4 Peripheral Ready */
#define SYSCON_PRWTIMER_R5 (1 << 5) /* Bit 5: 32/64-Bit Wide General-Purpose Timer 5 Peripheral Ready */
/* System Control Legacy Register Bit Definitions *******************************************/
/* Device Capabilities 0 */
#define SYSCON_DC0_FLASHSZ_SHIFT 0 /* Bits 15-0: FLASH Size */
#define SYSCON_DC0_FLASHSZ_MASK (0xffff << SYSCON_DC0_FLASHSZ_SHIFT)
#define SYSCON_DC0_SRAMSZ_SHIFT 16 /* Bits 31-16: SRAM Size */
#define SYSCON_DC0_SRAMSZ_MASK (0xffff << SYSCON_DC0_SRAMSZ_SHIFT)
/* Device Capabilities 1 */
#define SYSCON_DC1_JTAG (1 << 0) /* Bit 0: JTAG Present */
#define SYSCON_DC1_SWD (1 << 1) /* Bit 1: SWD Present */
#define SYSCON_DC1_SWO (1 << 2) /* Bit 2: SWO Trace Port Present */
#define SYSCON_DC1_WDT0 (1 << 3) /* Bit 3: Watchdog Timer 0 Present */
#define SYSCON_DC1_PLL (1 << 4) /* Bit 4: PLL Present */
#define SYSCON_DC1_TEMPSNS (1 << 5) /* Bit 5: Temp Sensor Present */
#define SYSCON_DC1_HIB (1 << 6) /* Bit 6: Hibernation Module Present */
#define SYSCON_DC1_MPU (1 << 7) /* Bit 7: MPU Present */
#define SYSCON_DC1_MAXADC0SPD_SHIFT (8) /* Bits 9-8: Max ADC Speed */
#define SYSCON_DC1_MAXADC0SPD_MASK (3 << SYSCON_DC1_MAXADC0SPD_SHIFT)
#define SYSCON_DC1_MAXADC1SPD_SHIFT (10) /* Bits 10-11: Max ADC Speed */
#define SYSCON_DC1_MAXADC1SPD_MASK (3 << SYSCON_DC1_MAXADC1SPD_SHIFT)
#define SYSCON_DC1_MINSYSDIV_SHIFT 12 /* Bits 12-15: System Clock Divider Minimum */
#define SYSCON_DC1_MINSYSDIV_MASK (15 << SYSCON_DC1_MINSYSDIV_SHIFT)
#define SYSCON_DC1_ADC0 (1 << 16) /* Bit 16: ADC0 Module Present */
#define SYSCON_DC1_ADC1 (1 << 17) /* Bit 17: ADC1 Module Present */
#define SYSCON_DC1_PWM0 (1 << 20) /* Bit 20: PWM0 Module Present */
#define SYSCON_DC1_PWM1 (1 << 21) /* Bit 21: PWM1 Module Present */
#define SYSCON_DC1_CAN0 (1 << 24) /* Bit 24: CAN0 Module Present */
#define SYSCON_DC1_CAN1 (1 << 25) /* Bit 25: CAN1 Module Present */
#define SYSCON_DC1_WDT1 (1 << 28) /* Bit 28: Watchdog Timer 1 Present */
/* Device Capabilities 2 */
#define SYSCON_DC2_UART0 (1 << 0) /* Bit 0: UART0 Module Present */
#define SYSCON_DC2_UART1 (1 << 1) /* Bit 1: UART1 Module Present */
#define SYSCON_DC2_UART2 (1 << 2) /* Bit 2: UART2 Module Present */
#define SYSCON_DC2_SSI0 (1 << 4) /* Bit 4: SSI0 Module Present */
#define SYSCON_DC2_SSI1 (1 << 5) /* Bit 5: SSI1 Module Present */
#define SYSCON_DC2_QEI0 (1 << 8) /* Bit 8: QEI0 Module Present */
#define SYSCON_DC2_QEI1 (1 << 9) /* Bit 9: QEI1 Module Present */
#define SYSCON_DC2_I2C0 (1 << 12) /* Bit 12: I2C Module 0 Present */
#define SYSCON_DC2_I2C0HS (1 << 13) /* Bit 13: I2C Module 0 Speed */
#define SYSCON_DC2_I2C1 (1 << 14) /* Bit 14: I2C Module 1 Present */
#define SYSCON_DC2_I2C1HS (1 << 15) /* Bit 15: I2C Module 1 Speed */
#define SYSCON_DC2_TIMER0 (1 << 16) /* Bit 16: Timer 0 Present */
#define SYSCON_DC2_TIMER1 (1 << 17) /* Bit 17: Timer 1 Present */
#define SYSCON_DC2_TIMER2 (1 << 18) /* Bit 18: Timer 2 Present */
#define SYSCON_DC2_TIMER3 (1 << 19) /* Bit 19: Timer 3 Present */
#define SYSCON_DC2_COMP0 (1 << 24) /* Bit 24: Analog Comparator 0 Present */
#define SYSCON_DC2_COMP1 (1 << 25) /* Bit 25: Analog Comparator 1 Present */
#define SYSCON_DC2_COMP2 (1 << 26) /* Bit 26: Analog Comparator 2 Present */
#define SYSCON_DC2_I2S0 (1 << 28) /* Bit 28: I2S Module 0 Present */
#define SYSCON_DC2_EPI0 (1 << 30) /* Bit 30: EPI Module 0 Present */
/* Device Capabilities 3 */
#define SYSCON_DC3_PWM0 (1 << 0) /* Bit 0: PWM0 Pin Present */
#define SYSCON_DC3_PWM1 (1 << 1) /* Bit 1: PWM1 Pin Present */
#define SYSCON_DC3_PWM2 (1 << 2) /* Bit 2: PWM2 Pin Present */
#define SYSCON_DC3_PWM3 (1 << 3) /* Bit 3: PWM3 Pin Present */
#define SYSCON_DC3_PWM4 (1 << 4) /* Bit 4: PWM4 Pin Present */
#define SYSCON_DC3_PWM5 (1 << 5) /* Bit 5: PWM5 Pin Present */
#define SYSCON_DC3_C0MINUS (1 << 6) /* Bit 6: C0- Pin Present */
#define SYSCON_DC3_C0PLUS (1 << 7) /* Bit 7: C0+ Pin Present */
#define SYSCON_DC3_C0O (1 << 8) /* Bit 8: C0o Pin Present */
#define SYSCON_DC3_C1MINUS (1 << 9) /* Bit 9: C1- Pin Present */
#define SYSCON_DC3_C1PLUS (1 << 10) /* Bit 10: C1+ Pin Present */
#define SYSCON_DC3_C1O (1 << 11) /* Bit 11: C1o Pin Present */
#define SYSCON_DC3_C2MINUS (1 << 12) /* Bit 12: C2- Pin Present */
#define SYSCON_DC3_C2PLUS (1 << 13) /* Bit 13: C2+ Pin Present */
#define SYSCON_DC3_C2O (1 << 14) /* Bit 14: C2o Pin Present */
#define SYSCON_DC3_PWMFAULT (1 << 15) /* Bit 15: PWM Fault Pin Pre */
#define SYSCON_DC3_ADC0AIN0 (1 << 16) /* Bit 16: ADC Module 0 AIN0 Pin Present */
#define SYSCON_DC3_ADC0AIN1 (1 << 17) /* Bit 17: ADC Module 0 AIN1 Pin Present */
#define SYSCON_DC3_ADC0AIN2 (1 << 18) /* Bit 18: ADC Module 0 AIN2 Pin Present */
#define SYSCON_DC3_ADC0AIN3 (1 << 19) /* Bit 19: ADC Module 0 AIN3 Pin Present */
#define SYSCON_DC3_ADC0AIN4 (1 << 20) /* Bit 20: ADC Module 0 AIN4 Pin Present */
#define SYSCON_DC3_ADC0AIN5 (1 << 21) /* Bit 21: ADC Module 0 AIN5 Pin Present */
#define SYSCON_DC3_ADC0AIN6 (1 << 22) /* Bit 22: ADC Module 0 AIN6 Pin Present */
#define SYSCON_DC3_ADC0AIN7 (1 << 23) /* Bit 23: ADC Module 0 AIN7 Pin Present */
#define SYSCON_DC3_CCP0 (1 << 24) /* Bit 24: T0CCP0 Pin Present */
#define SYSCON_DC3_CCP1 (1 << 25) /* Bit 25: T0CCP1 Pin Present */
#define SYSCON_DC3_CCP2 (1 << 26) /* Bit 26: T1CCP0 Pin Present */
#define SYSCON_DC3_CCP3 (1 << 27) /* Bit 27: T1CCP1 Pin Present */
#define SYSCON_DC3_CCP4 (1 << 28) /* Bit 28: T2CCP0 Pin Present */
#define SYSCON_DC3_CCP5 (1 << 29) /* Bit 29: T2CCP1 Pin Present */
#define SYSCON_DC3_32KHZ (1 << 31) /* Bit 31: 32KHz Input Clock Available */
/* Device Capabilities 4 */
#define SYSCON_DC4_GPIO(n) (1 << (n))
#define SYSCON_DC4_GPIOA (1 << 0) /* Bit 0: GPIO Port A Present */
#define SYSCON_DC4_GPIOB (1 << 1) /* Bit 1: GPIO Port B Present */
#define SYSCON_DC4_GPIOC (1 << 2) /* Bit 2: GPIO Port C Present */
#define SYSCON_DC4_GPIOD (1 << 3) /* Bit 3: GPIO Port D Present */
#define SYSCON_DC4_GPIOE (1 << 4) /* Bit 4: GPIO Port E Present */
#define SYSCON_DC4_GPIOF (1 << 5) /* Bit 5: GPIO Port F Present */
#define SYSCON_DC4_GPIOG (1 << 6) /* Bit 6: GPIO Port G Present */
#define SYSCON_DC4_GPIOH (1 << 7) /* Bit 7: GPIO Port H Present */
#define SYSCON_DC4_GPIOJ (1 << 8) /* Bit 8: GPIO Port J Present */
#define SYSCON_DC4_ROM (1 << 12) /* Bit 12: Internal Code ROM Present */
#define SYSCON_DC4_UDMA (1 << 13) /* Bit 13: Micro-DMA Module Present */
#define SYSCON_DC4_CCP6 (1 << 14) /* Bit 14: T3CCP0 Pin Present */
#define SYSCON_DC4_CCP7 (1 << 15) /* Bit 15: T3CCP1 Pin Present */
#define SYSCON_DC4_PICAL (1 << 18) /* Bit 18: PIOSC Calibrate */
#define SYSCON_DC4_E1588 (1 << 24) /* Bit 24: 1588 Capable */
#define SYSCON_DC4_EMAC0 (1 << 28) /* Bit 28: Ethernet MAC0 Present */
#define SYSCON_DC4_EPHY0 (1 << 30) /* Bit 30: Ethernet PHY0 Present */
/* Device Capabilities 5 */
#define TIVA_SYSCON_DC5_PWM0 (1 << 0) /* Bit 0: PWM0 Pin Present */
#define TIVA_SYSCON_DC5_PWM1 (1 << 1) /* Bit 1: PWM1 Pin Present */
#define TIVA_SYSCON_DC5_PWM2 (1 << 2) /* Bit 2: PWM2 Pin Present */
#define TIVA_SYSCON_DC5_PWM3 (1 << 3) /* Bit 3: PWM3 Pin Present */
#define TIVA_SYSCON_DC5_PWM4 (1 << 4) /* Bit 4: PWM4 Pin Present */
#define TIVA_SYSCON_DC5_PWM5 (1 << 5) /* Bit 5: PWM5 Pin Present */
#define TIVA_SYSCON_DC5_PWM6 (1 << 6) /* Bit 6: PWM6 Pin Present */
#define TIVA_SYSCON_DC5_PWM7 (1 << 7) /* Bit 7: PWM7 Pin Present */
#define TIVA_SYSCON_DC5_PWMESYNC (1 << 20) /* Bit 20: PWM Extended SYNC Active */
#define TIVA_SYSCON_DC5_PWMEFLT (1 << 21) /* Bit 21: PWM Extended Fault Active */
#define TIVA_SYSCON_DC5_PWMFAULT0 (1 << 24) /* Bit 24: PWM Fault 0 Pin Present */
#define TIVA_SYSCON_DC5_PWMFAULT1 (1 << 25) /* Bit 25: PWM Fault 1 Pin Present */
#define TIVA_SYSCON_DC5_PWMFAULT2 (1 << 26) /* Bit 26: PWM Fault 2 Pin Present */
#define TIVA_SYSCON_DC5_PWMFAULT3 (1 << 27) /* Bit 27: PWM Fault 3 Pin Present */
/* Device Capabilities 6 */
#define TIVA_SYSCON_DC6_USB0_SHIFT (0) /* Bits 0-1: USB Module 0 Present */
#define TIVA_SYSCON_DC6_USB0_MASK (3 << TIVA_SYSCON_DC6_USB0_SHIFT)
#define TIVA_SYSCON_DC6_USB0_NONE (1 << TIVA_SYSCON_DC6_USB0_SHIFT)
#define TIVA_SYSCON_DC6_USB0_DEVICE (2 << TIVA_SYSCON_DC6_USB0_SHIFT)
#define TIVA_SYSCON_DC6_USB0_HOST (3 << TIVA_SYSCON_DC6_USB0_SHIFT)
#define TIVA_SYSCON_DC6_USB0_OTG (3 << TIVA_SYSCON_DC6_USB0_SHIFT)
#define TIVA_SYSCON_DC6_USB0PHY (1 << 4) /* Bit 4: USB Module 0 PHY Present */
/* Device Capabilities 7 */
#define TIVA_SYSCON_DC7_DMACH0 (1 << 0) /* Bit 0: DMA Channel 0 */
#define TIVA_SYSCON_DC7_DMACH1 (1 << 1) /* Bit 1: DMA Channel 1 */
#define TIVA_SYSCON_DC7_DMACH2 (1 << 2) /* Bit 2: DMA Channel 2 */
#define TIVA_SYSCON_DC7_DMACH3 (1 << 3) /* Bit 3: DMA Channel 3 */
#define TIVA_SYSCON_DC7_DMACH4 (1 << 4) /* Bit 4: DMA Channel 4 */
#define TIVA_SYSCON_DC7_DMACH5 (1 << 5) /* Bit 5: DMA Channel 5 */
#define TIVA_SYSCON_DC7_DMACH6 (1 << 6) /* Bit 6: DMA Channel 6 */
#define TIVA_SYSCON_DC7_DMACH7 (1 << 7) /* Bit 7: DMA Channel 7 */
#define TIVA_SYSCON_DC7_DMACH8 (1 << 8) /* Bit 8: DMA Channel 8 */
#define TIVA_SYSCON_DC7_DMACH9 (1 << 9) /* Bit 9: DMA Channel 9 */
#define TIVA_SYSCON_DC7_DMACH10 (1 << 10) /* Bit 10: DMA Channel 10 */
#define TIVA_SYSCON_DC7_DMACH11 (1 << 11) /* Bit 11: DMA Channel 11 */
#define TIVA_SYSCON_DC7_DMACH12 (1 << 12) /* Bit 12: DMA Channel 12 */
#define TIVA_SYSCON_DC7_DMACH13 (1 << 13) /* Bit 13: DMA Channel 13 */
#define TIVA_SYSCON_DC7_DMACH14 (1 << 14) /* Bit 14: DMA Channel 14 */
#define TIVA_SYSCON_DC7_DMACH15 (1 << 15) /* Bit 15: DMA Channel 15 */
#define TIVA_SYSCON_DC7_DMACH16 (1 << 16) /* Bit 16: DMA Channel 16 */
#define TIVA_SYSCON_DC7_DMACH17 (1 << 17) /* Bit 17: DMA Channel 17 */
#define TIVA_SYSCON_DC7_DMACH18 (1 << 18) /* Bit 18: DMA Channel 18 */
#define TIVA_SYSCON_DC7_DMACH19 (1 << 19) /* Bit 19: DMA Channel 19 */
#define TIVA_SYSCON_DC7_DMACH20 (1 << 20) /* Bit 20: DMA Channel 20 */
#define TIVA_SYSCON_DC7_DMACH21 (1 << 21) /* Bit 21: DMA Channel 21 */
#define TIVA_SYSCON_DC7_DMACH22 (1 << 22) /* Bit 22: DMA Channel 22 */
#define TIVA_SYSCON_DC7_DMACH23 (1 << 23) /* Bit 23: DMA Channel 23 */
#define TIVA_SYSCON_DC7_DMACH24 (1 << 24) /* Bit 24: DMA Channel 24 */
#define TIVA_SYSCON_DC7_DMACH25 (1 << 25) /* Bit 25: DMA Channel 25 */
#define TIVA_SYSCON_DC7_DMACH26 (1 << 26) /* Bit 26: DMA Channel 26 */
#define TIVA_SYSCON_DC7_DMACH27 (1 << 27) /* Bit 27: DMA Channel 27 */
#define TIVA_SYSCON_DC7_DMACH28 (1 << 28) /* Bit 28: DMA Channel 28 */
#define TIVA_SYSCON_DC7_DMACH29 (1 << 29) /* Bit 29: DMA Channel 29 */
#define TIVA_SYSCON_DC7_DMACH30 (1 << 30) /* Bit 30: DMA Channel 30 */
/* Device Capabilities 8 */
#define TIVA_SYSCON_DC8_ADC0AIN0 (1 << 0) /* Bit 0: ADC Module 0 AIN0 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN1 (1 << 1) /* Bit 1: ADC Module 0 AIN1 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN2 (1 << 2) /* Bit 2: ADC Module 0 AIN2 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN3 (1 << 3) /* Bit 3: ADC Module 0 AIN3 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN4 (1 << 4) /* Bit 4: ADC Module 0 AIN4 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN5 (1 << 5) /* Bit 5: ADC Module 0 AIN5 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN6 (1 << 6) /* Bit 6: ADC Module 0 AIN6 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN7 (1 << 7) /* Bit 7: ADC Module 0 AIN7 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN8 (1 << 8) /* Bit 8: ADC Module 0 AIN8 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN9 (1 << 9) /* Bit 9: ADC Module 0 AIN9 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN10 (1 << 10) /* Bit 10: ADC Module 0 AIN10 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN11 (1 << 11) /* Bit 11: ADC Module 0 AIN11 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN12 (1 << 12) /* Bit 12: ADC Module 0 AIN12 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN13 (1 << 13) /* Bit 13: ADC Module 0 AIN13 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN14 (1 << 14) /* Bit 14: ADC Module 0 AIN14 Pin Present */
#define TIVA_SYSCON_DC8_ADC0AIN15 (1 << 15) /* Bit 15: ADC Module 0 AIN15 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN0 (1 << 16) /* Bit 16: ADC Module 1 AIN0 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN1 (1 << 17) /* Bit 17: ADC Module 1 AIN1 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN2 (1 << 18) /* Bit 18: ADC Module 1 AIN2 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN3 (1 << 19) /* Bit 19: ADC Module 1 AIN3 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN4 (1 << 20) /* Bit 20: ADC Module 1 AIN4 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN5 (1 << 21) /* Bit 21: ADC Module 1 AIN5 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN6 (1 << 22) /* Bit 22: ADC Module 1 AIN6 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN7 (1 << 23) /* Bit 23: ADC Module 1 AIN7 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN8 (1 << 24) /* Bit 24: ADC Module 1 AIN8 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN9 (1 << 25) /* Bit 25: ADC Module 1 AIN9 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN10 (1 << 26) /* Bit 26: ADC Module 1 AIN10 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN11 (1 << 27) /* Bit 27: ADC Module 1 AIN11 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN12 (1 << 28) /* Bit 28: ADC Module 1 AIN12 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN13 (1 << 29) /* Bit 29: ADC Module 1 AIN13 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN14 (1 << 30) /* Bit 30: ADC Module 1 AIN14 Pin Present */
#define TIVA_SYSCON_DC8_ADC1AIN15 (1 << 31) /* Bit 31: ADC Module 1 AIN15 Pin Present */
/* Software Reset Control 0 */
#define SYSCON_SRCR0_WDT0 (1 << 3) /* Bit 3: Watchdog Timer 0 Reset Control */
#define SYSCON_SRCR0_HIB (1 << 6) /* Bit 6: Hibernation Module Reset Control */
#define SYSCON_SRCR0_ADC0 (1 << 16) /* Bit 16: ADC0 Reset Control */
#define SYSCON_SRCR0_ADC1 (1 << 17) /* Bit 17: ADC1 Reset Control */
#define SYSCON_SRCR0_CAN0 (1 << 24) /* Bit 24: CAN0 Reset Control */
#define SYSCON_SRCR0_WDT1 (1 << 28) /* Bit 28: Watchdog Timer 1 Reset Control */
/* Software Reset Control 1 */
#define SYSCON_SRCR1_UART0 (1 << 0) /* Bit 0: UART0 Reset Control */
#define SYSCON_SRCR1_UART1 (1 << 1) /* Bit 1: UART1 Reset Control */
#define SYSCON_SRCR1_UART2 (1 << 2) /* Bit 2: UART2 Reset Control */
#define SYSCON_SRCR1_SSI0 (1 << 4) /* Bit 4: SSI0 Reset Control */
#define SYSCON_SRCR1_SSI1 (1 << 5) /* Bit 5: SSI1 Reset Control */
#define SYSCON_SRCR1_I2C0 (1 << 12) /* Bit 12: I2C 0 Reset Control */
#define SYSCON_SRCR1_I2C1 (1 << 14) /* Bit 14: I2C 1 Reset Control */
#define SYSCON_SRCR1_TIMER0 (1 << 16) /* Bit 16: Timer 0 Reset Control */
#define SYSCON_SRCR1_TIMER1 (1 << 17) /* Bit 17: Timer 1 Reset Control */
#define SYSCON_SRCR1_TIMER2 (1 << 18) /* Bit 18: Timer 2 Reset Control */
#define SYSCON_SRCR1_TIMER3 (1 << 19) /* Bit 19: Timer 3 Reset Control */
#define SYSCON_SRCR1_COMP0 (1 << 24) /* Bit 24: Analog Comparator 0 Reset Control */
#define SYSCON_SRCR1_COMP1 (1 << 25) /* Bit 25: Analog Comparator 1 Reset Control */
/* Software Reset Control 2 */
#define SYSCON_SRCR2_GPIO(n) (1 << (n))
#define SYSCON_SRCR2_GPIOA (1 << 0) /* Bit 0: Port A Reset Control */
#define SYSCON_SRCR2_GPIOB (1 << 1) /* Bit 1: Port B Reset Control */
#define SYSCON_SRCR2_GPIOC (1 << 2) /* Bit 2: Port C Reset Control */
#define SYSCON_SRCR2_GPIOD (1 << 3) /* Bit 3: Port D Reset Control */
#define SYSCON_SRCR2_GPIOE (1 << 4) /* Bit 4: Port E Reset Control */
#define SYSCON_SRCR2_GPIOF (1 << 5) /* Bit 5: Port F Reset Control */
#define SYSCON_SRCR2_UDMA (1 << 13) /* Bit 13: Micro-DMA Reset Control */
#define SYSCON_SRCR2_USB0 (1 << 16) /* Bit 16: USB0 Reset Control */
/* Run Mode Clock Gating Control Register 0 */
#define SYSCON_RCGC0_WDT0 (1 << 3) /* Bit 3: WDT0 Clock Gating Control */
#define SYSCON_RCGC0_HIB (1 << 6) /* Bit 6: HIB Clock Gating Control */
#define SYSCON_RCGC0_MAXADC0SPD_SHIFT (8) /* Bits 8-9: ADC0 Sample Speed */
#define SYSCON_RCGC0_MAXADC0SPD_MASK (3 << SYSCON_RCGC0_MAXADC0SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC0_125KSPS (0 << SYSCON_RCGC0_MAXADC0SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC0_250KSPS (1 << SYSCON_RCGC0_MAXADC0SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC0_500KSPS (2 << SYSCON_RCGC0_MAXADC0SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC0_1MSPS (3 << SYSCON_RCGC0_MAXADC0SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC1SPD_SHIFT (8) /* Bits 10-11: ADC1 Sample Speed */
#define SYSCON_RCGC0_MAXADC1SPD_MASK (3 << SYSCON_RCGC0_MAXADC1SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC1_125KSPS (0 << SYSCON_RCGC0_MAXADC1SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC1_250KSPS (1 << SYSCON_RCGC0_MAXADC1SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC1_500KSPS (2 << SYSCON_RCGC0_MAXADC1SPD_SHIFT)
#define SYSCON_RCGC0_MAXADC1_1MSPS (3 << SYSCON_RCGC0_MAXADC1SPD_SHIFT)
#define SYSCON_RCGC0_ADC0 (1 << 16) /* Bit 16: ADC0 Clock Gating Control */
#define SYSCON_RCGC0_CAN0 (1 << 24) /* Bit 24: CAN0 Clock Gating Control */
#define SYSCON_RCGC0_WDT1 (1 << 28) /* Bit 28: WDT1 Clock Gating Control */
/* Run Mode Clock Gating Control Register 1 */
#define SYSCON_RCGC1_UART0 (1 << 0) /* Bit 0: UART0 Clock Gating Control */
#define SYSCON_RCGC1_UART1 (1 << 1) /* Bit 1: UART1 Clock Gating Control */
#define SYSCON_RCGC1_UART2 (1 << 2) /* Bit 2: UART2 Clock Gating Control */
#define SYSCON_RCGC1_SSI0 (1 << 4) /* Bit 4: SSI0 Clock Gating Control */
#define SYSCON_RCGC1_SSI1 (1 << 5) /* Bit 5: SSI1 Clock Gating Control */
#define SYSCON_RCGC1_I2C0 (1 << 12) /* Bit 12: I2C0 Clock Gating Control */
#define SYSCON_RCGC1_I2C1 (1 << 14) /* Bit 14: I2C1 Clock Gating Control */
#define SYSCON_RCGC1_TIMER0 (1 << 16) /* Bit 16: Timer 0 Clock Gating Control */
#define SYSCON_RCGC1_TIMER1 (1 << 17) /* Bit 17: Timer 1 Clock Gating Control */
#define SYSCON_RCGC1_TIMER2 (1 << 18) /* Bit 18: Timer 2 Clock Gating Control */
#define SYSCON_RCGC1_TIMER3 (1 << 19) /* Bit 19: Timer 3 Clock Gating Control */
#define SYSCON_RCGC1_COMP0 (1 << 24) /* Bit 24: Analog Comparator 0 Clock Gating */
#define SYSCON_RCGC1_COMP1 (1 << 25) /* Bit 25: Analog Comparator 1 Clock Gating */
/* Run Mode Clock Gating Control Register 2 */
#define SYSCON_RCGC2_GPIO(n) (1 << (n))
#define SYSCON_RCGC2_GPIOA (1 << 0) /* Bit 0: Port A Clock Gating Control */
#define SYSCON_RCGC2_GPIOB (1 << 1) /* Bit 1: Port B Clock Gating Control */
#define SYSCON_RCGC2_GPIOC (1 << 2) /* Bit 2: Port C Clock Gating Control */
#define SYSCON_RCGC2_GPIOD (1 << 3) /* Bit 3: Port D Clock Gating Control */
#define SYSCON_RCGC2_GPIOE (1 << 4) /* Bit 4: Port E Clock Gating Control */
#define SYSCON_RCGC2_GPIOF (1 << 5) /* Bit 5: Port F Clock Gating Control */
#define SYSCON_RCGC2_UDMA (1 << 13) /* Bit 13: Micro-DMA Clock Gating Control */
#define SYSCON_RCGC2_USB0 (1 << 16) /* Bit 16: USB0 Clock Gating Control */
/* Sleep Mode Clock Gating Control Register 0 */
#define SYSCON_SCGC0_WDT0 (1 << 3) /* Bit 3: WDT0 Clock Gating Control */
#define SYSCON_SCGC0_HIB (1 << 6) /* Bit 6: HIB Clock Gating Control */
#define SYSCON_SCGC0_ADC0 (1 << 16) /* Bit 16: ADC0 Clock Gating Control */
#define SYSCON_SCGC0_ADC1 (1 << 17) /* Bit 17: ADC1 Clock Gating Control */
#define SYSCON_SCGC0_CAN0 (1 << 24) /* Bit 24: CAN0 Clock Gating Control */
#define SYSCON_SCGC0_WDT1 (1 << 28) /* Bit 28: WDT1 Clock Gating Control */
/* Sleep Mode Clock Gating Control Register 1 */
#define SYSCON_SCGC1_UART0 (1 << 0) /* Bit 0: UART0 Clock Gating Control */
#define SYSCON_SCGC1_UART1 (1 << 1) /* Bit 1: UART1 Clock Gating Control */
#define SYSCON_SCGC1_UART2 (1 << 2) /* Bit 2: UART2 Clock Gating Control */
#define SYSCON_SCGC1_SSI0 (1 << 4) /* Bit 4: SSI0 Clock Gating Control */
#define SYSCON_SCGC1_SSI1 (1 << 5) /* Bit 5: SSI1 Clock Gating Control */
#define SYSCON_SCGC1_I2C0 (1 << 12) /* Bit 12: I2C0 Clock Gating Control */
#define SYSCON_SCGC1_I2C1 (1 << 14) /* Bit 14: I2C1 Clock Gating Control */
#define SYSCON_SCGC1_TIMER0 (1 << 16) /* Bit 16: Timer 0 Clock Gating Control */
#define SYSCON_SCGC1_TIMER1 (1 << 17) /* Bit 17: Timer 1 Clock Gating Control */
#define SYSCON_SCGC1_TIMER2 (1 << 18) /* Bit 18: Timer 2 Clock Gating Control */
#define SYSCON_SCGC1_TIMER3 (1 << 19) /* Bit 19: Timer 3 Clock Gating Control */
#define SYSCON_SCGC1_COMP0 (1 << 24) /* Bit 24: Analog Comparator 0 Clock Gating */
#define SYSCON_SCGC1_COMP1 (1 << 25) /* Bit 25: Analog Comparator 1 Clock Gating */
/* Sleep Mode Clock Gating Control Register 2 */
#define SYSCON_SCGC2_GPIO(n) (1 << (n))
#define SYSCON_SCGC2_GPIOA (1 << 0) /* Bit 0: Port A Clock Gating Control */
#define SYSCON_SCGC2_GPIOB (1 << 1) /* Bit 1: Port B Clock Gating Control */
#define SYSCON_SCGC2_GPIOC (1 << 2) /* Bit 2: Port C Clock Gating Control */
#define SYSCON_SCGC2_GPIOD (1 << 3) /* Bit 3: Port D Clock Gating Control */
#define SYSCON_SCGC2_GPIOE (1 << 4) /* Bit 4: Port E Clock Gating Control */
#define SYSCON_SCGC2_GPIOF (1 << 5) /* Bit 5: Port F Clock Gating Control */
#define SYSCON_SCGC2_UDMA (1 << 13) /* Bit 13: Micro-DMA Clock Gating Control */
#define SYSCON_SCGC2_USB0 (1 << 16) /* Bit 16: PHY0 Clock Gating Control */
/* Deep Sleep Mode Clock Gating Control Register 0 */
#define SYSCON_DCGC0_WDT0 (1 << 3) /* Bit 3: WDT0 Clock Gating Control */
#define SYSCON_DCGC0_HIB (1 << 6) /* Bit 6: HIB Clock Gating Control */
#define SYSCON_DCGC0_ADC0 (1 << 16) /* Bit 16: ADC0 Clock Gating Control */
#define SYSCON_DCGC0_ADC1 (1 << 17) /* Bit 17: ADC1 Clock Gating Control */
#define SYSCON_DCGC0_CAN0 (1 << 24) /* Bit 24: CAN0 Clock Gating Control */
#define SYSCON_DCGC0_WDT1 (1 << 28) /* Bit 28: WDT1 Clock Gating Control */
/* Deep Sleep Mode Clock Gating Control Register 1 */
#define SYSCON_DCGC1_UART0 (1 << 0) /* Bit 0: UART0 Clock Gating Control */
#define SYSCON_DCGC1_UART1 (1 << 1) /* Bit 1: UART1 Clock Gating Control */
#define SYSCON_DCGC1_UART2 (1 << 2) /* Bit 2: UART2 Clock Gating Control */
#define SYSCON_DCGC1_SSI0 (1 << 4) /* Bit 4: SSI0 Clock Gating Control */
#define SYSCON_DCGC1_SSI1 (1 << 5) /* Bit 5: SSI1 Clock Gating Control */
#define SYSCON_DCGC1_I2C0 (1 << 12) /* Bit 12: I2C0 Clock Gating Control */
#define SYSCON_DCGC1_I2C1 (1 << 14) /* Bit 14: I2C1 Clock Gating Control */
#define SYSCON_DCGC1_TIMER0 (1 << 16) /* Bit 16: Timer 0 Clock Gating Control */
#define SYSCON_DCGC1_TIMER1 (1 << 17) /* Bit 17: Timer 1 Clock Gating Control */
#define SYSCON_DCGC1_TIMER2 (1 << 18) /* Bit 18: Timer 2 Clock Gating Control */
#define SYSCON_DCGC1_TIMER3 (1 << 19) /* Bit 19: Timer 3 Clock Gating Control */
#define SYSCON_DCGC1_COMP0 (1 << 24) /* Bit 24: Analog Comparator 0 Clock Gating */
#define SYSCON_DCGC1_COMP1 (1 << 25) /* Bit 25: Analog Comparator 1 Clock Gating */
/* Deep Sleep Mode Clock Gating Control Register 2 */
#define SYSCON_DCGC2_GPIO(n) (1 << (n))
#define SYSCON_DCGC2_GPIOA (1 << 0) /* Bit 0: Port A Clock Gating Control */
#define SYSCON_DCGC2_GPIOB (1 << 1) /* Bit 1: Port B Clock Gating Control */
#define SYSCON_DCGC2_GPIOC (1 << 2) /* Bit 2: Port C Clock Gating Control */
#define SYSCON_DCGC2_GPIOD (1 << 3) /* Bit 3: Port D Clock Gating Control */
#define SYSCON_DCGC2_GPIOE (1 << 4) /* Bit 4: Port E Clock Gating Control */
#define SYSCON_DCGC2_GPIOF (1 << 5) /* Bit 5: Port F Clock Gating Control */
#define SYSCON_DCGC2_UDMA (1 << 13) /* Bit 13: Micro-DMA Clock Gating Control */
#define SYSCON_DCGC2_USB0 (1 << 16) /* Bit 16: PHY0 Clock Gating Control */
/* Device Capabilities */
#define TIVA_SYSCON_DC9_ADC0DC0 (1 << 0) /* Bit 0: ADC0 DC0 Present */
#define TIVA_SYSCON_DC9_ADC0DC1 (1 << 1) /* Bit 1: ADC0 DC1 Present */
#define TIVA_SYSCON_DC9_ADC0DC2 (1 << 2) /* Bit 2: ADC0 DC2 Present */
#define TIVA_SYSCON_DC9_ADC0DC3 (1 << 3) /* Bit 3: ADC0 DC3 Present */
#define TIVA_SYSCON_DC9_ADC0DC4 (1 << 4) /* Bit 4: ADC0 DC4 Present */
#define TIVA_SYSCON_DC9_ADC0DC5 (1 << 5) /* Bit 5: ADC0 DC5 Present */
#define TIVA_SYSCON_DC9_ADC0DC6 (1 << 6) /* Bit 6: ADC0 DC6 Present */
#define TIVA_SYSCON_DC9_ADC0DC7 (1 << 7) /* Bit 7: ADC0 DC7 Present */
#define TIVA_SYSCON_DC9_ADC1DC0 (1 << 16) /* Bit 16: ADC1 DC0 Present */
#define TIVA_SYSCON_DC9_ADC1DC1 (1 << 17) /* Bit 17: ADC1 DC1 Present */
#define TIVA_SYSCON_DC9_ADC1DC2 (1 << 18) /* Bit 18: ADC1 DC2 Present */
#define TIVA_SYSCON_DC9_ADC1DC3 (1 << 19) /* Bit 19: ADC1 DC3 Present */
#define TIVA_SYSCON_DC9_ADC1DC4 (1 << 20) /* Bit 20: ADC1 DC4 Present */
#define TIVA_SYSCON_DC9_ADC1DC5 (1 << 21) /* Bit 21: ADC1 DC5 Present */
#define TIVA_SYSCON_DC9_ADC1DC6 (1 << 22) /* Bit 22: ADC1 DC6 Present */
#define TIVA_SYSCON_DC9_ADC1DC7 (1 << 23) /* Bit 23: ADC1 DC7 Present */
/* Non-Volatile Memory Information */
#define TIVA_SYSCON_NVMSTAT_FWB (1 << 0) /* Bit 0: 32 Word Flash Write Buffer Available */
/********************************************************************************************
* Public Types
********************************************************************************************/
/********************************************************************************************
* Public Data
********************************************************************************************/
/********************************************************************************************
* Public Functions
********************************************************************************************/
#endif /* __ARCH_ARM_SRC_TIVA_CHIP_LM4F_SYSCONTROL_H */
| 49,026 |
304 | /*
* Copyright 2019-2021 CloudNetService team & 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 de.dytanic.cloudnet.ext.cloudflare.listener;
import de.dytanic.cloudnet.common.language.LanguageManager;
import de.dytanic.cloudnet.driver.CloudNetDriver;
import de.dytanic.cloudnet.driver.event.EventListener;
import de.dytanic.cloudnet.event.service.CloudServicePostStartEvent;
import de.dytanic.cloudnet.event.service.CloudServicePostStopEvent;
import de.dytanic.cloudnet.ext.cloudflare.CloudNetCloudflareModule;
import de.dytanic.cloudnet.ext.cloudflare.CloudflareConfigurationEntry;
import de.dytanic.cloudnet.ext.cloudflare.CloudflareGroupConfiguration;
import de.dytanic.cloudnet.ext.cloudflare.cloudflare.CloudFlareAPI;
import de.dytanic.cloudnet.ext.cloudflare.cloudflare.DnsRecordDetail;
import de.dytanic.cloudnet.ext.cloudflare.dns.SRVRecord;
import de.dytanic.cloudnet.service.ICloudService;
import java.util.Arrays;
import java.util.function.BiConsumer;
public final class CloudflareStartAndStopListener {
private final CloudFlareAPI cloudFlareAPI;
public CloudflareStartAndStopListener(CloudFlareAPI cloudFlareAPI) {
this.cloudFlareAPI = cloudFlareAPI;
}
@EventListener
public void handle(CloudServicePostStartEvent event) {
this.handle0(event.getCloudService(), (entry, configuration) -> {
DnsRecordDetail recordDetail = this.cloudFlareAPI.createRecord(
event.getCloudService().getServiceId().getUniqueId(),
entry,
SRVRecord.forConfiguration(entry, configuration, event.getCloudService().getServiceConfiguration().getPort())
);
if (recordDetail != null) {
CloudNetDriver.getInstance().getLogger()
.info(LanguageManager.getMessage("module-cloudflare-create-dns-record-for-service")
.replace("%service%", event.getCloudService().getServiceId().getName())
.replace("%domain%", entry.getDomainName())
.replace("%recordId%", recordDetail.getId())
);
}
});
}
@EventListener
public void handle(CloudServicePostStopEvent event) {
this.handle0(event.getCloudService(), (entry, configuration) -> {
for (DnsRecordDetail detail : this.cloudFlareAPI.deleteAllRecords(event.getCloudService())) {
CloudNetDriver.getInstance().getLogger()
.info(LanguageManager.getMessage("module-cloudflare-delete-dns-record-for-service")
.replace("%service%", event.getCloudService().getServiceId().getName())
.replace("%domain%", entry.getDomainName())
.replace("%recordId%", detail.getId())
);
}
});
}
private void handle0(ICloudService cloudService,
BiConsumer<CloudflareConfigurationEntry, CloudflareGroupConfiguration> handler) {
for (CloudflareConfigurationEntry entry : CloudNetCloudflareModule.getInstance().getCloudflareConfiguration()
.getEntries()) {
if (entry != null && entry.isEnabled() && entry.getGroups() != null && !entry.getGroups().isEmpty()) {
for (CloudflareGroupConfiguration groupConfiguration : entry.getGroups()) {
if (groupConfiguration != null
&& Arrays.binarySearch(cloudService.getServiceConfiguration().getGroups(), groupConfiguration.getName())
>= 0) {
handler.accept(entry, groupConfiguration);
}
}
}
}
}
}
| 1,349 |
3,457 | <reponame>shareq2005/CarND-MPC-Project
#include <Eigen/Core>
#include <iostream>
using namespace Eigen;
using namespace std;
template<typename Derived>
Eigen::VectorBlock<Derived, 2>
firstTwo(MatrixBase<Derived>& v)
{
return Eigen::VectorBlock<Derived, 2>(v.derived(), 0);
}
template<typename Derived>
const Eigen::VectorBlock<const Derived, 2>
firstTwo(const MatrixBase<Derived>& v)
{
return Eigen::VectorBlock<const Derived, 2>(v.derived(), 0);
}
int main(int, char**)
{
Matrix<int,1,6> v; v << 1,2,3,4,5,6;
cout << firstTwo(4*v) << endl; // calls the const version
firstTwo(v) *= 2; // calls the non-const version
cout << "Now the vector v is:" << endl << v << endl;
return 0;
}
| 283 |
319 | /**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.math.geometry.point;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import Jama.Matrix;
/**
* Simple concrete implementation of a three dimensional point.
*
* @author <NAME>
*/
public class Point3dImpl implements Point3d, Cloneable {
/**
* The x-ordinate
*/
public double x;
/**
* The y-ordinate
*/
public double y;
/**
* The z-ordinate
*/
public double z;
/**
* Construct a Point3dImpl with the given (x, y, z) coordinates
*
* @param x
* x-ordinate
* @param y
* y-ordinate
* @param z
* z-ordinate
*/
public Point3dImpl(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
/**
* Construct a Point3dImpl with the given (x, y, z) coordinates packed into
* an array
*
* @param array
* the coordinates ([x, y, z])
*/
public Point3dImpl(double[] array)
{
this.x = array[0];
this.y = array[1];
this.z = array[2];
}
/**
* Construct a Point3dImpl with the (x,y,z) coordinates given via another
* point.
*
* @param p
* The point to copy from.
*/
public Point3dImpl(Point3d p)
{
this.copyFrom(p);
}
/**
* Construct a Point3dImpl at the origin.
*/
public Point3dImpl()
{
// do nothing
}
@Override
public double getX() {
return x;
}
@Override
public void setX(double x) {
this.x = x;
}
@Override
public double getY() {
return y;
}
@Override
public void setY(double y) {
this.y = y;
}
@Override
public double getZ() {
return z;
}
@Override
public void setZ(double z) {
this.z = z;
}
@Override
public void copyFrom(Point3d p)
{
this.x = p.getX();
this.y = p.getY();
this.z = p.getZ();
}
@Override
public String toString() {
return "(" + x + "," + y + "," + z + ")";
}
@Override
public Point3dImpl clone() {
Point3dImpl clone;
try {
clone = (Point3dImpl) super.clone();
} catch (final CloneNotSupportedException e) {
return null;
}
return clone;
}
@Override
public Double getOrdinate(int dimension) {
if (dimension == 0)
return x;
if (dimension == 1)
return y;
return z;
}
@Override
public int getDimensions() {
return 3;
}
@Override
public void translate(double x, double y, double z) {
this.x += x;
this.y += y;
this.z += z;
}
@Override
public void translate(Point3d v) {
this.x += v.getX();
this.y += v.getY();
this.z += v.getZ();
}
@Override
public Point3dImpl transform(Matrix transform) {
if (transform.getRowDimension() == 4) {
double xt = transform.get(0, 0) * getX() + transform.get(0, 1) * getY() + transform.get(0, 2) * getZ()
+ transform.get(0, 3);
double yt = transform.get(1, 0) * getX() + transform.get(1, 1) * getY() + transform.get(1, 2) * getZ()
+ transform.get(1, 3);
double zt = transform.get(2, 0) * getX() + transform.get(2, 1) * getY() + transform.get(2, 2) * getZ()
+ transform.get(2, 3);
final double ft = transform.get(3, 0) * getX() + transform.get(3, 1) * getY() + transform.get(3, 2) * getZ()
+ transform.get(3, 3);
xt /= ft;
yt /= ft;
zt /= ft;
return new Point3dImpl(xt, yt, zt);
}
throw new IllegalArgumentException("Transform matrix has unexpected size");
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Point3d))
return false;
final Point3d p = (Point3d) o;
return p.getX() == this.x && p.getY() == this.y && p.getZ() == this.getZ();
}
@Override
public int hashCode()
{
return toString().hashCode();
}
@Override
public Point3d minus(Point3d a) {
return new Point3dImpl(this.x - a.getX(), this.y - a.getY(), this.z - a.getZ());
}
@Override
public void readASCII(Scanner in) throws IOException {
x = in.nextDouble();
y = in.nextDouble();
z = in.nextDouble();
}
@Override
public String asciiHeader() {
return "Point3d";
}
@Override
public void readBinary(DataInput in) throws IOException {
x = in.readDouble();
y = in.readDouble();
z = in.readDouble();
}
@Override
public byte[] binaryHeader() {
return "PT3D".getBytes();
}
@Override
public void writeASCII(PrintWriter out) throws IOException {
out.format("%f %f %f", x, y, z);
}
@Override
public void writeBinary(DataOutput out) throws IOException {
out.writeDouble(x);
out.writeDouble(y);
out.writeDouble(z);
}
@Override
public Point3dImpl copy() {
return clone();
}
/**
* Create a random point in ([0..1], [0..1], [0..1]).
*
* @return random point.
*/
public static Point3d createRandomPoint() {
return new Point3dImpl(Math.random(), Math.random(), Math.random());
}
@Override
public void setOrdinate(int dimension, Number value) {
if (dimension == 0)
x = value.floatValue();
if (dimension == 1)
y = value.floatValue();
if (dimension == 2)
z = value.floatValue();
}
}
| 2,467 |
345 | <reponame>zhenbzha/Azure-DataFactory
{
"name": "HDInsightLinkedService",
"properties": {
"type": "HDInsight",
"typeProperties": {
"clusterUri": "https://<hdinsightclustername>.azurehdinsight.net/",
"userName": "<hdiusername>",
"location": "<hdiregion>",
"password": "<<PASSWORD>>",
"linkedServiceName": "<HDInsightStorageLinkedServiceName>"
}
}
} | 169 |
515 | /*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#ifndef CTKEABLACKLIST_H
#define CTKEABLACKLIST_H
/**
* This interface represents a simple set that allows to add service references
* and lookup whether a given reference is in the list. Note that implementations
* of this interface may do additional service reference life-cycle related
* clean-up actions like removing references that point to unregistered services.
*/
template<class Impl>
struct ctkEABlackList
{
/**
* Add a service to this blacklist.
*
* @param ref The reference of the service that is blacklisted
*/
void add(const ctkServiceReference& ref)
{
static_cast<Impl*>(this)->add(ref);
}
/**
* Lookup whether a given service is blacklisted.
*
* @param ref The reference of the service
*
* @return <tt>true</tt> in case that the service reference has been blacklisted,
* <tt>false</tt> otherwise.
*/
bool contains(const ctkServiceReference& ref) const
{
return static_cast<const Impl*>(this)->contains(ref);
}
virtual ~ctkEABlackList() {}
};
#endif // CTKEABLACKLIST_H
| 504 |
459 | /*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2021, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
/**
* Created by IntelliJ IDEA.
* User: <NAME>
* Date: 08/08/12
* Time: 15:27
*/
package org.chocosolver.solver.search.strategy.strategy;
import org.chocosolver.solver.search.strategy.assignments.DecisionOperatorFactory;
import org.chocosolver.solver.search.strategy.assignments.GraphDecisionOperator;
import org.chocosolver.solver.search.strategy.decision.GraphDecision;
import org.chocosolver.solver.search.strategy.selectors.values.graph.priority.GraphEdgesOnly;
import org.chocosolver.solver.variables.GraphVar;
import org.chocosolver.util.objects.setDataStructures.ISet;
public class GraphCostBasedSearch extends GraphStrategy {
//***********************************************************************************
// CONSTRUCTORS
//***********************************************************************************
// heuristics
public static final int LEX = 0;
public static final int MIN_P_DEGREE = 1;
public static final int MAX_P_DEGREE = 2;
public static final int MIN_M_DEGREE = 3;
public static final int MAX_M_DEGREE = 4;
public static final int MIN_DELTA_DEGREE = 5;
public static final int MAX_DELTA_DEGREE = 6;
public static final int MIN_COST = 7;
public static final int MAX_COST = 8;
// variables
private int n;
private int mode;
private int[][] costs;
private GraphDecisionOperator decisionType;
private int from, to;
private int value;
private boolean useLC;
private int lastFrom = -1;
private GraphVar g;
/**
* Search strategy for graphs
*
* @param graphVar varriable to branch on
*/
public GraphCostBasedSearch(GraphVar graphVar) {
this(graphVar, null);
}
/**
* Search strategy for graphs
*
* @param graphVar varriable to branch on
* @param costMatrix can be null
*/
public GraphCostBasedSearch(GraphVar graphVar, int[][] costMatrix) {
super(new GraphVar[] {graphVar}, null, new GraphEdgesOnly(),null, null, true);
costs = costMatrix;
this.g = graphVar;
n = g.getNbMaxNodes();
}
/**
* Configures the search
*
* @param policy way to select arcs
*/
public GraphCostBasedSearch configure(int policy) {
return configure(policy, true);
}
/**
* Configures the search
*
* @param policy way to select arcs
* @param enforce true if a decision is an arc enforcing
* false if a decision is an arc removal
*/
public GraphCostBasedSearch configure(int policy, boolean enforce) {
if (enforce) {
decisionType = DecisionOperatorFactory.makeGraphEnforce();
} else {
decisionType = DecisionOperatorFactory.makeGraphRemove();
}
mode = policy;
return this;
}
public GraphCostBasedSearch useLastConflict() {
useLC = true;
return this;
}
@Override
public GraphDecision getDecision() {
if (g.isInstantiated()) {
return null;
}
computeNextArc();
GraphDecision dec = g.getModel().getSolver().getDecisionPath().makeGraphEdgeDecision(g, decisionType, from, to);
lastFrom = from;
return dec;
}
private void computeNextArc() {
to = -1;
from = -1;
if (useLC && lastFrom != -1) {
evaluateNeighbors(lastFrom);
if (to != -1) {
return;
}
}
for (int i = 0; i < n; i++) {
if (evaluateNeighbors(i)) {
return;
}
}
if (to == -1) {
throw new UnsupportedOperationException();
}
}
private boolean evaluateNeighbors(int i) {
ISet set = g.getPotentialSuccessorsOf(i);
if (set.size() == g.getMandatorySuccessorsOf(i).size()) {
return false;
}
for (int j : set) {
if (!g.getMandatorySuccessorsOf(i).contains(j)) {
int v = -1;
switch (mode) {
case LEX:
from = i;
to = j;
return true;
case MIN_P_DEGREE:
case MAX_P_DEGREE:
v = g.getPotentialSuccessorsOf(i).size()
+ g.getPotentialPredecessorOf(j).size();
break;
case MIN_M_DEGREE:
case MAX_M_DEGREE:
v = g.getMandatorySuccessorsOf(i).size()
+ g.getMandatoryPredecessorsOf(j).size();
break;
case MIN_DELTA_DEGREE:
case MAX_DELTA_DEGREE:
v = g.getPotentialSuccessorsOf(i).size()
+ g.getPotentialPredecessorOf(j).size()
- g.getMandatorySuccessorsOf(i).size()
- g.getMandatoryPredecessorsOf(j).size();
break;
case MIN_COST:
case MAX_COST:
v = costs[i][j];
break;
default:
throw new UnsupportedOperationException("mode " + mode + " does not exist");
}
if (select(v)) {
value = v;
from = i;
to = j;
}
}
}
return false;
}
private boolean select(double v) {
return (from == -1 || (v < value && isMinOrIn(mode)) || (v > value && !isMinOrIn(mode)));
}
private static boolean isMinOrIn(int policy) {
return (policy % 2 == 1);
}
}
| 2,906 |
1,350 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.eventgrid.models;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Schema of the Data property of an EventGridEvent for a device telemetry
* event (DeviceTelemetry).
*/
public class DeviceTelemetryEventProperties {
/**
* The content of the message from the device.
*/
@JsonProperty(value = "body")
private Object body;
/**
* Application properties are user-defined strings that can be added to the
* message. These fields are optional.
*/
@JsonProperty(value = "properties")
private Map<String, String> properties;
/**
* System properties help identify contents and source of the messages.
*/
@JsonProperty(value = "systemProperties")
private Map<String, String> systemProperties;
/**
* Get the content of the message from the device.
*
* @return the body value
*/
public Object body() {
return this.body;
}
/**
* Set the content of the message from the device.
*
* @param body the body value to set
* @return the DeviceTelemetryEventProperties object itself.
*/
public DeviceTelemetryEventProperties withBody(Object body) {
this.body = body;
return this;
}
/**
* Get application properties are user-defined strings that can be added to the message. These fields are optional.
*
* @return the properties value
*/
public Map<String, String> properties() {
return this.properties;
}
/**
* Set application properties are user-defined strings that can be added to the message. These fields are optional.
*
* @param properties the properties value to set
* @return the DeviceTelemetryEventProperties object itself.
*/
public DeviceTelemetryEventProperties withProperties(Map<String, String> properties) {
this.properties = properties;
return this;
}
/**
* Get system properties help identify contents and source of the messages.
*
* @return the systemProperties value
*/
public Map<String, String> systemProperties() {
return this.systemProperties;
}
/**
* Set system properties help identify contents and source of the messages.
*
* @param systemProperties the systemProperties value to set
* @return the DeviceTelemetryEventProperties object itself.
*/
public DeviceTelemetryEventProperties withSystemProperties(Map<String, String> systemProperties) {
this.systemProperties = systemProperties;
return this;
}
}
| 935 |
370 | <filename>src/xapian/backends/honey/honey_cursor.h
/** @file honey_cursor.h
* @brief HoneyCursor class
*/
/* Copyright (C) 2017,2018 <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef XAPIAN_INCLUDED_HONEY_CURSOR_H
#define XAPIAN_INCLUDED_HONEY_CURSOR_H
#include "xapian/backends/honey/honey_table.h"
class HoneyCursor {
/** Search for @a key.
*
* If @a key isn't present, the behaviour depends on @a greater_than.
* If it's true, then the cursor will be left on the first key >
* @a key; otherwise it may be left at an unspecified position.
*/
bool do_find(const std::string& key, bool greater_than);
bool do_next();
/** Handle the value part of the (key,value). */
bool next_from_index();
BufferedFile store;
public:
std::string current_key, current_tag;
mutable size_t val_size = 0;
bool current_compressed = false;
mutable CompressionStream comp_stream;
bool is_at_end = false;
mutable std::string last_key;
// File offset to start of index.
off_t root;
// File offset to start of table (zero except for single-file DB).
off_t offset;
// Forward to next constructor form.
explicit HoneyCursor(const HoneyTable* table)
: store(table->store),
comp_stream(Z_DEFAULT_STRATEGY),
root(table->get_root()),
offset(table->get_offset())
{
store.set_pos(offset); // FIXME root
}
HoneyCursor(const HoneyCursor& o)
: store(o.store),
current_key(o.current_key),
current_tag(o.current_tag), // FIXME really copy?
val_size(o.val_size),
current_compressed(o.current_compressed),
comp_stream(Z_DEFAULT_STRATEGY),
is_at_end(o.is_at_end),
last_key(o.last_key),
root(o.root),
offset(o.offset)
{
store.set_pos(o.store.get_pos());
}
/** Position cursor on the dummy empty key.
*
* Calling next() after this moves the cursor to the first entry.
*/
void rewind() {
store.set_pos(offset); // FIXME root
current_key = last_key = std::string();
is_at_end = false;
val_size = 0;
}
void to_end() { is_at_end = true; }
bool after_end() const { return is_at_end; }
bool next() {
if (store.was_forced_closed()) {
HoneyTable::throw_database_closed();
}
return do_next();
}
bool read_tag(bool keep_compressed = false);
bool find_exact(const std::string& key) {
return do_find(key, false);
}
bool find_entry_ge(const std::string& key) {
return do_find(key, true);
}
/** Move to the item before the current one.
*
* If the cursor is after_end(), this moves to the last item.
*
* If the cursor is at the start of the table (on the empty key), do
* nothing and return false, otherwise return true.
*
* This method may not be particularly efficient.
*/
bool prev();
};
class MutableHoneyCursor : public HoneyCursor {
HoneyTable* table;
public:
MutableHoneyCursor(HoneyTable* table_)
: HoneyCursor(table_),
table(table_)
{ }
bool del() {
Assert(!is_at_end);
std::string key_to_del = current_key;
bool res = next();
table->del(key_to_del);
return res;
}
};
#endif // XAPIAN_INCLUDED_HONEY_CURSOR_H
| 1,434 |
571 | package me.devsaki.hentoid.viewholders;
import android.view.View;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.adapters.ItemAdapter;
import com.mikepenz.fastadapter.items.AbstractItem;
import org.jetbrains.annotations.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.annotation.Nonnull;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.json.GithubRelease;
import static androidx.core.view.ViewCompat.requireViewById;
public class GitHubReleaseItem extends AbstractItem<GitHubReleaseItem.ReleaseViewHolder> {
private static final String NOT_A_DIGIT = "[^\\d]";
private final String tagName;
private final String name;
private final String description;
private final Date creationDate;
private final String apkUrl;
public GitHubReleaseItem(GithubRelease releaseStruct) {
tagName = releaseStruct.tagName.replace("v", "");
name = releaseStruct.name;
description = releaseStruct.body;
creationDate = releaseStruct.creationDate;
apkUrl = releaseStruct.getApkAssetUrl();
}
public String getTagName() {
return tagName;
}
public String getApkUrl() {
return apkUrl;
}
public boolean isTagPrior(@Nonnull String tagName) {
return getIntFromTagName(this.tagName) <= getIntFromTagName(tagName);
}
private static int getIntFromTagName(@Nonnull String tagName) {
int result = 0;
String[] parts = tagName.split("\\.");
if (parts.length > 0)
result = 10000 * Integer.parseInt(parts[0].replaceAll(NOT_A_DIGIT, ""));
if (parts.length > 1)
result += 100 * Integer.parseInt(parts[1].replaceAll(NOT_A_DIGIT, ""));
if (parts.length > 2) result += Integer.parseInt(parts[2].replaceAll(NOT_A_DIGIT, ""));
return result;
}
@NotNull
@Override
public ReleaseViewHolder getViewHolder(@NotNull View view) {
return new ReleaseViewHolder(view);
}
@Override
public int getLayoutRes() {
return R.layout.item_changelog;
}
@Override
public int getType() {
return R.id.github_release;
}
static class ReleaseViewHolder extends FastAdapter.ViewHolder<GitHubReleaseItem> {
private final TextView title;
private final ItemAdapter<GitHubReleaseDescItem> itemAdapter = new ItemAdapter<>();
ReleaseViewHolder(View view) {
super(view);
title = requireViewById(view, R.id.changelogReleaseTitle);
FastAdapter<GitHubReleaseDescItem> releaseDescriptionAdapter = FastAdapter.with(itemAdapter);
RecyclerView releasedDescription = requireViewById(view, R.id.changelogReleaseDescription);
releasedDescription.setAdapter(releaseDescriptionAdapter);
}
@Override
public void bindView(@NotNull GitHubReleaseItem item, @NotNull List<?> list) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
setTitle(item.name + " (" + dateFormat.format(item.creationDate) + ")");
clearContent();
// Parse content and add lines to the description
for (String s : item.description.split("\\r\\n")) { // TODO - refactor this code with its copy in UpdateSuccessDialogFragment
s = s.trim();
if (s.startsWith("-")) addListContent(s);
else addDescContent(s);
}
}
public void setTitle(String title) {
this.title.setText(title);
}
void clearContent() {
itemAdapter.clear();
}
void addDescContent(String text) {
itemAdapter.add(new GitHubReleaseDescItem(text, GitHubReleaseDescItem.Type.DESCRIPTION));
}
void addListContent(String text) {
itemAdapter.add(new GitHubReleaseDescItem(text, GitHubReleaseDescItem.Type.LIST_ITEM));
}
@Override
public void unbindView(@NotNull GitHubReleaseItem item) {
// No specific behaviour to implement
}
}
}
| 1,696 |
47,880 | /*
* Copyright (C) 2013 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.CheckForNull;
/**
* Exception thrown upon the failure of a <a
* href="https://github.com/google/guava/wiki/ConditionalFailuresExplained">verification check</a>,
* including those performed by the convenience methods of the {@link Verify} class.
*
* @since 17.0
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
public class VerifyException extends RuntimeException {
/** Constructs a {@code VerifyException} with no message. */
public VerifyException() {}
/** Constructs a {@code VerifyException} with the message {@code message}. */
public VerifyException(@CheckForNull String message) {
super(message);
}
/**
* Constructs a {@code VerifyException} with the cause {@code cause} and a message that is {@code
* null} if {@code cause} is null, and {@code cause.toString()} otherwise.
*
* @since 19.0
*/
public VerifyException(@CheckForNull Throwable cause) {
super(cause);
}
/**
* Constructs a {@code VerifyException} with the message {@code message} and the cause {@code
* cause}.
*
* @since 19.0
*/
public VerifyException(@CheckForNull String message, @CheckForNull Throwable cause) {
super(message, cause);
}
}
| 549 |
6,289 | <reponame>imownbey/Detox
//
// Bridging-Header.h
// Detox
//
// Created by <NAME> (Wix) on 7/11/19.
// Copyright © 2019 Wix. All rights reserved.
//
#import "UIApplication+MockedSharedApplication.h"
| 82 |
602 | <reponame>maheshrajamani/stargate
/*
* Copyright The Stargate Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.stargate.graphql.schema.graphqlfirst.processor;
import io.stargate.db.schema.CollectionIndexingType;
import io.stargate.db.schema.ImmutableCollectionIndexingType;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public enum IndexTarget {
KEYS(ImmutableCollectionIndexingType.builder().indexKeys(true).build()),
VALUES(ImmutableCollectionIndexingType.builder().indexValues(true).build()),
ENTRIES(ImmutableCollectionIndexingType.builder().indexEntries(true).build()),
FULL(ImmutableCollectionIndexingType.builder().indexFull(true).build()),
;
private static final Map<CollectionIndexingType, IndexTarget> BY_TYPE =
Arrays.stream(values())
.collect(Collectors.toMap(IndexTarget::toIndexingType, Function.identity()));
private final CollectionIndexingType indexingType;
IndexTarget(CollectionIndexingType indexingType) {
this.indexingType = indexingType;
}
public CollectionIndexingType toIndexingType() {
return indexingType;
}
public static IndexTarget fromIndexingType(CollectionIndexingType indexingType) {
IndexTarget value = BY_TYPE.get(indexingType);
if (value == null) {
throw new IllegalArgumentException("Invalid value " + indexingType);
}
return value;
}
}
| 581 |
588 | <reponame>fmilano/CppMicroServices
/*=============================================================================
Library: CppMicroServices
Copyright (c) The CppMicroServices developers. See the COPYRIGHT
file at the top-level directory of this distribution and at
https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT .
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
#ifndef CPPMICROSERVICES_SERVICELISTENERS_H
#define CPPMICROSERVICES_SERVICELISTENERS_H
#include "cppmicroservices/GlobalConfig.h"
#include "cppmicroservices/detail/Threads.h"
#include "ServiceListenerEntry.h"
#include <list>
#include <mutex>
#include <set>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
namespace cppmicroservices {
class CoreBundleContext;
class BundleContextPrivate;
/**
* Here we handle all listeners that bundles have registered.
*
*/
class ServiceListeners : private detail::MultiThreaded<>
{
public:
using BundleListenerEntry = std::tuple<BundleListener, void*>;
using BundleListenerMap = std::unordered_map<
std::shared_ptr<BundleContextPrivate>,
std::unordered_map<ListenerTokenId, BundleListenerEntry>>;
struct : public MultiThreaded<>
{
BundleListenerMap value;
} bundleListenerMap;
using CacheType =
std::unordered_map<std::string, std::set<ServiceListenerEntry>>;
using ServiceListenerEntries = std::unordered_set<ServiceListenerEntry>;
using FrameworkListenerEntry = std::tuple<FrameworkListener, void*>;
using FrameworkListenerMap = std::unordered_map<
std::shared_ptr<BundleContextPrivate>,
std::unordered_map<ListenerTokenId, FrameworkListenerEntry>>;
private:
std::atomic<uint64_t> listenerId;
struct : public MultiThreaded<>
{
FrameworkListenerMap value;
} frameworkListenerMap;
std::vector<std::string> hashedServiceKeys;
static const int OBJECTCLASS_IX = 0;
static const int SERVICE_ID_IX = 1;
/* Service listeners with complicated or empty filters */
std::list<ServiceListenerEntry> complicatedListeners;
/* Service listeners with "simple" filters are cached. */
CacheType cache[2];
ServiceListenerEntries serviceSet;
CoreBundleContext* coreCtx;
public:
ServiceListeners(CoreBundleContext* coreCtx);
void Clear();
/**
* Add a new service listener. If an old one exists, and it has the
* same owning bundle, the old listener is removed first.
*
* @param context The bundle context adding this listener.
* @param listener The service listener to add.
* @param data Additional data to distinguish ServiceListener objects.
* @param filter An LDAP filter string to check when a service is modified.
* @returns a ListenerToken object that corresponds to the listener.
* @exception org.osgi.framework.InvalidSyntaxException
* If the filter is not a correct LDAP expression.
*/
ListenerToken AddServiceListener(
const std::shared_ptr<BundleContextPrivate>& context,
const ServiceListener& listener,
void* data,
const std::string& filter);
/**
* Remove service listener from current framework. Silently ignore
* if listener doesn't exist.
*
* @param context The bundle context who wants to remove listener.
* @param tokenId The ListenerTokenId associated with the listener.
* @param listener Object to remove.
* @param data Additional data to distinguish ServiceListener objects.
*/
void RemoveServiceListener(
const std::shared_ptr<BundleContextPrivate>& context,
ListenerTokenId tokenId,
const ServiceListener& listener,
void* data);
/**
* Add a new bundle listener.
*
* @param context The bundle context adding this listener.
* @param listener The bundle listener to add.
* @param data Additional data to distinguish BundleListener objects.
* @returns a ListenerToken object that corresponds to the listener.
*/
ListenerToken AddBundleListener(
const std::shared_ptr<BundleContextPrivate>& context,
const BundleListener& listener,
void* data);
/**
* Remove bundle listener from current framework. If listener doesn't
* exist, this method does nothing.
*
* @param context The bundle context who wants to remove listener.
* @param listener Object to remove.
* @param data Additional data to distinguish BundleListener objects.
*/
void RemoveBundleListener(
const std::shared_ptr<BundleContextPrivate>& context,
const BundleListener& listener,
void* data);
/**
* Add a new framework listener.
*
* @param context The bundle context adding this listener.
* @param listener The framework listener to add.
* @param data Additional data to distinguish FrameworkListener objects.
* @returns a ListenerToken object that corresponds to the listener.
*/
ListenerToken AddFrameworkListener(
const std::shared_ptr<BundleContextPrivate>& context,
const FrameworkListener& listener,
void* data);
/**
* Remove framework listener from current framework. If listener doesn't
* exist, this method does nothing.
*
* @param context The bundle context who wants to remove listener.
* @param listener Object to remove.
* @param data Additional data to distinguish FrameworkListener objects.
*/
void RemoveFrameworkListener(
const std::shared_ptr<BundleContextPrivate>& context,
const FrameworkListener& listener,
void* data);
/**
* Remove either a service, bundle or framework listener from current framework.
* If the token is invalid, this method does nothing.
*
* @param context The bundle context who wants to remove the listener.
* @param token A ListenerToken type object which corresponds to the listener.
*/
void RemoveListener(const std::shared_ptr<BundleContextPrivate>& context,
ListenerToken token);
void SendFrameworkEvent(const FrameworkEvent& evt);
void BundleChanged(const BundleEvent& evt);
/**
* Remove all listener registered by a bundle in the current framework.
*
* @param context Bundle context which listeners we want to remove.
*/
void RemoveAllListeners(const std::shared_ptr<BundleContextPrivate>& context);
/**
* Notify hooks that a bundle is about to be stopped
*
* @param context Bundle context which listeners are about to be removed.
*/
void HooksBundleStopped(const std::shared_ptr<BundleContextPrivate>& context);
/**
* Receive notification that a service has had a change occur in its lifecycle.
*
* @see org.osgi.framework.ServiceListener#serviceChanged
*/
void ServiceChanged(ServiceListenerEntries& receivers,
const ServiceEvent& evt,
ServiceListenerEntries& matchBefore);
void ServiceChanged(ServiceListenerEntries& receivers,
const ServiceEvent& evt);
/**
*
*
*/
void GetMatchingServiceListeners(const ServiceEvent& evt,
ServiceListenerEntries& listeners);
std::vector<ServiceListenerHook::ListenerInfo> GetListenerInfoCollection()
const;
private:
/**
* Factory method that returns an unique ListenerToken object.
* Called by methods which add listeners.
*/
ListenerToken MakeListenerToken();
/**
* Remove all references to a service listener from the service listener
* cache.
*/
void RemoveFromCache_unlocked(const ServiceListenerEntry& sle);
/**
* Checks if the specified service listener's filter is simple enough
* to cache.
*/
void CheckSimple_unlocked(const ServiceListenerEntry& sle);
void AddToSet_unlocked(ServiceListenerEntries& set,
const ServiceListenerEntries& receivers,
int cache_ix,
const std::string& val);
};
}
#endif // CPPMICROSERVICES_SERVICELISTENERS_H
| 2,501 |
679 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
package complex.bean;
// import complexlib.ComplexTestCase;
import com.sun.star.lang.XMultiServiceFactory;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import com.sun.star.comp.beans.OOoBean;
import com.sun.star.uno.UnoRuntime;
import java.awt.*;
// import org.junit.After;
import org.junit.AfterClass;
// import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openoffice.test.OfficeConnection;
import static org.junit.Assert.*;
class PrivateLocalOfficeConnection extends com.sun.star.comp.beans.LocalOfficeConnection
{
public PrivateLocalOfficeConnection(com.sun.star.uno.XComponentContext xContext)
{
super(xContext);
}
}
public class OOoBeanTest
{
// public String[] getTestMethodNames()
// {
// // TODO think about trigger of sub-tests from outside
// return new String[]
// {
// "test1",
// "test2",
// "test3",
// "test4",
// "test5",
// "test6",
// "test6a",
// "test7",
// "test8"
// };
// }
/** For X-Windows we need to prolong the time between painting windows. Because
it takes longer than on Windows.
*/
private int getSleepTime(int time)
{
int ret = time;
if (isWindows() == false)
{
return time * 5;
}
return time;
}
/** If it cannot be determined if we run on Windows then we assume
that we do not.
*/
private boolean isWindows()
{
boolean ret = false;
String os = System.getProperty("os.name");
if (os != null)
{
os = os.trim();
if (os.toLowerCase().indexOf("win") == 0)
{
ret = true;
}
}
return ret;
}
private String getText(OOoBean bean) throws Exception
{
com.sun.star.frame.XModel model = (com.sun.star.frame.XModel)bean.getDocument();
com.sun.star.text.XTextDocument myDoc =
UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class, model);
com.sun.star.text.XText xText = myDoc.getText();
return xText.getString();
}
/** 1.Create a Java frame
* 2.Add OOoBean (no document loaded yet)
* 3.Show frame
* 4.Load document
* @throws Exception
*/
@Test public void test1() throws Exception
{
WriterFrame f = null;
try
{
f = new WriterFrame(100 ,100, 500 ,400, false, connection.getComponentContext());
f.setText("OOoBean test.");
Thread.sleep(1000);
}
finally
{
if (f != null)
{
f.dispose();
}
}
}
/** Sizing, painting
* @throws Exception
*/
@Test public void test2() throws Exception
{
WriterFrame f = null;
ScreenComparer capturer = null;
try
{
f = new WriterFrame(100, 100, 500,500, false, connection.getComponentContext());
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error: Client are of Java frame does not match the UNO window.");
}
capturer = new ScreenComparer(100, 100, 500, 500);
//Minimize Window and back
f.goToStart();
f.pageDown();
Thread.sleep(1000);
for (int i = 0; i < 3; i++)
{
capturer.reset();
capturer.grabOne(f.getClientArea());
f.setExtendedState(Frame.ICONIFIED);
Thread.sleep(getSleepTime(200));
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error: Frame was iconified.");
}
f.setExtendedState(Frame.NORMAL);
Thread.sleep(getSleepTime(200));
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error: Frame size set back to normal after it was iconified.");
}
capturer.grabTwo(f.getClientArea());
if (capturer.compare() == false)
{
fail("Painting error: Minimize (iconify) frame and back to normal size.");
capturer.writeImages();
}
}
//Maximize Window and back to normal
for (int i = 0; i < 3; i++)
{
capturer.reset();
capturer.grabOne(f.getClientArea());
f.setExtendedState(Frame.MAXIMIZED_BOTH);
Thread.sleep(getSleepTime(200));
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error: Frame maximized.");
}
f.setExtendedState(Frame.NORMAL);
Thread.sleep(getSleepTime(200));
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error: Frame set from maximized to normal.");
}
capturer.grabTwo(f.getClientArea());
if (capturer.compare() == false)
{
fail("Painting error: Maximize frame and back to normal size");
capturer.writeImages();
}
}
//move Window top left
capturer.reset();
capturer.grabOne(f.getClientArea());
Rectangle oldPosition = f.getBounds();
f.setBounds(0, 0, oldPosition.width, oldPosition.height);
Thread.sleep(getSleepTime(200));
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error: Frame moved.");
}
capturer.grabTwo(f.getClientArea());
if (capturer.compare() == false)
{
fail("Painting error: Move frame to a different position.");
capturer.writeImages();
}
//move Window down
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int maxY = dim.height - f.getBounds().height;
int curY = 0;
while (curY < maxY)
{
capturer.reset();
capturer.grabOne(f.getClientArea());
oldPosition = f.getBounds();
f.setBounds(0, curY, oldPosition.width, oldPosition.height);
capturer.grabTwo(f.getClientArea());
if (capturer.compare() == false)
{
fail("Painting error: Move frame to a different position.");
capturer.writeImages();
}
curY+= 50;
Thread.sleep(getSleepTime(200));
}
//obscure the window and make it visible again
oldPosition = f.getBounds();
Rectangle pos = new Rectangle(oldPosition.x - 50, oldPosition.y - 50,
oldPosition.width, oldPosition.height);
Frame coverFrame = new Frame();
coverFrame.setBounds(pos);
capturer.reset();
capturer.grabOne(f.getClientArea());
for (int i = 0; i < 3; i++)
{
coverFrame.setVisible(true);
Thread.sleep(getSleepTime(200));
f.toFront();
Thread.sleep(getSleepTime(200));
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error: Frame moved from back to front.");
}
capturer.grabTwo(f.getClientArea());
if (capturer.compare() == false)
{
fail("Painting error: Move frame to back and to front.");
capturer.writeImages();
}
}
coverFrame.dispose();
}
finally
{
if (f != null)
{
f.dispose();
}
}
}
/**
1. Create a OOoBean
2. Load a document
3. Create Frame (do not show yet)
4. Add OOoBean to Frame
5. Show Frame
* @throws Exception
*/
@Test public void test3() throws Exception
{
WriterFrame f = null;
try
{
f = new WriterFrame(100, 100, 500, 300, true, connection.getComponentContext());
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error.");
}
}
finally
{
if (f != null)
{
f.dispose();
}
}
}
/** Test repeated OOoBean.aquireSystemWindow and OOoBean.releaseSystemWindow
* calls.
* @throws Exception
*/
@Test public void test4() throws Exception
{
WriterFrame f = null;
try
{
f = new WriterFrame(100, 100, 500, 300, false, connection.getComponentContext());
OOoBean b = f.getBean();
for (int i = 0; i < 100; i++)
{
b.releaseSystemWindow();
b.aquireSystemWindow();
}
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error.");
}
}
finally
{
if (f != null)
{
f.dispose();
}
if (isWindows() == false)
{
Thread.sleep(10000);
}
}
}
/** Adding and removing the bean to a Java frame multiple times.
* Test painting and sizing.
* @throws Exception
*/
@Test public void test5() throws Exception
{
WriterFrame f = null;
try
{
f = new WriterFrame(100, 100, 500, 400, false, connection.getComponentContext());
f.goToStart();
f.pageDown();
Thread.sleep(1000);
ScreenComparer capturer = new ScreenComparer(100,100,500,400);
capturer.grabOne();
for (int i = 0; i < 100; i++)
{
f.removeOOoBean();
f.addOOoBean();
}
f.goToStart();
f.pageDown();
Thread.sleep(getSleepTime(200));
capturer.grabTwo();
if (capturer.compare() == false)
{
fail("Painting error: adding and removing OOoBean " +
"repeatedly to java.lang.Frame.");
capturer.writeImages();
}
if (f.checkUnoFramePosition() == false)
{
fail("Sizing error.");
}
}
finally
{
if (f != null)
{
f.dispose();
}
if (isWindows() == false)
{
Thread.sleep(10000);
}
}
}
/** Test focus (i49454). After repeatedly adding and removing the bean to a window
* it should still be possible to enter text in the window. This does not
* work all the time on Windows. This is probably a timing problem. When using
* Thread.sleep (position #1) then it should work.
* @throws Exception
*/
@Test public void test6() throws Exception
{
for (int j = 0; j < 10; j++)
{
final OOoBean bean = new OOoBean(new PrivateLocalOfficeConnection(connection.getComponentContext()));
java.awt.Frame frame = null;
bean.setOOoCallTimeOut(10000);
try {
frame = new java.awt.Frame("OpenOffice.org Demo");
frame.add(bean, BorderLayout.CENTER);
frame.pack();
frame.setSize(600,300);
frame.show();
bean.loadFromURL("private:factory/swriter", null);
// #1
Thread.sleep(1000);
StringBuffer buf = new StringBuffer(1000);
for (int i = 0; i < 1; i++)
{
// Thread.sleep(1000);
bean.releaseSystemWindow();
frame.remove(bean);
// frame.validate();
// Thread.sleep(1000);
frame.add(bean, BorderLayout.CENTER);
bean.aquireSystemWindow();
// frame.validate();
}
if (isWindows() == false)
{
Thread.sleep(5000);
}
Robot roby = new Robot();
roby.keyPress(KeyEvent.VK_H);
roby.keyRelease(KeyEvent.VK_H);
buf.append("h");
String s = getText(bean);
if ( ! s.equals(buf.toString()))
{
fail("Focus error: After removing and adding the bean, the" +
"office window does not receive keyboard input.\n" +
"Try typing in the window, you've got 30s!!! This " +
"test may not work with Linux/Solaris");
Thread.sleep(30000);
break;
}
else
{
Thread.sleep(2000);
}
} finally {
bean.stopOOoConnection();
frame.dispose();
}
}
}
/** Tests focus problem just like test6, but the implementation is a little
* different. The bean is added and removed from within the event dispatch
* thread. Using Thread.sleep at various points (#1, #2, #3) seems to workaround
* the problem.
* @throws Exception
*/
@Test public void test6a() throws Exception
{
for (int j = 0; j < 50; j++)
{
final OOoBean bean = new OOoBean(new PrivateLocalOfficeConnection(connection.getComponentContext()));
final java.awt.Frame frame = new Frame("Openoffice.org");
bean.setOOoCallTimeOut(10000);
try {
frame.add(bean, BorderLayout.CENTER);
frame.pack();
frame.setSize(600,400);
frame.show();
bean.loadFromURL("private:factory/swriter", null);
frame.validate();
// #1
Thread.sleep(1000);
StringBuffer buf = new StringBuffer(1000);
int i = 0;
for (; i < 1; i++)
{
EventQueue q = Toolkit.getDefaultToolkit().getSystemEventQueue();
q.invokeAndWait( new Runnable() {
public void run() {
try {
bean.releaseSystemWindow();
frame.remove(bean);
frame.validate();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// #2
Thread.sleep(1000);
q.invokeAndWait( new Runnable() {
public void run() {
try {
frame.add(bean, BorderLayout.CENTER);
bean.aquireSystemWindow();
frame.validate();
} catch (Exception e) {
e.printStackTrace();
}
}
});
// #3
Thread.sleep(1000);
}
if (isWindows() == false)
{
Thread.sleep(5000);
}
Robot roby = new Robot();
roby.mouseMove(300, 200);
roby.waitForIdle();
roby.mousePress(InputEvent.BUTTON1_MASK);
roby.waitForIdle();
roby.mouseRelease(InputEvent.BUTTON1_MASK);
roby.waitForIdle();
roby.keyPress(KeyEvent.VK_H);
roby.waitForIdle();
roby.keyRelease(KeyEvent.VK_H);
roby.waitForIdle();
buf.append("h");
Thread.sleep(1000);
String s = getText(bean);
System.out.println(" getText: " + s);
if ( ! s.equals(buf.toString()))
{
roby.mousePress(InputEvent.BUTTON1_MASK);
roby.waitForIdle();
roby.mouseRelease(InputEvent.BUTTON1_MASK);
roby.waitForIdle();
roby.keyPress(KeyEvent.VK_H);
roby.waitForIdle();
roby.keyRelease(KeyEvent.VK_H);
roby.waitForIdle();
String sH = "h";
Thread.sleep(1000);
String s2 = getText(bean);
if ( ! sH.equals(s2))
{
fail("Focus error: After removing and adding the bean, the" +
"office window does not receive keyboard input.\n" +
"Try typing in the window, you've got 30s!!! This " +
"test may not work with Linux/Solaris");
System.out.println("j: " + j + " i: " + i);
Thread.sleep(30000);
break;
}
}
else
{
// Thread.sleep(2000);
}
} finally {
bean.stopOOoConnection();
frame.dispose();
}
}
}
/** Repeatedly loading a document in one and the same OOoBean instance.
* @throws Exception
*/
@Test public void test7() throws Exception
{
WriterFrame f = null;
try
{
f = new WriterFrame(100 ,100, 500 ,400, false, connection.getComponentContext());
String text = "OOoBean test.";
for (int i = 0; i < 10; i++)
{
f.getBean().clear();
f.getBean().loadFromURL("private:factory/swriter", null);
f.setText(text);
f.goToStart();
f.validate();
if (text.equals(f.getText()) == false)
{
fail("Repeated loading of a document failed.");
}
Thread.sleep(1000);
}
}
finally
{
if (f != null)
{
f.dispose();
}
}
}
/** Using multiple instances of OOoBean at the same time
* @throws Exception
*/
@Test public void test8() throws Exception
{
OOoBean bean1 = new OOoBean(new PrivateLocalOfficeConnection(connection.getComponentContext()));
BeanPanel bp1 = new BeanPanel(bean1);
OOoBean bean2 = new OOoBean(new PrivateLocalOfficeConnection(connection.getComponentContext()));
BeanPanel bp2 = new BeanPanel(bean2);
OOoBean bean3 = new OOoBean(new PrivateLocalOfficeConnection(connection.getComponentContext()));
BeanPanel bp3 = new BeanPanel(bean3);
OOoBean bean4 = new OOoBean(new PrivateLocalOfficeConnection(connection.getComponentContext()));
BeanPanel bp4 = new BeanPanel(bean4);
try
{
Frame f = new Frame("OOoBean example with several instances");
f.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.insets = new Insets(0, 0, 0, 10);
c.gridx = 0;
c.gridy = 0;
f.add(bp1, c);
c.gridx = 1;
c.insets = new Insets(0, 0, 0, 0);
f.add(bp2, c);
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10, 0, 0, 10);
f.add(bp3, c);
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(10, 0, 0, 0);
f.add(bp4, c);
f.pack();
f.setBounds(0, 0, 1000, 600);
f.setVisible(true);
try {
bean1.loadFromURL("private:factory/swriter", null);
bean2.loadFromURL("private:factory/swriter", null);
bean3.loadFromURL("private:factory/swriter", null);
bean4.loadFromURL("private:factory/swriter", null);
} catch( Exception e)
{
e.printStackTrace();
}
f.validate();
Thread.sleep(10000);
}
finally
{
bean1.stopOOoConnection();
bean2.stopOOoConnection();
bean3.stopOOoConnection();
bean4.stopOOoConnection();
}
}
class BeanPanel extends Panel
{
public BeanPanel(OOoBean b)
{
setLayout(new BorderLayout());
add(b, BorderLayout.CENTER);
}
public Dimension getPreferredSize()
{
Container c = getParent();
return new Dimension(200, 200);
}
}
private XMultiServiceFactory getMSF()
{
final XMultiServiceFactory xMSF1 = UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager());
return xMSF1;
}
// setup and close connections
@BeforeClass public static void setUpConnection() throws Exception {
System.out.println("setUpConnection()");
connection.setUp();
}
@AfterClass public static void tearDownConnection()
throws InterruptedException, com.sun.star.uno.Exception
{
System.out.println("tearDownConnection()");
connection.tearDown();
}
private static final OfficeConnection connection = new OfficeConnection();
}
| 12,738 |
445 | #ifndef MULTIVERSO_TIMER_H_
#define MULTIVERSO_TIMER_H_
#include <chrono>
#include <string>
namespace multiverso {
class Timer {
public:
Timer();
// Restart the timer
void Start();
// Get elapsed milliseconds since last Timer::Start
double elapse();
private:
using Clock = std::chrono::high_resolution_clock;
using TimePoint = Clock::time_point;
TimePoint start_point_;
};
} // namespace multiverso
#endif // MULTIVERSO_TIMER_H_
| 165 |
394 | <gh_stars>100-1000
/*
* Copyright (c) 2016, WSO2 Inc. (http://wso2.com) 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 org.wso2.msf4j.examples.petstore.security.ldap.server;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apacheds.DirectoryServiceFactory;
import org.wso2.carbon.apacheds.KDCServer;
import org.wso2.carbon.apacheds.KdcConfiguration;
import org.wso2.carbon.apacheds.LDAPConfiguration;
import org.wso2.carbon.apacheds.LDAPServer;
import org.wso2.carbon.apacheds.PartitionInfo;
import org.wso2.carbon.apacheds.PartitionManager;
import org.wso2.carbon.ldap.server.exception.DirectoryServerException;
import org.wso2.carbon.ldap.server.util.EmbeddingLDAPException;
import org.wso2.msf4j.util.SystemVariableUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* This start the EmbeddedLDAP-server. Needs to have "MSF4J_HOME" system variable configured by
* pointing to the directory that ldap data and config files get stored. If the "MSF4J_HOME" is not set
* current working directory will use as the MSF4J_HOME".
*/
public class ApacheDirectoryServerActivator {
private static final Logger log = LoggerFactory.getLogger(ApacheDirectoryServerActivator.class);
private String msf4jHome = SystemVariableUtil.getValue("MSF4J_HOME", System.getProperty("user.dir"));
private LDAPServer ldapServer;
private KDCServer kdcServer;
/**
* Starts EmbeddedLDAP-server.
*/
public void start() {
try {
/*Configure embedded-ldap.xml and default ldap schema, if those are not defined.*/
copyResources();
/*Read the embedded-ldap configuration file.*/
LDAPServerConfigurationBuilder configurationBuilder = new LDAPServerConfigurationBuilder(
getLdapConfigurationFile());
/*Make relevant objects that encapsulate different parts of config file.*/
configurationBuilder.buildConfigurations();
boolean embeddedLDAPEnabled = configurationBuilder.isEmbeddedLDAPEnabled();
//start LDAPServer only if embedded-ldap is enabled.
if (embeddedLDAPEnabled) {
LDAPConfiguration ldapConfiguration = configurationBuilder.getLdapConfiguration();
/*set the embedded-apacheds's schema location which is: carbon-home/repository/data/
is-default-schema.zip
*/
setSchemaLocation();
/* Set working directory where schema directory and ldap partitions are created*/
setWorkingDirectory(ldapConfiguration);
startLdapServer(ldapConfiguration);
/* replace default password with that is provided in the configuration file.*/
this.ldapServer.changeConnectionUserPassword(
configurationBuilder.getConnectionPassword());
// Add admin (default)partition if it is not already created.
PartitionManager partitionManager = this.ldapServer.getPartitionManager();
PartitionInfo defaultPartitionInfo = configurationBuilder.getPartitionConfigurations();
boolean defaultPartitionAlreadyExisted =
partitionManager.partitionDirectoryExists(defaultPartitionInfo.getPartitionId());
if (!defaultPartitionAlreadyExisted) {
partitionManager.addPartition(defaultPartitionInfo);
if (kdcServer == null) {
kdcServer = DirectoryServiceFactory.createKDCServer(DirectoryServiceFactory.LDAPServerType.
APACHE_DIRECTORY_SERVICE);
}
kdcServer.kerberizePartition(configurationBuilder.
getPartitionConfigurations(), this.ldapServer);
} else {
partitionManager.initializeExistingPartition(defaultPartitionInfo);
}
// Start KDC if enabled
if (configurationBuilder.isKdcEnabled()) {
startKDC(configurationBuilder.getKdcConfigurations());
}
if (log.isDebugEnabled()) {
log.debug("apacheds-server started.");
}
} else {
//if needed, create a dummy tenant manager service and register it.
log.info("Embedded LDAP is disabled.");
}
} catch (FileNotFoundException e) {
String errorMessage = "Could not start the embedded-ldap. ";
log.error(errorMessage, e);
} catch (DirectoryServerException e) {
String errorMessage = "Could not start the embedded-ldap. ";
log.error(errorMessage, e);
} catch (EmbeddingLDAPException e) {
String errorMessage = "Could not start the embedded-ldap. ";
log.error(errorMessage, e);
} catch (Exception e) {
String errorMessage = "An unknown exception occurred while starting LDAP server. ";
log.error(errorMessage, e);
} catch (Throwable e) {
String errorMessage = "An unknown error occurred while starting LDAP server. ";
log.error(errorMessage, e);
}
}
private void setSchemaLocation() throws EmbeddingLDAPException {
String schemaLocation = "repository" + File.separator + "data" + File.separator +
"is-default-schema.zip";
File dataDir = new File(getCarbonHome(), schemaLocation);
// Set schema location
System.setProperty("schema.zip.store.location", dataDir.getAbsolutePath());
}
private String getCarbonHome() throws EmbeddingLDAPException {
return msf4jHome;
}
private File getLdapConfigurationFile() throws EmbeddingLDAPException {
String configurationFilePath = "repository" + File.separator + "conf" + File.separator +
"embedded-ldap.xml";
return new File(getCarbonHome(), configurationFilePath);
}
private void setWorkingDirectory(LDAPConfiguration ldapConfiguration)
throws EmbeddingLDAPException {
if (ldapConfiguration.getWorkingDirectory().equals(".")) {
File dataDir = new File(getCarbonHome(), "repository" + File.separator + "data");
if (!dataDir.exists()) {
if (!dataDir.mkdir()) {
String msg = "Unable to create data directory at " + dataDir.getAbsolutePath();
log.error(msg);
throw new EmbeddingLDAPException(msg);
}
}
File bundleDataDir = new File(dataDir, "org.wso2.carbon.directory");
if (!bundleDataDir.exists()) {
if (!bundleDataDir.mkdirs()) {
String msg = "Unable to create schema data directory at " + bundleDataDir.
getAbsolutePath();
log.error(msg);
throw new EmbeddingLDAPException(msg);
}
}
ldapConfiguration.setWorkingDirectory(bundleDataDir.getAbsolutePath());
}
}
private void startLdapServer(LDAPConfiguration ldapConfiguration)
throws DirectoryServerException {
this.ldapServer = DirectoryServiceFactory.createLDAPServer(DirectoryServiceFactory.
LDAPServerType.APACHE_DIRECTORY_SERVICE);
log.info("Initializing Directory Server with working directory " + ldapConfiguration.
getWorkingDirectory() + " and port " + ldapConfiguration.getLdapPort());
this.ldapServer.init(ldapConfiguration);
this.ldapServer.start();
}
private void startKDC(KdcConfiguration kdcConfiguration)
throws DirectoryServerException {
if (kdcServer == null) {
kdcServer = DirectoryServiceFactory
.createKDCServer(DirectoryServiceFactory.LDAPServerType.APACHE_DIRECTORY_SERVICE);
}
kdcServer.init(kdcConfiguration, this.ldapServer);
kdcServer.start();
}
public void stop() throws Exception {
if (this.kdcServer != null) {
this.kdcServer.stop();
}
if (this.ldapServer != null) {
this.ldapServer.stop();
}
}
private void copyResources() throws IOException, EmbeddingLDAPException {
final File jarFile = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
final String repositoryDirectory = "repository";
final File destinationRoot = new File(getCarbonHome());
//Check whether ladap configs are already configured
File repository = new File(getCarbonHome() + File.separator + repositoryDirectory);
if (!repository.exists()) {
JarFile jar = null;
try {
jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
// Skip if the entry is not about the 'repository' directory.
if (!entry.getName().startsWith(repositoryDirectory)) {
continue;
}
// If the entry is a directory create the relevant directory in the destination.
File destination = new File(destinationRoot, entry.getName());
if (entry.isDirectory()) {
if (destination.mkdirs()) {
continue;
}
}
InputStream in = null;
OutputStream out = null;
try {
// If the entry is a file, copy the file to the destination
in = jar.getInputStream(entry);
out = new FileOutputStream(destination);
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
}
} finally {
if (jar != null) {
jar.close();
}
}
}
}
}
| 4,981 |
412 | <reponame>mauguignard/cbmc<gh_stars>100-1000
#include "../sensitivity-test-common-files/pointer_to_array_sensitivity_tests.c"
| 50 |
3,804 | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_BASICS_COMPARATORS_H_INCLUDED
#define RIPPLE_BASICS_COMPARATORS_H_INCLUDED
#include <functional>
namespace ripple {
#ifdef _MSC_VER
/*
* MSVC 2019 version 16.9.0 added [[nodiscard]] to the std comparison
* operator() functions. boost::bimap checks that the comparitor is a
* BinaryFunction, in part by calling the function and ignoring the value.
* These two things don't play well together. These wrapper classes simply
* strip [[nodiscard]] from operator() for use in boost::bimap.
*
* See also:
* https://www.boost.org/doc/libs/1_75_0/libs/bimap/doc/html/boost_bimap/the_tutorial/controlling_collection_types.html
*/
template <class T = void>
struct less
{
using result_type = bool;
constexpr bool
operator()(const T& left, const T& right) const
{
return std::less<T>()(left, right);
}
};
template <class T = void>
struct equal_to
{
using result_type = bool;
constexpr bool
operator()(const T& left, const T& right) const
{
return std::equal_to<T>()(left, right);
}
};
#else
template <class T = void>
using less = std::less<T>;
template <class T = void>
using equal_to = std::equal_to<T>;
#endif
} // namespace ripple
#endif
| 747 |
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.autoupdate.services;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import org.openide.util.NbPreferences;
/**
*
* @author <NAME>
*/
public class AutoupdateSettings {
private static final String PROP_OPEN_CONNECTION_TIMEOUT = "plugin.manager.connection.timeout"; // NOI18N
public static final int DEFAULT_OPEN_CONNECTION_TIMEOUT = 30000;
private static final String PROP_LAST_CHECK = "lastCheckTime"; // NOI18N
private static final Logger err = Logger.getLogger (AutoupdateSettings.class.getName ());
private AutoupdateSettings () {
}
public static void setLastCheck (Date lastCheck) {
err.log (Level.FINER, "Set the last check to " + lastCheck);
if (lastCheck != null) {
getPreferences().putLong (PROP_LAST_CHECK, lastCheck.getTime ());
} else {
getPreferences().remove (PROP_LAST_CHECK);
}
}
public static void setLastCheck (String updateProviderName, Date lastCheck) {
err.log (Level.FINER, "Set the last check to " + lastCheck);
if (lastCheck != null) {
getPreferences().putLong (updateProviderName+"_"+PROP_LAST_CHECK, lastCheck.getTime ());
} else {
getPreferences().remove (updateProviderName+"_"+PROP_LAST_CHECK);//NOI18N
}
}
private static Preferences getPreferences () {
return NbPreferences.root ().node ("/org/netbeans/modules/autoupdate");
}
public static int getOpenConnectionTimeout () {
return getPreferences ().getInt (PROP_OPEN_CONNECTION_TIMEOUT, DEFAULT_OPEN_CONNECTION_TIMEOUT);
}
}
| 878 |
5,169 | <reponame>Gantios/Specs
{
"name": "FairBidSDK",
"version": "2.0.5",
"summary": "Advertising SDK for mobile games.",
"homepage": "https://developer.fyber.com/",
"license": {
"type": "Commercial",
"text": "https://www.fyber.com/sdklicense/"
},
"authors": "Fyber",
"social_media_url": "https://www.facebook.com/fybernv/",
"source": {
"http": "https://d2jks9au6e6w94.cloudfront.net/sdk/ios/FairBid-iOS-SDK-2.0.5.zip"
},
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"vendored_frameworks": "FairBidSDK.framework",
"source_files": "FairBidSDK.framework/Versions/A/Headers/*.h",
"public_header_files": "FairBidSDK.framework/Versions/A/Headers/*.h",
"ios": {
"resources": [
"FairBidSDKResources.bundle",
"IASDKResources.bundle"
]
},
"frameworks": [
"AdSupport",
"AVFoundation",
"AVKit",
"CoreGraphics",
"CoreLocation",
"CoreMedia",
"CoreTelephony",
"EventKit",
"EventKitUI",
"MediaPlayer",
"MessageUI",
"MobileCoreServices",
"QuartzCore",
"Security",
"StoreKit",
"SystemConfiguration",
"WebKit"
],
"libraries": [
"xml2.2",
"sqlite3"
]
}
| 538 |
4,140 | <reponame>FANsZL/hive
/*
* 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.hadoop.hive.ql.optimizer.calcite.rules.jdbc;
import java.util.ArrayList;
import java.util.List;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexOver;
import org.apache.calcite.rex.RexVisitorImpl;
import org.apache.calcite.sql.SqlDialect;
import org.apache.calcite.sql.SqlOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A utility class that helps identify Hive-Jdbc functions gaps.
*/
public final class JDBCRexCallValidator {
private static final Logger LOG = LoggerFactory.getLogger(JDBCRexCallValidator.class);
private static final class JdbcRexCallValidatorVisitor extends RexVisitorImpl<Void> {
private final SqlDialect dialect;
private JdbcRexCallValidatorVisitor(SqlDialect dialect) {
super(true);
this.dialect = dialect;
}
boolean res = true;
private boolean validRexCall(RexCall call) {
if (call instanceof RexOver) {
LOG.debug("RexOver operator push down is not supported for now with the following operator:" + call);
return false;
}
final SqlOperator operator = call.getOperator();
List <RexNode> operands = call.getOperands();
RelDataType resType = call.getType();
ArrayList<RelDataType> paramsListType = new ArrayList<RelDataType>();
for (RexNode currNode : operands) {
paramsListType.add(currNode.getType());
}
return dialect.supportsFunction(operator, resType, paramsListType);
}
@Override
public Void visitCall(RexCall call) {
if (res) {
res = validRexCall(call);
if (res) {
return super.visitCall(call);
}
}
return null;
}
private boolean go(RexNode cond) {
cond.accept(this);
return res;
}
}
private JDBCRexCallValidator() {
}
public static boolean isValidJdbcOperation(RexNode cond, SqlDialect dialect) {
return new JdbcRexCallValidatorVisitor(dialect).go(cond);
}
};
| 1,000 |
2,996 | <filename>engine/src/main/java/org/terasology/engine/core/internal/TimeLwjgl.java
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.core.internal;
import org.lwjgl.glfw.GLFW;
public final class TimeLwjgl extends TimeBase {
public TimeLwjgl() {
super((long) (GLFW.glfwGetTime() * 1000));
}
@Override
public long getRawTimeInMs() {
return (long) (GLFW.glfwGetTime() * 1000);
}
}
| 193 |
335 | {
"word": "Welfarism",
"definitions": [
"The principles or policies associated with a welfare state."
],
"parts-of-speech": "Noun"
} | 64 |
2,338 | <filename>lldb/packages/Python/lldbsuite/test/commands/expression/macros/macro2.h
#define HUNDRED 100
#define THOUSAND 1000
#define MILLION 1000000
#define MAX(a, b)\
((a) > (b) ?\
(a):\
(b))
| 84 |
11,877 | /*
* Copyright 2016 <NAME>. 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.github.benmanes.caffeine.cache.simulator.membership;
/**
* A probabilistic set for testing the membership of an element.
*
* @author <EMAIL> (<NAME>)
*/
public interface Membership {
/**
* Returns if the element <i>might</i> have been put in this Bloom filter, {@code false} if this
* is <i>definitely</i> not the case.
*
* @param e the element whose presence is to be tested
* @return if the element might be present
*/
boolean mightContain(long e);
/** Removes all of the elements from this collection. */
void clear();
/**
* Puts an element into this collection so that subsequent queries with the same element will
* return {@code true}.
*
* @param e the element to add
* @return if the membership changed as a result of this operation
*/
boolean put(long e);
/** Returns an instance that contains nothing. */
static Membership disabled() {
return DisabledMembership.INSTANCE;
}
}
enum DisabledMembership implements Membership {
INSTANCE;
@Override
public boolean mightContain(long e) {
return false;
}
@Override
public void clear() {}
@Override
public boolean put(long e) {
return false;
}
}
| 519 |
409 | //
// snowflake.hpp
// *************
//
// Copyright (c) 2020 <NAME> (sharon at xandium dot io)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//
#pragma once
#include "aegis/fwd.hpp"
#include "aegis/config.hpp"
#include <nlohmann/json.hpp>
namespace aegis
{
/// Stores creation time and extra data specific to Discord for entities
class snowflake
{
public:
constexpr snowflake() noexcept : _id(0) {}
constexpr snowflake(int64_t _snowflake) noexcept : _id(_snowflake) {}
constexpr snowflake(const snowflake & _snowflake) noexcept : _id(_snowflake._id) {}
explicit snowflake(const char * _snowflake) noexcept : _id(std::stoll(std::string(_snowflake))) {}
explicit snowflake(const std::string & _snowflake) noexcept : _id(std::stoll(_snowflake)) {}
#if defined(AEGIS_CXX17)
explicit snowflake(const std::string_view _snowflake) noexcept : _id(std::stoll(std::string{ _snowflake })) {}
#endif
explicit snowflake(const nlohmann::json & _snowflake) noexcept : _id(std::stoll(_snowflake.get<std::string>())) {}
AEGIS_DECL snowflake(const aegis::user & _user) noexcept;
AEGIS_DECL snowflake(const aegis::guild & _guild) noexcept;
AEGIS_DECL snowflake(const aegis::channel & _channel) noexcept;
AEGIS_DECL snowflake(const aegis::gateway::objects::role & _role) noexcept;
AEGIS_DECL snowflake(const aegis::gateway::objects::message & _message) noexcept;
AEGIS_DECL snowflake(const aegis::gateway::objects::emoji & _emoji) noexcept;
AEGIS_DECL snowflake(const aegis::gateway::objects::attachment & _attachment) noexcept;
constexpr operator int64_t() const noexcept
{
return _id;
}
/// Get snowflake as int64_t
/**
* @returns int64_t Snowflake
*/
constexpr int64_t get() const noexcept
{
return _id;
};
/// Get snowflake as std::string
/**
* @returns std::string Snowflake
*/
std::string gets() const noexcept
{
return std::to_string(_id);
};
/// Obtain all the snowflake values as a tuple
/**
* @returns std::tuple of all the snowflake parts
*/
constexpr std::tuple<int64_t, int8_t, int8_t, int16_t> get_all() const noexcept
{
return std::tuple<int64_t, int8_t, int8_t, int16_t>{ get_timestamp(), get_worker(), get_process(), get_count() };
};
///
/**
* @returns int16_t Internal counter for snowflakes
*/
constexpr int16_t get_count() const noexcept
{
return static_cast<int16_t>(_id & _countMask);
};
///
/**
* @returns int8_t Process ID of the snowflake generator
*/
constexpr int8_t get_process() const noexcept
{
return static_cast<int8_t>((_id & _workerMask) >> 12);
};
///
/**
* @returns int8_t Worker ID of the snowflake generator
*/
constexpr int8_t get_worker() const noexcept
{
return static_cast<int8_t>((_id & _workerMask) >> 17);
};
///
/**
* @returns int64_t The Discord epoch timestamp this snowflake was generated
*/
constexpr int64_t get_timestamp() const noexcept
{
return (_id & _timestampMask) >> 22;
};
/// Obtain all the snowflake values as a tuple
/**
* @returns std::tuple of all the snowflake parts
*/
static constexpr std::tuple<int64_t, int8_t, int8_t, int16_t> c_get_all(int64_t _snowflake) noexcept
{
return std::tuple<int64_t, int8_t, int8_t, int16_t>{ c_get_timestamp(_snowflake), c_get_worker(_snowflake), c_get_process(_snowflake), c_get_count(_snowflake) };
};
///
/**
* @returns int16_t Internal counter for snowflakes
*/
static constexpr int16_t c_get_count(int64_t _snowflake) noexcept
{
return static_cast<int16_t>(_snowflake & _countMask);
};
///
/**
* @returns int8_t Process ID of the snowflake generator
*/
static constexpr int8_t c_get_process(int64_t _snowflake) noexcept
{
return static_cast<int8_t>((_snowflake & _workerMask) >> 12);
};
///
/**
* @returns int8_t Worker ID of the snowflake generator
*/
static constexpr int8_t c_get_worker(int64_t _snowflake) noexcept
{
return static_cast<int8_t>((_snowflake & _workerMask) >> 17);
};
///
/**
* @returns int64_t The Discord epoch timestamp this snowflake was generated
*/
static constexpr int64_t c_get_timestamp(int64_t _snowflake) noexcept
{
return (_snowflake & _timestampMask) >> 22;
};
///
/**
* @returns int64_t Unix timestamp this snowflake was generated
*/
constexpr int64_t get_time() const noexcept
{
return get_timestamp() + _discordEpoch;
};
///
/**
* @returns int64_t Unix timestamp this snowflake was generated
*/
static constexpr int64_t c_get_time(int64_t _snowflake) noexcept
{
return c_get_timestamp(_snowflake) + _discordEpoch;
};
private:
uint64_t _id;
static constexpr uint64_t _countMask = 0x0000000000000FFFL;
static constexpr uint64_t _processMask = 0x000000000001F000L;
static constexpr uint64_t _workerMask = 0x00000000003E0000L;
static constexpr uint64_t _timestampMask = 0xFFFFFFFFFFC00000L;
static constexpr uint64_t _discordEpoch = 1420070400000;
};
/// \cond TEMPLATES
AEGIS_DECL void from_json(const nlohmann::json& j, snowflake& s);
AEGIS_DECL void to_json(nlohmann::json& j, const snowflake& s);
/// \endcond
}
/// \cond TEMPLATES
namespace std
{
template <>
struct hash<aegis::snowflake>
{
std::size_t operator()(const aegis::snowflake& k) const
{
return hash<int64_t>()(k.get());
}
};
}
/// \endcond
#if defined(AEGIS_HEADER_ONLY)
#include "aegis/impl/snowflake.cpp"
#endif
| 2,409 |
337 | <filename>mava/components/tf/modules/communication/base.py
# python3
# Copyright 2021 InstaDeep Ltd. 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 abc
from typing import Dict, Union
import sonnet as snt
from mava.components.tf.architectures import BaseArchitecture, BasePolicyArchitecture
"""Base communication interface for multi-agent RL systems"""
class BaseCommunicationModule:
"""Base class for MARL communication.
Objects which implement this interface provide a set of functions
to create systems that can perform some form of communication between
agents in a multi-agent RL system.
"""
@abc.abstractmethod
def __init__(
self,
architecture: Union[
BaseArchitecture,
BasePolicyArchitecture,
],
shared: bool,
channel_size: int,
channel_noise: float,
) -> None:
"""Initializes the broadcaster communicator.
Args:
architecture: the BaseArchitecture used.
shared: if a shared communication channel is used.
channel_noise: stddev of normal noise in channel.
"""
@abc.abstractmethod
def process_messages(
self, messages: Dict[str, snt.Module]
) -> Dict[str, snt.Module]:
"""Abstract communication function."""
@abc.abstractmethod
def create_system(self) -> Dict[str, Dict[str, snt.Module]]:
"""Create system architecture with communication."""
| 669 |
4,071 | <reponame>hitflame/x-deeplearning
# Copyright (C) 2016-2018 Alibaba Group Holding Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import tensorflow as tf
from tensorflow.python.ops.variable_scope import _VariableStore
from xdl.python.framework.variable import Variable as xdl_variable
from xdl.python.backend.tf.convert_utils import TF2XDL
from xdl.python.lib.datatype import DataType
from xdl.python.utils.collections import *
from xdl.python.backend.model_scope import cur_model_scope
"""tensorflow get_variable hook"""
real_get_variable = _VariableStore.get_variable
_TF_VAR_DICT = {}
def get_variable(self, name, shape=None, dtype=DataType.float,
initializer=None, regularizer=None, reuse=None,
trainable=True, collections=None, caching_device=None,
partitioner=None, validate_shape=True, use_resource=None,
custom_getter=None, constraint=None, **kwargs):
global _TF_VAR_DICT
scope = cur_model_scope()
if scope not in _TF_VAR_DICT:
_TF_VAR_DICT[scope] = {}
tf_var_dict = _TF_VAR_DICT[scope]
if name in tf_var_dict:
if tf.get_variable_scope().reuse in [True, tf.AUTO_REUSE]:
return tf_var_dict[name]
else:
raise Exception("must set reuse flag to enable reuse")
def _custom_getter(getter, *args, **kwargs):
tf_var = getter(*args, **kwargs)
xdl_var = xdl_variable(
name = name,
shape = TF2XDL.convert_shape(shape),
dtype = TF2XDL.convert_type(dtype),
scope = scope,
trainable = True,
initializer = TF2XDL.convert_initializer(initializer))
add_to_collection(VAR_MAPPING, (xdl_var, tf_var), scope)
add_to_collection(BACKPROP_VARS, (name, tf_var), scope)
tf_var_dict[name] = tf_var
return tf_var
return real_get_variable(self, name, shape, dtype, initializer,
regularizer, reuse, trainable,
collections, caching_device, partitioner,
validate_shape, use_resource, _custom_getter,
constraint, **kwargs)
_VariableStore.get_variable = get_variable
| 1,069 |
5,169 | <reponame>Gantios/Specs
{
"name": "BNRSDKLib",
"version": "0.1.0",
"summary": "A short description of BNRSDKLib.",
"description": "Utility , Category in BNRSDKLib",
"homepage": "https://github.com/JustinYangJing/BNRSDK.git",
"license": "MIT",
"authors": {
"JustinYang": "<EMAIL>"
},
"platforms": {
"ios": "7.0"
},
"source": {
"git": "https://github.com/wang68543/BNRSDK.git"
},
"source_files": [
"BNRSDKLib/BNRSDKLib/*.{h,m}",
"BNRSDKLib/BNRSDKLib/**/*.{m,h}"
],
"exclude_files": "Classes/Exclude"
}
| 248 |
32,544 | package com.baeldung.concurrent.interrupt;
public class CustomInterruptedException extends Exception {
private static final long serialVersionUID = 1L;
CustomInterruptedException(String message) {
super(message);
}
}
| 77 |
1,353 | <filename>sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/NetUtil.java<gh_stars>1000+
package com.twelvemonkeys.net;
import com.twelvemonkeys.io.FileUtil;
import com.twelvemonkeys.lang.StringUtil;
import com.twelvemonkeys.util.CollectionUtil;
import java.io.*;
import java.net.*;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
/**
* Utility class with network related methods.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/net/NetUtil.java#2 $
*/
public final class NetUtil {
private final static String VERSION_ID = "NetUtil/2.1";
private static Authenticator sAuthenticator = null;
private final static int BUF_SIZE = 8192;
private final static String HTTP = "http://";
private final static String HTTPS = "https://";
/**
* Field HTTP_PROTOCOL
*/
public final static String HTTP_PROTOCOL = "http";
/**
* Field HTTPS_PROTOCOL
*/
public final static String HTTPS_PROTOCOL = "https";
/**
* Field HTTP_GET
*/
public final static String HTTP_GET = "GET";
/**
* Field HTTP_POST
*/
public final static String HTTP_POST = "POST";
/**
* Field HTTP_HEAD
*/
public final static String HTTP_HEAD = "HEAD";
/**
* Field HTTP_OPTIONS
*/
public final static String HTTP_OPTIONS = "OPTIONS";
/**
* Field HTTP_PUT
*/
public final static String HTTP_PUT = "PUT";
/**
* Field HTTP_DELETE
*/
public final static String HTTP_DELETE = "DELETE";
/**
* Field HTTP_TRACE
*/
public final static String HTTP_TRACE = "TRACE";
/**
* Creates a NetUtil.
* This class has only static methods and members, and should not be
* instantiated.
*/
private NetUtil() {
}
/**
* Main method, reads data from a URL and, optionally, writes it to stdout or a file.
* @param pArgs command line arguemnts
* @throws java.io.IOException if an I/O exception occurs
*/
public static void main(String[] pArgs) throws IOException {
// params:
int timeout = 0;
boolean followRedirects = true;
boolean debugHeaders = false;
String requestPropertiesFile = null;
String requestHeaders = null;
String postData = null;
File putData = null;
int argIdx = 0;
boolean errArgs = false;
boolean writeToFile = false;
boolean writeToStdOut = false;
String outFileName = null;
while ((argIdx < pArgs.length) && (pArgs[argIdx].charAt(0) == '-') && (pArgs[argIdx].length() >= 2)) {
if ((pArgs[argIdx].charAt(1) == 't') || pArgs[argIdx].equals("--timeout")) {
argIdx++;
try {
timeout = Integer.parseInt(pArgs[argIdx++]);
}
catch (NumberFormatException nfe) {
errArgs = true;
break;
}
}
else if ((pArgs[argIdx].charAt(1) == 'd') || pArgs[argIdx].equals("--debugheaders")) {
debugHeaders = true;
argIdx++;
}
else if ((pArgs[argIdx].charAt(1) == 'n') || pArgs[argIdx].equals("--nofollowredirects")) {
followRedirects = false;
argIdx++;
}
else if ((pArgs[argIdx].charAt(1) == 'r') || pArgs[argIdx].equals("--requestproperties")) {
argIdx++;
requestPropertiesFile = pArgs[argIdx++];
}
else if ((pArgs[argIdx].charAt(1) == 'p') || pArgs[argIdx].equals("--postdata")) {
argIdx++;
postData = pArgs[argIdx++];
}
else if ((pArgs[argIdx].charAt(1) == 'u') || pArgs[argIdx].equals("--putdata")) {
argIdx++;
putData = new File(pArgs[argIdx++]);
if (!putData.exists()) {
errArgs = true;
break;
}
}
else if ((pArgs[argIdx].charAt(1) == 'h') || pArgs[argIdx].equals("--header")) {
argIdx++;
requestHeaders = pArgs[argIdx++];
}
else if ((pArgs[argIdx].charAt(1) == 'f') || pArgs[argIdx].equals("--file")) {
argIdx++;
writeToFile = true;
// Get optional file name
if (!((argIdx >= (pArgs.length - 1)) || (pArgs[argIdx].charAt(0) == '-'))) {
outFileName = pArgs[argIdx++];
}
}
else if ((pArgs[argIdx].charAt(1) == 'o') || pArgs[argIdx].equals("--output")) {
argIdx++;
writeToStdOut = true;
}
else {
System.err.println("Unknown option \"" + pArgs[argIdx++] + "\"");
}
}
if (errArgs || (pArgs.length < (argIdx + 1))) {
System.err.println("Usage: java NetUtil [-f|--file [<file name>]] [-d|--debugheaders] [-h|--header <header data>] [-p|--postdata <URL-encoded postdata>] [-u|--putdata <file name>] [-r|--requestProperties <properties file>] [-t|--timeout <miliseconds>] [-n|--nofollowredirects] fromUrl");
System.exit(5);
}
String url = pArgs[argIdx/*++*/];
// DONE ARGS
// Get request properties
Properties requestProperties = new Properties();
if (requestPropertiesFile != null) {
// Just read, no exception handling...
requestProperties.load(new FileInputStream(new File(requestPropertiesFile)));
}
if (requestHeaders != null) {
// Get request headers
String[] headerPairs = StringUtil.toStringArray(requestHeaders, ",");
for (String headerPair : headerPairs) {
String[] pair = StringUtil.toStringArray(headerPair, ":");
String key = (pair.length > 0)
? pair[0].trim()
: null;
String value = (pair.length > 1)
? pair[1].trim()
: "";
if (key != null) {
requestProperties.setProperty(key, value);
}
}
}
HttpURLConnection conn;
// Create connection
URL reqURL = getURLAndSetAuthorization(url, requestProperties);
conn = createHttpURLConnection(reqURL, requestProperties, followRedirects, timeout);
// POST
if (postData != null) {
// HTTP POST method
conn.setRequestMethod(HTTP_POST);
// Set entity headers
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postData.length()));
conn.setRequestProperty("Content-Encoding", "ISO-8859-1");
// Get outputstream (this is where the connect actually happens)
OutputStream os = conn.getOutputStream();
System.err.println("OutputStream: " + os.getClass().getName() + "@" + System.identityHashCode(os));
OutputStreamWriter writer = new OutputStreamWriter(os, "ISO-8859-1");
// Write post data to the stream
writer.write(postData);
writer.write("\r\n");
//writer.flush();
writer.close(); // Does this close the underlying stream?
}
// PUT
else if (putData != null) {
// HTTP PUT method
conn.setRequestMethod(HTTP_PUT);
// Set entity headers
//conn.setRequestProperty("Content-Type", "???");
// TODO: Set Content-Type to correct type?
// TODO: Set content-encoding? Or can binary data be sent directly?
conn.setRequestProperty("Content-Length", String.valueOf(putData.length()));
// Get outputstream (this is where the connect actually happens)
OutputStream os = conn.getOutputStream();
System.err.println("OutputStream: " + os.getClass().getName() + "@" + System.identityHashCode(os));
// Write put data to the stream
FileUtil.copy(new FileInputStream(putData), os);
os.close();
}
//
InputStream is;
if (conn.getResponseCode() == 200) {
// Connect and get stream
is = conn.getInputStream();
}
else {
is = conn.getErrorStream();
}
//
if (debugHeaders) {
System.err.println("Request (debug):");
System.err.println(conn.getClass());
System.err.println("Response (debug):");
// Headerfield 0 is response code
System.err.println(conn.getHeaderField(0));
// Loop from 1, as headerFieldKey(0) == null...
for (int i = 1; ; i++) {
String key = conn.getHeaderFieldKey(i);
// Seems to be the way to loop through them all...
if (key == null) {
break;
}
System.err.println(key + ": " + conn.getHeaderField(key));
}
}
// Create output file if specified
OutputStream os;
if (writeToFile) {
if (outFileName == null) {
outFileName = reqURL.getFile();
if (StringUtil.isEmpty(outFileName)) {
outFileName = conn.getHeaderField("Location");
if (StringUtil.isEmpty(outFileName)) {
outFileName = "index";
// Find a suitable extension
// TODO: Replace with MIME-type util with MIME/file ext mapping
String ext = conn.getContentType();
if (!StringUtil.isEmpty(ext)) {
int idx = ext.lastIndexOf('/');
if (idx >= 0) {
ext = ext.substring(idx + 1);
}
idx = ext.indexOf(';');
if (idx >= 0) {
ext = ext.substring(0, idx);
}
outFileName += "." + ext;
}
}
}
int idx = outFileName.lastIndexOf('/');
if (idx >= 0) {
outFileName = outFileName.substring(idx + 1);
}
idx = outFileName.indexOf('?');
if (idx >= 0) {
outFileName = outFileName.substring(0, idx);
}
}
File outFile = new File(outFileName);
if (!outFile.createNewFile()) {
if (outFile.exists()) {
System.err.println("Cannot write to file " + outFile.getAbsolutePath() + ", file allready exists.");
}
else {
System.err.println("Cannot write to file " + outFile.getAbsolutePath() + ", check write permissions.");
}
System.exit(5);
}
os = new FileOutputStream(outFile);
}
else if (writeToStdOut) {
os = System.out;
}
else {
os = null;
}
// Get data.
if ((writeToFile || writeToStdOut) && is != null) {
FileUtil.copy(is, os);
}
/*
Hashtable postData = new Hashtable();
postData.put("SearchText", "condition");
try {
InputStream in = getInputStreamHttpPost(pArgs[argIdx], postData,
props, true, 0);
out = new FileOutputStream(file);
FileUtil.copy(in, out);
}
catch (Exception e) {
System.err.println("Error: " + e);
e.printStackTrace(System.err);
continue;
}
*/
}
/*
public static class Cookie {
String mName = null;
String mValue = null;
public Cookie(String pName, String pValue) {
mName = pName;
mValue = pValue;
}
public String toString() {
return mName + "=" + mValue;
}
*/
/*
// Just a way to set cookies..
if (pCookies != null) {
String cookieStr = "";
for (int i = 0; i < pCookies.length; i++)
cookieStr += ((i == pCookies.length) ? pCookies[i].toString()
: pCookies[i].toString() + ";");
// System.out.println("Cookie: " + cookieStr);
conn.setRequestProperty("Cookie", cookieStr);
}
*/
/*
}
*/
/**
* Test if the given URL is using HTTP protocol.
*
* @param pURL the url to condition
* @return true if the protocol is HTTP.
*/
public static boolean isHttpURL(String pURL) {
return ((pURL != null) && pURL.startsWith(HTTP));
}
/**
* Test if the given URL is using HTTP protocol.
*
* @param pURL the url to condition
* @return true if the protocol is HTTP.
*/
public static boolean isHttpURL(URL pURL) {
return ((pURL != null) && pURL.getProtocol().equals("http"));
}
/**
* Gets the content from a given URL, and returns it as a byte array.
* Supports basic HTTP
* authentication, using a URL string similar to most browsers.
* <P/>
* <SMALL>NOTE: If you supply a username and password for HTTP
* authentication, this method uses the java.net.Authenticator's static
* {@code setDefault()} method, that can only be set ONCE. This
* means that if the default Authenticator is allready set, this method
* will fail.
* It also means if any other piece of code tries to register a new default
* Authenticator within the current VM, it will fail.</SMALL>
*
* @param pURL A String containing the URL, on the form
* <CODE>[http://][<username>:<password>@]servername[/file.ext]</CODE>
* where everything in brackets are optional.
* @return a byte array with the URL contents. If an error occurs, the
* returned array may be zero-length, but not null.
* @throws MalformedURLException if the urlName parameter is not a valid
* URL. Note that the protocol cannot be anything but HTTP.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see java.net.Authenticator
* @see SimpleAuthenticator
*/
public static byte[] getBytesHttp(String pURL) throws IOException {
return getBytesHttp(pURL, 0);
}
/**
* Gets the content from a given URL, and returns it as a byte array.
*
* @param pURL the URL to get.
* @return a byte array with the URL contents. If an error occurs, the
* returned array may be zero-length, but not null.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see #getBytesHttp(String)
*/
public static byte[] getBytesHttp(URL pURL) throws IOException {
return getBytesHttp(pURL, 0);
}
/**
* Gets the InputStream from a given URL. Supports basic HTTP
* authentication, using a URL string similar to most browsers.
* <P/>
* <SMALL>NOTE: If you supply a username and password for HTTP
* authentication, this method uses the java.net.Authenticator's static
* {@code setDefault()} method, that can only be set ONCE. This
* means that if the default Authenticator is allready set, this method
* will fail.
* It also means if any other piece of code tries to register a new default
* Authenticator within the current VM, it will fail.</SMALL>
*
* @param pURL A String containing the URL, on the form
* <CODE>[http://][<username>:<password>@]servername[/file.ext]</CODE>
* where everything in brackets are optional.
* @return an input stream that reads from the connection created by the
* given URL.
* @throws MalformedURLException if the urlName parameter specifies an
* unknown protocol, or does not form a valid URL.
* Note that the protocol cannot be anything but HTTP.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see java.net.Authenticator
* @see SimpleAuthenticator
*/
public static InputStream getInputStreamHttp(String pURL) throws IOException {
return getInputStreamHttp(pURL, 0);
}
/**
* Gets the InputStream from a given URL.
*
* @param pURL the URL to get.
* @return an input stream that reads from the connection created by the
* given URL.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see #getInputStreamHttp(String)
*/
public static InputStream getInputStreamHttp(URL pURL) throws IOException {
return getInputStreamHttp(pURL, 0);
}
/**
* Gets the InputStream from a given URL, with the given timeout.
* The timeout must be > 0. A timeout of zero is interpreted as an
* infinite timeout. Supports basic HTTP
* authentication, using a URL string similar to most browsers.
* <P/>
* <SMALL>Implementation note: If the timeout parameter is greater than 0,
* this method uses my own implementation of
* java.net.HttpURLConnection, that uses plain sockets, to create an
* HTTP connection to the given URL. The {@code read} methods called
* on the returned InputStream, will block only for the specified timeout.
* If the timeout expires, a java.io.InterruptedIOException is raised. This
* might happen BEFORE OR AFTER this method returns, as the HTTP headers
* will be read and parsed from the InputStream before this method returns,
* while further read operations on the returned InputStream might be
* performed at a later stage.
* <BR/>
* </SMALL>
*
* @param pURL the URL to get.
* @param pTimeout the specified timeout, in milliseconds.
* @return an input stream that reads from the socket connection, created
* from the given URL.
* @throws MalformedURLException if the url parameter specifies an
* unknown protocol, or does not form a valid URL.
* @throws UnknownHostException if the IP address for the given URL cannot
* be resolved.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see #getInputStreamHttp(URL,int)
* @see java.net.Socket
* @see java.net.Socket#setSoTimeout(int) setSoTimeout
* @see java.io.InterruptedIOException
* @see <A href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</A>
*/
public static InputStream getInputStreamHttp(String pURL, int pTimeout) throws IOException {
return getInputStreamHttp(pURL, null, true, pTimeout);
}
/**
* Gets the InputStream from a given URL, with the given timeout.
* The timeout must be > 0. A timeout of zero is interpreted as an
* infinite timeout. Supports basic HTTP
* authentication, using a URL string similar to most browsers.
* <P/>
* <SMALL>Implementation note: If the timeout parameter is greater than 0,
* this method uses my own implementation of
* java.net.HttpURLConnection, that uses plain sockets, to create an
* HTTP connection to the given URL. The {@code read} methods called
* on the returned InputStream, will block only for the specified timeout.
* If the timeout expires, a java.io.InterruptedIOException is raised. This
* might happen BEFORE OR AFTER this method returns, as the HTTP headers
* will be read and parsed from the InputStream before this method returns,
* while further read operations on the returned InputStream might be
* performed at a later stage.
* <BR/>
* </SMALL>
*
* @param pURL the URL to get.
* @param pProperties the request header properties.
* @param pFollowRedirects specifying wether redirects should be followed.
* @param pTimeout the specified timeout, in milliseconds.
* @return an input stream that reads from the socket connection, created
* from the given URL.
* @throws MalformedURLException if the url parameter specifies an
* unknown protocol, or does not form a valid URL.
* @throws UnknownHostException if the IP address for the given URL cannot
* be resolved.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see #getInputStreamHttp(URL,int)
* @see java.net.Socket
* @see java.net.Socket#setSoTimeout(int) setSoTimeout
* @see java.io.InterruptedIOException
* @see <A href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</A>
*/
public static InputStream getInputStreamHttp(final String pURL, final Properties pProperties, final boolean pFollowRedirects, final int pTimeout)
throws IOException {
// Make sure we have properties
Properties properties = pProperties != null ? pProperties : new Properties();
//URL url = getURLAndRegisterPassword(pURL);
URL url = getURLAndSetAuthorization(pURL, properties);
//unregisterPassword(url);
return getInputStreamHttp(url, properties, pFollowRedirects, pTimeout);
}
/**
* Registers the password from the URL string, and returns the URL object.
*
* @param pURL the string representation of the URL, possibly including authorization part
* @param pProperties the
* @return the URL created from {@code pURL}.
* @throws java.net.MalformedURLException if there's a syntax error in {@code pURL}
*/
private static URL getURLAndSetAuthorization(final String pURL, final Properties pProperties) throws MalformedURLException {
String url = pURL;
// Split user/password away from url
String userPass = null;
String protocolPrefix = HTTP;
int httpIdx = url.indexOf(HTTPS);
if (httpIdx >= 0) {
protocolPrefix = HTTPS;
url = url.substring(httpIdx + HTTPS.length());
}
else {
httpIdx = url.indexOf(HTTP);
if (httpIdx >= 0) {
url = url.substring(httpIdx + HTTP.length());
}
}
// Get authorization part
int atIdx = url.indexOf("@");
if (atIdx >= 0) {
userPass = url.substring(0, atIdx);
url = url.substring(atIdx + 1);
}
// Set authorization if user/password is present
if (userPass != null) {
// System.out.println("Setting password ("+ userPass + ")!");
pProperties.setProperty("Authorization", "Basic " + BASE64.encode(userPass.getBytes()));
}
// Return URL
return new URL(protocolPrefix + url);
}
/**
* Gets the InputStream from a given URL, with the given timeout.
* The timeout must be > 0. A timeout of zero is interpreted as an
* infinite timeout.
* <P/>
* <SMALL>Implementation note: If the timeout parameter is greater than 0,
* this method uses my own implementation of
* java.net.HttpURLConnection, that uses plain sockets, to create an
* HTTP connection to the given URL. The {@code read} methods called
* on the returned InputStream, will block only for the specified timeout.
* If the timeout expires, a java.io.InterruptedIOException is raised. This
* might happen BEFORE OR AFTER this method returns, as the HTTP headers
* will be read and parsed from the InputStream before this method returns,
* while further read operations on the returned InputStream might be
* performed at a later stage.
* <BR/>
* </SMALL>
*
* @param pURL the URL to get.
* @param pTimeout the specified timeout, in milliseconds.
* @return an input stream that reads from the socket connection, created
* from the given URL.
* @throws UnknownHostException if the IP address for the given URL cannot
* be resolved.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see com.twelvemonkeys.net.HttpURLConnection
* @see java.net.Socket
* @see java.net.Socket#setSoTimeout(int) setSoTimeout
* @see HttpURLConnection
* @see java.io.InterruptedIOException
* @see <A href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</A>
*/
public static InputStream getInputStreamHttp(URL pURL, int pTimeout) throws IOException {
return getInputStreamHttp(pURL, null, true, pTimeout);
}
/**
* Gets the InputStream from a given URL, with the given timeout.
* The timeout must be > 0. A timeout of zero is interpreted as an
* infinite timeout. Supports basic HTTP
* authentication, using a URL string similar to most browsers.
* <P/>
* <SMALL>Implementation note: If the timeout parameter is greater than 0,
* this method uses my own implementation of
* java.net.HttpURLConnection, that uses plain sockets, to create an
* HTTP connection to the given URL. The {@code read} methods called
* on the returned InputStream, will block only for the specified timeout.
* If the timeout expires, a java.io.InterruptedIOException is raised. This
* might happen BEFORE OR AFTER this method returns, as the HTTP headers
* will be read and parsed from the InputStream before this method returns,
* while further read operations on the returned InputStream might be
* performed at a later stage.
* <BR/>
* </SMALL>
*
* @param pURL the URL to get.
* @param pProperties the request header properties.
* @param pFollowRedirects specifying wether redirects should be followed.
* @param pTimeout the specified timeout, in milliseconds.
* @return an input stream that reads from the socket connection, created
* from the given URL.
* @throws UnknownHostException if the IP address for the given URL cannot
* be resolved.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see #getInputStreamHttp(URL,int)
* @see java.net.Socket
* @see java.net.Socket#setSoTimeout(int) setSoTimeout
* @see java.io.InterruptedIOException
* @see <A href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</A>
*/
public static InputStream getInputStreamHttp(URL pURL, Properties pProperties, boolean pFollowRedirects, int pTimeout)
throws IOException {
// Open the connection, and get the stream
HttpURLConnection conn = createHttpURLConnection(pURL, pProperties, pFollowRedirects, pTimeout);
// HTTP GET method
conn.setRequestMethod(HTTP_GET);
// This is where the connect happens
InputStream is = conn.getInputStream();
// We only accept the 200 OK message
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("The request gave the response: " + conn.getResponseCode() + ": " + conn.getResponseMessage());
}
return is;
}
/**
* Gets the InputStream from a given URL, with the given timeout.
* The timeout must be > 0. A timeout of zero is interpreted as an
* infinite timeout. Supports basic HTTP
* authentication, using a URL string similar to most browsers.
* <P/>
* <SMALL>Implementation note: If the timeout parameter is greater than 0,
* this method uses my own implementation of
* java.net.HttpURLConnection, that uses plain sockets, to create an
* HTTP connection to the given URL. The {@code read} methods called
* on the returned InputStream, will block only for the specified timeout.
* If the timeout expires, a java.io.InterruptedIOException is raised. This
* might happen BEFORE OR AFTER this method returns, as the HTTP headers
* will be read and parsed from the InputStream before this method returns,
* while further read operations on the returned InputStream might be
* performed at a later stage.
* <BR/>
* </SMALL>
*
* @param pURL the URL to get.
* @param pPostData the post data.
* @param pProperties the request header properties.
* @param pFollowRedirects specifying wether redirects should be followed.
* @param pTimeout the specified timeout, in milliseconds.
* @return an input stream that reads from the socket connection, created
* from the given URL.
* @throws MalformedURLException if the url parameter specifies an
* unknown protocol, or does not form a valid URL.
* @throws UnknownHostException if the IP address for the given URL cannot
* be resolved.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
*/
public static InputStream getInputStreamHttpPost(String pURL, Map pPostData, Properties pProperties, boolean pFollowRedirects, int pTimeout)
throws IOException {
pProperties = pProperties != null ? pProperties : new Properties();
//URL url = getURLAndRegisterPassword(pURL);
URL url = getURLAndSetAuthorization(pURL, pProperties);
//unregisterPassword(url);
return getInputStreamHttpPost(url, pPostData, pProperties, pFollowRedirects, pTimeout);
}
/**
* Gets the InputStream from a given URL, with the given timeout.
* The timeout must be > 0. A timeout of zero is interpreted as an
* infinite timeout. Supports basic HTTP
* authentication, using a URL string similar to most browsers.
* <P/>
* <SMALL>Implementation note: If the timeout parameter is greater than 0,
* this method uses my own implementation of
* java.net.HttpURLConnection, that uses plain sockets, to create an
* HTTP connection to the given URL. The {@code read} methods called
* on the returned InputStream, will block only for the specified timeout.
* If the timeout expires, a java.io.InterruptedIOException is raised. This
* might happen BEFORE OR AFTER this method returns, as the HTTP headers
* will be read and parsed from the InputStream before this method returns,
* while further read operations on the returned InputStream might be
* performed at a later stage.
* <BR/>
* </SMALL>
*
* @param pURL the URL to get.
* @param pPostData the post data.
* @param pProperties the request header properties.
* @param pFollowRedirects specifying wether redirects should be followed.
* @param pTimeout the specified timeout, in milliseconds.
* @return an input stream that reads from the socket connection, created
* from the given URL.
* @throws UnknownHostException if the IP address for the given URL cannot
* be resolved.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
*/
public static InputStream getInputStreamHttpPost(URL pURL, Map pPostData, Properties pProperties, boolean pFollowRedirects, int pTimeout)
throws IOException {
// Open the connection, and get the stream
HttpURLConnection conn = createHttpURLConnection(pURL, pProperties, pFollowRedirects, pTimeout);
// HTTP POST method
conn.setRequestMethod(HTTP_POST);
// Iterate over and create post data string
StringBuilder postStr = new StringBuilder();
if (pPostData != null) {
Iterator data = pPostData.entrySet().iterator();
while (data.hasNext()) {
Map.Entry entry = (Map.Entry) data.next();
// Properties key/values can be safely cast to strings
// Encode the string
postStr.append(URLEncoder.encode((String) entry.getKey(), "UTF-8"));
postStr.append('=');
postStr.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
if (data.hasNext()) {
postStr.append('&');
}
}
}
// Set entity headers
String encoding = conn.getRequestProperty("Content-Encoding");
if (StringUtil.isEmpty(encoding)) {
encoding = "UTF-8";
}
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postStr.length()));
conn.setRequestProperty("Content-Encoding", encoding);
// Get outputstream (this is where the connect actually happens)
OutputStream os = conn.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, encoding);
// Write post data to the stream
writer.write(postStr.toString());
writer.write("\r\n");
writer.close(); // Does this close the underlying stream?
// Get the inputstream
InputStream is = conn.getInputStream();
// We only accept the 200 OK message
// TODO: Accept all 200 messages, like ACCEPTED, CREATED or NO_CONTENT?
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("The request gave the response: " + conn.getResponseCode() + ": " + conn.getResponseMessage());
}
return is;
}
/**
* Creates a HTTP connection to the given URL.
*
* @param pURL the URL to get.
* @param pProperties connection properties.
* @param pFollowRedirects specifies whether we should follow redirects.
* @param pTimeout the specified timeout, in milliseconds.
* @return a HttpURLConnection
* @throws UnknownHostException if the hostname in the URL cannot be found.
* @throws IOException if an I/O exception occurs.
*/
public static HttpURLConnection createHttpURLConnection(URL pURL, Properties pProperties, boolean pFollowRedirects, int pTimeout)
throws IOException {
// Open the connection, and get the stream
HttpURLConnection conn;
if (pTimeout > 0) {
// Supports timeout
conn = new com.twelvemonkeys.net.HttpURLConnection(pURL, pTimeout);
}
else {
// Faster, more compatible
conn = (HttpURLConnection) pURL.openConnection();
}
// Set user agent
if ((pProperties == null) || !pProperties.containsKey("User-Agent")) {
conn.setRequestProperty("User-Agent",
VERSION_ID
+ " (" + System.getProperty("os.name") + "/" + System.getProperty("os.version") + "; "
+ System.getProperty("os.arch") + "; "
+ System.getProperty("java.vm.name") + "/" + System.getProperty("java.vm.version") + ")");
}
// Set request properties
if (pProperties != null) {
for (Map.Entry<Object, Object> entry : pProperties.entrySet()) {
// Properties key/values can be safely cast to strings
conn.setRequestProperty((String) entry.getKey(), entry.getValue().toString());
}
}
try {
// Breaks with JRE1.2?
conn.setInstanceFollowRedirects(pFollowRedirects);
}
catch (LinkageError le) {
// This is the best we can do...
HttpURLConnection.setFollowRedirects(pFollowRedirects);
System.err.println("You are using an old Java Spec, consider upgrading.");
System.err.println("java.net.HttpURLConnection.setInstanceFollowRedirects(" + pFollowRedirects + ") failed.");
//le.printStackTrace(System.err);
}
conn.setDoInput(true);
conn.setDoOutput(true);
//conn.setUseCaches(true);
return conn;
}
/**
* This is a hack to get around the protected constructors in
* HttpURLConnection, should maybe consider registering and do things
* properly...
*/
/*
private static class TimedHttpURLConnection
extends com.twelvemonkeys.net.HttpURLConnection {
TimedHttpURLConnection(URL pURL, int pTimeout) {
super(pURL, pTimeout);
}
}
*/
/**
* Gets the content from a given URL, with the given timeout.
* The timeout must be > 0. A timeout of zero is interpreted as an
* infinite timeout. Supports basic HTTP
* authentication, using a URL string similar to most browsers.
* <P/>
* <SMALL>Implementation note: If the timeout parameter is greater than 0,
* this method uses my own implementation of
* java.net.HttpURLConnection, that uses plain sockets, to create an
* HTTP connection to the given URL. The {@code read} methods called
* on the returned InputStream, will block only for the specified timeout.
* If the timeout expires, a java.io.InterruptedIOException is raised.
* <BR/>
* </SMALL>
*
* @param pURL the URL to get.
* @param pTimeout the specified timeout, in milliseconds.
* @return a byte array that is read from the socket connection, created
* from the given URL.
* @throws MalformedURLException if the url parameter specifies an
* unknown protocol, or does not form a valid URL.
* @throws UnknownHostException if the IP address for the given URL cannot
* be resolved.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see #getBytesHttp(URL,int)
* @see java.net.Socket
* @see java.net.Socket#setSoTimeout(int) setSoTimeout
* @see java.io.InterruptedIOException
* @see <A href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</A>
*/
public static byte[] getBytesHttp(String pURL, int pTimeout) throws IOException {
// Get the input stream from the url
InputStream in = new BufferedInputStream(getInputStreamHttp(pURL, pTimeout), BUF_SIZE * 2);
// Get all the bytes in loop
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
int count;
byte[] buffer = new byte[BUF_SIZE];
try {
while ((count = in.read(buffer)) != -1) {
// NOTE: According to the J2SE API doc, read(byte[]) will read
// at least 1 byte, or return -1, if end-of-file is reached.
bytes.write(buffer, 0, count);
}
}
finally {
// Close the buffer
in.close();
}
return bytes.toByteArray();
}
/**
* Gets the content from a given URL, with the given timeout.
* The timeout must be > 0. A timeout of zero is interpreted as an
* infinite timeout.
* <P/>
* <SMALL>Implementation note: If the timeout parameter is greater than 0,
* this method uses my own implementation of
* java.net.HttpURLConnection, that uses plain sockets, to create an
* HTTP connection to the given URL. The {@code read} methods called
* on the returned InputStream, will block only for the specified timeout.
* If the timeout expires, a java.io.InterruptedIOException is raised.
* <BR/>
* </SMALL>
*
* @param pURL the URL to get.
* @param pTimeout the specified timeout, in milliseconds.
* @return an input stream that reads from the socket connection, created
* from the given URL.
* @throws UnknownHostException if the IP address for the given URL cannot
* be resolved.
* @throws FileNotFoundException if there is no file at the given URL.
* @throws IOException if an error occurs during transfer.
* @see #getInputStreamHttp(URL,int)
* @see com.twelvemonkeys.net.HttpURLConnection
* @see java.net.Socket
* @see java.net.Socket#setSoTimeout(int) setSoTimeout
* @see HttpURLConnection
* @see java.io.InterruptedIOException
* @see <A href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</A>
*/
public static byte[] getBytesHttp(URL pURL, int pTimeout) throws IOException {
// Get the input stream from the url
InputStream in = new BufferedInputStream(getInputStreamHttp(pURL, pTimeout), BUF_SIZE * 2);
// Get all the bytes in loop
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
int count;
byte[] buffer = new byte[BUF_SIZE];
try {
while ((count = in.read(buffer)) != -1) {
// NOTE: According to the J2SE API doc, read(byte[]) will read
// at least 1 byte, or return -1, if end-of-file is reached.
bytes.write(buffer, 0, count);
}
}
finally {
// Close the buffer
in.close();
}
return bytes.toByteArray();
}
/**
* Unregisters the password asscociated with this URL
*/
/*
private static void unregisterPassword(URL pURL) {
Authenticator auth = registerAuthenticator();
if (auth != null && auth instanceof SimpleAuthenticator)
((SimpleAuthenticator) auth)
.unregisterPasswordAuthentication(pURL);
}
*/
/**
* Registers the password from the URL string, and returns the URL object.
*/
/*
private static URL getURLAndRegisterPassword(String pURL)
throws MalformedURLException
{
// Split user/password away from url
String userPass = null;
String protocolPrefix = HTTP;
int httpIdx = pURL.indexOf(HTTPS);
if (httpIdx >= 0) {
protocolPrefix = HTTPS;
pURL = pURL.substring(httpIdx + HTTPS.length());
}
else {
httpIdx = pURL.indexOf(HTTP);
if (httpIdx >= 0)
pURL = pURL.substring(httpIdx + HTTP.length());
}
int atIdx = pURL.indexOf("@");
if (atIdx >= 0) {
userPass = pURL.substring(0, atIdx);
pURL = pURL.substring(atIdx + 1);
}
// Set URL
URL url = new URL(protocolPrefix + pURL);
// Set Authenticator if user/password is present
if (userPass != null) {
// System.out.println("Setting password ("+ userPass + ")!");
int colIdx = userPass.indexOf(":");
if (colIdx < 0)
throw new MalformedURLException("Error in username/password!");
String userName = userPass.substring(0, colIdx);
String passWord = <PASSWORD>.substring(colIdx + 1);
// Try to register the authenticator
// System.out.println("Trying to register authenticator!");
Authenticator auth = registerAuthenticator();
// System.out.println("Got authenticator " + auth + ".");
// Register our username/password with it
if (auth != null && auth instanceof SimpleAuthenticator) {
((SimpleAuthenticator) auth)
.registerPasswordAuthentication(url,
new PasswordAuthentication(userName,
passWord.toCharArray()));
}
else {
// Not supported!
throw new RuntimeException("Could not register PasswordAuthentication");
}
}
return url;
}
*/
/**
* Registers the Authenticator given in the system property
* {@code java.net.Authenticator}, or the default implementation
* ({@code com.twelvemonkeys.net.SimpleAuthenticator}).
* <P/>
* BUG: What if authenticator has allready been set outside this class?
*
* @return The Authenticator created and set as default, or null, if it
* was not set as the default. However, there is no (clean) way to
* be sure the authenticator was set (the SimpleAuthenticator uses
* a hack to get around this), so it might be possible that the
* returned authenticator was not set as default...
* @see Authenticator#setDefault(Authenticator)
* @see SimpleAuthenticator
*/
public synchronized static Authenticator registerAuthenticator() {
if (sAuthenticator != null) {
return sAuthenticator;
}
// Get the system property
String authenticatorName = System.getProperty("java.net.Authenticator");
// Try to get the Authenticator from the system property
if (authenticatorName != null) {
try {
Class authenticatorClass = Class.forName(authenticatorName);
sAuthenticator = (Authenticator) authenticatorClass.newInstance();
}
catch (ClassNotFoundException cnfe) {
// We should maybe rethrow this?
}
catch (InstantiationException ie) {
// Ignore
}
catch (IllegalAccessException iae) {
// Ignore
}
}
// Get the default authenticator
if (sAuthenticator == null) {
sAuthenticator = SimpleAuthenticator.getInstance();
}
// Register authenticator as default
Authenticator.setDefault(sAuthenticator);
return sAuthenticator;
}
/**
* Creates the InetAddress object from the given URL.
* Equivalent to calling {@code InetAddress.getByName(URL.getHost())}
* except that it returns null, instead of throwing UnknownHostException.
*
* @param pURL the URL to look up.
* @return the createad InetAddress, or null if the host was unknown.
* @see java.net.InetAddress
* @see java.net.URL
*/
public static InetAddress createInetAddressFromURL(URL pURL) {
try {
return InetAddress.getByName(pURL.getHost());
}
catch (UnknownHostException e) {
return null;
}
}
/**
* Creates an URL from the given InetAddress object, using the given
* protocol.
* Equivalent to calling
* {@code new URL(protocol, InetAddress.getHostName(), "")}
* except that it returns null, instead of throwing MalformedURLException.
*
* @param pIP the IP address to look up
* @param pProtocol the protocol to use in the new URL
* @return the created URL or null, if the URL could not be created.
* @see java.net.URL
* @see java.net.InetAddress
*/
public static URL createURLFromInetAddress(InetAddress pIP, String pProtocol) {
try {
return new URL(pProtocol, pIP.getHostName(), "");
}
catch (MalformedURLException e) {
return null;
}
}
/**
* Creates an URL from the given InetAddress object, using HTTP protocol.
* Equivalent to calling
* {@code new URL("http", InetAddress.getHostName(), "")}
* except that it returns null, instead of throwing MalformedURLException.
*
* @param pIP the IP address to look up
* @return the created URL or null, if the URL could not be created.
* @see java.net.URL
* @see java.net.InetAddress
*/
public static URL createURLFromInetAddress(InetAddress pIP) {
return createURLFromInetAddress(pIP, HTTP);
}
/*
* TODO: Benchmark!
*/
static byte[] getBytesHttpOld(String pURL) throws IOException {
// Get the input stream from the url
InputStream in = new BufferedInputStream(getInputStreamHttp(pURL), BUF_SIZE * 2);
// Get all the bytes in loop
byte[] bytes = new byte[0];
int count;
byte[] buffer = new byte[BUF_SIZE];
try {
while ((count = in.read(buffer)) != -1) {
// NOTE: According to the J2SE API doc, read(byte[]) will read
// at least 1 byte, or return -1, if end-of-file is reached.
bytes = (byte[]) CollectionUtil.mergeArrays(bytes, 0, bytes.length, buffer, 0, count);
}
}
finally {
// Close the buffer
in.close();
}
return bytes;
}
} | 20,986 |
373 | /** @file
*
* Copyright (c) 2015, Hisilicon Limited. All rights reserved.
* Copyright (c) 2015, Linaro Limited. All rights reserved.
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*
**/
#ifndef _MEMORY_MAP_GUID_H_
#define _MEMORY_MAP_GUID_H_
#define EFI_MEMORY_MAP_GUID \
{ \
0xf8870015,0x6994,0x4b98,0x95,0xa2,0xbd,0x56,0xda,0x91,0xc0,0x7f \
}
extern EFI_GUID gHisiEfiMemoryMapGuid;
#endif
| 226 |
2,151 | // 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.
package org.chromium.chrome.browser.offlinepages;
import android.net.Uri;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SmallTest;
import android.util.Base64;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.Callback;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.RetryOnFailure;
import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.offlinepages.OfflinePageBridge.OfflinePageModelObserver;
import org.chromium.chrome.browser.offlinepages.OfflinePageBridge.SavePageCallback;
import org.chromium.chrome.browser.offlinepages.downloads.OfflinePageDownloadBridge;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.test.ChromeActivityTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.components.offlinepages.DeletePageResult;
import org.chromium.components.offlinepages.SavePageResult;
import org.chromium.components.offlinepages.background.UpdateRequestResult;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.net.NetworkChangeNotifier;
import org.chromium.net.test.EmbeddedTestServer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
/** Unit tests for {@link OfflinePageBridge}. */
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class OfflinePageBridgeTest {
@Rule
public ChromeActivityTestRule<ChromeActivity> mActivityTestRule =
new ChromeActivityTestRule<>(ChromeActivity.class);
private static final String TEST_PAGE = "/chrome/test/data/android/about.html";
private static final int TIMEOUT_MS = 5000;
private static final long POLLING_INTERVAL = 100;
private static final ClientId TEST_CLIENT_ID =
new ClientId(OfflinePageBridge.DOWNLOAD_NAMESPACE, "1234");
private OfflinePageBridge mOfflinePageBridge;
private EmbeddedTestServer mTestServer;
private String mTestPage;
private void initializeBridgeForProfile(final boolean incognitoProfile)
throws InterruptedException {
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
Profile profile = Profile.getLastUsedProfile();
if (incognitoProfile) {
profile = profile.getOffTheRecordProfile();
}
// Ensure we start in an offline state.
mOfflinePageBridge = OfflinePageBridge.getForProfile(profile);
if (mOfflinePageBridge == null || mOfflinePageBridge.isOfflinePageModelLoaded()) {
semaphore.release();
return;
}
mOfflinePageBridge.addObserver(new OfflinePageModelObserver() {
@Override
public void offlinePageModelLoaded() {
semaphore.release();
mOfflinePageBridge.removeObserver(this);
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
@Before
public void setUp() throws Exception {
mActivityTestRule.startMainActivityOnBlankPage();
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
// Ensure we start in an offline state.
NetworkChangeNotifier.forceConnectivityState(false);
if (!NetworkChangeNotifier.isInitialized()) {
NetworkChangeNotifier.init();
}
}
});
initializeBridgeForProfile(false);
mTestServer = EmbeddedTestServer.createAndStartServer(InstrumentationRegistry.getContext());
mTestPage = mTestServer.getURL(TEST_PAGE);
}
@After
public void tearDown() throws Exception {
mTestServer.stopAndDestroyServer();
}
@Test
@SmallTest
@RetryOnFailure
public void testLoadOfflinePagesWhenEmpty() throws Exception {
List<OfflinePageItem> offlinePages = getAllPages();
Assert.assertEquals("Offline pages count incorrect.", 0, offlinePages.size());
}
@Test
@SmallTest
@RetryOnFailure
public void testAddOfflinePageAndLoad() throws Exception {
mActivityTestRule.loadUrl(mTestPage);
savePage(SavePageResult.SUCCESS, mTestPage);
List<OfflinePageItem> allPages = getAllPages();
OfflinePageItem offlinePage = allPages.get(0);
Assert.assertEquals("Offline pages count incorrect.", 1, allPages.size());
Assert.assertEquals("Offline page item url incorrect.", mTestPage, offlinePage.getUrl());
}
@Test
@SmallTest
@RetryOnFailure
public void testGetPageByBookmarkId() throws Exception {
mActivityTestRule.loadUrl(mTestPage);
savePage(SavePageResult.SUCCESS, mTestPage);
OfflinePageItem offlinePage = getPageByClientId(TEST_CLIENT_ID);
Assert.assertEquals("Offline page item url incorrect.", mTestPage, offlinePage.getUrl());
Assert.assertNull("Offline page is not supposed to exist",
getPageByClientId(new ClientId(OfflinePageBridge.BOOKMARK_NAMESPACE, "-42")));
}
@Test
@SmallTest
@RetryOnFailure
public void testDeleteOfflinePage() throws Exception {
deletePage(TEST_CLIENT_ID, DeletePageResult.SUCCESS);
mActivityTestRule.loadUrl(mTestPage);
savePage(SavePageResult.SUCCESS, mTestPage);
Assert.assertNotNull("Offline page should be available, but it is not.",
getPageByClientId(TEST_CLIENT_ID));
deletePage(TEST_CLIENT_ID, DeletePageResult.SUCCESS);
Assert.assertNull("Offline page should be gone, but it is available.",
getPageByClientId(TEST_CLIENT_ID));
}
@Test
@CommandLineFlags.Add("disable-features=OfflinePagesSharing")
@SmallTest
@RetryOnFailure
public void testPageSharingSwitch() throws Exception {
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
Assert.assertFalse(
"If offline page sharing is off, we should see the feature disabled",
OfflinePageBridge.isPageSharingEnabled());
}
});
}
@Test
@SmallTest
@RetryOnFailure
public void testGetRequestsInQueue() throws Exception {
String url = "https://www.google.com/";
String namespace = "custom_tabs";
savePageLater(url, namespace);
SavePageRequest[] requests = getRequestsInQueue();
Assert.assertEquals(1, requests.length);
Assert.assertEquals(namespace, requests[0].getClientId().getNamespace());
Assert.assertEquals(url, requests[0].getUrl());
String url2 = "https://mail.google.com/";
String namespace2 = "last_n";
savePageLater(url2, namespace2);
requests = getRequestsInQueue();
Assert.assertEquals(2, requests.length);
HashSet<String> expectedUrls = new HashSet<>();
expectedUrls.add(url);
expectedUrls.add(url2);
HashSet<String> expectedNamespaces = new HashSet<>();
expectedNamespaces.add(namespace);
expectedNamespaces.add(namespace2);
for (SavePageRequest request : requests) {
Assert.assertTrue(expectedNamespaces.contains(request.getClientId().getNamespace()));
expectedNamespaces.remove(request.getClientId().getNamespace());
Assert.assertTrue(expectedUrls.contains(request.getUrl()));
expectedUrls.remove(request.getUrl());
}
}
@Test
@SmallTest
@RetryOnFailure
public void testOfflinePageBridgeDisabledInIncognito() throws Exception {
initializeBridgeForProfile(true);
Assert.assertEquals(null, mOfflinePageBridge);
}
@Test
@SmallTest
@RetryOnFailure
public void testRemoveRequestsFromQueue() throws Exception {
String url = "https://www.google.com/";
String namespace = "custom_tabs";
savePageLater(url, namespace);
String url2 = "https://mail.google.com/";
String namespace2 = "last_n";
savePageLater(url2, namespace2);
SavePageRequest[] requests = getRequestsInQueue();
Assert.assertEquals(2, requests.length);
List<Long> requestsToRemove = new ArrayList<>();
requestsToRemove.add(Long.valueOf(requests[1].getRequestId()));
List<OfflinePageBridge.RequestRemovedResult> removed =
removeRequestsFromQueue(requestsToRemove);
Assert.assertEquals(requests[1].getRequestId(), removed.get(0).getRequestId());
Assert.assertEquals(UpdateRequestResult.SUCCESS, removed.get(0).getUpdateRequestResult());
SavePageRequest[] remaining = getRequestsInQueue();
Assert.assertEquals(1, remaining.length);
Assert.assertEquals(requests[0].getRequestId(), remaining[0].getRequestId());
Assert.assertEquals(requests[0].getUrl(), remaining[0].getUrl());
}
@Test
@SmallTest
public void testDeletePagesByOfflineIds() throws Exception {
// Save 3 pages and record their offline IDs to delete later.
Set<String> pageUrls = new HashSet<>();
pageUrls.add(mTestPage);
pageUrls.add(mTestPage + "?foo=1");
pageUrls.add(mTestPage + "?foo=2");
int pagesToDeleteCount = pageUrls.size();
List<Long> offlineIdsToDelete = new ArrayList<>();
for (String url : pageUrls) {
mActivityTestRule.loadUrl(url);
offlineIdsToDelete.add(savePage(SavePageResult.SUCCESS, url));
}
Assert.assertEquals("The pages should exist now that we saved them.", pagesToDeleteCount,
getUrlsExistOfflineFromSet(pageUrls).size());
// Save one more page but don't save the offline ID, this page should not be deleted.
Set<String> pageUrlsToSave = new HashSet<>();
String pageToSave = mTestPage + "?bar=1";
pageUrlsToSave.add(pageToSave);
int pagesToSaveCount = pageUrlsToSave.size();
for (String url : pageUrlsToSave) {
mActivityTestRule.loadUrl(url);
savePage(SavePageResult.SUCCESS, pageToSave);
}
Assert.assertEquals("The pages should exist now that we saved them.", pagesToSaveCount,
getUrlsExistOfflineFromSet(pageUrlsToSave).size());
// Delete the first 3 pages.
deletePages(offlineIdsToDelete);
Assert.assertEquals(
"The page should cease to exist.", 0, getUrlsExistOfflineFromSet(pageUrls).size());
// We should not have deleted the one we didn't ask to delete.
Assert.assertEquals("The page should not be deleted.", pagesToSaveCount,
getUrlsExistOfflineFromSet(pageUrlsToSave).size());
}
@Test
@SmallTest
public void testGetPagesByNamespace() throws Exception {
// Save 3 pages and record their offline IDs to delete later.
Set<Long> offlineIdsToFetch = new HashSet<>();
for (int i = 0; i < 3; i++) {
String url = mTestPage + "?foo=" + i;
mActivityTestRule.loadUrl(url);
offlineIdsToFetch.add(savePage(SavePageResult.SUCCESS, url));
}
// Save a page in a different namespace.
String urlToIgnore = mTestPage + "?bar=1";
mActivityTestRule.loadUrl(urlToIgnore);
long offlineIdToIgnore = savePage(SavePageResult.SUCCESS, urlToIgnore,
new ClientId(OfflinePageBridge.ASYNC_NAMESPACE, "-42"));
List<OfflinePageItem> pages = getPagesByNamespace(OfflinePageBridge.DOWNLOAD_NAMESPACE);
Assert.assertEquals(
"The number of pages returned does not match the number of pages saved.",
offlineIdsToFetch.size(), pages.size());
for (OfflinePageItem page : pages) {
offlineIdsToFetch.remove(page.getOfflineId());
}
Assert.assertEquals(
"There were different pages saved than those returned by getPagesByNamespace.", 0,
offlineIdsToFetch.size());
// Check that the page in the other namespace still exists.
List<OfflinePageItem> asyncPages = getPagesByNamespace(OfflinePageBridge.ASYNC_NAMESPACE);
Assert.assertEquals("The page saved in an alternate namespace is no longer there.", 1,
asyncPages.size());
Assert.assertEquals(
"The offline ID of the page saved in an alternate namespace does not match.",
offlineIdToIgnore, asyncPages.get(0).getOfflineId());
}
@Test
@SmallTest
@RetryOnFailure
public void testDownloadPage() throws Exception {
final OfflinePageOrigin origin =
new OfflinePageOrigin("abc.xyz", new String[] {"deadbeef"});
mActivityTestRule.loadUrl(mTestPage);
final String originString = origin.encodeAsJsonString();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
Assert.assertNotNull(
"Tab is null", mActivityTestRule.getActivity().getActivityTab());
Assert.assertEquals("URL does not match requested.", mTestPage,
mActivityTestRule.getActivity().getActivityTab().getUrl());
Assert.assertNotNull("WebContents is null", mActivityTestRule.getWebContents());
mOfflinePageBridge.addObserver(new OfflinePageModelObserver() {
@Override
public void offlinePageAdded(OfflinePageItem newPage) {
mOfflinePageBridge.removeObserver(this);
semaphore.release();
}
});
OfflinePageDownloadBridge.startDownload(
mActivityTestRule.getActivity().getActivityTab(), origin);
}
});
Assert.assertTrue("Semaphore acquire failed. Timed out.",
semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
List<OfflinePageItem> pages = getAllPages();
Assert.assertEquals(originString, pages.get(0).getRequestOrigin());
}
@Test
@SmallTest
public void testSavePageWithRequestOrigin() throws Exception {
final OfflinePageOrigin origin =
new OfflinePageOrigin("abc.xyz", new String[] {"deadbeef"});
mActivityTestRule.loadUrl(mTestPage);
final String originString = origin.encodeAsJsonString();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.addObserver(new OfflinePageModelObserver() {
@Override
public void offlinePageAdded(OfflinePageItem newPage) {
mOfflinePageBridge.removeObserver(this);
semaphore.release();
}
});
mOfflinePageBridge.savePage(mActivityTestRule.getWebContents(), TEST_CLIENT_ID,
origin, new SavePageCallback() {
@Override
public void onSavePageDone(
int savePageResult, String url, long offlineId) {}
});
}
});
Assert.assertTrue("Semaphore acquire failed. Timed out.",
semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
List<OfflinePageItem> pages = getAllPages();
Assert.assertEquals(originString, pages.get(0).getRequestOrigin());
}
@Test
@SmallTest
@DisabledTest(message = "crbug.com/842801")
public void testSavePageNoOrigin() throws Exception {
mActivityTestRule.loadUrl(mTestPage);
savePage(SavePageResult.SUCCESS, mTestPage);
List<OfflinePageItem> pages = getAllPages();
Assert.assertEquals("", pages.get(0).getRequestOrigin());
}
@Test
@SmallTest
@RetryOnFailure
public void testGetLoadUrlParamsForOpeningMhtmlFileUrl() throws Exception {
mActivityTestRule.loadUrl(mTestPage);
savePage(SavePageResult.SUCCESS, mTestPage);
List<OfflinePageItem> allPages = getAllPages();
Assert.assertEquals(1, allPages.size());
OfflinePageItem offlinePage = allPages.get(0);
File archiveFile = new File(offlinePage.getFilePath());
// The file URL pointing to the archive file should be replaced with http/https URL of the
// offline page.
String fileUrl = Uri.fromFile(archiveFile).toString();
LoadUrlParams loadUrlParams = getLoadUrlParamsForOpeningMhtmlFileOrContent(fileUrl);
Assert.assertEquals(offlinePage.getUrl(), loadUrlParams.getUrl());
String extraHeaders = loadUrlParams.getVerbatimHeaders();
Assert.assertNotNull(extraHeaders);
Assert.assertNotEquals(-1, extraHeaders.indexOf("reason=file_url_intent"));
Assert.assertNotEquals("intent_url field not found in header: " + extraHeaders, -1,
extraHeaders.indexOf("intent_url="
+ Base64.encodeToString(
ApiCompatibilityUtils.getBytesUtf8(fileUrl), Base64.NO_WRAP)));
Assert.assertNotEquals(
-1, extraHeaders.indexOf("id=" + Long.toString(offlinePage.getOfflineId())));
// Make a copy of the original archive file.
File tempFile = File.createTempFile("Test", "");
copyFile(archiveFile, tempFile);
// The file URL pointing to file copy should also be replaced with http/https URL of the
// offline page.
String tempFileUrl = Uri.fromFile(tempFile).toString();
loadUrlParams = getLoadUrlParamsForOpeningMhtmlFileOrContent(tempFileUrl);
Assert.assertEquals(offlinePage.getUrl(), loadUrlParams.getUrl());
extraHeaders = loadUrlParams.getVerbatimHeaders();
Assert.assertNotNull(extraHeaders);
Assert.assertNotEquals("reason field not found in header: " + extraHeaders, -1,
extraHeaders.indexOf("reason=file_url_intent"));
Assert.assertNotEquals("intent_url field not found in header: " + extraHeaders, -1,
extraHeaders.indexOf("intent_url="
+ Base64.encodeToString(ApiCompatibilityUtils.getBytesUtf8(tempFileUrl),
Base64.NO_WRAP)));
Assert.assertNotEquals("id field not found in header: " + extraHeaders, -1,
extraHeaders.indexOf("id=" + Long.toString(offlinePage.getOfflineId())));
// Modify the copied file.
FileChannel tempFileChannel = new FileOutputStream(tempFile, true).getChannel();
tempFileChannel.truncate(10);
tempFileChannel.close();
// The file URL pointing to modified file copy should still get the file URL.
loadUrlParams = getLoadUrlParamsForOpeningMhtmlFileOrContent(tempFileUrl);
Assert.assertEquals(tempFileUrl, loadUrlParams.getUrl());
extraHeaders = loadUrlParams.getVerbatimHeaders();
Assert.assertEquals("", extraHeaders);
// Cleans up.
Assert.assertTrue(tempFile.delete());
}
// Returns offline ID.
private long savePage(final int expectedResult, final String expectedUrl)
throws InterruptedException {
return savePage(expectedResult, expectedUrl, TEST_CLIENT_ID);
}
// Returns offline ID.
private long savePage(final int expectedResult, final String expectedUrl,
final ClientId clientId) throws InterruptedException {
final Semaphore semaphore = new Semaphore(0);
final AtomicLong result = new AtomicLong(-1);
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
Assert.assertNotNull(
"Tab is null", mActivityTestRule.getActivity().getActivityTab());
Assert.assertEquals("URL does not match requested.", expectedUrl,
mActivityTestRule.getActivity().getActivityTab().getUrl());
Assert.assertNotNull("WebContents is null", mActivityTestRule.getWebContents());
mOfflinePageBridge.savePage(
mActivityTestRule.getWebContents(), clientId, new SavePageCallback() {
@Override
public void onSavePageDone(
int savePageResult, String url, long offlineId) {
Assert.assertEquals(
"Requested and returned URLs differ.", expectedUrl, url);
Assert.assertEquals(
"Save result incorrect.", expectedResult, savePageResult);
result.set(offlineId);
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
return result.get();
}
private void deletePages(final List<Long> offlineIds) throws InterruptedException {
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.deletePagesByOfflineId(offlineIds, new Callback<Integer>() {
@Override
public void onResult(Integer deletePageResult) {
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
private void deletePage(final ClientId bookmarkId, final int expectedResult)
throws InterruptedException {
final Semaphore semaphore = new Semaphore(0);
final AtomicInteger deletePageResultRef = new AtomicInteger();
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.deletePage(bookmarkId, new Callback<Integer>() {
@Override
public void onResult(Integer deletePageResult) {
deletePageResultRef.set(deletePageResult.intValue());
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
Assert.assertEquals("Delete result incorrect.", expectedResult, deletePageResultRef.get());
}
private List<OfflinePageItem> getAllPages() throws InterruptedException {
final List<OfflinePageItem> result = new ArrayList<OfflinePageItem>();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.getAllPages(new Callback<List<OfflinePageItem>>() {
@Override
public void onResult(List<OfflinePageItem> pages) {
result.addAll(pages);
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
return result;
}
private List<OfflinePageItem> getPagesByNamespace(final String namespace)
throws InterruptedException {
final List<OfflinePageItem> result = new ArrayList<OfflinePageItem>();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.getPagesByNamespace(
namespace, new Callback<List<OfflinePageItem>>() {
@Override
public void onResult(List<OfflinePageItem> pages) {
result.addAll(pages);
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
return result;
}
private void forceConnectivityStateOnUiThread(final boolean state) {
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
NetworkChangeNotifier.forceConnectivityState(state);
}
});
}
private OfflinePageItem getPageByClientId(ClientId clientId) throws InterruptedException {
final OfflinePageItem[] result = {null};
final Semaphore semaphore = new Semaphore(0);
final List<ClientId> clientIdList = new ArrayList<>();
clientIdList.add(clientId);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.getPagesByClientIds(
clientIdList, new Callback<List<OfflinePageItem>>() {
@Override
public void onResult(List<OfflinePageItem> items) {
if (!items.isEmpty()) {
result[0] = items.get(0);
}
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
return result[0];
}
private Set<String> getUrlsExistOfflineFromSet(final Set<String> query)
throws InterruptedException {
final Set<String> result = new HashSet<>();
final List<OfflinePageItem> pages = new ArrayList<>();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.getAllPages(new Callback<List<OfflinePageItem>>() {
@Override
public void onResult(List<OfflinePageItem> offlinePages) {
pages.addAll(offlinePages);
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
for (String url : query) {
for (OfflinePageItem page : pages) {
if (url.equals(page.getUrl())) {
result.add(page.getUrl());
}
}
}
return result;
}
private void savePageLater(final String url, final String namespace)
throws InterruptedException {
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.savePageLater(url, namespace, true /* userRequested */,
new OfflinePageOrigin(), new Callback<Integer>() {
@Override
public void onResult(Integer i) {
Assert.assertEquals("SavePageLater did not succeed",
Integer.valueOf(0),
i); // 0 is SUCCESS
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
private SavePageRequest[] getRequestsInQueue() throws InterruptedException {
final AtomicReference<SavePageRequest[]> ref = new AtomicReference<>();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.getRequestsInQueue(new Callback<SavePageRequest[]>() {
@Override
public void onResult(SavePageRequest[] requestsInQueue) {
ref.set(requestsInQueue);
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
return ref.get();
}
private List<OfflinePageBridge.RequestRemovedResult> removeRequestsFromQueue(
final List<Long> requestsToRemove) throws InterruptedException {
final AtomicReference<List<OfflinePageBridge.RequestRemovedResult>> ref =
new AtomicReference<>();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.removeRequestsFromQueue(requestsToRemove,
new Callback<List<OfflinePageBridge.RequestRemovedResult>>() {
@Override
public void onResult(
List<OfflinePageBridge.RequestRemovedResult> removedRequests) {
ref.set(removedRequests);
semaphore.release();
}
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
return ref.get();
}
private LoadUrlParams getLoadUrlParamsForOpeningMhtmlFileOrContent(String url)
throws InterruptedException {
final AtomicReference<LoadUrlParams> ref = new AtomicReference<>();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.getLoadUrlParamsForOpeningMhtmlFileOrContent(
url, (loadUrlParams) -> {
ref.set(loadUrlParams);
semaphore.release();
});
}
});
Assert.assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
return ref.get();
}
private static void copyFile(File source, File dest) throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
}
}
| 14,451 |
416 | <filename>iPhoneOS14.2.sdk/System/Library/Frameworks/NetworkExtension.framework/Headers/NEAppPushProvider.h
/*
* Copyright (c) 2020 Apple Inc.
* All rights reserved.
*/
#ifndef __NE_INDIRECT__
#error "Please import the NetworkExtension module instead of this file directly."
#endif
NS_ASSUME_NONNULL_BEGIN
/*!
* @file NEAppPushProvider.h
* @discussion This file declares the NEAppPushProvider API. The NEAppPushProvider API is used to manage the life cycle of the provider.
* The API also allows provider to report incoming call and handle outgoing call message from the containing app.
*/
/*!
* @interface NEAppPushProvider
* @discussion The NEAppPushProvider class declares a programmatic interface to manage a life cycle of app push provider. It also allows the provider to handle outgoing
* communication message from the containing app, and pass incoming call message to the containing app.
* NEAppPushProvider is part of NetworkExtension.framework
*/
API_AVAILABLE(ios(14.0)) API_UNAVAILABLE(macos, tvos) __WATCHOS_PROHIBITED
@interface NEAppPushProvider : NEProvider
/*!
* @property providerConfiguration
* @discussion A dictionary containing current vendor-specific configuration parameters. This dictionary is provided by NEAppPushManager. Use KVO to watch for changes.
*/
@property (readonly, nullable) NSDictionary<NSString *, id> *providerConfiguration API_AVAILABLE(ios(14.0)) API_UNAVAILABLE(macos, tvos) __WATCHOS_PROHIBITED;
/*!
* @method startWithCompletionHandler:completionHandler:
* @discussion This method is called by the framework when the provider is started. Subclasses must override this method to create a connection with its server.
* @param completionHandler A block that must be called when the provider establishes a connection with the server. If the providers fails to create a connection,
* the subclass' implementation of this method must pass a non-nil NSError object to this block. A value of nil passed to the completion handler indicates that the connection
* was successfully created.
*/
- (void)startWithCompletionHandler:(void (^)(NSError * __nullable error))completionHandler API_AVAILABLE(ios(14.0)) API_UNAVAILABLE(macos, tvos) __WATCHOS_PROHIBITED;
/*!
* @method stopWithReason:reason:completionHandler:
* @discussion This method is called by the framework when the app push provider needs to be stopped. Subclasses must override this method to perform necessary tasks.
* @param reason An NEProviderStopReason indicating why the provider was stopped.
* @param completionHandler A block that must be called when the provider is completely stopped.
*/
- (void)stopWithReason:(NEProviderStopReason)reason completionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(14.0)) API_UNAVAILABLE(macos, tvos) __WATCHOS_PROHIBITED;
/*!
* @method reportIncomingCallWithUserInfo:userinfo:
* @discussion This function is called by the provider when it determines incoming call on the conection.
* @param userInfo A dictionary of custom information associated with the incoming call. This dictionary is passed to containg app as-is.
*/
- (void)reportIncomingCallWithUserInfo:(NSDictionary * _Nonnull)userInfo API_AVAILABLE(ios(14.0)) API_UNAVAILABLE(macos, tvos) __WATCHOS_PROHIBITED;
/*!
* @method handleTimerEvent
* @discussion This method is called by the framework periodically after every 60 seconds. Subclasses must override this method to perform necessary tasks.
*/
- (void)handleTimerEvent API_AVAILABLE(ios(14.0)) API_UNAVAILABLE(macos, tvos) __WATCHOS_PROHIBITED;
@end
NS_ASSUME_NONNULL_END
| 977 |
587 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.util.json;
public interface JsonHandlerProvider {
/**
* This will be called for every entry in a map. If you want to provide a
* special handler for that key, return its handler. If you return null, the
* default handler implementation will be used.
*
* @param key The key in the parent object for which the handler is being
* requested.
*/
JsonHandlerProvider getObjectEntryHandlerProvider(String key);
/**
* This will be called once each time an array is read. The returned handler
* provider will be used to get a handler for each object or array within
* the array. If you return null, the default handler implementation will be
* used.
*/
JsonHandlerProvider getArrayEntryHandlerProvider();
/**
* Return a handler to be used for reading an object.
*/
JsonObjectHandler getObjectHandler();
/**
* Return a handler to be used for reading an array.
*/
JsonArrayHandler getArrayHandler();
}
| 495 |
14,668 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/services/storage/public/mojom/buckets/bucket_id_mojom_traits.h"
#include "components/services/storage/public/cpp/buckets/bucket_id.h"
#include "components/services/storage/public/mojom/buckets/bucket_id.mojom.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace storage {
namespace {
TEST(BucketIdMojomTraitsTest, SerializeAndDeserialize) {
BucketId test_keys[] = {
BucketId(1),
BucketId(123),
BucketId(),
};
for (auto& original : test_keys) {
BucketId copied;
EXPECT_TRUE(
mojo::test::SerializeAndDeserialize<mojom::BucketId>(original, copied));
EXPECT_EQ(original, copied);
}
}
} // namespace
} // namespace storage
| 344 |
544 | <reponame>giladsharir/MNC-1
# --------------------------------------------------------
# Multitask Network Cascade
# Written by <NAME>
# Copyright (c) 2016, <NAME>
# Licensed under The MIT License [see LICENSE for details]
# --------------------------------------------------------
import caffe
import cv2
import numpy as np
from transform.mask_transform import mask_overlap
from mnc_config import cfg
class MaskLayer(caffe.Layer):
"""
This layer Take input from sigmoid predicted masks
Assign each label for segmentation classifier according
to region overlap
"""
def setup(self, bottom, top):
self._phase = str(self.phase)
self._top_name_map = {}
top[0].reshape(1, 1, cfg.MASK_SIZE, cfg.MASK_SIZE)
self._top_name_map['mask_proposal'] = 0
if self._phase == 'TRAIN':
top[1].reshape(1, 1)
self._top_name_map['mask_proposal_label'] = 1
def reshape(self, bottom, top):
"""
Reshaping happens during the call to forward
"""
pass
def forward(self, bottom, top):
if str(self.phase) == 'TRAIN':
blobs = self.forward_train(bottom, top)
elif str(self.phase) == 'TEST':
blobs = self.forward_test(bottom, top)
else:
print 'Unrecognized phase'
raise NotImplementedError
for blob_name, blob in blobs.iteritems():
top[self._top_name_map[blob_name]].reshape(*blob.shape)
top[self._top_name_map[blob_name]].data[...] = blob.astype(np.float32, copy=False)
def backward(self, top, propagate_down, bottom):
if propagate_down[0]:
bottom[0].diff.fill(0.)
top_grad = top[0].diff.reshape(top[0].diff.shape[0], cfg.MASK_SIZE * cfg.MASK_SIZE)
bottom[0].diff[self.pos_sample, :] = top_grad[self.pos_sample, :]
def forward_train(self, bottom, top):
# Take sigmoid prediction as input
mask_pred = bottom[0].data
# get ground truth mask and labels
gt_masks = bottom[1].data
gt_masks_info = bottom[2].data
num_mask_pred = mask_pred.shape[0]
top_label = np.zeros((gt_masks_info.shape[0], 1))
# 2. Calculate region overlap
# Since the target gt mask may have different size
# We need to resize predicted masks into different sizes
mask_size = cfg.MASK_SIZE
for i in xrange(num_mask_pred):
# if the bounding box is itself background
if gt_masks_info[i][0] == -1:
top_label[i][0] = 0
continue
else:
info = gt_masks_info[i]
gt_mask = gt_masks[info[0]][0:info[1], 0:info[2]]
ex_mask = mask_pred[i].reshape((mask_size, mask_size))
ex_box = np.round(info[4:8]).astype(int)
gt_box = np.round(info[8:12]).astype(int)
# resize to large gt_masks, note cv2.resize is column first
ex_mask = cv2.resize(ex_mask.astype(np.float32), (ex_box[2] - ex_box[0] + 1,
ex_box[3] - ex_box[1] + 1))
ex_mask = ex_mask >= cfg.BINARIZE_THRESH
top_label[i][0] = 0 if mask_overlap(ex_box, gt_box, ex_mask, gt_mask) < cfg.TRAIN.FG_SEG_THRESH else info[3]
# output continuous mask for MNC
resized_mask_pred = mask_pred.reshape((num_mask_pred, 1, cfg.MASK_SIZE, cfg.MASK_SIZE))
self.pos_sample = np.where(top_label > 0)[0]
blobs = {
'mask_proposal': resized_mask_pred,
'mask_proposal_label': top_label
}
return blobs
def forward_test(self, bottom, top):
mask_pred = bottom[0].data
num_mask_pred = mask_pred.shape[0]
resized_mask_pred = mask_pred.reshape((num_mask_pred, 1, cfg.MASK_SIZE, cfg.MASK_SIZE))
blobs = {
'mask_proposal': resized_mask_pred
}
return blobs
| 1,930 |
405 | package org.jeecgframework.core.extend.hqlsearch.parse.impl;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.extend.hqlsearch.parse.IHqlParse;
public class StringParseImpl implements IHqlParse {
private static final String SUFFIX_COMMA = ",";
private static final String SUFFIX_KG = " ";
/** 模糊查询符号 */
private static final String SUFFIX_ASTERISK = "*";
private static final String SUFFIX_ASTERISK_VAGUE = "%";
/** 不等于查询符号 */
private static final String SUFFIX_NOT_EQUAL = "!";
private static final String SUFFIX_NOT_EQUAL_NULL = "!NULL";
public void addCriteria(CriteriaQuery cq, String name, Object value) {
String searchValue = null;
if (value != null && (searchValue = value.toString().trim()) != "") {
// [1].In 多个条件查询{逗号隔开参数}
if (searchValue.indexOf(SUFFIX_COMMA) >= 0) {
// 页面输入查询条件,情况(取消字段的默认条件)
if (searchValue.indexOf(SUFFIX_KG) >= 0) {
String val = searchValue.substring(searchValue
.indexOf(SUFFIX_KG));
cq.eq(name, val);
} else {
String[] vs = searchValue.split(SUFFIX_COMMA);
cq.in(name, vs);
}
}
// [2].模糊查询{带有* 星号的参数}
else if (searchValue.indexOf(SUFFIX_ASTERISK) >= 0) {
cq.like(name, searchValue.replace(SUFFIX_ASTERISK,
SUFFIX_ASTERISK_VAGUE));
}
// [3].不匹配查询{等于!叹号}
// (1).不为空字符串
else if (searchValue.equals(SUFFIX_NOT_EQUAL)) {
cq.isNotNull(name);
}
// (2).不为NULL
else if (searchValue.toUpperCase().equals(SUFFIX_NOT_EQUAL_NULL)) {
cq.isNotNull(name);
}
// (3).正常不匹配
else if (searchValue.indexOf(SUFFIX_NOT_EQUAL) >= 0) {
cq.notEq(name, searchValue.replace(SUFFIX_NOT_EQUAL, ""));
}
// [4].全匹配查询{没有特殊符号的参数}
else {
cq.eq(name, searchValue);
}
}
}
public void addCriteria(CriteriaQuery cq, String name, Object value,
String beginValue, String endValue) {
addCriteria(cq,name,value);
}
}
| 1,032 |
406 | /***************************************************************************
* tests/containers/test_vector_sizes.cpp
*
* Part of the STXXL. See http://stxxl.sourceforge.net
*
* Copyright (C) 2010 <NAME> <<EMAIL>>
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**************************************************************************/
#include <stxxl/io>
#include <stxxl/vector>
typedef int my_type;
typedef stxxl::VECTOR_GENERATOR<my_type>::result vector_type;
typedef vector_type::block_type block_type;
void test_write(const char* fn, const char* ft, stxxl::unsigned_type sz, my_type ofs)
{
stxxl::file* f = stxxl::create_file(ft, fn, stxxl::file::CREAT | stxxl::file::DIRECT | stxxl::file::RDWR);
{
vector_type v(f);
v.resize(sz);
STXXL_MSG("writing " << v.size() << " elements");
for (stxxl::unsigned_type i = 0; i < v.size(); ++i)
v[i] = ofs + (int)i;
}
delete f;
}
template <typename Vector>
void test_rdwr(const char* fn, const char* ft, stxxl::unsigned_type sz, my_type ofs)
{
stxxl::file* f = stxxl::create_file(ft, fn, stxxl::file::DIRECT | stxxl::file::RDWR);
{
Vector v(f);
STXXL_MSG("reading " << v.size() << " elements (RDWR)");
STXXL_CHECK(v.size() == sz);
for (stxxl::unsigned_type i = 0; i < v.size(); ++i)
STXXL_CHECK(v[i] == ofs + my_type(i));
}
delete f;
}
template <typename Vector>
void test_rdonly(const char* fn, const char* ft, stxxl::unsigned_type sz, my_type ofs)
{
stxxl::file* f = stxxl::create_file(ft, fn, stxxl::file::DIRECT | stxxl::file::RDONLY);
{
Vector v(f);
STXXL_MSG("reading " << v.size() << " elements (RDONLY)");
STXXL_CHECK(v.size() == sz);
for (stxxl::unsigned_type i = 0; i < v.size(); ++i)
STXXL_CHECK(v[i] == ofs + my_type(i));
}
delete f;
}
void test(const char* fn, const char* ft, stxxl::unsigned_type sz, my_type ofs)
{
test_write(fn, ft, sz, ofs);
test_rdwr<const vector_type>(fn, ft, sz, ofs);
test_rdwr<vector_type>(fn, ft, sz, ofs);
// 2013-tb: there is a bug with read-only vectors on mmap backed files:
// copying from mmapped area will fail for invalid ranges at the end,
// whereas a usual read() will just stop short at the end. The read-only
// vector however will always read the last block in full, thus causing a
// segfault with mmap files. FIXME
if (strcmp(ft, "mmap") == 0) return;
test_rdonly<const vector_type>(fn, ft, sz, ofs);
//-tb: vector always writes data! FIXME
//test_rdonly<vector_type>(fn, ft, sz, ofs);
}
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " file [filetype]" << std::endl;
return -1;
}
stxxl::config::get_instance();
const char* fn = argv[1];
const char* ft = (argc >= 3) ? argv[2] : "syscall";
stxxl::unsigned_type start_elements = 42 * block_type::size;
STXXL_MSG("using " << ft << " file");
// multiple of block size
STXXL_MSG("running test with " << start_elements << " items");
test(fn, ft, start_elements, 100000000);
// multiple of page size, but not block size
STXXL_MSG("running test with " << start_elements << " + 4096 items");
test(fn, ft, start_elements + 4096, 200000000);
// multiple of neither block size nor page size
STXXL_MSG("running test with " << start_elements << " + 4096 + 23 items");
test(fn, ft, start_elements + 4096 + 23, 300000000);
// truncate 1 byte
{
stxxl::syscall_file f(fn, stxxl::file::DIRECT | stxxl::file::RDWR);
STXXL_MSG("file size is " << f.size() << " bytes");
f.set_size(f.size() - 1);
STXXL_MSG("truncated to " << f.size() << " bytes");
}
// will truncate after the last complete element
test_rdwr<vector_type>(fn, ft, start_elements + 4096 + 23 - 1, 300000000);
// truncate 1 more byte
{
stxxl::syscall_file f(fn, stxxl::file::DIRECT | stxxl::file::RDWR);
STXXL_MSG("file size is " << f.size() << " bytes");
f.set_size(f.size() - 1);
STXXL_MSG("truncated to " << f.size() << " bytes");
}
// will not truncate
//-tb: vector already writes data! TODO
//test_rdonly<vector_type>(fn, ft, start_elements + 4096 + 23 - 2, 300000000);
// check final size
{
stxxl::syscall_file f(fn, stxxl::file::DIRECT | stxxl::file::RDWR);
STXXL_MSG("file size is " << f.size() << " bytes");
STXXL_CHECK(f.size() == (start_elements + 4096 + 23 - 1) * sizeof(my_type) - 1);
}
{
stxxl::syscall_file f(fn, stxxl::file::DIRECT | stxxl::file::RDWR);
f.close_remove();
}
}
// vim: et:ts=4:sw=4
| 2,095 |
611 | <gh_stars>100-1000
package fr.adrienbrault.idea.symfony2plugin.doctrine.metadata;
import com.intellij.codeInsight.completion.*;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.patterns.XmlPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.util.DoctrineMetadataUtil;
import fr.adrienbrault.idea.symfony2plugin.util.completion.PhpClassCompletionProvider;
import org.jetbrains.annotations.NotNull;
/**
* @author <NAME> <<EMAIL>>
*/
public class DoctrineXmlCompletionContributor extends CompletionContributor {
public DoctrineXmlCompletionContributor() {
// <entity name="Class\Name"/>
// <document name="Class\Name"/>
// <embeddable name="Class\Name"/>
extend(CompletionType.BASIC, XmlPatterns.psiElement().withParent(PlatformPatterns.or(
DoctrineMetadataPattern.getXmlModelClass(),
DoctrineMetadataPattern.getXmlTargetEntityClass(),
DoctrineMetadataPattern.getXmlTargetDocumentClass(),
DoctrineMetadataPattern.getEmbeddableNameClassPattern()
)), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext processingContext, @NotNull CompletionResultSet resultSet) {
PsiElement psiElement = parameters.getOriginalPosition();
if(psiElement == null || !Symfony2ProjectComponent.isEnabled(psiElement)) {
return;
}
PhpClassCompletionProvider.addClassCompletion(parameters, resultSet, psiElement, false);
}
});
// <entity repository-class="Class\Name"/>
// <document repository-class="Class\Name"/>
extend(CompletionType.BASIC, XmlPatterns.psiElement().withParent(PlatformPatterns.or(DoctrineMetadataPattern.getXmlRepositoryClass())),
new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext processingContext, @NotNull CompletionResultSet resultSet) {
PsiElement psiElement = parameters.getOriginalPosition();
if(psiElement == null || !Symfony2ProjectComponent.isEnabled(psiElement)) {
return;
}
// @TODO: filter on doctrine manager
resultSet.addAllElements(
DoctrineMetadataUtil.getObjectRepositoryLookupElements(psiElement.getProject())
);
}
});
}
}
| 1,103 |
3,897 | /*************************************************************************************************/
/*!
* \file
*
* \brief Device manager privacy module.
*
* Copyright (c) 2011-2019 Arm Ltd. All Rights Reserved.
*
* Copyright (c) 2019 Packetcraft, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*************************************************************************************************/
#include <string.h>
#include "wsf_types.h"
#include "wsf_msg.h"
#include "sec_api.h"
#include "util/calc128.h"
#include "dm_api.h"
#include "dm_priv.h"
#include "dm_dev.h"
#include "dm_main.h"
/**************************************************************************************************
Macros
**************************************************************************************************/
/* progress (dmPrivCb.inProgress) bitmask bits */
#define DM_PRIV_INPROGRESS_RES_ADDR (1 << 0) /* resolve address in progress */
#define DM_PRIV_INPROGRESS_GEN_ADDR (1 << 1) /* generate address in progress */
/**************************************************************************************************
Local Variables
**************************************************************************************************/
/* Privacy action function table */
static const dmPrivAct_t dmPrivAct[] =
{
dmPrivActResolveAddr,
dmPrivActAddDevToResList,
dmPrivActRemDevFromResList,
dmPrivActClearResList,
dmPrivActSetAddrResEnable,
dmPrivActSetPrivacyMode,
dmPrivActGenAddr
};
/* Privacy component function interface */
static const dmFcnIf_t dmPrivFcnIf =
{
dmPrivReset,
dmPrivHciHandler,
dmPrivMsgHandler
};
/* Privacy AES action function table */
static const dmPrivAct_t dmPrivAesAct[] =
{
dmPrivAesActResAddrAesCmpl,
dmPrivAesActGenAddrAesCmpl
};
/* Privacy AES component function interface */
static const dmFcnIf_t dmPrivAesFcnIf =
{
dmEmptyReset,
(dmHciHandler_t) dmEmptyHandler,
dmPrivAesMsgHandler
};
/* Control block */
dmPrivCb_t dmPrivCb;
/**************************************************************************************************
Local Functions
**************************************************************************************************/
static void dmPrivSetAddrResEnable(bool_t enable);
/*************************************************************************************************/
/*!
* \brief Start address resolution procedure
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivActResolveAddr(dmPrivMsg_t *pMsg)
{
uint8_t buf[DM_PRIV_PLAINTEXT_LEN];
/* verify no resolution procedure currently in progress */
if ((dmPrivCb.inProgress & DM_PRIV_INPROGRESS_RES_ADDR) == 0)
{
/* store hash */
memcpy(dmPrivCb.hash, pMsg->apiResolveAddr.addr, DM_PRIV_HASH_LEN);
/* copy random part of address with padding for address resolution calculation */
memcpy(buf, &pMsg->apiResolveAddr.addr[3], DM_PRIV_PRAND_LEN);
memset(buf + DM_PRIV_PRAND_LEN, 0, (DM_PRIV_PLAINTEXT_LEN - DM_PRIV_PRAND_LEN));
/* set in progress */
dmPrivCb.inProgress |= DM_PRIV_INPROGRESS_RES_ADDR;
/* run calculation */
SecAes(pMsg->apiResolveAddr.irk, buf, dmCb.handlerId,
pMsg->hdr.param, DM_PRIV_MSG_RESOLVE_AES_CMPL);
}
else
{
/* call callback with error (note hdr.param is already set) */
pMsg->hdr.status = HCI_ERR_MEMORY_EXCEEDED;
pMsg->hdr.event = DM_PRIV_RESOLVED_ADDR_IND;
(*dmCb.cback)((dmEvt_t *) pMsg);
}
}
/*************************************************************************************************/
/*!
* \brief Finish address resolution procedure upon completion of AES calculation.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivAesActResAddrAesCmpl(dmPrivMsg_t *pMsg)
{
/* compare calculated value with hash */
if (memcmp(dmPrivCb.hash, pMsg->aes.pCiphertext, DM_PRIV_HASH_LEN) == 0)
{
pMsg->hdr.status = HCI_SUCCESS;
}
else
{
pMsg->hdr.status = HCI_ERR_AUTH_FAILURE;
}
/* clear in progress */
dmPrivCb.inProgress &= ~DM_PRIV_INPROGRESS_RES_ADDR;
/* call client callback (note hdr.param is already set) */
pMsg->hdr.event = DM_PRIV_RESOLVED_ADDR_IND;
(*dmCb.cback)((dmEvt_t *) pMsg);
}
/*************************************************************************************************/
/*!
* \brief Add device to resolving list command.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivActAddDevToResList(dmPrivMsg_t *pMsg)
{
dmPrivApiAddDevToResList_t *pDev = &pMsg->apiAddDevToResList;
/* save whether asked to enable address resolution */
dmPrivCb.enableLlPriv = pDev->enableLlPriv;
/* save client-defined parameter for callback event */
dmPrivCb.addDevToResListParam = pMsg->hdr.param;
/* add device to resolving list */
HciLeAddDeviceToResolvingListCmd(pDev->addrType, pDev->peerAddr, pDev->peerIrk, pDev->localIrk);
}
/*************************************************************************************************/
/*!
* \brief Remove device from resolving list command.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivActRemDevFromResList(dmPrivMsg_t *pMsg)
{
dmPrivApiRemDevFromResList_t *pDev = &pMsg->apiRemDevFromResList;
/* save client-defined parameter for callback event */
dmPrivCb.remDevFromResListParam = pMsg->hdr.param;
/* remove device from resolving list */
HciLeRemoveDeviceFromResolvingList(pDev->addrType, pDev->peerAddr);
}
/*************************************************************************************************/
/*!
* \brief Clear resolving list command.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivActClearResList(dmPrivMsg_t *pMsg)
{
/* clear resolving list */
HciLeClearResolvingList();
}
/*************************************************************************************************/
/*!
* \brief Set address resolution enable command.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivActSetAddrResEnable(dmPrivMsg_t *pMsg)
{
dmPrivApiSetAddrResEnable_t *pAddrRes = &pMsg->apiSetAddrResEnable;
/* enable or disable address resolution in LL */
dmPrivSetAddrResEnable(pAddrRes->enable);
}
/*************************************************************************************************/
/*!
* \brief Set privacy mode command.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivActSetPrivacyMode(dmPrivMsg_t *pMsg)
{
dmPrivApiSetPrivacyMode_t *pPrivacyMode = &pMsg->apiSetPrivacyMode;
/* set privacy mode */
HciLeSetPrivacyModeCmd(pPrivacyMode->addrType, pPrivacyMode->peerAddr, pPrivacyMode->mode);
}
/*************************************************************************************************/
/*!
* \brief Start address generation procedure.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivActGenAddr(dmPrivMsg_t *pMsg)
{
if ((dmPrivCb.inProgress & DM_PRIV_INPROGRESS_GEN_ADDR) == 0)
{
/* get random number */
SecRand(dmPrivCb.genAddrBuf, DM_PRIV_PRAND_LEN);
/* set address type in random number */
dmPrivCb.genAddrBuf[2] = (dmPrivCb.genAddrBuf[2] & 0x3F) | DM_RAND_ADDR_RESOLV;
/* pad buffer */
memset(dmPrivCb.genAddrBuf + DM_PRIV_PRAND_LEN, 0, (DM_PRIV_PLAINTEXT_LEN - DM_PRIV_PRAND_LEN));
/* set in progress */
dmPrivCb.inProgress |= DM_PRIV_INPROGRESS_GEN_ADDR;
/* run calculation */
SecAes(pMsg->apiGenerateAddr.irk, dmPrivCb.genAddrBuf, dmCb.handlerId,
pMsg->hdr.param, DM_PRIV_MSG_GEN_ADDR_AES_CMPL);
}
else
{
/* call callback with error (note hdr.param is already set) */
pMsg->hdr.status = HCI_ERR_MEMORY_EXCEEDED;
pMsg->hdr.event = DM_PRIV_GENERATE_ADDR_IND;
(*dmCb.cback)((dmEvt_t *) pMsg);
}
}
/*************************************************************************************************/
/*!
* \brief Finish generate RPA procedure upon completion of AES calculation.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivAesActGenAddrAesCmpl(dmPrivMsg_t *pMsg)
{
dmPrivGenAddrIndEvt_t *pAddrEvt = (dmPrivGenAddrIndEvt_t*) pMsg;
/* copy the hash and address to buffer */
memcpy(pAddrEvt->addr, pMsg->aes.pCiphertext, DM_PRIV_HASH_LEN);
memcpy(pAddrEvt->addr + DM_PRIV_HASH_LEN, dmPrivCb.genAddrBuf, DM_PRIV_PRAND_LEN);
/* clear in progress */
dmPrivCb.inProgress &= ~DM_PRIV_INPROGRESS_GEN_ADDR;
/* call client callback */
pAddrEvt->hdr.event = DM_PRIV_GENERATE_ADDR_IND;
pMsg->hdr.status = HCI_SUCCESS;
(*dmCb.cback)((dmEvt_t *) pAddrEvt);
}
/*************************************************************************************************/
/*!
* \brief DM priv HCI callback event handler.
*
* \param pEvent Pointer to HCI callback event structure.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivHciHandler(hciEvt_t *pEvent)
{
/* handle incoming event */
switch (pEvent->hdr.event)
{
case HCI_LE_ADD_DEV_TO_RES_LIST_CMD_CMPL_CBACK_EVT:
pEvent->hdr.event = DM_PRIV_ADD_DEV_TO_RES_LIST_IND;
pEvent->hdr.param = dmPrivCb.addDevToResListParam;
/* if LE add device to resolving list command succeeded and been asked to enable address
* resolution in LL and it's not enabled yet
*/
if ((pEvent->hdr.status == HCI_SUCCESS) && dmPrivCb.enableLlPriv && !dmCb.llPrivEnabled)
{
/* enable address resolution in LL */
dmPrivSetAddrResEnable(TRUE);
}
break;
case HCI_LE_REM_DEV_FROM_RES_LIST_CMD_CMPL_CBACK_EVT:
pEvent->hdr.event = DM_PRIV_REM_DEV_FROM_RES_LIST_IND;
pEvent->hdr.param = dmPrivCb.remDevFromResListParam;
break;
case HCI_LE_CLEAR_RES_LIST_CMD_CMPL_CBACK_EVT:
pEvent->hdr.event = DM_PRIV_CLEAR_RES_LIST_IND;
/* if LE clear resolving list command succeeded and address resolution's enabled in LL */
if ((pEvent->hdr.status == HCI_SUCCESS) && dmCb.llPrivEnabled)
{
/* disable address resolution in LL */
dmPrivSetAddrResEnable(FALSE);
}
break;
case HCI_LE_READ_PEER_RES_ADDR_CMD_CMPL_CBACK_EVT:
pEvent->hdr.event = DM_PRIV_READ_PEER_RES_ADDR_IND;
break;
case HCI_LE_READ_LOCAL_RES_ADDR_CMD_CMPL_CBACK_EVT:
pEvent->hdr.event = DM_PRIV_READ_LOCAL_RES_ADDR_IND;
break;
case HCI_LE_SET_ADDR_RES_ENABLE_CMD_CMPL_CBACK_EVT:
pEvent->hdr.event = DM_PRIV_SET_ADDR_RES_ENABLE_IND;
/* if LE set address resoultion enable command succeeded */
if (pEvent->hdr.status == HCI_SUCCESS)
{
/* update LL Privacy Enabled flag */
dmCb.llPrivEnabled = dmPrivCb.addrResEnable;
/* pass LL Privacy enable/disable event to dev priv */
dmDevPassEvtToDevPriv(dmCb.llPrivEnabled ? DM_DEV_PRIV_MSG_RPA_STOP : DM_DEV_PRIV_MSG_RPA_START,
dmCb.llPrivEnabled ? TRUE : FALSE, 0, 0);
}
break;
default:
/* should never get here */
return;
}
/* call callback (note hdr.status is already set) */
(*dmCb.cback)((dmEvt_t *)pEvent);
}
/*************************************************************************************************/
/*!
* \brief Set address resolution enable command.
*
* \param enable Set to TRUE to enable address resolution or FALSE to disable it.
*
* \return None.
*/
/*************************************************************************************************/
static void dmPrivSetAddrResEnable(bool_t enable)
{
/* save input parameter */
dmPrivCb.addrResEnable = enable;
/* enable or disable address resolution in LL */
HciLeSetAddrResolutionEnable(enable);
}
/*************************************************************************************************/
/*!
* \brief DM priv event handler.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivMsgHandler(wsfMsgHdr_t *pMsg)
{
/* execute action function */
(*dmPrivAct[DM_MSG_MASK(pMsg->event)])((dmPrivMsg_t *) pMsg);
}
/*************************************************************************************************/
/*!
* \brief Reset the privacy module.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivReset(void)
{
/* initialize control block */
dmPrivCb.inProgress = 0;
dmCb.llPrivEnabled = FALSE;
}
/*************************************************************************************************/
/*!
* \brief DM priv AES event handler.
*
* \param pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void dmPrivAesMsgHandler(wsfMsgHdr_t *pMsg)
{
/* execute action function */
(*dmPrivAesAct[DM_MSG_MASK(pMsg->event)])((dmPrivMsg_t *) pMsg);
}
/*************************************************************************************************/
/*!
* \brief Initialize DM privacy module.
*
* \return None.
*/
/*************************************************************************************************/
void DmPrivInit(void)
{
WsfTaskLock();
dmFcnIfTbl[DM_ID_PRIV] = (dmFcnIf_t *) &dmPrivFcnIf;
dmFcnIfTbl[DM_ID_PRIV_AES] = (dmFcnIf_t *) &dmPrivAesFcnIf;
WsfTaskUnlock();
}
/*************************************************************************************************/
/*!
* \brief Resolve a private resolvable address. When complete the client's callback function
* is called with a DM_PRIV_RESOLVED_ADDR_IND event. The client must wait to receive
* this event before executing this function again.
*
* \param pAddr Peer device address.
* \param pIrk The peer's identity resolving key.
* \param param client-defined parameter returned with callback event.
*
* \return None.
*/
/*************************************************************************************************/
void DmPrivResolveAddr(uint8_t *pAddr, uint8_t *pIrk, uint16_t param)
{
dmPrivApiResolveAddr_t *pMsg;
if ((pMsg = WsfMsgAlloc(sizeof(dmPrivApiResolveAddr_t))) != NULL)
{
pMsg->hdr.event = DM_PRIV_MSG_API_RESOLVE_ADDR;
pMsg->hdr.param = param;
Calc128Cpy(pMsg->irk, pIrk);
BdaCpy(pMsg->addr, pAddr);
WsfMsgSend(dmCb.handlerId, pMsg);
}
}
/*************************************************************************************************/
/*!
* \brief Add device to resolving list. When complete the client's callback function
* is called with a DM_PRIV_ADD_DEV_TO_RES_LIST_IND event. The client must wait
* to receive this event before executing this function again.
*
* \param addrType Peer identity address type.
* \param pIdentityAddr Peer identity address.
* \param pPeerIrk The peer's identity resolving key.
* \param pLocalIrk The local identity resolving key.
* \param enableLlPriv Set to TRUE to enable address resolution in LL.
* \param param client-defined parameter returned with callback event.
*
* \return None.
*
* \Note This command cannot be used when address resolution is enabled in the Controller and:
* - Advertising (other than periodic advertising) is enabled,
* - Scanning is enabled, or
* - (Extended) Create connection or Create Sync command is outstanding.
*
* \Note If the local or peer IRK associated with the peer Identity Address is all zeros then
* the Controller will use or accept the local or peer Identity Address respectively.
*
* \Note Parameter 'enableLlPriv' should be set to TRUE when the last device is being added
* to resolving list to enable address resolution in the Controller.
*/
/*************************************************************************************************/
void DmPrivAddDevToResList(uint8_t addrType, const uint8_t *pIdentityAddr, uint8_t *pPeerIrk,
uint8_t *pLocalIrk, bool_t enableLlPriv, uint16_t param)
{
dmPrivApiAddDevToResList_t *pMsg;
if ((pMsg = WsfMsgAlloc(sizeof(dmPrivApiAddDevToResList_t))) != NULL)
{
pMsg->hdr.event = DM_PRIV_MSG_API_ADD_DEV_TO_RES_LIST;
pMsg->hdr.param = param;
pMsg->addrType = addrType;
BdaCpy(pMsg->peerAddr, pIdentityAddr);
Calc128Cpy(pMsg->peerIrk, pPeerIrk);
Calc128Cpy(pMsg->localIrk, pLocalIrk);
pMsg->enableLlPriv = enableLlPriv;
WsfMsgSend(dmCb.handlerId, pMsg);
}
}
/*************************************************************************************************/
/*!
* \brief Remove device from resolving list. When complete the client's callback function
* is called with a DM_PRIV_REM_DEV_FROM_RES_LIST_IND event. The client must wait to
* receive this event before executing this function again.
*
* \param addrType Peer identity address type.
* \param pIdentityAddr Peer identity address.
* \param param client-defined parameter returned with callback event.
*
* \return None.
*
* \Note This command cannot be used when address resolution is enabled in the Controller and:
* - Advertising (other than periodic advertising) is enabled,
* - Scanning is enabled, or
* - (Extended) Create connection or Create Sync command is outstanding.
*/
/*************************************************************************************************/
void DmPrivRemDevFromResList(uint8_t addrType, const uint8_t *pIdentityAddr, uint16_t param)
{
dmPrivApiRemDevFromResList_t *pMsg;
if ((pMsg = WsfMsgAlloc(sizeof(dmPrivApiRemDevFromResList_t))) != NULL)
{
pMsg->hdr.event = DM_PRIV_MSG_API_REM_DEV_FROM_RES_LIST;
pMsg->hdr.param = param;
pMsg->addrType = addrType;
BdaCpy(pMsg->peerAddr, pIdentityAddr);
WsfMsgSend(dmCb.handlerId, pMsg);
}
}
/*************************************************************************************************/
/*!
* \brief Clear resolving list. When complete the client's callback function is called with a
* DM_PRIV_CLEAR_RES_LIST_IND event. The client must wait to receive this event before
* executing this function again.
*
* \return None.
*
* \Note This command cannot be used when address resolution is enabled in the Controller and:
* - Advertising (other than periodic advertising) is enabled,
* - Scanning is enabled, or
* - (Extended) Create connection or Create Sync command is outstanding.
*
* \Note Address resolution in the Controller will be disabled when resolving list's cleared
* successfully.
*/
/*************************************************************************************************/
void DmPrivClearResList(void)
{
dmPrivMsg_t *pMsg;
if ((pMsg = WsfMsgAlloc(sizeof(dmPrivMsg_t))) != NULL)
{
pMsg->hdr.event = DM_PRIV_MSG_API_CLEAR_RES_LIST;
WsfMsgSend(dmCb.handlerId, pMsg);
}
}
/*************************************************************************************************/
/*!
* \brief HCI read peer resolvable address command. When complete the client's callback
* function is called with a DM_PRIV_READ_PEER_RES_ADDR_IND event. The client must
* wait to receive this event before executing this function again.
*
* \param addrType Peer identity address type.
* \param pIdentityAddr Peer identity address.
*
* \return None.
*/
/*************************************************************************************************/
void DmPrivReadPeerResolvableAddr(uint8_t addrType, const uint8_t *pIdentityAddr)
{
HciLeReadPeerResolvableAddr(addrType, pIdentityAddr);
}
/*************************************************************************************************/
/*!
* \brief Read local resolvable address command. When complete the client's callback
* function is called with a DM_PRIV_READ_LOCAL_RES_ADDR_IND event. The client must
* wait to receive this event before executing this function again.
*
* \param addrType Peer identity address type.
* \param pIdentityAddr Peer identity address.
*
* \return None.
*/
/*************************************************************************************************/
void DmPrivReadLocalResolvableAddr(uint8_t addrType, const uint8_t *pIdentityAddr)
{
HciLeReadLocalResolvableAddr(addrType, pIdentityAddr);
}
/*************************************************************************************************/
/*!
* \brief Enable or disable address resolution in LL. When complete the client's callback
* function is called with a DM_PRIV_SET_ADDR_RES_ENABLE_IND event. The client must
* wait to receive this event before executing this function again.
*
* \param enable Set to TRUE to enable address resolution or FALSE to disable it.
*
* \return None.
*
* \Note This command can be used at any time except when:
* - Advertising (other than periodic advertising) is enabled,
* - Scanning is enabled, or
* - (Extended) Create connection or Create Sync command is outstanding.
*/
/*************************************************************************************************/
void DmPrivSetAddrResEnable(bool_t enable)
{
dmPrivApiSetAddrResEnable_t *pMsg;
if ((pMsg = WsfMsgAlloc(sizeof(dmPrivMsg_t))) != NULL)
{
pMsg->hdr.event = DM_PRIV_MSG_API_SET_ADDR_RES_ENABLE;
pMsg->hdr.param = 0;
pMsg->enable = enable;
WsfMsgSend(dmCb.handlerId, pMsg);
}
}
/*************************************************************************************************/
/*!
* \brief Set resolvable private address timeout command.
*
* \param rpaTimeout Timeout measured in seconds.
*
* \return None.
*/
/*************************************************************************************************/
void DmPrivSetResolvablePrivateAddrTimeout(uint16_t rpaTimeout)
{
HciLeSetResolvablePrivateAddrTimeout(rpaTimeout);
}
/*************************************************************************************************/
/*!
* \brief Set privacy mode for a given entry in the resolving list.
*
* \param addrType Peer identity address type.
* \param pIdentityAddr Peer identity address.
* \param mode Privacy mode (by default, network privacy mode is used).
*
* \return None.
*
* \Note This command can be used at any time except when:
* - Advertising (other than periodic advertising) is enabled,
* - Scanning is enabled, or
* - (Extended) Create connection or Create Sync command is outstanding.
*/
/*************************************************************************************************/
void DmPrivSetPrivacyMode(uint8_t addrType, const uint8_t *pIdentityAddr, uint8_t mode)
{
dmPrivApiSetPrivacyMode_t *pMsg;
if ((pMsg = WsfMsgAlloc(sizeof(dmPrivApiSetPrivacyMode_t))) != NULL)
{
pMsg->hdr.event = DM_PRIV_MSG_API_SET_PRIVACY_MODE;
pMsg->addrType = addrType;
BdaCpy(pMsg->peerAddr, pIdentityAddr);
pMsg->mode = mode;
WsfMsgSend(dmCb.handlerId, pMsg);
}
}
/*************************************************************************************************/
/*!
* \brief Generate a Resolvable Private Address (RPA).
*
* \param pIrk The identity resolving key.
* \param param Client-defined parameter returned with callback event.
*
* \return None.
*/
/*************************************************************************************************/
void DmPrivGenerateAddr(uint8_t *pIrk, uint16_t param)
{
dmPrivApiGenAddr_t *pMsg;
if ((pMsg = WsfMsgAlloc(sizeof(dmPrivApiGenAddr_t))) != NULL)
{
pMsg->hdr.event = DM_PRIV_MSG_API_GEN_ADDR;
pMsg->hdr.param = param;
Calc128Cpy(pMsg->irk, pIrk);
WsfMsgSend(dmCb.handlerId, pMsg);
}
}
| 8,318 |
3,553 | <reponame>eugenebnd/fluent-bit<filename>plugins/in_nginx_exporter_metrics/nginx.h
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2019-2021 The Fluent Bit Authors
* Copyright (C) 2015-2018 Treasure Data 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.
*/
#ifndef FLB_IN_NGINX_H
#define FLB_IN_NGINX_H
#include <msgpack.h>
#include <fluent-bit/flb_input.h>
#include <fluent-bit/flb_parser.h>
#include <fluent-bit/flb_network.h>
#define DEFAULT_STATUS_URL "/status"
struct nginx_ctx
{
int coll_id; /* collector id */
flb_sds_t status_url;
struct flb_parser *parser;
struct flb_input_instance *ins; /* Input plugin instace */
struct flb_upstream *upstream;
struct cmt *cmt;
struct cmt_counter *connections_accepted;
struct cmt_counter *connections_handled;
struct cmt_counter *connections_total;
struct cmt_gauge *connection_active;
struct cmt_gauge *connections_active;
struct cmt_gauge *connections_reading;
struct cmt_gauge *connections_writing;
struct cmt_gauge *connections_waiting;
struct cmt_gauge *connection_up;
bool is_up;
};
struct nginx_status
{
uint64_t active;
uint64_t reading;
uint64_t writing;
uint64_t waiting;
uint64_t accepts;
uint64_t handled;
uint64_t requests;
};
#endif
| 733 |
1,050 | <filename>conf/nebula/offline/SlotToProfileVarMap.json<gh_stars>1000+
{
"uid": [
"uid__visit_dynamic_count__1h__slot",
"uid_did__visit_dynamic_count_top20__1h__slot",
"uid_useragent__visit_dynamic_count_top20__1h__slot",
"uid__visit_incident_count__1h__slot",
"uid_geo_city__visit_dynamic_count_top20__1h__slot",
"uid__visit_dynamic_last_timestamp__1h__slot",
"uid__visit_dynamic_distinct_count_did__1h__slot",
"uid__visit_dynamic_distinct_count_ip__1h__slot"
],
"did": [
"did__visit_dynamic_distinct_count_ip__1h__slot",
"did__visit_dynamic_distinct_count_uid__1h__slot"
],
"ip": [
"ip__visit_dynamic_distinct_count_uid__1h__slot",
"ip__visit_dynamic_distinct_count_did__1h__slot"
]
}
| 350 |
554 | package github.tornaco.xposedmoduletest.xposed.service;
/**
* Created by guohao4 on 2017/11/1.
* Email: <EMAIL>
*/
public @interface PMRuleCheck {
}
| 66 |
631 | /*
Copyright (c) 2017-2020 Origin Quantum Computing. All Right Reserved.
Licensed under the Apache License 2.0
GraphDijkstra.h
Author: Wangjing
Created in 2018-8-31
Classes for get the shortes path of graph
*/
#ifndef METADATAVALIDITYFUNCTIONVECTOR_H
#define METADATAVALIDITYFUNCTIONVECTOR_H
#include "Core/Utilities/QPandaNamespace.h"
#include <iostream>
#include <string>
#include <vector>
#include <functional>
QPANDA_BEGIN
/**
* @brief Single gate transfer type
*/
enum SingleGateTransferType
{
SINGLE_GATE_INVALID = -1,
ARBITRARY_ROTATION,
DOUBLE_CONTINUOUS,
SINGLE_CONTINUOUS_DISCRETE,
DOUBLE_DISCRETE
};
/**
* @brief Double gate transfer type
*/
enum DoubleGateTransferType
{
DOUBLE_GATE_INVALID = -1,
DOUBLE_BIT_GATE
};
/**
* @brief Judge if the metadata's type is arbitrary rotation
* @ingroup Utilities
* @param std::vector<std::string>& the gates is judged
* @param std::vector<std::string>& output the valid gates
* @return Return the style of metadata validity
*/
int arbitraryRotationMetadataValidity(std::vector<std::string>&gates,
std::vector<std::string>&valid_gates);
/**
* @brief Judge if the metadata's type is double continuous
* @ingroup Utilities
* @param std::vector<std::string>& the gates is judged
* @param std::vector<std::string>& output the valid gates
* @return Return the style of metadata validity
*/
int doubleContinuousMetadataValidity(std::vector<std::string>&gates,
std::vector<std::string>&valid_gates);
/**
* @brief Judge if the metadata's type is single continuous and discrete
* @ingroup Utilities
* @param std::vector<std::string>& the gates is judged
* @param std::vector<std::string>& output the valid gates
* @return Return the style of metadata validity
*/
int singleContinuousAndDiscreteMetadataValidity(std::vector<std::string>&gates,
std::vector<std::string>&valid_gates);
/**
* @brief Judge if the metadata's type is double discrete
* @ingroup Utilities
* @param std::vector<std::string>& the gates is judged
* @param std::vector<std::string>& output the valid gates
* @return Return the style of metadata validity
*/
int doubleDiscreteMetadataValidity(std::vector<std::string>&gates,
std::vector<std::string>&valid_gates);
/**
* @brief Judge double gate type
* @ingroup Utilities
* @param std::vector<std::string>& the gates is judged
* @param std::vector<std::string>& output the valid gates
* @return Return the style of metadata validity
*/
int doubleGateMetadataValidity(std::vector<std::string>&gates,
std::vector<std::string>&valid_gates);
/**
* @brief typedef MetadataValidity_cb that add all functions of metadata validity
*/
typedef std::function<int(std::vector<std::string>&, std::vector<std::string>&)> MetadataValidity_cb;
/**
* @brief Metadata Validity
* @ingroup Utilities
*/
class MetadataValidity
{
public:
void push_back(MetadataValidity_cb func);
MetadataValidity_cb operator[](int i);
size_t size();
virtual ~MetadataValidity();
private:
std::vector<MetadataValidity_cb> m_metadata_validity_functions;
};
/**
* @brief Get single gate metadata Validator type
* @ingroup Utilities
*/
class SingleGateTypeValidator
{
public:
SingleGateTypeValidator();
static int GateType(std::vector<std::string>&gates,
std::vector<std::string>&valid_gates);
virtual ~SingleGateTypeValidator();
MetadataValidity m_metadata_validity_functions;
private:
};
/**
* @brief Get double gate metadata Validator type
* @ingroup Utilities
*/
class DoubleGateTypeValidator
{
public:
DoubleGateTypeValidator();
static int GateType(std::vector<std::string>&gates, std::vector<std::string>&valid_gates);
virtual ~DoubleGateTypeValidator();
MetadataValidity m_metadata_validity_functions;
private:
};
/* new interface */
/**
* @brief Verify the validity of single quantum gates
* @ingroup Utilities
* @param[in] std::vector<std::string>& gates vertor
* @param[out] std::vector<std::string>& output the valid gates
* @return int single quantum gate type
*/
int validateSingleQGateType(std::vector<std::string> &gates, std::vector<std::string> &valid_gates);
/**
* @brief Verify the validity of double quantum gates
* @ingroup Utilitie
* @param[in] std::vector<std::string>& the gates is judged
* @param[out] std::vector<std::string>& output the valid gates
* @return int double quantum gate type
*/
int validateDoubleQGateType(std::vector<std::string> &gates, std::vector<std::string> &valid_gates);
QPANDA_END
#endif // METADATAVALIDITYFUNCTIONVECTOR_H
| 1,735 |
1,893 | <gh_stars>1000+
"""
ANN module tests
"""
import os
import tempfile
import unittest
import numpy as np
from txtai.ann import ANNFactory, ANN
class TestANN(unittest.TestCase):
"""
ANN tests.
"""
def testAnnoy(self):
"""
Test Annoy backend
"""
self.runTests("annoy", None, False)
def testAnnoyCustom(self):
"""
Test Annoy backend with custom settings
"""
# Test with custom settings
self.runTests("annoy", {"annoy": {"ntrees": 2, "searchk": 1}}, False)
def testFaiss(self):
"""
Test Faiss backend
"""
self.runTests("faiss")
def testFaissCustom(self):
"""
Test Faiss backend with custom settings
"""
# Test with custom settings
self.runTests("faiss", {"faiss": {"nprobe": 2, "components": "PCA16,IDMap,SQ8"}}, False)
def testHnsw(self):
"""
Test Hnswlib backend
"""
self.runTests("hnsw")
def testHnswCustom(self):
"""
Test Hnswlib backend with custom settings
"""
# Test with custom settings
self.runTests("hnsw", {"hnsw": {"efconstruction": 100, "m": 4, "randomseed": 0, "efsearch": 5}})
def testNotImplemented(self):
"""
Tests exceptions for non-implemented methods
"""
ann = ANN({})
self.assertRaises(NotImplementedError, ann.load, None)
self.assertRaises(NotImplementedError, ann.index, None)
self.assertRaises(NotImplementedError, ann.append, None)
self.assertRaises(NotImplementedError, ann.delete, None)
self.assertRaises(NotImplementedError, ann.search, None, None)
self.assertRaises(NotImplementedError, ann.count)
self.assertRaises(NotImplementedError, ann.save, None)
def runTests(self, name, params=None, update=True):
"""
Runs a series of standard backend tests.
Args:
name: backend name
params: additional config parameters
update: If append/delete options should be tested
"""
self.assertEqual(self.backend(name, params).config["backend"], name)
self.assertEqual(self.save(name, params).count(), 10000)
if update:
self.assertEqual(self.append(name, params, 500).count(), 10500)
self.assertEqual(self.delete(name, params, [0, 1]).count(), 9998)
self.assertEqual(self.delete(name, params, [100000]).count(), 10000)
self.assertGreater(self.search(name, params), 0)
def backend(self, name, params=None, length=10000):
"""
Test a backend.
Args:
name: backend name
params: additional config parameters
length: number of rows to generate
Returns:
ANN model
"""
# Generate test data
data = np.random.rand(length, 300).astype(np.float32)
self.normalize(data)
config = {"backend": name, "dimensions": data.shape[1]}
if params:
config.update(params)
model = ANNFactory.create(config)
model.index(data)
return model
def append(self, name, params=None, length=500):
"""
Appends new data to index.
Args:
name: backend name
params: additional config parameters
length: number of rows to generate
Returns:
ANN model
"""
# Initial model
model = self.backend(name, params)
# Generate test data
data = np.random.rand(length, 300).astype(np.float32)
self.normalize(data)
model.append(data)
return model
def delete(self, name, params=None, ids=None):
"""
Deletes data from index.
Args:
name: backend name
params: additional config parameters
ids: ids to delete
Returns:
ANN model
"""
# Initial model
model = self.backend(name, params)
model.delete(ids)
return model
def save(self, name, params=None):
"""
Test save/load.
Args:
name: backend name
params: additional config parameters
Returns:
ANN model
"""
model = self.backend(name, params)
# Generate temp file path
index = os.path.join(tempfile.gettempdir(), "ann")
model.save(index)
model.load(index)
return model
def search(self, name, params=None):
"""
Test ANN search.
Args:
name: backend name
params: additional config parameters
Returns:
search results
"""
# Generate ANN index
model = self.backend(name, params)
# Generate query vector
query = np.random.rand(300).astype(np.float32)
self.normalize(query)
# Ensure top result has similarity > 0
return model.search(np.array([query]), 1)[0][0][1]
def normalize(self, embeddings):
"""
Normalizes embeddings using L2 normalization. Operation applied directly on array.
Args:
embeddings: input embeddings matrix
"""
# Calculation is different for matrices vs vectors
if len(embeddings.shape) > 1:
embeddings /= np.linalg.norm(embeddings, axis=1)[:, np.newaxis]
else:
embeddings /= np.linalg.norm(embeddings)
| 2,514 |
2,013 | """Unit tests for the FileChecker class."""
from unittest import mock
import pytest
import flake8
from flake8 import checker
@mock.patch("flake8.checker.FileChecker._make_processor", return_value=None)
def test_repr(*args):
"""Verify we generate a correct repr."""
file_checker = checker.FileChecker(
"example.py",
checks={},
options=object(),
)
assert repr(file_checker) == "FileChecker for example.py"
def test_nonexistent_file():
"""Verify that checking non-existent file results in an error."""
c = checker.FileChecker("foobar.py", checks={}, options=object())
assert c.processor is None
assert not c.should_process
assert len(c.results) == 1
error = c.results[0]
assert error[0] == "E902"
def test_raises_exception_on_failed_plugin(tmp_path, default_options):
"""Checks that a failing plugin results in PluginExecutionFailed."""
foobar = tmp_path / "foobar.py"
foobar.write_text("I exist!") # Create temp file
plugin = {
"name": "failure",
"plugin_name": "failure", # Both are necessary
"parameters": dict(),
"plugin": mock.MagicMock(side_effect=ValueError),
}
"""Verify a failing plugin results in an plugin error"""
fchecker = checker.FileChecker(
str(foobar), checks=[], options=default_options
)
with pytest.raises(flake8.exceptions.PluginExecutionFailed):
fchecker.run_check(plugin)
| 551 |
856 | //
// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "NeonLogicalNotWorkload.hpp"
#include "NeonWorkloadUtils.hpp"
#include <aclCommon/ArmComputeTensorHandle.hpp>
#include <aclCommon/ArmComputeTensorUtils.hpp>
#include <armnn/utility/PolymorphicDowncast.hpp>
namespace armnn
{
arm_compute::Status NeonLogicalNotWorkloadValidate(const TensorInfo& input,
const TensorInfo& output)
{
const arm_compute::TensorInfo aclInputInfo = BuildArmComputeTensorInfo(input);
const arm_compute::TensorInfo aclOutputInfo = BuildArmComputeTensorInfo(output);
const arm_compute::Status aclStatus = arm_compute::NELogicalNot::validate(&aclInputInfo,
&aclOutputInfo);
return aclStatus;
}
NeonLogicalNotWorkload::NeonLogicalNotWorkload(const ElementwiseUnaryQueueDescriptor& descriptor,
const WorkloadInfo& info)
: BaseWorkload<ElementwiseUnaryQueueDescriptor>(descriptor, info)
{
// Report Profiling Details
ARMNN_REPORT_PROFILING_WORKLOAD_DESC("NeonLogicalNotWorkload_Construct",
descriptor.m_Parameters,
info,
this->GetGuid());
m_Data.ValidateInputsOutputs("NeonLogicalNotWorkload", 1, 1);
arm_compute::ITensor& input = PolymorphicDowncast<IAclTensorHandle*>(m_Data.m_Inputs[0])->GetTensor();
arm_compute::ITensor& output = PolymorphicDowncast<IAclTensorHandle*>(m_Data.m_Outputs[0])->GetTensor();
m_LogicalNotLayer.configure(&input, &output);
}
void NeonLogicalNotWorkload::Execute() const
{
ARMNN_SCOPED_PROFILING_EVENT_NEON_GUID("NeonLogicalNotWorkload_Execute", this->GetGuid());
m_LogicalNotLayer.run();
}
} // namespace armnn
| 894 |
491 | import k2
s1 = '''
0 1 0 0.1
0 1 1 0.2
1 1 2 0.3
1 2 -1 0.4
2
'''
s2 = '''
0 1 1 1
0 1 2 2
1 2 -1 3
2
'''
a_fsa = k2.Fsa.from_str(s1)
b_fsa = k2.Fsa.from_str(s2)
c_fsa = k2.intersect(a_fsa, b_fsa)
a_fsa.draw('a_fsa_intersect.svg', title='a_fsa')
b_fsa.draw('b_fsa_intersect.svg', title='b_fsa')
c_fsa.draw('c_fsa_intersect.svg', title='c_fsa')
| 212 |
407 | package com.alibaba.smart.framework.engine.xml.parser;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;
import com.alibaba.smart.framework.engine.hook.LifeCycleHook;
/**
* XML处理器扩展点 Created by ettear on 16-4-12.
*/
public interface XmlParserFacade extends LifeCycleHook {
/**
* Reads a model from an XMLStreamReader.
*
* @param reader The XMLStreamReader
* @param context The context
* @return A model representation of the input.
*/
Object parseElement(XMLStreamReader reader, ParseContext context);
/**
* Reads a model from an XMLStreamReader.
*
* @param reader The XMLStreamReader
* @param context The context
* @return A model representation of the input.
*/
Object parseAttribute(QName attributeName, XMLStreamReader reader, ParseContext context);
}
| 310 |
1,475 | /*
* 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.geode.admin;
/**
* Interface to represent a single statistic of a <code>StatisticResource</code>
*
* @since GemFire 3.5
*
* @deprecated as of 7.0 use the <code><a href=
* "{@docRoot}/org/apache/geode/management/package-summary.html">management</a></code>
* package instead
*/
public interface Statistic extends java.io.Serializable {
/**
* Gets the identifying name of this statistic.
*
* @return the identifying name of this statistic
*/
String getName();
/**
* Gets the value of this statistic as a <code>java.lang.Number</code>.
*
* @return the value of this statistic
*/
Number getValue();
/**
* Gets the unit of measurement (if any) this statistic represents.
*
* @return the unit of measurement (if any) this statistic represents
*/
String getUnits();
/**
* Returns true if this statistic represents a numeric value which always increases.
*
* @return true if this statistic represents a value which always increases
*/
boolean isCounter();
/**
* Gets the full description of this statistic.
*
* @return the full description of this statistic
*/
String getDescription();
}
| 556 |
3,477 | // Copyright Microsoft and Project Verona Contributors.
// SPDX-License-Identifier: MIT
#include <verona.h>
size_t do_nothing(size_t x)
{
return x;
}
| 54 |
7,073 | import sys
def output(rc=0, stdout='', stderr='', count=1):
if stdout:
sys.stdout.write((stdout+'\n') * int(count))
if stderr:
sys.stderr.write((stderr+'\n') * int(count))
return int(rc)
if __name__ == '__main__':
rc = output(*sys.argv[1:])
sys.exit(rc)
| 145 |
435 | <filename>pycon-uk-2017/videos/pycon-uk-2017-docs-or-it-didn-t-happen.json
{
"copyright_text": "Standard YouTube License",
"description": "**Apologies for the occasional mumbling in the audio over the presenter, a mic was left live next to the mixer for part of Thursday**\n\nIf you ever skimmed through a README, tried to follow a quickstart tutorial, attempted to decipher an error message, or typed '--help' in your console, congratulations -- you have encountered documentation!\n\nLong gone are the days of massive books with never-ending stories about your software. Today's users are smarter and less patient, which means that we no longer need to document all the things, as long as what we do document is clear, concise, helpful, and accessible. And that's where the real work starts.\n\nDocumentation requires some attitude adjustment, since prose doesn't neatly compile into binaries as code does. But Don't Panic(tm)! No matter what your role is in the community, you can apply a few key principles from the technical writing world to make your project more docs-friendly, and therefore more user- and contributor-friendly.\n\nThis high-level (and all-level) talk aims to introduce or re-acquaint you with topics such as content strategy, modular content architecture, tone and style, optimized DevOps for docs, and contribution workflows. Open-source projects of all shapes and sizes are welcome!",
"duration": 1584,
"language": "eng",
"recorded": "2017-10-26T11:30:00+01:00",
"related_urls": [
{
"label": "event schedule",
"url": "http://2017.pyconuk.org/schedule/"
},
{
"label": "talk slides",
"url": "https://speakerdeck.com/thatdocslady/docs-or-it-didnt-happen"
}
],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi/muhxjdxhIR0/hqdefault.jpg",
"title": "Docs or it didn't happen",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=muhxjdxhIR0"
}
]
}
| 625 |
416 | <reponame>ljz663/tencentcloud-sdk-java
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.faceid.v20180301.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class DetectDetail extends AbstractModel{
/**
* 请求时间戳。
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("ReqTime")
@Expose
private String ReqTime;
/**
* 本次活体一比一请求的唯一标记。
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Seq")
@Expose
private String Seq;
/**
* 参与本次活体一比一的身份证号。
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Idcard")
@Expose
private String Idcard;
/**
* 参与本次活体一比一的姓名。
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Name")
@Expose
private String Name;
/**
* 本次活体一比一的相似度。
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Sim")
@Expose
private String Sim;
/**
* 本次活体一比一是否收费
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("IsNeedCharge")
@Expose
private Boolean IsNeedCharge;
/**
* 本次活体一比一最终结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Errcode")
@Expose
private Long Errcode;
/**
* 本次活体一比一最终结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Errmsg")
@Expose
private String Errmsg;
/**
* 本次活体结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Livestatus")
@Expose
private Long Livestatus;
/**
* 本次活体结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Livemsg")
@Expose
private String Livemsg;
/**
* 本次一比一结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Comparestatus")
@Expose
private Long Comparestatus;
/**
* 本次一比一结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("Comparemsg")
@Expose
private String Comparemsg;
/**
* 比对库源类型。包括:
公安商业库;
业务方自有库(用户上传照片、客户的混合库、混合部署库);
二次验证库;
人工审核库;
注意:此字段可能返回 null,表示取不到有效值。
*/
@SerializedName("CompareLibType")
@Expose
private String CompareLibType;
/**
* Get 请求时间戳。
注意:此字段可能返回 null,表示取不到有效值。
* @return ReqTime 请求时间戳。
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getReqTime() {
return this.ReqTime;
}
/**
* Set 请求时间戳。
注意:此字段可能返回 null,表示取不到有效值。
* @param ReqTime 请求时间戳。
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setReqTime(String ReqTime) {
this.ReqTime = ReqTime;
}
/**
* Get 本次活体一比一请求的唯一标记。
注意:此字段可能返回 null,表示取不到有效值。
* @return Seq 本次活体一比一请求的唯一标记。
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getSeq() {
return this.Seq;
}
/**
* Set 本次活体一比一请求的唯一标记。
注意:此字段可能返回 null,表示取不到有效值。
* @param Seq 本次活体一比一请求的唯一标记。
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setSeq(String Seq) {
this.Seq = Seq;
}
/**
* Get 参与本次活体一比一的身份证号。
注意:此字段可能返回 null,表示取不到有效值。
* @return Idcard 参与本次活体一比一的身份证号。
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getIdcard() {
return this.Idcard;
}
/**
* Set 参与本次活体一比一的身份证号。
注意:此字段可能返回 null,表示取不到有效值。
* @param Idcard 参与本次活体一比一的身份证号。
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setIdcard(String Idcard) {
this.Idcard = Idcard;
}
/**
* Get 参与本次活体一比一的姓名。
注意:此字段可能返回 null,表示取不到有效值。
* @return Name 参与本次活体一比一的姓名。
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getName() {
return this.Name;
}
/**
* Set 参与本次活体一比一的姓名。
注意:此字段可能返回 null,表示取不到有效值。
* @param Name 参与本次活体一比一的姓名。
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* Get 本次活体一比一的相似度。
注意:此字段可能返回 null,表示取不到有效值。
* @return Sim 本次活体一比一的相似度。
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getSim() {
return this.Sim;
}
/**
* Set 本次活体一比一的相似度。
注意:此字段可能返回 null,表示取不到有效值。
* @param Sim 本次活体一比一的相似度。
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setSim(String Sim) {
this.Sim = Sim;
}
/**
* Get 本次活体一比一是否收费
注意:此字段可能返回 null,表示取不到有效值。
* @return IsNeedCharge 本次活体一比一是否收费
注意:此字段可能返回 null,表示取不到有效值。
*/
public Boolean getIsNeedCharge() {
return this.IsNeedCharge;
}
/**
* Set 本次活体一比一是否收费
注意:此字段可能返回 null,表示取不到有效值。
* @param IsNeedCharge 本次活体一比一是否收费
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setIsNeedCharge(Boolean IsNeedCharge) {
this.IsNeedCharge = IsNeedCharge;
}
/**
* Get 本次活体一比一最终结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
* @return Errcode 本次活体一比一最终结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
public Long getErrcode() {
return this.Errcode;
}
/**
* Set 本次活体一比一最终结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
* @param Errcode 本次活体一比一最终结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setErrcode(Long Errcode) {
this.Errcode = Errcode;
}
/**
* Get 本次活体一比一最终结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
* @return Errmsg 本次活体一比一最终结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getErrmsg() {
return this.Errmsg;
}
/**
* Set 本次活体一比一最终结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
* @param Errmsg 本次活体一比一最终结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setErrmsg(String Errmsg) {
this.Errmsg = Errmsg;
}
/**
* Get 本次活体结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
* @return Livestatus 本次活体结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
public Long getLivestatus() {
return this.Livestatus;
}
/**
* Set 本次活体结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
* @param Livestatus 本次活体结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setLivestatus(Long Livestatus) {
this.Livestatus = Livestatus;
}
/**
* Get 本次活体结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
* @return Livemsg 本次活体结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getLivemsg() {
return this.Livemsg;
}
/**
* Set 本次活体结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
* @param Livemsg 本次活体结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setLivemsg(String Livemsg) {
this.Livemsg = Livemsg;
}
/**
* Get 本次一比一结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
* @return Comparestatus 本次一比一结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
public Long getComparestatus() {
return this.Comparestatus;
}
/**
* Set 本次一比一结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
* @param Comparestatus 本次一比一结果。0为成功
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setComparestatus(Long Comparestatus) {
this.Comparestatus = Comparestatus;
}
/**
* Get 本次一比一结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
* @return Comparemsg 本次一比一结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getComparemsg() {
return this.Comparemsg;
}
/**
* Set 本次一比一结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
* @param Comparemsg 本次一比一结果描述。(仅描述用,文案更新时不会通知。)
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setComparemsg(String Comparemsg) {
this.Comparemsg = Comparemsg;
}
/**
* Get 比对库源类型。包括:
公安商业库;
业务方自有库(用户上传照片、客户的混合库、混合部署库);
二次验证库;
人工审核库;
注意:此字段可能返回 null,表示取不到有效值。
* @return CompareLibType 比对库源类型。包括:
公安商业库;
业务方自有库(用户上传照片、客户的混合库、混合部署库);
二次验证库;
人工审核库;
注意:此字段可能返回 null,表示取不到有效值。
*/
public String getCompareLibType() {
return this.CompareLibType;
}
/**
* Set 比对库源类型。包括:
公安商业库;
业务方自有库(用户上传照片、客户的混合库、混合部署库);
二次验证库;
人工审核库;
注意:此字段可能返回 null,表示取不到有效值。
* @param CompareLibType 比对库源类型。包括:
公安商业库;
业务方自有库(用户上传照片、客户的混合库、混合部署库);
二次验证库;
人工审核库;
注意:此字段可能返回 null,表示取不到有效值。
*/
public void setCompareLibType(String CompareLibType) {
this.CompareLibType = CompareLibType;
}
public DetectDetail() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public DetectDetail(DetectDetail source) {
if (source.ReqTime != null) {
this.ReqTime = new String(source.ReqTime);
}
if (source.Seq != null) {
this.Seq = new String(source.Seq);
}
if (source.Idcard != null) {
this.Idcard = new String(source.Idcard);
}
if (source.Name != null) {
this.Name = new String(source.Name);
}
if (source.Sim != null) {
this.Sim = new String(source.Sim);
}
if (source.IsNeedCharge != null) {
this.IsNeedCharge = new Boolean(source.IsNeedCharge);
}
if (source.Errcode != null) {
this.Errcode = new Long(source.Errcode);
}
if (source.Errmsg != null) {
this.Errmsg = new String(source.Errmsg);
}
if (source.Livestatus != null) {
this.Livestatus = new Long(source.Livestatus);
}
if (source.Livemsg != null) {
this.Livemsg = new String(source.Livemsg);
}
if (source.Comparestatus != null) {
this.Comparestatus = new Long(source.Comparestatus);
}
if (source.Comparemsg != null) {
this.Comparemsg = new String(source.Comparemsg);
}
if (source.CompareLibType != null) {
this.CompareLibType = new String(source.CompareLibType);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "ReqTime", this.ReqTime);
this.setParamSimple(map, prefix + "Seq", this.Seq);
this.setParamSimple(map, prefix + "Idcard", this.Idcard);
this.setParamSimple(map, prefix + "Name", this.Name);
this.setParamSimple(map, prefix + "Sim", this.Sim);
this.setParamSimple(map, prefix + "IsNeedCharge", this.IsNeedCharge);
this.setParamSimple(map, prefix + "Errcode", this.Errcode);
this.setParamSimple(map, prefix + "Errmsg", this.Errmsg);
this.setParamSimple(map, prefix + "Livestatus", this.Livestatus);
this.setParamSimple(map, prefix + "Livemsg", this.Livemsg);
this.setParamSimple(map, prefix + "Comparestatus", this.Comparestatus);
this.setParamSimple(map, prefix + "Comparemsg", this.Comparemsg);
this.setParamSimple(map, prefix + "CompareLibType", this.CompareLibType);
}
}
| 9,392 |
319 | from test.support import run_unittest, TESTFN
import unittest
import os
import sunau
nchannels = 2
sampwidth = 2
framerate = 8000
nframes = 100
class SunAUTest(unittest.TestCase):
def setUp(self):
self.f = None
def tearDown(self):
if self.f is not None:
self.f.close()
try:
os.remove(TESTFN)
except OSError:
pass
def test_lin(self):
self.f = sunau.open(TESTFN, 'w')
self.f.setnchannels(nchannels)
self.f.setsampwidth(sampwidth)
self.f.setframerate(framerate)
self.f.setcomptype('NONE', 'not compressed')
output = b'\xff\x00\x12\xcc' * (nframes * nchannels * sampwidth // 4)
self.f.writeframes(output)
self.f.close()
self.f = sunau.open(TESTFN, 'rb')
self.assertEqual(nchannels, self.f.getnchannels())
self.assertEqual(sampwidth, self.f.getsampwidth())
self.assertEqual(framerate, self.f.getframerate())
self.assertEqual(nframes, self.f.getnframes())
self.assertEqual('NONE', self.f.getcomptype())
self.assertEqual(self.f.readframes(nframes), output)
self.f.close()
def test_ulaw(self):
self.f = sunau.open(TESTFN, 'w')
self.f.setnchannels(nchannels)
self.f.setsampwidth(sampwidth)
self.f.setframerate(framerate)
self.f.setcomptype('ULAW', '')
# u-law compression is lossy, therefore we can't expect non-zero data
# to come back unchanged.
output = b'\0' * nframes * nchannels * sampwidth
self.f.writeframes(output)
self.f.close()
self.f = sunau.open(TESTFN, 'rb')
self.assertEqual(nchannels, self.f.getnchannels())
self.assertEqual(sampwidth, self.f.getsampwidth())
self.assertEqual(framerate, self.f.getframerate())
self.assertEqual(nframes, self.f.getnframes())
self.assertEqual('ULAW', self.f.getcomptype())
self.assertEqual(self.f.readframes(nframes), output)
self.f.close()
def test_main():
run_unittest(SunAUTest)
if __name__ == "__main__":
unittest.main()
| 1,021 |
5,411 | <reponame>thorium-cfx/fivem
/*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#pragma once
namespace rage
{
struct Vector3
{
float x, y, z;
private:
float __pad;
public:
Vector3(float x, float y, float z)
: x(x), y(y), z(z), __pad(NAN)
{
}
Vector3()
: Vector3(0.0f, 0.0f, 0.0f)
{
}
inline Vector3 operator*(const float value) const
{
return Vector3(x * value, y * value, z * value);
}
inline Vector3 operator*(const Vector3& value) const
{
return Vector3(x * value.x, y * value.y, z * value.z);
}
inline Vector3 operator+(const Vector3& right) const
{
return Vector3(x + right.x, y + right.y, z + right.z);
}
inline Vector3 operator-(const Vector3& right) const
{
return Vector3(x - right.x, y - right.y, z - right.z);
}
inline void operator*=(const float value)
{
x *= value;
y *= value;
z *= value;
}
inline void operator+=(const Vector3& right)
{
x += right.x;
y += right.y;
z += right.z;
}
inline void operator-=(const Vector3& right)
{
x -= right.x;
y -= right.y;
z -= right.z;
}
inline int MaxAxis() const
{
return x < y ? (y < z ? 2 : 1) : (x < z ? 2 : 0);
}
inline float operator[](int idx) const
{
switch (idx)
{
case 0:
return x;
case 1:
return y;
case 2:
return z;
default:
return NAN;
}
}
inline static Vector3 CrossProduct(const Vector3& v1, const Vector3& v2)
{
return Vector3(
(v1.y * v2.z) - (v1.z * v2.y),
(v1.z * v2.x) - (v1.x * v2.z),
(v1.x * v2.y) - (v1.y * v2.x)
);
}
inline float Length() const
{
return sqrtf((x * x) + (y * y) + (z * z));
}
};
struct Vector4
{
float x, y, z, w;
public:
Vector4(float x, float y, float z, float w)
: x(x), y(y), z(z), w(w)
{
}
Vector4()
: Vector4(0.0f, 0.0f, 0.0f, 1.0f)
{
}
};
}
| 1,117 |
488 | // # 1 "width.c"
// # 1 "<built-in>"
// # 1 "<command-line>"
// # 1 "width.c"
// # 18 "width.c"
// # 1 "../../config.h" 1
// # 19 "width.c" 2
// # 1 "../uniwidth.h" 1
// # 22 "../uniwidth.h"
// # 1 "../unitypes.h" 1
// # 22 "../unitypes.h"
// # 1 "/usr/include/stdint.h" 1 3 4
// # 26 "/usr/include/stdint.h" 3 4
// # 1 "/usr/include/features.h" 1 3 4
// # 329 "/usr/include/features.h" 3 4
// # 1 "/usr/include/sys/cdefs.h" 1 3 4
// # 313 "/usr/include/sys/cdefs.h" 3 4
// # 1 "/usr/include/bits/wordsize.h" 1 3 4
// # 314 "/usr/include/sys/cdefs.h" 2 3 4
// # 330 "/usr/include/features.h" 2 3 4
// # 352 "/usr/include/features.h" 3 4
// # 1 "/usr/include/gnu/stubs.h" 1 3 4
// # 1 "/usr/include/bits/wordsize.h" 1 3 4
// # 5 "/usr/include/gnu/stubs.h" 2 3 4
// # 1 "/usr/include/gnu/stubs-64.h" 1 3 4
// # 10 "/usr/include/gnu/stubs.h" 2 3 4
// # 353 "/usr/include/features.h" 2 3 4
// # 27 "/usr/include/stdint.h" 2 3 4
// # 1 "/usr/include/bits/wchar.h" 1 3 4
// # 28 "/usr/include/stdint.h" 2 3 4
// # 1 "/usr/include/bits/wordsize.h" 1 3 4
// # 29 "/usr/include/stdint.h" 2 3 4
// # 37 "/usr/include/stdint.h" 3 4
typedef signed char int8_t;
typedef short int int16_t;
typedef int int32_t;
typedef long int int64_t;
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long int uint64_t;
// # 66 "/usr/include/stdint.h" 3 4
typedef signed char int_least8_t;
typedef short int int_least16_t;
typedef int int_least32_t;
typedef long int int_least64_t;
typedef unsigned char uint_least8_t;
typedef unsigned short int uint_least16_t;
typedef unsigned int uint_least32_t;
typedef unsigned long int uint_least64_t;
// # 91 "/usr/include/stdint.h" 3 4
typedef signed char int_fast8_t;
typedef long int int_fast16_t;
typedef long int int_fast32_t;
typedef long int int_fast64_t;
// # 104 "/usr/include/stdint.h" 3 4
typedef unsigned char uint_fast8_t;
typedef unsigned long int uint_fast16_t;
typedef unsigned long int uint_fast32_t;
typedef unsigned long int uint_fast64_t;
// # 120 "/usr/include/stdint.h" 3 4
typedef long int intptr_t;
typedef unsigned long int uintptr_t;
// # 135 "/usr/include/stdint.h" 3 4
typedef long int intmax_t;
typedef unsigned long int uintmax_t;
// # 23 "../unitypes.h" 2
typedef uint32_t ucs4_t;
// # 23 "../uniwidth.h" 2
// # 1 "/nfs/apps/gcc/4.2.4/lib/gcc/x86_64-unknown-linux-gnu/4.2.4/include/stddef.h" 1 3 4
// # 152 "/nfs/apps/gcc/4.2.4/lib/gcc/x86_64-unknown-linux-gnu/4.2.4/include/stddef.h" 3 4
typedef long int ptrdiff_t;
// # 214 "/nfs/apps/gcc/4.2.4/lib/gcc/x86_64-unknown-linux-gnu/4.2.4/include/stddef.h" 3 4
typedef long unsigned int size_t;
// # 326 "/nfs/apps/gcc/4.2.4/lib/gcc/x86_64-unknown-linux-gnu/4.2.4/include/stddef.h" 3 4
typedef int wchar_t;
// # 26 "../uniwidth.h" 2
// # 1 "../localcharset.h" 1
// # 32 "../localcharset.h"
extern const char * locale_charset (void);
// # 29 "../uniwidth.h" 2
// # 41 "../uniwidth.h"
extern int
uc_width (ucs4_t uc, const char *encoding)
__attribute__ ((__pure__));
extern int
u8_width (const uint8_t *s, size_t n, const char *encoding)
__attribute__ ((__pure__));
extern int
u16_width (const uint16_t *s, size_t n, const char *encoding)
__attribute__ ((__pure__));
extern int
u32_width (const uint32_t *s, size_t n, const char *encoding)
__attribute__ ((__pure__));
extern int
u8_strwidth (const uint8_t *s, const char *encoding)
__attribute__ ((__pure__));
extern int
u16_strwidth (const uint16_t *s, const char *encoding)
__attribute__ ((__pure__));
extern int
u32_strwidth (const uint32_t *s, const char *encoding)
__attribute__ ((__pure__));
// # 22 "width.c" 2
// # 1 "cjk.h" 1
// # 18 "cjk.h"
// # 1 "../streq.h" 1
// # 22 "../streq.h"
// # 1 "../string.h" 1
// # 22 "../string.h"
// # 23 "../string.h" 3
// # 1 "/usr/include/string.h" 1 3 4
// # 28 "/usr/include/string.h" 3 4
// # 1 "/nfs/apps/gcc/4.2.4/lib/gcc/x86_64-unknown-linux-gnu/4.2.4/include/stddef.h" 1 3 4
// # 34 "/usr/include/string.h" 2 3 4
extern void *memcpy (void *__restrict __dest,
__const void *__restrict __src, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memmove (void *__dest, __const void *__src, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memccpy (void *__restrict __dest, __const void *__restrict __src,
int __c, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memset (void *__s, int __c, size_t __n) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1)));
extern int memcmp (__const void *__s1, __const void *__s2, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memchr (__const void *__s, int __c, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern void *rawmemchr (__const void *__s, int __c)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern void *memrchr (__const void *__s, int __c, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strcpy (char *__restrict __dest, __const char *__restrict __src)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncpy (char *__restrict __dest,
__const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strcat (char *__restrict __dest, __const char *__restrict __src)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strncat (char *__restrict __dest, __const char *__restrict __src,
size_t __n) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcmp (__const char *__s1, __const char *__s2)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncmp (__const char *__s1, __const char *__s2, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcoll (__const char *__s1, __const char *__s2)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strxfrm (char *__restrict __dest,
__const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2)));
// # 1 "/usr/include/xlocale.h" 1 3 4
// # 28 "/usr/include/xlocale.h" 3 4
typedef struct __locale_struct
{
struct locale_data *__locales[13];
const unsigned short int *__ctype_b;
const int *__ctype_tolower;
const int *__ctype_toupper;
const char *__names[13];
} *__locale_t;
// # 119 "/usr/include/string.h" 2 3 4
extern int strcoll_l (__const char *__s1, __const char *__s2, __locale_t __l)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 3)));
extern size_t strxfrm_l (char *__dest, __const char *__src, size_t __n,
__locale_t __l) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2, 4)));
extern char *strdup (__const char *__s)
__attribute__ ((__nothrow__)) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
extern char *strndup (__const char *__string, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__malloc__)) __attribute__ ((__nonnull__ (1)));
// # 165 "/usr/include/string.h" 3 4
extern char *strchr (__const char *__s, int __c)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strrchr (__const char *__s, int __c)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strchrnul (__const char *__s, int __c)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern size_t strcspn (__const char *__s, __const char *__reject)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strspn (__const char *__s, __const char *__accept)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strpbrk (__const char *__s, __const char *__accept)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strstr (__const char *__haystack, __const char *__needle)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strtok (char *__restrict __s, __const char *__restrict __delim)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2)));
extern char *__strtok_r (char *__restrict __s,
__const char *__restrict __delim,
char **__restrict __save_ptr)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2, 3)));
extern char *strtok_r (char *__restrict __s, __const char *__restrict __delim,
char **__restrict __save_ptr)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2, 3)));
extern char *strcasestr (__const char *__haystack, __const char *__needle)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *memmem (__const void *__haystack, size_t __haystacklen,
__const void *__needle, size_t __needlelen)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 3)));
extern void *__mempcpy (void *__restrict __dest,
__const void *__restrict __src, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern void *mempcpy (void *__restrict __dest,
__const void *__restrict __src, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern size_t strlen (__const char *__s)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern size_t strnlen (__const char *__string, size_t __maxlen)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *strerror (int __errnum) __attribute__ ((__nothrow__));
// # 281 "/usr/include/string.h" 3 4
extern char *strerror_r (int __errnum, char *__buf, size_t __buflen)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (2)));
extern void __bzero (void *__s, size_t __n) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1)));
extern void bcopy (__const void *__src, void *__dest, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern void bzero (void *__s, size_t __n) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1)));
extern int bcmp (__const void *__s1, __const void *__s2, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *index (__const char *__s, int __c)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern char *rindex (__const char *__s, int __c)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern int ffs (int __i) __attribute__ ((__nothrow__)) __attribute__ ((__const__));
extern int ffsl (long int __l) __attribute__ ((__nothrow__)) __attribute__ ((__const__));
__extension__ extern int ffsll (long long int __ll)
__attribute__ ((__nothrow__)) __attribute__ ((__const__));
extern int strcasecmp (__const char *__s1, __const char *__s2)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strncasecmp (__const char *__s1, __const char *__s2, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strcasecmp_l (__const char *__s1, __const char *__s2,
__locale_t __loc)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 3)));
extern int strncasecmp_l (__const char *__s1, __const char *__s2,
size_t __n, __locale_t __loc)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2, 4)));
extern char *strsep (char **__restrict __stringp,
__const char *__restrict __delim)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern int strverscmp (__const char *__s1, __const char *__s2)
__attribute__ ((__nothrow__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strsignal (int __sig) __attribute__ ((__nothrow__));
extern char *__stpcpy (char *__restrict __dest, __const char *__restrict __src)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpcpy (char *__restrict __dest, __const char *__restrict __src)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *__stpncpy (char *__restrict __dest,
__const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *stpncpy (char *__restrict __dest,
__const char *__restrict __src, size_t __n)
__attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1, 2)));
extern char *strfry (char *__string) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1)));
extern void *memfrob (void *__s, size_t __n) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1)));
extern char *basename (__const char *__filename) __attribute__ ((__nothrow__)) __attribute__ ((__nonnull__ (1)));
// # 426 "/usr/include/string.h" 3 4
// # 28 "../string.h" 2 3
// # 1 "/nfs/apps/gcc/4.2.4/lib/gcc/x86_64-unknown-linux-gnu/4.2.4/include/stddef.h" 1 3 4
// # 34 "../string.h" 2 3
// # 422 "../string.h" 3
extern int _gl_cxxalias_dummy;
// # 432 "../string.h" 3
extern int _gl_cxxalias_dummy;
// # 486 "../string.h" 3
extern int _gl_cxxalias_dummy;
extern int _gl_cxxalias_dummy;
// # 508 "../string.h" 3
extern int _gl_cxxalias_dummy;
extern int _gl_cxxalias_dummy;
// # 563 "../string.h" 3
extern int _gl_cxxalias_dummy;
extern int _gl_cxxalias_dummy;
// # 675 "../string.h" 3
extern int _gl_cxxalias_dummy;
extern int _gl_cxxalias_dummy;
// # 753 "../string.h" 3
extern int _gl_cxxalias_dummy;
extern int _gl_cxxalias_dummy;
// # 1044 "../string.h" 3
extern size_t mbslen (const char *string) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1)));
extern int _gl_cxxalias_dummy;
extern int _gl_cxxalias_dummy;
// # 1109 "../string.h" 3
extern char * mbsstr (const char *haystack, const char *needle)
__attribute__ ((__pure__))
__attribute__ ((__nonnull__ (1, 2)));
// # 1121 "../string.h" 3
extern int mbscasecmp (const char *s1, const char *s2)
__attribute__ ((__pure__))
__attribute__ ((__nonnull__ (1, 2)));
// # 1257 "../string.h" 3
extern char * rpl_strerror (int);
extern int _gl_cxxalias_dummy;
extern int _gl_cxxalias_dummy;
// # 23 "../streq.h" 2
// # 19 "cjk.h" 2
static int
is_cjk_encoding (const char *encoding)
{
if (0
|| (strcmp (encoding, "EUC-JP") == 0)
|| (strcmp (encoding, "GB2312") == 0)
|| (strcmp (encoding, "GBK") == 0)
|| (strcmp (encoding, "EUC-TW") == 0)
|| (strcmp (encoding, "BIG5") == 0)
|| (strcmp (encoding, "EUC-KR") == 0)
|| (strcmp (encoding, "CP949") == 0)
|| (strcmp (encoding, "JOHAB") == 0))
return 1;
return 0;
}
// # 24 "width.c" 2
// # 35 "width.c"
static const unsigned char nonspacing_table_data[27*64] = {
0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0xff, 0xff, 0xff, 0xff, 0x00, 0x20, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xf8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xbf,
0xb6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x00, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00,
0x00, 0xf8, 0xff, 0xff, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xc0, 0xbf, 0x9f, 0x3d, 0x00, 0x00,
0x00, 0x80, 0x02, 0x00, 0x00, 0x00, 0xff, 0xff,
0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x0f, 0x00,
0x00, 0x00, 0xc0, 0xfb, 0xef, 0x3e, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14,
0xfe, 0x21, 0xfe, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
0x1e, 0x20, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
0x86, 0x39, 0x02, 0x00, 0x00, 0x00, 0x23, 0x00,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
0xbe, 0x21, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90,
0x1e, 0x20, 0x40, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0,
0xc1, 0x3d, 0x60, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
0x00, 0x30, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1e, 0x20, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x04, 0x5c, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf2, 0x07,
0x80, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf2, 0x1b,
0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0xa0, 0x02,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f,
0xdf, 0xe0, 0xff, 0xfe, 0xff, 0xff, 0xff, 0x1f,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xfd, 0x66,
0x00, 0x00, 0x00, 0xc3, 0x01, 0x00, 0x1e, 0x00,
0x64, 0x20, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x1c, 0x00,
0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0c, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x3f,
0x40, 0xfe, 0x0f, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x87, 0x01, 0x04, 0x0e,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x40, 0x7f, 0xe5, 0x1f, 0xf8, 0x9f,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x17,
0x04, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x0f, 0x00,
0x03, 0x00, 0x00, 0x00, 0x3c, 0x03, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x40, 0xa3, 0x03, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xcf, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xf7, 0xff, 0xfd, 0x21, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0xf0,
0x00, 0xf8, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0xfc, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x03, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x07, 0x30,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x08, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0xff, 0xff, 0x03, 0x00,
0x00, 0x00, 0x00, 0x00, 0xc0, 0x3f, 0x00, 0x00,
0x80, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x13,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x66, 0x00,
0x08, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9d, 0xc1,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x20, 0x21, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20,
0x6e, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x26,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x03, 0xf8, 0xff,
0xe7, 0x0f, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static const signed char nonspacing_table_ind[240] = {
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, -1, 10, 11, 12, 13, -1,
14, -1, -1, -1, -1, -1, 15, -1,
16, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 17, 18, 19, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 20, -1, 21,
22, -1, -1, -1, -1, 23, -1, -1,
24, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
25, 26, -1, -1, -1, -1, -1, -1
};
int
uc_width (ucs4_t uc, const char *encoding)
{
if ((uc >> 9) < 240)
{
int ind = nonspacing_table_ind[uc >> 9];
if (ind >= 0)
if ((nonspacing_table_data[64*ind + ((uc >> 3) & 63)] >> (uc & 7)) & 1)
{
if (uc > 0 && uc < 0xa0)
return -1;
else
return 0;
}
}
else if ((uc >> 9) == (0xe0000 >> 9))
{
if (uc >= 0xe0100)
{
if (uc <= 0xe01ef)
return 0;
}
else
{
if (uc >= 0xe0020 ? uc <= 0xe007f : uc == 0xe0001)
return 0;
}
}
if (uc >= 0x1100
&& ((uc < 0x1160)
|| (uc >= 0x2329 && uc < 0x232b)
|| (uc >= 0x2e80 && uc < 0xa4d0
&& !(uc == 0x303f) && !(uc >= 0x4dc0 && uc < 0x4e00))
|| (uc >= 0xac00 && uc < 0xd7a4)
|| (uc >= 0xf900 && uc < 0xfb00)
|| (uc >= 0xfe10 && uc < 0xfe20)
|| (uc >= 0xfe30 && uc < 0xfe70)
|| (uc >= 0xff00 && uc < 0xff61)
|| (uc >= 0xffe0 && uc < 0xffe7)
|| (uc >= 0x20000 && uc <= 0x2ffff)
|| (uc >= 0x30000 && uc <= 0x3ffff)
) )
return 2;
if (uc >= 0x00A1 && uc < 0xFF61 && uc != 0x20A9
&& is_cjk_encoding (encoding))
return 2;
return 1;
}
| 15,483 |
4,606 | <filename>examples/docs_snippets_crag/docs_snippets_crag/concepts/solids_pipelines/graph_provides_config.py
from dagster import graph, op
@op(config_schema={"n": float})
def add_n(context, number):
return number + context.solid_config["n"]
@op(config_schema={"m": float})
def multiply_by_m(context, number):
return number * context.solid_config["m"]
@graph(config={"multiply_by_m": {"config": {"m": 1.8}}, "add_n": {"config": {"n": 32}}})
def celsius_to_fahrenheit(number):
return multiply_by_m(add_n(number))
| 204 |
1,090 | #include <math.h>
double hypotenuse(double a, double b) {
return sqrt(a*a + b*b);
}
| 38 |
4,816 | /**
* @file src/llvmir2hll/ir/if_stmt.cpp
* @brief Implementation of IfStmt.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/llvmir2hll/ir/expression.h"
#include "retdec/llvmir2hll/ir/if_stmt.h"
#include "retdec/llvmir2hll/ir/variable.h"
#include "retdec/llvmir2hll/support/debug.h"
#include "retdec/llvmir2hll/support/visitor.h"
namespace retdec {
namespace llvmir2hll {
/**
* @brief Constructs a new if/else-if/else statement.
*
* See create() for more information.
*/
IfStmt::IfStmt(ShPtr<Expression> cond, ShPtr<Statement> body, Address a):
Statement(a), ifClauseList{IfClause(cond, body)}, elseClause() {}
ShPtr<Value> IfStmt::clone() {
ShPtr<IfStmt> ifStmt(IfStmt::create(
ucast<Expression>(ifClauseList.front().first->clone()),
ucast<Statement>(Statement::cloneStatements(ifClauseList.front().second)),
nullptr,
getAddress()));
if (elseClause) {
ifStmt->setElseClause(
ucast<Statement>(Statement::cloneStatements(elseClause)));
}
// Clone all other clauses.
for (const auto &clause : ifClauseList) {
// The first clause has already been cloned, so skip it.
if (clause == ifClauseList.front()) {
continue;
}
ifStmt->addClause(
ucast<Expression>(clause.first->clone()),
ucast<Statement>(Statement::cloneStatements(clause.second)));
}
ifStmt->setMetadata(getMetadata());
return ifStmt;
}
bool IfStmt::isEqualTo(ShPtr<Value> otherValue) const {
// The types of compared instances have to match.
ShPtr<IfStmt> otherIfStmt = cast<IfStmt>(otherValue);
if (!otherIfStmt) {
return false;
}
// The number of 'if' clauses have to match.
if (ifClauseList.size() != otherIfStmt->ifClauseList.size()) {
return false;
}
// All 'if' clauses have to match.
for (auto i = clause_begin(), j = otherIfStmt->clause_begin(),
e = clause_end(); i != e; ++i, ++j) {
if (!(i->first->isEqualTo(j->first) &&
i->second->isEqualTo(j->second))) {
return false;
}
}
// The else clauses have to match.
if (hasElseClause()) {
return otherIfStmt->hasElseClause() &&
elseClause->isEqualTo(otherIfStmt->elseClause);
}
// The first if statement doesn't have an else clause, so the other if
// statement should also not have one.
return !otherIfStmt->hasElseClause();
}
void IfStmt::replace(ShPtr<Expression> oldExpr, ShPtr<Expression> newExpr) {
// For each clause...
for (auto &clause : ifClauseList) {
if (clause.first == oldExpr) {
clause.first->removeObserver(shared_from_this());
newExpr->addObserver(shared_from_this());
clause.first = newExpr;
} else {
clause.first->replace(oldExpr, newExpr);
}
}
}
ShPtr<Expression> IfStmt::asExpression() const {
// Cannot be converted into an expression.
return {};
}
/**
* @brief Adds a new clause (`[else] if cond then body`).
*
* @param[in] cond Clause condition.
* @param[in] body Clause body.
*
* If there are no clauses, the added clause is the if clause; otherwise, it is
* an else-if clause.
*
* Does not invalidate any existing iterators to this if statement.
*
* @par Preconditions
* - both arguments are non-null
*/
void IfStmt::addClause(ShPtr<Expression> cond, ShPtr<Statement> body) {
PRECONDITION_NON_NULL(cond);
PRECONDITION_NON_NULL(body);
body->removePredecessors(true);
cond->addObserver(shared_from_this());
body->addObserver(shared_from_this());
ifClauseList.push_back(IfClause(cond, body));
}
/**
* @brief Returns @c true if there is at least one else-if clause, @c false
* otherwise.
*
* An else-if clause is a clause which is not the main if's clause or the else
* clause.
*/
bool IfStmt::hasElseIfClauses() const {
return ifClauseList.size() > 1;
}
/**
* @brief Removes the given clause, specified by an iterator.
*
* @return Iterator to the next clause (or clause_end() if there are no
* subsequent clauses).
*
* After this function is called, existing iterators to the removed clause are
* invalidated. To provide an easy way of removing clauses while iterating over
* them, the iterator returned from this function can be used. Example:
* @code
* clause_iterator i(ifStmt->clause_begin());
* while (i != ifStmt->clause_end()) {
* if (condition) {
* i = ifStmt->removeClause(i);
* } else {
* ++i;
* }
* }
* @endcode
*
* You cannot remove the else clause by this function; use removeElseClause()
* instead.
*
* If you remove the only clause of the statement, then the statement becomes a
* statement without any clauses. Such a statement is useless.
*
* @par Preconditions
* - the passed iterator is valid
*/
IfStmt::clause_iterator IfStmt::removeClause(clause_iterator clauseIterator) {
// We assume that the used container is std::list.
clauseIterator->first->removeObserver(shared_from_this());
clauseIterator->second->removeObserver(shared_from_this());
return ifClauseList.erase(clauseIterator);
}
/**
* @brief Returns @c true if there is at least one clause, @c false otherwise.
*
* This function takes into account all the types of clauses: the if clause,
* else-if clauses, and the else clause (if any).
*/
bool IfStmt::hasClauses() const {
return !ifClauseList.empty() || elseClause;
}
/**
* @brief Returns @c true if the statement has the if clause, @c false otherwise.
*
* Note that if this function returns @c false, then the statement is most
* probably not valid (every if statement should have an if clause).
*/
bool IfStmt::hasIfClause() const {
return !ifClauseList.empty();
}
/**
* @brief Sets the else clause (`else body`).
*
* @param[in] body Clause body.
*
* If @a body is the null pointer, then there is no else clause.
*/
void IfStmt::setElseClause(ShPtr<Statement> body) {
if (hasElseClause()) {
elseClause->removeObserver(shared_from_this());
}
if (body) {
body->removePredecessors(true);
body->addObserver(shared_from_this());
}
elseClause = body;
}
/**
* @brief Removes the else clause (if any).
*
* Calling this function is the same as calling @c
* setElseClause(ShPtr<Statement>()).
*/
void IfStmt::removeElseClause() {
setElseClause(ShPtr<Statement>());
}
/**
* @brief Returns @c true if this if statement has an else clause, @c false
* otherwise.
*/
bool IfStmt::hasElseClause() const {
return elseClause != nullptr;
}
/**
* @brief Returns an iterator to the first if clause (`if cond then body`).
*
* Use getElseClause() to obtain the else clause (it cannot be accessed by
* iterators).
*/
IfStmt::clause_iterator IfStmt::clause_begin() const {
return ifClauseList.begin();
}
/**
* @brief Returns an iterator past the last else-if clause.
*
* Use getElseClause() to obtain the else clause (it cannot be accessed by
* iterators).
*/
IfStmt::clause_iterator IfStmt::clause_end() const {
return ifClauseList.end();
}
/**
* @brief Returns the else clause (if any), the null pointer otherwise.
*/
ShPtr<Statement> IfStmt::getElseClause() const {
return elseClause;
}
/**
* @brief Constructs a new if statement.
*
* @param[in] cond Statement condition.
* @param[in] body Statement body.
* @param[in] succ Follower of the statement in the program flow.
* @param[in] a Address.
*
* @par Preconditions
* - @a cond and @a body are non-null
*/
ShPtr<IfStmt> IfStmt::create(ShPtr<Expression> cond, ShPtr<Statement> body,
ShPtr<Statement> succ, Address a) {
PRECONDITION_NON_NULL(cond);
PRECONDITION_NON_NULL(body);
ShPtr<IfStmt> stmt(new IfStmt(cond, body, a));
stmt->setSuccessor(succ);
// Initialization (recall that shared_from_this() cannot be called in a
// constructor).
cond->addObserver(stmt);
body->addObserver(stmt);
body->removePredecessors(true);
return stmt;
}
/**
* @brief Updates the statement according to the changes of @a subject.
*
* @param[in] subject Observable object.
* @param[in] arg Optional argument.
*
* Replaces @a subject with @a arg. For example, if @a subject is the conditions
* of some if-clause, this function replaces it with @a arg.
*
* This function does nothing when:
* - @a subject does not correspond to any part of the statement
* - @a arg is not a statement/expression
*
* @par Preconditions
* - @a subject is non-null
* - when @a subject is a condition or a body of an if-clause, @a arg has to be
* non-null
*
* @see Subject::update()
*/
void IfStmt::update(ShPtr<Value> subject, ShPtr<Value> arg) {
PRECONDITION_NON_NULL(subject);
// Check all if/else-if clauses.
ShPtr<Expression> newCond = cast<Expression>(arg);
ShPtr<Statement> newBody = cast<Statement>(arg);
for (auto &clause : ifClauseList) {
// TODO Refactor the handling of observers into a separate function
// after methods for updating if-else clauses are implemented.
if (subject == clause.first && newCond) {
clause.first->removeObserver(shared_from_this());
newCond->addObserver(shared_from_this());
clause.first = newCond;
} else if (subject == clause.second && newBody) {
clause.second->removeObserver(shared_from_this());
newBody->addObserver(shared_from_this());
clause.second = newBody;
}
}
// Check the else clause.
if (hasElseClause() && subject == elseClause && (!arg || newBody)) {
setElseClause(newBody);
return;
}
}
void IfStmt::accept(Visitor *v) {
v->visit(ucast<IfStmt>(shared_from_this()));
}
/**
* @brief Returns the condition of the first if clause in the statement.
*
* If there are no if clauses, the null pointer is returned.
*/
ShPtr<Expression> IfStmt::getFirstIfCond() const {
if (ifClauseList.empty()) {
return ShPtr<Expression>();
}
return clause_begin()->first;
}
/**
* @brief Returns the body of the first if clause in the statement.
*
* If there are no if clauses, the null pointer is returned.
*/
ShPtr<Statement> IfStmt::getFirstIfBody() const {
if (ifClauseList.empty()) {
return ShPtr<Statement>();
}
return clause_begin()->second;
}
/**
* @brief Sets a new condition of the first if clause.
*
* @par Preconditions
* - @a newCond is non-null
*/
void IfStmt::setFirstIfCond(ShPtr<Expression> newCond) {
PRECONDITION_NON_NULL(newCond);
ifClauseList.begin()->first->removeObserver(shared_from_this());
newCond->addObserver(shared_from_this());
*ifClauseList.begin() = IfClause(newCond, ifClauseList.begin()->second);
}
/**
* @brief Sets a new body of the first if clause.
*
* @par Preconditions
* - @a newBody is non-null
*/
void IfStmt::setFirstIfBody(ShPtr<Statement> newBody) {
PRECONDITION_NON_NULL(newBody);
ifClauseList.begin()->second->removeObserver(shared_from_this());
newBody->addObserver(shared_from_this());
newBody->removePredecessors(true);
*ifClauseList.begin() = IfClause(ifClauseList.begin()->first, newBody);
}
} // namespace llvmir2hll
} // namespace retdec
| 3,743 |
892 | <reponame>westonsteimel/advisory-database-github<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-p62j-hrxm-xcxf",
"modified": "2022-01-06T19:44:35Z",
"published": "2022-01-06T23:53:35Z",
"aliases": [
],
"summary": "Book page text, count, and author/title length is not limited in PocketMine-MP",
"details": "### Impact\nPlayers can fill book pages with as many characters as they like; the server does not check this.\nIn addition, the maximum of 50 pages is also not enforced, meaning that players can create \"book bombs\".\n\nThis causes a variety of problems:\n- Oversized NBT on the wire costing excess bandwidth for server and client\n- Server crashes when saving region-based worlds due to exceeding maximum chunk size of 1 MB (PM3-specific)\n- Server crashes if any book page exceeds 32 KiB (due to TAG_String size limit) (PM4-specific)\n\nThis does, however, require that an attacker obtain a writable book in the first place in order to exploit the problem.\n\n### Patches\nThe bug has been fixed in 3.26.5 and 4.0.5.\n\n### Workarounds\nBan writable books, or use a plugin to cancel `PlayerEditBookEvent` to cancel the event if `strlen(text) > 1024 || mb_strlen(text) > 256`.\n\n### For more information\nIf you have any questions or comments about this advisory:\n* Email us at [<EMAIL>](mailto:<EMAIL>)\n",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H"
}
],
"affected": [
{
"package": {
"ecosystem": "Packagist",
"name": "pocketmine/pocketmine-mp"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "0"
},
{
"fixed": "3.26.5"
}
]
}
]
},
{
"package": {
"ecosystem": "Packagist",
"name": "pocketmine/pocketmine-mp"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "4.0.0"
},
{
"fixed": "4.0.5"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/pmmp/PocketMine-MP/security/advisories/GHSA-p62j-hrxm-xcxf"
},
{
"type": "PACKAGE",
"url": "https://github.com/pmmp/PocketMine-MP"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": true
}
} | 1,183 |
684 | /* 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.activiti.explorer.ui.content.url;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Attachment;
import org.activiti.explorer.ExplorerApp;
import org.activiti.explorer.I18nManager;
import org.activiti.explorer.Messages;
import org.activiti.explorer.ui.content.AttachmentEditorComponent;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.ui.Form;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
/**
* @author <NAME>
*/
public class UrlAttachmentEditorComponent extends Form implements AttachmentEditorComponent {
private static final long serialVersionUID = 1L;
protected Attachment attachment;
protected String taskId;
protected String processInstanceId;
protected I18nManager i18nManager;
protected transient TaskService taskService;
public UrlAttachmentEditorComponent(String taskId, String processInstanceId) {
this(null, taskId, processInstanceId);
}
public UrlAttachmentEditorComponent(Attachment attachment, String taskId, String processInstanceId) {
this.attachment = attachment;
this.taskId = taskId;
this.processInstanceId = processInstanceId;
this.i18nManager = ExplorerApp.get().getI18nManager();
taskService = ProcessEngines.getDefaultProcessEngine().getTaskService();
setSizeFull();
setDescription(i18nManager.getMessage(Messages.RELATED_CONTENT_TYPE_URL_HELP));
initUrl();
initName();
initDescription();
}
protected void initUrl() {
TextField urlField = new TextField(i18nManager.getMessage(Messages.RELATED_CONTENT_TYPE_URL_URL));
urlField.focus();
urlField.setRequired(true);
urlField.setRequiredError(i18nManager.getMessage(Messages.RELATED_CONTENT_TYPE_URL_URL_REQUIRED));
urlField.setWidth(100, UNITS_PERCENTAGE);
// URL isn't mutable once attachment is created
if(attachment != null) {
urlField.setEnabled(false);
}
addField("url", urlField);
}
protected void initDescription() {
TextArea descriptionField = new TextArea(i18nManager.getMessage(Messages.RELATED_CONTENT_DESCRIPTION));
descriptionField.setWidth(100, UNITS_PERCENTAGE);
descriptionField.setHeight(100, UNITS_PIXELS);
addField("description", descriptionField);
}
protected void initName() {
TextField nameField = new TextField(i18nManager.getMessage(Messages.RELATED_CONTENT_NAME));
nameField.setWidth(100, UNITS_PERCENTAGE);
addField("name", nameField);
}
public Attachment getAttachment() throws InvalidValueException {
// Force validation of the fields
commit();
if(attachment != null) {
applyValuesToAttachment();
} else {
// Create new attachment based on values
// TODO: use explorerApp to get service
attachment = taskService.createAttachment(UrlAttachmentRenderer.ATTACHMENT_TYPE, taskId, processInstanceId,
getAttachmentName(), getAttachmentDescription(), getAttachmentUrl());
}
return attachment;
}
protected String getAttachmentUrl() {
return (String) getFieldValue("url");
}
protected String getAttachmentName() {
String name = (String) getFieldValue("name");
if(name == null) {
name = getAttachmentUrl();
}
return name;
}
protected String getAttachmentDescription() {
return getFieldValue("description");
}
protected String getFieldValue(String key) {
String value = (String) getField(key).getValue();
if("".equals(value)) {
return null;
}
return value;
}
private void applyValuesToAttachment() {
attachment.setName(getAttachmentName());
attachment.setDescription(getAttachmentDescription());
}
}
| 1,390 |
522 | <filename>tests/timeinittest.cpp
#include "rtptimeutilities.h"
#include "rtpudpv4transmitter.h"
#include <iostream>
int main(void)
{
jrtplib::RTPUDPv4Transmitter trans(0);
jrtplib::RTPTime t(0);
std::cout << t.GetDouble() << std::endl;
return 0;
}
| 113 |
604 | <reponame>xxoolm/IbEverythingExt<gh_stars>100-1000
#include "pch.h"
#include "ipc.hpp"
#include "helper.hpp"
ib::Holder<Everythings::EverythingMT> ipc_ev;
Everythings::EverythingMT::Version ipc_version;
void ipc_init(std::wstring_view instance_name) {
ipc_ev.create(instance_name);
ipc_version = ipc_ev->get_version();
}
void ipc_destroy() {
ipc_ev.destroy();
} | 160 |
683 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.api;
final class CallDepthThreadLocalMap {
private static final ClassValue<ThreadLocalDepth> TLS =
new ClassValue<ThreadLocalDepth>() {
@Override
protected ThreadLocalDepth computeValue(Class<?> type) {
return new ThreadLocalDepth();
}
};
static CallDepth getCallDepth(Class<?> k) {
return TLS.get(k).get();
}
private static final class ThreadLocalDepth extends ThreadLocal<CallDepth> {
@Override
protected CallDepth initialValue() {
return new CallDepth();
}
}
private CallDepthThreadLocalMap() {}
}
| 245 |
302 | #include "../cpu/isr.h"
#include "../drivers/screen.h"
#include "kernel.h"
#include "../libc/string.h"
#include "../memory/kheap.h"
#include <stdint.h>
void kernel_main()
{
isr_install();
irq_install();
fprint("Type something, it will go through the kernel\n"
"Type END to halt the CPU or PAGE to request a kmalloc()\n> ");
}
void user_input(char *input)
{
if (strcmp(input, "END") == 0)
{
fprint("Stopping the CPU. Bye!\n");
asm volatile("hlt");
}
else if (strcmp(input, "PAGE") == 0)
{
uint32_t phys_addr;
uint32_t page = kmalloc_ap(1000, &phys_addr);
fprint("Page: %d, physical address: %x\n", page, phys_addr);
}
fprint("You said: %s\n> ", input);
}
| 341 |
479 | // 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 com.google.gerrit.server.config;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.jgit.lib.Config;
@Singleton
public class ThreadSettingsConfig {
private final int sshdThreads;
private final int httpdMaxThreads;
private final int sshdBatchThreads;
private final int databasePoolLimit;
@Inject
ThreadSettingsConfig(@GerritServerConfig Config cfg) {
int cores = Runtime.getRuntime().availableProcessors();
sshdThreads = cfg.getInt("sshd", "threads", 2 * cores);
httpdMaxThreads = cfg.getInt("httpd", "maxThreads", 25);
int defaultDatabasePoolLimit = sshdThreads + httpdMaxThreads + 2;
databasePoolLimit = cfg.getInt("database", "poolLimit", defaultDatabasePoolLimit);
sshdBatchThreads = cores == 1 ? 1 : 2;
}
public int getDatabasePoolLimit() {
return databasePoolLimit;
}
public int getHttpdMaxThreads() {
return httpdMaxThreads;
}
public int getSshdThreads() {
return sshdThreads;
}
public int getSshdBatchTreads() {
return sshdBatchThreads;
}
}
| 512 |
1,346 | <filename>app/src/main/java/com/huanchengfly/tieba/post/components/dialogs/BaseBottomSheetDialog.java
package com.huanchengfly.tieba.post.components.dialogs;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.huanchengfly.tieba.post.R;
public abstract class BaseBottomSheetDialog extends BottomSheetDialog {
public BaseBottomSheetDialog(@NonNull Context context) {
this(context, R.style.BottomSheetDialogStyle);
}
public BaseBottomSheetDialog(@NonNull Context context, int theme) {
super(context, theme);
initView();
}
protected BaseBottomSheetDialog(@NonNull Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
initView();
}
private void initView() {
View view = getLayoutInflater().inflate(getLayoutId(), null);
setContentView(view);
initView(view);
}
protected abstract void initView(View contentView);
abstract int getLayoutId();
}
| 392 |
14,425 | <reponame>bzhaoopenstack/hadoop
/**
* 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.hadoop.mapreduce.v2.hs.webapp;
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.hadoop.http.HttpConfig;
import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.junit.Test;
public class TestMapReduceTrackingUriPlugin {
@Test
public void testProducesHistoryServerUriForAppId()
throws URISyntaxException {
final String historyAddress = "example.net:424242";
YarnConfiguration conf = new YarnConfiguration();
conf.set(JHAdminConfig.MR_HS_HTTP_POLICY,
HttpConfig.Policy.HTTP_ONLY.name());
conf.set(JHAdminConfig.MR_HISTORY_WEBAPP_ADDRESS, historyAddress);
MapReduceTrackingUriPlugin plugin = new MapReduceTrackingUriPlugin();
plugin.setConf(conf);
ApplicationId id = ApplicationId.newInstance(6384623L, 5);
String jobSuffix = id.toString().replaceFirst("^application_", "job_");
URI expected =
new URI("http://" + historyAddress + "/jobhistory/job/" + jobSuffix);
URI actual = plugin.getTrackingUri(id);
assertEquals(expected, actual);
}
@Test
public void testProducesHistoryServerUriWithHTTPS()
throws URISyntaxException {
final String historyAddress = "example.net:404040";
YarnConfiguration conf = new YarnConfiguration();
conf.set(JHAdminConfig.MR_HS_HTTP_POLICY,
HttpConfig.Policy.HTTPS_ONLY.name());
conf.set(JHAdminConfig.MR_HISTORY_WEBAPP_HTTPS_ADDRESS, historyAddress);
MapReduceTrackingUriPlugin plugin = new MapReduceTrackingUriPlugin();
plugin.setConf(conf);
ApplicationId id = ApplicationId.newInstance(6384623L, 5);
String jobSuffix = id.toString().replaceFirst("^application_", "job_");
URI expected =
new URI("https://" + historyAddress + "/jobhistory/job/" + jobSuffix);
URI actual = plugin.getTrackingUri(id);
assertEquals(expected, actual);
}
} | 956 |
5,964 | <filename>src/compiler/branch-elimination.h
// Copyright 2015 the V8 project 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 V8_COMPILER_BRANCH_CONDITION_ELIMINATION_H_
#define V8_COMPILER_BRANCH_CONDITION_ELIMINATION_H_
#include "src/base/compiler-specific.h"
#include "src/compiler/graph-reducer.h"
#include "src/globals.h"
namespace v8 {
namespace internal {
namespace compiler {
// Forward declarations.
class CommonOperatorBuilder;
class JSGraph;
class V8_EXPORT_PRIVATE BranchElimination final
: public NON_EXPORTED_BASE(AdvancedReducer) {
public:
BranchElimination(Editor* editor, JSGraph* js_graph, Zone* zone);
~BranchElimination() final;
Reduction Reduce(Node* node) final;
private:
struct BranchCondition {
Node* condition;
bool is_true;
BranchCondition* next;
BranchCondition(Node* condition, bool is_true, BranchCondition* next)
: condition(condition), is_true(is_true), next(next) {}
};
// Class for tracking information about branch conditions.
// At the moment it is a linked list of conditions and their values
// (true or false).
class ControlPathConditions {
public:
Maybe<bool> LookupCondition(Node* condition) const;
const ControlPathConditions* AddCondition(Zone* zone, Node* condition,
bool is_true) const;
static const ControlPathConditions* Empty(Zone* zone);
void Merge(const ControlPathConditions& other);
bool operator==(const ControlPathConditions& other) const;
bool operator!=(const ControlPathConditions& other) const {
return !(*this == other);
}
private:
ControlPathConditions(BranchCondition* head, size_t condition_count)
: head_(head), condition_count_(condition_count) {}
BranchCondition* head_;
// We keep track of the list length so that we can find the longest
// common tail easily.
size_t condition_count_;
};
// Maps each control node to the condition information known about the node.
// If the information is nullptr, then we have not calculated the information
// yet.
class PathConditionsForControlNodes {
public:
PathConditionsForControlNodes(Zone* zone, size_t size_hint)
: info_for_node_(size_hint, nullptr, zone) {}
const ControlPathConditions* Get(Node* node);
void Set(Node* node, const ControlPathConditions* conditions);
private:
ZoneVector<const ControlPathConditions*> info_for_node_;
};
Reduction ReduceBranch(Node* node);
Reduction ReduceDeoptimizeConditional(Node* node);
Reduction ReduceIf(Node* node, bool is_true_branch);
Reduction ReduceLoop(Node* node);
Reduction ReduceMerge(Node* node);
Reduction ReduceStart(Node* node);
Reduction ReduceOtherControl(Node* node);
Reduction TakeConditionsFromFirstControl(Node* node);
Reduction UpdateConditions(Node* node,
const ControlPathConditions* conditions);
Node* dead() const { return dead_; }
Graph* graph() const;
JSGraph* jsgraph() const { return jsgraph_; }
CommonOperatorBuilder* common() const;
JSGraph* const jsgraph_;
PathConditionsForControlNodes node_conditions_;
Zone* zone_;
Node* dead_;
};
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_COMPILER_BRANCH_CONDITION_ELIMINATION_H_
| 1,143 |
314 | <reponame>kolinkrewinkel/Multiplex
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "CDStructures.h"
@interface IDEIPAProcessor : NSObject
{
}
+ (id)sharedInstance;
- (BOOL)compileBitcodeForPayloadAppAtPath:(id)arg1 toPath:(id)arg2 logAspect:(id)arg3 error:(id *)arg4;
- (BOOL)optimizePayloadAppAtPath:(id)arg1 toPath:(id)arg2 forDeviceFamily:(id)arg3 logAspect:(id)arg4 error:(id *)arg5;
- (id)consolidateDeviceFamiliesWithEquivalentTraits:(id)arg1;
- (id)applicableDeviceFamiliesForPayloadAtPath:(id)arg1 logAspect:(id)arg2 error:(id *)arg3;
- (BOOL)enumerateSupportedDeviceSetInfosForPayloadAppAtPath:(id)arg1 logAspect:(id)arg2 error:(id *)arg3 usingBlock:(dispatch_block_t)arg4;
- (id)runIPAToolWithInputPath:(id)arg1 outputPath:(id)arg2 arguments:(id)arg3 logAspect:(id)arg4 outError:(id *)arg5;
- (id)binSearchPathForIPATool;
@end
| 371 |
916 | package com.pancm.basics;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
*
* @Title: setTest
* @Description: 重写set中的equals和hashcode
* @Version:1.0.0
* @author panchengming
* @date 2017年9月17日
*/
public class SetTest {
public static void main(String[] args) {
Set hashSet = new HashSet();
Set treeSet = new TreeSet();
Set linkedSet = new LinkedHashSet();
set();
hashSetTest();
treeSet1();
treeSet2();
}
/**
* set去重
*/
public static void set(){
// 初始化list
List<String> list = new ArrayList<String>();
list.add("Jhon");
list.add("Jency");
list.add("Mike");
list.add("Dmitri");
list.add("Mike");
// 利用set不允许元素重复的性质去掉相同的元素
Set<String> set = new HashSet<String>();
for (int i = 0; i < list.size(); i++) {
String items = list.get(i);
System.out.println("items:"+items);
if (!set.add(items)) {
// 打印重复的元素
System.out.println("重复的数据: " + items);
}
}
System.out.println("list:"+list);
}
/**
* 使用hashSet去重
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void hashSetTest(){
HashSet hs = new HashSet();
// TreeMap tm=new TreeMap();
hs.add(new AA("ABC", 20));
hs.add(new AA("BCD", 20));
hs.add(new AA("CDE", 20));
hs.add(new AA("ABC", 20));
hs.add(new AA("BCD", 20));
Iterator it = hs.iterator(); //定义迭代器
while (it.hasNext()) {
Object next = it.next();
System.out.println("排序之前:"+next);
// Entry<String, Object> me=(Entry<String, Object>) it.next();
// tm.put(me.getKey(), me.getValue());
}
// System.out.println("TreeMap排序之后:"+tm);
}
/**
* 一,让容器自身具备比较性,自定义比较器。
需求:当元素自身不具备比较性,或者元素自身具备的比较性不是所需的。
那么这时只能让容器自身具备。
定义一个类实现Comparator 接口,覆盖compare方法。
并将该接口的子类对象作为参数传递给TreeSet集合的构造函数。
当Comparable比较方式,及Comparator比较方式同时存在,以Comparator
比较方式为主
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void treeSet1(){
TreeSet ts = new TreeSet(new MyComparator());
ts.add(new Book("think in java", 100));
ts.add(new Book("java 核心技术", 75));
ts.add(new Book("现代操作系统", 50));
ts.add(new Book("java就业教程", 35));
ts.add(new Book("think in java", 100));
ts.add(new Book("ccc in java", 100));
System.out.println("treeSet1:"+ts);
}
/**
*
二,让元素自身具备比较性。
也就是元素需要实现Comparable接口,覆盖compareTo 方法。
这种方式也作为元素的自然排序,也可称为默认排序。
年龄按照搜要条件,年龄相同再比姓名。
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void treeSet2(){
TreeSet ts = new TreeSet();
ts.add(new Person("aa", 20, "男"));
ts.add(new Person("bb", 18, "女"));
ts.add(new Person("cc", 17, "男"));
ts.add(new Person("dd", 17, "女"));
ts.add(new Person("dd", 15, "女"));
ts.add(new Person("dd", 15, "女"));
System.out.println("treeSet2:"+ts);
System.out.println(ts.size()); // 5
}
}
class AA{
private String name;
private int age;
public AA(String name, int age) {
this.name=name;
this.age=age;
}
AA() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重写hashCode
@Override
public int hashCode() {
System.out.println("hashCode:" + this.name);
return this.name.hashCode() + age * 37;
}
//重写equals
@Override
public boolean equals(Object obj) {
if (obj instanceof AA) {
AA a = (AA) obj;
return this.name.equals(a.name) && this.age == a.age;
} else {
return false;
}
}
@Override
public String toString() {
return "姓名:" + this.name + " 年龄:" + this.age;
}
}
@SuppressWarnings("rawtypes")
class Person implements Comparable {
private String name;
private int age;
private String gender; //性别
public Person() {
}
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public int hashCode() {
return name.hashCode() + age * 37;
}
public boolean equals(Object obj) {
System.err.println(this + "equals :" + obj);
if (!(obj instanceof Person)) {
return false;
}
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + ", gender=" + gender
+ "]";
}
@Override
public int compareTo(Object obj) {
Person p = (Person) obj;
System.out.println(this+" compareTo:"+p);
if (this.age > p.age) {
return 1;
}
if (this.age < p.age) {
return -1;
}
return this.name.compareTo(p.name);
}
}
@SuppressWarnings("rawtypes")
class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
Book b1 = (Book) o1;
Book b2 = (Book) o2;
System.out.println(b1+" comparator "+b2);
if (b1.getPrice() > b2.getPrice()) {
return 1;
}
if (b1.getPrice() < b2.getPrice()) {
return -1;
}
return b1.getName().compareTo(b2.getName());
}
}
class Book {
private String name;
private double price;
public Book() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Book(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Book [name=" + name + ", price=" + price + "]";
}
}
| 4,058 |
2,293 | /*----------------------------------------------------------------------------
* CMSIS-RTOS - RTX
*----------------------------------------------------------------------------
* Name: RT_TASK.H
* Purpose: Task functions and system start up.
* Rev.: V4.79
*----------------------------------------------------------------------------
*
* Copyright (c) 1999-2009 KEIL, 2009-2017 ARM Germany GmbH. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* 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.
*---------------------------------------------------------------------------*/
/* Definitions */
/* Values for 'state' */
#define INACTIVE 0U
#define READY 1U
#define RUNNING 2U
#define WAIT_DLY 3U
#define WAIT_ITV 4U
#define WAIT_OR 5U
#define WAIT_AND 6U
#define WAIT_SEM 7U
#define WAIT_MBX 8U
#define WAIT_MUT 9U
/* Return codes */
#define OS_R_TMO 0x01U
#define OS_R_EVT 0x02U
#define OS_R_SEM 0x03U
#define OS_R_MBX 0x04U
#define OS_R_MUT 0x05U
#define OS_R_OK 0x00U
#define OS_R_NOK 0xFFU
/* Variables */
extern struct OS_TSK os_tsk;
extern struct OS_TCB os_idle_TCB;
/* Functions */
extern void rt_switch_req (P_TCB p_next);
extern void rt_dispatch (P_TCB next_TCB);
extern void rt_block (U16 timeout, U8 block_state);
extern void rt_tsk_pass (void);
extern OS_TID rt_tsk_self (void);
extern OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio);
extern OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv);
extern OS_RESULT rt_tsk_delete (OS_TID task_id);
#ifdef __CMSIS_RTOS
extern void rt_sys_init (void);
extern void rt_sys_start (void);
#else
extern void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk);
#endif
/*----------------------------------------------------------------------------
* end of file
*---------------------------------------------------------------------------*/
| 957 |
1,473 | /*
* Autopsy
*
* Copyright 2020 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.discovery.search;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* Interface implemented by all types of results.
*/
public abstract class Result {
private SearchData.Frequency frequency = SearchData.Frequency.UNKNOWN;
private SearchData.PreviouslyNotable notabilityStatus = SearchData.PreviouslyNotable.NOT_PREVIOUSLY_NOTABLE;
private final List<String> tagNames = new ArrayList<>();
/**
* Get the Object ID for the data source the result is in.
*
* @return The Object ID of the data source the result is in.
*/
public abstract long getDataSourceObjectId();
/**
* Get the frequency of this result in the central repository.
*
* @return The Frequency enum.
*/
public SearchData.Frequency getFrequency() {
return frequency;
}
/**
* Get the known status of the result (known status being NSRL).
*
* @return The Known status of the result.
*/
public abstract TskData.FileKnown getKnown();
/**
* Mark the result as being previously notable in the CR.
*/
final public void markAsPreviouslyNotableInCR() {
this.notabilityStatus = SearchData.PreviouslyNotable.PREVIOUSLY_NOTABLE;
}
/**
* Get the previously notable value of this result.
*
* @return The previously notable status enum.
*/
final public SearchData.PreviouslyNotable getPreviouslyNotableInCR() {
return this.notabilityStatus;
}
/**
* Set the frequency of this result in the central repository.
*
* @param frequency The frequency of the result as an enum.
*/
final public void setFrequency(SearchData.Frequency frequency) {
this.frequency = frequency;
}
/**
* Get the data source associated with this result.
*
* @return The data source this result came from.
*
* @throws TskCoreException
*/
public abstract Content getDataSource() throws TskCoreException;
/**
* Get the type of this result.
*
* @return The type of items being searched for.
*/
public abstract SearchData.Type getType();
/**
* Add a tag name that matched this file.
*
* @param tagName
*/
public void addTagName(String tagName) {
if (!tagNames.contains(tagName)) {
tagNames.add(tagName);
}
// Sort the list so the getTagNames() will be consistent regardless of the order added
Collections.sort(tagNames);
}
/**
* Get the tag names for this file
*
* @return the tag names that matched this file.
*/
public List<String> getTagNames() {
return Collections.unmodifiableList(tagNames);
}
}
| 1,217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.