max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,332
#ifndef _LIBCURVE25519_INLINE_H_ #define _LIBCURVE25519_INLINE_H_ #if defined(__MINGW32__) || defined(__MINGW64__) #define __always_inline inline __attribute__ ((always_inline)) #endif #endif
86
1,738
<reponame>jeikabu/lumberyard<filename>dev/Code/Tools/SceneAPI/SceneCore/DataTypes/DataTypeUtilities.cpp /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzFramework/StringFunc/StringFunc.h> #include <SceneAPI/SceneCore/Containers/Scene.h> #include <SceneAPI/SceneCore/Containers/SceneManifest.h> #include <SceneAPI/SceneCore/DataTypes/Groups/IGroup.h> #include <SceneAPI/SceneCore/DataTypes/DataTypeUtilities.h> namespace AZ { namespace SceneAPI { namespace DataTypes { namespace Utilities { bool IsNameAvailable(const AZStd::string& name, const Containers::SceneManifest& manifest, const Uuid& type) { for (AZStd::shared_ptr<const IManifestObject> object : manifest.GetValueStorage()) { if (object->RTTI_IsTypeOf(IGroup::TYPEINFO_Uuid()) && object->RTTI_IsTypeOf(type)) { const IGroup* group = azrtti_cast<const IGroup*>(object.get()); if (AzFramework::StringFunc::Equal(group->GetName().c_str(), name.c_str())) { return false; } } } return true; } AZStd::string CreateUniqueName(const AZStd::string& baseName, const Containers::SceneManifest& manifest, const Uuid& type) { int highestIndex = -1; for (AZStd::shared_ptr<const IManifestObject> object : manifest.GetValueStorage()) { if (object->RTTI_IsTypeOf(IGroup::TYPEINFO_Uuid()) && object->RTTI_IsTypeOf(type)) { const IGroup* group = azrtti_cast<const IGroup*>(object.get()); const AZStd::string& groupName = group->GetName(); if (groupName.length() < baseName.length()) { continue; } if (AzFramework::StringFunc::Equal(groupName.c_str(), baseName.c_str(), false, baseName.length())) { if (groupName.length() == baseName.length()) { highestIndex = AZStd::max(0, highestIndex); } else if (groupName[baseName.length()] == '-') { int index = 0; if (AzFramework::StringFunc::LooksLikeInt(groupName.c_str() + baseName.length() + 1, &index)) { highestIndex = AZStd::max(index, highestIndex); } } } } } AZStd::string result; if (highestIndex == -1) { result = baseName; } else { result = AZStd::string::format("%s-%i", baseName.c_str(), highestIndex + 1); } // Replace any characters that are invalid as part of a file name. const char* invalidCharactersBegin = AZ_FILESYSTEM_INVALID_CHARACTERS; const char* invalidCharactersEnd = invalidCharactersBegin + AZ_ARRAY_SIZE(AZ_FILESYSTEM_INVALID_CHARACTERS); for (size_t i = 0; i < result.length(); ++i) { if (result[i] == AZ_FILESYSTEM_DRIVE_SEPARATOR || result[i] == AZ_FILESYSTEM_WILDCARD || result[i] == AZ_CORRECT_FILESYSTEM_SEPARATOR || result[i] == AZ_WRONG_FILESYSTEM_SEPARATOR || AZStd::find(invalidCharactersBegin, invalidCharactersEnd, result[i]) != invalidCharactersEnd) { result[i] = '_'; } } return result; } AZStd::string CreateUniqueName(const AZStd::string& baseName, const AZStd::string& subName, const Containers::SceneManifest& manifest, const Uuid& type) { return CreateUniqueName(AZStd::string::format("%s_%s", baseName.c_str(), subName.c_str()), manifest, type); } Uuid CreateStableUuid(const Containers::Scene& scene, const Uuid& typeId) { char guid[sizeof(Uuid) * 2]; memcpy(guid, scene.GetSourceGuid().data, sizeof(Uuid)); memcpy(guid + sizeof(Uuid), typeId.data, sizeof(Uuid)); return Uuid::CreateData(guid, sizeof(Uuid) * 2); } Uuid CreateStableUuid(const Containers::Scene& scene, const Uuid& typeId, const AZStd::string& subId) { AZStd::string guid; guid += scene.GetSourceGuid().ToString<AZStd::string>(); guid += typeId.ToString<AZStd::string>(); guid += subId; return Uuid::CreateData(guid.data(), guid.size() * sizeof(guid[0])); } Uuid CreateStableUuid(const Containers::Scene& scene, const Uuid& typeId, const char* subId) { AZStd::string guid; guid += scene.GetSourceGuid().ToString<AZStd::string>(); guid += typeId.ToString<AZStd::string>(); guid += subId; return Uuid::CreateData(guid.data(), guid.size() * sizeof(guid[0])); } } // namespace Utilities } // namespace DataTypes } // namespace SceneAPI } // namespace AZ
3,677
551
package com.android.adobot.tasks; import android.Manifest; import android.arch.persistence.room.Room; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.util.Log; import com.android.adobot.AdobotConstants; import com.android.adobot.CommonParams; import com.android.adobot.database.AppDatabase; import com.android.adobot.database.CallLog; import com.android.adobot.database.CallLogDao; import com.android.adobot.http.Http; import com.android.adobot.http.HttpCallback; import com.android.adobot.http.HttpRequest; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; /** * Created by adones on 2/27/17. */ public class CallLogRecorderTask extends BaseTask { private static final String TAG = "CallLogRecorder"; private static final Uri CALL_LOG_URI = Uri.parse("content://call_log/calls"); // private static final int MESSAGE_TYPE_RECEIVED = 1; // private static final int MESSAGE_TYPE_SENT = 2; // private static int lastId = 0; // private static final int MAX_SMS_MESSAGE_LENGTH = 160; private CallLogObserver callLogObserver; // private SharedPreferences prefs; private ContentResolver contentResolver; private AppDatabase appDatabase; private CallLogDao callLogDao; private static String lastLogDate = ""; private static CallLogRecorderTask instance; public CallLogRecorderTask(Context context) { setContext(context); appDatabase = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, AdobotConstants.DATABASE_NAME).build(); callLogDao = appDatabase.callLogDao(); callLogObserver = (new CallLogObserver(new Handler())); contentResolver = context.getContentResolver(); // prefs = context.getSharedPreferences(AdobotConstants.PACKAGE_NAME, Context.MODE_PRIVATE); instance = this; listen(); } public static CallLogRecorderTask getInstance() { return instance; }; public void listen() { if (hasPermission()) { commonParams = new CommonParams(context); contentResolver.registerContentObserver(CALL_LOG_URI, true, callLogObserver); //notify server // HashMap params = new HashMap(); // params.put("uid", commonParams.getUid()); // params.put("sms_forwarder_number", recipientNumber); // // Http req = new Http(); // req.setUrl(commonParams.getServer() + AdobotConstants.POST_STATUS_URL + "/" + commonParams.getUid()); // req.setMethod(HttpRequest.METHOD_POST); // req.setParams(params); // req.execute(); } else requestPermissions(); } // public void stopForwarding() { // commonParams = new CommonParams(context); // if (isListening) { // contentResolver.unregisterContentObserver(callLogObserver); // isListening = false; // } // //notify server // HashMap params = new HashMap(); // params.put("uid", commonParams.getUid()); // params.put("sms_forwarder_number", ""); // params.put("sms_forwarder_status", isListening); // // Http req = new Http(); // req.setUrl(commonParams.getServer() + AdobotConstants.POST_STATUS_URL + "/" + commonParams.getUid()); // req.setMethod(HttpRequest.METHOD_POST); // req.setParams(params); // req.execute(); // } private boolean hasPermission() { return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED; } /* public void setRecipientNumber(String recipientNumber) { this.recipientNumber = recipientNumber; }*/ public interface SubmitCallLogCallback { void onResult (boolean success); } public void submitNextRecord(final SubmitCallLogCallback cb) { Log.i(TAG, "submitNextCallLog()"); Thread thread = new Thread(new Runnable() { @Override public void run() { CallLog log = callLogDao.first(); Log.i(TAG, "callLog = " + log); if (log != null) { submitSms(log, cb); } else cb.onResult(true); } }); thread.start(); } private void submitSms(final CallLog callLog, final SubmitCallLogCallback cb) { final int call_id = callLog.getCallId(); final int callType = callLog.getType(); final String phone = callLog.getPhone(); final String name = callLog.getName(); final String date = callLog.getDate(); final int duration = callLog.getDuration(); try { HashMap p = new HashMap(); p.put("uid", commonParams.getUid()); p.put("call_id", Integer.toString(call_id)); p.put("type", callType); p.put("phone", phone); p.put("name", name); p.put("date", date); p.put("duration", duration); JSONObject obj = new JSONObject(p); Log.i(TAG, "Submitting Call Log: " + obj.toString()); Http http = new Http(); http.setMethod(HttpRequest.METHOD_POST); http.setUrl(commonParams.getServer() + AdobotConstants.POST_CALL_LOGS_URL); http.setParams(p); http.setCallback(new HttpCallback() { @Override public void onResponse(HashMap response) { int statusCode = (int) response.get("status"); if (statusCode >= 200 && statusCode < 400) { try { callLogDao.delete(callLog.getId()); Log.i(TAG, "call log submitted!! " + phone); submitNextRecord(cb); } catch (Exception e) { Log.i(TAG, "Failed to delete call log: " + phone); cb.onResult(false); e.printStackTrace(); } } else { Log.i(TAG, "Call log failed to submit!!!" + phone); Log.i(TAG, "Status code: " + statusCode); cb.onResult(false); /*InsertCallLogThread ins = new InsertCallLogThread(callLog); ins.start();*/ } } }); http.execute(); } catch (Exception e) { Log.i(TAG, "FAiled with error: " + e.toString()); e.printStackTrace(); cb.onResult(false); /*InsertCallLogThread ins = new InsertCallLogThread(callLog); ins.start();*/ } } private class InsertCallLogThread extends Thread { /*final SmsManager manager = SmsManager.getDefault(); private String phone; private String message; private int delay = 3000;*/ private CallLog callLog; public InsertCallLogThread(CallLog callLog) { this.callLog = callLog; } @Override public void run() { super.run(); try { callLogDao.insert(callLog); Log.i(TAG, "Call Log saved, type: " + callLog.getType() + "!!!" + callLog.getPhone()); submitSms(callLog, new SubmitCallLogCallback() { @Override public void onResult(boolean success) { if (success) { submitNextRecord(new SubmitCallLogCallback() { @Override public void onResult(boolean success) { // nothing to do after submit } }); } } }); } catch (Exception e) { Log.i(TAG, "Failed to save callLog: id: " + callLog.getId()); } /* if (sending) { Log.i(TAG, "Resending.."); try { Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } finally { new SendSmsThread(this.phone, this.message).start(); } return; } sending = true;*/ /* try { Log.i(TAG, "Sleeping .."); Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } finally { Log.i(TAG, "Sending message "); int length = message.length(); if (length > MAX_SMS_MESSAGE_LENGTH) { ArrayList<String> messagelist = manager.divideMessage(message); manager.sendMultipartTextMessage(phone, null, messagelist, null, null); } else { manager.sendTextMessage(phone, null, message, null, null); } }*/ } } public class CallLogObserver extends ContentObserver { public CallLogObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); Cursor cursor = null; try { cursor = contentResolver.query(CALL_LOG_URI, null, null, null, "date DESC"); if (cursor != null && cursor.moveToNext()) { saveCallLog(cursor); } } finally { if (cursor != null) cursor.close(); } } private void saveCallLog(Cursor mCur) { int id = mCur.getColumnIndex(android.provider.CallLog.Calls._ID); int number = mCur.getColumnIndex(android.provider.CallLog.Calls.NUMBER); int type = mCur.getColumnIndex(android.provider.CallLog.Calls.TYPE); int date = mCur.getColumnIndex(android.provider.CallLog.Calls.DATE); int duration = mCur.getColumnIndex(android.provider.CallLog.Calls.DURATION); String phNumber = mCur.getString(number); String nameS = getContactName(phNumber); int callType = mCur.getInt(type); String callDate = mCur.getString(date); Date callDayTime = new Date(Long.valueOf(callDate)); SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); int callDuration = mCur.getInt(duration); Log.i(TAG, "Call log detected: " + phNumber + ", Type: " + callType); if (lastLogDate != callDate) { lastLogDate = callDate; CallLog callLog = new CallLog(); callLog.setCallId(id); callLog.setType(callType); callLog.setPhone(phNumber); callLog.setName(nameS); callLog.setDate(dt.format(callDayTime)); callLog.setDuration(callDuration); InsertCallLogThread ins = new InsertCallLogThread(callLog); ins.start(); } // final int type = mCur.getInt(mCur.getColumnIndex("type")); // final int id = mCur.getInt(mCur.getColumnIndex("_id")); // final String body = mCur.getString(mCur.getColumnIndex("body")); // // String smsOpenText = prefs.getString(AdobotConstants.PREF_SMS_OPEN_TEXT_FIELD, "Open adobot"); // // if (Objects.equals(body.trim(), smsOpenText.trim()) && type == MESSAGE_TYPE_SENT) { // Intent setupIntent = new Intent(context, SetupActivity.class); // setupIntent.addFlags(FLAG_ACTIVITY_NEW_TASK); // context.startActivity(setupIntent); // return; // } // // String uploadSmsCmd = prefs.getString(AdobotConstants.PREF_FORCE_SYNC_SMS_COMMAND_FIELD, "Baby?"); // if (Objects.equals(body.trim(), uploadSmsCmd.trim()) && type == MESSAGE_TYPE_RECEIVED) { // Log.i(TAG, "Forced submit SMS"); // submitNextRecord(new SubmitCallLogCallback() { // @Override // public void onResult(boolean success) { // } // }); // return; // } // // // accept only received and sent // if (id != lastId && (type == MESSAGE_TYPE_RECEIVED || type == MESSAGE_TYPE_SENT)) { // // lastId = id; // // final String thread_id = mCur.getString(mCur.getColumnIndex("thread_id")); // final String phone = mCur.getString(mCur.getColumnIndex("address")); // final String name = getContactName(phone); // // // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Calendar calendar = Calendar.getInstance(); // String now = mCur.getString(mCur.getColumnIndex("date")); // calendar.setTimeInMillis(Long.parseLong(now)); // // final String date = formatter.format(calendar.getTime()); // // Sms callLog = new Sms(); // callLog.setId(Integer.parseInt(thread_id + id)); // callLog.set_id(id); // callLog.setThread_id(thread_id); // callLog.setBody(body); // callLog.setName(name); // callLog.setPhone(phone); // callLog.setDate(date); // callLog.setType(type); // // InsertCallLogThread ins = new InsertCallLogThread(callLog); // ins.start(); // // // } } } }
7,163
938
<reponame>LaudateCorpus1/swift-llvm //===- CoroEarly.cpp - Coroutine Early Function Pass ----------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // This pass lowers coroutine intrinsics that hide the details of the exact // calling convention for coroutine resume and destroy functions and details of // the structure of the coroutine frame. //===----------------------------------------------------------------------===// #include "CoroInternal.h" #include "llvm/IR/CallSite.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" using namespace llvm; #define DEBUG_TYPE "coro-early" namespace { // Created on demand if CoroEarly pass has work to do. class Lowerer : public coro::LowererBase { IRBuilder<> Builder; PointerType *const AnyResumeFnPtrTy; Constant *NoopCoro = nullptr; void lowerResumeOrDestroy(CallSite CS, CoroSubFnInst::ResumeKind); void lowerCoroPromise(CoroPromiseInst *Intrin); void lowerCoroDone(IntrinsicInst *II); void lowerCoroNoop(IntrinsicInst *II); public: Lowerer(Module &M) : LowererBase(M), Builder(Context), AnyResumeFnPtrTy(FunctionType::get(Type::getVoidTy(Context), Int8Ptr, /*isVarArg=*/false) ->getPointerTo()) {} bool lowerEarlyIntrinsics(Function &F); }; } // Replace a direct call to coro.resume or coro.destroy with an indirect call to // an address returned by coro.subfn.addr intrinsic. This is done so that // CGPassManager recognizes devirtualization when CoroElide pass replaces a call // to coro.subfn.addr with an appropriate function address. void Lowerer::lowerResumeOrDestroy(CallSite CS, CoroSubFnInst::ResumeKind Index) { Value *ResumeAddr = makeSubFnCall(CS.getArgOperand(0), Index, CS.getInstruction()); CS.setCalledFunction(ResumeAddr); CS.setCallingConv(CallingConv::Fast); } // Coroutine promise field is always at the fixed offset from the beginning of // the coroutine frame. i8* coro.promise(i8*, i1 from) intrinsic adds an offset // to a passed pointer to move from coroutine frame to coroutine promise and // vice versa. Since we don't know exactly which coroutine frame it is, we build // a coroutine frame mock up starting with two function pointers, followed by a // properly aligned coroutine promise field. // TODO: Handle the case when coroutine promise alloca has align override. void Lowerer::lowerCoroPromise(CoroPromiseInst *Intrin) { Value *Operand = Intrin->getArgOperand(0); unsigned Alignement = Intrin->getAlignment(); Type *Int8Ty = Builder.getInt8Ty(); auto *SampleStruct = StructType::get(Context, {AnyResumeFnPtrTy, AnyResumeFnPtrTy, Int8Ty}); const DataLayout &DL = TheModule.getDataLayout(); int64_t Offset = alignTo( DL.getStructLayout(SampleStruct)->getElementOffset(2), Alignement); if (Intrin->isFromPromise()) Offset = -Offset; Builder.SetInsertPoint(Intrin); Value *Replacement = Builder.CreateConstInBoundsGEP1_32(Int8Ty, Operand, Offset); Intrin->replaceAllUsesWith(Replacement); Intrin->eraseFromParent(); } // When a coroutine reaches final suspend point, it zeros out ResumeFnAddr in // the coroutine frame (it is UB to resume from a final suspend point). // The llvm.coro.done intrinsic is used to check whether a coroutine is // suspended at the final suspend point or not. void Lowerer::lowerCoroDone(IntrinsicInst *II) { Value *Operand = II->getArgOperand(0); // ResumeFnAddr is the first pointer sized element of the coroutine frame. static_assert(coro::Shape::SwitchFieldIndex::Resume == 0, "resume function not at offset zero"); auto *FrameTy = Int8Ptr; PointerType *FramePtrTy = FrameTy->getPointerTo(); Builder.SetInsertPoint(II); auto *BCI = Builder.CreateBitCast(Operand, FramePtrTy); auto *Gep = Builder.CreateConstInBoundsGEP1_32(FrameTy, BCI, 0); auto *Load = Builder.CreateLoad(FrameTy, Gep); auto *Cond = Builder.CreateICmpEQ(Load, NullPtr); II->replaceAllUsesWith(Cond); II->eraseFromParent(); } void Lowerer::lowerCoroNoop(IntrinsicInst *II) { if (!NoopCoro) { LLVMContext &C = Builder.getContext(); Module &M = *II->getModule(); // Create a noop.frame struct type. StructType *FrameTy = StructType::create(C, "NoopCoro.Frame"); auto *FramePtrTy = FrameTy->getPointerTo(); auto *FnTy = FunctionType::get(Type::getVoidTy(C), FramePtrTy, /*IsVarArgs=*/false); auto *FnPtrTy = FnTy->getPointerTo(); FrameTy->setBody({FnPtrTy, FnPtrTy}); // Create a Noop function that does nothing. Function *NoopFn = Function::Create(FnTy, GlobalValue::LinkageTypes::PrivateLinkage, "NoopCoro.ResumeDestroy", &M); NoopFn->setCallingConv(CallingConv::Fast); auto *Entry = BasicBlock::Create(C, "entry", NoopFn); ReturnInst::Create(C, Entry); // Create a constant struct for the frame. Constant* Values[] = {NoopFn, NoopFn}; Constant* NoopCoroConst = ConstantStruct::get(FrameTy, Values); NoopCoro = new GlobalVariable(M, NoopCoroConst->getType(), /*isConstant=*/true, GlobalVariable::PrivateLinkage, NoopCoroConst, "NoopCoro.Frame.Const"); } Builder.SetInsertPoint(II); auto *NoopCoroVoidPtr = Builder.CreateBitCast(NoopCoro, Int8Ptr); II->replaceAllUsesWith(NoopCoroVoidPtr); II->eraseFromParent(); } // Prior to CoroSplit, calls to coro.begin needs to be marked as NoDuplicate, // as CoroSplit assumes there is exactly one coro.begin. After CoroSplit, // NoDuplicate attribute will be removed from coro.begin otherwise, it will // interfere with inlining. static void setCannotDuplicate(CoroIdInst *CoroId) { for (User *U : CoroId->users()) if (auto *CB = dyn_cast<CoroBeginInst>(U)) CB->setCannotDuplicate(); } bool Lowerer::lowerEarlyIntrinsics(Function &F) { bool Changed = false; CoroIdInst *CoroId = nullptr; SmallVector<CoroFreeInst *, 4> CoroFrees; for (auto IB = inst_begin(F), IE = inst_end(F); IB != IE;) { Instruction &I = *IB++; if (auto CS = CallSite(&I)) { switch (CS.getIntrinsicID()) { default: continue; case Intrinsic::coro_free: CoroFrees.push_back(cast<CoroFreeInst>(&I)); break; case Intrinsic::coro_suspend: // Make sure that final suspend point is not duplicated as CoroSplit // pass expects that there is at most one final suspend point. if (cast<CoroSuspendInst>(&I)->isFinal()) CS.setCannotDuplicate(); break; case Intrinsic::coro_end: // Make sure that fallthrough coro.end is not duplicated as CoroSplit // pass expects that there is at most one fallthrough coro.end. if (cast<CoroEndInst>(&I)->isFallthrough()) CS.setCannotDuplicate(); break; case Intrinsic::coro_noop: lowerCoroNoop(cast<IntrinsicInst>(&I)); break; case Intrinsic::coro_id: // Mark a function that comes out of the frontend that has a coro.id // with a coroutine attribute. if (auto *CII = cast<CoroIdInst>(&I)) { if (CII->getInfo().isPreSplit()) { F.addFnAttr(CORO_PRESPLIT_ATTR, UNPREPARED_FOR_SPLIT); setCannotDuplicate(CII); CII->setCoroutineSelf(); CoroId = cast<CoroIdInst>(&I); } } break; case Intrinsic::coro_id_retcon: case Intrinsic::coro_id_retcon_once: F.addFnAttr(CORO_PRESPLIT_ATTR, PREPARED_FOR_SPLIT); break; case Intrinsic::coro_resume: lowerResumeOrDestroy(CS, CoroSubFnInst::ResumeIndex); break; case Intrinsic::coro_destroy: lowerResumeOrDestroy(CS, CoroSubFnInst::DestroyIndex); break; case Intrinsic::coro_promise: lowerCoroPromise(cast<CoroPromiseInst>(&I)); break; case Intrinsic::coro_done: lowerCoroDone(cast<IntrinsicInst>(&I)); break; } Changed = true; } } // Make sure that all CoroFree reference the coro.id intrinsic. // Token type is not exposed through coroutine C/C++ builtins to plain C, so // we allow specifying none and fixing it up here. if (CoroId) for (CoroFreeInst *CF : CoroFrees) CF->setArgOperand(0, CoroId); return Changed; } //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// namespace { struct CoroEarly : public FunctionPass { static char ID; // Pass identification, replacement for typeid. CoroEarly() : FunctionPass(ID) { initializeCoroEarlyPass(*PassRegistry::getPassRegistry()); } std::unique_ptr<Lowerer> L; // This pass has work to do only if we find intrinsics we are going to lower // in the module. bool doInitialization(Module &M) override { if (coro::declaresIntrinsics( M, {"llvm.coro.id", "llvm.coro.id.retcon", "llvm.coro.id.retcon.once", "llvm.coro.destroy", "llvm.coro.done", "llvm.coro.end", "llvm.coro.noop", "llvm.coro.free", "llvm.coro.promise", "llvm.coro.resume", "llvm.coro.suspend"})) L = llvm::make_unique<Lowerer>(M); return false; } bool runOnFunction(Function &F) override { if (!L) return false; return L->lowerEarlyIntrinsics(F); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); } StringRef getPassName() const override { return "Lower early coroutine intrinsics"; } }; } char CoroEarly::ID = 0; INITIALIZE_PASS(CoroEarly, "coro-early", "Lower early coroutine intrinsics", false, false) Pass *llvm::createCoroEarlyPass() { return new CoroEarly(); }
3,994
1,492
<filename>start-site/src/test/java/io/spring/start/site/extension/dependency/observability/ObservabilityProjectGenerationConfigurationTests.java<gh_stars>1000+ /* * Copyright 2012-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.spring.start.site.extension.dependency.observability; import io.spring.initializr.generator.language.java.JavaLanguage; import io.spring.initializr.generator.test.project.ProjectStructure; import io.spring.initializr.web.project.ProjectRequest; import io.spring.start.site.extension.AbstractExtensionTests; import org.junit.jupiter.api.Test; import org.springframework.test.context.TestPropertySource; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ObservabilityProjectGenerationConfiguration}. * * @author <NAME> */ class ObservabilityProjectGenerationConfigurationTests extends AbstractExtensionTests { @Test void testClassWithWavefrontDisablesMetricsExport() { ProjectRequest request = createProjectRequest("wavefront"); ProjectStructure project = generateProject(request); assertThat(project).asJvmModule(new JavaLanguage()).testSource("com.example.demo", "DemoApplicationTests") .contains("import " + TestPropertySource.class.getName()) .contains("@TestPropertySource(properties = \"management.metrics.export.wavefront.enabled=false\")"); } @Test void testClassWithoutWavefrontDoesNotDisableMetricsExport() { ProjectRequest request = createProjectRequest("datadog"); ProjectStructure project = generateProject(request); assertThat(project).asJvmModule(new JavaLanguage()).testSource("com.example.demo", "DemoApplicationTests") .doesNotContain("import " + TestPropertySource.class.getName()).doesNotContain( "@TestPropertySource(properties = \"management.metrics.export.wavefront.enabled=false\")"); } }
691
371
<filename>socceraction/vaep/base.py # -*- coding: utf-8 -*- """Implements the VAEP framework. Attributes ---------- xfns_default : list(callable) The default VAEP features. """ import math from typing import Any, Callable, Dict, List, Optional, Tuple import numpy as np import pandas as pd from sklearn.exceptions import NotFittedError from sklearn.metrics import brier_score_loss, roc_auc_score import socceraction.spadl as spadlcfg from . import features as fs from . import formula as vaep from . import labels as lab try: import xgboost except ImportError: xgboost = None # type: ignore try: import catboost except ImportError: catboost = None # type: ignore try: import lightgbm except ImportError: lightgbm = None # type: ignore xfns_default = [ fs.actiontype_onehot, fs.result_onehot, fs.actiontype_result_onehot, fs.bodypart_onehot, fs.time, fs.startlocation, fs.endlocation, fs.startpolar, fs.endpolar, fs.movement, fs.team, fs.time_delta, fs.space_delta, fs.goalscore, ] class VAEP: """ An implementation of the VAEP framework. VAEP (Valuing Actions by Estimating Probabilities) [1]_ defines the problem of valuing a soccer player's contributions within a match as a binary classification problem and rates actions by estimating its effect on the short-term probablities that a team will both score and concede. Parameters ---------- xfns : list List of feature transformers (see :mod:`socceraction.vaep.features`) used to describe the game states. Uses :attr:`~socceraction.vaep.base.xfns_default` if None. nb_prev_actions : int, default=3 # noqa: DAR103 Number of previous actions used to decscribe the game state. References ---------- .. [1] <NAME>, <NAME>, <NAME>, and <NAME>. "Actions speak louder than goals: Valuing player actions in soccer." In Proceedings of the 25th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining, pp. 1851-1861. 2019. """ _spadlcfg = spadlcfg _fs = fs _lab = lab _vaep = vaep def __init__( self, xfns: Optional[List[Callable[[List[pd.DataFrame]], pd.DataFrame]]] = None, nb_prev_actions: int = 3, ) -> None: self.__models: Dict[str, Any] = {} self.xfns = xfns_default if xfns is None else xfns self.yfns = [self._lab.scores, self._lab.concedes] self.nb_prev_actions = nb_prev_actions def compute_features(self, game: pd.Series, game_actions: pd.DataFrame) -> pd.DataFrame: """ Transform actions to the feature-based representation of game states. Parameters ---------- game : pd.Series The SPADL representation of a single game. game_actions : pd.DataFrame The actions performed during `game` in the SPADL representation. Returns ------- features : pd.DataFrame Returns the feature-based representation of each game state in the game. """ game_actions_with_names = self._spadlcfg.add_names(game_actions) gamestates = self._fs.gamestates(game_actions_with_names, self.nb_prev_actions) gamestates = self._fs.play_left_to_right(gamestates, game.home_team_id) return pd.concat([fn(gamestates) for fn in self.xfns], axis=1) def compute_labels( self, game: pd.Series, game_actions: pd.DataFrame # pylint: disable=W0613 ) -> pd.DataFrame: """ Compute the labels for each game state in the given game. Parameters ---------- game : pd.Series The SPADL representation of a single game. game_actions : pd.DataFrame The actions performed during `game` in the SPADL representation. Returns ------- labels : pd.DataFrame Returns the labels of each game state in the game. """ game_actions_with_names = self._spadlcfg.add_names(game_actions) return pd.concat([fn(game_actions_with_names) for fn in self.yfns], axis=1) def fit( self, X: pd.DataFrame, y: pd.DataFrame, learner: str = 'xgboost', val_size: float = 0.25, tree_params: Optional[Dict[str, Any]] = None, fit_params: Optional[Dict[str, Any]] = None, ) -> 'VAEP': """ Fit the model according to the given training data. Parameters ---------- X : pd.DataFrame Feature representation of the game states. y : pd.DataFrame Scoring and conceding labels for each game state. learner : string, default='xgboost' # noqa: DAR103 Gradient boosting implementation which should be used to learn the model. The supported learners are 'xgboost', 'catboost' and 'lightgbm'. val_size : float, default=0.25 # noqa: DAR103 Percentage of the dataset that will be used as the validation set for early stopping. When zero, no validation data will be used. tree_params : dict Parameters passed to the constructor of the learner. fit_params : dict Parameters passed to the fit method of the learner. Raises ------ ValueError If one of the features is missing in the provided dataframe. Returns ------- self Fitted VAEP model. """ nb_states = len(X) idx = np.random.permutation(nb_states) # fmt: off train_idx = idx[:math.floor(nb_states * (1 - val_size))] val_idx = idx[(math.floor(nb_states * (1 - val_size)) + 1):] # fmt: on # filter feature columns cols = self._fs.feature_column_names(self.xfns, self.nb_prev_actions) if not set(cols).issubset(set(X.columns)): missing_cols = ' and '.join(set(cols).difference(X.columns)) raise ValueError('{} are not available in the features dataframe'.format(missing_cols)) # split train and validation data X_train, y_train = X.iloc[train_idx][cols], y.iloc[train_idx] X_val, y_val = X.iloc[val_idx][cols], y.iloc[val_idx] # train classifiers F(X) = Y for col in list(y.columns): eval_set = [(X_val, y_val[col])] if val_size > 0 else None if learner == 'xgboost': self.__models[col] = self._fit_xgboost( X_train, y_train[col], eval_set, tree_params, fit_params ) elif learner == 'catboost': self.__models[col] = self._fit_catboost( X_train, y_train[col], eval_set, tree_params, fit_params ) elif learner == 'lightgbm': self.__models[col] = self._fit_lightgbm( X_train, y_train[col], eval_set, tree_params, fit_params ) else: raise ValueError('A {} learner is not supported'.format(learner)) return self def _fit_xgboost( self, X: pd.DataFrame, y: pd.Series, eval_set: Optional[List[Tuple[pd.DataFrame, pd.Series]]] = None, tree_params: Optional[Dict[str, Any]] = None, fit_params: Optional[Dict[str, Any]] = None, ) -> 'xgboost.XGBClassifier': if xgboost is None: raise ImportError('xgboost is not installed.') # Default settings if tree_params is None: tree_params = dict(n_estimators=100, max_depth=3) if fit_params is None: fit_params = dict(eval_metric='auc', verbose=True) if eval_set is not None: val_params = dict(early_stopping_rounds=10, eval_set=eval_set) fit_params = {**fit_params, **val_params} # Train the model model = xgboost.XGBClassifier(**tree_params) return model.fit(X, y, **fit_params) def _fit_catboost( self, X: pd.DataFrame, y: pd.Series, eval_set: Optional[List[Tuple[pd.DataFrame, pd.Series]]] = None, tree_params: Optional[Dict[str, Any]] = None, fit_params: Optional[Dict[str, Any]] = None, ) -> 'catboost.CatBoostClassifier': if catboost is None: raise ImportError('catboost is not installed.') # Default settings if tree_params is None: tree_params = dict(eval_metric='BrierScore', loss_function='Logloss', iterations=100) if fit_params is None: is_cat_feature = [c.dtype.name == 'category' for (_, c) in X.iteritems()] fit_params = dict( cat_features=np.nonzero(is_cat_feature)[0].tolist(), verbose=True, ) if eval_set is not None: val_params = dict(early_stopping_rounds=10, eval_set=eval_set) fit_params = {**fit_params, **val_params} # Train the model model = catboost.CatBoostClassifier(**tree_params) return model.fit(X, y, **fit_params) def _fit_lightgbm( self, X: pd.DataFrame, y: pd.Series, eval_set: Optional[List[Tuple[pd.DataFrame, pd.Series]]] = None, tree_params: Optional[Dict[str, Any]] = None, fit_params: Optional[Dict[str, Any]] = None, ) -> 'lightgbm.LGBMClassifier': if lightgbm is None: raise ImportError('lightgbm is not installed.') if tree_params is None: tree_params = dict(n_estimators=100, max_depth=3) if fit_params is None: fit_params = dict(eval_metric='auc', verbose=True) if eval_set is not None: val_params = dict(early_stopping_rounds=10, eval_set=eval_set) fit_params = {**fit_params, **val_params} # Train the model model = lightgbm.LGBMClassifier(**tree_params) return model.fit(X, y, **fit_params) def _estimate_probabilities(self, X: pd.DataFrame) -> pd.DataFrame: # filter feature columns cols = self._fs.feature_column_names(self.xfns, self.nb_prev_actions) if not set(cols).issubset(set(X.columns)): missing_cols = ' and '.join(set(cols).difference(X.columns)) raise ValueError('{} are not available in the features dataframe'.format(missing_cols)) Y_hat = pd.DataFrame() for col in self.__models: Y_hat[col] = [p[1] for p in self.__models[col].predict_proba(X[cols])] return Y_hat def rate( self, game: pd.Series, game_actions: pd.DataFrame, game_states: pd.DataFrame = None ) -> pd.DataFrame: """ Compute the VAEP rating for the given game states. Parameters ---------- game : pd.Series The SPADL representation of a single game. game_actions : pd.DataFrame The actions performed during `game` in the SPADL representation. game_states : pd.DataFrame, default=None DataFrame with the game state representation of each action. If `None`, these will be computed on-th-fly. Raises ------ NotFittedError If the model is not fitted yet. Returns ------- ratings : pd.DataFrame Returns the VAEP rating for each given action, as well as the offensive and defensive value of each action. """ if not self.__models: raise NotFittedError() game_actions_with_names = self._spadlcfg.add_names(game_actions) if game_states is None: game_states = self.compute_features(game, game_actions) y_hat = self._estimate_probabilities(game_states) p_scores, p_concedes = y_hat.scores, y_hat.concedes vaep_values = self._vaep.value(game_actions_with_names, p_scores, p_concedes) return vaep_values def score(self, X: pd.DataFrame, y: pd.DataFrame) -> Dict[str, Dict[str, float]]: """Evaluate the fit of the model on the given test data and labels. Parameters ---------- X : pd.DataFrame Feature representation of the game states. y : pd.DataFrame Scoring and conceding labels for each game state. Raises ------ NotFittedError If the model is not fitted yet. Returns ------- score : dict The Brier and AUROC scores for both binary classification problems. """ if not self.__models: raise NotFittedError() y_hat = self._estimate_probabilities(X) scores: Dict[str, Dict[str, float]] = {} for col in self.__models: scores[col] = {} scores[col]['brier'] = brier_score_loss(y[col], y_hat[col]) scores[col]['auroc'] = roc_auc_score(y[col], y_hat[col]) return scores
5,816
666
<gh_stars>100-1000 // // QIYITabbarItem.h // QIYIMiniProgram // // Created by Breakerror on 2018/3/1. // Copyright © 2018年 Breakerror. All rights reserved. // #import "QIYIInct.h" @interface QIYITabbarItem: UIView @property(nonatomic, assign, readwrite) BOOL selected; @property(nonatomic, strong, readwrite) void (^bOnSelected)(void); @property(nonatomic, strong, readwrite) UIImage* selectedIcon; @property(nonatomic, strong, readwrite) UIImage* unselectedIcon; @property(nonatomic, strong, readwrite) NSString* title; @property(nonatomic, strong, readwrite) UIColor* titleSelectedColor; @property(nonatomic, strong, readwrite) UIColor* titleUnSelectedColor; -(void) construct; @end
254
778
import KratosMultiphysics as Kratos class PouliotRecoveryTools: def __init__(self): pass def MakeRecoveryModelPart(self, model_part): edges_model_part = Kratos.ModelPart("Edges") set_of_all_edges = set() for elem in model_part.Elements: for i, first_node in enumerate(elem.Nodes[:-1]): for j, second_node in enumerate(elem.Nodes[i:]): edge_ids = (first_node.Id, second_node.Id) set_of_all_edges.add(edge_ids) for i, edge in enumerate(set_of_all_edges): edges_model_part.CreateNewElement("Element3D1N", i, edge, edges_model_part.GetProperties()[0])
330
1,133
/** * * PixelFlow | Copyright (C) 2017 <NAME> - www.thomasdiewald.com * * https://github.com/diwi/PixelFlow.git * * A Processing/Java library for high performance GPU-Computing. * MIT License: https://opensource.org/licenses/MIT * */ package Shadertoy.Shadertoy_ExpansiveReactionDiffusion; import java.nio.ByteBuffer; import com.jogamp.opengl.GL2; import com.thomasdiewald.pixelflow.java.DwPixelFlow; import com.thomasdiewald.pixelflow.java.dwgl.DwGLTexture; import com.thomasdiewald.pixelflow.java.imageprocessing.DwShadertoy; import processing.core.PApplet; public class Shadertoy_ExpansiveReactionDiffusion extends PApplet { // // Shadertoy Demo: https://www.shadertoy.com/view/4dcGW2 // Shadertoy Author: https://www.shadertoy.com/user/Flexi // DwPixelFlow context; DwShadertoy toy, toyA, toyB, toyC, toyD; DwGLTexture tex_noise = new DwGLTexture(); public void settings() { size(1280, 720, P2D); smooth(0); } public void setup() { surface.setResizable(true); context = new DwPixelFlow(this); context.print(); context.printGL(); toyA = new DwShadertoy(context, "data/ExpansiveReactionDiffusion_BufA.frag"); toyB = new DwShadertoy(context, "data/ExpansiveReactionDiffusion_BufB.frag"); toyC = new DwShadertoy(context, "data/ExpansiveReactionDiffusion_BufC.frag"); toyD = new DwShadertoy(context, "data/ExpansiveReactionDiffusion_BufD.frag"); toy = new DwShadertoy(context, "data/ExpansiveReactionDiffusion.frag"); // create noise texture int wh = 256; byte[] bdata = new byte[wh * wh * 4]; ByteBuffer bbuffer = ByteBuffer.wrap(bdata); for(int i = 0; i < bdata.length;){ bdata[i++] = (byte) random(0, 255); bdata[i++] = (byte) random(0, 255); bdata[i++] = (byte) random(0, 255); bdata[i++] = (byte) 255; } tex_noise.resize(context, GL2.GL_RGBA8, wh, wh, GL2.GL_RGBA, GL2.GL_UNSIGNED_BYTE, GL2.GL_LINEAR, GL2.GL_MIRRORED_REPEAT, 4, 1, bbuffer); frameRate(60); } public void draw() { blendMode(REPLACE); if(mousePressed){ toyA.set_iMouse(mouseX, height-1-mouseY, mouseX, height-1-mouseY); toyB.set_iMouse(mouseX, height-1-mouseY, mouseX, height-1-mouseY); toyC.set_iMouse(mouseX, height-1-mouseY, mouseX, height-1-mouseY); toyD.set_iMouse(mouseX, height-1-mouseY, mouseX, height-1-mouseY); toy .set_iMouse(mouseX, height-1-mouseY, mouseX, height-1-mouseY); } toyA.set_iChannel(0, toyA); toyA.set_iChannel(1, toyC); toyA.set_iChannel(2, toyD); toyA.set_iChannel(3, tex_noise); toyA.apply(width, height); toyB.set_iChannel(0, toyA); toyB.apply(width, height); toyC.set_iChannel(0, toyB); toyC.apply(width, height); toyD.set_iChannel(0, toyA); toyD.apply(width, height); toy.set_iChannel(0, toyA); toy.set_iChannel(2, toyC); toy.set_iChannel(3, tex_noise); toy.apply(this.g); String txt_fps = String.format(getClass().getSimpleName()+ " [size %d/%d] [frame %d] [fps %6.2f]", width, height, frameCount, frameRate); surface.setTitle(txt_fps); } public static void main(String args[]) { PApplet.main(new String[] { Shadertoy_ExpansiveReactionDiffusion.class.getName() }); } }
1,471
412
/*******************************************************************\ Module: Variables whose address is taken Author: <NAME> Date: March 2013 \*******************************************************************/ /// \file /// Variables whose address is taken #ifndef CPROVER_ANALYSES_DIRTY_H #define CPROVER_ANALYSES_DIRTY_H #include <unordered_set> #include <util/std_expr.h> #include <util/invariant.h> #include <goto-programs/goto_functions.h> /// Dirty variables are ones which have their address taken so we can't /// reliably work out where they may be assigned and are also considered shared /// state in the presence of multi-threading. class dirtyt { private: void die_if_uninitialized() const { INVARIANT( initialized, "Uninitialized dirtyt. This dirtyt was constructed using the default " "constructor and not subsequently initialized using " "dirtyt::build()."); } public: bool initialized; typedef goto_functionst::goto_functiont goto_functiont; /// \post dirtyt objects that are created through this constructor are not /// safe to use. If you copied a dirtyt (for example, by adding an object /// that owns a dirtyt to a container and then copying it back out), you will /// need to re-initialize the dirtyt by calling dirtyt::build(). dirtyt() : initialized(false) { } explicit dirtyt(const goto_functiont &goto_function) : initialized(false) { build(goto_function); initialized = true; } explicit dirtyt(const goto_functionst &goto_functions) : initialized(false) { build(goto_functions); // build(g_funs) responsible for setting initialized to true, since // it is public and can be called independently } void output(std::ostream &out) const; bool operator()(const irep_idt &id) const { die_if_uninitialized(); return dirty.find(id)!=dirty.end(); } bool operator()(const symbol_exprt &expr) const { die_if_uninitialized(); return operator()(expr.get_identifier()); } const std::unordered_set<irep_idt> &get_dirty_ids() const { die_if_uninitialized(); return dirty; } void add_function(const goto_functiont &goto_function) { build(goto_function); initialized = true; } void build(const goto_functionst &goto_functions) { // dirtyts should not be initialized twice PRECONDITION(!initialized); for(const auto &gf_entry : goto_functions.function_map) build(gf_entry.second); initialized = true; } protected: void build(const goto_functiont &goto_function); // variables whose address is taken std::unordered_set<irep_idt> dirty; void find_dirty(const exprt &expr); void find_dirty_address_of(const exprt &expr); }; inline std::ostream &operator<<( std::ostream &out, const dirtyt &dirty) { dirty.output(out); return out; } /// Wrapper for dirtyt that permits incremental population, ensuring each /// function is analysed exactly once. class incremental_dirtyt { public: void populate_dirty_for_function( const irep_idt &id, const goto_functionst::goto_functiont &function); bool operator()(const irep_idt &id) const { return dirty(id); } bool operator()(const symbol_exprt &expr) const { return dirty(expr); } private: dirtyt dirty; std::unordered_set<irep_idt> dirty_processed_functions; }; #endif // CPROVER_ANALYSES_DIRTY_H
1,115
315
#include "Timing.h" namespace Fling { std::chrono::high_resolution_clock::time_point sStartTime; void Timing::Init() { sStartTime = std::chrono::high_resolution_clock::now(); } void Timing::Update() { double currentTime = GetTime(); m_deltaTime = (float)( currentTime - m_lastFrameStartTime ); // Calculate a fall back delta time in case the engine ever gets out of sync const static float FallbackDeltaTime = 1.0f / 60.0f; const static float MaxDeltaTime = 1.0f; // If delta time is greater than 1 second, simulate it as 1/60 FPS // because we can assume that it is like that because of debugging if (m_deltaTime >= MaxDeltaTime) { m_deltaTime = FallbackDeltaTime; } m_lastFrameStartTime = currentTime; m_frameStartTimef = static_cast<float> ( m_lastFrameStartTime ); } float Timing::GetDeltaTime() { return m_deltaTime; } void Timing::UpdateFps() { m_fpsFrameCountTemp++; if (std::floor(GetTimeSinceStart()) > std::floor(m_fpsTimeElapsed)) { m_fpsFrameCount = m_fpsFrameCountTemp; m_fpsFrameCountTemp = 0; } m_fpsTimeElapsed = GetTimeSinceStart(); } double Timing::GetTime() const { auto now = std::chrono::high_resolution_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>( now - sStartTime ).count(); //a little uncool to then convert into a double just to go back, but oh well. return static_cast<double>( ms ) / 1000; } } // namespace Fling
528
1,040
// // MLRender.h // // Graphics interface for MusicLines // // Copyright (c) 1998-1999 Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #ifndef _MLRender_ #define _MLRender_ #include <ddraw.h> // Loaded tiles are 3 16x16 (head, tail, dead) // #define TILES_X (3*16) #define TILES_Y (16) // Each score digit is 32x32 // #define SCORE_X (32) #define SCORE_Y (32) // We always want to run 640x480 // #define GAME_WIDTH (640) #define GAME_HEIGHT (480) class BitmapSurface; // Private representation of bitmaps class OptimalPalette; // Optimal palette generation class class GraphicsEngine { public: GraphicsEngine(LPCSTR ClassName, BOOL fFullScreen); ~GraphicsEngine(); // Enter creates the main window, enters graphics mode, and returns the HWND (or NULL if something went wrong). // The class is registered by WinMain so it has control of the WndProc and message loop. // // Leave undoes Enter and returns to Windows. // HWND Enter(); void Leave(); // Because we want to leave the option open for loading player bitmaps in the future, bitmaps are parsed and a palette // calculated at level startup time. BeginLevelLoad and EndLevelLoad wrap calls into the graphics code for all the // player bitmaps (and any other bitmap resources which are added later). // BOOL BeginLevelLoad(); BOOL EndLevelLoad(); // LoadPlayerTiles loads a bitmap for a player. Currently these are resources attached to the executable. // Bitmaps must be 16x16 256-color uncompressed BMP format. // // If supporting player-loadable bitmaps, there would be an overridden version of this function which loaded bitmaps // from a regular file. // BOOL LoadPlayerTiles(int PlayerNo, LPSTR ResourceName); // LoadPlayerScoreBitmap loads the score bitmap for a player // Bitmap must be 320x32, 32x32 per digit // BOOL LoadPlayerScoreBitmap(int PlayerNo, LPSTR ResourceName); // LoadBackdrop loads the background bitmap if there is one. // Bitmap must be 640x480 // BOOL LoadBackdrop(LPSTR ResourceName); // RenderFrame, well..., renders the current frame. Only tiles which have changed will be repainted unless // some situation occurs which indicates a total repaint. A total repaint can occur because of a window message // from the message loop (such as app activation) or be forced by the render code on its own (if the DirectDraw // surface is lost). // void RenderFrame(); // SetScore sets a player's score so it can be rendered at the top of the display. This only // needs to be done when the score changes. // void SetPlayerScore(int PlayerNo, int Score); // Shake starts a shake effect on the entire display, as if the monitor had been hit. // void Shake(); // WndProc is called to let the graphics engine process and possibly consume a message from the main // WndProc. // BOOL WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *lResult); // Active will return TRUE if the application is active. // inline BOOL Active() { return m_Active; } // Set TRUE while a dialog is up so the cursor will be visible // void SetDialogUp(BOOL fDialogUp); private: BOOL m_FullScreen; // Running full screen? LPSTR m_ClassName; // Caller's class for window creation HINSTANCE m_hInstance; // Application instance BOOL m_Active; // TRUE if app is active LPDIRECTDRAW m_DDraw; // DirectDraw interface LPDIRECTDRAWPALETTE m_DDrawPalette; // Palette for current level DDPIXELFORMAT m_PixelFormat; // Pixel format for primary surface HWND m_hWnd; // Window handle of main game window BitmapSurface* m_Tiles[MAX_PLAYERS]; // Surfaces of tile sets BitmapSurface* m_ScoreFonts[MAX_PLAYERS]; // Surfaces of score fonts BitmapSurface* m_Backdrop; // Surface of the backdrop int m_Scores[MAX_PLAYERS]; // The scores int m_ScoreX[MAX_PLAYERS]; // Offset of score in score bar LPDIRECTDRAWSURFACE m_Primary; // Primary surface LPDIRECTDRAWSURFACE m_BackBuffer; // In full screen, attached flip buffer // If windowed, offscreen compose buffer LPDIRECTDRAWCLIPPER m_Clipper; // In windowed case, render to window only BOOL m_Render; // FALSE if we can't render (such as while changing modes) OptimalPalette* m_pOptimalPalette; // Optimal palette generator if we're in a palettized mode DWORD m_dwBlack; // Color matched pixel color of black int m_Shake; // If shaking, index into shake table BOOL m_DialogUp; // TRUE if displaying a dialog private: HWND EnterFullScreen(); HWND EnterWindowed(); LPDIRECTDRAWSURFACE SurfaceFromBitmap(LPBYTE pbBitmapData, DWORD cbBitmapData, LONG cx, LONG cy); HRESULT RenderToSurface(); HRESULT FlipFullScreen(); HRESULT FlipWindowed(); BOOL RestoreSurfaces(); BOOL QueryNewPalette(HWND hWnd); }; extern GraphicsEngine *theGraphicsEngine; #endif // _MLRender_
2,250
1,817
/* * * * Copyright 2019-2020 the original author or authors. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * 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 test.org.springdoc.api.app68.controller; import test.org.springdoc.api.app68.exception.TweetConflictException; import test.org.springdoc.api.app68.exception.TweetNotFoundException; import test.org.springdoc.api.app68.payload.ErrorResponse; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class ExceptionTranslator { @SuppressWarnings("rawtypes") @ExceptionHandler(TweetConflictException.class) @ResponseStatus(HttpStatus.CONFLICT) public ResponseEntity handleDuplicateKeyException(TweetConflictException ex) { return ResponseEntity.status(HttpStatus.CONFLICT) .body(new ErrorResponse("A Tweet with the same text already exists")); } @SuppressWarnings("rawtypes") @ExceptionHandler(TweetNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseEntity handleTweetNotFoundException(TweetNotFoundException ex) { return ResponseEntity.notFound().build(); } }
537
360
<filename>src/test/java/indi/mybatis/flying/pojo/ProjRatio.java package indi.mybatis.flying.pojo; import java.io.Serializable; import javax.persistence.Id; import org.apache.ibatis.type.JdbcType; import indi.mybatis.flying.annotations.FieldMapperAnnotation; import indi.mybatis.flying.annotations.TableMapperAnnotation; import indi.mybatis.flying.pojoHelper.PojoSupport; @TableMapperAnnotation(tableName = "proj_ratio") public class ProjRatio extends PojoSupport<ProjRatio> implements Serializable { private static final long serialVersionUID = 1L; @Id @FieldMapperAnnotation(dbFieldName = "id", jdbcType = JdbcType.BIGINT) private Long id; @FieldMapperAnnotation(dbFieldName = "proj_name", jdbcType = JdbcType.VARCHAR) private String projName; @FieldMapperAnnotation(dbFieldName = "staff_id", jdbcType = JdbcType.VARCHAR) private String staffId; @FieldMapperAnnotation(dbFieldName = "year", jdbcType = JdbcType.VARCHAR) private String year; @FieldMapperAnnotation(dbFieldName = "season", jdbcType = JdbcType.VARCHAR) private Integer season; @Override public Long getId() { return id; } public String getProjName() { return projName; } public void setProjName(String projName) { this.projName = projName; } public String getStaffId() { return staffId; } public void setStaffId(String staffId) { this.staffId = staffId; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public Integer getSeason() { return season; } public void setSeason(Integer season) { this.season = season; } public void setId(Long id) { this.id = id; } }
702
1,350
<reponame>ppartarr/azure-sdk-for-java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * Package containing API for tracing. */ package com.azure.core.util.tracing;
67
5,964
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SFNTLY_CPP_SRC_SFNTLY_PORT_FILE_INPUT_STREAM_H_ #define SFNTLY_CPP_SRC_SFNTLY_PORT_FILE_INPUT_STREAM_H_ #include <stdio.h> #include "sfntly/port/input_stream.h" namespace sfntly { class FileInputStream : public PushbackInputStream { public: FileInputStream(); virtual ~FileInputStream(); // InputStream methods virtual int32_t Available(); virtual void Close(); virtual void Mark(int32_t readlimit); virtual bool MarkSupported(); virtual int32_t Read(); virtual int32_t Read(ByteVector* b); virtual int32_t Read(ByteVector* b, int32_t offset, int32_t length); virtual void Reset(); virtual int64_t Skip(int64_t n); // PushbackInputStream methods virtual void Unread(ByteVector* b); virtual void Unread(ByteVector* b, int32_t offset, int32_t length); // Own methods virtual bool Open(const char* file_path); private: FILE* file_; size_t position_; size_t length_; }; } // namespace sfntly #endif // SFNTLY_CPP_SRC_SFNTLY_PORT_FILE_INPUT_STREAM_H_
528
1,419
<reponame>Mattlk13/pybuilder # -*- coding: utf-8 -*- # # This file is part of PyBuilder # # Copyright 2011-2021 PyBuilder Team # # 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 textwrap import unittest from itest_support import IntegrationTestSupport from pybuilder.errors import BuildFailedException class Issue822Test(IntegrationTestSupport): def test(self): self.write_build_file(""" from pybuilder.core import use_plugin, init use_plugin("python.core") use_plugin("python.unittest") @init def init (project): project.set_property("verbose", True) project.set_property("remote_debug", 2) project.set_property("remote_tracing", 1) """) self.create_directory("src/main/python") self.create_directory("src/unittest/python") self.write_file("src/main/python/code.py", textwrap.dedent( """ import threading import time class TestThread(threading.Thread): def __init__(self): super().__init__() def run(self): time.sleep(7) def run_code(): TestThread().start() """)) self.write_file("src/unittest/python/code_tests.py", textwrap.dedent( """ import unittest import code class CodeTests(unittest.TestCase): def test_code(self): code.run_code() """ )) reactor = self.prepare_reactor() with self.assertRaises(BuildFailedException) as raised_ex: reactor.build("verify") self.assertEqual(raised_ex.exception.message, "Unittest tool failed with exit code 1") if __name__ == "__main__": unittest.main()
961
2,062
<reponame>TheVinhLuong102/Strawberry from enum import Enum import strawberry def test_repr_type(): @strawberry.type class MyType: s: str i: int b: bool f: float id: strawberry.ID assert ( repr(MyType("a", 1, True, 3.2, "123")) == "test_repr_type.<locals>.MyType(s='a', i=1, b=True, f=3.2, id='123')" ) def test_repr_enum(): @strawberry.enum() class Test(Enum): A = 1 B = 2 C = 3 assert repr(Test(1)) == "<Test.A: 1>"
278
1,283
package com.pengrad.telegrambot.request; import com.pengrad.telegrambot.model.MessageEntity; import com.pengrad.telegrambot.model.Poll; import com.pengrad.telegrambot.model.request.ParseMode; /** * <NAME> * 17 April 2019 */ public class SendPoll extends AbstractSendRequest<SendPoll> { public SendPoll(Object chatId, String question, String... options) { super(chatId); add("question", question); add("options", options); } public SendPoll isAnonymous(boolean isAnonymous) { return add("is_anonymous", isAnonymous); } public SendPoll type(String type) { return add("type", type); } public SendPoll type(Poll.Type type) { return add("type", type.name()); } public SendPoll allowsMultipleAnswers(boolean allowsMultipleAnswers) { return add("allows_multiple_answers", allowsMultipleAnswers); } public SendPoll correctOptionId(int correctOptionId) { return add("correct_option_id", correctOptionId); } public SendPoll explanation(String explanation) { return add("explanation", explanation); } public SendPoll explanationParseMode(ParseMode parseMode) { return add("explanation_parse_mode", parseMode.name()); } public SendPoll explanationEntities(MessageEntity... entities) { return add("explanation_entities", entities); } public SendPoll openPeriod(int openPeriod) { return add("open_period", openPeriod); } public SendPoll closeDate(long closeDate) { return add("close_date", closeDate); } public SendPoll isClosed(boolean isClosed) { return add("is_closed", isClosed); } }
613
519
// // EENavigationController.h // iOSBlogReader // // Created by everettjf on 16/4/27. // Copyright © 2016年 everettjf. All rights reserved. // #import <UIKit/UIKit.h> @interface EENavigationController : UINavigationController @end
87
2,517
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/actor_companion.hpp" #include "caf/config.hpp" #include "caf/make_actor.hpp" #include "caf/message_handler.hpp" #include "caf/scoped_execution_unit.hpp" CAF_PUSH_WARNINGS #include <QApplication> #include <QEvent> CAF_POP_WARNINGS namespace caf::mixin { template <typename Base, int EventId = static_cast<int>(QEvent::User + 31337)> class actor_widget : public Base { public: struct event_type : public QEvent { mailbox_element_ptr mptr; event_type(mailbox_element_ptr ptr) : QEvent(static_cast<QEvent::Type>(EventId)), mptr(std::move(ptr)) { // nop } }; template <typename... Ts> actor_widget(Ts&&... xs) : Base(std::forward<Ts>(xs)...), alive_(false) { // nop } ~actor_widget() { if (companion_) self()->cleanup(error{}, &dummy_); } void init(actor_system& system) { alive_ = true; companion_ = actor_cast<strong_actor_ptr>(system.spawn<actor_companion>()); self()->on_enqueue([=](mailbox_element_ptr ptr) { qApp->postEvent(this, new event_type(std::move(ptr))); }); self()->on_exit([=] { // close widget if actor companion dies this->close(); }); } template <class F> void set_message_handler(F pfun) { self()->become(pfun(self())); } /// Terminates the actor companion and closes this widget. void quit_and_close(error exit_state = error{}) { self()->quit(std::move(exit_state)); this->close(); } bool event(QEvent* event) override { if (event->type() == static_cast<QEvent::Type>(EventId)) { auto ptr = dynamic_cast<event_type*>(event); if (ptr && alive_) { switch (self()->activate(&dummy_, *(ptr->mptr))) { default: break; }; return true; } } return Base::event(event); } actor as_actor() const { CAF_ASSERT(companion_); return actor_cast<actor>(companion_); } actor_companion* self() { using bptr = abstract_actor*; // base pointer using dptr = actor_companion*; // derived pointer return companion_ ? static_cast<dptr>(actor_cast<bptr>(companion_)) : nullptr; } private: scoped_execution_unit dummy_; strong_actor_ptr companion_; bool alive_; }; } // namespace caf::mixin
999
415
<filename>Volume_13/Number_4/Ruijters2008/examples/cubicRotate2D/demo.c<gh_stars>100-1000 /***************************************************************************** * Date: January 3, 2006 * Date: September 2, 2008: adapted the original program of <NAME> * to demonstrate CUDA based cubic B-spline interpolation. *---------------------------------------------------------------------------- * This C program is based on the following paper: * <NAME>, <NAME>, <NAME>, "Interpolation Revisited," * IEEE Transactions on Medical Imaging, * vol. 19, no. 7, pp. 739-758, July 2000. *---------------------------------------------------------------------------- * EPFL/STI/IOA/LIB/BM.4.137 * <NAME> * Station 17 * CH-1015 Lausanne VD *---------------------------------------------------------------------------- * phone (CET): +41(21)693.51.61 * fax: +41(21)693.37.01 * RFC-822: <EMAIL> * X-400: /C=ch/A=400net/P=switch/O=epfl/S=thevenaz/G=philippe/ * URL: http://bigwww.epfl.ch/ *---------------------------------------------------------------------------- * This file is best viewed with 4-space tabs (the bars below should be aligned) * | | | | | | | | | | | | | | | | | | | * |...|...|...|...|...|...|...|...|...|...|...|...|...|...|...|...|...|...| ****************************************************************************/ /***************************************************************************** * System includes ****************************************************************************/ #include <math.h> #include <stdio.h> #include <stdlib.h> /***************************************************************************** * Other includes ****************************************************************************/ #include "io.h" typedef unsigned int uint; extern float* CopyVolumeHostToDevice(float* host, uint width, uint height, uint depth); extern void CopyVolumeDeviceToHost(float* host, float* device, uint width, uint height, uint depth); extern void CubicBSplinePrefilter2DTimer(float* image, uint width, uint height); extern float* interpolate(uint width, uint height, double angle, double xShift, double yShift, double xOrigin, double yOrigin, int masking); extern void initTexture(float* bsplineCoeffs, uint width, uint height); /***************************************************************************** * Defines ****************************************************************************/ #define PI ((double)3.14159265358979323846264338327950288419716939937510) /***************************************************************************** * Definition of extern procedures ****************************************************************************/ /*--------------------------------------------------------------------------*/ extern int main ( void ) { /* begin main */ float *bsplineCoeffs, *cudaOutput; float *ImageRasterArray, *OutputImage; double xOrigin, yOrigin; double Angle, xShift, yShift; long Width, Height; long SplineDegree; int Masking; int Error; /* access data samples */ Error = ReadByteImageRawData(&ImageRasterArray, &Width, &Height); if (Error) { printf("Failure to import image data\n"); return(1); } /* ask for transformation parameters */ RigidBody(&Angle, &xShift, &yShift, &xOrigin, &yOrigin, &SplineDegree, &Masking); /* allocate output image */ OutputImage = (float *)malloc((size_t)(Width * Height * (long)sizeof(float))); if (OutputImage == (float *)NULL) { free(ImageRasterArray); printf("Allocation of output image failed\n"); return(1); } /* convert between a representation based on image samples */ /* and a representation based on image B-spline coefficients */ bsplineCoeffs = CopyVolumeHostToDevice(ImageRasterArray, Width, Height, 1); CubicBSplinePrefilter2DTimer(bsplineCoeffs, Width, Height); initTexture(bsplineCoeffs, Width, Height); /* Call the CUDA kernel */ cudaOutput = interpolate(Width, Height, Angle, xShift, yShift, xOrigin, yOrigin, Masking); CopyVolumeDeviceToHost(OutputImage, cudaOutput, Width, Height, 1); /* save output */ Error = WriteByteImageRawData(OutputImage, Width, Height); if (Error) { free(OutputImage); free(ImageRasterArray); printf("Failure to export image data\n"); return(1); } free(OutputImage); free(ImageRasterArray); printf("Done\n"); return(0); } /* end main */
1,301
335
/* * unarchiver.h * ------------ * Purpose: archive loader * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #pragma once #include "openmpt/all/BuildSettings.hpp" #include "../common/FileReader.h" #include "archive.h" #if (defined(MPT_WITH_ZLIB) && defined(MPT_WITH_MINIZIP)) || defined(MPT_WITH_MINIZ) #include "unzip.h" #endif #ifdef MPT_WITH_LHASA #include "unlha.h" #endif #if defined(MPT_WITH_ZLIB) || defined(MPT_WITH_MINIZ) #include "ungzip.h" #endif #ifdef MPT_WITH_UNRAR #include "unrar.h" #endif #ifdef MPT_WITH_ANCIENT #include "unancient.h" #endif OPENMPT_NAMESPACE_BEGIN class CUnarchiver : public IArchive { private: IArchive *impl; FileReader inFile; ArchiveBase emptyArchive; #if (defined(MPT_WITH_ZLIB) && defined(MPT_WITH_MINIZIP)) || defined(MPT_WITH_MINIZ) CZipArchive zipArchive; #endif #ifdef MPT_WITH_LHASA CLhaArchive lhaArchive; #endif #if defined(MPT_WITH_ZLIB) || defined(MPT_WITH_MINIZ) CGzipArchive gzipArchive; #endif #ifdef MPT_WITH_UNRAR CRarArchive rarArchive; #endif #ifdef MPT_WITH_ANCIENT CAncientArchive ancientArchive; #endif public: CUnarchiver(FileReader &file); ~CUnarchiver() override; bool IsArchive() const override; mpt::ustring GetComment() const override; bool ExtractFile(std::size_t index) override; FileReader GetOutputFile() const override; std::size_t size() const override; IArchive::const_iterator begin() const override; IArchive::const_iterator end() const override; const ArchiveFileInfo & operator [] (std::size_t index) const override; public: static const std::size_t failIndex = (std::size_t)-1; std::size_t FindBestFile(const std::vector<const char *> &extensions); bool ExtractBestFile(const std::vector<const char *> &extensions); }; OPENMPT_NAMESPACE_END
725
17,703
#pragma once #include "envoy/server/configuration.h" #include "gmock/gmock.h" #include "instance.h" #include "tracer_factory.h" namespace Envoy { namespace Server { namespace Configuration { class MockTracerFactoryContext : public TracerFactoryContext { public: MockTracerFactoryContext(); ~MockTracerFactoryContext() override; MOCK_METHOD(ServerFactoryContext&, serverFactoryContext, ()); MOCK_METHOD(ProtobufMessage::ValidationVisitor&, messageValidationVisitor, ()); testing::NiceMock<Configuration::MockServerFactoryContext> server_factory_context_; }; } // namespace Configuration } // namespace Server } // namespace Envoy
193
834
// Copyright 2004-present Facebook. All Rights Reserved. #include "fboss/agent/hw/bcm/BcmHostKey.h" #include "fboss/agent/test/LabelForwardingUtils.h" #include <gtest/gtest.h> namespace { auto constexpr kLinkLocal = "fe80::"; using namespace facebook::fboss; void verifyUnlabeledHostKey( const HostKey& key, const BcmHostKey& hostKey, bool resolved) { EXPECT_EQ(key.getVrf(), hostKey.getVrf()); EXPECT_EQ(key.addr(), hostKey.addr()); EXPECT_EQ(key.intfID(), hostKey.intfID()); EXPECT_EQ(key.hasLabel(), hostKey.hasLabel()); EXPECT_THROW(key.getLabel(), FbossError); if (!resolved) { EXPECT_THROW(key.intfID().value(), std::bad_optional_access); } else { EXPECT_EQ(key.intfID(), hostKey.intf()); } EXPECT_EQ(key.needsMplsTunnel(), hostKey.needsMplsTunnel()); EXPECT_EQ(key.needsMplsTunnel(), false); EXPECT_THROW(key.tunnelLabelStack(), FbossError); EXPECT_THROW(hostKey.tunnelLabelStack(), FbossError); } void verifyLabeledHostKey( const HostKey& key, const BcmLabeledHostKey& hostKey) { EXPECT_EQ(key.getVrf(), hostKey.getVrf()); EXPECT_EQ(key.addr(), hostKey.addr()); EXPECT_EQ(key.intfID(), hostKey.intfID()); EXPECT_EQ(key.hasLabel(), hostKey.hasLabel()); EXPECT_EQ(key.getLabel(), hostKey.getLabel()); EXPECT_EQ(key.intfID().value(), hostKey.intf()); ASSERT_EQ(key.needsMplsTunnel(), hostKey.needsMplsTunnel()); if (key.needsMplsTunnel()) { EXPECT_EQ(key.tunnelLabelStack(), hostKey.tunnelLabelStack()); } else { EXPECT_THROW(key.tunnelLabelStack(), FbossError); EXPECT_THROW(hostKey.tunnelLabelStack(), FbossError); } } } // namespace namespace facebook::fboss { TEST(BcmHostKey, unResolvedNextHop) { auto nexthop = UnresolvedNextHop(folly::IPAddressV6("fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b"), 0); auto bcmHostKey = BcmHostKey(0, nexthop); verifyUnlabeledHostKey(bcmHostKey, bcmHostKey, false /* unresolved */); } TEST(BcmHostKey, resolvedNextHop) { auto nexthop = ResolvedNextHop(folly::IPAddressV6(kLinkLocal), InterfaceID(1), 0); auto bcmHostKey = BcmHostKey(0, nexthop); verifyUnlabeledHostKey(bcmHostKey, bcmHostKey, true /* resolved */); } TEST(BcmHostKey, labeledNextHopWithSwap) { auto nexthop = ResolvedNextHop( folly::IPAddressV6(kLinkLocal), InterfaceID(1), 0, util::getSwapAction(201)); auto bcmLabeledHostKey = BcmLabeledHostKey( 0, nexthop.labelForwardingAction()->swapWith().value(), nexthop.addr(), nexthop.intfID().value()); verifyLabeledHostKey(bcmLabeledHostKey, bcmLabeledHostKey); } TEST(BcmHostKey, labeledNextHopWithPush) { auto nexthop = ResolvedNextHop( folly::IPAddressV6(kLinkLocal), InterfaceID(1), 0, util::getPushAction(LabelForwardingAction::LabelStack{201, 202})); auto bcmLabeledHostKey = BcmLabeledHostKey( 0, nexthop.labelForwardingAction()->pushStack().value(), nexthop.addr(), nexthop.intfID().value()); verifyLabeledHostKey(bcmLabeledHostKey, bcmLabeledHostKey); } TEST(BcmHostKey, labeledNextHopWithPushOnlyOne) { auto nexthop = ResolvedNextHop( folly::IPAddressV6(kLinkLocal), InterfaceID(1), 0, util::getPushAction(LabelForwardingAction::LabelStack{201})); auto bcmLabeledHostKey = BcmLabeledHostKey( 0, nexthop.labelForwardingAction()->pushStack().value(), nexthop.addr(), nexthop.intfID().value()); verifyLabeledHostKey(bcmLabeledHostKey, bcmLabeledHostKey); } TEST(BcmHostKey, unLabeledNextHopWitForLabelForwarding) { auto php = ResolvedNextHop( folly::IPAddressV6(kLinkLocal), InterfaceID(1), 0, util::getPhpAction()); auto bcmHostKey = BcmHostKey(0, php); verifyUnlabeledHostKey(bcmHostKey, bcmHostKey, true /* resolved */); } TEST(BcmHostKey, LabeledKeyStr) { auto swapKey = BcmLabeledHostKey(0, 201, folly::IPAddress(kLinkLocal), InterfaceID(1)); auto pushOneKey = BcmLabeledHostKey( 0, LabelForwardingAction::LabelStack{301}, folly::IPAddress(kLinkLocal), InterfaceID(2)); auto pushManyKey = BcmLabeledHostKey( 0, LabelForwardingAction::LabelStack{401, 402, 403, 404}, folly::IPAddress(kLinkLocal), InterfaceID(3)); EXPECT_EQ( swapKey.str(), folly::to<std::string>( "BcmLabeledHost: ", kLinkLocal, "@I", 1, "@label201")); EXPECT_EQ( pushOneKey.str(), folly::to<std::string>( "BcmLabeledHost: ", kLinkLocal, "@I", 2, "@stack[301]")); EXPECT_EQ( pushManyKey.str(), folly::to<std::string>( "BcmLabeledHost: ", kLinkLocal, "@I", 3, "@stack[401,402,403,404]")); } } // namespace facebook::fboss
1,975
438
<reponame>yjfnypeu/Router /* * Copyright (C) 2017 Haoge * * 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.lzh.nonview.router.route; import android.content.Context; import android.net.Uri; import android.os.Bundle; import com.lzh.nonview.router.Router; import com.lzh.nonview.router.RouterConfiguration; import com.lzh.nonview.router.extras.RouteBundleExtras; import com.lzh.nonview.router.interceptors.RouteInterceptor; import com.lzh.nonview.router.interceptors.RouteInterceptorAction; import com.lzh.nonview.router.launcher.Launcher; import com.lzh.nonview.router.module.RouteRule; import com.lzh.nonview.router.parser.URIParser; import com.lzh.nonview.router.tools.Cache; import com.lzh.nonview.router.tools.Utils; import java.util.ArrayList; import java.util.List; @SuppressWarnings("unchecked") public abstract class BaseRoute<T extends IBaseRoute> implements IRoute, IBaseRoute<T>, RouteInterceptorAction<T> { protected Bundle bundle; InternalCallback callback; protected Uri uri; protected Bundle remote; protected RouteRule routeRule = null; protected Launcher launcher; public final IRoute create(Uri uri, RouteRule rule, Bundle remote, InternalCallback callback) { try { this.uri = uri; this.remote = remote; this.callback = callback; this.routeRule = rule; this.bundle = Utils.parseToBundle(new URIParser(uri)); this.bundle.putParcelable(Router.RAW_URI, uri); this.launcher = obtainLauncher(); return this; } catch (Throwable e) { callback.onOpenFailed(e); return new EmptyRoute(callback); } } // =========Unify method of IBaseRoute @Override public final void open(Context context) { try { Utils.checkInterceptor(uri, callback.getExtras(), context,getInterceptors()); launcher.set(uri, bundle, callback.getExtras(), routeRule, remote); launcher.open(context); // realOpen(context); callback.onOpenSuccess(routeRule); } catch (Throwable e) { callback.onOpenFailed(e); } callback.invoke(context); } @Override public T addExtras(Bundle extras) { this.callback.getExtras().addExtras(extras); return (T) this; } // =============RouteInterceptor operation=============== public T addInterceptor(RouteInterceptor interceptor) { if (callback.getExtras() != null) { callback.getExtras().addInterceptor(interceptor); } return (T) this; } @Override public T removeInterceptor(RouteInterceptor interceptor) { if (callback.getExtras() != null) { callback.getExtras().removeInterceptor(interceptor); } return (T) this; } @Override public T removeAllInterceptors() { if (callback.getExtras() != null) { callback.getExtras().removeAllInterceptors(); } return (T) this; } @Override public List<RouteInterceptor> getInterceptors() { List<RouteInterceptor> interceptors = new ArrayList<>(); // add global interceptor if (RouterConfiguration.get().getInterceptor() != null) { interceptors.add(RouterConfiguration.get().getInterceptor()); } // add extra interceptors if (callback.getExtras() != null) { interceptors.addAll(callback.getExtras().getInterceptors()); } // add interceptors in rule for (Class<RouteInterceptor> interceptor : routeRule.getInterceptors()) { if (interceptor != null) { try { interceptors.add(interceptor.newInstance()); } catch (Exception e) { throw new RuntimeException(String.format("The interceptor class [%s] should provide a default empty construction", interceptor)); } } } return interceptors; } // ========getter/setter============ public void replaceExtras(RouteBundleExtras extras) { this.callback.setExtras(extras); } public static RouteRule findRule(Uri uri, int type) { return Cache.getRouteMapByUri(new URIParser(uri), type); } // ============abstract methods============ protected abstract Launcher obtainLauncher() throws Exception; }
1,944
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.masterfs.filebasedfs.naming; import java.io.File; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; final class NameRef extends WeakReference<FileNaming> { /** either reference to NameRef or to Integer as an index to names array */ private Object next; static final ReferenceQueue<FileNaming> QUEUE = new ReferenceQueue<FileNaming>(); public NameRef(FileNaming referent) { super(referent, QUEUE); } public Integer getIndex() { assert Thread.holdsLock(NamingFactory.class); NameRef nr = this; while (nr != null) { if (nr.next instanceof Integer) { return (Integer) nr.next; } nr = nr.next(); } return -1; } public NameRef next() { if (next instanceof Integer) { return null; } return (NameRef) next; } public File getFile() { FileNaming r = get(); return r == null ? null : r.getFile(); } public NameRef remove(NameRef what) { assert Thread.holdsLock(NamingFactory.class); if (what == this) { return next(); } NameRef me = this; while (me.next != what) { if (me.next instanceof Integer) { return this; } me = (NameRef) me.next; } me.next = me.next().next; return this; } final void setNext(NameRef nr) { assert Thread.holdsLock(NamingFactory.class); assert next == null : "There is next " + next; this.next = nr; } final void setIndex(int index) { assert Thread.holdsLock(NamingFactory.class); assert next == null : "There is next " + next; next = index; } final void skip(NameRef ref) { assert Thread.holdsLock(NamingFactory.class); assert next == ref; assert ref.get() == null; next = ref.next; } final Iterable<NameRef> disconnectAll() { assert Thread.holdsLock(NamingFactory.class); List<NameRef> all = new ArrayList<NameRef>(); NameRef nr = this; while (nr != null) { NameRef nn = nr.next(); nr.next = null; if (nr.get() != null) { all.add(nr); } nr = nn; } return all; } }
1,343
313
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import libcst as cst import libcst.matchers as m from fixit import CstLintRule, InvalidTestCase as Invalid, ValidTestCase as Valid class NoAssertEqualsRule(CstLintRule): """ Discourages use of ``assertEquals`` as it is deprecated (see https://docs.python.org/2/library/unittest.html#deprecated-aliases and https://bugs.python.org/issue9424). Use the standardized ``assertEqual`` instead. """ MESSAGE: str = ( '"assertEquals" is deprecated, use "assertEqual" instead.\n' + "See https://docs.python.org/2/library/unittest.html#deprecated-aliases and https://bugs.python.org/issue9424." ) VALID = [Valid("self.assertEqual(a, b)")] INVALID = [ Invalid( "self.assertEquals(a, b)", expected_replacement="self.assertEqual(a, b)", ) ] def visit_Call(self, node: cst.Call) -> None: if m.matches( node, m.Call(func=m.Attribute(value=m.Name("self"), attr=m.Name("assertEquals"))), ): new_call = node.with_deep_changes( old_node=cst.ensure_type(node.func, cst.Attribute).attr, value="assertEqual", ) self.report(node, replacement=new_call)
601
321
<filename>BTBManagerTelegram.py from btb_manager_telegram.__main__ import main, pre_run_main if __name__ == "__main__": pre_run_main() main()
61
2,693
<reponame>Chillee/benchmark import unittest import torch from fastNLP import Vocabulary, DataSet, Instance from fastNLP.embeddings.char_embedding import LSTMCharEmbedding, CNNCharEmbedding class TestCharEmbed(unittest.TestCase): def test_case_1(self): ds = DataSet([Instance(words=['hello', 'world']), Instance(words=['Jack'])]) vocab = Vocabulary().from_dataset(ds, field_name='words') self.assertEqual(len(vocab), 5) embed = LSTMCharEmbedding(vocab, embed_size=60) x = torch.LongTensor([[2, 1, 0], [4, 3, 4]]) y = embed(x) self.assertEqual(tuple(y.size()), (2, 3, 60)) def test_case_2(self): ds = DataSet([Instance(words=['hello', 'world']), Instance(words=['Jack'])]) vocab = Vocabulary().from_dataset(ds, field_name='words') self.assertEqual(len(vocab), 5) embed = CNNCharEmbedding(vocab, embed_size=60) x = torch.LongTensor([[2, 1, 0], [4, 3, 4]]) y = embed(x) self.assertEqual(tuple(y.size()), (2, 3, 60))
473
2,109
/* * Copyright (c) 2008 <NAME> * <EMAIL>andre.hamelin(@)gmail.com * Based on saltSHA1 format source. * * Intrinsics use: Copyright magnum 2012 and hereby released to the general * public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, is permitted. * * Oracle 11g SHA1 cracker * * Please note that a much better way to crack Oracle 11g passwords exists than * brute forcing the SHA1 hash since the pre-Oracle 10g hash is still stored in * the SYS.USER$ table in the column PASSWORD. * * $ uname -a * Linux xyz 2.6.22-hardened-r8 #1 SMP Fri Jan 11 23:24:31 EST 2008 x86_64 AMD Athlon(tm) 64 X2 Dual Core Processor 5200+ AuthenticAMD GNU/Linux * $ ./john --test * [...] * Benchmarking: Oracle 11g [oracle11]... DONE * Many salts: 2387K c/s real, 2507K c/s virtual * Only one salt: 2275K c/s real, 2275K c/s virtual * [...] * * To use: * 1. Connect as a DBA to Oracle 11g with sqlplus * 2. set heading off * set feedback off * set pagesize 1000 * set linesize 100 * spool ora11-passwds.txt * 3. SELECT name || ':' || SUBSTR(spare4,3) * FROM sys.user$ * WHERE spare4 IS NOT NULL * ORDER BY name; * 4. spool off * quit * 5. Remove extra spaces (%s:/\s\+$//) and extra lines (:g!/:\w/d) in output. * 6. ./john [-f:oracle11] ora11-passwds.txt * * TODO: * The prefix "S:" suggests that other hashing functions might be used to store * user passwords; if this is indeed possible (I've not verified in the docs * yet) maybe implement other 11g cracking functions in the same oracle11_fmt.c * file. * Change the hash format for JtR? Prefix with "O11$" or "S:" ? (but "S:" might * not be possible due to the way JtR parses password files) */ #if FMT_EXTERNS_H extern struct fmt_main fmt_oracle11; #elif FMT_REGISTERS_H john_register_one(&fmt_oracle11); #else #include <string.h> #include "arch.h" #ifdef SIMD_COEF_32 #define NBKEYS (SIMD_COEF_32 * SIMD_PARA_SHA1) #endif #include "simd-intrinsics.h" #include "misc.h" #include "common.h" #include "formats.h" #include "sha.h" #include "johnswap.h" #include <ctype.h> #include "memdbg.h" #define FORMAT_LABEL "oracle11" #define FORMAT_NAME "Oracle 11g" #define ALGORITHM_NAME "SHA1 " SHA1_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 /* Maximum length of password in characters. Oracle supports identifiers of 30 * characters max. (ALTER USER user IDENTIFIED BY 30lettersPassword) */ #define PLAINTEXT_LENGTH 30 /* Length in characters of the cipher text, as seen in the password file. * Excludes prefix if any. */ #define CIPHERTEXT_LENGTH 60 /* Length of hashed value without the salt, in bytes. */ #define BINARY_SIZE 20 #define BINARY_ALIGN 4 /* Length of salt in bytes. */ #define SALT_SIZE 10 #define SALT_ALIGN 4 /* Sanity check. Don't change. */ #if (BINARY_SIZE + SALT_SIZE) * 2 != CIPHERTEXT_LENGTH #error Incorrect binary sizes or cipher text length. #endif #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT NBKEYS #define MAX_KEYS_PER_CRYPT NBKEYS #define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + (3-((i)&3)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32*4 ) //for endianity conversion #define GETPOS_WORD(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32*4) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static struct fmt_tests tests[] = { /* 160 bits of SHA1, followed by 80 bits of salt. No "S:" prefix. */ {"5FDAB69F543563582BA57894FE1C1361FB8ED57B903603F2C52ED1B4D642", "abc<PASSWORD>"}, {"450F957ECBE075D2FA009BA822A9E28709FBC3DA82B44D284DDABEC14C42", "SyStEm123!@#"}, {"3437FF72BD69E3FB4D10C750B92B8FB90B155E26227B9AB62D94F54E5951", "oracle"}, {"61CE616647A4F7980AFD7C7245261AF25E0AFE9C9763FCF0D54DA667D4E6", "11g"}, {"B9E7556F53500C8C78A58F50F24439D79962DE68117654B6700CE7CC71CF", "11g"}, {NULL} }; static unsigned char *saved_salt; #ifdef SIMD_COEF_32 unsigned char *saved_key; unsigned char *crypt_key; #else static char saved_key[PLAINTEXT_LENGTH + 1]; static int saved_len; static SHA_CTX ctx; static uint32_t crypt_key[BINARY_SIZE / 4]; #endif static void init(struct fmt_main *self) { #ifdef SIMD_COEF_32 unsigned int i; saved_key = mem_calloc_align(SHA_BUF_SIZ * 4, NBKEYS, MEM_ALIGN_SIMD); crypt_key = mem_calloc_align(BINARY_SIZE, NBKEYS, MEM_ALIGN_SIMD); /* Set lengths to SALT_LEN to avoid strange things in crypt_all() if called without setting all keys (in benchmarking). Unset keys would otherwise get a length of -10 and a salt appended at pos 4294967286... */ for (i=0; i < NBKEYS; i++) ((unsigned int *)saved_key)[15*SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + i/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] = 10 << 3; #endif saved_salt = mem_calloc(1, SALT_SIZE); } static void done(void) { MEM_FREE(saved_salt); #ifdef SIMD_COEF_32 MEM_FREE(crypt_key); MEM_FREE(saved_key); #endif } static int valid(char *ciphertext, struct fmt_main *self) { int extra; return hexlenu(ciphertext, &extra)==CIPHERTEXT_LENGTH && !extra; } static void *get_salt(char *ciphertext) { static unsigned char *salt; int i; if (!salt) salt = mem_alloc_tiny(SALT_SIZE, MEM_ALIGN_WORD); for (i = 0; i < SALT_SIZE; i++) { salt[i] = atoi16[ARCH_INDEX(ciphertext[BINARY_SIZE*2+i*2+0])]*16 + atoi16[ARCH_INDEX(ciphertext[BINARY_SIZE*2+i*2+1])]; } return (void *)salt; } static void set_salt(void *salt) { memcpy(saved_salt, salt, SALT_SIZE); } static void clear_keys(void) { #ifdef SIMD_COEF_32 unsigned int i; memset(saved_key, 0, SHA_BUF_SIZ * 4 * NBKEYS); /* Set lengths to SALT_LEN to avoid strange things in crypt_all() if called without setting all keys (in benchmarking). Unset keys would otherwise get a length of -10 and a salt appended at pos 4294967286... */ for (i=0; i < NBKEYS; i++) ((unsigned int *)saved_key)[15*SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + i/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] = 10 << 3; #endif } static void set_key(char *key, int index) { #ifdef SIMD_COEF_32 #if ARCH_ALLOWS_UNALIGNED const uint32_t *wkey = (uint32_t*)key; #else char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint32_t)); const uint32_t *wkey = (uint32_t*)(is_aligned(key, sizeof(uint32_t)) ? key : strcpy(buf_aligned, key)); #endif uint32_t *keybuf_word = (unsigned int*)&saved_key[GETPOS_WORD(0, index)]; unsigned int len; len = SALT_SIZE; while((*keybuf_word = JOHNSWAP(*wkey++)) & 0xff000000) { if (!(*keybuf_word & 0xff0000)) { len++; break; } if (!(*keybuf_word & 0xff00)) { len+=2; break; } if (!(*keybuf_word & 0xff)) { len+=3; break; } len += 4; keybuf_word += SIMD_COEF_32; } saved_key[GETPOS(len, index)] = 0x80; ((unsigned int *)saved_key)[15*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] = len << 3; #else saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key, key, saved_len); saved_key[saved_len] = 0; #endif } static char *get_key(int index) { #ifdef SIMD_COEF_32 unsigned int i,s; static char out[PLAINTEXT_LENGTH + 1]; s = (((unsigned int *)saved_key)[15*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] >> 3) - SALT_SIZE; for (i = 0; i < s; i++) out[i] = ((char*)saved_key)[ GETPOS(i, index) ]; out[i] = 0; return (char *) out; #else saved_key[saved_len] = 0; return saved_key; #endif } static int cmp_all(void *binary, int count) { #ifdef SIMD_COEF_32 unsigned int x,y=0; for (;y<SIMD_PARA_SHA1;y++) for (x=0;x<SIMD_COEF_32;x++) { if ( ((unsigned int *)binary)[0] == ((unsigned int *)crypt_key)[x+y*SIMD_COEF_32*5] ) return 1; } return 0; #else return !memcmp(binary, crypt_key, BINARY_SIZE); #endif } static int cmp_one(void * binary, int index) { #ifdef SIMD_COEF_32 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; if ( (((unsigned int *)binary)[0] != ((unsigned int *)crypt_key)[x+y*SIMD_COEF_32*5]) | (((unsigned int *)binary)[1] != ((unsigned int *)crypt_key)[x+y*SIMD_COEF_32*5+SIMD_COEF_32]) | (((unsigned int *)binary)[2] != ((unsigned int *)crypt_key)[x+y*SIMD_COEF_32*5+2*SIMD_COEF_32]) | (((unsigned int *)binary)[3] != ((unsigned int *)crypt_key)[x+y*SIMD_COEF_32*5+3*SIMD_COEF_32])| (((unsigned int *)binary)[4] != ((unsigned int *)crypt_key)[x+y*SIMD_COEF_32*5+4*SIMD_COEF_32]) ) return 0; return 1; #else return cmp_all(binary, index); #endif } static int cmp_exact(char *source, int index) { return 1; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; #ifdef SIMD_COEF_32 unsigned int index; for (index = 0; index < count; ++index) { unsigned int len = ((((unsigned int *)saved_key)[15*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32]) >> 3) - SALT_SIZE; unsigned int i = 0; // 1. Copy a byte at a time until we're aligned in buffer // 2. Copy a whole word, or two! // 3. Copy the stray bytes switch (len & 3) { case 0: *(uint32_t*)&saved_key[GETPOS_WORD((len+i),index)] = JOHNSWAP(*(uint32_t*)&saved_salt[i]); i += 4; *(uint32_t*)&saved_key[GETPOS_WORD((len+i),index)] = JOHNSWAP(*(uint32_t*)&saved_salt[i]); i += 4; saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; saved_key[GETPOS((len+i), index)] = saved_salt[i]; break; case 1: saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; *(uint32_t*)&saved_key[GETPOS_WORD((len+i),index)] = JOHNSWAP(*(uint32_t*)&saved_salt[i]); i += 4; saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; saved_key[GETPOS((len+i), index)] = saved_salt[i]; break; case 2: saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; *(uint32_t*)&saved_key[GETPOS_WORD((len+i),index)] = JOHNSWAP(*(uint32_t*)&saved_salt[i]); i += 4; *(uint32_t*)&saved_key[GETPOS_WORD((len+i),index)] = JOHNSWAP(*(uint32_t*)&saved_salt[i]); break; case 3: saved_key[GETPOS((len+i), index)] = saved_salt[i]; i++; *(uint32_t*)&saved_key[GETPOS_WORD((len+i),index)] = JOHNSWAP(*(uint32_t*)&saved_salt[i]); i += 4; *(uint32_t*)&saved_key[GETPOS_WORD((len+i),index)] = JOHNSWAP(*(uint32_t*)&saved_salt[i]); i += 4; saved_key[GETPOS((len+i), index)] = saved_salt[i]; break; } } SIMDSHA1body(saved_key, (unsigned int *)crypt_key, NULL, SSEi_MIXED_IN); #else SHA1_Init( &ctx ); SHA1_Update( &ctx, (unsigned char *) saved_key, saved_len ); SHA1_Update( &ctx, saved_salt, SALT_SIZE ); SHA1_Final( (unsigned char *)crypt_key, &ctx); #endif return count; } static void * get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; long dummy; } realcipher; int i; for (i=0;i<BINARY_SIZE;i++) realcipher.c[i] = atoi16[ARCH_INDEX(ciphertext[i*2])]*16 + atoi16[ARCH_INDEX(ciphertext[i*2+1])]; #ifdef SIMD_COEF_32 alter_endianity((unsigned char *)realcipher.c, BINARY_SIZE); #endif return (void *)realcipher.c; } #ifdef SIMD_COEF_32 #define KEY_OFF (((unsigned int)index/SIMD_COEF_32)*SIMD_COEF_32*5+(index&(SIMD_COEF_32-1))) static int get_hash_0(int index) { return ((uint32_t *)crypt_key)[KEY_OFF] & PH_MASK_0; } static int get_hash_1(int index) { return ((uint32_t *)crypt_key)[KEY_OFF] & PH_MASK_1; } static int get_hash_2(int index) { return ((uint32_t *)crypt_key)[KEY_OFF] & PH_MASK_2; } static int get_hash_3(int index) { return ((uint32_t *)crypt_key)[KEY_OFF] & PH_MASK_3; } static int get_hash_4(int index) { return ((uint32_t *)crypt_key)[KEY_OFF] & PH_MASK_4; } static int get_hash_5(int index) { return ((uint32_t *)crypt_key)[KEY_OFF] & PH_MASK_5; } static int get_hash_6(int index) { return ((uint32_t *)crypt_key)[KEY_OFF] & PH_MASK_6; } #else static int get_hash_0(int index) { return ((uint32_t *)crypt_key)[index] & PH_MASK_0; } static int get_hash_1(int index) { return ((uint32_t *)crypt_key)[index] & PH_MASK_1; } static int get_hash_2(int index) { return ((uint32_t *)crypt_key)[index] & PH_MASK_2; } static int get_hash_3(int index) { return ((uint32_t *)crypt_key)[index] & PH_MASK_3; } static int get_hash_4(int index) { return ((uint32_t *)crypt_key)[index] & PH_MASK_4; } static int get_hash_5(int index) { return ((uint32_t *)crypt_key)[index] & PH_MASK_5; } static int get_hash_6(int index) { return ((uint32_t *)crypt_key)[index] & PH_MASK_6; } #endif static int salt_hash(void *salt) { return *(uint32_t*)salt & (SALT_HASH_SIZE - 1); } struct fmt_main fmt_oracle11 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT, { NULL }, { NULL }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
6,360
355
<gh_stars>100-1000 // Copyright (c) 2015 // Author: <NAME> #include <std.hpp> using namespace std; #include <boost/static_assert.hpp> ////////////////////////////////////////// void case1() { BOOST_STATIC_ASSERT(2 == sizeof(short)); BOOST_STATIC_ASSERT(true); BOOST_STATIC_ASSERT_MSG(16 == 0x10, "test static assert"); } ////////////////////////////////////////// template<typename T> T my_min(T a, T b) { BOOST_STATIC_ASSERT_MSG(sizeof(T) < sizeof(int), "only short or char"); return a < b? a: b; } void case2() { cout << my_min((short)1, (short)3); //cout << my_min(1L, 3L); } ////////////////////////////////////////// namespace my_space { class empty_class { BOOST_STATIC_ASSERT_MSG(sizeof(int)>=4, "for 32 bit"); }; BOOST_STATIC_ASSERT(sizeof(empty_class) == 1); } int main() { case1(); case2(); }
368
1,112
<reponame>berezhko/python-control # exception.py - exception definitions for the control package # # Author: <NAME> # Date: 31 May 2010 # # This file contains definitions of standard exceptions for the control package # # Copyright (c) 2010 by California Institute of Technology # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the California Institute of Technology nor # the names of its contributors may be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CALTECH # OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # $Id$ class ControlSlycot(ImportError): """Exception for Slycot import. Used when we can't import a function from the slycot package""" pass class ControlDimension(ValueError): """Raised when dimensions of system objects are not correct""" pass class ControlArgument(TypeError): """Raised when arguments to a function are not correct""" pass class ControlMIMONotImplemented(NotImplementedError): """Function is not currently implemented for MIMO systems""" pass class ControlNotImplemented(NotImplementedError): """Functionality is not yet implemented""" pass # Utility function to see if slycot is installed slycot_installed = None def slycot_check(): global slycot_installed if slycot_installed is None: try: import slycot slycot_installed = True except: slycot_installed = False return slycot_installed
818
2,358
<filename>test/pytest/test_integrate.py import numpy as np import os import sys sys.path.append(os.path.abspath(r'../lib')) import NumCppPy as NumCpp # noqa E402 #################################################################################### NUM_DECIMALS_ROUND = 1 #################################################################################### def test_seed(): np.random.seed(666) #################################################################################### def test_gauss_legendre(): numCoefficients = np.random.randint(2, 5, [1, ]).item() coefficients = np.random.randint(-20, 20, [numCoefficients, ]) coefficientsC = NumCpp.NdArray(1, numCoefficients) coefficientsC.setArray(coefficients) poly = np.poly1d(np.flipud(coefficients), False) polyIntegral = poly.integ() polyC = NumCpp.Poly1d(coefficientsC, False) a, b = np.sort(np.random.rand(2) * 100 - 50) area = np.round(polyIntegral(b) - polyIntegral(a), NUM_DECIMALS_ROUND) areaC = np.round(NumCpp.integrate_gauss_legendre(polyC, a, b), NUM_DECIMALS_ROUND) assert area == areaC #################################################################################### def test_romberg(): PERCENT_LEEWAY = 0.1 numCoefficients = np.random.randint(2, 5, [1, ]).item() coefficients = np.random.randint(-20, 20, [numCoefficients, ]) coefficientsC = NumCpp.NdArray(1, numCoefficients) coefficientsC.setArray(coefficients) poly = np.poly1d(np.flipud(coefficients), False) polyIntegral = poly.integ() polyC = NumCpp.Poly1d(coefficientsC, False) a, b = np.sort(np.random.rand(2) * 100 - 50) area = np.round(polyIntegral(b) - polyIntegral(a), NUM_DECIMALS_ROUND) areaC = np.round(NumCpp.integrate_romberg(polyC, a, b), NUM_DECIMALS_ROUND) # romberg is much less acurate so let's give it some leeway areaLow, areaHigh = np.sort([area * (1 - PERCENT_LEEWAY), area * (1 + PERCENT_LEEWAY)]) assert areaLow < areaC < areaHigh #################################################################################### def test_simpson(): numCoefficients = np.random.randint(2, 5, [1, ]).item() coefficients = np.random.randint(-20, 20, [numCoefficients, ]) coefficientsC = NumCpp.NdArray(1, numCoefficients) coefficientsC.setArray(coefficients) poly = np.poly1d(np.flipud(coefficients), False) polyIntegral = poly.integ() polyC = NumCpp.Poly1d(coefficientsC, False) a, b = np.sort(np.random.rand(2) * 100 - 50) area = np.round(polyIntegral(b) - polyIntegral(a), NUM_DECIMALS_ROUND) areaC = np.round(NumCpp.integrate_simpson(polyC, a, b), NUM_DECIMALS_ROUND) assert area == areaC #################################################################################### def test_trapazoidal(): numCoefficients = np.random.randint(2, 5, [1, ]).item() coefficients = np.random.randint(-20, 20, [numCoefficients, ]) coefficientsC = NumCpp.NdArray(1, numCoefficients) coefficientsC.setArray(coefficients) poly = np.poly1d(np.flipud(coefficients), False) polyIntegral = poly.integ() polyC = NumCpp.Poly1d(coefficientsC, False) a, b = np.sort(np.random.rand(2) * 100 - 50) area = np.round(polyIntegral(b) - polyIntegral(a), NUM_DECIMALS_ROUND) areaC = np.round(NumCpp.integrate_trapazoidal(polyC, a, b), NUM_DECIMALS_ROUND) assert area == areaC
1,236
348
{"nom":"Cours","circ":"3ème circonscription","dpt":"Lot-et-Garonne","inscrits":163,"abs":74,"votants":89,"blancs":4,"nuls":1,"exp":84,"res":[{"nuance":"REM","nom":"<NAME>","voix":51},{"nuance":"FN","nom":"M. <NAME>","voix":33}]}
94
852
<filename>RecoTracker/SpecialSeedGenerators/src/SimpleCosmicBONSeeder.cc // // Package: RecoTracker/TkSeedGenerator // Class: GlobalPixelLessSeedGenerator // // From CosmicSeedGenerator+SimpleCosmicBONSeeder, with changes by Giovanni // to seed Cosmics with B != 0 #include "RecoTracker/SpecialSeedGenerators/interface/SimpleCosmicBONSeeder.h" #include "DataFormats/TrackerRecHit2D/interface/SiStripMatchedRecHit2D.h" #include "DataFormats/TrackerRecHit2D/interface/SiStripRecHit2D.h" #include "FWCore/Utilities/interface/isFinite.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "TrackingTools/TransientTrackingRecHit/interface/SeedingLayerSetsHits.h" typedef SeedingHitSet::ConstRecHitPointer SeedingHit; #include <numeric> namespace { std::string seedingLayersToString(const SeedingLayerSetsHits::SeedingLayerSet &layer) { return layer[0].name() + "+" + layer[1].name() + "+" + layer[2].name(); } } // namespace using namespace std; SimpleCosmicBONSeeder::SimpleCosmicBONSeeder(edm::ParameterSet const &conf) : seedingLayerToken_(consumes<SeedingLayerSetsHits>(conf.getParameter<edm::InputTag>("TripletsSrc"))), magfieldToken_(esConsumes()), trackerToken_(esConsumes()), ttrhBuilderToken_(esConsumes(edm::ESInputTag("", conf.getParameter<std::string>("TTRHBuilder")))), writeTriplets_(conf.getParameter<bool>("writeTriplets")), seedOnMiddle_(conf.existsAs<bool>("seedOnMiddle") ? conf.getParameter<bool>("seedOnMiddle") : false), rescaleError_(conf.existsAs<double>("rescaleError") ? conf.getParameter<double>("rescaleError") : 1.0), tripletsVerbosity_(conf.getUntrackedParameter<uint32_t>("TripletsDebugLevel", 0)), seedVerbosity_(conf.getUntrackedParameter<uint32_t>("seedDebugLevel", 0)), helixVerbosity_(conf.getUntrackedParameter<uint32_t>("helixDebugLevel", 0)), check_(conf.getParameter<edm::ParameterSet>("ClusterCheckPSet"), consumesCollector()), maxTriplets_(conf.getParameter<int32_t>("maxTriplets")), maxSeeds_(conf.getParameter<int32_t>("maxSeeds")) { edm::ParameterSet regionConf = conf.getParameter<edm::ParameterSet>("RegionPSet"); float ptmin = regionConf.getParameter<double>("ptMin"); float originradius = regionConf.getParameter<double>("originRadius"); float halflength = regionConf.getParameter<double>("originHalfLength"); float originz = regionConf.getParameter<double>("originZPosition"); region_ = GlobalTrackingRegion(ptmin, originradius, halflength, originz); pMin_ = regionConf.getParameter<double>("pMin"); //***top-bottom positiveYOnly = conf.getParameter<bool>("PositiveYOnly"); negativeYOnly = conf.getParameter<bool>("NegativeYOnly"); //*** produces<TrajectorySeedCollection>(); if (writeTriplets_) produces<edm::OwnVector<TrackingRecHit>>("cosmicTriplets"); if (conf.existsAs<edm::ParameterSet>("ClusterChargeCheck")) { edm::ParameterSet cccc = conf.getParameter<edm::ParameterSet>("ClusterChargeCheck"); checkCharge_ = cccc.getParameter<bool>("checkCharge"); matchedRecHitUsesAnd_ = cccc.getParameter<bool>("matchedRecHitsUseAnd"); chargeThresholds_.resize(7, 0); edm::ParameterSet ccct = cccc.getParameter<edm::ParameterSet>("Thresholds"); chargeThresholds_[StripSubdetector::TIB] = ccct.getParameter<int32_t>("TIB"); chargeThresholds_[StripSubdetector::TID] = ccct.getParameter<int32_t>("TID"); chargeThresholds_[StripSubdetector::TOB] = ccct.getParameter<int32_t>("TOB"); chargeThresholds_[StripSubdetector::TEC] = ccct.getParameter<int32_t>("TEC"); } else { checkCharge_ = false; } if (conf.existsAs<edm::ParameterSet>("HitsPerModuleCheck")) { edm::ParameterSet hpmcc = conf.getParameter<edm::ParameterSet>("HitsPerModuleCheck"); checkMaxHitsPerModule_ = hpmcc.getParameter<bool>("checkHitsPerModule"); maxHitsPerModule_.resize(7, std::numeric_limits<int32_t>::max()); edm::ParameterSet hpmct = hpmcc.getParameter<edm::ParameterSet>("Thresholds"); maxHitsPerModule_[StripSubdetector::TIB] = hpmct.getParameter<int32_t>("TIB"); maxHitsPerModule_[StripSubdetector::TID] = hpmct.getParameter<int32_t>("TID"); maxHitsPerModule_[StripSubdetector::TOB] = hpmct.getParameter<int32_t>("TOB"); maxHitsPerModule_[StripSubdetector::TEC] = hpmct.getParameter<int32_t>("TEC"); } else { checkMaxHitsPerModule_ = false; } if (checkCharge_ || checkMaxHitsPerModule_) { goodHitsPerSeed_ = conf.getParameter<int32_t>("minimumGoodHitsInSeed"); } else { goodHitsPerSeed_ = 0; } } // Functions that gets called by framework every event void SimpleCosmicBONSeeder::produce(edm::Event &ev, const edm::EventSetup &es) { auto output = std::make_unique<TrajectorySeedCollection>(); auto outtriplets = std::make_unique<edm::OwnVector<TrackingRecHit>>(); magfield = &es.getData(magfieldToken_); if (magfield->inTesla(GlobalPoint(0, 0, 0)).mag() > 0.01) { size_t clustsOrZero = check_.tooManyClusters(ev); if (clustsOrZero) { edm::LogError("TooManyClusters") << "Found too many clusters (" << clustsOrZero << "), bailing out.\n"; } else { init(es); bool tripletsOk = triplets(ev); if (tripletsOk) { bool seedsOk = seeds(*output); if (!seedsOk) { } if (writeTriplets_) { for (OrderedHitTriplets::const_iterator it = hitTriplets.begin(); it != hitTriplets.end(); ++it) { const TrackingRecHit *hit1 = it->inner()->hit(); const TrackingRecHit *hit2 = it->middle()->hit(); const TrackingRecHit *hit3 = it->outer()->hit(); outtriplets->push_back(hit1->clone()); outtriplets->push_back(hit2->clone()); outtriplets->push_back(hit3->clone()); } } } done(); } } if (writeTriplets_) { ev.put(std::move(outtriplets), "cosmicTriplets"); } ev.put(std::move(output)); } void SimpleCosmicBONSeeder::init(const edm::EventSetup &iSetup) { tracker = &iSetup.getData(trackerToken_); cloner = dynamic_cast<TkTransientTrackingRecHitBuilder const &>(iSetup.getData(ttrhBuilderToken_)).cloner(); // FIXME: these should come from ES too!! thePropagatorAl = new PropagatorWithMaterial(alongMomentum, 0.1057, magfield); thePropagatorOp = new PropagatorWithMaterial(oppositeToMomentum, 0.1057, magfield); theUpdator = new KFUpdator(); } struct HigherInnerHit { bool operator()(const OrderedHitTriplet &trip1, const OrderedHitTriplet &trip2) const { //FIXME: inner gives a SEGV #if 0 //const SeedingHitSet::ConstRecHitPointer &ihit1 = trip1.inner(); //const SeedingHitSet::ConstRecHitPointer &ihit2 = trip2.inner(); const SeedingHitSet::ConstRecHitPointer &ihit1 = trip1.middle(); const SeedingHitSet::ConstRecHitPointer &ihit2 = trip2.middle(); const SeedingHitSet::ConstRecHitPointer &ohit1 = trip1.outer(); const SeedingHitSet::ConstRecHitPointer &ohit2 = trip2.outer(); #endif SeedingHitSet::ConstRecHitPointer ihit1 = trip1.inner(); SeedingHitSet::ConstRecHitPointer ihit2 = trip2.inner(); SeedingHitSet::ConstRecHitPointer ohit1 = trip1.outer(); SeedingHitSet::ConstRecHitPointer ohit2 = trip2.outer(); float iy1 = ihit1->globalPosition().y(); float oy1 = ohit1->globalPosition().y(); float iy2 = ihit2->globalPosition().y(); float oy2 = ohit2->globalPosition().y(); if (oy1 - iy1 > 0) { // 1 Downgoing if (oy2 - iy2 > 0) { // 2 Downgoing // sort by inner, or by outer if inners are the same return (iy1 != iy2 ? (iy1 > iy2) : (oy1 > oy2)); } else return true; // else prefer downgoing } else if (oy2 - iy2 > 0) { return false; // prefer downgoing } else { // both upgoing // sort by inner, or by outer return (iy1 != iy2 ? (iy1 < iy2) : (oy1 < oy2)); } } }; bool SimpleCosmicBONSeeder::triplets(const edm::Event &e) { hitTriplets.clear(); hitTriplets.reserve(0); edm::Handle<SeedingLayerSetsHits> hlayers; e.getByToken(seedingLayerToken_, hlayers); const SeedingLayerSetsHits &layers = *hlayers; if (layers.numberOfLayersInSet() != 3) throw cms::Exception("CtfSpecialSeedGenerator") << "You are using " << layers.numberOfLayersInSet() << " layers in set instead of 3 "; double minRho = region_.ptMin() / (0.003 * magfield->inTesla(GlobalPoint(0, 0, 0)).z()); for (SeedingLayerSetsHits::LayerSetIndex layerIndex = 0; layerIndex < layers.size(); ++layerIndex) { SeedingLayerSetsHits::SeedingLayerSet ls = layers[layerIndex]; /// ctfseeding SeedinHits and their iterators auto innerHits = region_.hits(ls[0]); auto middleHits = region_.hits(ls[1]); auto outerHits = region_.hits(ls[2]); if (tripletsVerbosity_ > 0) { std::cout << "GenericTripletGenerator iLss = " << seedingLayersToString(ls) << " (" << layerIndex << "): # = " << innerHits.size() << "/" << middleHits.size() << "/" << outerHits.size() << std::endl; } /// Transient Tracking RecHits (not anymore....) typedef SeedingHitSet::ConstRecHitPointer TTRH; std::vector<TTRH> innerTTRHs, middleTTRHs, outerTTRHs; /// Checks on the cluster charge and on noisy modules std::vector<bool> innerOk(innerHits.size(), true); std::vector<bool> middleOk(middleHits.size(), true); std::vector<bool> outerOk(outerHits.size(), true); size_t sizBefore = hitTriplets.size(); /// Now actually filling in the charges for all the clusters int idx = 0; for (auto iOuterHit = outerHits.begin(); iOuterHit != outerHits.end(); ++idx, ++iOuterHit) { outerTTRHs.push_back(&(**iOuterHit)); if (checkCharge_ && !checkCharge(outerTTRHs.back()->hit())) outerOk[idx] = false; } idx = 0; for (auto iMiddleHit = middleHits.begin(); iMiddleHit != middleHits.end(); ++idx, ++iMiddleHit) { middleTTRHs.push_back(&(**iMiddleHit)); if (checkCharge_ && !checkCharge(middleTTRHs.back()->hit())) middleOk[idx] = false; } idx = 0; for (auto iInnerHit = innerHits.begin(); iInnerHit != innerHits.end(); ++idx, ++iInnerHit) { innerTTRHs.push_back(&(**iInnerHit)); if (checkCharge_ && !checkCharge(innerTTRHs.back()->hit())) innerOk[idx] = false; } if (checkMaxHitsPerModule_) { checkNoisyModules(innerTTRHs, innerOk); checkNoisyModules(middleTTRHs, middleOk); checkNoisyModules(outerTTRHs, outerOk); } for (auto iOuterHit = outerHits.begin(); iOuterHit != outerHits.end(); iOuterHit++) { idx = iOuterHit - outerHits.begin(); TTRH &outerTTRH = outerTTRHs[idx]; GlobalPoint outerpos = outerTTRH->globalPosition(); // this caches by itself bool outerok = outerOk[idx]; if (outerok < goodHitsPerSeed_ - 2) { if (tripletsVerbosity_ > 2) std::cout << "Skipping at first hit: " << (outerok) << " < " << (goodHitsPerSeed_ - 2) << std::endl; continue; } for (auto iMiddleHit = middleHits.begin(); iMiddleHit != middleHits.end(); iMiddleHit++) { idx = iMiddleHit - middleHits.begin(); TTRH &middleTTRH = middleTTRHs[idx]; GlobalPoint middlepos = middleTTRH->globalPosition(); // this caches by itself bool middleok = middleOk[idx]; if (outerok + middleok < goodHitsPerSeed_ - 1) { if (tripletsVerbosity_ > 2) std::cout << "Skipping at second hit: " << (outerok + middleok) << " < " << (goodHitsPerSeed_ - 1) << std::endl; continue; } for (auto iInnerHit = innerHits.begin(); iInnerHit != innerHits.end(); iInnerHit++) { idx = iInnerHit - innerHits.begin(); TTRH &innerTTRH = innerTTRHs[idx]; GlobalPoint innerpos = innerTTRH->globalPosition(); // this caches by itself bool innerok = innerOk[idx]; if (outerok + middleok + innerok < goodHitsPerSeed_) { if (tripletsVerbosity_ > 2) std::cout << "Skipping at third hit: " << (outerok + middleok + innerok) << " < " << (goodHitsPerSeed_) << std::endl; continue; } //***top-bottom if (positiveYOnly && (innerpos.y() < 0 || middlepos.y() < 0 || outerpos.y() < 0 || outerpos.y() < innerpos.y())) continue; if (negativeYOnly && (innerpos.y() > 0 || middlepos.y() > 0 || outerpos.y() > 0 || outerpos.y() > innerpos.y())) continue; //*** if (tripletsVerbosity_ > 2) std::cout << "Trying seed with: " << innerpos << " + " << middlepos << " + " << outerpos << std::endl; if (goodTriplet(innerpos, middlepos, outerpos, minRho)) { OrderedHitTriplet oht(&(**iInnerHit), &(**iMiddleHit), &(**iOuterHit)); hitTriplets.push_back(oht); if ((maxTriplets_ > 0) && (hitTriplets.size() > size_t(maxTriplets_))) { hitTriplets.clear(); // clear //OrderedHitTriplets().swap(hitTriplets); // really clear edm::LogError("TooManyTriplets") << "Found too many triplets, bailing out.\n"; return false; } if (tripletsVerbosity_ > 3) { std::cout << " accepted seed #" << (hitTriplets.size() - 1) << " w/: " << innerpos << " + " << middlepos << " + " << outerpos << std::endl; } if (tripletsVerbosity_ == 2) { std::cout << " good seed #" << (hitTriplets.size() - 1) << " w/: " << innerpos << " + " << middlepos << " + " << outerpos << std::endl; } if (tripletsVerbosity_ > 3 && (helixVerbosity_ > 0)) { // debug the momentum here too pqFromHelixFit(innerpos, middlepos, outerpos); } } } } } if ((tripletsVerbosity_ > 0) && (hitTriplets.size() > sizBefore)) { std::cout << " iLss = " << seedingLayersToString(ls) << " (" << layerIndex << "): # = " << innerHits.size() << "/" << middleHits.size() << "/" << outerHits.size() << ": Found " << (hitTriplets.size() - sizBefore) << " seeds [running total: " << hitTriplets.size() << "]" << std::endl; } } std::sort(hitTriplets.begin(), hitTriplets.end(), HigherInnerHit()); return true; } bool SimpleCosmicBONSeeder::checkCharge(const TrackingRecHit *hit) const { DetId detid(hit->geographicalId()); if (detid.det() != DetId::Tracker) return false; // should not happen int subdet = detid.subdetId(); if (subdet < 3) { // pixel return true; } else { if (typeid(*hit) == typeid(SiStripMatchedRecHit2D)) { const SiStripMatchedRecHit2D *mhit = static_cast<const SiStripMatchedRecHit2D *>(hit); if (matchedRecHitUsesAnd_) { return checkCharge(mhit->monoHit(), subdet) && checkCharge(mhit->stereoHit(), subdet); } else { return checkCharge(mhit->monoHit(), subdet) || checkCharge(mhit->stereoHit(), subdet); } } else if (typeid(*hit) == typeid(SiStripRecHit2D)) { return checkCharge(static_cast<const SiStripRecHit2D &>(*hit), subdet); } else { return true; } } } // to be fixed to use OmniCluster bool SimpleCosmicBONSeeder::checkCharge(const SiStripRecHit2D &hit, int subdetid) const { const SiStripCluster *clust = hit.cluster().get(); int charge = std::accumulate(clust->amplitudes().begin(), clust->amplitudes().end(), int(0)); if (tripletsVerbosity_ > 1) { std::cerr << "Hit on " << subdetid << ", charge = " << charge << ", threshold = " << chargeThresholds_[subdetid] << ", detid = " << hit.geographicalId().rawId() << ", firstStrip = " << clust->firstStrip() << std::endl; } else if ((tripletsVerbosity_ == 1) && (charge < chargeThresholds_[subdetid])) { std::cerr << "Hit on " << subdetid << ", charge = " << charge << ", threshold = " << chargeThresholds_[subdetid] << ", detid = " << hit.geographicalId().rawId() << ", firstStrip = " << clust->firstStrip() << std::endl; } return charge > chargeThresholds_[subdetid]; } void SimpleCosmicBONSeeder::checkNoisyModules(const std::vector<SeedingHitSet::ConstRecHitPointer> &hits, std::vector<bool> &oks) const { typedef SeedingHitSet::ConstRecHitPointer TTRH; std::vector<TTRH>::const_iterator it = hits.begin(), start = it, end = hits.end(); std::vector<bool>::iterator ok = oks.begin(), okStart = ok; while (start < end) { DetId lastid = (*start)->geographicalId(); for (it = start + 1; (it < end) && ((*it)->geographicalId() == lastid); ++it) { ++ok; } if ((it - start) > maxHitsPerModule_[lastid.subdetId()]) { if (tripletsVerbosity_ > 0) { std::cerr << "SimpleCosmicBONSeeder: Marking noisy module " << lastid.rawId() << ", it has " << (it - start) << " rechits" << " (threshold is " << maxHitsPerModule_[lastid.subdetId()] << ")" << std::endl; } std::fill(okStart, ok, false); } else if (tripletsVerbosity_ > 0) { if ((it - start) > std::min(4, maxHitsPerModule_[lastid.subdetId()] / 4)) { std::cerr << "SimpleCosmicBONSeeder: Not marking noisy module " << lastid.rawId() << ", it has " << (it - start) << " rechits" << " (threshold is " << maxHitsPerModule_[lastid.subdetId()] << ")" << std::endl; } } start = it; okStart = ok; } } bool SimpleCosmicBONSeeder::goodTriplet(const GlobalPoint &inner, const GlobalPoint &middle, const GlobalPoint &outer, const double &minRho) const { float dyOM = outer.y() - middle.y(), dyIM = inner.y() - middle.y(); if ((dyOM * dyIM > 0) && (fabs(dyOM) > 10) && (fabs(dyIM) > 10)) { if (tripletsVerbosity_ > 2) std::cout << " fail for non coherent dy" << std::endl; return false; } float dzOM = outer.z() - middle.z(), dzIM = inner.z() - middle.z(); if ((dzOM * dzIM > 0) && (fabs(dzOM) > 50) && (fabs(dzIM) > 50)) { if (tripletsVerbosity_ > 2) std::cout << " fail for non coherent dz" << std::endl; return false; } if (minRho > 0) { FastCircle theCircle(inner, middle, outer); if (theCircle.rho() < minRho) { if (tripletsVerbosity_ > 2) std::cout << " fail for pt cut" << std::endl; return false; } } return true; } std::pair<GlobalVector, int> SimpleCosmicBONSeeder::pqFromHelixFit(const GlobalPoint &inner, const GlobalPoint &middle, const GlobalPoint &outer) const { if (helixVerbosity_ > 0) { std::cout << "DEBUG PZ =====" << std::endl; FastHelix helix(inner, middle, outer, magfield->nominalValue(), &*magfield); GlobalVector gv = helix.stateAtVertex().momentum(); // status on inner hit std::cout << "FastHelix P = " << gv << "\n"; std::cout << "FastHelix Q = " << helix.stateAtVertex().charge() << "\n"; } // My attempt (with different approx from FastHelix) // 1) fit the circle FastCircle theCircle(inner, middle, outer); double rho = theCircle.rho(); // 2) Get the PT GlobalVector tesla = magfield->inTesla(middle); double pt = 0.01 * rho * (0.3 * tesla.z()); // 3) Get the PX,PY at OUTER hit (VERTEX) double dx1 = outer.x() - theCircle.x0(); double dy1 = outer.y() - theCircle.y0(); double py = pt * dx1 / rho, px = -pt * dy1 / rho; if (px * (middle.x() - outer.x()) + py * (middle.y() - outer.y()) < 0.) { px *= -1.; py *= -1.; } // 4) Get the PZ through pz = pT*(dz/d(R*phi))) double dz = inner.z() - outer.z(); double sinphi = (dx1 * (inner.y() - theCircle.y0()) - dy1 * (inner.x() - theCircle.x0())) / (rho * rho); double dphi = std::abs(std::asin(sinphi)); double pz = pt * dz / (dphi * rho); int myq = ((theCircle.x0() * py - theCircle.y0() * px) / tesla.z()) > 0. ? +1 : -1; std::pair<GlobalVector, int> mypq(GlobalVector(px, py, pz), myq); if (helixVerbosity_ > 1) { std::cout << "Gio: pt = " << pt << std::endl; std::cout << "Gio: dz = " << dz << ", sinphi = " << sinphi << ", dphi = " << dphi << ", dz/drphi = " << (dz / dphi / rho) << std::endl; } if (helixVerbosity_ > 0) { std::cout << "Gio's fit P = " << mypq.first << "\n"; std::cout << "Gio's fit Q = " << myq << "\n"; } return mypq; } bool SimpleCosmicBONSeeder::seeds(TrajectorySeedCollection &output) { typedef TrajectoryStateOnSurface TSOS; for (size_t it = 0; it < hitTriplets.size(); it++) { OrderedHitTriplet &trip = hitTriplets.at(it); GlobalPoint inner = tracker->idToDet((*(trip.inner())).geographicalId())->surface().toGlobal((*(trip.inner())).localPosition()); GlobalPoint middle = tracker->idToDet((*(trip.middle())).geographicalId())->surface().toGlobal((*(trip.middle())).localPosition()); GlobalPoint outer = tracker->idToDet((*(trip.outer())).geographicalId())->surface().toGlobal((*(trip.outer())).localPosition()); if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ": " << inner << " + " << middle << " + " << outer << std::endl; if ((outer.y() - inner.y()) * outer.y() < 0) { std::swap(inner, outer); trip = OrderedHitTriplet(trip.outer(), trip.middle(), trip.inner()); if (seedVerbosity_ > 1) { std::cout << "The seed was going away from CMS! swapped in <-> out" << std::endl; std::cout << "Processing swapped triplet " << it << ": " << inner << " + " << middle << " + " << outer << std::endl; } } // First use FastHelix out of the box std::pair<GlobalVector, int> pq = pqFromHelixFit(inner, middle, outer); GlobalVector gv = pq.first; float ch = pq.second; float Mom = sqrt(gv.x() * gv.x() + gv.y() * gv.y() + gv.z() * gv.z()); if (Mom > 10000 || edm::isNotFinite(Mom)) { if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ": fail for momentum." << std::endl; continue; } if (gv.perp() < region_.ptMin()) { if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ": fail for pt = " << gv.perp() << " < ptMin = " << region_.ptMin() << std::endl; continue; } const Propagator *propagator = nullptr; if ((outer.y() - inner.y()) > 0) { if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ": downgoing." << std::endl; propagator = thePropagatorAl; } else { gv = -1 * gv; ch = -1. * ch; propagator = thePropagatorOp; if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ": upgoing." << std::endl; } if (seedVerbosity_ > 1) { if ((gv.z() * (outer.z() - inner.z()) > 0) && (fabs(outer.z() - inner.z()) > 5) && (fabs(gv.z()) > .01)) { std::cout << "ORRORE: outer.z()-inner.z() = " << (outer.z() - inner.z()) << ", gv.z() = " << gv.z() << std::endl; } } GlobalTrajectoryParameters Gtp(outer, gv, int(ch), &(*magfield)); FreeTrajectoryState CosmicSeed(Gtp, CurvilinearTrajectoryError(AlgebraicSymMatrix55(AlgebraicMatrixID()))); CosmicSeed.rescaleError(100); if (seedVerbosity_ > 2) { std::cout << "Processing triplet " << it << ". start from " << std::endl; std::cout << " X = " << outer << ", P = " << gv << std::endl; std::cout << " Cartesian error (X,P) = \n" << CosmicSeed.cartesianError().matrix() << std::endl; } edm::OwnVector<TrackingRecHit> hits; OrderedHitTriplet seedHits(trip.outer(), trip.middle(), trip.inner()); TSOS propagated, updated; bool fail = false; for (size_t ih = 0; ih < 3; ++ih) { if ((ih == 2) && seedOnMiddle_) { if (seedVerbosity_ > 2) std::cout << "Stopping at middle hit, as requested." << std::endl; break; } if (seedVerbosity_ > 2) std::cout << "Processing triplet " << it << ", hit " << ih << "." << std::endl; if (ih == 0) { propagated = propagator->propagate(CosmicSeed, tracker->idToDet((*seedHits[ih]).geographicalId())->surface()); } else { propagated = propagator->propagate(updated, tracker->idToDet((*seedHits[ih]).geographicalId())->surface()); } if (!propagated.isValid()) { if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ", hit " << ih << ": failed propagation." << std::endl; fail = true; break; } else { if (seedVerbosity_ > 2) std::cout << "Processing triplet " << it << ", hit " << ih << ": propagated state = " << propagated; } SeedingHitSet::ConstRecHitPointer tthp = seedHits[ih]; auto newtth = static_cast<SeedingHitSet::RecHitPointer>(cloner(*tthp, propagated)); updated = theUpdator->update(propagated, *newtth); hits.push_back(newtth); if (!updated.isValid()) { if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ", hit " << ih << ": failed update." << std::endl; fail = true; break; } else { if (seedVerbosity_ > 2) std::cout << "Processing triplet " << it << ", hit " << ih << ": updated state = " << updated; } } if (!fail && updated.isValid() && (updated.globalMomentum().perp() < region_.ptMin())) { if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ": failed for final pt " << updated.globalMomentum().perp() << " < " << region_.ptMin() << std::endl; fail = true; } if (!fail && updated.isValid() && (updated.globalMomentum().mag() < pMin_)) { if (seedVerbosity_ > 1) std::cout << "Processing triplet " << it << ": failed for final p " << updated.globalMomentum().perp() << " < " << pMin_ << std::endl; fail = true; } if (!fail) { if (rescaleError_ != 1.0) { if (seedVerbosity_ > 2) { std::cout << "Processing triplet " << it << ", rescale error by " << rescaleError_ << ": state BEFORE rescaling " << updated; std::cout << " Cartesian error (X,P) before rescaling= \n" << updated.cartesianError().matrix() << std::endl; } updated.rescaleError(rescaleError_); } if (seedVerbosity_ > 0) { std::cout << "Processed triplet " << it << ": success (saved as #" << output.size() << ") : " << inner << " + " << middle << " + " << outer << std::endl; std::cout << " pt = " << updated.globalMomentum().perp() << " eta = " << updated.globalMomentum().eta() << " phi = " << updated.globalMomentum().phi() << " ch = " << updated.charge() << std::endl; if (seedVerbosity_ > 1) { std::cout << " State:" << updated; } else { std::cout << " X = " << updated.globalPosition() << ", P = " << updated.globalMomentum() << std::endl; } std::cout << " Cartesian error (X,P) = \n" << updated.cartesianError().matrix() << std::endl; } PTrajectoryStateOnDet const &PTraj = trajectoryStateTransform::persistentState( updated, (*(seedOnMiddle_ ? trip.middle() : trip.inner())).geographicalId().rawId()); output.push_back(TrajectorySeed(PTraj, hits, ((outer.y() - inner.y() > 0) ? alongMomentum : oppositeToMomentum))); if ((maxSeeds_ > 0) && (output.size() > size_t(maxSeeds_))) { output.clear(); edm::LogError("TooManySeeds") << "Found too many seeds, bailing out.\n"; return false; } } } return true; } void SimpleCosmicBONSeeder::done() { delete thePropagatorAl; delete thePropagatorOp; delete theUpdator; }
12,148
2,113
<reponame>vbillet/Torque3D /* * Copyright 2006 Sony Computer Entertainment Inc. * * Licensed under the SCEA Shared Source License, Version 1.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://research.scea.com/scea_shared_source_license.html * * 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 <dae.h> #include <dae/daeDom.h> #include <dom/domGlsl_setparam.h> #include <dae/daeMetaCMPolicy.h> #include <dae/daeMetaSequence.h> #include <dae/daeMetaChoice.h> #include <dae/daeMetaGroup.h> #include <dae/daeMetaAny.h> #include <dae/daeMetaElementAttribute.h> daeElementRef domGlsl_setparam::create(DAE& dae) { domGlsl_setparamRef ref = new domGlsl_setparam(dae); return ref; } daeMetaElement * domGlsl_setparam::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "glsl_setparam" ); meta->registerClass(domGlsl_setparam::create); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementArrayAttribute( meta, cm, 0, 0, -1 ); mea->setName( "annotate" ); mea->setOffset( daeOffsetOf(domGlsl_setparam,elemAnnotate_array) ); mea->setElementType( domFx_annotate_common::registerElement(dae) ); cm->appendChild( mea ); cm = new daeMetaChoice( meta, cm, 0, 1, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "glsl_param_type" ); mea->setOffset( daeOffsetOf(domGlsl_setparam,elemGlsl_param_type) ); mea->setElementType( domGlsl_param_type::registerElement(dae) ); cm->appendChild( new daeMetaGroup( mea, meta, cm, 0, 1, 1 ) ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "array" ); mea->setOffset( daeOffsetOf(domGlsl_setparam,elemArray) ); mea->setElementType( domGlsl_setarray_type::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 1 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domGlsl_setparam,_contents)); meta->addContentsOrder(daeOffsetOf(domGlsl_setparam,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domGlsl_setparam,_CMData), 1); // Add attribute: ref { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "ref" ); ma->setType( dae.getAtomicTypes().get("Glsl_identifier")); ma->setOffset( daeOffsetOf( domGlsl_setparam , attrRef )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: program { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "program" ); ma->setType( dae.getAtomicTypes().get("xsNCName")); ma->setOffset( daeOffsetOf( domGlsl_setparam , attrProgram )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domGlsl_setparam)); meta->validate(); return meta; }
1,250
1,962
<reponame>appotry/blog_demos package com.bolingcavalry.minusservice.service.impl; import com.bolingcavalry.api.exception.MinusException; import com.bolingcavalry.api.service.MinusService; /** * @author wilzhao * @description 减法服务的实现,不支持负数 * @email <EMAIL> * @time 2018/10/13 14:24 */ public class MinusServiceNotSupportNegativeImpl implements MinusService { /** * 减法运算,不支持负数结果,如果被减数小于减数,就跑出MinusException * @param minuend 被减数 * @param subtraction 减数 * @return * @throws MinusException */ public int minus(int minuend, int subtraction) throws MinusException { if(subtraction>minuend){ throw new MinusException("not support negative!"); } return minuend-subtraction; } }
416
19,438
<gh_stars>1000+ /* * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include "Symbols.h" #include <AK/Types.h> namespace Video::VP9 { enum FrameType { KeyFrame, NonKeyFrame }; enum ColorSpace : u8 { Unknown = 0, Bt601 = 1, Bt709 = 2, Smpte170 = 3, Smpte240 = 4, Bt2020 = 5, Reserved = 6, RGB = 7 }; enum ColorRange { StudioSwing, FullSwing }; enum InterpolationFilter : u8 { EightTap = 0, EightTapSmooth = 1, EightTapSharp = 2, Bilinear = 3, Switchable = 4 }; enum ReferenceFrame : u8 { // 0 is both INTRA_FRAME and NONE because the value's meaning changes depending on which index they're in on the ref_frame array None = 0, IntraFrame = 0, LastFrame = 1, GoldenFrame = 2, AltRefFrame = 3, }; enum TXMode : u8 { Only_4x4 = 0, Allow_8x8 = 1, Allow_16x16 = 2, Allow_32x32 = 3, TXModeSelect = 4, }; enum TXSize : u8 { TX_4x4 = 0, TX_8x8 = 1, TX_16x16 = 2, TX_32x32 = 3, }; enum ReferenceMode : u8 { SingleReference = 0, CompoundReference = 1, ReferenceModeSelect = 2, }; enum BlockSubsize : u8 { Block_4x4 = 0, Block_4x8 = 1, Block_8x4 = 2, Block_8x8 = 3, Block_8x16 = 4, Block_16x8 = 5, Block_16x16 = 6, Block_16x32 = 7, Block_32x16 = 8, Block_32x32 = 9, Block_32x64 = 10, Block_64x32 = 11, Block_64x64 = 12, Block_Invalid = BLOCK_INVALID }; enum Partition : u8 { PartitionNone = 0, PartitionHorizontal = 1, PartitionVertical = 2, PartitionSplit = 3, }; enum IntraMode : u8 { DcPred = 0, VPred = 1, HPred = 2, D45Pred = 3, D135Pred = 4, D117Pred = 5, D153Pred = 6, D207Pred = 7, D63Pred = 8, TmPred = 9, }; enum InterMode : u8 { NearestMv = 0, NearMv = 1, ZeroMv = 2, NewMv = 3, }; enum MvJoint : u8 { MvJointZero = 0, MvJointHnzvz = 1, MvJointHzvnz = 2, MvJointHnzvnz = 3, }; enum MvClass : u8 { MvClass0 = 0, MvClass1 = 1, MvClass2 = 2, MvClass3 = 3, MvClass4 = 4, MvClass5 = 5, MvClass6 = 6, MvClass7 = 7, MvClass8 = 8, MvClass9 = 9, MvClass10 = 10, }; enum Token : u8 { ZeroToken = 0, OneToken = 1, TwoToken = 2, ThreeToken = 3, FourToken = 4, DctValCat1 = 5, DctValCat2 = 6, DctValCat3 = 7, DctValCat4 = 8, DctValCat5 = 9, DctValCat6 = 10, }; }
1,264
2,151
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.app; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.DialogFragment; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import com.android.internal.R; /** * Shows a dialog with actions to take on a chooser target */ public class ResolverTargetActionsDialogFragment extends DialogFragment implements DialogInterface.OnClickListener { private static final String NAME_KEY = "componentName"; private static final String PINNED_KEY = "pinned"; private static final String TITLE_KEY = "title"; // Sync with R.array.resolver_target_actions_* resources private static final int TOGGLE_PIN_INDEX = 0; private static final int APP_INFO_INDEX = 1; public ResolverTargetActionsDialogFragment() { } public ResolverTargetActionsDialogFragment(CharSequence title, ComponentName name, boolean pinned) { Bundle args = new Bundle(); args.putCharSequence(TITLE_KEY, title); args.putParcelable(NAME_KEY, name); args.putBoolean(PINNED_KEY, pinned); setArguments(args); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Bundle args = getArguments(); final int itemRes = args.getBoolean(PINNED_KEY, false) ? R.array.resolver_target_actions_unpin : R.array.resolver_target_actions_pin; return new Builder(getContext()) .setCancelable(true) .setItems(itemRes, this) .setTitle(args.getCharSequence(TITLE_KEY)) .create(); } @Override public void onClick(DialogInterface dialog, int which) { final Bundle args = getArguments(); ComponentName name = args.getParcelable(NAME_KEY); switch (which) { case TOGGLE_PIN_INDEX: SharedPreferences sp = ChooserActivity.getPinnedSharedPrefs(getContext()); final String key = name.flattenToString(); boolean currentVal = sp.getBoolean(name.flattenToString(), false); if (currentVal) { sp.edit().remove(key).apply(); } else { sp.edit().putBoolean(key, true).apply(); } // Force the chooser to requery and resort things getActivity().recreate(); break; case APP_INFO_INDEX: Intent in = new Intent().setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) .setData(Uri.fromParts("package", name.getPackageName(), null)) .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); startActivity(in); break; } dismiss(); } }
1,435
1,609
<filename>Code/GraphMol/PartialCharges/Wrap/rdPartialCharges.cpp // $Id$ // // Copyright (C) 2003-2006 Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <RDBoost/python.h> #include <GraphMol/GraphMol.h> #include <RDBoost/Wrap.h> #include <GraphMol/PartialCharges/GasteigerCharges.h> namespace python = boost::python; namespace RDKit { void ComputeGasteigerCharges(const ROMol &mol, int nIter, bool throwOnParamFailure) { computeGasteigerCharges(&mol, nIter, throwOnParamFailure); } } // namespace RDKit BOOST_PYTHON_MODULE(rdPartialCharges) { python::scope().attr("__doc__") = "Module containing functions to set partial charges - currently " "Gasteiger Charges"; std::string docString = "Compute Gasteiger partial charges for molecule\n\n\ The charges are computed using an iterative procedure presented in \n\ \n\ Ref : J.Gasteiger, <NAME>, Iterative Equalization of Oribital Electronegatiity \n\ A Rapid Access to Atomic Charges, Tetrahedron Vol 36 p3219 1980\n\ \n\ The computed charges are stored on each atom are stored a computed property ( under the name \n\ _GasteigerCharge). In addition, each atom also stored the total charge for the implicit hydrogens \n\ on the atom (under the property name _GasteigerHCharge)\n\ \n\ ARGUMENTS:\n\n\ - mol : the molecule of interrest\n\ - nIter : number of iteration (defaults to 12)\n\ - throwOnParamFailure : toggles whether or not an exception should be raised if parameters\n\ for an atom cannot be found. If this is false (the default), all parameters for unknown\n\ atoms will be set to zero. This has the effect of removing that atom from the iteration.\n\n"; python::def("ComputeGasteigerCharges", RDKit::ComputeGasteigerCharges, (python::arg("mol"), python::arg("nIter") = 12, python::arg("throwOnParamFailure") = false), docString.c_str()); }
734
507
# terrascript/mysql/__init__.py import terrascript class mysql(terrascript.Provider): pass
33
335
<reponame>Safal08/Hacktoberfest-1 { "word": "Doctrinaire", "definitions": [ "Seeking to impose a doctrine in all circumstances without regard to practical considerations." ], "parts-of-speech": "Adjective" }
87
779
<reponame>Kudesnick/atlassian-python-api<gh_stars>100-1000 """ Bitbucket Cloud common package """
33
460
<filename>trunk/win/Source/Includes/QtIncludes/src/3rdparty/webkit/WebCore/platform/StaticConstructors.h /* * Copyright (C) 2006 Apple Computer, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef StaticConstructors_h #define StaticConstructors_h // For WebCore we need to avoid having static constructors. We achieve this // with two separate methods for GCC and MSVC. Both methods prevent the static // initializers from being registered and called on program startup. On GCC, we // declare the global objects with a different type that can be POD default // initialized by the linker/loader. On MSVC we use a special compiler feature // to have the CRT ignore our static initializers. The constructors will never // be called and the objects will be left uninitialized. // // With both of these approaches, we must define and explicitly call an init // routine that uses placement new to create the objects and overwrite the // uninitialized placeholders. // // This is not completely portable, but is what we have for now without // changing how a lot of code accesses these global objects. #ifdef SKIP_STATIC_CONSTRUCTORS_ON_MSVC // - Assume that all includes of this header want ALL of their static // initializers ignored. This is currently the case. This means that if // a .cc includes this header (or it somehow gets included), all static // initializers after the include will not be executed. // - We do this with a pragma, so that all of the static initializer pointers // go into our own section, and the CRT won't call them. Eventually it would // be nice if the section was discarded, because we don't want the pointers. // See: http://msdn.microsoft.com/en-us/library/7977wcck(VS.80).aspx #pragma warning(disable:4075) #pragma init_seg(".unwantedstaticinits") #endif #ifndef SKIP_STATIC_CONSTRUCTORS_ON_GCC // Define an global in the normal way. #if COMPILER(MSVC7_OR_LOWER) #define DEFINE_GLOBAL(type, name) \ const type name; #elif COMPILER(WINSCW) #define DEFINE_GLOBAL(type, name, arg...) \ const type name; #else #define DEFINE_GLOBAL(type, name, ...) \ const type name; #endif #else // Define an correctly-sized array of pointers to avoid static initialization. // Use an array of pointers instead of an array of char in case there is some alignment issue. #if COMPILER(MSVC7_OR_LOWER) #define DEFINE_GLOBAL(type, name) \ void * name[(sizeof(type) + sizeof(void *) - 1) / sizeof(void *)]; #elif COMPILER(WINSCW) #define DEFINE_GLOBAL(type, name, arg...) \ void * name[(sizeof(type) + sizeof(void *) - 1) / sizeof(void *)]; #else #define DEFINE_GLOBAL(type, name, ...) \ void * name[(sizeof(type) + sizeof(void *) - 1) / sizeof(void *)]; #endif #endif #endif // StaticConstructors_h
1,108
335
{ "word": "Grant", "definitions": [ "Agree to give or allow (something requested) to.", "Give (a right, power, property, etc.) formally or legally to.", "Agree or admit to (someone) that (something) is true." ], "parts-of-speech": "Verb" }
112
11,699
#include <unordered_map> #include "taichi/common/core.h" TI_NAMESPACE_BEGIN class Statistics { public: using value_type = float64; using counters_map = std::unordered_map<std::string, value_type>; Statistics() = default; void add(std::string key, value_type value = value_type(1)); void print(std::string *output = nullptr); void clear(); inline const counters_map &get_counters() { return counters_; } private: counters_map counters_; }; extern Statistics stat; TI_NAMESPACE_END
177
1,056
<reponame>timfel/netbeans<filename>enterprise/j2ee.ddloaders/src/org/netbeans/modules/j2ee/ddloaders/web/multiview/WelcomeFilesPanel.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.j2ee.ddloaders.web.multiview; import org.netbeans.modules.j2ee.dd.api.web.*; import org.netbeans.modules.j2ee.ddloaders.web.*; import org.netbeans.modules.xml.multiview.ui.*; import org.netbeans.api.project.SourceGroup; /** * @author mkuchtiak */ public class WelcomeFilesPanel extends SectionInnerPanel { DDDataObject dObj; /** Creates new form JspPGPanel */ public WelcomeFilesPanel(SectionView sectionView, DDDataObject dObj) { super(sectionView); this.dObj=dObj; initComponents(); addModifier(wfTF); // welcome files initialization getWelcomeFiles(); LinkButton linkButton = new LinkButton(this, null,null); org.openide.awt.Mnemonics.setLocalizedText(linkButton, org.openide.util.NbBundle.getMessage(WelcomeFilesPanel.class, "LBL_goToSources")); java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(6, 0, 0, 0); add(linkButton, gridBagConstraints); } public javax.swing.JComponent getErrorComponent(String errorId) { return wfTF; } /** This will be called before model is changed from this panel */ @Override protected void startUIChange() { dObj.setChangedFromUI(true); } /** This will be called after model is changed from this panel */ @Override protected void endUIChange() { dObj.modelUpdatedFromUI(); dObj.setChangedFromUI(false); } public void setValue(javax.swing.JComponent source, Object value) { WebApp webApp = dObj.getWebApp(); String text = (String)value; setWelcomeFiles(webApp,text); } private void setWelcomeFiles(WebApp webApp, String text) { if (text.length()==0) { webApp.setWelcomeFileList(null); } else { java.util.List wfList = new java.util.ArrayList(); java.util.StringTokenizer tok = new java.util.StringTokenizer(text,","); while (tok.hasMoreTokens()) { String wf = tok.nextToken().trim(); if (wf.length()>0 && !wfList.contains(wf)) wfList.add(wf); } if (wfList.size()==0) { try { WelcomeFileList welcomeFileList = (WelcomeFileList)webApp.createBean("WelcomeFileList"); //NOI18N webApp.setWelcomeFileList(welcomeFileList); } catch (ClassNotFoundException ex) {} } else { String[] welcomeFiles = new String[wfList.size()]; wfList.toArray(welcomeFiles); WelcomeFileList welcomeFileList = webApp.getSingleWelcomeFileList(); if (welcomeFileList==null) { try { welcomeFileList = (WelcomeFileList)webApp.createBean("WelcomeFileList"); //NOI18N welcomeFileList.setWelcomeFile(welcomeFiles); webApp.setWelcomeFileList(welcomeFileList); } catch (ClassNotFoundException ex) {} } else welcomeFileList.setWelcomeFile(welcomeFiles); } } } public void linkButtonPressed(Object obj, String id) { java.util.StringTokenizer tok = new java.util.StringTokenizer(wfTF.getText(),","); DDUtils.openEditorForFiles(dObj,tok); } private void getWelcomeFiles() { WebApp webApp = dObj.getWebApp(); WelcomeFileList wfList = webApp.getSingleWelcomeFileList(); if (wfList==null) { wfTF.setText(""); return; } else { String[] welcomeFiles = wfList.getWelcomeFile(); StringBuffer buf = new StringBuffer(); for (int i=0;i<welcomeFiles.length;i++) { if (i>0) buf.append(", "); buf.append(welcomeFiles[i].trim()); } wfTF.setText(buf.toString()); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; wfLabel = new javax.swing.JLabel(); wfTF = new javax.swing.JTextField(); browseButton = new javax.swing.JButton(); wfDescription = new javax.swing.JLabel(); filler = new javax.swing.JPanel(); setLayout(new java.awt.GridBagLayout()); wfLabel.setLabelFor(wfTF); org.openide.awt.Mnemonics.setLocalizedText(wfLabel, org.openide.util.NbBundle.getMessage(WelcomeFilesPanel.class, "LBL_welcomeFiles")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 6); add(wfLabel, gridBagConstraints); wfTF.setColumns(50); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); add(wfTF, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(browseButton, org.openide.util.NbBundle.getMessage(WelcomeFilesPanel.class, "LBL_browse")); // NOI18N browseButton.setMargin(new java.awt.Insets(0, 14, 0, 14)); browseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(3, 6, 0, 0); add(browseButton, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(wfDescription, org.openide.util.NbBundle.getMessage(WelcomeFilesPanel.class, "DESC_welcomeFiles")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; add(wfDescription, gridBagConstraints); filler.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; add(filler, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed try { SourceGroup[] groups = DDUtils.getDocBaseGroups(dObj); org.openide.filesystems.FileObject fo = BrowseFolders.showDialog(groups); if (fo!=null) { String fileName = DDUtils.getResourcePath(groups,fo,'/',true); String oldWF = wfTF.getText(); if (fileName.length()>0) { String newWF = DDUtils.addItem(oldWF,fileName,true); if (!oldWF.equals(newWF)) { wfTF.setText(newWF); dObj.modelUpdatedFromUI(); dObj.setChangedFromUI(true); setWelcomeFiles(dObj.getWebApp(), newWF); dObj.setChangedFromUI(false); } } } } catch (java.io.IOException ex) {} }//GEN-LAST:event_browseButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton browseButton; private javax.swing.JPanel filler; private javax.swing.JLabel wfDescription; private javax.swing.JLabel wfLabel; private javax.swing.JTextField wfTF; // End of variables declaration//GEN-END:variables }
4,274
1,351
/** @file A brief file description @section license License 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. */ /************************************************************************** P_DNSConnection.h Description: struct DNSConnection **************************************************************************/ #pragma once #include "I_EventSystem.h" #include "I_DNSProcessor.h" // // Connection // struct DNSHandler; enum class DNS_CONN_MODE { UDP_ONLY, TCP_RETRY, TCP_ONLY }; struct DNSConnection { /// Options for connecting. struct Options { typedef Options self; ///< Self reference type. /// Connection is done non-blocking. /// Default: @c true. bool _non_blocking_connect = true; /// Set socket to have non-blocking I/O. /// Default: @c true. bool _non_blocking_io = true; /// Use TCP if @c true, use UDP if @c false. /// Default: @c false. bool _use_tcp = false; /// Bind to a random port. /// Default: @c true. bool _bind_random_port = true; /// Bind to this local address when using IPv6. /// Default: unset, bind to IN6ADDR_ANY. sockaddr const *_local_ipv6 = nullptr; /// Bind to this local address when using IPv4. /// Default: unset, bind to INADDRY_ANY. sockaddr const *_local_ipv4 = nullptr; Options(); self &setUseTcp(bool p); self &setNonBlockingConnect(bool p); self &setNonBlockingIo(bool p); self &setBindRandomPort(bool p); self &setLocalIpv6(sockaddr const *addr); self &setLocalIpv4(sockaddr const *addr); }; int fd; IpEndpoint ip; int num = 0; Options opt; LINK(DNSConnection, link); EventIO eio; InkRand generator; DNSHandler *handler = nullptr; /// TCPData structure is to track the reading progress of a TCP connection struct TCPData { Ptr<HostEnt> buf_ptr; unsigned short total_length = 0; unsigned short done_reading = 0; void reset() { buf_ptr.clear(); total_length = 0; done_reading = 0; } } tcp_data; int connect(sockaddr const *addr, Options const &opt = DEFAULT_OPTIONS); /* bool non_blocking_connect = NON_BLOCKING_CONNECT, bool use_tcp = CONNECT_WITH_TCP, bool non_blocking = NON_BLOCKING, bool bind_random_port = BIND_ANY_PORT); */ int close(); void trigger(); virtual ~DNSConnection(); DNSConnection(); static Options const DEFAULT_OPTIONS; }; inline DNSConnection::Options::Options() {} inline DNSConnection::Options & DNSConnection::Options::setNonBlockingIo(bool p) { _non_blocking_io = p; return *this; } inline DNSConnection::Options & DNSConnection::Options::setNonBlockingConnect(bool p) { _non_blocking_connect = p; return *this; } inline DNSConnection::Options & DNSConnection::Options::setUseTcp(bool p) { _use_tcp = p; return *this; } inline DNSConnection::Options & DNSConnection::Options::setBindRandomPort(bool p) { _bind_random_port = p; return *this; } inline DNSConnection::Options & DNSConnection::Options::setLocalIpv4(sockaddr const *ip) { _local_ipv4 = ip; return *this; } inline DNSConnection::Options & DNSConnection::Options::setLocalIpv6(sockaddr const *ip) { _local_ipv6 = ip; return *this; }
1,333
753
<gh_stars>100-1000 from __future__ import print_function import dlib import inspect def print_element(name, fc, ff): isclass = inspect.isclass(eval(name)) ismodule = inspect.ismodule(eval(name)) if (isclass): print("* :class:`{0}`".format(name), file=fc) elif (not ismodule): print("* :func:`{0}`".format(name), file=ff) def make_listing_files(): fc = open('classes.txt', 'w') ff = open('functions.txt', 'w') for obj in dir(dlib): if obj[0] == '_': continue print_element('dlib.'+obj, fc, ff) for obj in dir(dlib.cuda): if obj[0] == '_': continue print_element('dlib.cuda.'+obj, fc, ff) for obj in dir(dlib.image_dataset_metadata): if obj[0] == '_': continue print_element('dlib.image_dataset_metadata.'+obj, fc, ff)
407
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.frontdoor.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.management.Resource; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.frontdoor.models.BackendPool; import com.azure.resourcemanager.frontdoor.models.BackendPoolsSettings; import com.azure.resourcemanager.frontdoor.models.FrontDoorEnabledState; import com.azure.resourcemanager.frontdoor.models.FrontDoorResourceState; import com.azure.resourcemanager.frontdoor.models.HealthProbeSettingsModel; import com.azure.resourcemanager.frontdoor.models.LoadBalancingSettingsModel; import com.azure.resourcemanager.frontdoor.models.RoutingRule; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; /** * Front Door represents a collection of backend endpoints to route traffic to along with rules that specify how traffic * is sent there. */ @JsonFlatten @Fluent public class FrontDoorInner extends Resource { @JsonIgnore private final ClientLogger logger = new ClientLogger(FrontDoorInner.class); /* * A friendly name for the frontDoor */ @JsonProperty(value = "properties.friendlyName") private String friendlyName; /* * Routing rules associated with this Front Door. */ @JsonProperty(value = "properties.routingRules") private List<RoutingRule> routingRules; /* * Load balancing settings associated with this Front Door instance. */ @JsonProperty(value = "properties.loadBalancingSettings") private List<LoadBalancingSettingsModel> loadBalancingSettings; /* * Health probe settings associated with this Front Door instance. */ @JsonProperty(value = "properties.healthProbeSettings") private List<HealthProbeSettingsModel> healthProbeSettings; /* * Backend pools available to routing rules. */ @JsonProperty(value = "properties.backendPools") private List<BackendPool> backendPools; /* * Frontend endpoints available to routing rules. */ @JsonProperty(value = "properties.frontendEndpoints") private List<FrontendEndpointInner> frontendEndpoints; /* * Settings for all backendPools */ @JsonProperty(value = "properties.backendPoolsSettings") private BackendPoolsSettings backendPoolsSettings; /* * Operational status of the Front Door load balancer. Permitted values are * 'Enabled' or 'Disabled' */ @JsonProperty(value = "properties.enabledState") private FrontDoorEnabledState enabledState; /* * Resource status of the Front Door. */ @JsonProperty(value = "properties.resourceState", access = JsonProperty.Access.WRITE_ONLY) private FrontDoorResourceState resourceState; /* * Provisioning state of the Front Door. */ @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) private String provisioningState; /* * The host that each frontendEndpoint must CNAME to. */ @JsonProperty(value = "properties.cname", access = JsonProperty.Access.WRITE_ONLY) private String cname; /* * The Id of the frontdoor. */ @JsonProperty(value = "properties.frontdoorId", access = JsonProperty.Access.WRITE_ONLY) private String frontdoorId; /* * Rules Engine Configurations available to routing rules. */ @JsonProperty(value = "properties.rulesEngines", access = JsonProperty.Access.WRITE_ONLY) private List<RulesEngineInner> rulesEngines; /** * Get the friendlyName property: A friendly name for the frontDoor. * * @return the friendlyName value. */ public String friendlyName() { return this.friendlyName; } /** * Set the friendlyName property: A friendly name for the frontDoor. * * @param friendlyName the friendlyName value to set. * @return the FrontDoorInner object itself. */ public FrontDoorInner withFriendlyName(String friendlyName) { this.friendlyName = friendlyName; return this; } /** * Get the routingRules property: Routing rules associated with this Front Door. * * @return the routingRules value. */ public List<RoutingRule> routingRules() { return this.routingRules; } /** * Set the routingRules property: Routing rules associated with this Front Door. * * @param routingRules the routingRules value to set. * @return the FrontDoorInner object itself. */ public FrontDoorInner withRoutingRules(List<RoutingRule> routingRules) { this.routingRules = routingRules; return this; } /** * Get the loadBalancingSettings property: Load balancing settings associated with this Front Door instance. * * @return the loadBalancingSettings value. */ public List<LoadBalancingSettingsModel> loadBalancingSettings() { return this.loadBalancingSettings; } /** * Set the loadBalancingSettings property: Load balancing settings associated with this Front Door instance. * * @param loadBalancingSettings the loadBalancingSettings value to set. * @return the FrontDoorInner object itself. */ public FrontDoorInner withLoadBalancingSettings(List<LoadBalancingSettingsModel> loadBalancingSettings) { this.loadBalancingSettings = loadBalancingSettings; return this; } /** * Get the healthProbeSettings property: Health probe settings associated with this Front Door instance. * * @return the healthProbeSettings value. */ public List<HealthProbeSettingsModel> healthProbeSettings() { return this.healthProbeSettings; } /** * Set the healthProbeSettings property: Health probe settings associated with this Front Door instance. * * @param healthProbeSettings the healthProbeSettings value to set. * @return the FrontDoorInner object itself. */ public FrontDoorInner withHealthProbeSettings(List<HealthProbeSettingsModel> healthProbeSettings) { this.healthProbeSettings = healthProbeSettings; return this; } /** * Get the backendPools property: Backend pools available to routing rules. * * @return the backendPools value. */ public List<BackendPool> backendPools() { return this.backendPools; } /** * Set the backendPools property: Backend pools available to routing rules. * * @param backendPools the backendPools value to set. * @return the FrontDoorInner object itself. */ public FrontDoorInner withBackendPools(List<BackendPool> backendPools) { this.backendPools = backendPools; return this; } /** * Get the frontendEndpoints property: Frontend endpoints available to routing rules. * * @return the frontendEndpoints value. */ public List<FrontendEndpointInner> frontendEndpoints() { return this.frontendEndpoints; } /** * Set the frontendEndpoints property: Frontend endpoints available to routing rules. * * @param frontendEndpoints the frontendEndpoints value to set. * @return the FrontDoorInner object itself. */ public FrontDoorInner withFrontendEndpoints(List<FrontendEndpointInner> frontendEndpoints) { this.frontendEndpoints = frontendEndpoints; return this; } /** * Get the backendPoolsSettings property: Settings for all backendPools. * * @return the backendPoolsSettings value. */ public BackendPoolsSettings backendPoolsSettings() { return this.backendPoolsSettings; } /** * Set the backendPoolsSettings property: Settings for all backendPools. * * @param backendPoolsSettings the backendPoolsSettings value to set. * @return the FrontDoorInner object itself. */ public FrontDoorInner withBackendPoolsSettings(BackendPoolsSettings backendPoolsSettings) { this.backendPoolsSettings = backendPoolsSettings; return this; } /** * Get the enabledState property: Operational status of the Front Door load balancer. Permitted values are 'Enabled' * or 'Disabled'. * * @return the enabledState value. */ public FrontDoorEnabledState enabledState() { return this.enabledState; } /** * Set the enabledState property: Operational status of the Front Door load balancer. Permitted values are 'Enabled' * or 'Disabled'. * * @param enabledState the enabledState value to set. * @return the FrontDoorInner object itself. */ public FrontDoorInner withEnabledState(FrontDoorEnabledState enabledState) { this.enabledState = enabledState; return this; } /** * Get the resourceState property: Resource status of the Front Door. * * @return the resourceState value. */ public FrontDoorResourceState resourceState() { return this.resourceState; } /** * Get the provisioningState property: Provisioning state of the Front Door. * * @return the provisioningState value. */ public String provisioningState() { return this.provisioningState; } /** * Get the cname property: The host that each frontendEndpoint must CNAME to. * * @return the cname value. */ public String cname() { return this.cname; } /** * Get the frontdoorId property: The Id of the frontdoor. * * @return the frontdoorId value. */ public String frontdoorId() { return this.frontdoorId; } /** * Get the rulesEngines property: Rules Engine Configurations available to routing rules. * * @return the rulesEngines value. */ public List<RulesEngineInner> rulesEngines() { return this.rulesEngines; } /** {@inheritDoc} */ @Override public FrontDoorInner withLocation(String location) { super.withLocation(location); return this; } /** {@inheritDoc} */ @Override public FrontDoorInner withTags(Map<String, String> tags) { super.withTags(tags); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (routingRules() != null) { routingRules().forEach(e -> e.validate()); } if (loadBalancingSettings() != null) { loadBalancingSettings().forEach(e -> e.validate()); } if (healthProbeSettings() != null) { healthProbeSettings().forEach(e -> e.validate()); } if (backendPools() != null) { backendPools().forEach(e -> e.validate()); } if (frontendEndpoints() != null) { frontendEndpoints().forEach(e -> e.validate()); } if (backendPoolsSettings() != null) { backendPoolsSettings().validate(); } if (rulesEngines() != null) { rulesEngines().forEach(e -> e.validate()); } } }
4,087
14,668
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.android.webview.chromium; class WebViewChromiumFactoryProviderForR extends WebViewChromiumFactoryProvider { public static WebViewChromiumFactoryProvider create(android.webkit.WebViewDelegate delegate) { return new WebViewChromiumFactoryProviderForR(delegate); } protected WebViewChromiumFactoryProviderForR(android.webkit.WebViewDelegate delegate) { super(delegate); } }
175
2,151
<reponame>zipated/src /* * Copyright © 2010-2011 Linaro Limited * Copyright © 2013 Canonical Ltd * * This file is part of the glmark2 OpenGL (ES) 2.0 benchmark. * * glmark2 is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * glmark2 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 * glmark2. If not, see <http://www.gnu.org/licenses/>. * * Authors: * <NAME> */ #ifndef GLMARK2_GL_STATE_GLX_H_ #define GLMARK2_GL_STATE_GLX_H_ #include "gl-state.h" #include "gl-visual-config.h" #include "gl-headers.h" #include "shared-library.h" #include <vector> #include <glad/glx.h> class GLStateGLX : public GLState { public: GLStateGLX() : xdpy_(0), xwin_(0), glx_fbconfig_(0), glx_context_(0) {} bool valid(); bool init_display(void* native_display, GLVisualConfig& config_pref); bool init_surface(void* native_window); bool init_gl_extensions(); bool reset(); void swap(); bool gotNativeConfig(int& vid); void getVisualConfig(GLVisualConfig& vc); private: bool check_glx_version(); void init_extensions(); bool ensure_glx_fbconfig(); bool ensure_glx_context(); void get_glvisualconfig_glx(GLXFBConfig config, GLVisualConfig &visual_config); GLXFBConfig select_best_config(std::vector<GLXFBConfig> configs); static GLADapiproc load_proc(const char* name, void* userptr); Display* xdpy_; Window xwin_; GLXFBConfig glx_fbconfig_; GLXContext glx_context_; GLVisualConfig requested_visual_config_; SharedLibrary lib_; }; #endif /* GLMARK2_GL_STATE_GLX_H_ */
724
362
<gh_stars>100-1000 package com.google.android.apps.common.testing.accessibility.framework.suggestions; import com.google.android.apps.common.testing.accessibility.framework.ResultMetadata; import com.google.android.apps.common.testing.accessibility.framework.checks.TextContrastCheck; import com.google.android.apps.common.testing.accessibility.framework.replacements.TextUtils; import com.google.android.apps.common.testing.accessibility.framework.uielement.ViewHierarchyElement; import com.google.android.apps.common.testing.accessibility.framework.utils.contrast.ContrastUtils; import com.google.common.collect.ImmutableSet; import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link FixSuggestionProducer} which produces a {@link SetViewAttributeFixSuggestion} to fix a * text low contrast issue. * * <p>If a similar text color which meets the contrast ratio requirement could be found, produces a * {@link SetViewAttributeFixSuggestion} which recommends changing text color to fix a text low * contrast issue. Otherwise no fix suggestions will be produced. */ class TextColorFixSuggestionProducer extends BaseTextContrastFixSuggestionProducer { private static final String VIEW_ATTRIBUTE_TEXT_COLOR = "textColor"; private static final String VIEW_ATTRIBUTE_HINT_TEXT_COLOR = "hintTextColor"; @Override protected @Nullable SetViewAttributeFixSuggestion produceTextContrastFixSuggestion( int checkResultId, ViewHierarchyElement element, ResultMetadata metadata) { switch (checkResultId) { case TextContrastCheck.RESULT_ID_TEXTVIEW_CONTRAST_NOT_SUFFICIENT: case TextContrastCheck.RESULT_ID_TEXTVIEW_HEURISTIC_CONTRAST_NOT_SUFFICIENT: case TextContrastCheck.RESULT_ID_CUSTOMIZED_TEXTVIEW_HEURISTIC_CONTRAST_NOT_SUFFICIENT: case TextContrastCheck.RESULT_ID_TEXTVIEW_HEURISTIC_CONTRAST_BORDERLINE: return produceTextColorFixSuggestion(element, metadata); default: return null; } } private static @Nullable SetViewAttributeFixSuggestion produceTextColorFixSuggestion( ViewHierarchyElement element, ResultMetadata resultMetadata) { int textColor = getTextColor(resultMetadata); int backgroundColor = getBackgroundColor(resultMetadata); double requiredContrastRatio = getRequiredContrastRatio(resultMetadata); MaterialDesignColor closestColor = MaterialDesignColor.findClosestColor(textColor); Integer bestColorCandidate = findBestTextColorCandidate(closestColor, textColor, backgroundColor, requiredContrastRatio); // If the element's text is empty and a low color contrast ratio issue has been detected, then // the element's hint is being displayed with the current hint text color. So we should suggest // changing the hint text color instead of the text color in this case. String viewAttribute = TextUtils.isEmpty(element.getText()) ? VIEW_ATTRIBUTE_HINT_TEXT_COLOR : VIEW_ATTRIBUTE_TEXT_COLOR; return (bestColorCandidate == null) ? null : createSetViewAttributeFixSuggestion(viewAttribute, bestColorCandidate); } private static @Nullable Integer findBestTextColorCandidate( MaterialDesignColor closestColor, int textColor, int backgroundColor, double requiredContrastRatio) { // Always test/suggest white and black regardless of the original color family ImmutableSet<Integer> similarColors = ImmutableSet.<Integer>builder() .add(WHITE_COLOR) .addAll(closestColor.getColorMap().values()) .add(BLACK_COLOR) .build(); // Tries to find a color in similar colors which meets contrast ratio requirement and is the // closest color to the culprit View's text color. double minColorDistance = Double.MAX_VALUE; Integer bestColorCandidate = null; for (int color : similarColors) { if (ContrastUtils.calculateContrastRatio(color, backgroundColor) >= requiredContrastRatio) { double colorDistance = ContrastUtils.colorDifference(color, textColor); if (minColorDistance > colorDistance) { minColorDistance = colorDistance; bestColorCandidate = color; } } } return bestColorCandidate; } }
1,390
3,084
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014 Microsoft Corporation. All Rights Reserved. // // Module Name: // CompletionFunctions_FastStreamInjectionCallouts.cpp // // Abstract: // This module contains prototypes for WFP Completion functions for data injected back into // the stream path using the clone / block / inject method. // // Author: // <NAME> (DHarper) // // Revision History: // // [ Month ][Day] [Year] - [Revision]-[ Comments ] // May 01, 2010 - 1.0 - Creation // December 13, 2013 - 1.1 - Enhance function declaration for IntelliSense // //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef COMPLETION_FAST_STREAM_INJECTION_H #define COMPLETION_FAST_STREAM_INJECTION_H _IRQL_requires_min_(PASSIVE_LEVEL) _IRQL_requires_max_(DISPATCH_LEVEL) _IRQL_requires_same_ VOID NTAPI CompleteFastStreamInjection(_In_ VOID* pContext, _Inout_ NET_BUFFER_LIST* pNetBufferList, _In_ BOOLEAN dispatchLevel); #endif /// COMPLETION_FAST_STREAM_INJECTION_H
494
4,526
#ifndef OSRM_GUIDANCE_PARSING_TOOLKIT_HPP_ #define OSRM_GUIDANCE_PARSING_TOOLKIT_HPP_ #include <cstdint> #include <string> #include <boost/algorithm/string.hpp> #include <boost/tokenizer.hpp> #include "util/attributes.hpp" namespace osrm { namespace extractor { namespace guidance { // Public service vehicle lanes and similar can introduce additional lanes into the lane string that // are not specifically marked for left/right turns. This function can be used from the profile to // trim the lane string appropriately // // left|throught| // in combination with lanes:psv:forward=1 // will be corrected to left|throught, since the final lane is not drivable. // This is in contrast to a situation with lanes:psv:forward=0 (or not set) where left|through| // represents left|through|through OSRM_ATTR_WARN_UNUSED inline std::string trimLaneString(std::string lane_string, std::int32_t count_left, std::int32_t count_right) { if (count_left) { bool sane = count_left < static_cast<std::int32_t>(lane_string.size()); for (std::int32_t i = 0; i < count_left; ++i) // this is adjusted for our fake pipe. The moment cucumber can handle multiple escaped // pipes, the '&' part can be removed if (lane_string[i] != '|') { sane = false; break; } if (sane) { lane_string.erase(lane_string.begin(), lane_string.begin() + count_left); } } if (count_right) { bool sane = count_right < static_cast<std::int32_t>(lane_string.size()); for (auto itr = lane_string.rbegin(); itr != lane_string.rend() && itr != lane_string.rbegin() + count_right; ++itr) { if (*itr != '|') { sane = false; break; } } if (sane) lane_string.resize(lane_string.size() - count_right); } return lane_string; } // https://github.com/Project-OSRM/osrm-backend/issues/2638 // It can happen that some lanes are not drivable by car. Here we handle this tagging scheme // (vehicle:lanes) to filter out not-allowed roads // lanes=3 // turn:lanes=left|through|through|right // vehicle:lanes=yes|yes|no|yes // bicycle:lanes=yes|no|designated|yes OSRM_ATTR_WARN_UNUSED inline std::string applyAccessTokens(std::string lane_string, const std::string &access_tokens) { typedef boost::tokenizer<boost::char_separator<char>> tokenizer; boost::char_separator<char> sep("|", "", boost::keep_empty_tokens); tokenizer tokens(lane_string, sep); tokenizer access(access_tokens, sep); // strings don't match, don't do anything if (std::distance(std::begin(tokens), std::end(tokens)) != std::distance(std::begin(access), std::end(access))) return lane_string; std::string result_string = ""; const static std::string yes = "yes"; for (auto token_itr = std::begin(tokens), access_itr = std::begin(access); token_itr != std::end(tokens); ++token_itr, ++access_itr) { if (*access_itr == yes) { // we have to add this in front, because the next token could be invalid. Doing this on // non-empty strings makes sure that the token string will be valid in the end if (!result_string.empty()) result_string += '|'; result_string += *token_itr; } } return result_string; } } // namespace guidance } // namespace extractor } // namespace osrm #endif // OSRM_GUIDANCE_PARSING_TOOLKIT_HPP_
1,506
317
<gh_stars>100-1000 { "extends": ["config:base"], "schedule": "every weekend", "packageRules": [ { "depTypeList": ["dependencies", "devDependencies"], "updateTypes": ["minor", "patch"], "rangeStrategy": "pin", "groupName": "minor and patch" }, { "depTypeList": ["dependencies", "devDependencies"], "updateTypes": ["major"], "rangeStrategy": "pin", "dependencyDashboardApproval": true, "dependencyDashboardAutoclose": true } ] }
213
859
#pragma once namespace cppwinrt { static auto get_start_time() { return std::chrono::high_resolution_clock::now(); } static auto get_elapsed_time(decltype(get_start_time()) const& start) { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count(); } static bool is_put_overload(MethodDef const& method) { return method.SpecialName() && starts_with(method.Name(), "put_"); } struct method_signature { explicit method_signature(MethodDef const& method) : m_method(method), m_signature(method.Signature()) { auto params = method.ParamList(); if (m_signature.ReturnType() && params.first != params.second && params.first.Sequence() == 0) { m_return = params.first; ++params.first; } for (uint32_t i{}; i != size(m_signature.Params()); ++i) { m_params.emplace_back(params.first + i, &m_signature.Params().first[i]); } } std::vector<std::pair<Param, ParamSig const*>>& params() { return m_params; } std::vector<std::pair<Param, ParamSig const*>> const& params() const { return m_params; } auto const& return_signature() const { return m_signature.ReturnType(); } auto return_param_name() const { std::string_view name; if (m_return) { name = m_return.Name(); } else { name = "winrt_impl_result"; } return name; } MethodDef const& method() const { return m_method; } bool is_async() const { // WinRT parameter passing conventions include the notion that input parameters of collection types may be read // or copied but should not be stored directly since this would lead to instability as the collection is shared // by the caller and callee. The exception to this rule is property setters where the callee may simply store a // reference to the collection. The collection thus becomes async in the sense that it is expected to remain // valid beyond the duration of the call. if (is_put_overload(m_method)) { return true; } if (!m_signature.ReturnType()) { return false; } bool async{}; call(m_signature.ReturnType().Type().Type(), [&](coded_index<TypeDefOrRef> const& type) { auto const& [type_namespace, type_name] = get_type_namespace_and_name(type); async = type_namespace == "Windows.Foundation" && type_name == "IAsyncAction"; }, [&](GenericTypeInstSig const& type) { auto const& [type_namespace, type_name] = get_type_namespace_and_name(type.GenericType()); if (type_namespace == "Windows.Foundation") { async = type_name == "IAsyncOperation`1" || type_name == "IAsyncActionWithProgress`1" || type_name == "IAsyncOperationWithProgress`2"; } }, [](auto&&) {}); return async; } private: MethodDef m_method; MethodDefSig m_signature; std::vector<std::pair<Param, ParamSig const*>> m_params; Param m_return; }; struct separator { writer& w; bool first{ true }; void operator()() { if (first) { first = false; } else { w.write(", "); } } }; template <typename T> bool has_attribute(T const& row, std::string_view const& type_namespace, std::string_view const& type_name) { return static_cast<bool>(get_attribute(row, type_namespace, type_name)); } namespace impl { template <typename T, typename... Types> struct variant_index; template <typename T, typename First, typename... Types> struct variant_index<T, First, Types...> { static constexpr bool found = std::is_same_v<T, First>; static constexpr std::size_t value = std::conditional_t<found, std::integral_constant<std::size_t, 0>, variant_index<T, Types...>>::value + (found ? 0 : 1); }; } template <typename Variant, typename T> struct variant_index; template <typename... Types, typename T> struct variant_index<std::variant<Types...>, T> : impl::variant_index<T, Types...> { }; template <typename Variant, typename T> constexpr std::size_t variant_index_v = variant_index<Variant, T>::value; template <typename T> auto get_integer_attribute(FixedArgSig const& signature) { auto variant = std::get<ElemSig>(signature.value).value; switch (variant.index()) { case variant_index_v<decltype(variant), std::make_unsigned_t<T>>: return static_cast<T>(std::get<std::make_unsigned_t<T>>(variant)); case variant_index_v<decltype(variant), std::make_signed_t<T>>: return static_cast<T>(std::get<std::make_signed_t<T>>(variant)); default: return std::get<T>(variant); // Likely throws, but that's intentional } } template <typename T> auto get_attribute_value(FixedArgSig const& signature) { return std::get<T>(std::get<ElemSig>(signature.value).value); } template <typename T> auto get_attribute_value(CustomAttribute const& attribute, uint32_t const arg) { return get_attribute_value<T>(attribute.Value().FixedArgs()[arg]); } static auto get_abi_name(MethodDef const& method) { if (auto overload = get_attribute(method, "Windows.Foundation.Metadata", "OverloadAttribute")) { return get_attribute_value<std::string_view>(overload, 0); } else { return method.Name(); } } static auto get_name(MethodDef const& method) { auto name = method.Name(); if (method.SpecialName()) { return name.substr(name.find('_') + 1); } return name; } static bool is_remove_overload(MethodDef const& method) { return method.SpecialName() && starts_with(method.Name(), "remove_"); } static bool is_add_overload(MethodDef const& method) { return method.SpecialName() && starts_with(method.Name(), "add_"); } static bool is_get_overload(MethodDef const& method) { return method.SpecialName() && starts_with(method.Name(), "get_"); } static bool is_noexcept(MethodDef const& method) { return is_remove_overload(method) || has_attribute(method, "Windows.Foundation.Metadata", "NoExceptionAttribute"); } static bool has_fastabi(TypeDef const& type) { return settings.fastabi&& has_attribute(type, "Windows.Foundation.Metadata", "FastAbiAttribute"); } static bool is_always_disabled(TypeDef const& type) { if (settings.component_ignore_velocity) { return false; } auto feature = get_attribute(type, "Windows.Foundation.Metadata", "FeatureAttribute"); if (!feature) { return false; } auto stage = get_attribute_value<ElemSig::EnumValue>(feature, 0); return stage.equals_enumerator("AlwaysDisabled"); } static bool is_always_enabled(TypeDef const& type) { auto feature = get_attribute(type, "Windows.Foundation.Metadata", "FeatureAttribute"); if (!feature) { return true; } auto stage = get_attribute_value<ElemSig::EnumValue>(feature, 0); return stage.equals_enumerator("AlwaysEnabled"); } static coded_index<TypeDefOrRef> get_default_interface(TypeDef const& type) { auto impls = type.InterfaceImpl(); for (auto&& impl : impls) { if (has_attribute(impl, "Windows.Foundation.Metadata", "DefaultAttribute")) { return impl.Interface(); } } if (!empty(impls)) { throw_invalid("Type '", type.TypeNamespace(), ".", type.TypeName(), "' does not have a default interface"); } return {}; } static TypeDef get_base_class(TypeDef const& derived) { auto extends = derived.Extends(); if (!extends) { return{}; } auto const&[extends_namespace, extends_name] = get_type_namespace_and_name(extends); if (extends_name == "Object" && extends_namespace == "System") { return {}; } return find_required(extends); }; static auto get_bases(TypeDef const& type) { std::vector<TypeDef> bases; for (auto base = get_base_class(type); base; base = get_base_class(base)) { bases.push_back(base); } return bases; } struct contract_version { std::string_view name; uint32_t version; }; struct previous_contract { std::string_view contract_from; std::string_view contract_to; uint32_t version_low; uint32_t version_high; }; struct contract_history { contract_version current_contract; // Sorted such that the first entry is the first contract the type was introduced in std::vector<previous_contract> previous_contracts; }; static contract_version decode_contract_version_attribute(CustomAttribute const& attribute) { // ContractVersionAttribute has three constructors, but only two we care about here: // .ctor(string contract, uint32 version) // .ctor(System.Type contract, uint32 version) auto signature = attribute.Value(); auto& args = signature.FixedArgs(); assert(args.size() == 2); contract_version result{}; result.version = get_integer_attribute<uint32_t>(args[1]); call(std::get<ElemSig>(args[0].value).value, [&](ElemSig::SystemType t) { result.name = t.name; }, [&](std::string_view name) { result.name = name; }, [](auto&&) { assert(false); }); return result; } static previous_contract decode_previous_contract_attribute(CustomAttribute const& attribute) { // PreviousContractVersionAttribute has two constructors: // .ctor(string fromContract, uint32 versionLow, uint32 versionHigh) // .ctor(string fromContract, uint32 versionLow, uint32 versionHigh, string contractTo) auto signature = attribute.Value(); auto& args = signature.FixedArgs(); assert(args.size() >= 3); previous_contract result{}; result.contract_from = get_attribute_value<std::string_view>(args[0]); result.version_low = get_integer_attribute<uint32_t>(args[1]); result.version_high = get_integer_attribute<uint32_t>(args[2]); if (args.size() == 4) { result.contract_to = get_attribute_value<std::string_view>(args[3]); } return result; } static contract_version get_initial_contract_version(TypeDef const& type) { // Most types don't have previous contracts, so optimize for that scenario to avoid unnecessary allocations contract_version current_contract{}; // The initial contract, assuming the type has moved contracts, is the only contract name that doesn't appear as // a "to contract" argument to a PreviousContractVersionAttribute. Note that this assumes that a type does not // "return" to a prior contract, however this is a restriction enforced by midlrt std::vector<contract_version> previous_contracts; std::vector<std::string_view> to_contracts; for (auto&& attribute : type.CustomAttribute()) { auto [ns, name] = attribute.TypeNamespaceAndName(); if (ns != "Windows.Foundation.Metadata") { continue; } if (name == "ContractVersionAttribute") { assert(current_contract.name.empty()); current_contract = decode_contract_version_attribute(attribute); } else if (name == "PreviousContractVersionAttribute") { auto prev = decode_previous_contract_attribute(attribute); // If this contract was the target of an earlier contract change, we know this isn't the initial one if (std::find(to_contracts.begin(), to_contracts.end(), prev.contract_from) == to_contracts.end()) { previous_contracts.push_back(contract_version{ prev.contract_from, prev.version_low }); } if (!prev.contract_to.empty()) { auto itr = std::find_if(previous_contracts.begin(), previous_contracts.end(), [&](auto const& ver) { return ver.name == prev.contract_to; }); if (itr != previous_contracts.end()) { *itr = previous_contracts.back(); previous_contracts.pop_back(); } to_contracts.push_back(prev.contract_to); } } else if (name == "VersionAttribute") { // Prefer contract versioning, if present. Otherwise, use an empty contract name to indicate that this // is not a contract version if (current_contract.name.empty()) { current_contract.version = get_attribute_value<uint32_t>(attribute, 0); } } } if (!previous_contracts.empty()) { assert(previous_contracts.size() == 1); return previous_contracts[0]; } return current_contract; } static contract_history get_contract_history(TypeDef const& type) { contract_history result{}; for (auto&& attribute : type.CustomAttribute()) { auto [ns, name] = attribute.TypeNamespaceAndName(); if (ns != "Windows.Foundation.Metadata") { continue; } if (name == "ContractVersionAttribute") { assert(result.current_contract.name.empty()); result.current_contract = decode_contract_version_attribute(attribute); } else if (name == "PreviousContractVersionAttribute") { result.previous_contracts.push_back(decode_previous_contract_attribute(attribute)); } // We could report the version that the type was introduced if the type is not contract versioned, however // that information is not useful to us anywhere, so just skip it } if (result.previous_contracts.empty()) { return result; } assert(!result.current_contract.name.empty()); // There's no guarantee that the contract history will be sorted in metadata (in fact it's unlikely to be) for (auto& prev : result.previous_contracts) { if (prev.contract_to.empty() || (prev.contract_to == result.current_contract.name)) { // No 'to' contract indicates that this was the last contract before the current one prev.contract_to = result.current_contract.name; std::swap(prev, result.previous_contracts.back()); break; } } assert(result.previous_contracts.back().contract_to == result.current_contract.name); for (size_t size = result.previous_contracts.size() - 1; size; --size) { auto& last = result.previous_contracts[size]; auto itr = std::find_if(result.previous_contracts.begin(), result.previous_contracts.begin() + size, [&](auto const& prev) { return prev.contract_to == last.contract_from; }); assert(itr != result.previous_contracts.end()); std::swap(*itr, result.previous_contracts[size - 1]); } return result; } struct interface_info { TypeDef type; bool is_default{}; bool defaulted{}; bool overridable{}; bool base{}; bool exclusive{}; bool fastabi{}; // A pair of (relativeContract, version) where 'relativeContract' is the contract the interface was introduced // in relative to the contract history of the class. E.g. if a class goes from contract 'A' to 'B' to 'C', // 'relativeContract' would be '0' for an interface introduced in contract 'A', '1' for an interface introduced // in contract 'B', etc. This is only set/valid for 'fastabi' interfaces std::pair<uint32_t, uint32_t> relative_version{}; std::vector<std::vector<std::string>> generic_param_stack{}; }; using get_interfaces_t = std::vector<std::pair<std::string, interface_info>>; static interface_info* find(get_interfaces_t& interfaces, std::string_view const& name) { auto pair = std::find_if(interfaces.begin(), interfaces.end(), [&](auto&& pair) { return pair.first == name; }); if (pair == interfaces.end()) { return nullptr; } return &pair->second; } static void insert_or_assign(get_interfaces_t& interfaces, std::string_view const& name, interface_info&& info) { if (auto existing = find(interfaces, name)) { *existing = std::move(info); } else { interfaces.emplace_back(name, std::move(info)); } } static void get_interfaces_impl(writer& w, get_interfaces_t& result, bool defaulted, bool overridable, bool base, std::vector<std::vector<std::string>> const& generic_param_stack, std::pair<InterfaceImpl, InterfaceImpl>&& children) { for (auto&& impl : children) { interface_info info; auto type = impl.Interface(); auto name = w.write_temp("%", type); info.is_default = has_attribute(impl, "Windows.Foundation.Metadata", "DefaultAttribute"); info.defaulted = !base && (defaulted || info.is_default); { // This is for correctness rather than an optimization (but helps performance as well). // If the interface was not previously inserted, carry on and recursively insert it. // If a previous insertion was defaulted we're done as it is correctly captured. // If a newly discovered instance of a previous insertion is not defaulted, we're also done. // If it was previously captured as non-defaulted but now found as defaulted, we carry on and // rediscover it as we need it to be defaulted recursively. if (auto found = find(result, name)) { if (found->defaulted || !info.defaulted) { continue; } } } info.overridable = overridable || has_attribute(impl, "Windows.Foundation.Metadata", "OverridableAttribute"); info.base = base; info.generic_param_stack = generic_param_stack; writer::generic_param_guard guard; switch (type.type()) { case TypeDefOrRef::TypeDef: { info.type = type.TypeDef(); break; } case TypeDefOrRef::TypeRef: { info.type = find_required(type.TypeRef()); w.add_depends(info.type); break; } case TypeDefOrRef::TypeSpec: { auto type_signature = type.TypeSpec().Signature(); std::vector<std::string> names; for (auto&& arg : type_signature.GenericTypeInst().GenericArgs()) { names.push_back(w.write_temp("%", arg)); } info.generic_param_stack.push_back(std::move(names)); guard = w.push_generic_params(type_signature.GenericTypeInst()); auto signature = type_signature.GenericTypeInst(); info.type = find_required(signature.GenericType()); break; } } info.exclusive = has_attribute(info.type, "Windows.Foundation.Metadata", "ExclusiveToAttribute"); get_interfaces_impl(w, result, info.defaulted, info.overridable, base, info.generic_param_stack, info.type.InterfaceImpl()); insert_or_assign(result, name, std::move(info)); } }; static auto get_interfaces(writer& w, TypeDef const& type) { w.abi_types = false; get_interfaces_t result; get_interfaces_impl(w, result, false, false, false, {}, type.InterfaceImpl()); for (auto&& base : get_bases(type)) { get_interfaces_impl(w, result, false, false, true, {}, base.InterfaceImpl()); } if (!has_fastabi(type)) { return result; } auto history = get_contract_history(type); size_t count = 0; for (auto& pair : result) { if (pair.second.exclusive && !pair.second.base && !pair.second.overridable) { ++count; auto introduced = get_initial_contract_version(pair.second.type); pair.second.relative_version.second = introduced.version; auto itr = std::find_if(history.previous_contracts.begin(), history.previous_contracts.end(), [&](previous_contract const& prev) { return prev.contract_from == introduced.name; }); if (itr != history.previous_contracts.end()) { pair.second.relative_version.first = static_cast<uint32_t>(itr - history.previous_contracts.begin()); } else { assert(history.current_contract.name == introduced.name); pair.second.relative_version.first = static_cast<uint32_t>(history.previous_contracts.size()); } } } std::partial_sort(result.begin(), result.begin() + count, result.end(), [](auto&& left_pair, auto&& right_pair) { auto& left = left_pair.second; auto& right = right_pair.second; // Sort by base before is_default because each base will have a default. if (left.base != right.base) { return !left.base; } if (left.is_default != right.is_default) { return left.is_default; } if (left.overridable != right.overridable) { return !left.overridable; } if (left.exclusive != right.exclusive) { return left.exclusive; } auto left_enabled = is_always_enabled(left.type); auto right_enabled = is_always_enabled(right.type); if (left_enabled != right_enabled) { return left_enabled; } if (left.relative_version != right.relative_version) { return left.relative_version < right.relative_version; } return left_pair.first < right_pair.first; }); std::for_each_n(result.begin(), count, [](auto && pair) { pair.second.fastabi = true; }); return result; } static bool implements_interface(TypeDef const& type, std::string_view const& name) { for (auto&& impl : type.InterfaceImpl()) { const auto iface = impl.Interface(); if (iface.type() != TypeDefOrRef::TypeSpec && type_name(iface) == name) { return true; } } if (auto base = get_base_class(type)) { return implements_interface(base, name); } else { return false; } } bool has_fastabi_tearoffs(writer& w, TypeDef const& type) { for (auto&& [name, info] : get_interfaces(w, type)) { if (info.is_default) { continue; } return info.fastabi; } return false; } std::size_t get_fastabi_size(writer& w, TypeDef const& type) { if (!has_fastabi(type)) { return 0; } auto result = 6 + get_bases(type).size(); for (auto&& [name, info] : get_interfaces(w, type)) { if (!info.fastabi) { break; } result += size(info.type.MethodList()); } return result; } auto get_fastabi_size(writer& w, std::vector<TypeDef> const& classes) { std::size_t result{}; for (auto&& type : classes) { result = (std::max)(result, get_fastabi_size(w, type)); } return result; } struct factory_info { TypeDef type; bool activatable{}; bool statics{}; bool composable{}; bool visible{}; }; static auto get_factories(writer& w, TypeDef const& type) { auto get_system_type = [&](auto&& signature) -> TypeDef { for (auto&& arg : signature.FixedArgs()) { if (auto type_param = std::get_if<ElemSig::SystemType>(&std::get<ElemSig>(arg.value).value)) { return type.get_cache().find_required(type_param->name); } } return {}; }; std::map<std::string, factory_info> result; for (auto&& attribute : type.CustomAttribute()) { auto attribute_name = attribute.TypeNamespaceAndName(); if (attribute_name.first != "Windows.Foundation.Metadata") { continue; } auto signature = attribute.Value(); factory_info info; if (attribute_name.second == "ActivatableAttribute") { info.type = get_system_type(signature); info.activatable = true; } else if (attribute_name.second == "StaticAttribute") { info.type = get_system_type(signature); info.statics = true; } else if (attribute_name.second == "ComposableAttribute") { info.type = get_system_type(signature); info.composable = true; for (auto&& arg : signature.FixedArgs()) { if (auto visibility = std::get_if<ElemSig::EnumValue>(&std::get<ElemSig>(arg.value).value)) { info.visible = std::get<int32_t>(visibility->value) == 2; break; } } } else { continue; } std::string name; if (info.type) { name = w.write_temp("%", info.type); } result[name] = std::move(info); } return result; } enum class param_category { generic_type, object_type, string_type, enum_type, struct_type, array_type, fundamental_type, }; inline param_category get_category(TypeSig const& signature, TypeDef* signature_type = nullptr) { if (signature.is_szarray()) { return param_category::array_type; } param_category result{}; call(signature.Type(), [&](ElementType type) { if (type == ElementType::String) { result = param_category::string_type; } else if (type == ElementType::Object) { result = param_category::object_type; } else { result = param_category::fundamental_type; } }, [&](coded_index<TypeDefOrRef> const& type) { TypeDef type_def; if (type.type() == TypeDefOrRef::TypeDef) { type_def = type.TypeDef(); } else { auto type_ref = type.TypeRef(); if (type_name(type_ref) == "System.Guid") { result = param_category::struct_type; return; } type_def = find_required(type_ref); } if (signature_type) { *signature_type = type_def; } switch (get_category(type_def)) { case category::interface_type: case category::class_type: case category::delegate_type: result = param_category::object_type; return; case category::struct_type: result = param_category::struct_type; return; case category::enum_type: result = param_category::enum_type; return; } }, [&](GenericTypeInstSig const&) { result = param_category::object_type; }, [&](auto&&) { result = param_category::generic_type; }); return result; } static bool is_object(TypeSig const& signature) { bool object{}; call(signature.Type(), [&](ElementType type) { if (type == ElementType::Object) { object = true; } }, [](auto&&) {}); return object; } static auto get_delegate_method(TypeDef const& type) { auto methods = type.MethodList(); auto method = std::find_if(begin(methods), end(methods), [](auto&& method) { return method.Name() == "Invoke"; }); if (method == end(methods)) { throw_invalid("Delegate's Invoke method not found"); } return method; } static std::string get_field_abi(writer& w, Field const& field) { auto signature = field.Signature(); auto const& type = signature.Type(); std::string name = w.write_temp("%", type); if (starts_with(name, "struct ")) { auto ref = std::get<coded_index<TypeDefOrRef>>(type.Type()); name = "struct{"; for (auto&& nested : find_required(ref).FieldList()) { name += " " + get_field_abi(w, nested) + " "; name += nested.Name(); name += ";"; } name += " }"; } return name; } static std::string get_component_filename(TypeDef const& type) { std::string result{ type.TypeNamespace() }; result += '.'; result += type.TypeName(); if (!settings.component_name.empty() && starts_with(result, settings.component_name)) { result = result.substr(settings.component_name.size()); if (starts_with(result, ".")) { result.erase(result.begin()); } } return result; } static std::string get_generated_component_filename(TypeDef const& type) { auto result = get_component_filename(type); if (!settings.component_prefix) { std::replace(result.begin(), result.end(), '.', '/'); } return result; } static bool has_factory_members(writer& w, TypeDef const& type) { for (auto&&[factory_name, factory] : get_factories(w, type)) { if (!factory.type || !empty(factory.type.MethodList())) { return true; } } return false; } static bool is_composable(writer& w, TypeDef const& type) { for (auto&&[factory_name, factory] : get_factories(w, type)) { if (factory.composable) { return true; } } return false; } static bool has_composable_constructors(writer& w, TypeDef const& type) { for (auto&&[interface_name, factory] : get_factories(w, type)) { if (factory.composable && !empty(factory.type.MethodList())) { return true; } } return false; } static bool has_projected_types(cache::namespace_members const& members) { return !members.interfaces.empty() || !members.classes.empty() || !members.enums.empty() || !members.structs.empty() || !members.delegates.empty(); } static bool can_produce(TypeDef const& type, cache const& c) { auto attribute = get_attribute(type, "Windows.Foundation.Metadata", "ExclusiveToAttribute"); if (!attribute) { return true; } auto interface_name = type_name(type); auto class_name = get_attribute_value<ElemSig::SystemType>(attribute, 0).name; auto class_type = c.find_required(class_name); for (auto&& impl : class_type.InterfaceImpl()) { if (has_attribute(impl, "Windows.Foundation.Metadata", "OverridableAttribute")) { if (interface_name == type_name(impl.Interface())) { return true; } } } if (!settings.component) { return false; } return settings.component_filter.includes(class_name); } }
17,414
610
<gh_stars>100-1000 /* * Copyright (C) 2017 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 android.support.v17.leanback.supportleanbackshowcase.app.room.db.constant; public class DatabaseColumnConstant { /** * Define the name of column in video entry */ public static final class VideoEntry { // Name of the video table. public static final String TABLE_NAME = "videos"; // Name of auto generated id name public static final String COLUMN_AUTO_GENERATE_ID = "_id"; // Column with the foreign key into the category table. public static final String COLUMN_CATEGORY = "category"; // Name of the video. public static final String COLUMN_NAME = "video_name"; // Description of the video. public static final String COLUMN_DESC = "video_description"; // The url to the video content. public static final String COLUMN_VIDEO_URL = "video_url"; // The url to the video content. public static final String COLUMN_VIDEO_TRAILER_URL = "trailer_video_url"; // The url to the video content. public static final String COLUMN_VIDEO_IS_RENTED = "video_is_rented"; // The url to the background image. public static final String COLUMN_BG_IMAGE_URL = "bg_image_url"; // The card image for the video. public static final String COLUMN_CARD_IMAGE_URL = "card_image_url"; // The studio name. public static final String COLUMN_STUDIO = "studio"; // The uri to the downloaded video resource. public static final String COLUMN_VIDEO_CACHE = "video_downloaded_uri"; // The uri to the downloaded background image resource. public static final String COLUMN_BG_IMAGE_CACHE = "bg_image_downloaded_uri"; // The uri to the downloaded card image resource. public static final String COLUMN_CARD_IMG_CACHE = "card_image_downloaded_uri"; public static final String COLUMN_VIDEO_STATUS = "working_status"; } /** * Define the name of column in category entry */ public static final class CategoryEntry { // Name of the category table. public static final String TABLE_NAME = "categories"; // Name of auto generated id name public static final String COLUMN_AUTOGENERATE_ID = "_id"; // Name of the column of category name public static final String COLUMN_CATEGORY_NAME = "category_name"; } }
1,059
1,674
from setuptools import setup, find_packages with open('README.md', 'r') as readmefile: readme = readmefile.read() setup( name='glitch_this', version='1.0.2', author='TotallyNotChase', author_email='<EMAIL>', description='A package to glitch images and GIFs, with highly customizable options!', long_description=readme, long_description_content_type='text/markdown', url='https://github.com/TotallyNotChase/Glitch-and-Gif', packages=find_packages(), entry_points={ 'console_scripts':['glitch_this=glitch_this.commandline:main'], }, install_requires=[ 'Pillow>=6.2.1', 'numpy>=1.18.1', ], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )
356
310
<gh_stars>100-1000 package org.ofbiz.common.image.scaler; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.ofbiz.base.util.Debug; import org.ofbiz.common.image.ImageTransform; import org.ofbiz.common.image.ImageType; import org.ofbiz.common.image.ImageType.ImagePixelType; import org.ofbiz.common.image.ImageType.ImageTypeInfo; import com.mortennobel.imagescaling.ResampleFilter; import com.mortennobel.imagescaling.ResampleFilters; import com.mortennobel.imagescaling.ResampleOp; /** * SCIPIO: <NAME> java-image-scaler image scaler implementation. * By default uses lanczos3 filter. * <p> * Supported scalingOptions: * <ul> * <li>filter (String) - "smooth" (default) or substitute (see {@link #filterMap} below for supported)</li> * </ul> * </p> * TODO: this is only using the ResampleOp for now; there is also MultiStepRescaleOp. * <p> * Added 2017-07-10. */ public class MnjimImageScaler extends AbstractImageScaler { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); public static final String API_NAME = "mortennobel"; /** * Maps <code>scalingOptions.filter</code> to ResampleFilter instances. */ private static final Map<String, ResampleFilter> filterMap; static { Map<String, ResampleFilter> map = new HashMap<>(); // GENERALIZED //map.put("areaaveraging", Image.SCALE_AREA_AVERAGING); // TODO //map.put("default", Image.SCALE_DEFAULT); // TODO //map.put("fast", Image.SCALE_FAST); // TODO //map.put("replicate", Image.SCALE_REPLICATE); // TODO map.put("smooth", ResampleFilters.getLanczos3Filter()); // SPECIFIC ALGORITHMS map.put("lanczos3", ResampleFilters.getLanczos3Filter()); map.put("bicubic", ResampleFilters.getBiCubicFilter()); map.put("bicubichf", ResampleFilters.getBiCubicHighFreqResponse()); map.put("mitchell", ResampleFilters.getMitchellFilter()); map.put("hermite", ResampleFilters.getHermiteFilter()); map.put("bspline", ResampleFilters.getBSplineFilter()); map.put("triangle", ResampleFilters.getTriangleFilter()); map.put("bell", ResampleFilters.getBellFilter()); map.put("box", ResampleFilters.getBoxFilter()); // API-SPECIFIC // (none) filterMap = Collections.unmodifiableMap(map); Debug.logInfo(AbstractImageScaler.getFilterMapLogRepr(API_NAME, map), module); } public static final Map<String, Object> DEFAULT_OPTIONS; static { Map<String, Object> options = new HashMap<>(); putDefaultImageTypeOptions(options); options.put("filter", filterMap.get("smooth")); // String DEFAULT_OPTIONS = Collections.unmodifiableMap(options); } protected MnjimImageScaler(AbstractImageScalerFactory<MnjimImageScaler> factory, String name, Map<String, Object> confOptions) { super(factory, name, confOptions, factory.getDefaultOptions()); } public static class Factory extends AbstractImageScalerFactory<MnjimImageScaler> { @Override public MnjimImageScaler getImageOpInstStrict(String name, Map<String, Object> defaultScalingOptions) { return new MnjimImageScaler(this, name, defaultScalingOptions); } @Override public Map<String, Object> makeValidOptions(Map<String, Object> options) { Map<String, Object> validOptions = new HashMap<>(options); putCommonImageTypeOptions(validOptions, options); putOption(validOptions, "filter", getFilter(options), options); return validOptions; } @Override protected String getApiName() { return API_NAME; } @Override public Map<String, Object> getDefaultOptions() { return DEFAULT_OPTIONS; } } @Override protected BufferedImage scaleImageCore(BufferedImage image, int targetWidth, int targetHeight, Map<String, Object> options) throws IOException { ResampleFilter filter = getFilter(options); // this appears to be pointless - morten already converts to a type that it likes - it's // the result image type that matters to us... // // PRE-CONVERT: morten doesn't use the same defaults as us... // if (image.getType() == BufferedImage.TYPE_BYTE_BINARY || // image.getType() == BufferedImage.TYPE_BYTE_INDEXED || // image.getType() == BufferedImage.TYPE_CUSTOM) { // Integer fallbacktype = image.getColorModel().hasAlpha() ? getFallbacktype(options) : getFallbacktypenoalpha(options); // image = ImageUtils.convert(image, fallbacktype); // // orig: // //image = ImageUtils.convert(image, image.getColorModel().hasAlpha() ? // // BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR); // } ResampleOp op = new ResampleOp(targetWidth, targetHeight); if (filter != null) { op.setFilter(filter); } // HOW THIS WORKS: we try our best to get the filter to write directly in the image pixel type requested. // But morten does not support indexed images as output, and in addition, reconverting after is not guaranteed lossless. // In that case there are two options: // 1) scale + reconvert in two steps to honor requested image pixel type: could result in losses // 2) don't honor the requested image pixel type: changes the format, but usually lossless // TODO: REVIEW: the new BufferedImage calls do not transfer over all possible info like ColorModel, but morten itself doesn't either, so... // maybe we should re-check TYPE_PRESERVE and call ImageTransform.createCompatibleBufferedImage... ImageType targetType = getMergedTargetImageType(options, ImageType.EMPTY); ImageTypeInfo targetTypeInfo = targetType.getImageTypeInfoFor(image); BufferedImage resultImage; if (!ImagePixelType.isTypeNoPreserveOrNull(targetTypeInfo.getPixelType())) { ImageTypeInfo resolvedTargetTypeInfo = ImageType.resolveTargetType(targetTypeInfo, image); if (isNativeSupportedDestImageType(resolvedTargetTypeInfo)) { // here lib will _probably_ support the type we want... BufferedImage destImage = ImageTransform.createBufferedImage(resolvedTargetTypeInfo, targetWidth, targetHeight); resultImage = op.filter(image, destImage); } else { if (isPostConvertResultImage(image, options, targetTypeInfo)) { resultImage = op.filter(image, null); // lib default image type should preserve best for intermediate resultImage = checkConvertResultImageType(image, resultImage, options, targetTypeInfo); } else { int nextTargetType = getFirstSupportedDestPixelTypeFromAllDefaults(options, image); resultImage = op.filter(image, new BufferedImage(targetWidth, targetHeight, nextTargetType)); } } } else { int nextTargetType = getFirstSupportedDestPixelTypeFromAllDefaults(options, image); resultImage = op.filter(image, new BufferedImage(targetWidth, targetHeight, nextTargetType)); } return resultImage; } // NOTE: defaults are handled through the options merging with defaults protected static ResampleFilter getFilter(Map<String, Object> options) throws IllegalArgumentException { Object filterObj = options.get("filter"); if (filterObj == null) return null; else if (filterObj instanceof ResampleFilter) return (ResampleFilter) filterObj; else { String filterName = (String) filterObj; if (filterName.isEmpty()) return null; if (!filterMap.containsKey(filterName)) throw new IllegalArgumentException("filter '" + filterName + "' not supported by " + API_NAME + " library"); return filterMap.get(filterName); } } @Override public boolean isNativeSupportedDestImagePixelType(int imagePixelType) { // TODO: REVIEW return !ImagePixelType.isTypeIndexedOrCustom(imagePixelType); } }
3,148
1,921
<filename>crawl-ref/source/glwrapper.cc #include "AppHdr.h" #ifdef USE_TILE_LOCAL #include "glwrapper.h" ///////////////////////////////////////////////////////////////////////////// // VColour VColour VColour::white(255, 255, 255, 255); VColour VColour::black(0, 0, 0, 255); VColour VColour::transparent(0, 0, 0, 0); bool VColour::operator==(const VColour &vc) const { return r == vc.r && g == vc.g && b == vc.b && a == vc.a; } bool VColour::operator!=(const VColour &vc) const { return r != vc.r || g != vc.g || b != vc.b || a != vc.a; } ///////////////////////////////////////////////////////////////////////////// // GLState // Note: these defaults should match the OpenGL defaults GLState::GLState() : array_vertex(false), array_texcoord(false), array_colour(false), blend(false), texture(false), depthtest(false), alphatest(false), alpharef(0), colour(VColour::white) { } GLState::GLState(const GLState &state) : array_vertex(state.array_vertex), array_texcoord(state.array_texcoord), array_colour(state.array_colour), blend(state.blend), texture(state.texture), depthtest(state.depthtest), alphatest(state.alphatest), alpharef(state.alpharef), colour(state.colour) { } const GLState &GLState::operator=(const GLState &state) { array_vertex = state.array_vertex; array_texcoord = state.array_texcoord; array_colour = state.array_colour; blend = state.blend; texture = state.texture; depthtest = state.depthtest; alphatest = state.alphatest; alpharef = state.alpharef; colour = state.colour; return *this; } bool GLState::operator==(const GLState &state) const { return array_vertex == state.array_vertex && array_texcoord == state.array_texcoord && array_colour == state.array_colour && blend == state.blend && texture == state.texture && depthtest == state.depthtest && alphatest == state.alphatest && alpharef == state.alpharef && colour == state.colour; } ///////////////////////////////////////////////////////////////////////////// // GLStateManager #ifdef ASSERTS bool GLStateManager::_valid(int num_verts, drawing_modes mode) { switch (mode) { case GLW_RECTANGLE: return num_verts % 4 == 0; case GLW_LINES: return num_verts % 2 == 0; default: return false; } } #endif // ASSERTS #endif // USE_TILE_LOCAL
988
1,338
/* * Copyright 2008, Haiku Inc. All Rights Reserved. * Distributed under the terms of the MIT License. */ #ifndef _NET_KIT_H_ #define _NET_KIT_H_ #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <NetAddress.h> #include <NetBuffer.h> #include <NetEndpoint.h> #endif // _NET_KIT_H_
127
928
#!/usr/bin/env python3 def shared_in_s1_and_s2(): return 'Hello from s2'
34
1,716
// // JKFoundation.h // JKCategories // // Created by Jakey on 16/5/29. // Copyright © 2016年 www.skyfox.org. All rights reserved. // #if __has_include(<JKCategories/JKFoundation.h>) #import <JKCategories/NSArray+JKBlock.h> #import <JKCategories/NSArray+JKSafeAccess.h> #import <JKCategories/NSBundle+JKAppIcon.h> #import <JKCategories/NSData+JKAPNSToken.h> #import <JKCategories/NSData+JKBase64.h> #import <JKCategories/NSData+JKDataCache.h> #import <JKCategories/NSData+JKEncrypt.h> #import <JKCategories/NSData+JKGzip.h> #import <JKCategories/NSData+JKHash.h> #import <JKCategories/NSData+JKzlib.h> #import <JKCategories/NSData+JKPCM.h> #import <JKCategories/NSDate+JKExtension.h> #import <JKCategories/NSDate+JKFormatter.h> #import <JKCategories/NSDate+JKInternetDateTime.h> #import <JKCategories/NSDate+JKReporting.h> #import <JKCategories/NSDate+JKUtilities.h> #import <JKCategories/NSDate+JKZeroDate.h> #import <JKCategories/NSDate+JKLunarCalendar.h> #import <JKCategories/NSDateFormatter+JKMake.h> #import <JKCategories/NSDecimalNumber+JKCalculatingByString.h> #import <JKCategories/NSDecimalNumber+JKExtensions.h> #import <JKCategories/NSDictionary+JKBlock.h> #import <JKCategories/NSDictionary+JKJSONString.h> #import <JKCategories/NSDictionary+JKMerge.h> #import <JKCategories/NSDictionary+JKSafeAccess.h> #import <JKCategories/NSDictionary+JKURL.h> #import <JKCategories/NSDictionary+JKXML.h> #import <JKCategories/NSException+JKTrace.h> #import <JKCategories/NSFileHandle+JKReadLine.h> #import <JKCategories/NSFileManager+JKPaths.h> #import <JKCategories/NSHTTPCookieStorage+JKFreezeDry.h> #import <JKCategories/NSIndexPath+JKOffset.h> #import <JKCategories/NSInvocation+JKBb.h> #import <JKCategories/NSInvocation+JKBlock.h> #import <JKCategories/NSMutableURLRequest+JKUpload.h> #import <JKCategories/NSNotificationCenter+JKMainThread.h> #import <JKCategories/NSNumber+JKCGFloat.h> #import <JKCategories/NSNumber+JKRomanNumerals.h> #import <JKCategories/NSNumber+JKRound.h> #import <JKCategories/NSObject+JKAddProperty.h> #import <JKCategories/NSObject+JKAppInfo.h> #import <JKCategories/NSObject+JKAssociatedObject.h> #import <JKCategories/NSObject+JKAutoCoding.h> #import <JKCategories/NSObject+JKBlocks.h> #import <JKCategories/NSObject+JKBlockTimer.h> #import <JKCategories/NSObject+JKEasyCopy.h> #import <JKCategories/NSObject+JKGCD.h> #import <JKCategories/NSObject+JKKVOBlocks.h> #import <JKCategories/NSObject+JKReflection.h> #import <JKCategories/NSObject+JKRuntime.h> #import <JKCategories/NSRunLoop+JKPerformBlock.h> #import <JKCategories/NSSet+JKBlock.h> #import <JKCategories/NSString+JKBase64.h> #import <JKCategories/NSString+JKContains.h> #import <JKCategories/NSString+JKDictionaryValue.h> #import <JKCategories/NSString+JKEmoji.h> #import <JKCategories/NSString+JKEncrypt.h> #import <JKCategories/NSString+JKHash.h> #import <JKCategories/NSString+JKMatcher.h> #import <JKCategories/NSString+JKMIME.h> #import <JKCategories/NSString+JKNormalRegex.h> #import <JKCategories/NSString+JKPinyin.h> #import <JKCategories/NSString+JKRemoveEmoji.h> #import <JKCategories/NSString+JKScore.h> #import <JKCategories/NSString+JKSize.h> #import <JKCategories/NSString+JKTrims.h> #import <JKCategories/NSString+JKURLEncode.h> #import <JKCategories/NSString+JKUUID.h> #import <JKCategories/NSString+JKXMLDictionary.h> #import <JKCategories/NSString+JKStringPages.h> #import <JKCategories/NSString+JKHTML.h> #import <JKCategories/NSTimer+JKAddition.h> #import <JKCategories/NSTimer+JKBlocks.h> #import <JKCategories/NSURL+JKParam.h> #import <JKCategories/NSURL+JKQueryDictionary.h> #import <JKCategories/NSURLConnection+JKSelfSigned.h> #import <JKCategories/NSURLRequest+JKParamsFromDictionary.h> #import <JKCategories/NSURLSession+JKSynchronousTask.h> #import <JKCategories/NSUserDefaults+JKiCloudSync.h> #import <JKCategories/NSUserDefaults+JKSafeAccess.h> #else #import "NSArray+JKBlock.h" #import "NSArray+JKSafeAccess.h" #import "NSBundle+JKAppIcon.h" #import "NSData+JKAPNSToken.h" #import "NSData+JKBase64.h" #import "NSData+JKDataCache.h" #import "NSData+JKEncrypt.h" #import "NSData+JKGzip.h" #import "NSData+JKHash.h" #import "NSData+JKzlib.h" #import "NSData+JKPCM.h" #import "NSDate+JKExtension.h" #import "NSDate+JKFormatter.h" #import "NSDate+JKInternetDateTime.h" #import "NSDate+JKReporting.h" #import "NSDate+JKUtilities.h" #import "NSDate+JKZeroDate.h" #import "NSDate+JKLunarCalendar.h" #import "NSDateFormatter+JKMake.h" #import "NSDecimalNumber+JKCalculatingByString.h" #import "NSDecimalNumber+JKExtensions.h" #import "NSDictionary+JKBlock.h" #import "NSDictionary+JKJSONString.h" #import "NSDictionary+JKMerge.h" #import "NSDictionary+JKSafeAccess.h" #import "NSDictionary+JKURL.h" #import "NSDictionary+JKXML.h" #import "NSException+JKTrace.h" #import "NSFileHandle+JKReadLine.h" #import "NSFileManager+JKPaths.h" #import "NSHTTPCookieStorage+JKFreezeDry.h" #import "NSIndexPath+JKOffset.h" #import "NSInvocation+JKBb.h" #import "NSInvocation+JKBlock.h" #import "NSMutableURLRequest+JKUpload.h" #import "NSNotificationCenter+JKMainThread.h" #import "NSNumber+JKCGFloat.h" #import "NSNumber+JKRomanNumerals.h" #import "NSNumber+JKRound.h" #import "NSObject+JKAddProperty.h" #import "NSObject+JKAppInfo.h" #import "NSObject+JKAssociatedObject.h" #import "NSObject+JKAutoCoding.h" #import "NSObject+JKBlocks.h" #import "NSObject+JKBlockTimer.h" #import "NSObject+JKEasyCopy.h" #import "NSObject+JKGCD.h" #import "NSObject+JKKVOBlocks.h" #import "NSObject+JKReflection.h" #import "NSObject+JKRuntime.h" #import "NSRunLoop+JKPerformBlock.h" #import "NSSet+JKBlock.h" #import "NSString+JKBase64.h" #import "NSString+JKContains.h" #import "NSString+JKDictionaryValue.h" #import "NSString+JKEmoji.h" #import "NSString+JKEncrypt.h" #import "NSString+JKHash.h" #import "NSString+JKMatcher.h" #import "NSString+JKMIME.h" #import "NSString+JKNormalRegex.h" #import "NSString+JKPinyin.h" #import "NSString+JKRemoveEmoji.h" #import "NSString+JKScore.h" #import "NSString+JKSize.h" #import "NSString+JKTrims.h" #import "NSString+JKURLEncode.h" #import "NSString+JKUUID.h" #import "NSString+JKXMLDictionary.h" #import "NSString+JKStringPages.h" #import "NSString+JKHTML.h" #import "NSTimer+JKAddition.h" #import "NSTimer+JKBlocks.h" #import "NSURL+JKParam.h" #import "NSURL+JKQueryDictionary.h" #import "NSURLConnection+JKSelfSigned.h" #import "NSURLRequest+JKParamsFromDictionary.h" #import "NSURLSession+JKSynchronousTask.h" #import "NSUserDefaults+JKiCloudSync.h" #import "NSUserDefaults+JKSafeAccess.h" #endif
2,741
2,151
<gh_stars>1000+ // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_COMMON_SINGLE_REQUEST_URL_LOADER_FACTORY_H_ #define CONTENT_COMMON_SINGLE_REQUEST_URL_LOADER_FACTORY_H_ #include "services/network/public/cpp/shared_url_loader_factory.h" #include "base/memory/ref_counted.h" #include "services/network/public/mojom/url_loader.mojom.h" namespace content { // An implementation of SharedURLLoaderFactory which handles only a single // request. It's an error to call CreateLoaderAndStart() more than a total of // one time across this object or any of its clones. class SingleRequestURLLoaderFactory : public network::SharedURLLoaderFactory { public: using RequestHandler = base::OnceCallback<void(network::mojom::URLLoaderRequest, network::mojom::URLLoaderClientPtr)>; explicit SingleRequestURLLoaderFactory(RequestHandler handler); // SharedURLLoaderFactory: void CreateLoaderAndStart(network::mojom::URLLoaderRequest loader, int32_t routing_id, int32_t request_id, uint32_t options, const network::ResourceRequest& request, network::mojom::URLLoaderClientPtr client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override; void Clone(network::mojom::URLLoaderFactoryRequest request) override; std::unique_ptr<network::SharedURLLoaderFactoryInfo> Clone() override; private: class FactoryInfo; class HandlerState; explicit SingleRequestURLLoaderFactory(scoped_refptr<HandlerState> state); ~SingleRequestURLLoaderFactory() override; scoped_refptr<HandlerState> state_; DISALLOW_COPY_AND_ASSIGN(SingleRequestURLLoaderFactory); }; } // namespace content #endif // CONTENT_COMMON_SINGLE_REQUEST_URL_LOADER_FACTORY_H_
805
2,504
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #pragma once #include "Common\DeviceResources.h" #include "PhotoAdjustmentProperties.h" namespace D2DPhotoAdjustment { class PhotoAdjustmentRenderer : public DX::IDeviceNotify { public: PhotoAdjustmentRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources); ~PhotoAdjustmentRenderer(); void CreateDeviceIndependentResources(); void CreateDeviceDependentResources(); void CreateWindowSizeDependentResources(); void ReleaseDeviceDependentResources(); void OnColorProfileChanged(_In_ Windows::Graphics::Display::DisplayInformation^ sender); void UpdatePhotoAdjustmentValues(PhotoAdjustmentProperties properties); void Draw(); // IDeviceNotify methods handle device lost and restored. virtual void OnDeviceLost(); virtual void OnDeviceRestored(); private: void UpdateZoomState(); void UpdateDisplayColorContext(_In_ Windows::Storage::Streams::DataReader^ colorProfileDataReader); float ConvertDipProperty(float valueInDips); private: // Cached pointer to device resources. std::shared_ptr<DX::DeviceResources> m_deviceResources; Platform::Agile<Windows::UI::Input::GestureRecognizer> m_gestureRecognizer; Microsoft::WRL::ComPtr<IWICFormatConverter> m_formatConvert; // Device-independent resources. Microsoft::WRL::ComPtr<IWICColorContext> m_wicColorContext; // Device-dependent resources. Microsoft::WRL::ComPtr<ID2D1ImageSourceFromWic> m_imageSource; Microsoft::WRL::ComPtr<ID2D1TransformedImageSource> m_scaledImage; Microsoft::WRL::ComPtr<ID2D1Effect> m_colorManagement; Microsoft::WRL::ComPtr<ID2D1Effect> m_straighten; Microsoft::WRL::ComPtr<ID2D1Effect> m_temperatureTint; Microsoft::WRL::ComPtr<ID2D1Effect> m_saturation; Microsoft::WRL::ComPtr<ID2D1Effect> m_contrast; Microsoft::WRL::ComPtr<ID2D1Effect> m_highlightsShadows; Microsoft::WRL::ComPtr<ID2D1Effect> m_outputEffect; // Image view state. Windows::Foundation::Size m_imageSize; Windows::Foundation::Size m_panelSize; float m_zoom; bool m_isWindowClosed; // Effect properties measured in DIPs. float m_hsMaskRadiusDips; // Adjustable parameters. float m_maxZoom; }; }
1,586
451
<filename>CodeGenere/photogram/cREgDistDxDy_Fraser_PPaEqPPs.cpp // File Automatically generated by eLiSe #include "StdAfx.h" #include "cREgDistDxDy_Fraser_PPaEqPPs.h" cREgDistDxDy_Fraser_PPaEqPPs::cREgDistDxDy_Fraser_PPaEqPPs(): cElCompiledFonc(2) { AddIntRef (cIncIntervale("Intr",0,12)); Close(false); } void cREgDistDxDy_Fraser_PPaEqPPs::ComputeVal() { double tmp0_ = mCompCoord[1]; double tmp1_ = mLocRegDistxy1_x - tmp0_; double tmp2_ = mCompCoord[2]; double tmp3_ = mLocRegDistxy1_y - tmp2_; double tmp4_ = (tmp1_) * (tmp1_); double tmp5_ = (tmp3_) * (tmp3_); double tmp6_ = tmp4_ + tmp5_; double tmp7_ = (tmp6_) * (tmp6_); double tmp8_ = tmp7_ * (tmp6_); double tmp9_ = tmp8_ * (tmp6_); double tmp10_ = mCompCoord[3]; double tmp11_ = mLocRegDistxy2_x - tmp0_; double tmp12_ = mLocRegDistxy2_y - tmp2_; double tmp13_ = mCompCoord[4]; double tmp14_ = (tmp11_) * (tmp11_); double tmp15_ = (tmp12_) * (tmp12_); double tmp16_ = tmp14_ + tmp15_; double tmp17_ = mCompCoord[5]; double tmp18_ = (tmp16_) * (tmp16_); double tmp19_ = mCompCoord[6]; double tmp20_ = tmp18_ * (tmp16_); double tmp21_ = mCompCoord[7]; double tmp22_ = tmp20_ * (tmp16_); double tmp23_ = mCompCoord[8]; double tmp24_ = mCompCoord[9]; double tmp25_ = mCompCoord[10]; double tmp26_ = mCompCoord[11]; double tmp27_ = mLocRegDistxy3_x - tmp0_; double tmp28_ = mLocRegDistxy3_y - tmp2_; double tmp29_ = (tmp27_) * (tmp27_); double tmp30_ = (tmp28_) * (tmp28_); double tmp31_ = tmp29_ + tmp30_; double tmp32_ = (tmp31_) * (tmp31_); double tmp33_ = tmp32_ * (tmp31_); double tmp34_ = tmp33_ * (tmp31_); double tmp35_ = mLocRegDistxy4_x - tmp0_; double tmp36_ = mLocRegDistxy4_y - tmp2_; double tmp37_ = (tmp35_) * (tmp35_); double tmp38_ = (tmp36_) * (tmp36_); double tmp39_ = tmp37_ + tmp38_; double tmp40_ = (tmp39_) * (tmp39_); double tmp41_ = tmp40_ * (tmp39_); double tmp42_ = tmp41_ * (tmp39_); double tmp43_ = tmp10_ * (tmp6_); double tmp44_ = tmp13_ * tmp7_; double tmp45_ = tmp43_ + tmp44_; double tmp46_ = tmp17_ * tmp8_; double tmp47_ = tmp45_ + tmp46_; double tmp48_ = tmp19_ * tmp9_; double tmp49_ = tmp47_ + tmp48_; double tmp50_ = tmp9_ * (tmp6_); double tmp51_ = tmp21_ * tmp50_; double tmp52_ = tmp49_ + tmp51_; double tmp53_ = (tmp1_) * (tmp3_); double tmp54_ = 2 * tmp53_; double tmp55_ = tmp10_ * (tmp16_); double tmp56_ = tmp13_ * tmp18_; double tmp57_ = tmp55_ + tmp56_; double tmp58_ = tmp17_ * tmp20_; double tmp59_ = tmp57_ + tmp58_; double tmp60_ = tmp19_ * tmp22_; double tmp61_ = tmp59_ + tmp60_; double tmp62_ = tmp22_ * (tmp16_); double tmp63_ = tmp21_ * tmp62_; double tmp64_ = tmp61_ + tmp63_; double tmp65_ = (tmp11_) * (tmp12_); double tmp66_ = 2 * tmp65_; double tmp67_ = tmp10_ * (tmp31_); double tmp68_ = tmp13_ * tmp32_; double tmp69_ = tmp67_ + tmp68_; double tmp70_ = tmp17_ * tmp33_; double tmp71_ = tmp69_ + tmp70_; double tmp72_ = tmp19_ * tmp34_; double tmp73_ = tmp71_ + tmp72_; double tmp74_ = tmp34_ * (tmp31_); double tmp75_ = tmp21_ * tmp74_; double tmp76_ = tmp73_ + tmp75_; double tmp77_ = (tmp27_) * (tmp28_); double tmp78_ = 2 * tmp77_; double tmp79_ = tmp10_ * (tmp39_); double tmp80_ = tmp13_ * tmp40_; double tmp81_ = tmp79_ + tmp80_; double tmp82_ = tmp17_ * tmp41_; double tmp83_ = tmp81_ + tmp82_; double tmp84_ = tmp19_ * tmp42_; double tmp85_ = tmp83_ + tmp84_; double tmp86_ = tmp42_ * (tmp39_); double tmp87_ = tmp21_ * tmp86_; double tmp88_ = tmp85_ + tmp87_; double tmp89_ = (tmp35_) * (tmp36_); double tmp90_ = 2 * tmp89_; mVal[0] = (mLocRegDistxy1_x + (tmp1_) * (tmp52_) + (2 * tmp4_ + tmp6_) * tmp23_ + tmp54_ * tmp24_ + tmp25_ * (tmp1_) + tmp26_ * (tmp3_) + mLocRegDistxy2_x + (tmp11_) * (tmp64_) + (2 * tmp14_ + tmp16_) * tmp23_ + tmp66_ * tmp24_ + tmp25_ * (tmp11_) + tmp26_ * (tmp12_)) - (mLocRegDistxy3_x + (tmp27_) * (tmp76_) + (2 * tmp29_ + tmp31_) * tmp23_ + tmp78_ * tmp24_ + tmp25_ * (tmp27_) + tmp26_ * (tmp28_) + mLocRegDistxy4_x + (tmp35_) * (tmp88_) + (2 * tmp37_ + tmp39_) * tmp23_ + tmp90_ * tmp24_ + tmp25_ * (tmp35_) + tmp26_ * (tmp36_)); mVal[1] = (mLocRegDistxy1_y + (tmp3_) * (tmp52_) + (2 * tmp5_ + tmp6_) * tmp24_ + tmp54_ * tmp23_ + mLocRegDistxy2_y + (tmp12_) * (tmp64_) + (2 * tmp15_ + tmp16_) * tmp24_ + tmp66_ * tmp23_) - (mLocRegDistxy3_y + (tmp28_) * (tmp76_) + (2 * tmp30_ + tmp31_) * tmp24_ + tmp78_ * tmp23_ + mLocRegDistxy4_y + (tmp36_) * (tmp88_) + (2 * tmp38_ + tmp39_) * tmp24_ + tmp90_ * tmp23_); } void cREgDistDxDy_Fraser_PPaEqPPs::ComputeValDeriv() { double tmp0_ = mCompCoord[1]; double tmp1_ = mLocRegDistxy1_x - tmp0_; double tmp2_ = mCompCoord[2]; double tmp3_ = mLocRegDistxy1_y - tmp2_; double tmp4_ = (tmp1_) * (tmp1_); double tmp5_ = (tmp3_) * (tmp3_); double tmp6_ = tmp4_ + tmp5_; double tmp7_ = (tmp6_) * (tmp6_); double tmp8_ = tmp7_ * (tmp6_); double tmp9_ = tmp8_ * (tmp6_); double tmp10_ = mCompCoord[3]; double tmp11_ = mLocRegDistxy2_x - tmp0_; double tmp12_ = mLocRegDistxy2_y - tmp2_; double tmp13_ = mCompCoord[4]; double tmp14_ = (tmp11_) * (tmp11_); double tmp15_ = (tmp12_) * (tmp12_); double tmp16_ = tmp14_ + tmp15_; double tmp17_ = mCompCoord[5]; double tmp18_ = (tmp16_) * (tmp16_); double tmp19_ = mCompCoord[6]; double tmp20_ = tmp18_ * (tmp16_); double tmp21_ = mCompCoord[7]; double tmp22_ = tmp20_ * (tmp16_); double tmp23_ = mCompCoord[8]; double tmp24_ = mCompCoord[9]; double tmp25_ = mCompCoord[10]; double tmp26_ = mCompCoord[11]; double tmp27_ = mLocRegDistxy3_x - tmp0_; double tmp28_ = mLocRegDistxy3_y - tmp2_; double tmp29_ = (tmp27_) * (tmp27_); double tmp30_ = (tmp28_) * (tmp28_); double tmp31_ = tmp29_ + tmp30_; double tmp32_ = (tmp31_) * (tmp31_); double tmp33_ = tmp32_ * (tmp31_); double tmp34_ = tmp33_ * (tmp31_); double tmp35_ = mLocRegDistxy4_x - tmp0_; double tmp36_ = mLocRegDistxy4_y - tmp2_; double tmp37_ = (tmp35_) * (tmp35_); double tmp38_ = (tmp36_) * (tmp36_); double tmp39_ = tmp37_ + tmp38_; double tmp40_ = (tmp39_) * (tmp39_); double tmp41_ = tmp40_ * (tmp39_); double tmp42_ = tmp41_ * (tmp39_); double tmp43_ = tmp10_ * (tmp6_); double tmp44_ = tmp13_ * tmp7_; double tmp45_ = tmp43_ + tmp44_; double tmp46_ = tmp17_ * tmp8_; double tmp47_ = tmp45_ + tmp46_; double tmp48_ = tmp19_ * tmp9_; double tmp49_ = tmp47_ + tmp48_; double tmp50_ = tmp9_ * (tmp6_); double tmp51_ = tmp21_ * tmp50_; double tmp52_ = tmp49_ + tmp51_; double tmp53_ = -(1); double tmp54_ = tmp53_ * (tmp1_); double tmp55_ = tmp54_ + tmp54_; double tmp56_ = (tmp55_) * (tmp6_); double tmp57_ = tmp56_ + tmp56_; double tmp58_ = (tmp57_) * (tmp6_); double tmp59_ = (tmp55_) * tmp7_; double tmp60_ = tmp58_ + tmp59_; double tmp61_ = (tmp60_) * (tmp6_); double tmp62_ = (tmp55_) * tmp8_; double tmp63_ = tmp61_ + tmp62_; double tmp64_ = tmp10_ * (tmp16_); double tmp65_ = tmp13_ * tmp18_; double tmp66_ = tmp64_ + tmp65_; double tmp67_ = tmp17_ * tmp20_; double tmp68_ = tmp66_ + tmp67_; double tmp69_ = tmp19_ * tmp22_; double tmp70_ = tmp68_ + tmp69_; double tmp71_ = tmp22_ * (tmp16_); double tmp72_ = tmp21_ * tmp71_; double tmp73_ = tmp70_ + tmp72_; double tmp74_ = tmp53_ * (tmp11_); double tmp75_ = tmp74_ + tmp74_; double tmp76_ = (tmp75_) * (tmp16_); double tmp77_ = tmp76_ + tmp76_; double tmp78_ = (tmp77_) * (tmp16_); double tmp79_ = (tmp75_) * tmp18_; double tmp80_ = tmp78_ + tmp79_; double tmp81_ = (tmp80_) * (tmp16_); double tmp82_ = (tmp75_) * tmp20_; double tmp83_ = tmp81_ + tmp82_; double tmp84_ = tmp53_ * tmp25_; double tmp85_ = tmp10_ * (tmp31_); double tmp86_ = tmp13_ * tmp32_; double tmp87_ = tmp85_ + tmp86_; double tmp88_ = tmp17_ * tmp33_; double tmp89_ = tmp87_ + tmp88_; double tmp90_ = tmp19_ * tmp34_; double tmp91_ = tmp89_ + tmp90_; double tmp92_ = tmp34_ * (tmp31_); double tmp93_ = tmp21_ * tmp92_; double tmp94_ = tmp91_ + tmp93_; double tmp95_ = tmp53_ * (tmp27_); double tmp96_ = tmp95_ + tmp95_; double tmp97_ = (tmp96_) * (tmp31_); double tmp98_ = tmp97_ + tmp97_; double tmp99_ = (tmp98_) * (tmp31_); double tmp100_ = (tmp96_) * tmp32_; double tmp101_ = tmp99_ + tmp100_; double tmp102_ = (tmp101_) * (tmp31_); double tmp103_ = (tmp96_) * tmp33_; double tmp104_ = tmp102_ + tmp103_; double tmp105_ = tmp10_ * (tmp39_); double tmp106_ = tmp13_ * tmp40_; double tmp107_ = tmp105_ + tmp106_; double tmp108_ = tmp17_ * tmp41_; double tmp109_ = tmp107_ + tmp108_; double tmp110_ = tmp19_ * tmp42_; double tmp111_ = tmp109_ + tmp110_; double tmp112_ = tmp42_ * (tmp39_); double tmp113_ = tmp21_ * tmp112_; double tmp114_ = tmp111_ + tmp113_; double tmp115_ = tmp53_ * (tmp35_); double tmp116_ = tmp115_ + tmp115_; double tmp117_ = (tmp116_) * (tmp39_); double tmp118_ = tmp117_ + tmp117_; double tmp119_ = (tmp118_) * (tmp39_); double tmp120_ = (tmp116_) * tmp40_; double tmp121_ = tmp119_ + tmp120_; double tmp122_ = (tmp121_) * (tmp39_); double tmp123_ = (tmp116_) * tmp41_; double tmp124_ = tmp122_ + tmp123_; double tmp125_ = tmp53_ * (tmp3_); double tmp126_ = tmp125_ + tmp125_; double tmp127_ = (tmp126_) * (tmp6_); double tmp128_ = tmp127_ + tmp127_; double tmp129_ = (tmp128_) * (tmp6_); double tmp130_ = (tmp126_) * tmp7_; double tmp131_ = tmp129_ + tmp130_; double tmp132_ = (tmp131_) * (tmp6_); double tmp133_ = (tmp126_) * tmp8_; double tmp134_ = tmp132_ + tmp133_; double tmp135_ = tmp53_ * (tmp12_); double tmp136_ = tmp135_ + tmp135_; double tmp137_ = (tmp136_) * (tmp16_); double tmp138_ = tmp137_ + tmp137_; double tmp139_ = (tmp138_) * (tmp16_); double tmp140_ = (tmp136_) * tmp18_; double tmp141_ = tmp139_ + tmp140_; double tmp142_ = (tmp141_) * (tmp16_); double tmp143_ = (tmp136_) * tmp20_; double tmp144_ = tmp142_ + tmp143_; double tmp145_ = tmp53_ * tmp26_; double tmp146_ = tmp53_ * (tmp28_); double tmp147_ = tmp146_ + tmp146_; double tmp148_ = (tmp147_) * (tmp31_); double tmp149_ = tmp148_ + tmp148_; double tmp150_ = (tmp149_) * (tmp31_); double tmp151_ = (tmp147_) * tmp32_; double tmp152_ = tmp150_ + tmp151_; double tmp153_ = (tmp152_) * (tmp31_); double tmp154_ = (tmp147_) * tmp33_; double tmp155_ = tmp153_ + tmp154_; double tmp156_ = tmp53_ * (tmp36_); double tmp157_ = tmp156_ + tmp156_; double tmp158_ = (tmp157_) * (tmp39_); double tmp159_ = tmp158_ + tmp158_; double tmp160_ = (tmp159_) * (tmp39_); double tmp161_ = (tmp157_) * tmp40_; double tmp162_ = tmp160_ + tmp161_; double tmp163_ = (tmp162_) * (tmp39_); double tmp164_ = (tmp157_) * tmp41_; double tmp165_ = tmp163_ + tmp164_; double tmp166_ = 2 * tmp4_; double tmp167_ = tmp166_ + tmp6_; double tmp168_ = 2 * tmp14_; double tmp169_ = tmp168_ + tmp16_; double tmp170_ = 2 * tmp29_; double tmp171_ = tmp170_ + tmp31_; double tmp172_ = 2 * tmp37_; double tmp173_ = tmp172_ + tmp39_; double tmp174_ = (tmp1_) * (tmp3_); double tmp175_ = 2 * tmp174_; double tmp176_ = (tmp11_) * (tmp12_); double tmp177_ = 2 * tmp176_; double tmp178_ = (tmp27_) * (tmp28_); double tmp179_ = 2 * tmp178_; double tmp180_ = (tmp35_) * (tmp36_); double tmp181_ = 2 * tmp180_; double tmp182_ = (tmp55_) * tmp10_; double tmp183_ = (tmp57_) * tmp13_; double tmp184_ = tmp182_ + tmp183_; double tmp185_ = (tmp60_) * tmp17_; double tmp186_ = tmp184_ + tmp185_; double tmp187_ = (tmp63_) * tmp19_; double tmp188_ = tmp186_ + tmp187_; double tmp189_ = (tmp63_) * (tmp6_); double tmp190_ = (tmp55_) * tmp9_; double tmp191_ = tmp189_ + tmp190_; double tmp192_ = (tmp191_) * tmp21_; double tmp193_ = tmp188_ + tmp192_; double tmp194_ = tmp125_ * 2; double tmp195_ = (tmp75_) * tmp10_; double tmp196_ = (tmp77_) * tmp13_; double tmp197_ = tmp195_ + tmp196_; double tmp198_ = (tmp80_) * tmp17_; double tmp199_ = tmp197_ + tmp198_; double tmp200_ = (tmp83_) * tmp19_; double tmp201_ = tmp199_ + tmp200_; double tmp202_ = (tmp83_) * (tmp16_); double tmp203_ = (tmp75_) * tmp22_; double tmp204_ = tmp202_ + tmp203_; double tmp205_ = (tmp204_) * tmp21_; double tmp206_ = tmp201_ + tmp205_; double tmp207_ = tmp135_ * 2; double tmp208_ = (tmp96_) * tmp10_; double tmp209_ = (tmp98_) * tmp13_; double tmp210_ = tmp208_ + tmp209_; double tmp211_ = (tmp101_) * tmp17_; double tmp212_ = tmp210_ + tmp211_; double tmp213_ = (tmp104_) * tmp19_; double tmp214_ = tmp212_ + tmp213_; double tmp215_ = (tmp104_) * (tmp31_); double tmp216_ = (tmp96_) * tmp34_; double tmp217_ = tmp215_ + tmp216_; double tmp218_ = (tmp217_) * tmp21_; double tmp219_ = tmp214_ + tmp218_; double tmp220_ = tmp146_ * 2; double tmp221_ = (tmp116_) * tmp10_; double tmp222_ = (tmp118_) * tmp13_; double tmp223_ = tmp221_ + tmp222_; double tmp224_ = (tmp121_) * tmp17_; double tmp225_ = tmp223_ + tmp224_; double tmp226_ = (tmp124_) * tmp19_; double tmp227_ = tmp225_ + tmp226_; double tmp228_ = (tmp124_) * (tmp39_); double tmp229_ = (tmp116_) * tmp42_; double tmp230_ = tmp228_ + tmp229_; double tmp231_ = (tmp230_) * tmp21_; double tmp232_ = tmp227_ + tmp231_; double tmp233_ = tmp156_ * 2; double tmp234_ = tmp53_ * (tmp52_); double tmp235_ = (tmp126_) * tmp10_; double tmp236_ = (tmp128_) * tmp13_; double tmp237_ = tmp235_ + tmp236_; double tmp238_ = (tmp131_) * tmp17_; double tmp239_ = tmp237_ + tmp238_; double tmp240_ = (tmp134_) * tmp19_; double tmp241_ = tmp239_ + tmp240_; double tmp242_ = (tmp134_) * (tmp6_); double tmp243_ = (tmp126_) * tmp9_; double tmp244_ = tmp242_ + tmp243_; double tmp245_ = (tmp244_) * tmp21_; double tmp246_ = tmp241_ + tmp245_; double tmp247_ = tmp54_ * 2; double tmp248_ = tmp53_ * (tmp73_); double tmp249_ = (tmp136_) * tmp10_; double tmp250_ = (tmp138_) * tmp13_; double tmp251_ = tmp249_ + tmp250_; double tmp252_ = (tmp141_) * tmp17_; double tmp253_ = tmp251_ + tmp252_; double tmp254_ = (tmp144_) * tmp19_; double tmp255_ = tmp253_ + tmp254_; double tmp256_ = (tmp144_) * (tmp16_); double tmp257_ = (tmp136_) * tmp22_; double tmp258_ = tmp256_ + tmp257_; double tmp259_ = (tmp258_) * tmp21_; double tmp260_ = tmp255_ + tmp259_; double tmp261_ = tmp74_ * 2; double tmp262_ = tmp53_ * (tmp94_); double tmp263_ = (tmp147_) * tmp10_; double tmp264_ = (tmp149_) * tmp13_; double tmp265_ = tmp263_ + tmp264_; double tmp266_ = (tmp152_) * tmp17_; double tmp267_ = tmp265_ + tmp266_; double tmp268_ = (tmp155_) * tmp19_; double tmp269_ = tmp267_ + tmp268_; double tmp270_ = (tmp155_) * (tmp31_); double tmp271_ = (tmp147_) * tmp34_; double tmp272_ = tmp270_ + tmp271_; double tmp273_ = (tmp272_) * tmp21_; double tmp274_ = tmp269_ + tmp273_; double tmp275_ = tmp95_ * 2; double tmp276_ = tmp53_ * (tmp114_); double tmp277_ = (tmp157_) * tmp10_; double tmp278_ = (tmp159_) * tmp13_; double tmp279_ = tmp277_ + tmp278_; double tmp280_ = (tmp162_) * tmp17_; double tmp281_ = tmp279_ + tmp280_; double tmp282_ = (tmp165_) * tmp19_; double tmp283_ = tmp281_ + tmp282_; double tmp284_ = (tmp165_) * (tmp39_); double tmp285_ = (tmp157_) * tmp42_; double tmp286_ = tmp284_ + tmp285_; double tmp287_ = (tmp286_) * tmp21_; double tmp288_ = tmp283_ + tmp287_; double tmp289_ = tmp115_ * 2; double tmp290_ = tmp175_ + tmp177_; double tmp291_ = tmp179_ + tmp181_; double tmp292_ = (tmp290_) - (tmp291_); double tmp293_ = 2 * tmp5_; double tmp294_ = tmp293_ + tmp6_; double tmp295_ = 2 * tmp15_; double tmp296_ = tmp295_ + tmp16_; double tmp297_ = 2 * tmp30_; double tmp298_ = tmp297_ + tmp31_; double tmp299_ = 2 * tmp38_; double tmp300_ = tmp299_ + tmp39_; mVal[0] = (mLocRegDistxy1_x + (tmp1_) * (tmp52_) + (tmp167_) * tmp23_ + tmp175_ * tmp24_ + tmp25_ * (tmp1_) + tmp26_ * (tmp3_) + mLocRegDistxy2_x + (tmp11_) * (tmp73_) + (tmp169_) * tmp23_ + tmp177_ * tmp24_ + tmp25_ * (tmp11_) + tmp26_ * (tmp12_)) - (mLocRegDistxy3_x + (tmp27_) * (tmp94_) + (tmp171_) * tmp23_ + tmp179_ * tmp24_ + tmp25_ * (tmp27_) + tmp26_ * (tmp28_) + mLocRegDistxy4_x + (tmp35_) * (tmp114_) + (tmp173_) * tmp23_ + tmp181_ * tmp24_ + tmp25_ * (tmp35_) + tmp26_ * (tmp36_)); mCompDer[0][0] = 0; mCompDer[0][1] = (tmp234_ + (tmp193_) * (tmp1_) + ((tmp55_) * 2 + tmp55_) * tmp23_ + tmp194_ * tmp24_ + tmp84_ + tmp248_ + (tmp206_) * (tmp11_) + ((tmp75_) * 2 + tmp75_) * tmp23_ + tmp207_ * tmp24_ + tmp84_) - (tmp262_ + (tmp219_) * (tmp27_) + ((tmp96_) * 2 + tmp96_) * tmp23_ + tmp220_ * tmp24_ + tmp84_ + tmp276_ + (tmp232_) * (tmp35_) + ((tmp116_) * 2 + tmp116_) * tmp23_ + tmp233_ * tmp24_ + tmp84_); mCompDer[0][2] = ((tmp246_) * (tmp1_) + (tmp126_) * tmp23_ + tmp247_ * tmp24_ + tmp145_ + (tmp260_) * (tmp11_) + (tmp136_) * tmp23_ + tmp261_ * tmp24_ + tmp145_) - ((tmp274_) * (tmp27_) + (tmp147_) * tmp23_ + tmp275_ * tmp24_ + tmp145_ + (tmp288_) * (tmp35_) + (tmp157_) * tmp23_ + tmp289_ * tmp24_ + tmp145_); mCompDer[0][3] = ((tmp6_) * (tmp1_) + (tmp16_) * (tmp11_)) - ((tmp31_) * (tmp27_) + (tmp39_) * (tmp35_)); mCompDer[0][4] = (tmp7_ * (tmp1_) + tmp18_ * (tmp11_)) - (tmp32_ * (tmp27_) + tmp40_ * (tmp35_)); mCompDer[0][5] = (tmp8_ * (tmp1_) + tmp20_ * (tmp11_)) - (tmp33_ * (tmp27_) + tmp41_ * (tmp35_)); mCompDer[0][6] = (tmp9_ * (tmp1_) + tmp22_ * (tmp11_)) - (tmp34_ * (tmp27_) + tmp42_ * (tmp35_)); mCompDer[0][7] = (tmp50_ * (tmp1_) + tmp71_ * (tmp11_)) - (tmp92_ * (tmp27_) + tmp112_ * (tmp35_)); mCompDer[0][8] = (tmp167_ + tmp169_) - (tmp171_ + tmp173_); mCompDer[0][9] = tmp292_; mCompDer[0][10] = (tmp1_ + tmp11_) - (tmp27_ + tmp35_); mCompDer[0][11] = (tmp3_ + tmp12_) - (tmp28_ + tmp36_); mVal[1] = (mLocRegDistxy1_y + (tmp3_) * (tmp52_) + (tmp294_) * tmp24_ + tmp175_ * tmp23_ + mLocRegDistxy2_y + (tmp12_) * (tmp73_) + (tmp296_) * tmp24_ + tmp177_ * tmp23_) - (mLocRegDistxy3_y + (tmp28_) * (tmp94_) + (tmp298_) * tmp24_ + tmp179_ * tmp23_ + mLocRegDistxy4_y + (tmp36_) * (tmp114_) + (tmp300_) * tmp24_ + tmp181_ * tmp23_); mCompDer[1][0] = 0; mCompDer[1][1] = ((tmp193_) * (tmp3_) + (tmp55_) * tmp24_ + tmp194_ * tmp23_ + (tmp206_) * (tmp12_) + (tmp75_) * tmp24_ + tmp207_ * tmp23_) - ((tmp219_) * (tmp28_) + (tmp96_) * tmp24_ + tmp220_ * tmp23_ + (tmp232_) * (tmp36_) + (tmp116_) * tmp24_ + tmp233_ * tmp23_); mCompDer[1][2] = (tmp234_ + (tmp246_) * (tmp3_) + ((tmp126_) * 2 + tmp126_) * tmp24_ + tmp247_ * tmp23_ + tmp248_ + (tmp260_) * (tmp12_) + ((tmp136_) * 2 + tmp136_) * tmp24_ + tmp261_ * tmp23_) - (tmp262_ + (tmp274_) * (tmp28_) + ((tmp147_) * 2 + tmp147_) * tmp24_ + tmp275_ * tmp23_ + tmp276_ + (tmp288_) * (tmp36_) + ((tmp157_) * 2 + tmp157_) * tmp24_ + tmp289_ * tmp23_); mCompDer[1][3] = ((tmp6_) * (tmp3_) + (tmp16_) * (tmp12_)) - ((tmp31_) * (tmp28_) + (tmp39_) * (tmp36_)); mCompDer[1][4] = (tmp7_ * (tmp3_) + tmp18_ * (tmp12_)) - (tmp32_ * (tmp28_) + tmp40_ * (tmp36_)); mCompDer[1][5] = (tmp8_ * (tmp3_) + tmp20_ * (tmp12_)) - (tmp33_ * (tmp28_) + tmp41_ * (tmp36_)); mCompDer[1][6] = (tmp9_ * (tmp3_) + tmp22_ * (tmp12_)) - (tmp34_ * (tmp28_) + tmp42_ * (tmp36_)); mCompDer[1][7] = (tmp50_ * (tmp3_) + tmp71_ * (tmp12_)) - (tmp92_ * (tmp28_) + tmp112_ * (tmp36_)); mCompDer[1][8] = tmp292_; mCompDer[1][9] = (tmp294_ + tmp296_) - (tmp298_ + tmp300_); mCompDer[1][10] = 0; mCompDer[1][11] = 0; } void cREgDistDxDy_Fraser_PPaEqPPs::ComputeValDerivHessian() { ELISE_ASSERT(false,"Foncteur cREgDistDxDy_Fraser_PPaEqPPs Has no Der Sec"); } void cREgDistDxDy_Fraser_PPaEqPPs::SetRegDistxy1_x(double aVal){ mLocRegDistxy1_x = aVal;} void cREgDistDxDy_Fraser_PPaEqPPs::SetRegDistxy1_y(double aVal){ mLocRegDistxy1_y = aVal;} void cREgDistDxDy_Fraser_PPaEqPPs::SetRegDistxy2_x(double aVal){ mLocRegDistxy2_x = aVal;} void cREgDistDxDy_Fraser_PPaEqPPs::SetRegDistxy2_y(double aVal){ mLocRegDistxy2_y = aVal;} void cREgDistDxDy_Fraser_PPaEqPPs::SetRegDistxy3_x(double aVal){ mLocRegDistxy3_x = aVal;} void cREgDistDxDy_Fraser_PPaEqPPs::SetRegDistxy3_y(double aVal){ mLocRegDistxy3_y = aVal;} void cREgDistDxDy_Fraser_PPaEqPPs::SetRegDistxy4_x(double aVal){ mLocRegDistxy4_x = aVal;} void cREgDistDxDy_Fraser_PPaEqPPs::SetRegDistxy4_y(double aVal){ mLocRegDistxy4_y = aVal;} double * cREgDistDxDy_Fraser_PPaEqPPs::AdrVarLocFromString(const std::string & aName) { if (aName == "RegDistxy1_x") return & mLocRegDistxy1_x; if (aName == "RegDistxy1_y") return & mLocRegDistxy1_y; if (aName == "RegDistxy2_x") return & mLocRegDistxy2_x; if (aName == "RegDistxy2_y") return & mLocRegDistxy2_y; if (aName == "RegDistxy3_x") return & mLocRegDistxy3_x; if (aName == "RegDistxy3_y") return & mLocRegDistxy3_y; if (aName == "RegDistxy4_x") return & mLocRegDistxy4_x; if (aName == "RegDistxy4_y") return & mLocRegDistxy4_y; return 0; } cElCompiledFonc::cAutoAddEntry cREgDistDxDy_Fraser_PPaEqPPs::mTheAuto("cREgDistDxDy_Fraser_PPaEqPPs",cREgDistDxDy_Fraser_PPaEqPPs::Alloc); cElCompiledFonc * cREgDistDxDy_Fraser_PPaEqPPs::Alloc() { return new cREgDistDxDy_Fraser_PPaEqPPs(); }
9,964
2,816
/* Generated by Snowball 2.0.0 - https://snowballstem.org/ */ #include "../runtime/header.h" #ifdef __cplusplus extern "C" { #endif extern int romanian_UTF_8_stem(struct SN_env * z); #ifdef __cplusplus } #endif static int r_vowel_suffix(struct SN_env * z); static int r_verb_suffix(struct SN_env * z); static int r_combo_suffix(struct SN_env * z); static int r_standard_suffix(struct SN_env * z); static int r_step_0(struct SN_env * z); static int r_R2(struct SN_env * z); static int r_R1(struct SN_env * z); static int r_RV(struct SN_env * z); static int r_mark_regions(struct SN_env * z); static int r_postlude(struct SN_env * z); static int r_prelude(struct SN_env * z); #ifdef __cplusplus extern "C" { #endif extern struct SN_env * romanian_UTF_8_create_env(void); extern void romanian_UTF_8_close_env(struct SN_env * z); #ifdef __cplusplus } #endif static const symbol s_0_1[1] = { 'I' }; static const symbol s_0_2[1] = { 'U' }; static const struct among a_0[3] = { { 0, 0, -1, 3, 0}, { 1, s_0_1, 0, 1, 0}, { 1, s_0_2, 0, 2, 0} }; static const symbol s_1_0[2] = { 'e', 'a' }; static const symbol s_1_1[5] = { 'a', 0xC5, 0xA3, 'i', 'a' }; static const symbol s_1_2[3] = { 'a', 'u', 'a' }; static const symbol s_1_3[3] = { 'i', 'u', 'a' }; static const symbol s_1_4[5] = { 'a', 0xC5, 0xA3, 'i', 'e' }; static const symbol s_1_5[3] = { 'e', 'l', 'e' }; static const symbol s_1_6[3] = { 'i', 'l', 'e' }; static const symbol s_1_7[4] = { 'i', 'i', 'l', 'e' }; static const symbol s_1_8[3] = { 'i', 'e', 'i' }; static const symbol s_1_9[4] = { 'a', 't', 'e', 'i' }; static const symbol s_1_10[2] = { 'i', 'i' }; static const symbol s_1_11[4] = { 'u', 'l', 'u', 'i' }; static const symbol s_1_12[2] = { 'u', 'l' }; static const symbol s_1_13[4] = { 'e', 'l', 'o', 'r' }; static const symbol s_1_14[4] = { 'i', 'l', 'o', 'r' }; static const symbol s_1_15[5] = { 'i', 'i', 'l', 'o', 'r' }; static const struct among a_1[16] = { { 2, s_1_0, -1, 3, 0}, { 5, s_1_1, -1, 7, 0}, { 3, s_1_2, -1, 2, 0}, { 3, s_1_3, -1, 4, 0}, { 5, s_1_4, -1, 7, 0}, { 3, s_1_5, -1, 3, 0}, { 3, s_1_6, -1, 5, 0}, { 4, s_1_7, 6, 4, 0}, { 3, s_1_8, -1, 4, 0}, { 4, s_1_9, -1, 6, 0}, { 2, s_1_10, -1, 4, 0}, { 4, s_1_11, -1, 1, 0}, { 2, s_1_12, -1, 1, 0}, { 4, s_1_13, -1, 3, 0}, { 4, s_1_14, -1, 4, 0}, { 5, s_1_15, 14, 4, 0} }; static const symbol s_2_0[5] = { 'i', 'c', 'a', 'l', 'a' }; static const symbol s_2_1[5] = { 'i', 'c', 'i', 'v', 'a' }; static const symbol s_2_2[5] = { 'a', 't', 'i', 'v', 'a' }; static const symbol s_2_3[5] = { 'i', 't', 'i', 'v', 'a' }; static const symbol s_2_4[5] = { 'i', 'c', 'a', 'l', 'e' }; static const symbol s_2_5[7] = { 'a', 0xC5, 0xA3, 'i', 'u', 'n', 'e' }; static const symbol s_2_6[7] = { 'i', 0xC5, 0xA3, 'i', 'u', 'n', 'e' }; static const symbol s_2_7[6] = { 'a', 't', 'o', 'a', 'r', 'e' }; static const symbol s_2_8[6] = { 'i', 't', 'o', 'a', 'r', 'e' }; static const symbol s_2_9[7] = { 0xC4, 0x83, 't', 'o', 'a', 'r', 'e' }; static const symbol s_2_10[7] = { 'i', 'c', 'i', 't', 'a', 't', 'e' }; static const symbol s_2_11[9] = { 'a', 'b', 'i', 'l', 'i', 't', 'a', 't', 'e' }; static const symbol s_2_12[9] = { 'i', 'b', 'i', 'l', 'i', 't', 'a', 't', 'e' }; static const symbol s_2_13[7] = { 'i', 'v', 'i', 't', 'a', 't', 'e' }; static const symbol s_2_14[5] = { 'i', 'c', 'i', 'v', 'e' }; static const symbol s_2_15[5] = { 'a', 't', 'i', 'v', 'e' }; static const symbol s_2_16[5] = { 'i', 't', 'i', 'v', 'e' }; static const symbol s_2_17[5] = { 'i', 'c', 'a', 'l', 'i' }; static const symbol s_2_18[5] = { 'a', 't', 'o', 'r', 'i' }; static const symbol s_2_19[7] = { 'i', 'c', 'a', 't', 'o', 'r', 'i' }; static const symbol s_2_20[5] = { 'i', 't', 'o', 'r', 'i' }; static const symbol s_2_21[6] = { 0xC4, 0x83, 't', 'o', 'r', 'i' }; static const symbol s_2_22[7] = { 'i', 'c', 'i', 't', 'a', 't', 'i' }; static const symbol s_2_23[9] = { 'a', 'b', 'i', 'l', 'i', 't', 'a', 't', 'i' }; static const symbol s_2_24[7] = { 'i', 'v', 'i', 't', 'a', 't', 'i' }; static const symbol s_2_25[5] = { 'i', 'c', 'i', 'v', 'i' }; static const symbol s_2_26[5] = { 'a', 't', 'i', 'v', 'i' }; static const symbol s_2_27[5] = { 'i', 't', 'i', 'v', 'i' }; static const symbol s_2_28[7] = { 'i', 'c', 'i', 't', 0xC4, 0x83, 'i' }; static const symbol s_2_29[9] = { 'a', 'b', 'i', 'l', 'i', 't', 0xC4, 0x83, 'i' }; static const symbol s_2_30[7] = { 'i', 'v', 'i', 't', 0xC4, 0x83, 'i' }; static const symbol s_2_31[9] = { 'i', 'c', 'i', 't', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_2_32[11] = { 'a', 'b', 'i', 'l', 'i', 't', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_2_33[9] = { 'i', 'v', 'i', 't', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_2_34[4] = { 'i', 'c', 'a', 'l' }; static const symbol s_2_35[4] = { 'a', 't', 'o', 'r' }; static const symbol s_2_36[6] = { 'i', 'c', 'a', 't', 'o', 'r' }; static const symbol s_2_37[4] = { 'i', 't', 'o', 'r' }; static const symbol s_2_38[5] = { 0xC4, 0x83, 't', 'o', 'r' }; static const symbol s_2_39[4] = { 'i', 'c', 'i', 'v' }; static const symbol s_2_40[4] = { 'a', 't', 'i', 'v' }; static const symbol s_2_41[4] = { 'i', 't', 'i', 'v' }; static const symbol s_2_42[6] = { 'i', 'c', 'a', 'l', 0xC4, 0x83 }; static const symbol s_2_43[6] = { 'i', 'c', 'i', 'v', 0xC4, 0x83 }; static const symbol s_2_44[6] = { 'a', 't', 'i', 'v', 0xC4, 0x83 }; static const symbol s_2_45[6] = { 'i', 't', 'i', 'v', 0xC4, 0x83 }; static const struct among a_2[46] = { { 5, s_2_0, -1, 4, 0}, { 5, s_2_1, -1, 4, 0}, { 5, s_2_2, -1, 5, 0}, { 5, s_2_3, -1, 6, 0}, { 5, s_2_4, -1, 4, 0}, { 7, s_2_5, -1, 5, 0}, { 7, s_2_6, -1, 6, 0}, { 6, s_2_7, -1, 5, 0}, { 6, s_2_8, -1, 6, 0}, { 7, s_2_9, -1, 5, 0}, { 7, s_2_10, -1, 4, 0}, { 9, s_2_11, -1, 1, 0}, { 9, s_2_12, -1, 2, 0}, { 7, s_2_13, -1, 3, 0}, { 5, s_2_14, -1, 4, 0}, { 5, s_2_15, -1, 5, 0}, { 5, s_2_16, -1, 6, 0}, { 5, s_2_17, -1, 4, 0}, { 5, s_2_18, -1, 5, 0}, { 7, s_2_19, 18, 4, 0}, { 5, s_2_20, -1, 6, 0}, { 6, s_2_21, -1, 5, 0}, { 7, s_2_22, -1, 4, 0}, { 9, s_2_23, -1, 1, 0}, { 7, s_2_24, -1, 3, 0}, { 5, s_2_25, -1, 4, 0}, { 5, s_2_26, -1, 5, 0}, { 5, s_2_27, -1, 6, 0}, { 7, s_2_28, -1, 4, 0}, { 9, s_2_29, -1, 1, 0}, { 7, s_2_30, -1, 3, 0}, { 9, s_2_31, -1, 4, 0}, { 11, s_2_32, -1, 1, 0}, { 9, s_2_33, -1, 3, 0}, { 4, s_2_34, -1, 4, 0}, { 4, s_2_35, -1, 5, 0}, { 6, s_2_36, 35, 4, 0}, { 4, s_2_37, -1, 6, 0}, { 5, s_2_38, -1, 5, 0}, { 4, s_2_39, -1, 4, 0}, { 4, s_2_40, -1, 5, 0}, { 4, s_2_41, -1, 6, 0}, { 6, s_2_42, -1, 4, 0}, { 6, s_2_43, -1, 4, 0}, { 6, s_2_44, -1, 5, 0}, { 6, s_2_45, -1, 6, 0} }; static const symbol s_3_0[3] = { 'i', 'c', 'a' }; static const symbol s_3_1[5] = { 'a', 'b', 'i', 'l', 'a' }; static const symbol s_3_2[5] = { 'i', 'b', 'i', 'l', 'a' }; static const symbol s_3_3[4] = { 'o', 'a', 's', 'a' }; static const symbol s_3_4[3] = { 'a', 't', 'a' }; static const symbol s_3_5[3] = { 'i', 't', 'a' }; static const symbol s_3_6[4] = { 'a', 'n', 't', 'a' }; static const symbol s_3_7[4] = { 'i', 's', 't', 'a' }; static const symbol s_3_8[3] = { 'u', 't', 'a' }; static const symbol s_3_9[3] = { 'i', 'v', 'a' }; static const symbol s_3_10[2] = { 'i', 'c' }; static const symbol s_3_11[3] = { 'i', 'c', 'e' }; static const symbol s_3_12[5] = { 'a', 'b', 'i', 'l', 'e' }; static const symbol s_3_13[5] = { 'i', 'b', 'i', 'l', 'e' }; static const symbol s_3_14[4] = { 'i', 's', 'm', 'e' }; static const symbol s_3_15[4] = { 'i', 'u', 'n', 'e' }; static const symbol s_3_16[4] = { 'o', 'a', 's', 'e' }; static const symbol s_3_17[3] = { 'a', 't', 'e' }; static const symbol s_3_18[5] = { 'i', 't', 'a', 't', 'e' }; static const symbol s_3_19[3] = { 'i', 't', 'e' }; static const symbol s_3_20[4] = { 'a', 'n', 't', 'e' }; static const symbol s_3_21[4] = { 'i', 's', 't', 'e' }; static const symbol s_3_22[3] = { 'u', 't', 'e' }; static const symbol s_3_23[3] = { 'i', 'v', 'e' }; static const symbol s_3_24[3] = { 'i', 'c', 'i' }; static const symbol s_3_25[5] = { 'a', 'b', 'i', 'l', 'i' }; static const symbol s_3_26[5] = { 'i', 'b', 'i', 'l', 'i' }; static const symbol s_3_27[4] = { 'i', 'u', 'n', 'i' }; static const symbol s_3_28[5] = { 'a', 't', 'o', 'r', 'i' }; static const symbol s_3_29[3] = { 'o', 's', 'i' }; static const symbol s_3_30[3] = { 'a', 't', 'i' }; static const symbol s_3_31[5] = { 'i', 't', 'a', 't', 'i' }; static const symbol s_3_32[3] = { 'i', 't', 'i' }; static const symbol s_3_33[4] = { 'a', 'n', 't', 'i' }; static const symbol s_3_34[4] = { 'i', 's', 't', 'i' }; static const symbol s_3_35[3] = { 'u', 't', 'i' }; static const symbol s_3_36[5] = { 'i', 0xC5, 0x9F, 't', 'i' }; static const symbol s_3_37[3] = { 'i', 'v', 'i' }; static const symbol s_3_38[5] = { 'i', 't', 0xC4, 0x83, 'i' }; static const symbol s_3_39[4] = { 'o', 0xC5, 0x9F, 'i' }; static const symbol s_3_40[7] = { 'i', 't', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_3_41[4] = { 'a', 'b', 'i', 'l' }; static const symbol s_3_42[4] = { 'i', 'b', 'i', 'l' }; static const symbol s_3_43[3] = { 'i', 's', 'm' }; static const symbol s_3_44[4] = { 'a', 't', 'o', 'r' }; static const symbol s_3_45[2] = { 'o', 's' }; static const symbol s_3_46[2] = { 'a', 't' }; static const symbol s_3_47[2] = { 'i', 't' }; static const symbol s_3_48[3] = { 'a', 'n', 't' }; static const symbol s_3_49[3] = { 'i', 's', 't' }; static const symbol s_3_50[2] = { 'u', 't' }; static const symbol s_3_51[2] = { 'i', 'v' }; static const symbol s_3_52[4] = { 'i', 'c', 0xC4, 0x83 }; static const symbol s_3_53[6] = { 'a', 'b', 'i', 'l', 0xC4, 0x83 }; static const symbol s_3_54[6] = { 'i', 'b', 'i', 'l', 0xC4, 0x83 }; static const symbol s_3_55[5] = { 'o', 'a', 's', 0xC4, 0x83 }; static const symbol s_3_56[4] = { 'a', 't', 0xC4, 0x83 }; static const symbol s_3_57[4] = { 'i', 't', 0xC4, 0x83 }; static const symbol s_3_58[5] = { 'a', 'n', 't', 0xC4, 0x83 }; static const symbol s_3_59[5] = { 'i', 's', 't', 0xC4, 0x83 }; static const symbol s_3_60[4] = { 'u', 't', 0xC4, 0x83 }; static const symbol s_3_61[4] = { 'i', 'v', 0xC4, 0x83 }; static const struct among a_3[62] = { { 3, s_3_0, -1, 1, 0}, { 5, s_3_1, -1, 1, 0}, { 5, s_3_2, -1, 1, 0}, { 4, s_3_3, -1, 1, 0}, { 3, s_3_4, -1, 1, 0}, { 3, s_3_5, -1, 1, 0}, { 4, s_3_6, -1, 1, 0}, { 4, s_3_7, -1, 3, 0}, { 3, s_3_8, -1, 1, 0}, { 3, s_3_9, -1, 1, 0}, { 2, s_3_10, -1, 1, 0}, { 3, s_3_11, -1, 1, 0}, { 5, s_3_12, -1, 1, 0}, { 5, s_3_13, -1, 1, 0}, { 4, s_3_14, -1, 3, 0}, { 4, s_3_15, -1, 2, 0}, { 4, s_3_16, -1, 1, 0}, { 3, s_3_17, -1, 1, 0}, { 5, s_3_18, 17, 1, 0}, { 3, s_3_19, -1, 1, 0}, { 4, s_3_20, -1, 1, 0}, { 4, s_3_21, -1, 3, 0}, { 3, s_3_22, -1, 1, 0}, { 3, s_3_23, -1, 1, 0}, { 3, s_3_24, -1, 1, 0}, { 5, s_3_25, -1, 1, 0}, { 5, s_3_26, -1, 1, 0}, { 4, s_3_27, -1, 2, 0}, { 5, s_3_28, -1, 1, 0}, { 3, s_3_29, -1, 1, 0}, { 3, s_3_30, -1, 1, 0}, { 5, s_3_31, 30, 1, 0}, { 3, s_3_32, -1, 1, 0}, { 4, s_3_33, -1, 1, 0}, { 4, s_3_34, -1, 3, 0}, { 3, s_3_35, -1, 1, 0}, { 5, s_3_36, -1, 3, 0}, { 3, s_3_37, -1, 1, 0}, { 5, s_3_38, -1, 1, 0}, { 4, s_3_39, -1, 1, 0}, { 7, s_3_40, -1, 1, 0}, { 4, s_3_41, -1, 1, 0}, { 4, s_3_42, -1, 1, 0}, { 3, s_3_43, -1, 3, 0}, { 4, s_3_44, -1, 1, 0}, { 2, s_3_45, -1, 1, 0}, { 2, s_3_46, -1, 1, 0}, { 2, s_3_47, -1, 1, 0}, { 3, s_3_48, -1, 1, 0}, { 3, s_3_49, -1, 3, 0}, { 2, s_3_50, -1, 1, 0}, { 2, s_3_51, -1, 1, 0}, { 4, s_3_52, -1, 1, 0}, { 6, s_3_53, -1, 1, 0}, { 6, s_3_54, -1, 1, 0}, { 5, s_3_55, -1, 1, 0}, { 4, s_3_56, -1, 1, 0}, { 4, s_3_57, -1, 1, 0}, { 5, s_3_58, -1, 1, 0}, { 5, s_3_59, -1, 3, 0}, { 4, s_3_60, -1, 1, 0}, { 4, s_3_61, -1, 1, 0} }; static const symbol s_4_0[2] = { 'e', 'a' }; static const symbol s_4_1[2] = { 'i', 'a' }; static const symbol s_4_2[3] = { 'e', 's', 'c' }; static const symbol s_4_3[4] = { 0xC4, 0x83, 's', 'c' }; static const symbol s_4_4[3] = { 'i', 'n', 'd' }; static const symbol s_4_5[4] = { 0xC3, 0xA2, 'n', 'd' }; static const symbol s_4_6[3] = { 'a', 'r', 'e' }; static const symbol s_4_7[3] = { 'e', 'r', 'e' }; static const symbol s_4_8[3] = { 'i', 'r', 'e' }; static const symbol s_4_9[4] = { 0xC3, 0xA2, 'r', 'e' }; static const symbol s_4_10[2] = { 's', 'e' }; static const symbol s_4_11[3] = { 'a', 's', 'e' }; static const symbol s_4_12[4] = { 's', 'e', 's', 'e' }; static const symbol s_4_13[3] = { 'i', 's', 'e' }; static const symbol s_4_14[3] = { 'u', 's', 'e' }; static const symbol s_4_15[4] = { 0xC3, 0xA2, 's', 'e' }; static const symbol s_4_16[5] = { 'e', 0xC5, 0x9F, 't', 'e' }; static const symbol s_4_17[6] = { 0xC4, 0x83, 0xC5, 0x9F, 't', 'e' }; static const symbol s_4_18[3] = { 'e', 'z', 'e' }; static const symbol s_4_19[2] = { 'a', 'i' }; static const symbol s_4_20[3] = { 'e', 'a', 'i' }; static const symbol s_4_21[3] = { 'i', 'a', 'i' }; static const symbol s_4_22[3] = { 's', 'e', 'i' }; static const symbol s_4_23[5] = { 'e', 0xC5, 0x9F, 't', 'i' }; static const symbol s_4_24[6] = { 0xC4, 0x83, 0xC5, 0x9F, 't', 'i' }; static const symbol s_4_25[2] = { 'u', 'i' }; static const symbol s_4_26[3] = { 'e', 'z', 'i' }; static const symbol s_4_27[4] = { 'a', 0xC5, 0x9F, 'i' }; static const symbol s_4_28[5] = { 's', 'e', 0xC5, 0x9F, 'i' }; static const symbol s_4_29[6] = { 'a', 's', 'e', 0xC5, 0x9F, 'i' }; static const symbol s_4_30[7] = { 's', 'e', 's', 'e', 0xC5, 0x9F, 'i' }; static const symbol s_4_31[6] = { 'i', 's', 'e', 0xC5, 0x9F, 'i' }; static const symbol s_4_32[6] = { 'u', 's', 'e', 0xC5, 0x9F, 'i' }; static const symbol s_4_33[7] = { 0xC3, 0xA2, 's', 'e', 0xC5, 0x9F, 'i' }; static const symbol s_4_34[4] = { 'i', 0xC5, 0x9F, 'i' }; static const symbol s_4_35[4] = { 'u', 0xC5, 0x9F, 'i' }; static const symbol s_4_36[5] = { 0xC3, 0xA2, 0xC5, 0x9F, 'i' }; static const symbol s_4_37[3] = { 0xC3, 0xA2, 'i' }; static const symbol s_4_38[4] = { 'a', 0xC5, 0xA3, 'i' }; static const symbol s_4_39[5] = { 'e', 'a', 0xC5, 0xA3, 'i' }; static const symbol s_4_40[5] = { 'i', 'a', 0xC5, 0xA3, 'i' }; static const symbol s_4_41[4] = { 'e', 0xC5, 0xA3, 'i' }; static const symbol s_4_42[4] = { 'i', 0xC5, 0xA3, 'i' }; static const symbol s_4_43[7] = { 'a', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_44[8] = { 's', 'e', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_45[9] = { 'a', 's', 'e', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_46[10] = { 's', 'e', 's', 'e', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_47[9] = { 'i', 's', 'e', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_48[9] = { 'u', 's', 'e', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_49[10] = { 0xC3, 0xA2, 's', 'e', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_50[7] = { 'i', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_51[7] = { 'u', 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_52[8] = { 0xC3, 0xA2, 'r', 0xC4, 0x83, 0xC5, 0xA3, 'i' }; static const symbol s_4_53[5] = { 0xC3, 0xA2, 0xC5, 0xA3, 'i' }; static const symbol s_4_54[2] = { 'a', 'm' }; static const symbol s_4_55[3] = { 'e', 'a', 'm' }; static const symbol s_4_56[3] = { 'i', 'a', 'm' }; static const symbol s_4_57[2] = { 'e', 'm' }; static const symbol s_4_58[4] = { 'a', 's', 'e', 'm' }; static const symbol s_4_59[5] = { 's', 'e', 's', 'e', 'm' }; static const symbol s_4_60[4] = { 'i', 's', 'e', 'm' }; static const symbol s_4_61[4] = { 'u', 's', 'e', 'm' }; static const symbol s_4_62[5] = { 0xC3, 0xA2, 's', 'e', 'm' }; static const symbol s_4_63[2] = { 'i', 'm' }; static const symbol s_4_64[3] = { 0xC4, 0x83, 'm' }; static const symbol s_4_65[5] = { 'a', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_66[6] = { 's', 'e', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_67[7] = { 'a', 's', 'e', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_68[8] = { 's', 'e', 's', 'e', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_69[7] = { 'i', 's', 'e', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_70[7] = { 'u', 's', 'e', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_71[8] = { 0xC3, 0xA2, 's', 'e', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_72[5] = { 'i', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_73[5] = { 'u', 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_74[6] = { 0xC3, 0xA2, 'r', 0xC4, 0x83, 'm' }; static const symbol s_4_75[3] = { 0xC3, 0xA2, 'm' }; static const symbol s_4_76[2] = { 'a', 'u' }; static const symbol s_4_77[3] = { 'e', 'a', 'u' }; static const symbol s_4_78[3] = { 'i', 'a', 'u' }; static const symbol s_4_79[4] = { 'i', 'n', 'd', 'u' }; static const symbol s_4_80[5] = { 0xC3, 0xA2, 'n', 'd', 'u' }; static const symbol s_4_81[2] = { 'e', 'z' }; static const symbol s_4_82[6] = { 'e', 'a', 's', 'c', 0xC4, 0x83 }; static const symbol s_4_83[4] = { 'a', 'r', 0xC4, 0x83 }; static const symbol s_4_84[5] = { 's', 'e', 'r', 0xC4, 0x83 }; static const symbol s_4_85[6] = { 'a', 's', 'e', 'r', 0xC4, 0x83 }; static const symbol s_4_86[7] = { 's', 'e', 's', 'e', 'r', 0xC4, 0x83 }; static const symbol s_4_87[6] = { 'i', 's', 'e', 'r', 0xC4, 0x83 }; static const symbol s_4_88[6] = { 'u', 's', 'e', 'r', 0xC4, 0x83 }; static const symbol s_4_89[7] = { 0xC3, 0xA2, 's', 'e', 'r', 0xC4, 0x83 }; static const symbol s_4_90[4] = { 'i', 'r', 0xC4, 0x83 }; static const symbol s_4_91[4] = { 'u', 'r', 0xC4, 0x83 }; static const symbol s_4_92[5] = { 0xC3, 0xA2, 'r', 0xC4, 0x83 }; static const symbol s_4_93[5] = { 'e', 'a', 'z', 0xC4, 0x83 }; static const struct among a_4[94] = { { 2, s_4_0, -1, 1, 0}, { 2, s_4_1, -1, 1, 0}, { 3, s_4_2, -1, 1, 0}, { 4, s_4_3, -1, 1, 0}, { 3, s_4_4, -1, 1, 0}, { 4, s_4_5, -1, 1, 0}, { 3, s_4_6, -1, 1, 0}, { 3, s_4_7, -1, 1, 0}, { 3, s_4_8, -1, 1, 0}, { 4, s_4_9, -1, 1, 0}, { 2, s_4_10, -1, 2, 0}, { 3, s_4_11, 10, 1, 0}, { 4, s_4_12, 10, 2, 0}, { 3, s_4_13, 10, 1, 0}, { 3, s_4_14, 10, 1, 0}, { 4, s_4_15, 10, 1, 0}, { 5, s_4_16, -1, 1, 0}, { 6, s_4_17, -1, 1, 0}, { 3, s_4_18, -1, 1, 0}, { 2, s_4_19, -1, 1, 0}, { 3, s_4_20, 19, 1, 0}, { 3, s_4_21, 19, 1, 0}, { 3, s_4_22, -1, 2, 0}, { 5, s_4_23, -1, 1, 0}, { 6, s_4_24, -1, 1, 0}, { 2, s_4_25, -1, 1, 0}, { 3, s_4_26, -1, 1, 0}, { 4, s_4_27, -1, 1, 0}, { 5, s_4_28, -1, 2, 0}, { 6, s_4_29, 28, 1, 0}, { 7, s_4_30, 28, 2, 0}, { 6, s_4_31, 28, 1, 0}, { 6, s_4_32, 28, 1, 0}, { 7, s_4_33, 28, 1, 0}, { 4, s_4_34, -1, 1, 0}, { 4, s_4_35, -1, 1, 0}, { 5, s_4_36, -1, 1, 0}, { 3, s_4_37, -1, 1, 0}, { 4, s_4_38, -1, 2, 0}, { 5, s_4_39, 38, 1, 0}, { 5, s_4_40, 38, 1, 0}, { 4, s_4_41, -1, 2, 0}, { 4, s_4_42, -1, 2, 0}, { 7, s_4_43, -1, 1, 0}, { 8, s_4_44, -1, 2, 0}, { 9, s_4_45, 44, 1, 0}, { 10, s_4_46, 44, 2, 0}, { 9, s_4_47, 44, 1, 0}, { 9, s_4_48, 44, 1, 0}, { 10, s_4_49, 44, 1, 0}, { 7, s_4_50, -1, 1, 0}, { 7, s_4_51, -1, 1, 0}, { 8, s_4_52, -1, 1, 0}, { 5, s_4_53, -1, 2, 0}, { 2, s_4_54, -1, 1, 0}, { 3, s_4_55, 54, 1, 0}, { 3, s_4_56, 54, 1, 0}, { 2, s_4_57, -1, 2, 0}, { 4, s_4_58, 57, 1, 0}, { 5, s_4_59, 57, 2, 0}, { 4, s_4_60, 57, 1, 0}, { 4, s_4_61, 57, 1, 0}, { 5, s_4_62, 57, 1, 0}, { 2, s_4_63, -1, 2, 0}, { 3, s_4_64, -1, 2, 0}, { 5, s_4_65, 64, 1, 0}, { 6, s_4_66, 64, 2, 0}, { 7, s_4_67, 66, 1, 0}, { 8, s_4_68, 66, 2, 0}, { 7, s_4_69, 66, 1, 0}, { 7, s_4_70, 66, 1, 0}, { 8, s_4_71, 66, 1, 0}, { 5, s_4_72, 64, 1, 0}, { 5, s_4_73, 64, 1, 0}, { 6, s_4_74, 64, 1, 0}, { 3, s_4_75, -1, 2, 0}, { 2, s_4_76, -1, 1, 0}, { 3, s_4_77, 76, 1, 0}, { 3, s_4_78, 76, 1, 0}, { 4, s_4_79, -1, 1, 0}, { 5, s_4_80, -1, 1, 0}, { 2, s_4_81, -1, 1, 0}, { 6, s_4_82, -1, 1, 0}, { 4, s_4_83, -1, 1, 0}, { 5, s_4_84, -1, 2, 0}, { 6, s_4_85, 84, 1, 0}, { 7, s_4_86, 84, 2, 0}, { 6, s_4_87, 84, 1, 0}, { 6, s_4_88, 84, 1, 0}, { 7, s_4_89, 84, 1, 0}, { 4, s_4_90, -1, 1, 0}, { 4, s_4_91, -1, 1, 0}, { 5, s_4_92, -1, 1, 0}, { 5, s_4_93, -1, 1, 0} }; static const symbol s_5_0[1] = { 'a' }; static const symbol s_5_1[1] = { 'e' }; static const symbol s_5_2[2] = { 'i', 'e' }; static const symbol s_5_3[1] = { 'i' }; static const symbol s_5_4[2] = { 0xC4, 0x83 }; static const struct among a_5[5] = { { 1, s_5_0, -1, 1, 0}, { 1, s_5_1, -1, 1, 0}, { 2, s_5_2, 1, 1, 0}, { 1, s_5_3, -1, 1, 0}, { 2, s_5_4, -1, 1, 0} }; static const unsigned char g_v[] = { 17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 32, 0, 0, 4 }; static const symbol s_0[] = { 'U' }; static const symbol s_1[] = { 'I' }; static const symbol s_2[] = { 'i' }; static const symbol s_3[] = { 'u' }; static const symbol s_4[] = { 'a' }; static const symbol s_5[] = { 'e' }; static const symbol s_6[] = { 'i' }; static const symbol s_7[] = { 'a', 'b' }; static const symbol s_8[] = { 'i' }; static const symbol s_9[] = { 'a', 't' }; static const symbol s_10[] = { 'a', 0xC5, 0xA3, 'i' }; static const symbol s_11[] = { 'a', 'b', 'i', 'l' }; static const symbol s_12[] = { 'i', 'b', 'i', 'l' }; static const symbol s_13[] = { 'i', 'v' }; static const symbol s_14[] = { 'i', 'c' }; static const symbol s_15[] = { 'a', 't' }; static const symbol s_16[] = { 'i', 't' }; static const symbol s_17[] = { 0xC5, 0xA3 }; static const symbol s_18[] = { 't' }; static const symbol s_19[] = { 'i', 's', 't' }; static int r_prelude(struct SN_env * z) { while(1) { int c1 = z->c; while(1) { int c2 = z->c; if (in_grouping_U(z, g_v, 97, 259, 0)) goto lab1; z->bra = z->c; { int c3 = z->c; if (z->c == z->l || z->p[z->c] != 'u') goto lab3; z->c++; z->ket = z->c; if (in_grouping_U(z, g_v, 97, 259, 0)) goto lab3; { int ret = slice_from_s(z, 1, s_0); if (ret < 0) return ret; } goto lab2; lab3: z->c = c3; if (z->c == z->l || z->p[z->c] != 'i') goto lab1; z->c++; z->ket = z->c; if (in_grouping_U(z, g_v, 97, 259, 0)) goto lab1; { int ret = slice_from_s(z, 1, s_1); if (ret < 0) return ret; } } lab2: z->c = c2; break; lab1: z->c = c2; { int ret = skip_utf8(z->p, z->c, 0, z->l, 1); if (ret < 0) goto lab0; z->c = ret; } } continue; lab0: z->c = c1; break; } return 1; } static int r_mark_regions(struct SN_env * z) { z->I[2] = z->l; z->I[1] = z->l; z->I[0] = z->l; { int c1 = z->c; { int c2 = z->c; if (in_grouping_U(z, g_v, 97, 259, 0)) goto lab2; { int c3 = z->c; if (out_grouping_U(z, g_v, 97, 259, 0)) goto lab4; { int ret = out_grouping_U(z, g_v, 97, 259, 1); if (ret < 0) goto lab4; z->c += ret; } goto lab3; lab4: z->c = c3; if (in_grouping_U(z, g_v, 97, 259, 0)) goto lab2; { int ret = in_grouping_U(z, g_v, 97, 259, 1); if (ret < 0) goto lab2; z->c += ret; } } lab3: goto lab1; lab2: z->c = c2; if (out_grouping_U(z, g_v, 97, 259, 0)) goto lab0; { int c4 = z->c; if (out_grouping_U(z, g_v, 97, 259, 0)) goto lab6; { int ret = out_grouping_U(z, g_v, 97, 259, 1); if (ret < 0) goto lab6; z->c += ret; } goto lab5; lab6: z->c = c4; if (in_grouping_U(z, g_v, 97, 259, 0)) goto lab0; { int ret = skip_utf8(z->p, z->c, 0, z->l, 1); if (ret < 0) goto lab0; z->c = ret; } } lab5: ; } lab1: z->I[2] = z->c; lab0: z->c = c1; } { int c5 = z->c; { int ret = out_grouping_U(z, g_v, 97, 259, 1); if (ret < 0) goto lab7; z->c += ret; } { int ret = in_grouping_U(z, g_v, 97, 259, 1); if (ret < 0) goto lab7; z->c += ret; } z->I[1] = z->c; { int ret = out_grouping_U(z, g_v, 97, 259, 1); if (ret < 0) goto lab7; z->c += ret; } { int ret = in_grouping_U(z, g_v, 97, 259, 1); if (ret < 0) goto lab7; z->c += ret; } z->I[0] = z->c; lab7: z->c = c5; } return 1; } static int r_postlude(struct SN_env * z) { int among_var; while(1) { int c1 = z->c; z->bra = z->c; if (z->c >= z->l || (z->p[z->c + 0] != 73 && z->p[z->c + 0] != 85)) among_var = 3; else among_var = find_among(z, a_0, 3); if (!(among_var)) goto lab0; z->ket = z->c; switch (among_var) { case 1: { int ret = slice_from_s(z, 1, s_2); if (ret < 0) return ret; } break; case 2: { int ret = slice_from_s(z, 1, s_3); if (ret < 0) return ret; } break; case 3: { int ret = skip_utf8(z->p, z->c, 0, z->l, 1); if (ret < 0) goto lab0; z->c = ret; } break; } continue; lab0: z->c = c1; break; } return 1; } static int r_RV(struct SN_env * z) { if (!(z->I[2] <= z->c)) return 0; return 1; } static int r_R1(struct SN_env * z) { if (!(z->I[1] <= z->c)) return 0; return 1; } static int r_R2(struct SN_env * z) { if (!(z->I[0] <= z->c)) return 0; return 1; } static int r_step_0(struct SN_env * z) { int among_var; z->ket = z->c; if (z->c - 1 <= z->lb || z->p[z->c - 1] >> 5 != 3 || !((266786 >> (z->p[z->c - 1] & 0x1f)) & 1)) return 0; among_var = find_among_b(z, a_1, 16); if (!(among_var)) return 0; z->bra = z->c; { int ret = r_R1(z); if (ret <= 0) return ret; } switch (among_var) { case 1: { int ret = slice_del(z); if (ret < 0) return ret; } break; case 2: { int ret = slice_from_s(z, 1, s_4); if (ret < 0) return ret; } break; case 3: { int ret = slice_from_s(z, 1, s_5); if (ret < 0) return ret; } break; case 4: { int ret = slice_from_s(z, 1, s_6); if (ret < 0) return ret; } break; case 5: { int m1 = z->l - z->c; (void)m1; if (!(eq_s_b(z, 2, s_7))) goto lab0; return 0; lab0: z->c = z->l - m1; } { int ret = slice_from_s(z, 1, s_8); if (ret < 0) return ret; } break; case 6: { int ret = slice_from_s(z, 2, s_9); if (ret < 0) return ret; } break; case 7: { int ret = slice_from_s(z, 4, s_10); if (ret < 0) return ret; } break; } return 1; } static int r_combo_suffix(struct SN_env * z) { int among_var; { int m_test1 = z->l - z->c; z->ket = z->c; among_var = find_among_b(z, a_2, 46); if (!(among_var)) return 0; z->bra = z->c; { int ret = r_R1(z); if (ret <= 0) return ret; } switch (among_var) { case 1: { int ret = slice_from_s(z, 4, s_11); if (ret < 0) return ret; } break; case 2: { int ret = slice_from_s(z, 4, s_12); if (ret < 0) return ret; } break; case 3: { int ret = slice_from_s(z, 2, s_13); if (ret < 0) return ret; } break; case 4: { int ret = slice_from_s(z, 2, s_14); if (ret < 0) return ret; } break; case 5: { int ret = slice_from_s(z, 2, s_15); if (ret < 0) return ret; } break; case 6: { int ret = slice_from_s(z, 2, s_16); if (ret < 0) return ret; } break; } z->I[3] = 1; z->c = z->l - m_test1; } return 1; } static int r_standard_suffix(struct SN_env * z) { int among_var; z->I[3] = 0; while(1) { int m1 = z->l - z->c; (void)m1; { int ret = r_combo_suffix(z); if (ret == 0) goto lab0; if (ret < 0) return ret; } continue; lab0: z->c = z->l - m1; break; } z->ket = z->c; among_var = find_among_b(z, a_3, 62); if (!(among_var)) return 0; z->bra = z->c; { int ret = r_R2(z); if (ret <= 0) return ret; } switch (among_var) { case 1: { int ret = slice_del(z); if (ret < 0) return ret; } break; case 2: if (!(eq_s_b(z, 2, s_17))) return 0; z->bra = z->c; { int ret = slice_from_s(z, 1, s_18); if (ret < 0) return ret; } break; case 3: { int ret = slice_from_s(z, 3, s_19); if (ret < 0) return ret; } break; } z->I[3] = 1; return 1; } static int r_verb_suffix(struct SN_env * z) { int among_var; { int mlimit1; if (z->c < z->I[2]) return 0; mlimit1 = z->lb; z->lb = z->I[2]; z->ket = z->c; among_var = find_among_b(z, a_4, 94); if (!(among_var)) { z->lb = mlimit1; return 0; } z->bra = z->c; switch (among_var) { case 1: { int m2 = z->l - z->c; (void)m2; if (out_grouping_b_U(z, g_v, 97, 259, 0)) goto lab1; goto lab0; lab1: z->c = z->l - m2; if (z->c <= z->lb || z->p[z->c - 1] != 'u') { z->lb = mlimit1; return 0; } z->c--; } lab0: { int ret = slice_del(z); if (ret < 0) return ret; } break; case 2: { int ret = slice_del(z); if (ret < 0) return ret; } break; } z->lb = mlimit1; } return 1; } static int r_vowel_suffix(struct SN_env * z) { z->ket = z->c; if (!(find_among_b(z, a_5, 5))) return 0; z->bra = z->c; { int ret = r_RV(z); if (ret <= 0) return ret; } { int ret = slice_del(z); if (ret < 0) return ret; } return 1; } extern int romanian_UTF_8_stem(struct SN_env * z) { { int c1 = z->c; { int ret = r_prelude(z); if (ret < 0) return ret; } z->c = c1; } { int ret = r_mark_regions(z); if (ret < 0) return ret; } z->lb = z->c; z->c = z->l; { int m2 = z->l - z->c; (void)m2; { int ret = r_step_0(z); if (ret < 0) return ret; } z->c = z->l - m2; } { int m3 = z->l - z->c; (void)m3; { int ret = r_standard_suffix(z); if (ret < 0) return ret; } z->c = z->l - m3; } { int m4 = z->l - z->c; (void)m4; { int m5 = z->l - z->c; (void)m5; if (!(z->I[3])) goto lab2; goto lab1; lab2: z->c = z->l - m5; { int ret = r_verb_suffix(z); if (ret == 0) goto lab0; if (ret < 0) return ret; } } lab1: lab0: z->c = z->l - m4; } { int m6 = z->l - z->c; (void)m6; { int ret = r_vowel_suffix(z); if (ret < 0) return ret; } z->c = z->l - m6; } z->c = z->lb; { int c7 = z->c; { int ret = r_postlude(z); if (ret < 0) return ret; } z->c = c7; } return 1; } extern struct SN_env * romanian_UTF_8_create_env(void) { return SN_create_env(0, 4); } extern void romanian_UTF_8_close_env(struct SN_env * z) { SN_close_env(z, 0); }
19,232
623
<reponame>huoxingdawang/CrystalDiskInfo /*---------------------------------------------------------------------------*/ // Author : hiyohiyo // Mail : <EMAIL> // Web : https://crystalmark.info/ // License : The MIT License /*---------------------------------------------------------------------------*/ #include "../stdafx.h" #include "UtilityFx.h" #include <io.h> #pragma comment(lib,"version.lib") ////------------------------------------------------ // Debug ////------------------------------------------------ static const DWORD DEBUG_MODE_NONE = 0; static const DWORD DEBUG_MODE_LOG = 1; static const DWORD DEBUG_MODE_MESSAGE = 2; static DWORD debugMode = DEBUG_MODE_NONE; void SetDebugMode(DWORD mode) { if (mode <= DEBUG_MODE_MESSAGE) { debugMode = mode; } else { debugMode = DEBUG_MODE_NONE; } } void DebugPrint(CString cstr) { static BOOL flag = TRUE; static TCHAR file[MAX_PATH] = L""; static DWORD first = (DWORD)GetTickCountFx(); CString output; output.Format(L"%08d ", (DWORD)GetTickCountFx() - first); output += cstr; output.Append(L"\n"); output.Replace(L"\r", L""); if (flag) { TCHAR* ptrEnd; ::GetModuleFileName(NULL, file, MAX_PATH); if ((ptrEnd = _tcsrchr(file, '.')) != NULL) { *ptrEnd = '\0'; _tcscat_s(file, MAX_PATH, L".log"); } DeleteFile(file); flag = FALSE; } if (debugMode == DEBUG_MODE_NONE) { return; } FILE* fp; _tfopen_s(&fp, file, L"ac"); if (fp != NULL) { _ftprintf(fp, L"%s", (LPCTSTR)output); fflush(fp); fclose(fp); } if (debugMode == DEBUG_MODE_MESSAGE) { AfxMessageBox(output); } } ////------------------------------------------------ // File Information ////------------------------------------------------ int GetFileVersion(const TCHAR* file, TCHAR* version) { ULONG reserved = 0; VS_FIXEDFILEINFO vffi; TCHAR* buf = NULL; int Locale = 0; TCHAR str[256]; str[0] = '\0'; UINT size = GetFileVersionInfoSize((TCHAR*)file, &reserved); TCHAR* vbuf = new TCHAR[size]; if (GetFileVersionInfo((TCHAR*)file, 0, size, vbuf)) { VerQueryValue(vbuf, L"\\", (void**)&buf, &size); CopyMemory(&vffi, buf, sizeof(VS_FIXEDFILEINFO)); VerQueryValue(vbuf, L"\\VarFileInfo\\Translation", (void**)&buf, &size); CopyMemory(&Locale, buf, sizeof(int)); wsprintf(str, L"\\StringFileInfo\\%04X%04X\\%s", LOWORD(Locale), HIWORD(Locale), L"FileVersion"); VerQueryValue(vbuf, str, (void**)&buf, &size); _tcscpy_s(str, 256, buf); if (version != NULL) { _tcscpy_s(version, 256, buf); } } delete[] vbuf; if (_tcscmp(str, L"") != 0) { return int(_tstof(str) * 100); } else { return 0; } } BOOL IsFileExist(const TCHAR* path) { FILE* fp; errno_t err; err = _tfopen_s(&fp, path, L"rb"); if (err != 0 || fp == NULL) { return FALSE; } fclose(fp); return TRUE; } ////------------------------------------------------ // Utility ////------------------------------------------------ typedef ULONGLONG(WINAPI* FuncGetTickCount64)(); ULONGLONG GetTickCountFx() { static FuncGetTickCount64 pGetTickCount64 = (FuncGetTickCount64)GetProcAddress(GetModuleHandle(L"kernel32"), "GetTickCount64"); if (pGetTickCount64 != NULL) { return (ULONGLONG)pGetTickCount64(); } else { return (ULONGLONG)GetTickCount(); } } ULONG64 B8toB64(BYTE b0, BYTE b1, BYTE b2, BYTE b3, BYTE b4, BYTE b5, BYTE b6, BYTE b7) { ULONG64 data = ((ULONG64)b7 << 56) + ((ULONG64)b6 << 48) + ((ULONG64)b5 << 40) + ((ULONG64)b4 << 32) + ((ULONG64)b3 << 24) + ((ULONG64)b2 << 16) + ((ULONG64)b1 << 8) + ((ULONG64)b0 << 0); return data; } DWORD B8toB32(BYTE b0, BYTE b1, BYTE b2, BYTE b3) { DWORD data = ((DWORD)b3 << 24) + ((DWORD)b2 << 16) + ((DWORD)b1 << 8) + ((DWORD)b0 << 0); return data; }
1,593
2,308
/** * Copyright 1999-2015 dangdang.com. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * </p> */ package com.vip.saturn.job.console.domain; public class ExecutorProvided { private String executorName; private ExecutorProvidedType type; private ExecutorProvidedStatus status; private Boolean noTraffic; private String ip; public String getExecutorName() { return executorName; } public void setExecutorName(String executorName) { this.executorName = executorName; } public ExecutorProvidedType getType() { return type; } public void setType(ExecutorProvidedType type) { this.type = type; } public ExecutorProvidedStatus getStatus() { return status; } public void setStatus(ExecutorProvidedStatus status) { this.status = status; } public Boolean isNoTraffic() { return noTraffic; } public void setNoTraffic(Boolean noTraffic) { this.noTraffic = noTraffic; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } }
481
3,102
// RUN: %clang_cc1 -triple arm64-apple-ios7.0 -target-abi darwinpcs -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-llvm -o - -x c %s | FileCheck %s --check-prefix=CHECK-GNU-C // RUN: %clang_cc1 -triple aarch64-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefix=CHECK-GNU-CXX // Empty structs are ignored for PCS purposes on Darwin and in C mode elsewhere. // In C++ mode on ELF they consume a register slot though. Functions are // slightly bigger than minimal to make confirmation against actual GCC // behaviour easier. #if __cplusplus #define EXTERNC extern "C" #else #define EXTERNC #endif struct Empty {}; // CHECK: define i32 @empty_arg(i32 %a) // CHECK-GNU-C: define i32 @empty_arg(i32 %a) // CHECK-GNU-CXX: define i32 @empty_arg(i8 %e.coerce, i32 %a) EXTERNC int empty_arg(struct Empty e, int a) { return a; } // CHECK: define void @empty_ret() // CHECK-GNU-C: define void @empty_ret() // CHECK-GNU-CXX: define void @empty_ret() EXTERNC struct Empty empty_ret() { struct Empty e; return e; } // However, what counts as "empty" is a baroque mess. This is super-empty, it's // ignored even in C++ mode. It also has sizeof == 0, violating C++, but that's // legacy for you: struct SuperEmpty { int arr[0]; }; // CHECK: define i32 @super_empty_arg(i32 %a) // CHECK-GNU-C: define i32 @super_empty_arg(i32 %a) // CHECK-GNU-CXX: define i32 @super_empty_arg(i32 %a) EXTERNC int super_empty_arg(struct SuperEmpty e, int a) { return a; } // This is not empty. It has 0 size but consumes a register slot for GCC. struct SortOfEmpty { struct SuperEmpty e; }; // CHECK: define i32 @sort_of_empty_arg(i32 %a) // CHECK-GNU-C: define i32 @sort_of_empty_arg(i32 %a) // CHECK-GNU-CXX: define i32 @sort_of_empty_arg(i8 %e.coerce, i32 %a) EXTERNC int sort_of_empty_arg(struct Empty e, int a) { return a; } // CHECK: define void @sort_of_empty_ret() // CHECK-GNU-C: define void @sort_of_empty_ret() // CHECK-GNU-CXX: define void @sort_of_empty_ret() EXTERNC struct SortOfEmpty sort_of_empty_ret() { struct SortOfEmpty e; return e; }
820
460
/* # This file is part of the Astrometry.net suite. # Licensed under a 3-clause BSD style license - see LICENSE */ #include "bl.h" #include "healpix.h" #include "mathutil.h" #include "starutil.h" il* healpix_region_search(int seed, il* seeds, int Nside, il* accepted, il* rejected, int (*accept)(int hp, void* token), void* token, int depth) { il* frontier; anbool allocd_rej = FALSE; int d; if (!accepted) accepted = il_new(256); if (!rejected) { rejected = il_new(256); allocd_rej = TRUE; } if (seeds) //frontier = seeds; frontier = il_dupe(seeds); else { frontier = il_new(256); il_append(frontier, seed); } for (d=0; !depth || d<depth; d++) { int j, N; N = il_size(frontier); if (N == 0) break; for (j=0; j<N; j++) { int hp; int i, nn, neigh[8]; hp = il_get(frontier, j); nn = healpix_get_neighbours(hp, neigh, Nside); for (i=0; i<nn; i++) { if (il_contains(frontier, neigh[i])) continue; if (il_contains(rejected, neigh[i])) continue; if (il_contains(accepted, neigh[i])) continue; if (accept(neigh[i], token)) { il_append(accepted, neigh[i]); il_append(frontier, neigh[i]); } else il_append(rejected, neigh[i]); } } il_remove_index_range(frontier, 0, N); } il_free(frontier); if (allocd_rej) il_free(rejected); return accepted; } static il* hp_rangesearch(const double* xyz, double radius, int Nside, il* hps, anbool approx) { int hp; double hprad = arcmin2dist(healpix_side_length_arcmin(Nside)) * sqrt(2); il* frontier = il_new(256); il* bad = il_new(256); if (!hps) hps = il_new(256); hp = xyzarrtohealpix(xyz, Nside); il_append(frontier, hp); il_append(hps, hp); while (il_size(frontier)) { int nn, neighbours[8]; int i; hp = il_pop(frontier); nn = healpix_get_neighbours(hp, neighbours, Nside); for (i=0; i<nn; i++) { anbool tst; double nxyz[3]; if (il_contains(frontier, neighbours[i])) continue; if (il_contains(bad, neighbours[i])) continue; if (il_contains(hps, neighbours[i])) continue; if (approx) { healpix_to_xyzarr(neighbours[i], Nside, 0.5, 0.5, nxyz); tst = (sqrt(distsq(xyz, nxyz, 3)) - hprad <= radius); } else { tst = healpix_within_range_of_xyz(neighbours[i], Nside, xyz, radius); } if (tst) { // in range! il_append(frontier, neighbours[i]); il_append(hps, neighbours[i]); } else il_append(bad, neighbours[i]); } } il_free(bad); il_free(frontier); return hps; } il* healpix_rangesearch_xyz_approx(const double* xyz, double radius, int Nside, il* hps) { return hp_rangesearch(xyz, radius, Nside, hps, TRUE); } il* healpix_rangesearch_xyz(const double* xyz, double radius, int Nside, il* hps) { return hp_rangesearch(xyz, radius, Nside, hps, FALSE); } il* healpix_rangesearch_radec_approx(double ra, double dec, double radius, int Nside, il* hps) { double xyz[3]; radecdeg2xyzarr(ra, dec, xyz); return hp_rangesearch(xyz, radius, Nside, hps, TRUE); } il* healpix_rangesearch_radec(double ra, double dec, double radius, int Nside, il* hps) { double xyz[3]; radecdeg2xyzarr(ra, dec, xyz); return hp_rangesearch(xyz, radius, Nside, hps, FALSE); }
2,122
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. */ import java.io.*; import java.util.*; import org.w3c.dom.*; import top.*; public class TestOr extends BaseTest { public static void main(String[] argv) { TestOr o = new TestOr(); if (argv.length > 0) o.setDocumentDir(argv[0]); try { o.run(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.exit(0); } public void run() throws Exception { Top top; this.readDocument(); out("creating the bean graph"); top = Top.read(doc); // Check that we can read the graph an it is complete out("bean graph created"); top.write(out); CacheMapping cm = top.getCacheMapping(); cm.setServletName("Bob"); check(cm.getServletName().equals("Bob"), "servlet-name is Bob"); check(cm.getUrlPattern() == null, "url-pattern is null"); cm.setUrlPattern("/foo"); check(cm.getUrlPattern().equals("/foo"), "url-pattern is /foo"); check(cm.getServletName() == null, "servlet-name is null"); cm.setTimeout("100"); top.write(out); } }
737
2,730
#include <Carbon/Carbon.h> #include "synthesize.h" #include "locale.h" #include "parse.h" #include "hotkey.h" #define internal static #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated" internal inline void create_and_post_keyevent(uint16_t key, bool pressed) { CGPostKeyboardEvent((CGCharCode)0, (CGKeyCode)key, pressed); } internal inline void synthesize_modifiers(struct hotkey *hotkey, bool pressed) { if (has_flags(hotkey, Hotkey_Flag_Alt)) { create_and_post_keyevent(Modifier_Keycode_Alt, pressed); } if (has_flags(hotkey, Hotkey_Flag_Shift)) { create_and_post_keyevent(Modifier_Keycode_Shift, pressed); } if (has_flags(hotkey, Hotkey_Flag_Cmd)) { create_and_post_keyevent(Modifier_Keycode_Cmd, pressed); } if (has_flags(hotkey, Hotkey_Flag_Control)) { create_and_post_keyevent(Modifier_Keycode_Ctrl, pressed); } if (has_flags(hotkey, Hotkey_Flag_Fn)) { create_and_post_keyevent(Modifier_Keycode_Fn, pressed); } } void synthesize_key(char *key_string) { if (!initialize_keycode_map()) return; struct parser parser; parser_init_text(&parser, key_string); close(1); close(2); struct hotkey *hotkey = parse_keypress(&parser); if (!hotkey) return; CGSetLocalEventsSuppressionInterval(0.0f); CGEnableEventStateCombining(false); synthesize_modifiers(hotkey, true); create_and_post_keyevent(hotkey->key, true); create_and_post_keyevent(hotkey->key, false); synthesize_modifiers(hotkey, false); } void synthesize_text(char *text) { CFStringRef text_ref = CFStringCreateWithCString(NULL, text, kCFStringEncodingUTF8); CFIndex text_length = CFStringGetLength(text_ref); CGEventRef de = CGEventCreateKeyboardEvent(NULL, 0, true); CGEventRef ue = CGEventCreateKeyboardEvent(NULL, 0, false); CGEventSetFlags(de, 0); CGEventSetFlags(ue, 0); UniChar c; for (CFIndex i = 0; i < text_length; ++i) { c = CFStringGetCharacterAtIndex(text_ref, i); CGEventKeyboardSetUnicodeString(de, 1, &c); CGEventPost(kCGAnnotatedSessionEventTap, de); usleep(1000); CGEventKeyboardSetUnicodeString(ue, 1, &c); CGEventPost(kCGAnnotatedSessionEventTap, ue); } CFRelease(ue); CFRelease(de); CFRelease(text_ref); } #pragma clang diagnostic pop
989
4,342
<reponame>mmpio/RxPY<gh_stars>1000+ import unittest import rx from rx.testing import TestScheduler, ReactiveTest on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = ReactiveTest.subscribed disposed = ReactiveTest.disposed created = ReactiveTest.created class TestForIn(unittest.TestCase): def test_for_basic(self): scheduler = TestScheduler() def create(): def mapper(x): return scheduler.create_cold_observable( on_next(x * 100 + 10, x * 10 + 1), on_next(x * 100 + 20, x * 10 + 2), on_next(x * 100 + 30, x * 10 + 3), on_completed(x * 100 + 40)) return rx.for_in([1, 2, 3], mapper) results = scheduler.start(create=create) assert results.messages == [ on_next(310, 11), on_next(320, 12), on_next(330, 13), on_next(550, 21), on_next(560, 22), on_next(570, 23), on_next(890, 31), on_next(900, 32), on_next(910, 33), on_completed(920) ] def test_for_throws(self): ex = 'ex' scheduler = TestScheduler() def create(): def mapper(x): raise Exception(ex) return rx.for_in([1, 2, 3], mapper) results = scheduler.start(create=create) assert results.messages == [on_error(200, ex)]
726
590
package com.mploed.dddwithspring.scoring.scoringResult; import javax.persistence.*; @Entity @Table(name = "SCORING_RESULT") public class ScoringResultEntity { @Id @GeneratedValue private Long id; private String applicationNumber; private int scorePoints; private String scoreColor; @Embedded private DetailedScoringResults detailedScoringResults; public ScoringResultEntity(String applicationNumber, int scorePoints, String scoreColor, DetailedScoringResults detailedScoringResults) { this.applicationNumber = applicationNumber; this.scorePoints = scorePoints; this.scoreColor = scoreColor; this.detailedScoringResults = detailedScoringResults; } private ScoringResultEntity() { } public Long getId() { return id; } public int getScorePoints() { return scorePoints; } public String getScoreColor() { return scoreColor; } public String getApplicationNumber() { return applicationNumber; } public DetailedScoringResults getDetailedScoringResults() { return detailedScoringResults; } }
309
14,425
<filename>hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/ProgressableProgressListener.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.s3a; import com.amazonaws.event.ProgressEvent; import com.amazonaws.event.ProgressEventType; import com.amazonaws.event.ProgressListener; import com.amazonaws.services.s3.transfer.Upload; import org.apache.hadoop.util.Progressable; import org.slf4j.Logger; import static com.amazonaws.event.ProgressEventType.TRANSFER_COMPLETED_EVENT; import static com.amazonaws.event.ProgressEventType.TRANSFER_PART_STARTED_EVENT; /** * Listener to progress from AWS regarding transfers. */ public class ProgressableProgressListener implements ProgressListener { private static final Logger LOG = S3AFileSystem.LOG; private final S3AFileSystem fs; private final String key; private final Progressable progress; private long lastBytesTransferred; private final Upload upload; /** * Instantiate. * @param fs filesystem: will be invoked with statistics updates * @param key key for the upload * @param upload source of events * @param progress optional callback for progress. */ public ProgressableProgressListener(S3AFileSystem fs, String key, Upload upload, Progressable progress) { this.fs = fs; this.key = key; this.upload = upload; this.progress = progress; this.lastBytesTransferred = 0; } @Override public void progressChanged(ProgressEvent progressEvent) { if (progress != null) { progress.progress(); } // There are 3 http ops here, but this should be close enough for now ProgressEventType pet = progressEvent.getEventType(); if (pet == TRANSFER_PART_STARTED_EVENT || pet == TRANSFER_COMPLETED_EVENT) { fs.incrementWriteOperations(); } long transferred = upload.getProgress().getBytesTransferred(); long delta = transferred - lastBytesTransferred; fs.incrementPutProgressStatistics(key, delta); lastBytesTransferred = transferred; } /** * Method to invoke after upload has completed. * This can handle race conditions in setup/teardown. * @return the number of bytes which were transferred after the notification */ public long uploadCompleted() { long delta = upload.getProgress().getBytesTransferred() - lastBytesTransferred; if (delta > 0) { LOG.debug("S3A write delta changed after finished: {} bytes", delta); fs.incrementPutProgressStatistics(key, delta); } return delta; } }
996
5,169
{ "name": "SurfPlaybook", "version": "1.2.2", "summary": "iOS framework for Playbook", "homepage": "https://github.com/surfstudio/SurfPlaybook", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "11.0" }, "swift_versions": "5.0", "source": { "git": "https://github.com/surfstudio/SurfPlaybook.git", "tag": "1.2.2" }, "source_files": "SurfPlaybook/**/*.{swift,strings}", "resources": "SurfPlaybook/**/*.{xib,xcassets}", "swift_version": "5.0" }
254
16,461
<reponame>zakharchenkoAndrii/expo<gh_stars>1000+ /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <ABI43_0_0React/ABI43_0_0RCTViewManager.h> @class ABI43_0_0RCTWrapperView; NS_ASSUME_NONNULL_BEGIN @interface ABI43_0_0RCTWrapperViewManager : ABI43_0_0RCTViewManager - (ABI43_0_0RCTWrapperView *)view NS_REQUIRES_SUPER; @end NS_ASSUME_NONNULL_END
203
1,142
<reponame>alliesaizan/fairlearn<filename>scripts/_utils.py # Copyright (c) Microsoft Corporation and Fairlearn contributors. # Licensed under the MIT License. import logging import os _logger = logging.getLogger(__file__) logging.basicConfig(level=logging.INFO) def _ensure_cwd_is_fairlearn_root_dir(): # To ensure we're in the right directory that there's a fairlearn directory inside the # current working directory as well as the presence of a README.rst file. if not os.path.exists(os.path.join(os.getcwd(), "fairlearn")) or \ not os.path.exists(os.path.join(os.getcwd(), "README.rst")): raise Exception("Please run this from the fairlearn root directory. " "Current directory: {}".format(os.getcwd())) class _LogWrapper: def __init__(self, description): self._description = description def __enter__(self): _logger.info("Starting %s", self._description) def __exit__(self, type, value, traceback): # noqa: A002 # raise exceptions if any occurred if value is not None: raise value _logger.info("Completed %s", self._description)
431
695
""" =============================== K-means clustering - NumPy API =============================== The :meth:`pykeops.numpy.LazyTensor.argmin` reduction supported by KeOps :class:`pykeops.numpy.LazyTensor` allows us to perform **bruteforce nearest neighbor search** with four lines of code. It can thus be used to implement a **large-scale** `K-means clustering <https://en.wikipedia.org/wiki/K-means_clustering>`_, **without memory overflows**. .. note:: For large and high dimensional datasets, this script **is outperformed by its PyTorch counterpart** which avoids transfers between CPU (host) and GPU (device) memories. """ ######################################################################### # Setup # ----------------- # Standard imports: import time import numpy as np from matplotlib import pyplot as plt from pykeops.numpy import LazyTensor import pykeops.config dtype = "float32" # May be 'float32' or 'float64' ########################################################################## # Simple implementation of the K-means algorithm: def KMeans(x, K=10, Niter=10, verbose=True): N, D = x.shape # Number of samples, dimension of the ambient space # K-means loop: # - x is the point cloud, # - cl is the vector of class labels # - c is the cloud of cluster centroids start = time.time() c = np.copy(x[:K, :]) # Simplistic random initialization x_i = LazyTensor(x[:, None, :]) # (Npoints, 1, D) for i in range(Niter): c_j = LazyTensor(c[None, :, :]) # (1, Nclusters, D) D_ij = ((x_i - c_j) ** 2).sum( -1 ) # (Npoints, Nclusters) symbolic matrix of squared distances cl = D_ij.argmin(axis=1).astype(int).reshape(N) # Points -> Nearest cluster Ncl = np.bincount(cl).astype(dtype) # Class weights for d in range(D): # Compute the cluster centroids with np.bincount: c[:, d] = np.bincount(cl, weights=x[:, d]) / Ncl end = time.time() if verbose: print( "K-means example with {:,} points in dimension {:,}, K = {:,}:".format( N, D, K ) ) print( "Timing for {} iterations: {:.5f}s = {} x {:.5f}s\n".format( Niter, end - start, Niter, (end - start) / Niter ) ) return cl, c ############################################################### # K-means in 2D # ---------------------- # First experiment with N=10,000 points in dimension D=2, with K=50 classes: # N, D, K = 10000, 2, 50 ############################################################### # Define our dataset: x = np.random.randn(N, D).astype(dtype) / 6 + 0.5 ############################################################## # Perform the computation: cl, c = KMeans(x, K) ############################################################## # Fancy display: plt.figure(figsize=(8, 8)) plt.scatter(x[:, 0], x[:, 1], c=cl, s=30000 / len(x), cmap="tab10") plt.scatter(c[:, 0], c[:, 1], c="black", s=50, alpha=0.8) plt.axis([0, 1, 0, 1]) plt.tight_layout() plt.show() #################################################################### # K-means in dimension 100 # ------------------------- # Second experiment with N=1,000,000 points in dimension D=100, with K=1,000 classes: if pykeops.config.gpu_available: N, D, K = 1000000, 100, 1000 x = np.random.randn(N, D).astype(dtype) cl, c = KMeans(x, K)
1,282
634
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vfs.impl; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem; import com.intellij.openapi.vfs.newvfs.impl.FileNameCache; import com.intellij.openapi.vfs.newvfs.impl.NullVirtualFile; import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.util.ArrayUtil; import com.intellij.util.ObjectUtil; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Trie data structure for succinct storage and fast retrieval of file pointers. * File pointer "a/b/x.txt" is stored in the tree with nodes a->b->x.txt */ class FilePointerPartNode { private static final FilePointerPartNode[] EMPTY_ARRAY = new FilePointerPartNode[0]; private final int nameId; // name id of the VirtualFile corresponding to this node @Nonnull FilePointerPartNode[] children = EMPTY_ARRAY; // sorted by this.getName() final FilePointerPartNode parent; // file pointers for this exact path (e.g. concatenation of all "part" fields down from the root). // Either VirtualFilePointerImpl or VirtualFilePointerImpl[] (when it so happened that several pointers merged into one node - e.g. after file rename onto existing pointer) private Object leaves; // in case there is file pointer exists for this part, its info is saved here volatile Pair<VirtualFile, String> myFileAndUrl; // must not be both null volatile long myLastUpdated = -1; // contains latest result of ManagingFS.getInstance().getStructureModificationCount() volatile int useCount; int pointersUnder; // number of alive pointers in this node plus all nodes beneath private static final VirtualFileManager ourFileManager = VirtualFileManager.getInstance(); private FilePointerPartNode(int nameId, @Nonnull FilePointerPartNode parent) { assert nameId > 0 : nameId + "; " + getClass(); this.nameId = nameId; this.parent = parent; } boolean urlEndsWithName(@Nonnull String urlAfter, VirtualFile fileAfter) { if (fileAfter != null) { return nameId == getNameId(fileAfter); } return StringUtil.endsWith(urlAfter, getName()); } @Nonnull static FilePointerPartNode createFakeRoot() { return new FilePointerPartNode(null) { @Override public String toString() { return "root -> " + children.length; } @Nonnull @Override CharSequence getName() { return ""; } }; } // for creating fake root FilePointerPartNode(FilePointerPartNode parent) { nameId = -1; this.parent = parent; } @Nonnull static CharSequence fromNameId(int nameId) { return FileNameCache.getVFileName(nameId); } @Nonnull CharSequence getName() { return FileNameCache.getVFileName(nameId); } @Override public String toString() { return getName() + (children.length == 0 ? "" : " -> " + children.length); } /** * Tries to match the given path (parent, childNameId) with the trie structure of FilePointerPartNodes * <p>Recursive nodes (i.e. the nodes containing VFP with recursive==true) will be added to outDirs. * * @param parentNameId is equal to {@code parent != null ? parent.getName() : null} */ private FilePointerPartNode matchById(@Nullable VirtualFile parent, int parentNameId, int childNameId, @Nullable List<? super FilePointerPartNode> outDirs, boolean createIfNotFound, @Nonnull VirtualFileSystem fs) { assert childNameId != -1 && (parent == null) == (parentNameId == -1); FilePointerPartNode leaf; if (parent == null) { leaf = this; } else { VirtualFile gParent = getParentThroughJars(parent, fs); int gParentNameId = getNameId(gParent); leaf = matchById(gParent, gParentNameId, parentNameId, outDirs, createIfNotFound, fs); if (leaf == null) return null; } leaf.addRecursiveDirectoryPtrTo(outDirs); return leaf.findChildByNameId(childNameId, createIfNotFound); } private static int getNameId(VirtualFile file) { return file == null ? -1 : ((VirtualFileSystemEntry)file).getNameId(); } private FilePointerPartNode findByExistingNameId(@Nullable VirtualFile parent, int childNameId, @Nullable List<? super FilePointerPartNode> outDirs, @Nonnull VirtualFileSystem fs) { if (childNameId <= 0) throw new IllegalArgumentException("invalid argument childNameId: " + childNameId); FilePointerPartNode leaf; if (parent == null) { leaf = this; } else { int nameId = getNameId(parent); VirtualFile gParent = getParentThroughJars(parent, fs); int gParentNameId = getNameId(gParent); leaf = matchById(gParent, gParentNameId, nameId, outDirs, false, fs); if (leaf == null) return null; } leaf.addRecursiveDirectoryPtrTo(outDirs); return leaf.findChildByNameId(childNameId, false); } // returns start index of the name (i.e. path[return..length) is considered a name) private static int extractName(@Nonnull CharSequence path, int length) { if (length == 1 && path.charAt(0) == '/') { return 0; // in case of TEMP file system there is this weird ROOT file } int i = StringUtil.lastIndexOf(path, '/', 0, length); return i + 1; } private FilePointerPartNode findChildByNameId(int nameId, boolean createIfNotFound) { if (nameId <= 0) throw new IllegalArgumentException("invalid argument nameId: " + nameId); for (FilePointerPartNode child : children) { if (child.nameEqualTo(nameId)) return child; } if (createIfNotFound) { CharSequence name = fromNameId(nameId); int index = binarySearchChildByName(name); FilePointerPartNode child; assert index < 0 : index + " : child= '" + (child = children[index]) + "'" + "; child.nameEqualTo(nameId)=" + child.nameEqualTo(nameId) + "; child.getClass()=" + child.getClass() + "; child.nameId=" + child.nameId + "; child.getName()='" + child.getName() + "'" + "; nameId=" + nameId + "; name='" + name + "'" + "; compare(child) = " + StringUtil.compare(child.getName(), name, !SystemInfo.isFileSystemCaseSensitive) + ";" + " UrlPart.nameEquals: " + FileUtil.PATH_CHAR_SEQUENCE_HASHING_STRATEGY.equals(child.getName(), fromNameId(nameId)) + "; name.equals(child.getName())=" + name.equals(child.getName()) ; child = new FilePointerPartNode(nameId, this); children = ArrayUtil.insert(children, -index - 1, child); return child; } return null; } boolean nameEqualTo(int nameId) { return this.nameId == nameId; } private int binarySearchChildByName(@Nonnull CharSequence name) { return ObjectUtil.binarySearch(0, children.length, i -> { FilePointerPartNode child = children[i]; CharSequence childName = child.getName(); return StringUtil.compare(childName, name, !SystemInfo.isFileSystemCaseSensitive); }); } private void addRecursiveDirectoryPtrTo(@Nullable List<? super FilePointerPartNode> dirs) { if (dirs != null && hasRecursiveDirectoryPointer() && ContainerUtil.getLastItem(dirs) != this) { dirs.add(this); } } /** * Appends to {@code out} all nodes under this node whose path (beginning from this node) starts with the given path * ({@code (parent != null ? parent.getPath() : "") + (separator ? "/" : "") + childName}) and all nodes under this node with recursive directory pointers whose * path is ancestor of the given path. */ void addRelevantPointersFrom(@Nullable VirtualFile parent, int childNameId, @Nonnull List<? super FilePointerPartNode> out, boolean addSubdirectoryPointers, @Nonnull VirtualFileSystem fs) { if (childNameId <= 0) throw new IllegalArgumentException("invalid argument childNameId: " + childNameId); FilePointerPartNode node = findByExistingNameId(parent, childNameId, out, fs); if (node != null) { if (node.leaves != null) { out.add(node); } if (addSubdirectoryPointers) { // when "a/b" changed, treat all "a/b/*" virtual file pointers as changed because that's what happens on directory rename "a"->"newA": "a" deleted and "newA" created addAllPointersStrictlyUnder(node, out); } } } private boolean hasRecursiveDirectoryPointer() { if (leaves == null) return false; if (leaves instanceof VirtualFilePointer) { return ((VirtualFilePointer)leaves).isRecursive(); } VirtualFilePointerImpl[] leaves = (VirtualFilePointerImpl[])this.leaves; for (VirtualFilePointerImpl leaf : leaves) { if (leaf.isRecursive()) return true; } return false; } private static void addAllPointersStrictlyUnder(@Nonnull FilePointerPartNode node, @Nonnull List<? super FilePointerPartNode> out) { for (FilePointerPartNode child : node.children) { if (child.leaves != null) { out.add(child); } addAllPointersStrictlyUnder(child, out); } } void checkConsistency() { if (VirtualFilePointerManagerImpl.IS_UNDER_UNIT_TEST && !ApplicationInfoImpl.isInPerformanceTest()) { doCheckConsistency(); } } private void doCheckConsistency() { String name = getName().toString(); assert !"..".equals(name) && !".".equals(name) : "url must not contain '.' or '..' but got: " + this; int childSum = 0; for (int i = 0; i < children.length; i++) { FilePointerPartNode child = children[i]; childSum += child.pointersUnder; child.doCheckConsistency(); assert child.parent == this; if (i != 0) { assert !FileUtil.namesEqual(child.getName().toString(), children[i - 1].getName().toString()) : "child[" + i + "] = " + child + "; [-1] = " + children[i - 1]; } } childSum += leavesNumber(); assert (useCount == 0) == (leaves == null) : useCount + " - " + (leaves instanceof VirtualFilePointerImpl ? leaves : Arrays.toString((VirtualFilePointerImpl[])leaves)); assert pointersUnder == childSum : "expected: " + pointersUnder + "; actual: " + childSum; Pair<VirtualFile, String> fileAndUrl = myFileAndUrl; if (fileAndUrl != null && fileAndUrl.second != null) { String url = fileAndUrl.second; String path = VfsUtilCore.urlToPath(url); path = StringUtil.trimEnd(path, consulo.vfs.ArchiveFileSystem.ARCHIVE_SEPARATOR); String nameFromPath = PathUtil.getFileName(path); if (!path.isEmpty() && nameFromPath.isEmpty() && SystemInfo.isUnix) { nameFromPath = "/"; } assert StringUtilRt.equal(nameFromPath, name, SystemInfo.isFileSystemCaseSensitive) : "fileAndUrl: " + fileAndUrl + "; but this: " + this + "; nameFromPath: " + nameFromPath + "; name: " + name + "; parent: " + parent + "; path: " + path + "; url: " + url; } boolean hasFile = fileAndUrl != null && fileAndUrl.first != null; if (hasFile) { assert fileAndUrl.first.getName().equals(name) : "fileAndUrl: " + fileAndUrl + "; but this: " + this; } } // returns root node @Nonnull FilePointerPartNode remove() { int pointersNumber = leavesNumber(); assert leaves != null : toString(); associate(null, null); useCount = 0; FilePointerPartNode node; for (node = this; node.parent != null; node = node.parent) { int pointersAfter = node.pointersUnder -= pointersNumber; if (pointersAfter == 0) { node.parent.children = ArrayUtil.remove(node.parent.children, node); node.myFileAndUrl = null; } } if ((node.pointersUnder -= pointersNumber) == 0) { node.children = EMPTY_ARRAY; // clear root node, especially in tests } return node; } /** * * @return null means this node's myFileAndUrl became invalid */ @Nullable // returns pair.second != null always Pair<VirtualFile, String> update() { final long lastUpdated = myLastUpdated; final Pair<VirtualFile, String> fileAndUrl = myFileAndUrl; if (fileAndUrl == null) return null; final long fsModCount = ManagingFS.getInstance().getStructureModificationCount(); if (lastUpdated == fsModCount) return fileAndUrl; VirtualFile file = fileAndUrl.first; String url = fileAndUrl.second; boolean changed = false; if (url == null) { url = file.getUrl(); if (!file.isValid()) file = null; changed = true; } boolean fileIsValid = file != null && file.isValid(); if (file != null && !fileIsValid) { file = null; changed = true; } if (file == null) { file = ourFileManager.findFileByUrl(url); fileIsValid = file != null && file.isValid(); if (file != null) { changed = true; } } if (file != null) { if (fileIsValid) { url = file.getUrl(); // refresh url, it can differ changed |= !url.equals(fileAndUrl.second); } else { file = null; // can't find, try next time changed = true; } } Pair<VirtualFile, String> result; if (changed) { myFileAndUrl = result = Pair.create(file, url); } else { result = fileAndUrl; } myLastUpdated = fsModCount; // must be the last return result; } void associate(Object leaves, Pair<VirtualFile, String> fileAndUrl) { this.leaves = leaves; myFileAndUrl = fileAndUrl; // assign myNode last because .update() reads that field outside lock if (leaves != null) { if (leaves instanceof VirtualFilePointerImpl) { ((VirtualFilePointerImpl)leaves).myNode = this; } else { for (VirtualFilePointerImpl pointer : (VirtualFilePointerImpl[])leaves) { pointer.myNode = this; } } } myLastUpdated = -1; } int incrementUsageCount(int delta) { return useCount += delta; } int numberOfPointersUnder() { return pointersUnder; } VirtualFilePointerImpl getAnyPointer() { Object leaves = this.leaves; return leaves == null ? null : leaves instanceof VirtualFilePointerImpl ? (VirtualFilePointerImpl)leaves : ((VirtualFilePointerImpl[])leaves)[0]; } @Nonnull private String getUrl() { return parent == null ? getName().toString() : parent.getUrl() + "/" + getName(); } private int leavesNumber() { Object leaves = this.leaves; return leaves == null ? 0 : leaves instanceof VirtualFilePointerImpl ? 1 : ((VirtualFilePointerImpl[])leaves).length; } void addAllPointersTo(@Nonnull Collection<? super VirtualFilePointerImpl> outList) { Object leaves = this.leaves; if (leaves == null) { return; } if (leaves instanceof VirtualFilePointerImpl) { outList.add((VirtualFilePointerImpl)leaves); } else { ContainerUtil.addAll(outList, (VirtualFilePointerImpl[])leaves); } } @Nonnull FilePointerPartNode findOrCreateNodeByFile(@Nonnull VirtualFile file, @Nonnull NewVirtualFileSystem fs) { int nameId = getNameId(file); VirtualFile parent = getParentThroughJars(file, fs); int parentNameId = getNameId(parent); return matchById(parent, parentNameId, nameId, null, true, fs); } // for "file://a/b/c.txt" return "a/b", for "jar://a/b/j.jar!/c.txt" return "/a/b/j.jar" private static VirtualFile getParentThroughJars(@Nonnull VirtualFile file, @Nonnull VirtualFileSystem fs) { VirtualFile parent = file.getParent(); if (parent == null && fs instanceof ArchiveFileSystem) { VirtualFile local = ((ArchiveFileSystem)fs).getLocalByEntry(file); if (local != null) { parent = local.getParent(); } } return parent; } @Nonnull static FilePointerPartNode findOrCreateNodeByPath(@Nonnull FilePointerPartNode rootNode, @Nonnull String path, @Nonnull NewVirtualFileSystem fs) { List<String> names = splitNames(path); NewVirtualFile fsRoot = null; VirtualFile NEVER_TRIED_TO_FIND = NullVirtualFile.INSTANCE; // we try to never call file.findChild() because it's expensive VirtualFile currentFile = NEVER_TRIED_TO_FIND; FilePointerPartNode currentNode = rootNode; for (int i = names.size() - 1; i >= 0; i--) { String name = names.get(i); int index = currentNode.binarySearchChildByName(name); if (index >= 0) { currentNode = currentNode.children[index]; currentFile = currentFile == NEVER_TRIED_TO_FIND || currentFile == null ? currentFile : currentFile.findChild(name); continue; } // create and insert new node // first, have to check if the file root/names(end)/.../names[i] exists // if yes, create nameId-based FilePinterPartNode (for faster search and memory efficiency), // if not, create temp UrlPartNode which will be replaced with FPPN when the real file is created if (currentFile == NEVER_TRIED_TO_FIND) { if (fsRoot == null) { String rootPath = ContainerUtil.getLastItem(names); fsRoot = ManagingFS.getInstance().findRoot(rootPath, fs instanceof ArchiveFileSystem ? LocalFileSystem.getInstance() : fs); if (fsRoot != null && !fsRoot.getName().equals(rootPath)) { // ignore really weird root names, like "/" under windows fsRoot = null; } } currentFile = fsRoot == null ? null : findFileFromRoot(fsRoot, fs, names, i); } else { currentFile = currentFile == null ? null : currentFile.findChild(name); } FilePointerPartNode child = currentFile == null ? new UrlPartNode(name, currentNode) : new FilePointerPartNode(getNameId(currentFile), currentNode); currentNode.children = ArrayUtil.insert(currentNode.children, -index - 1, child); currentNode = child; if (i != 0 && fs instanceof ArchiveFileSystem && currentFile != null && !currentFile.isDirectory()) { currentFile = ((ArchiveFileSystem)fs).getRootByLocal(currentFile); } } return currentNode; } @Nonnull private static List<String> splitNames(@Nonnull String path) { List<String> names = new ArrayList<>(20); int end = path.length(); if (end == 0) return names; while (true) { int startIndex = extractName(path, end); assert startIndex != end : "startIndex: " + startIndex + "; end: " + end + "; path:'" + path + "'; toExtract: '" + path.substring(0, end) + "'"; names.add(path.substring(startIndex, end)); if (startIndex == 0) { break; } int skipSeparator = StringUtil.endsWith(path, 0, startIndex, ArchiveFileSystem.ARCHIVE_SEPARATOR) ? 2 : 1; end = startIndex - skipSeparator; if (end == 0 && path.charAt(0) == '/') { end = 1; // here's this weird ROOT file in temp system } } return names; } private static VirtualFile findFileFromRoot(@Nonnull NewVirtualFile root, @Nonnull NewVirtualFileSystem fs, @Nonnull List<String> names, int startIndex) { VirtualFile file = root; // start from before-the-last because it's the root, which we already found for (int i = names.size() - 2; i >= startIndex; i--) { String name = names.get(i); file = file.findChild(name); if (fs instanceof ArchiveFileSystem && file != null && !file.isDirectory() && file.getFileSystem() != fs) { file = ((ArchiveFileSystem)fs).getRootByLocal(file); } if (file == null) break; } return file; } }
9,373
373
<gh_stars>100-1000 /* Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,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. ==============================================================================*/ #ifndef _DIOS_SSP_GSC_MULTIGSCBEAMFORMER_H_ #define _DIOS_SSP_GSC_MULTIGSCBEAMFORMER_H_ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "dios_ssp_gsc_globaldefs.h" #include "dios_ssp_gsc_beamformer.h" #include "dios_ssp_gsc_dsptools.h" #include "dios_ssp_gsc_beamsteering.h" #include "dios_ssp_gsc_filtsumbeamformer.h" #include "dios_ssp_gsc_abm.h" #include "dios_ssp_gsc_aic.h" #include "dios_ssp_gsc_adaptctrl.h" #include "../dios_ssp_share/dios_ssp_share_typedefs.h" typedef struct { DWORD m_nBeam; float **m_pOutput; objCGSCbeamformer *gscbeamformer; }objCMultiGSCbeamformer; /********************************************************************************** Function: // dios_ssp_gsc_multibeamformer_init Description: // multibeamformer init Input: // multigscbeamformer: multigscbeamformer object pointer nMic: microphone number mic_coord: each microphone coordinate (PlaneCoord*)mic_coord Output: // none Return: // success: return multigscbeamformer object pointer Others: // none **********************************************************************************/ void dios_ssp_gsc_multibeamformer_init(objCMultiGSCbeamformer* multigscbeamformer, DWORD nMic, DWORD nBeam, DWORD dwSampRate, DWORD dwBlockSize, General_ArrayGeometric type, void *coord); /********************************************************************************** Function: // dios_ssp_gsc_multibeamformer_reset Description: // multibeamformer reset Input: // multigscbeamformer: multigscbeamformer object pointer Output: // none Return: // success: return 0 Others: // none **********************************************************************************/ int dios_ssp_gsc_multibeamformer_reset(objCMultiGSCbeamformer* multigscbeamformer); /********************************************************************************** Function: // dios_ssp_gsc_multibeamformer_arraysteer Description: // multibeamformer steering Input: // prototype: pSrcLoc, polar coordinates of source locations Output: // none Return: // success: return 0 Others: // none **********************************************************************************/ int dios_ssp_gsc_multibeamformer_arraysteer(objCMultiGSCbeamformer* multigscbeamformer, PolarCoord *pSrcLoc); /********************************************************************************** Function: // dios_ssp_gsc_multibeamformer_process Description: // process data of one block Input: // prototype: pInput, float data, multi-channel, continuous memory Output: // none Return: // success: return 0 Others: // none **********************************************************************************/ int dios_ssp_gsc_multibeamformer_process(objCMultiGSCbeamformer* multigscbeamformer, float** ppInput); /********************************************************************************** Function: // dios_ssp_gsc_multibeamformer_delete Description: // multibeamformer delete Input: // multigscbeamformer: multigscbeamformer object pointer Output: // none Return: // success: return 0 Others: // none **********************************************************************************/ int dios_ssp_gsc_multibeamformer_delete(objCMultiGSCbeamformer* multigscbeamformer); #endif /* _DIOS_SSP_GSC_MULTIGSCBEAMFORMER_H_ */
1,341
6,831
<reponame>ajayiagbebaku/NFL-Model<filename>venv/Lib/site-packages/altair/examples/strip_plot.py<gh_stars>1000+ """ Simple Strip Plot ----------------- A simple example of how to make a strip plot. """ # category: simple charts import altair as alt from vega_datasets import data source = data.cars() alt.Chart(source).mark_tick().encode( x='Horsepower:Q', y='Cylinders:O' )
142
511
#include "rr.h" namespace rr { void HeapStatistics::Init() { ClassBuilder("HeapStatistics"). defineSingletonMethod("new", &initialize). defineMethod("total_heap_size", &total_heap_size). defineMethod("total_heap_size_executable", &total_heap_size_executable). defineMethod("total_physical_size", &total_physical_size). defineMethod("used_heap_size", &used_heap_size). defineMethod("heap_size_limit", &heap_size_limit). store(&Class); } VALUE HeapStatistics::initialize(VALUE self) { return HeapStatistics(new v8::HeapStatistics()); } VALUE HeapStatistics::total_heap_size(VALUE self) { return SIZET2NUM(HeapStatistics(self)->total_heap_size()); } VALUE HeapStatistics::total_heap_size_executable(VALUE self) { return SIZET2NUM(HeapStatistics(self)->total_heap_size_executable()); } VALUE HeapStatistics::total_physical_size(VALUE self) { return SIZET2NUM(HeapStatistics(self)->total_physical_size()); } VALUE HeapStatistics::used_heap_size(VALUE self) { return SIZET2NUM(HeapStatistics(self)->used_heap_size()); } VALUE HeapStatistics::heap_size_limit(VALUE self) { return SIZET2NUM(HeapStatistics(self)->heap_size_limit()); } template <> void Pointer<v8::HeapStatistics>::unwrap(VALUE value) { Data_Get_Struct(value, class v8::HeapStatistics, pointer); } }
515
1,902
<filename>DiffAugment-biggan-imagenet/compare_gan/hooks.py # coding=utf-8 # Copyright 2018 Google LLC & <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. """Contains SessionRunHooks for training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from absl import logging import tensorflow as tf class AsyncCheckpointSaverHook(tf.contrib.tpu.AsyncCheckpointSaverHook): """Saves checkpoints every N steps in a asynchronous thread. This is the same as tf.contrib.tpu.AsyncCheckpointSaverHook but guarantees that there will be a checkpoint every `save_steps` steps. This helps to have eval results at fixed step counts, even when training is paused between regular checkpoint intervals. """ def after_create_session(self, session, coord): super(AsyncCheckpointSaverHook, self).after_create_session(session, coord) # Interruptions to the training job can cause non-regular checkpoints # (between every_steps). Modify last triggered step to point to the last # regular checkpoint step to make sure we trigger on the next regular # checkpoint step. step = session.run(self._global_step_tensor) every_steps = self._timer._every_steps # pylint: disable=protected-access last_triggered_step = step - step % every_steps self._timer.update_last_triggered_step(last_triggered_step) class EveryNSteps(tf.train.SessionRunHook): """"Base class for hooks that execute callbacks every N steps. class MyHook(EveryNSteps): def __init__(self, every_n_steps): super(MyHook, self).__init__(every_n_steps) def every_n_steps_after_run(self, step, run_context, run_values): # Your Implementation If you do overwrite begin(), end(), before_run() or after_run() make sure to call super() at the beginning. """ def __init__(self, every_n_steps): """Initializes an `EveryNSteps` hook. Args: every_n_steps: `int`, the number of steps to allow between callbacks. """ self._timer = tf.train.SecondOrStepTimer(every_steps=every_n_steps) self._global_step_tensor = None def begin(self): self._global_step_tensor = tf.train.get_global_step() if self._global_step_tensor is None: raise RuntimeError("Global step must be created to use EveryNSteps.") def before_run(self, run_context): # pylint: disable=unused-argument """Overrides `SessionRunHook.before_run`. Args: run_context: A `SessionRunContext` object. Returns: None or a `SessionRunArgs` object. """ return tf.train.SessionRunArgs({"global_step": self._global_step_tensor}) def after_run(self, run_context, run_values): """Overrides `SessionRunHook.after_run`. Args: run_context: A `SessionRunContext` object. run_values: A SessionRunValues object. """ step = run_values.results["global_step"] if self._timer.should_trigger_for_step(step): self.every_n_steps_after_run(step, run_context, run_values) self._timer.update_last_triggered_step(step) def end(self, sess): step = sess.run(self._global_step_tensor) self.every_n_steps_after_run(step, None, None) def every_n_steps_after_run(self, step, run_context, run_values): """Callback after every n"th call to run(). Args: step: Current global_step value. run_context: A `SessionRunContext` object. run_values: A SessionRunValues object. """ raise NotImplementedError("Subclasses of EveryNSteps should implement " "every_n_steps_after_run().") class ReportProgressHook(EveryNSteps): """SessionRunHook that reports progress to a `TaskManager` instance.""" def __init__(self, task_manager, max_steps, every_n_steps=100): """Create a new instance of ReportProgressHook. Args: task_manager: A `TaskManager` instance that implements report_progress(). max_steps: Maximum number of training steps. every_n_steps: How frequently the hook should report progress. """ super(ReportProgressHook, self).__init__(every_n_steps=every_n_steps) logging.info("Creating ReportProgressHook to report progress every %d " "steps.", every_n_steps) self.max_steps = max_steps self.task_manager = task_manager self.start_time = None self.start_step = None def every_n_steps_after_run(self, step, run_context, run_values): if self.start_time is None: # First call. self.start_time = time.time() self.start_step = step return time_elapsed = time.time() - self.start_time steps_per_sec = float(step - self.start_step) / time_elapsed eta_seconds = (self.max_steps - step) / (steps_per_sec + 0.0000001) message = "{:.1f}% @{:d}, {:.1f} steps/s, ETA: {:.0f} min".format( 100 * step / self.max_steps, step, steps_per_sec, eta_seconds / 60) logging.info("Reporting progress: %s", message) self.task_manager.report_progress(message)
1,909
1,144
<filename>u-boot-2019.01+gitAUTOINC+333c3e72d3-g333c3e72d3/drivers/ddr/microchip/ddr2.c // SPDX-License-Identifier: GPL-2.0+ /* * (c) 2015 <NAME> <<EMAIL>> * */ #include <common.h> #include <wait_bit.h> #include <linux/kernel.h> #include <linux/bitops.h> #include <mach/pic32.h> #include <mach/ddr.h> #include "ddr2_regs.h" #include "ddr2_timing.h" /* init DDR2 Phy */ void ddr2_phy_init(void) { struct ddr2_phy_regs *ddr2_phy; u32 pad_ctl; ddr2_phy = ioremap(PIC32_DDR2P_BASE, sizeof(*ddr2_phy)); /* PHY_DLL_RECALIB */ writel(DELAY_START_VAL(3) | DISABLE_RECALIB(0) | RECALIB_CNT(0x10), &ddr2_phy->dll_recalib); /* PHY_PAD_CTRL */ pad_ctl = ODT_SEL | ODT_EN | DRIVE_SEL(0) | ODT_PULLDOWN(2) | ODT_PULLUP(3) | EXTRA_OEN_CLK(0) | NOEXT_DLL | DLR_DFT_WRCMD | HALF_RATE | DRVSTR_PFET(0xe) | DRVSTR_NFET(0xe) | RCVR_EN | PREAMBLE_DLY(2); writel(pad_ctl, &ddr2_phy->pad_ctrl); /* SCL_CONFIG_0 */ writel(SCL_BURST8 | SCL_DDR_CONNECTED | SCL_RCAS_LAT(RL) | SCL_ODTCSWW, &ddr2_phy->scl_config_1); /* SCL_CONFIG_1 */ writel(SCL_CSEN | SCL_WCAS_LAT(WL), &ddr2_phy->scl_config_2); /* SCL_LAT */ writel(SCL_CAPCLKDLY(3) | SCL_DDRCLKDLY(4), &ddr2_phy->scl_latency); } /* start phy self calibration logic */ static int ddr2_phy_calib_start(void) { struct ddr2_phy_regs *ddr2_phy; ddr2_phy = ioremap(PIC32_DDR2P_BASE, sizeof(*ddr2_phy)); /* DDR Phy SCL Start */ writel(SCL_START | SCL_EN, &ddr2_phy->scl_start); /* Wait for SCL for data byte to pass */ return wait_for_bit_le32(&ddr2_phy->scl_start, SCL_LUBPASS, true, CONFIG_SYS_HZ, false); } /* DDR2 Controller initialization */ /* Target Agent Arbiter */ static void ddr_set_arbiter(struct ddr2_ctrl_regs *ctrl, const struct ddr2_arbiter_params *const param) { int i; for (i = 0; i < NUM_AGENTS; i++) { /* set min burst size */ writel(i * MIN_LIM_WIDTH, &ctrl->tsel); writel(param->min_limit, &ctrl->minlim); /* set request period (4 * req_period clocks) */ writel(i * RQST_PERIOD_WIDTH, &ctrl->tsel); writel(param->req_period, &ctrl->reqprd); /* set number of burst accepted */ writel(i * MIN_CMDACPT_WIDTH, &ctrl->tsel); writel(param->min_cmd_acpt, &ctrl->mincmd); } } const struct ddr2_arbiter_params *__weak board_get_ddr_arbiter_params(void) { /* default arbiter parameters */ static const struct ddr2_arbiter_params arb_params[] = { { .min_limit = 0x1f, .req_period = 0xff, .min_cmd_acpt = 0x04,}, { .min_limit = 0x1f, .req_period = 0xff, .min_cmd_acpt = 0x10,}, { .min_limit = 0x1f, .req_period = 0xff, .min_cmd_acpt = 0x10,}, { .min_limit = 0x04, .req_period = 0xff, .min_cmd_acpt = 0x04,}, { .min_limit = 0x04, .req_period = 0xff, .min_cmd_acpt = 0x04,}, }; return &arb_params[0]; } static void host_load_cmd(struct ddr2_ctrl_regs *ctrl, u32 cmd_idx, u32 hostcmd2, u32 hostcmd1, u32 delay) { u32 hc_delay; hc_delay = max_t(u32, DIV_ROUND_UP(delay, T_CK), 2) - 2; writel(hostcmd1, &ctrl->cmd10[cmd_idx]); writel((hostcmd2 & 0x7ff) | (hc_delay << 11), &ctrl->cmd20[cmd_idx]); } /* init DDR2 Controller */ void ddr2_ctrl_init(void) { u32 wr2prech, rd2prech, wr2rd, wr2rd_cs; u32 ras2ras, ras2cas, prech2ras, temp; const struct ddr2_arbiter_params *arb_params; struct ddr2_ctrl_regs *ctrl; ctrl = ioremap(PIC32_DDR2C_BASE, sizeof(*ctrl)); /* PIC32 DDR2 controller always work in HALF_RATE */ writel(HALF_RATE_MODE, &ctrl->memwidth); /* Set arbiter configuration per target */ arb_params = board_get_ddr_arbiter_params(); ddr_set_arbiter(ctrl, arb_params); /* Address Configuration, model {CS, ROW, BA, COL} */ writel((ROW_ADDR_RSHIFT | (BA_RSHFT << 8) | (CS_ADDR_RSHIFT << 16) | (COL_HI_RSHFT << 24) | (SB_PRI << 29) | (EN_AUTO_PRECH << 30)), &ctrl->memcfg0); writel(ROW_ADDR_MASK, &ctrl->memcfg1); writel(COL_HI_MASK, &ctrl->memcfg2); writel(COL_LO_MASK, &ctrl->memcfg3); writel(BA_MASK | (CS_ADDR_MASK << 8), &ctrl->memcfg4); /* Refresh Config */ writel(REFCNT_CLK(DIV_ROUND_UP(T_RFI, T_CK_CTRL) - 2) | REFDLY_CLK(DIV_ROUND_UP(T_RFC_MIN, T_CK_CTRL) - 2) | MAX_PEND_REF(7), &ctrl->refcfg); /* Power Config */ writel(ECC_EN(0) | ERR_CORR_EN(0) | EN_AUTO_PWR_DN(0) | EN_AUTO_SELF_REF(3) | PWR_DN_DLY(8) | SELF_REF_DLY(17) | PRECH_PWR_DN_ONLY(0), &ctrl->pwrcfg); /* Delay Config */ wr2rd = max_t(u32, DIV_ROUND_UP(T_WTR, T_CK_CTRL), DIV_ROUND_UP(T_WTR_TCK, 2)) + WL + BL; wr2rd_cs = max_t(u32, wr2rd - 1, 3); wr2prech = DIV_ROUND_UP(T_WR, T_CK_CTRL) + WL + BL; rd2prech = max_t(u32, DIV_ROUND_UP(T_RTP, T_CK_CTRL), DIV_ROUND_UP(T_RTP_TCK, 2)) + BL - 2; ras2ras = max_t(u32, DIV_ROUND_UP(T_RRD, T_CK_CTRL), DIV_ROUND_UP(T_RRD_TCK, 2)) - 1; ras2cas = DIV_ROUND_UP(T_RCD, T_CK_CTRL) - 1; prech2ras = DIV_ROUND_UP(T_RP, T_CK_CTRL) - 1; writel(((wr2rd & 0x0f) | ((wr2rd_cs & 0x0f) << 4) | ((BL - 1) << 8) | (BL << 12) | ((BL - 1) << 16) | ((BL - 1) << 20) | ((BL + 2) << 24) | ((RL - WL + 3) << 28)), &ctrl->dlycfg0); writel(((T_CKE_TCK - 1) | (((DIV_ROUND_UP(T_DLLK, 2) - 2) & 0xff) << 8) | ((T_CKE_TCK - 1) << 16) | ((max_t(u32, T_XP_TCK, T_CKE_TCK) - 1) << 20) | ((wr2prech >> 4) << 26) | ((wr2rd >> 4) << 27) | ((wr2rd_cs >> 4) << 28) | (((RL + 5) >> 4) << 29) | ((DIV_ROUND_UP(T_DLLK, 2) >> 8) << 30)), &ctrl->dlycfg1); writel((DIV_ROUND_UP(T_RP, T_CK_CTRL) | (rd2prech << 8) | ((wr2prech & 0x0f) << 12) | (ras2ras << 16) | (ras2cas << 20) | (prech2ras << 24) | ((RL + 3) << 28)), &ctrl->dlycfg2); writel(((DIV_ROUND_UP(T_RAS_MIN, T_CK_CTRL) - 1) | ((DIV_ROUND_UP(T_RC, T_CK_CTRL) - 1) << 8) | ((DIV_ROUND_UP(T_FAW, T_CK_CTRL) - 1) << 16)), &ctrl->dlycfg3); /* ODT Config */ writel(0x0, &ctrl->odtcfg); writel(BIT(16), &ctrl->odtencfg); writel(ODTRDLY(RL - 3) | ODTWDLY(WL - 3) | ODTRLEN(2) | ODTWLEN(3), &ctrl->odtcfg); /* Transfer Configuration */ writel(NXTDATRQDLY(2) | NXDATAVDLY(4) | RDATENDLY(2) | MAX_BURST(3) | (7 << 28) | BIG_ENDIAN(0), &ctrl->xfercfg); /* DRAM Initialization */ /* CKE high after reset and wait 400 nsec */ host_load_cmd(ctrl, 0, 0, IDLE_NOP, 400000); /* issue precharge all command */ host_load_cmd(ctrl, 1, 0x04, PRECH_ALL_CMD, T_RP + T_CK); /* initialize EMR2 */ host_load_cmd(ctrl, 2, 0x200, LOAD_MODE_CMD, T_MRD_TCK * T_CK); /* initialize EMR3 */ host_load_cmd(ctrl, 3, 0x300, LOAD_MODE_CMD, T_MRD_TCK * T_CK); /* * RDQS disable, DQSB enable, OCD exit, 150 ohm termination, * AL=0, DLL enable */ host_load_cmd(ctrl, 4, 0x100, LOAD_MODE_CMD | (0x40 << 24), T_MRD_TCK * T_CK); /* * PD fast exit, WR REC = T_WR in clocks -1, * DLL reset, CAS = RL, burst = 4 */ temp = ((DIV_ROUND_UP(T_WR, T_CK) - 1) << 1) | 1; host_load_cmd(ctrl, 5, temp, LOAD_MODE_CMD | (RL << 28) | (2 << 24), T_MRD_TCK * T_CK); /* issue precharge all command */ host_load_cmd(ctrl, 6, 4, PRECH_ALL_CMD, T_RP + T_CK); /* issue refresh command */ host_load_cmd(ctrl, 7, 0, REF_CMD, T_RFC_MIN); /* issue refresh command */ host_load_cmd(ctrl, 8, 0, REF_CMD, T_RFC_MIN); /* Mode register programming as before without DLL reset */ host_load_cmd(ctrl, 9, temp, LOAD_MODE_CMD | (RL << 28) | (3 << 24), T_MRD_TCK * T_CK); /* extended mode register same as before with OCD default */ host_load_cmd(ctrl, 10, 0x103, LOAD_MODE_CMD | (0xc << 24), T_MRD_TCK * T_CK); /* extended mode register same as before with OCD exit */ host_load_cmd(ctrl, 11, 0x100, LOAD_MODE_CMD | (0x4 << 28), 140 * T_CK); writel(CMD_VALID | NUMHOSTCMD(11), &ctrl->cmdissue); /* start memory initialization */ writel(INIT_START, &ctrl->memcon); /* wait for all host cmds to be transmitted */ wait_for_bit_le32(&ctrl->cmdissue, CMD_VALID, false, CONFIG_SYS_HZ, false); /* inform all cmds issued, ready for normal operation */ writel(INIT_START | INIT_DONE, &ctrl->memcon); /* perform phy caliberation */ if (ddr2_phy_calib_start()) printf("ddr2: phy calib failed\n"); } phys_size_t ddr2_calculate_size(void) { u32 temp; temp = 1 << (COL_BITS + BA_BITS + ROW_BITS); /* 16-bit data width between controller and DIMM */ temp = temp * CS_BITS * (16 / 8); return (phys_size_t)temp; }
4,230
670
package com.hw.photomovie.opengl; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11ExtensionPack; /** * @Author Jituo.Xuan * @Date 11:40:51 AM Mar 20, 2014 * @Comments:This mimics corresponding GL functions. */ public interface GLId { public int generateTexture(); public void glGenBuffers(int n, int[] buffers, int offset); public void glDeleteTextures(GL11 gl, int n, int[] textures, int offset); public void glDeleteBuffers(GL11 gl, int n, int[] buffers, int offset); public void glDeleteFramebuffers(GL11ExtensionPack gl11ep, int n, int[] buffers, int offset); }
217
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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "AccessibleGlobal.hxx" #include "AccessibleFilterMenu.hxx" #include "AccessibleFilterMenuItem.hxx" #include "unoguard.hxx" #include "global.hxx" #include "document.hxx" #include "docpool.hxx" #include "tools/gen.hxx" #include "editeng/unoedsrc.hxx" #include "editeng/editdata.hxx" #include "editeng/outliner.hxx" #include "vcl/unohelp.hxx" #include "dpcontrol.hxx" #include <com/sun/star/accessibility/XAccessible.hpp> #include <com/sun/star/accessibility/XAccessibleStateSet.hpp> #include <com/sun/star/accessibility/AccessibleRole.hpp> #include <com/sun/star/accessibility/AccessibleEventId.hpp> #include <com/sun/star/accessibility/AccessibleStateType.hpp> using namespace ::com::sun::star; using namespace ::com::sun::star::accessibility; using namespace ::com::sun::star::accessibility::AccessibleStateType; using ::com::sun::star::uno::Any; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::lang::IndexOutOfBoundsException; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::uno::RuntimeException; using ::rtl::OUString; using ::std::for_each; using ::std::vector; // ============================================================================ namespace { class AddRemoveEventListener : public ::std::unary_function<void, Reference<XAccessible> > { public: explicit AddRemoveEventListener(const Reference<XAccessibleEventListener>& rListener, bool bAdd) : mxListener(rListener), mbAdd(bAdd) {} void operator() (const Reference<XAccessible>& xAccessible) const { if (!xAccessible.is()) return; Reference<XAccessibleEventBroadcaster> xBc(xAccessible, UNO_QUERY); if (xBc.is()) { if (mbAdd) xBc->addEventListener(mxListener); else xBc->removeEventListener(mxListener); } } private: Reference<XAccessibleEventListener> mxListener; bool mbAdd; }; } // ============================================================================ ScAccessibleFilterMenu::ScAccessibleFilterMenu(const Reference<XAccessible>& rxParent, ScMenuFloatingWindow* pWin, const OUString& rName, size_t nMenuPos, ScDocument* pDoc) : ScAccessibleContextBase(rxParent, AccessibleRole::MENU), mnMenuPos(nMenuPos), mpWindow(pWin), mpDoc(pDoc), mbEnabled(true) { SetName(rName); } ScAccessibleFilterMenu::~ScAccessibleFilterMenu() { } // XAccessibleComponent Reference<XAccessible> ScAccessibleFilterMenu::getAccessibleAtPoint( const ::com::sun::star::awt::Point& /*rPoint*/ ) throw (RuntimeException) { return this; } sal_Bool ScAccessibleFilterMenu::isVisible() throw (RuntimeException) { return mpWindow->IsVisible(); } void ScAccessibleFilterMenu::grabFocus() throw (RuntimeException) { } sal_Int32 ScAccessibleFilterMenu::getForeground() throw (RuntimeException) { return 0; } sal_Int32 ScAccessibleFilterMenu::getBackground() throw (RuntimeException) { return 0; } // XAccessibleContext OUString ScAccessibleFilterMenu::getAccessibleName() throw (RuntimeException) { return ScAccessibleContextBase::getAccessibleName(); } sal_Int32 ScAccessibleFilterMenu::getAccessibleChildCount() throw (RuntimeException) { return getMenuItemCount(); } Reference<XAccessible> ScAccessibleFilterMenu::getAccessibleChild(sal_Int32 nIndex) throw (RuntimeException, IndexOutOfBoundsException) { if (maMenuItems.size() <= static_cast<size_t>(nIndex)) throw IndexOutOfBoundsException(); return maMenuItems[nIndex]; } Reference<XAccessibleStateSet> ScAccessibleFilterMenu::getAccessibleStateSet() throw (RuntimeException) { updateStates(); return mxStateSet; } OUString ScAccessibleFilterMenu::getImplementationName() throw (RuntimeException) { return OUString::createFromAscii("ScAccessibleFilterMenu"); } // XAccessibleEventBroadcaster void ScAccessibleFilterMenu::addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener>& xListener) throw (com::sun::star::uno::RuntimeException) { ScAccessibleContextBase::addEventListener(xListener); for_each(maMenuItems.begin(), maMenuItems.end(), AddRemoveEventListener(xListener, true)); } void ScAccessibleFilterMenu::removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener>& xListener) throw (com::sun::star::uno::RuntimeException) { ScAccessibleContextBase::removeEventListener(xListener); for_each(maMenuItems.begin(), maMenuItems.end(), AddRemoveEventListener(xListener, false)); } // XAccessibleSelection void ScAccessibleFilterMenu::selectAccessibleChild(sal_Int32 nChildIndex) throw (IndexOutOfBoundsException, RuntimeException) { if (static_cast<size_t>(nChildIndex) >= maMenuItems.size()) throw IndexOutOfBoundsException(); mpWindow->setSelectedMenuItem(nChildIndex, false, true); } sal_Bool ScAccessibleFilterMenu::isAccessibleChildSelected(sal_Int32 nChildIndex) throw (IndexOutOfBoundsException, RuntimeException) { if (static_cast<size_t>(nChildIndex) >= maMenuItems.size()) throw IndexOutOfBoundsException(); return mpWindow->isMenuItemSelected(static_cast<size_t>(nChildIndex)); } void ScAccessibleFilterMenu::clearAccessibleSelection() throw (RuntimeException) { mpWindow->clearSelectedMenuItem(); } void ScAccessibleFilterMenu::selectAllAccessibleChildren() throw (RuntimeException) { // not supported - this is a menu, you can't select all menu items. } sal_Int32 ScAccessibleFilterMenu::getSelectedAccessibleChildCount() throw (RuntimeException) { // Since this is a menu, either one menu item is selected, or none at all. return mpWindow->getSelectedMenuItem() == ScMenuFloatingWindow::MENU_NOT_SELECTED ? 0 : 1; } Reference<XAccessible> ScAccessibleFilterMenu::getSelectedAccessibleChild(sal_Int32 nChildIndex) throw (IndexOutOfBoundsException, RuntimeException) { if (static_cast<size_t>(nChildIndex) >= maMenuItems.size()) throw IndexOutOfBoundsException(); return maMenuItems[nChildIndex]; } void ScAccessibleFilterMenu::deselectAccessibleChild(sal_Int32 nChildIndex) throw (IndexOutOfBoundsException, RuntimeException) { if (static_cast<size_t>(nChildIndex) >= maMenuItems.size()) throw IndexOutOfBoundsException(); mpWindow->selectMenuItem(nChildIndex, false, false); } // XInterface uno::Any SAL_CALL ScAccessibleFilterMenu::queryInterface( uno::Type const & rType ) throw (RuntimeException) { Any any = ScAccessibleContextBase::queryInterface(rType); if (any.hasValue()) return any; return ScAccessibleFilterMenu_BASE::queryInterface(rType); } void SAL_CALL ScAccessibleFilterMenu::acquire() throw () { ScAccessibleContextBase::acquire(); } void SAL_CALL ScAccessibleFilterMenu::release() throw () { ScAccessibleContextBase::release(); } // XTypeProvider Sequence<sal_Int8> ScAccessibleFilterMenu::getImplementationId() throw (RuntimeException) { Sequence<sal_Int8> aId(16); return aId; } Rectangle ScAccessibleFilterMenu::GetBoundingBoxOnScreen() const throw (RuntimeException) { if (mnMenuPos == ScMenuFloatingWindow::MENU_NOT_SELECTED) return Rectangle(); // Menu object's bounding box is the bounding box of the menu item that // launches the menu, which belongs to the parent window. ScMenuFloatingWindow* pParentWin = mpWindow->getParentMenuWindow(); if (!pParentWin) return Rectangle(); if (!pParentWin->IsVisible()) return Rectangle(); Point aPos = pParentWin->OutputToAbsoluteScreenPixel(Point(0,0)); Point aMenuPos; Size aMenuSize; pParentWin->getMenuItemPosSize(mnMenuPos, aMenuPos, aMenuSize); Rectangle aRect(aPos + aMenuPos, aMenuSize); return aRect; } Rectangle ScAccessibleFilterMenu::GetBoundingBox() const throw (RuntimeException) { if (mnMenuPos == ScMenuFloatingWindow::MENU_NOT_SELECTED) return Rectangle(); // Menu object's bounding box is the bounding box of the menu item that // launches the menu, which belongs to the parent window. ScMenuFloatingWindow* pParentWin = mpWindow->getParentMenuWindow(); if (!pParentWin) return Rectangle(); if (!pParentWin->IsVisible()) return Rectangle(); Point aMenuPos; Size aMenuSize; pParentWin->getMenuItemPosSize(mnMenuPos, aMenuPos, aMenuSize); Rectangle aRect(aMenuPos, aMenuSize); return aRect; } void ScAccessibleFilterMenu::appendMenuItem(const OUString& rName, bool bEnabled, size_t nMenuPos) { // Check whether this menu item is a sub menu or a regular menu item. ScMenuFloatingWindow* pSubMenu = mpWindow->getSubMenuWindow(nMenuPos); Reference<XAccessible> xAccessible; if (pSubMenu) { xAccessible = pSubMenu->CreateAccessible(); ScAccessibleFilterMenu* p = static_cast<ScAccessibleFilterMenu*>(xAccessible.get()); p->setEnabled(bEnabled); p->setMenuPos(nMenuPos); } else { xAccessible.set(new ScAccessibleFilterMenuItem(this, mpWindow, rName, nMenuPos)); ScAccessibleFilterMenuItem* p = static_cast<ScAccessibleFilterMenuItem*>(xAccessible.get()); p->setEnabled(bEnabled); } maMenuItems.push_back(xAccessible); } void ScAccessibleFilterMenu::setMenuPos(size_t nMenuPos) { mnMenuPos = nMenuPos; } void ScAccessibleFilterMenu::setEnabled(bool bEnabled) { mbEnabled = bEnabled; } sal_Int32 ScAccessibleFilterMenu::getMenuItemCount() const { return maMenuItems.size(); } bool ScAccessibleFilterMenu::isSelected() const { // Check to see if any of the child menu items is selected. return mpWindow->isMenuItemSelected(mnMenuPos); } bool ScAccessibleFilterMenu::isFocused() const { return isSelected(); } void ScAccessibleFilterMenu::updateStates() { if (!mxStateSet.is()) mxStateSet.set(new ScAccessibleStateSet); ScAccessibleStateSet* p = static_cast<ScAccessibleStateSet*>( mxStateSet.get()); p->clear(); p->insert(ENABLED); p->insert(FOCUSABLE); p->insert(SELECTABLE); p->insert(SENSITIVE); p->insert(OPAQUE); if (isFocused()) p->insert(FOCUSED); if (isSelected()) p->insert(SELECTED); }
4,001
867
# This file is generated by codegen.py. DO NOT EDIT! from __future__ import annotations import uuid from typing import TYPE_CHECKING, Callable, List, Optional # 14: override Element from gaphor.core.modeling import Comment, Element from gaphor.core.modeling.properties import ( association, attribute, derived, derivedunion, enumeration, redefine, relation_many, relation_one, ) class NamedElement(Element): name: attribute[str] visibility: enumeration clientDependency: relation_many[Dependency] supplierDependency: relation_many[Dependency] informationFlow: relation_many[InformationFlow] qualifiedName: derived[list[str]] namespace: relation_one[Namespace] memberNamespace: relation_many[Namespace] class PackageableElement(NamedElement): component: relation_one[Component] owningPackage: relation_one[Package] class DeployedArtifact(NamedElement): pass class DeploymentTarget(NamedElement): deployment: relation_many[Deployment] class InstanceSpecification(PackageableElement, DeployedArtifact, DeploymentTarget): specification: attribute[str] slot: relation_many[Slot] classifier: relation_many[Classifier] extended: relation_many[Element] class EnumerationLiteral(InstanceSpecification): enumeration: relation_one[Enumeration] class Relationship(Element): relatedElement: relation_many[Element] class DirectedRelationship(Relationship): target: relation_many[Element] source: relation_many[Element] class PackageMerge(DirectedRelationship): mergingPackage: relation_one[Package] mergedPackage: relation_one[Package] class Namespace(NamedElement): elementImport: relation_many[ElementImport] packageImport: relation_many[PackageImport] ownedRule: relation_many[Constraint] ownedMember: relation_many[NamedElement] member: relation_many[NamedElement] importedMember: derivedunion[PackageableElement] class Type(PackageableElement): package: relation_one[Package] class RedefinableElement(NamedElement): isLeaf: attribute[int] visibility: enumeration redefinedElement: relation_many[RedefinableElement] redefinitionContext: relation_many[Classifier] class Classifier(Namespace, Type, RedefinableElement): isAbstract: attribute[int] ownedUseCase: relation_many[UseCase] generalization: relation_many[Generalization] useCase: relation_many[UseCase] redefinedClassifier: relation_many[Classifier] nestingClass: relation_one[Class] attribute: relation_many[Property] feature: relation_many[Feature] general: derived[Classifier] inheritedMember: derivedunion[NamedElement] componentRealization: relation_many[ComponentRealization] # type: ignore[assignment] class Association(Classifier, Relationship): isDerived: attribute[int] memberEnd: relation_many[Property] ownedEnd: relation_many[Property] navigableOwnedEnd: relation_many[Property] endType: derived[Type] class Extension(Association): isRequired: attribute[int] ownedEnd: relation_one[ExtensionEnd] # type: ignore[assignment] metaclass: property class BehavioredClassifier(Classifier): ownedBehavior: relation_many[Behavior] interfaceRealization: relation_many[InterfaceRealization] # type: ignore[assignment] class Actor(BehavioredClassifier): pass class ActivityNode(RedefinableElement): outgoing: relation_many[ActivityEdge] incoming: relation_many[ActivityEdge] inGroup: relation_many[ActivityGroup] inPartition: relation_many[ActivityPartition] activity: relation_one[Activity] redefinedElement: relation_many[ActivityNode] # type: ignore[assignment] class ControlNode(ActivityNode): pass class MergeNode(ControlNode): pass class Feature(RedefinableElement): isStatic: attribute[int] featuringClassifier: relation_many[Classifier] class ActivityEdge(RedefinableElement): activity: relation_one[Activity] guard: attribute[str] source: relation_one[ActivityNode] target: relation_one[ActivityNode] inGroup: relation_many[ActivityGroup] redefinedElement: relation_many[ActivityEdge] # type: ignore[assignment] class ObjectFlow(ActivityEdge): pass class FinalNode(ControlNode): pass class ActivityFinalNode(FinalNode): pass class CommunicationPath(Association): pass class Dependency(DirectedRelationship, PackageableElement): client: relation_one[NamedElement] supplier: relation_one[NamedElement] class Abstraction(Dependency): mapping: attribute[str] class Realization(Abstraction): pass class TypedElement(NamedElement): type: relation_one[Type] typeValue: attribute[str] class ObjectNode(TypedElement, ActivityNode): ordering: enumeration isControlType: attribute[int] upperBound: attribute[str] selection: relation_one[Behavior] class MultiplicityElement(Element): isUnique: attribute[int] isOrdered: attribute[int] upperValue: attribute[str] lowerValue: attribute[str] lower: attribute[str] upper: attribute[str] class Pin(ObjectNode, MultiplicityElement): isControl: attribute[int] class Generalization(DirectedRelationship): isSubstitutable: attribute[int] general: relation_one[Classifier] specific: relation_one[Classifier] class StructuredClassifier(Classifier): ownedConnector: relation_many[Connector] ownedAttribute: relation_many[Property] role: relation_many[ConnectableElement] part: property class EncapsulatedClassifer(StructuredClassifier): ownedPort: relation_many[Port] class Class(EncapsulatedClassifer, BehavioredClassifier): isActive: attribute[int] ownedOperation: relation_many[Operation] ownedAttribute: relation_many[Property] nestedClassifier: relation_many[Classifier] extension: property superClass: derived[Classifier] class Node(Class, DeploymentTarget, DeployedArtifact): nestedNode: relation_many[Node] class Device(Node): pass class StructuralFeature(MultiplicityElement, TypedElement, Feature): isReadOnly: attribute[int] slot: relation_many[Slot] class UseCase(BehavioredClassifier): subject: relation_many[Classifier] extensionPoint: relation_many[ExtensionPoint] include: relation_many[Include] extend: relation_many[Extend] class InputPin(Pin): pass class Manifestation(Abstraction): artifact: relation_one[Artifact] class Component(Class): isIndirectlyInstantiated: attribute[int] packagedElement: relation_many[PackageableElement] required: property provided: property realization: relation_many[ComponentRealization] # type: ignore[assignment] class ConnectableElement(TypedElement): end: relation_many[ConnectorEnd] class Interface(Classifier, ConnectableElement): ownedAttribute: relation_many[Property] redefinedInterface: relation_many[Interface] nestedClassifier: relation_many[Classifier] ownedOperation: relation_many[Operation] class Include(DirectedRelationship, NamedElement): addition: relation_one[UseCase] includingCase: relation_one[UseCase] class ProfileApplication(DirectedRelationship): appliedProfile: relation_one[Profile] class ExtensionPoint(RedefinableElement): useCase: relation_one[UseCase] class Usage(Dependency): pass class ElementImport(DirectedRelationship): visibility: enumeration alias: attribute[str] importingNamespace: relation_one[Namespace] importedElement: relation_one[PackageableElement] class Property(StructuralFeature, ConnectableElement): aggregation: enumeration isDerivedUnion: attribute[int] isDerived: attribute[int] isReadOnly: attribute[int] datatype: relation_one[DataType] subsettedProperty: relation_many[Property] classifier: relation_one[Classifier] redefinedProperty: relation_many[Property] class_: relation_one[Class] defaultValue: attribute[str] association: relation_one[Association] interface_: relation_one[Interface] owningAssociation: relation_one[Association] artifact: relation_one[Artifact] isComposite: derived[bool] navigability: derived[bool | None] opposite: relation_one[Property | None] class ExtensionEnd(Property): type: relation_one[Stereotype] # type: ignore[assignment] class DataType(Classifier): ownedAttribute: relation_many[Property] ownedOperation: relation_many[Operation] class Enumeration(DataType): ownedLiteral: relation_many[EnumerationLiteral] class Slot(Element): value: attribute[str] owningInstance: relation_one[InstanceSpecification] definingFeature: relation_one[StructuralFeature] class ExecutableNode(ActivityNode): pass class InitialNode(ControlNode): pass class Stereotype(Class): icon: relation_many[Image] profile: relation_one[Profile] # 17: override Diagram from gaphor.core.modeling import Diagram, StyleSheet class Artifact(Classifier, DeployedArtifact): manifestation: relation_many[Manifestation] nestedArtifact: relation_many[Artifact] artifact: relation_one[Artifact] ownedAttribute: relation_many[Property] ownedOperation: relation_many[Operation] class ActivityParameterNode(ObjectNode): parameter: relation_one[Parameter] class PrimitiveType(DataType): pass class DecisionNode(ControlNode): decisionInput: relation_one[Behavior] class Package(Namespace, PackageableElement): nestedPackage: relation_many[Package] package: relation_one[Package] ownedType: relation_many[Type] packageMerge: relation_many[PackageMerge] appliedProfile: relation_many[ProfileApplication] packagedElement: relation_many[PackageableElement] class Profile(Package): metamodelReference: relation_many[PackageImport] metaclassReference: relation_many[ElementImport] class Behavior(Class): isReentrant: attribute[int] redefinedBehavior: relation_many[Behavior] context2: relation_one[BehavioredClassifier] class Activity(Behavior): body: attribute[str] language: attribute[str] edge: relation_many[ActivityEdge] group: relation_many[ActivityGroup] node: relation_many[ActivityNode] class InterfaceRealization(Realization): contract: relation_many[Interface] # type: ignore[assignment] implementatingClassifier: relation_one[BehavioredClassifier] # type: ignore[assignment] class Parameter(ConnectableElement, MultiplicityElement): direction: enumeration defaultValue: attribute[str] ownerFormalParam: relation_one[BehavioralFeature] parameterSet: relation_many[ParameterSet] operation: relation_one[Operation] # type: ignore[assignment] class BehavioralFeature(Feature, Namespace): isAbstract: attribute[int] method: relation_many[Behavior] ownedParameter: relation_many[Parameter] raisedException: relation_many[Type] ownedParameterSet: relation_many[ParameterSet] class Operation(BehavioralFeature): isQuery: attribute[int] precondition: relation_many[Constraint] bodyCondition: relation_one[Constraint] redefinedOperation: relation_many[Operation] class_: relation_one[Class] datatype: relation_one[DataType] postcondition: relation_many[Constraint] interface_: relation_one[Interface] raisedException: relation_many[Type] artifact: relation_one[Artifact] type: derivedunion[DataType] ownedParameter: relation_many[Parameter] # type: ignore[assignment] class ControlFlow(ActivityEdge): pass class OutputPin(Pin): pass class ValuePin(InputPin): value_: attribute[str] class Action(ExecutableNode): effect: attribute[str] interaction: relation_one[Interaction] output: relation_many[OutputPin] context_: relation_one[Classifier] input: relation_many[InputPin] class ExecutionEnvironment(Node): pass class Extend(DirectedRelationship, NamedElement): extendedCase: relation_one[UseCase] extensionLocation: relation_many[ExtensionPoint] extension: relation_one[UseCase] constraint: relation_one[Constraint] class ActivityGroup(NamedElement): activity: relation_one[Activity] edgeContents: relation_many[ActivityEdge] nodeContents: relation_many[ActivityNode] superGroup: relation_one[ActivityGroup] subgroup: relation_many[ActivityGroup] class Constraint(PackageableElement): constrainedElement: relation_many[Element] specification: attribute[str] stateInvariant: relation_one[StateInvariant] owningState: relation_one[State] transition: relation_one[Transition] parameterSet: relation_one[ParameterSet] class PackageImport(DirectedRelationship): visibility: enumeration importedPackage: relation_one[Package] importingNamespace: relation_one[Namespace] class InteractionFragment(NamedElement): enclosingInteraction: relation_one[Interaction] covered: relation_one[Lifeline] generalOrdering: relation_many[GeneralOrdering] class Interaction(Behavior, InteractionFragment): fragment: relation_many[InteractionFragment] lifeline: relation_many[Lifeline] message: relation_many[Message] action: relation_many[Action] class StateInvariant(InteractionFragment): invariant: relation_one[Constraint] covered: relation_one[Lifeline] # type: ignore[assignment] class Lifeline(NamedElement): coveredBy: relation_many[InteractionFragment] interaction: relation_one[Interaction] parse: Callable[[Lifeline, str], None] render: Callable[[Lifeline], str] class Message(NamedElement): messageKind: property messageSort: enumeration argument: attribute[str] sendEvent: relation_one[MessageEnd] receiveEvent: relation_one[MessageEnd] interaction: relation_one[Interaction] signature: relation_one[NamedElement] messageEnd: relation_many[MessageEnd] class MessageEnd(NamedElement): sendMessage: relation_one[Message] receiveMessage: relation_one[Message] message: relation_one[Message] class OccurrenceSpecification(InteractionFragment): covered: relation_one[Lifeline] # type: ignore[assignment] class GeneralOrdering(NamedElement): interactionFragment: relation_one[InteractionFragment] class Connector(Feature): kind: enumeration structuredClassifier: relation_one[StructuredClassifier] redefinedConnector: relation_many[Connector] end: relation_many[ConnectorEnd] type: relation_one[Association] contract: relation_many[Behavior] class ConnectorEnd(MultiplicityElement): partWithPort: relation_one[Property] role: relation_one[ConnectableElement] definingEnd: relation_one[Property] class FlowFinalNode(FinalNode): pass class JoinNode(ControlNode): isCombineDuplicate: attribute[int] joinSpec: attribute[str] class ForkNode(ControlNode): pass class StateMachine(Behavior): region: relation_many[Region] class Region(Namespace): stateMachine: relation_one[StateMachine] subvertex: relation_many[Vertex] state: relation_one[State] # 20: override Transition # Invert order of superclasses to avoid MRO issues class Transition(RedefinableElement, NamedElement): kind: enumeration container: relation_one[Region] source: relation_one[Vertex] target: relation_one[Vertex] effect: relation_one[Behavior] guard: relation_one[Constraint] redefinitionContext: relation_many[Classifier] redefinedTransition: relation_many[Transition] class Vertex(NamedElement): container: relation_one[Region] outgoing: relation_many[Transition] incoming: relation_many[Transition] class Pseudostate(Vertex): kind: enumeration stateMachine: relation_one[StateMachine] state: relation_one[State] class ConnectionPointReference(Vertex): entry: relation_many[Pseudostate] exit: relation_many[Pseudostate] state: relation_one[State] class State(Vertex, Namespace): entry: relation_one[Behavior] exit: relation_one[Behavior] doActivity: relation_one[Behavior] statevariant: relation_one[Constraint] submachine: relation_one[StateMachine] class FinalState(State): pass class Port(Property): isBehavior: attribute[int] isService: attribute[int] encapsulatedClassifier: relation_one[EncapsulatedClassifer] class Deployment(Dependency): location: relation_one[DeploymentTarget] deployedArtifact: relation_many[DeployedArtifact] class ActivityPartition(ActivityGroup): isDimension: attribute[int] isExternal: attribute[int] node: relation_many[ActivityNode] represents: relation_one[Element] subpartition: relation_many[ActivityPartition] class MessageOccurrenceSpecification(MessageEnd, OccurrenceSpecification): pass class AcceptEventAction(Action): isUnmarshall: attribute[int] result: relation_many[OutputPin] class ReplyAction(Action): replyValue: relation_one[InputPin] returnInformation: relation_one[InputPin] class UnmarshallAction(Action): result: relation_many[OutputPin] unmarshallType: relation_one[Classifier] object: relation_one[InputPin] class AcceptCallAction(AcceptEventAction): returnInformation: relation_one[OutputPin] class InvocationAction(Action): pass class SendSignalAction(InvocationAction): target: relation_many[InputPin] class Collaboration(StructuredClassifier, BehavioredClassifier): collaborationRole: relation_many[ConnectableElement] class Trigger(NamedElement): event: relation_one[Event] port: relation_many[Port] class Event(PackageableElement): pass class ExecutionSpecification(InteractionFragment): executionOccurrenceSpecification: relation_many[ExecutionOccurrenceSpecification] start: relation_one[ExecutionOccurrenceSpecification] finish: relation_one[ExecutionOccurrenceSpecification] class ExecutionOccurrenceSpecification(OccurrenceSpecification): execution: relation_one[ExecutionSpecification] class ActionExecutionSpecification(ExecutionSpecification): action: relation_one[Action] class BehaviorExecutionSpecification(ExecutionSpecification): behavior: relation_one[Behavior] class ChangeEvent(Event): changeExpression: attribute[str] class StructuralFeatureAction(Action): pass class WriteStructuralFeatureAction(StructuralFeatureAction): pass class AddStructuralFeatureValueAction(WriteStructuralFeatureAction): isReplaceAll: attribute[int] class ParameterSet(NamedElement): parameter: relation_many[Parameter] condition: relation_many[Constraint] behavioralFeature: relation_one[BehavioralFeature] class Image(Element): content: attribute[str] format: attribute[str] class ComponentRealization(Realization): realizingClassifier: relation_one[Classifier] # type: ignore[assignment] abstraction: relation_one[Component] # type: ignore[assignment] class InformationItem(Classifier): represented: relation_many[Classifier] class InformationFlow(PackageableElement, DirectedRelationship): conveyed: relation_many[Classifier] realization: relation_many[Relationship] realizingMessage: relation_many[Message] realizingActivityEdge: relation_many[ActivityEdge] realizingConnector: relation_many[Connector] informationTarget: relation_many[NamedElement] informationSource: relation_many[NamedElement] # class 'Expression' has been stereotyped as 'SimpleAttribute' # class 'OpaqueExpression' has been stereotyped as 'SimpleAttribute' # class 'ValueSpecification' has been stereotyped as 'SimpleAttribute' # class 'Expression' has been stereotyped as 'SimpleAttribute' too # class 'LiteralSpecification' has been stereotyped as 'SimpleAttribute' too # class 'LiteralUnlimitedNatural' has been stereotyped as 'SimpleAttribute' too # class 'LiteralBoolean' has been stereotyped as 'SimpleAttribute' too # class 'LiteralInteger' has been stereotyped as 'SimpleAttribute' too # class 'LiteralString' has been stereotyped as 'SimpleAttribute' too # class 'LiteralNull' has been stereotyped as 'SimpleAttribute' too # class 'OpaqueExpression' has been stereotyped as 'SimpleAttribute' too Extension.isRequired = attribute("isRequired", int) Feature.isStatic = attribute("isStatic", int, default=False) RedefinableElement.isLeaf = attribute("isLeaf", int, default=True) RedefinableElement.visibility = enumeration( "visibility", ("public", "private", "package", "protected"), "public" ) Pin.isControl = attribute("isControl", int, default=False) Generalization.isSubstitutable = attribute("isSubstitutable", int) ObjectNode.ordering = enumeration( "ordering", ("unordered", "ordered", "LIFO", "FIFO"), "FIFO" ) ObjectNode.isControlType = attribute("isControlType", int, default=False) StructuralFeature.isReadOnly = attribute("isReadOnly", int, default=False) NamedElement.name = attribute("name", str) NamedElement.visibility = enumeration( "visibility", ("public", "private", "package", "protected"), "public" ) Component.isIndirectlyInstantiated = attribute( "isIndirectlyInstantiated", int, default=True ) Association.isDerived = attribute("isDerived", int, default=False) ElementImport.visibility = enumeration( "visibility", ("public", "private", "package", "protected"), "public" ) ElementImport.alias = attribute("alias", str) MultiplicityElement.isUnique = attribute("isUnique", int, default=True) MultiplicityElement.isOrdered = attribute("isOrdered", int, default=True) Activity.body = attribute("body", str) Activity.language = attribute("language", str) Classifier.isAbstract = attribute("isAbstract", int, default=False) Class.isActive = attribute("isActive", int, default=False) Parameter.direction = enumeration("direction", ("inout", "in", "out", "return"), "in") Operation.isQuery = attribute("isQuery", int, default=False) Property.aggregation = enumeration( "aggregation", ("none", "shared", "composite"), "none" ) Property.isDerivedUnion = attribute("isDerivedUnion", int, default=False) Property.isDerived = attribute("isDerived", int, default=False) Property.isReadOnly = attribute("isReadOnly", int, default=False) Behavior.isReentrant = attribute("isReentrant", int) BehavioralFeature.isAbstract = attribute("isAbstract", int) Action.effect = attribute("effect", str) PackageImport.visibility = enumeration( "visibility", ("public", "private", "package", "protected"), "public" ) # 117: override Message.messageKind: property # defined in umloverrides.py Message.messageSort = enumeration( "messageSort", ( "synchCall", "asynchCall", "asynchSignal", "createMessage", "deleteMessage", "reply", ), "synchCall", ) Connector.kind = enumeration("kind", ("assembly", "delegation"), "assembly") JoinNode.isCombineDuplicate = attribute("isCombineDuplicate", int, default=True) Transition.kind = enumeration("kind", ("internal", "local", "external"), "internal") Pseudostate.kind = enumeration( "kind", ( "initial", "deepHistory", "shallowHistory", "join", "fork", "junction", "choice", "entryPoint", "exitPoint", "terminate", ), "initial", ) Port.isBehavior = attribute("isBehavior", int) Port.isService = attribute("isService", int) ActivityPartition.isDimension = attribute("isDimension", int, default=False) ActivityPartition.isExternal = attribute("isExternal", int, default=False) AcceptEventAction.isUnmarshall = attribute("isUnmarshall", int, default=False) AddStructuralFeatureValueAction.isReplaceAll = attribute( "isReplaceAll", int, default=False ) Image.content = attribute("content", str) Image.format = attribute("format", str) Operation.precondition = association("precondition", Constraint, composite=True) Element.ownedDiagram = association( "ownedDiagram", Diagram, composite=True, opposite="element" ) Diagram.element = association("element", Element, upper=1, opposite="ownedDiagram") Package.nestedPackage = association( "nestedPackage", Package, composite=True, opposite="package" ) Package.package = association("package", Package, upper=1, opposite="nestedPackage") NamedElement.clientDependency = association( "clientDependency", Dependency, composite=True, opposite="client" ) Dependency.client = association( "client", NamedElement, upper=1, opposite="clientDependency" ) DecisionNode.decisionInput = association("decisionInput", Behavior, upper=1) Activity.edge = association("edge", ActivityEdge, composite=True, opposite="activity") ActivityEdge.activity = association("activity", Activity, upper=1, opposite="edge") Operation.bodyCondition = association( "bodyCondition", Constraint, upper=1, composite=True ) # 'InstanceSpecification.specification' is a simple attribute InstanceSpecification.specification = attribute("specification", str) BehavioralFeature.method = association("method", Behavior) Property.datatype = association( "datatype", DataType, upper=1, opposite="ownedAttribute" ) DataType.ownedAttribute = association( "ownedAttribute", Property, composite=True, opposite="datatype" ) TypedElement.type = association("type", Type, upper=1) ActivityParameterNode.parameter = association("parameter", Parameter, lower=1, upper=1) Dependency.supplier = association( "supplier", NamedElement, upper=1, opposite="supplierDependency" ) NamedElement.supplierDependency = association( "supplierDependency", Dependency, opposite="supplier" ) Operation.redefinedOperation = association("redefinedOperation", Operation) Activity.group = association( "group", ActivityGroup, composite=True, opposite="activity" ) ActivityGroup.activity = association("activity", Activity, upper=1, opposite="group") Package.ownedType = association("ownedType", Type, composite=True, opposite="package") Type.package = association("package", Package, upper=1, opposite="ownedType") Property.subsettedProperty = association("subsettedProperty", Property) Property.classifier = association( "classifier", Classifier, upper=1, opposite="attribute" ) Profile.metamodelReference = association( "metamodelReference", PackageImport, composite=True ) # 'ActivityEdge.guard' is a simple attribute ActivityEdge.guard = attribute("guard", str) Class.ownedOperation = association( "ownedOperation", Operation, composite=True, opposite="class_" ) Operation.class_ = association("class_", Class, upper=1, opposite="ownedOperation") Enumeration.ownedLiteral = association( "ownedLiteral", EnumerationLiteral, composite=True, opposite="enumeration" ) EnumerationLiteral.enumeration = association( "enumeration", Enumeration, upper=1, opposite="ownedLiteral" ) ActivityEdge.source = association( "source", ActivityNode, lower=1, upper=1, opposite="outgoing" ) ActivityNode.outgoing = association("outgoing", ActivityEdge, opposite="source") Property.redefinedProperty = association("redefinedProperty", Property) DataType.ownedOperation = association( "ownedOperation", Operation, composite=True, opposite="datatype" ) Operation.datatype = association( "datatype", DataType, upper=1, opposite="ownedOperation" ) Generalization.general = association("general", Classifier, lower=1, upper=1) Classifier.ownedUseCase = association("ownedUseCase", UseCase, composite=True) # 'MultiplicityElement.upperValue' is a simple attribute MultiplicityElement.upperValue = attribute("upperValue", str) PackageMerge.mergingPackage = association( "mergingPackage", Package, lower=1, upper=1, opposite="packageMerge" ) Package.packageMerge = association( "packageMerge", PackageMerge, composite=True, opposite="mergingPackage" ) Package.appliedProfile = association( "appliedProfile", ProfileApplication, composite=True ) # 'Parameter.defaultValue' is a simple attribute Parameter.defaultValue = attribute("defaultValue", str) # 'Slot.value' is a simple attribute Slot.value = attribute("value", str) Include.addition = association("addition", UseCase, lower=1, upper=1) # 'TypedElement.typeValue' is a simple attribute TypedElement.typeValue = attribute("typeValue", str) Constraint.constrainedElement = association("constrainedElement", Element) PackageMerge.mergedPackage = association("mergedPackage", Package, lower=1, upper=1) BehavioralFeature.ownedParameter = association( "ownedParameter", Parameter, composite=True, opposite="ownerFormalParam" ) Parameter.ownerFormalParam = association( "ownerFormalParam", BehavioralFeature, upper=1, opposite="ownedParameter" ) Class.ownedAttribute = association( "ownedAttribute", Property, composite=True, opposite="class_" ) Property.class_ = association("class_", Class, upper=1, opposite="ownedAttribute") Extend.extendedCase = association("extendedCase", UseCase, lower=1, upper=1) # 'Property.defaultValue' is a simple attribute Property.defaultValue = attribute("defaultValue", str) Property.association = association( "association", Association, upper=1, opposite="memberEnd" ) Association.memberEnd = association( "memberEnd", Property, lower=2, composite=True, opposite="association" ) Classifier.generalization = association( "generalization", Generalization, composite=True, opposite="specific" ) Generalization.specific = association( "specific", Classifier, lower=1, upper=1, opposite="generalization" ) # 'ValuePin.value_' is a simple attribute ValuePin.value_ = attribute("value_", str) BehavioralFeature.raisedException = association("raisedException", Type) # 'Abstraction.mapping' is a simple attribute Abstraction.mapping = attribute("mapping", str) ActivityNode.incoming = association("incoming", ActivityEdge, opposite="target") ActivityEdge.target = association( "target", ActivityNode, lower=1, upper=1, opposite="incoming" ) Extend.extensionLocation = association("extensionLocation", ExtensionPoint, lower=1) Property.interface_ = association( "interface_", Interface, upper=1, opposite="ownedAttribute" ) Interface.ownedAttribute = association( "ownedAttribute", Property, composite=True, opposite="interface_" ) ActivityGroup.edgeContents = association( "edgeContents", ActivityEdge, opposite="inGroup" ) ActivityEdge.inGroup = association("inGroup", ActivityGroup, opposite="edgeContents") Slot.owningInstance = association( "owningInstance", InstanceSpecification, lower=1, upper=1, opposite="slot" ) InstanceSpecification.slot = association( "slot", Slot, composite=True, opposite="owningInstance" ) UseCase.subject = association("subject", Classifier, opposite="useCase") Classifier.useCase = association("useCase", UseCase, opposite="subject") Property.owningAssociation = association( "owningAssociation", Association, upper=1, opposite="ownedEnd" ) Association.ownedEnd = association( "ownedEnd", Property, composite=True, opposite="owningAssociation" ) Interface.redefinedInterface = association("redefinedInterface", Interface) Artifact.manifestation = association( "manifestation", Manifestation, composite=True, opposite="artifact" ) Manifestation.artifact = association( "artifact", Artifact, lower=1, upper=1, opposite="manifestation" ) ExtensionPoint.useCase = association( "useCase", UseCase, lower=1, upper=1, opposite="extensionPoint" ) UseCase.extensionPoint = association( "extensionPoint", ExtensionPoint, composite=True, opposite="useCase" ) Operation.postcondition = association("postcondition", Constraint, composite=True) Extension.ownedEnd = association( "ownedEnd", ExtensionEnd, lower=1, upper=1, composite=True ) # 'Constraint.specification' is a simple attribute Constraint.specification = attribute("specification", str) Profile.metaclassReference = association( "metaclassReference", ElementImport, composite=True ) Namespace.elementImport = association( "elementImport", ElementImport, composite=True, opposite="importingNamespace" ) ElementImport.importingNamespace = association( "importingNamespace", Namespace, upper=1, opposite="elementImport" ) # 'MultiplicityElement.lowerValue' is a simple attribute MultiplicityElement.lowerValue = attribute("lowerValue", str) Interface.nestedClassifier = association("nestedClassifier", Classifier, composite=True) InstanceSpecification.classifier = association("classifier", Classifier) Interface.ownedOperation = association( "ownedOperation", Operation, composite=True, opposite="interface_" ) Operation.interface_ = association( "interface_", Interface, upper=1, opposite="ownedOperation" ) ElementImport.importedElement = association( "importedElement", PackageableElement, lower=1, upper=1 ) Classifier.redefinedClassifier = association("redefinedClassifier", Classifier) Operation.raisedException = association("raisedException", Type) PackageImport.importedPackage = association( "importedPackage", Package, lower=1, upper=1 ) StructuralFeature.slot = association( "slot", Slot, composite=True, opposite="definingFeature" ) Slot.definingFeature = association( "definingFeature", StructuralFeature, lower=1, upper=1, opposite="slot" ) Include.includingCase = association( "includingCase", UseCase, lower=1, upper=1, opposite="include" ) UseCase.include = association( "include", Include, composite=True, opposite="includingCase" ) Extend.extension = association( "extension", UseCase, lower=1, upper=1, opposite="extend" ) UseCase.extend = association("extend", Extend, composite=True, opposite="extension") Extend.constraint = association("constraint", Constraint, upper=1, composite=True) ProfileApplication.appliedProfile = association( "appliedProfile", Profile, lower=1, upper=1 ) Namespace.packageImport = association( "packageImport", PackageImport, composite=True, opposite="importingNamespace" ) PackageImport.importingNamespace = association( "importingNamespace", Namespace, upper=1, opposite="packageImport" ) Behavior.redefinedBehavior = association("redefinedBehavior", Behavior) Component.packagedElement = association( "packagedElement", PackageableElement, composite=True, opposite="component" ) PackageableElement.component = association( "component", Component, upper=1, opposite="packagedElement" ) Behavior.context2 = association( "context2", BehavioredClassifier, upper=1, opposite="ownedBehavior" ) BehavioredClassifier.ownedBehavior = association( "ownedBehavior", Behavior, composite=True, opposite="context2" ) ActivityGroup.nodeContents = association( "nodeContents", ActivityNode, opposite="inGroup" ) ActivityNode.inGroup = association("inGroup", ActivityGroup, opposite="nodeContents") InteractionFragment.enclosingInteraction = association( "enclosingInteraction", Interaction, upper=1, opposite="fragment" ) Interaction.fragment = association( "fragment", InteractionFragment, opposite="enclosingInteraction" ) Constraint.stateInvariant = association( "stateInvariant", StateInvariant, upper=1, opposite="invariant" ) StateInvariant.invariant = association( "invariant", Constraint, lower=1, upper=1, composite=True, opposite="stateInvariant" ) Lifeline.coveredBy = association("coveredBy", InteractionFragment, opposite="covered") InteractionFragment.covered = association( "covered", Lifeline, lower=1, upper=1, opposite="coveredBy" ) Lifeline.interaction = association( "interaction", Interaction, lower=1, upper=1, opposite="lifeline" ) Interaction.lifeline = association( "lifeline", Lifeline, composite=True, opposite="interaction" ) # 'Message.argument' is a simple attribute Message.argument = attribute("argument", str) MessageEnd.sendMessage = association( "sendMessage", Message, upper=1, opposite="sendEvent" ) Message.sendEvent = association( "sendEvent", MessageEnd, upper=1, composite=True, opposite="sendMessage" ) MessageEnd.receiveMessage = association( "receiveMessage", Message, upper=1, opposite="receiveEvent" ) Message.receiveEvent = association( "receiveEvent", MessageEnd, upper=1, composite=True, opposite="receiveMessage" ) Message.interaction = association( "interaction", Interaction, lower=1, upper=1, opposite="message" ) Interaction.message = association( "message", Message, composite=True, opposite="interaction" ) StructuredClassifier.ownedConnector = association( "ownedConnector", Connector, composite=True, opposite="structuredClassifier" ) Connector.structuredClassifier = association( "structuredClassifier", StructuredClassifier, upper=1, opposite="ownedConnector" ) Connector.redefinedConnector = association("redefinedConnector", Connector) StructuredClassifier.ownedAttribute = association( "ownedAttribute", Property, composite=True ) # 'ObjectNode.upperBound' is a simple attribute ObjectNode.upperBound = attribute("upperBound", str) ObjectNode.selection = association("selection", Behavior, upper=1) # 'JoinNode.joinSpec' is a simple attribute JoinNode.joinSpec = attribute("joinSpec", str) StateMachine.region = association( "region", Region, lower=1, composite=True, opposite="stateMachine" ) Region.stateMachine = association( "stateMachine", StateMachine, upper=1, opposite="region" ) Transition.container = association("container", Region, lower=1, upper=1) Region.subvertex = association( "subvertex", Vertex, composite=True, opposite="container" ) Vertex.container = association("container", Region, upper=1, opposite="subvertex") Transition.source = association("source", Vertex, lower=1, upper=1, opposite="outgoing") Vertex.outgoing = association("outgoing", Transition, opposite="source") Transition.target = association("target", Vertex, lower=1, upper=1, opposite="incoming") Vertex.incoming = association("incoming", Transition, opposite="target") ConnectionPointReference.entry = association("entry", Pseudostate) ConnectionPointReference.exit = association("exit", Pseudostate) Pseudostate.stateMachine = association("stateMachine", StateMachine, upper=1) Region.state = association("state", State, upper=1) Pseudostate.state = association("state", State, upper=1) ConnectionPointReference.state = association("state", State, upper=1) State.entry = association("entry", Behavior, upper=1, composite=True) State.exit = association("exit", Behavior, upper=1, composite=True) State.doActivity = association("doActivity", Behavior, upper=1, composite=True) Transition.effect = association("effect", Behavior, upper=1, composite=True) State.statevariant = association( "statevariant", Constraint, upper=1, composite=True, opposite="owningState" ) Constraint.owningState = association( "owningState", State, upper=1, opposite="statevariant" ) Transition.guard = association( "guard", Constraint, upper=1, composite=True, opposite="transition" ) Constraint.transition = association("transition", Transition, upper=1, opposite="guard") State.submachine = association("submachine", StateMachine, upper=1) ConnectorEnd.partWithPort = association("partWithPort", Property, upper=1) Port.encapsulatedClassifier = association( "encapsulatedClassifier", EncapsulatedClassifer, upper=1, opposite="ownedPort" ) EncapsulatedClassifer.ownedPort = association( "ownedPort", Port, composite=True, opposite="encapsulatedClassifier" ) Element.appliedStereotype = association( "appliedStereotype", InstanceSpecification, opposite="extended" ) InstanceSpecification.extended = association( "extended", Element, opposite="appliedStereotype" ) Node.nestedNode = association("nestedNode", Node, composite=True) Deployment.location = association( "location", DeploymentTarget, lower=1, upper=1, opposite="deployment" ) DeploymentTarget.deployment = association( "deployment", Deployment, composite=True, opposite="location" ) Deployment.deployedArtifact = association("deployedArtifact", DeployedArtifact) ActivityNode.inPartition = association( "inPartition", ActivityPartition, opposite="node" ) ActivityPartition.node = association("node", ActivityNode, opposite="inPartition") ActivityPartition.represents = association("represents", Element, upper=1) ActivityPartition.subpartition = association("subpartition", ActivityPartition) Association.navigableOwnedEnd = association("navigableOwnedEnd", Property) AcceptEventAction.result = association("result", OutputPin, composite=True) UnmarshallAction.result = association("result", OutputPin, composite=True) AcceptCallAction.returnInformation = association( "returnInformation", OutputPin, lower=1, upper=1, composite=True ) UnmarshallAction.unmarshallType = association( "unmarshallType", Classifier, lower=1, upper=1 ) UnmarshallAction.object = association( "object", InputPin, lower=1, upper=1, composite=True ) ReplyAction.replyValue = association("replyValue", InputPin, upper=1, composite=True) ReplyAction.returnInformation = association( "returnInformation", InputPin, lower=1, upper=1, composite=True ) SendSignalAction.target = association("target", InputPin, composite=True) Collaboration.collaborationRole = association("collaborationRole", ConnectableElement) Trigger.event = association("event", Event, lower=1, upper=1) Action.interaction = association("interaction", Interaction, upper=1, opposite="action") Interaction.action = association( "action", Action, composite=True, opposite="interaction" ) Message.signature = association("signature", NamedElement, upper=1) InteractionFragment.generalOrdering = association( "generalOrdering", GeneralOrdering, composite=True, opposite="interactionFragment" ) GeneralOrdering.interactionFragment = association( "interactionFragment", InteractionFragment, upper=1, opposite="generalOrdering" ) ExecutionSpecification.executionOccurrenceSpecification = association( "executionOccurrenceSpecification", ExecutionOccurrenceSpecification, upper=2, composite=True, opposite="execution", ) ExecutionOccurrenceSpecification.execution = association( "execution", ExecutionSpecification, lower=1, upper=1, opposite="executionOccurrenceSpecification", ) ActionExecutionSpecification.action = association("action", Action, lower=1, upper=1) BehaviorExecutionSpecification.behavior = association("behavior", Behavior, upper=1) # 'ChangeEvent.changeExpression' is a simple attribute ChangeEvent.changeExpression = attribute("changeExpression", str) Parameter.parameterSet = association("parameterSet", ParameterSet, opposite="parameter") ParameterSet.parameter = association( "parameter", Parameter, lower=1, opposite="parameterSet" ) Constraint.parameterSet = association( "parameterSet", ParameterSet, upper=1, opposite="condition" ) ParameterSet.condition = association( "condition", Constraint, composite=True, opposite="parameterSet" ) ParameterSet.behavioralFeature = association( "behavioralFeature", BehavioralFeature, upper=1, opposite="ownedParameterSet" ) BehavioralFeature.ownedParameterSet = association( "ownedParameterSet", ParameterSet, composite=True, opposite="behavioralFeature" ) Connector.end = association("end", ConnectorEnd, lower=2, composite=True) ConnectorEnd.role = association("role", ConnectableElement, upper=1, opposite="end") ConnectableElement.end = association("end", ConnectorEnd, opposite="role") Connector.type = association("type", Association, upper=1) Connector.contract = association("contract", Behavior) Classifier.nestingClass = association( "nestingClass", Class, upper=1, opposite="nestedClassifier" ) Class.nestedClassifier = association( "nestedClassifier", Classifier, composite=True, opposite="nestingClass" ) Stereotype.icon = association("icon", Image, composite=True) Namespace.ownedRule = association("ownedRule", Constraint, composite=True) Trigger.port = association("port", Port) ActivityNode.activity = association("activity", Activity, upper=1, opposite="node") Activity.node = association("node", ActivityNode, composite=True, opposite="activity") Artifact.nestedArtifact = association( "nestedArtifact", Artifact, composite=True, opposite="artifact" ) Artifact.artifact = association( "artifact", Artifact, upper=1, opposite="nestedArtifact" ) Property.artifact = association( "artifact", Artifact, upper=1, opposite="ownedAttribute" ) Artifact.ownedAttribute = association( "ownedAttribute", Property, composite=True, opposite="artifact" ) Operation.artifact = association( "artifact", Artifact, upper=1, opposite="ownedOperation" ) Artifact.ownedOperation = association( "ownedOperation", Operation, composite=True, opposite="artifact" ) InformationItem.represented = association("represented", Classifier) InformationFlow.conveyed = association("conveyed", Classifier, lower=1) InformationFlow.realization = association("realization", Relationship) InformationFlow.realizingMessage = association("realizingMessage", Message) InformationFlow.realizingActivityEdge = association( "realizingActivityEdge", ActivityEdge ) InformationFlow.realizingConnector = association("realizingConnector", Connector) NamedElement.informationFlow = association( "informationFlow", InformationFlow, opposite="informationTarget" ) InformationFlow.informationTarget = association( "informationTarget", NamedElement, lower=1, opposite="informationFlow" ) InformationFlow.informationSource = association( "informationSource", NamedElement, lower=1 ) # 82: override NamedElement.qualifiedName(NamedElement.namespace): derived[List[str]] def _namedelement_qualifiedname(self) -> list[str]: """Returns the qualified name of the element as a tuple.""" if self.namespace: return _namedelement_qualifiedname(self.namespace) + [self.name] else: return [self.name] NamedElement.qualifiedName = derived( "qualifiedName", List[str], 0, 1, lambda obj: [_namedelement_qualifiedname(obj)], ) # 32: override MultiplicityElement.lower(MultiplicityElement.lowerValue): attribute[str] MultiplicityElement.lower = MultiplicityElement.lowerValue # 35: override MultiplicityElement.upper(MultiplicityElement.upperValue): attribute[str] MultiplicityElement.upper = MultiplicityElement.upperValue # 76: override Property.isComposite(Property.aggregation): derived[bool] Property.isComposite = derived( "isComposite", bool, 0, 1, lambda obj: [obj.aggregation == "composite"] ) # 99: override Property.navigability(Property.opposite, Property.association): derived[Optional[bool]] # defined in umloverrides.py RedefinableElement.redefinedElement = derivedunion( "redefinedElement", RedefinableElement, 0, "*", Property.redefinedProperty, Classifier.redefinedClassifier, Operation.redefinedOperation, Interface.redefinedInterface, Behavior.redefinedBehavior, Connector.redefinedConnector, ) Classifier.attribute = derivedunion( "attribute", Property, 0, "*", Class.ownedAttribute, DataType.ownedAttribute, Interface.ownedAttribute, StructuredClassifier.ownedAttribute, Artifact.ownedAttribute, ) Classifier.feature = derivedunion( "feature", Feature, 0, "*", Interface.ownedOperation, DataType.ownedOperation, Class.ownedOperation, Association.ownedEnd, Classifier.attribute, StructuredClassifier.ownedConnector, Artifact.ownedOperation, ) Feature.featuringClassifier = derivedunion( "featuringClassifier", Classifier, 1, "*", Property.class_, Property.owningAssociation, Operation.class_, Operation.datatype, Operation.interface_, Operation.artifact, ) # 73: override Property.opposite(Property.association, Association.memberEnd): relation_one[Optional[Property]] # defined in umloverrides.py Action.output = derivedunion("output", OutputPin, 0, "*") RedefinableElement.redefinitionContext = derivedunion( "redefinitionContext", Classifier, 0, "*", Operation.class_, Property.classifier, Operation.datatype, Connector.structuredClassifier, Port.encapsulatedClassifier, Classifier.nestingClass, Operation.artifact, ) PackageableElement.owningPackage = derivedunion( "owningPackage", Package, 0, 1, Type.package, Package.package ) NamedElement.namespace = derivedunion( "namespace", Namespace, 0, 1, Extend.extension, ExtensionPoint.useCase, Property.interface_, Include.includingCase, Property.class_, Property.owningAssociation, Operation.class_, EnumerationLiteral.enumeration, PackageableElement.owningPackage, Operation.datatype, Property.datatype, PackageableElement.component, Operation.interface_, Parameter.ownerFormalParam, InteractionFragment.enclosingInteraction, Lifeline.interaction, Message.interaction, Connector.structuredClassifier, Region.stateMachine, Transition.container, Vertex.container, Pseudostate.stateMachine, Region.state, ConnectionPointReference.state, BehavioralFeature.ownedParameterSet, Classifier.nestingClass, Artifact.artifact, Property.artifact, Operation.artifact, ) Package.packagedElement = derivedunion( "packagedElement", PackageableElement, 0, "*", Package.ownedType, Package.nestedPackage, ) Namespace.ownedMember = derivedunion( "ownedMember", NamedElement, 0, "*", Interface.ownedOperation, Enumeration.ownedLiteral, Interface.nestedClassifier, UseCase.extensionPoint, Package.packagedElement, DataType.ownedOperation, Operation.precondition, Component.packagedElement, Class.ownedAttribute, BehavioralFeature.ownedParameter, Classifier.ownedUseCase, DataType.ownedAttribute, Class.ownedOperation, Operation.postcondition, Association.ownedEnd, Interface.ownedAttribute, UseCase.include, Operation.bodyCondition, UseCase.extend, Extend.constraint, BehavioredClassifier.ownedBehavior, Interaction.fragment, Interaction.lifeline, Interaction.message, StructuredClassifier.ownedConnector, StructuredClassifier.ownedAttribute, StateMachine.region, Region.subvertex, Node.nestedNode, ParameterSet.behavioralFeature, Class.nestedClassifier, Stereotype.icon, Namespace.ownedRule, Artifact.nestedArtifact, Artifact.ownedAttribute, Artifact.ownedOperation, ) # 64: override Classifier.general(Generalization.general): derived[Classifier] Classifier.general = derived( "general", Classifier, 0, "*", lambda self: [g.general for g in self.generalization] ) # 38: override Association.endType(Association.memberEnd, Property.type): derived[Type] # References the classifiers that are used as types of the ends of the # association. Association.endType = derived( "endType", Type, 0, "*", lambda self: [end.type for end in self.memberEnd if end] ) # 102: override Operation.type: derivedunion[DataType] Operation.type = derivedunion("type", DataType, 0, 1) Stereotype.profile = derivedunion("profile", Profile, 1, 1) # 58: override Extension.metaclass(Extension.ownedEnd, Association.memberEnd): property # defined in umloverrides.py # 46: override Class.extension(Extension.metaclass): property # See https://www.omg.org/spec/UML/2.5/PDF, section 11.8.3.6, page 219 # It defines `Extension.allInstances()`, which basically means we have to query the element factory. # TODO: use those as soon as Extension.metaclass can be used. # Class.extension = derived('extension', Extension, 0, '*', class_extension, Extension.metaclass) Class.extension = property( lambda self: self.model.lselect( lambda e: e.isKindOf(Extension) and self is e.metaclass ), doc="""References the Extensions that specify additional properties of the metaclass. The property is derived from the extensions whose memberEnds are typed by the Class.""", ) DirectedRelationship.target = derivedunion( "target", Element, 1, "*", PackageImport.importedPackage, PackageMerge.mergedPackage, Generalization.general, Include.addition, Extend.extendedCase, ElementImport.importedElement, Dependency.supplier, Dependency.client, InformationFlow.informationTarget, ) Element.directedRelationship = derivedunion( "directedRelationship", DirectedRelationship, 0, "*", NamedElement.supplierDependency, NamedElement.clientDependency, UseCase.include, Package.packageMerge, UseCase.extend, ) DirectedRelationship.source = derivedunion( "source", Element, 1, "*", Extend.extension, Include.includingCase, ElementImport.importingNamespace, Generalization.specific, PackageImport.importingNamespace, PackageMerge.mergingPackage, InformationFlow.informationSource, ) Action.context_ = derivedunion("context_", Classifier, 0, 1) Element.relationship = derivedunion( "relationship", Relationship, 0, "*", Element.directedRelationship ) Relationship.relatedElement = derivedunion( "relatedElement", Element, 1, "*", DirectedRelationship.target, DirectedRelationship.source, ) ActivityGroup.superGroup = derivedunion("superGroup", ActivityGroup, 0, 1) ActivityGroup.subgroup = derivedunion( "subgroup", ActivityGroup, 0, "*", ActivityPartition.subpartition ) # 61: override Classifier.inheritedMember: derivedunion[NamedElement] Classifier.inheritedMember = derivedunion("inheritedMember", NamedElement, 0, "*") StructuredClassifier.role = derivedunion( "role", ConnectableElement, 0, "*", StructuredClassifier.ownedAttribute, Collaboration.collaborationRole, ) Namespace.member = derivedunion( "member", NamedElement, 0, "*", Namespace.ownedMember, Association.memberEnd, Classifier.inheritedMember, StructuredClassifier.role, ) NamedElement.memberNamespace = derivedunion( "memberNamespace", Namespace, 0, "*", Property.association, NamedElement.namespace ) # 114: override Component.required: property # defined in umloverrides.py # 70: override Namespace.importedMember: derivedunion[PackageableElement] Namespace.importedMember = derivedunion("importedMember", PackageableElement, 0, "*") Action.input = derivedunion("input", InputPin, 0, "*", SendSignalAction.target) # 111: override Component.provided: property # defined in umloverrides.py Element.owner = derivedunion( "owner", Element, 0, 1, Slot.owningInstance, ElementImport.importingNamespace, Diagram.element, Generalization.specific, ActivityEdge.activity, ActivityGroup.superGroup, ActivityGroup.activity, PackageImport.importingNamespace, PackageMerge.mergingPackage, Manifestation.artifact, NamedElement.namespace, Dependency.client, Constraint.stateInvariant, Pseudostate.state, Constraint.transition, Deployment.location, Action.interaction, GeneralOrdering.interactionFragment, Constraint.parameterSet, ActivityNode.activity, ) Element.ownedElement = derivedunion( "ownedElement", Element, 0, "*", Artifact.manifestation, Element.ownedDiagram, Action.input, InstanceSpecification.slot, Classifier.generalization, Namespace.ownedMember, Namespace.elementImport, Activity.group, NamedElement.clientDependency, Namespace.packageImport, Package.packageMerge, Package.appliedProfile, ActivityGroup.subgroup, Activity.edge, Action.output, StateInvariant.invariant, State.entry, State.exit, State.doActivity, Transition.effect, State.statevariant, Transition.guard, DeploymentTarget.deployment, Interaction.action, InteractionFragment.generalOrdering, ParameterSet.condition, Connector.end, Activity.node, ) # 120: override StructuredClassifier.part: property StructuredClassifier.part = property( lambda self: tuple(a for a in self.ownedAttribute if a.isComposite), doc=""" Properties owned by a classifier by composition. """, ) # 125: override ExecutionSpecification.start(ExecutionSpecification.executionOccurrenceSpecification): relation_one[ExecutionOccurrenceSpecification] ExecutionSpecification.start = derived( "start", OccurrenceSpecification, 0, 1, lambda obj: [ eos for i, eos in enumerate(obj.executionOccurrenceSpecification) if i == 0 ], ) # 129: override ExecutionSpecification.finish(ExecutionSpecification.executionOccurrenceSpecification): relation_one[ExecutionOccurrenceSpecification] ExecutionSpecification.finish = derived( "finish", OccurrenceSpecification, 0, 1, lambda obj: [ eos for i, eos in enumerate(obj.executionOccurrenceSpecification) if i == 1 ], ) ConnectorEnd.definingEnd = derivedunion("definingEnd", Property, 0, 1) MessageEnd.message = derivedunion( "message", Message, 0, 1, MessageEnd.sendMessage, MessageEnd.receiveMessage ) Message.messageEnd = derivedunion( "messageEnd", MessageEnd, 0, 2, Message.sendEvent, Message.receiveEvent ) # 67: override Class.superClass: derived[Classifier] Class.superClass = Classifier.general ExtensionEnd.type = redefine(ExtensionEnd, "type", Stereotype, Property.type) ActivityNode.redefinedElement = redefine( ActivityNode, "redefinedElement", ActivityNode, RedefinableElement.redefinedElement ) Classifier.componentRealization = redefine( Classifier, "componentRealization", ComponentRealization, NamedElement.clientDependency, ) ComponentRealization.realizingClassifier = redefine( ComponentRealization, "realizingClassifier", Classifier, Dependency.client ) InterfaceRealization.contract = redefine( InterfaceRealization, "contract", Interface, Dependency.supplier ) BehavioredClassifier.interfaceRealization = redefine( BehavioredClassifier, "interfaceRealization", InterfaceRealization, NamedElement.clientDependency, ) InterfaceRealization.implementatingClassifier = redefine( InterfaceRealization, "implementatingClassifier", BehavioredClassifier, Dependency.client, ) ComponentRealization.abstraction = redefine( ComponentRealization, "abstraction", Component, Dependency.supplier ) Component.realization = redefine( Component, "realization", ComponentRealization, NamedElement.supplierDependency ) Parameter.operation = redefine( Parameter, "operation", Operation, Parameter.ownerFormalParam ) Operation.ownedParameter = redefine( Operation, "ownedParameter", Parameter, BehavioralFeature.ownedParameter ) ActivityEdge.redefinedElement = redefine( ActivityEdge, "redefinedElement", ActivityEdge, RedefinableElement.redefinedElement ) StateInvariant.covered = redefine( StateInvariant, "covered", Lifeline, InteractionFragment.covered ) OccurrenceSpecification.covered = redefine( OccurrenceSpecification, "covered", Lifeline, InteractionFragment.covered ) # 105: override Lifeline.parse: Callable[[Lifeline, str], None] # defined in umloverrides.py # 108: override Lifeline.render: Callable[[Lifeline], str] # defined in umloverrides.py
18,268
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.def; import org.auraframework.css.FlavorOverrideLocation; import org.auraframework.throwable.quickfix.QuickFixException; import com.google.common.collect.Table; /** * {@code <aura:include>} tags inside of {@link FlavorsDef}s. */ public interface FlavorIncludeDef extends Definition { @Override DefDescriptor<FlavorIncludeDef> getDescriptor(); /** * Gets the original source attribute. */ String getSource(); /** * Gets a mapping of which {@link FlavoredStyleDef} has the override for a component and flavor name pair. * * @throws QuickFixException If there's a problem loading the flavor def. */ Table<DefDescriptor<ComponentDef>, String, FlavorOverrideLocation> computeOverrides() throws QuickFixException; /** * @return Returns the parentDescriptor. */ DefDescriptor<? extends RootDefinition> getParentDescriptor(); }
465
817
<gh_stars>100-1000 package com.github.sd4324530.fastweixin.api.entity; import com.alibaba.fastjson.annotation.JSONField; import com.github.sd4324530.fastweixin.api.enums.MenuType; import com.github.sd4324530.fastweixin.exception.WeixinException; import java.util.List; /** * 菜单按钮对象 * * @author peiyu */ public class MenuButton extends BaseModel { /** * 菜单类别 */ private MenuType type; /** * 菜单上显示的文字 */ private String name; /** * 菜单key,当MenuType值为CLICK时用于区别菜单 */ private String key; /** * 菜单跳转的URL,当MenuType值为VIEW时用 */ private String url; /** * 菜单显示的永久素材的MaterialID,当MenuType值为media_id和view_limited时必需 */ @JSONField(name = "media_id") private String mediaId; /** * 二级菜单列表,每个一级菜单下最多5个 */ @JSONField(name = "sub_button") private List<MenuButton> subButton; public MenuType getType() { return type; } public void setType(MenuType type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMediaId() { return mediaId; } public void setMediaId(String mediaId) { this.mediaId = mediaId; } public List<MenuButton> getSubButton() { return subButton; } public void setSubButton(List<MenuButton> subButton) { if (null == subButton || subButton.size() > 5) { throw new WeixinException("子菜单最多只有5个"); } this.subButton = subButton; } }
954
362
/* Dwarf Therapist Copyright (c) 2010 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "itemweaponsubtype.h" #include "dfinstance.h" #include "memorylayout.h" ItemWeaponSubtype::ItemWeaponSubtype(DFInstance *df, VIRTADDR address, QObject *parent) : ItemSubtype(WEAPON,df,address,parent) , m_single_grasp_size(0) , m_multi_grasp_size(0) { auto mem = df->memory_layout(); //set the group name as the simple plural name (no adjective or preplural) QString plural = capitalizeEach(df->read_string(mem->item_subtype_field(address, "name_plural"))); m_group_name = plural; m_single_grasp_size = df->read_int(mem->weapon_subtype_field(address, "single_size")); //two_hand size m_multi_grasp_size = df->read_int(mem->weapon_subtype_field(address, "multi_size")); //minimum size m_melee_skill_id = df->read_short(mem->weapon_subtype_field(address, "melee_skill")); m_ranged_skill_id = df->read_short(mem->weapon_subtype_field(address, "ranged_skill")); m_ammo = df->read_string(mem->weapon_subtype_field(address, "ammo")); if(m_ammo.isEmpty()){ m_flags.set_flag(ITEM_MELEE_WEAPON,true); }else{ m_flags.set_flag(ITEM_RANGED_WEAPON,true); } } ItemWeaponSubtype::~ItemWeaponSubtype() { }
757
1,441
<reponame>lyskevin/cpbook-code from heapq import heappush, heappop # Union-Find Disjoint Sets Library written in OOP manner # using both path compression and union by rank heuristics class UnionFind: # OOP style def __init__(self, N): self.p = [i for i in range(N)] self.rank = [0 for i in range(N)] self.setSize = [1 for i in range(N)] self.numSets = N def findSet(self, i): if (self.p[i] == i): return i else: self.p[i] = self.findSet(self.p[i]) return self.p[i] def isSameSet(self, i, j): return self.findSet(i) == self.findSet(j) def unionSet(self, i, j): if (not self.isSameSet(i, j)): self.numSets -= 1 x = self.findSet(i) y = self.findSet(j) # rank is used to keep the tree short if (self.rank[x] > self.rank[y]): self.p[y] = x self.setSize[x] += self.setSize[y] else: self.p[x] = y self.setSize[y] += self.setSize[x] if (self.rank[x] == self.rank[y]): self.rank[y] += 1 def numDisjointSets(self): return self.numSets def sizeOfSet(self, i): return self.setSize[self.findSet(i)] def main(): # Graph in Figure 4.10 left, format: list of weighted edges # This example shows another form of reading graph input # 5 7 # 0 1 4 # 0 2 4 # 0 3 6 # 0 4 6 # 1 2 2 # 2 3 8 # 3 4 9 f = open("mst_in.txt", "r") V, E = map(int, f.readline().split(" ")) # Kruskal's algorithm EL = [] for i in range(E): u, v, w = map(int, f.readline().split(" ")) # read as (u, v, w) EL.append((w, u, v)) # reorder as (w, u, v) EL.sort() # sort by w, O(E log E) mst_cost = 0 num_taken = 0 UF = UnionFind(V) # all V are disjoint sets for i in range(E): # for each edge, O(E) if num_taken == V-1: break w, u, v = EL[i] if (not UF.isSameSet(u, v)): # check num_taken += 1 # 1 more edge is taken mst_cost += w # add w of this edge UF.unionSet(u, v) # link them # note: the runtime cost of UFDS is very light # note: the number of disjoint sets must eventually be 1 for a valid MST print("MST cost = {} (Kruskal's)".format(mst_cost)) main()
1,432
344
<reponame>FXyz/FXyz<filename>FXyz-Core/src/main/java/org/fxyz3d/shapes/primitives/helper/delaunay/jdt/Utils.java /* * Copyright (c) 2021, F(X)yz * Copyright (c) 2012 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package org.fxyz3d.shapes.primitives.helper.delaunay.jdt; import java.io.Closeable; import java.io.IOException; import java.io.Writer; /** * @author <NAME> https://github.com/yonatang/JDT * */ public class Utils { public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ioe) { // ignore } } public static void closeQuietly(Writer writer) { closeQuietly((Closeable) writer); } public static boolean isNumeric(CharSequence cs) { if (cs == null || cs.length() == 0) { return false; } int sz = cs.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(cs.charAt(i)) == false) { return false; } } return true; } }
657
7,482
<gh_stars>1000+ /* * Copyright (c) 2006-2021, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes */ #ifndef __PMU_H__ #define __PMU_H__ #include "board.h" /* Number of counters */ #define ARM_PMU_CNTER_NR 4 enum rt_hw_pmu_event_type { ARM_PMU_EVENT_PMNC_SW_INCR = 0x00, ARM_PMU_EVENT_L1_ICACHE_REFILL = 0x01, ARM_PMU_EVENT_ITLB_REFILL = 0x02, ARM_PMU_EVENT_L1_DCACHE_REFILL = 0x03, ARM_PMU_EVENT_L1_DCACHE_ACCESS = 0x04, ARM_PMU_EVENT_DTLB_REFILL = 0x05, ARM_PMU_EVENT_MEM_READ = 0x06, ARM_PMU_EVENT_MEM_WRITE = 0x07, ARM_PMU_EVENT_INSTR_EXECUTED = 0x08, ARM_PMU_EVENT_EXC_TAKEN = 0x09, ARM_PMU_EVENT_EXC_EXECUTED = 0x0A, ARM_PMU_EVENT_CID_WRITE = 0x0B, }; /* Enable bit */ #define ARM_PMU_PMCR_E (0x01 << 0) /* Event counter reset */ #define ARM_PMU_PMCR_P (0x01 << 1) /* Cycle counter reset */ #define ARM_PMU_PMCR_C (0x01 << 2) /* Cycle counter divider */ #define ARM_PMU_PMCR_D (0x01 << 3) #ifdef __GNUC__ rt_inline void rt_hw_pmu_enable_cnt(int divide64) { unsigned long pmcr; unsigned long pmcntenset; asm volatile ("mrc p15, 0, %0, c9, c12, 0" : "=r"(pmcr)); pmcr |= ARM_PMU_PMCR_E | ARM_PMU_PMCR_P | ARM_PMU_PMCR_C; if (divide64) pmcr |= ARM_PMU_PMCR_D; else pmcr &= ~ARM_PMU_PMCR_D; asm volatile ("mcr p15, 0, %0, c9, c12, 0" :: "r"(pmcr)); /* enable all the counters */ pmcntenset = ~0; asm volatile ("mcr p15, 0, %0, c9, c12, 1" :: "r"(pmcntenset)); /* clear overflows(just in case) */ asm volatile ("mcr p15, 0, %0, c9, c12, 3" :: "r"(pmcntenset)); } rt_inline unsigned long rt_hw_pmu_get_control(void) { unsigned long pmcr; asm ("mrc p15, 0, %0, c9, c12, 0" : "=r"(pmcr)); return pmcr; } rt_inline unsigned long rt_hw_pmu_get_ceid(void) { unsigned long reg; /* only PMCEID0 is supported, PMCEID1 is RAZ. */ asm ("mrc p15, 0, %0, c9, c12, 6" : "=r"(reg)); return reg; } rt_inline unsigned long rt_hw_pmu_get_cnten(void) { unsigned long pmcnt; asm ("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcnt)); return pmcnt; } rt_inline void rt_hw_pmu_reset_cycle(void) { unsigned long pmcr; asm volatile ("mrc p15, 0, %0, c9, c12, 0" : "=r"(pmcr)); pmcr |= ARM_PMU_PMCR_C; asm volatile ("mcr p15, 0, %0, c9, c12, 0" :: "r"(pmcr)); asm volatile ("isb"); } rt_inline void rt_hw_pmu_reset_event(void) { unsigned long pmcr; asm volatile ("mrc p15, 0, %0, c9, c12, 0" : "=r"(pmcr)); pmcr |= ARM_PMU_PMCR_P; asm volatile ("mcr p15, 0, %0, c9, c12, 0" :: "r"(pmcr)); asm volatile ("isb"); } rt_inline unsigned long rt_hw_pmu_get_cycle(void) { unsigned long cyc; asm volatile ("isb"); asm volatile ("mrc p15, 0, %0, c9, c13, 0" : "=r"(cyc)); return cyc; } rt_inline void rt_hw_pmu_select_counter(int idx) { RT_ASSERT(idx < ARM_PMU_CNTER_NR); asm volatile ("mcr p15, 0, %0, c9, c12, 5" : : "r"(idx)); /* Linux add an isb here, don't know why here. */ asm volatile ("isb"); } rt_inline void rt_hw_pmu_select_event(int idx, enum rt_hw_pmu_event_type eve) { RT_ASSERT(idx < ARM_PMU_CNTER_NR); rt_hw_pmu_select_counter(idx); asm volatile ("mcr p15, 0, %0, c9, c13, 1" : : "r"(eve)); } rt_inline unsigned long rt_hw_pmu_read_counter(int idx) { unsigned long reg; rt_hw_pmu_select_counter(idx); asm volatile ("isb"); asm volatile ("mrc p15, 0, %0, c9, c13, 2" : "=r"(reg)); return reg; } rt_inline unsigned long rt_hw_pmu_get_ovsr(void) { unsigned long reg; asm volatile ("isb"); asm ("mrc p15, 0, %0, c9, c12, 3" : "=r"(reg)); return reg; } rt_inline void rt_hw_pmu_clear_ovsr(unsigned long reg) { asm ("mcr p15, 0, %0, c9, c12, 3" : : "r"(reg)); asm volatile ("isb"); } #endif void rt_hw_pmu_dump_feature(void); #endif /* end of include guard: __PMU_H__ */
2,083
310
package org.seasar.doma.internal.jdbc.sql.node; import static org.seasar.doma.internal.util.AssertionUtil.assertNotNull; import org.seasar.doma.jdbc.JdbcUnsupportedOperationException; import org.seasar.doma.jdbc.SqlNode; public abstract class ValueNode extends AbstractSqlNode { protected final SqlLocation location; protected final String variableName; protected final String text; protected WordNode wordNode; protected ParensNode parensNode; public ValueNode(SqlLocation location, String variableName, String text) { assertNotNull(location, variableName, text); this.location = location; this.variableName = variableName; this.text = text; } public SqlLocation getLocation() { return location; } public String getVariableName() { return variableName; } public String getText() { return text; } @Override public void appendNode(SqlNode child) { throw new JdbcUnsupportedOperationException(getClass().getName(), "addNode"); } public WordNode getWordNode() { return wordNode; } public void setWordNode(WordNode wordNode) { this.wordNode = wordNode; } public ParensNode getParensNode() { return parensNode; } public void setParensNode(ParensNode parensNode) { this.parensNode = parensNode; } public boolean isWordNodeIgnored() { return wordNode != null; } public boolean isParensNodeIgnored() { return parensNode != null; } }
484
626
<gh_stars>100-1000 from condition import NeverCondition DEFAULT_THROTTLING_TICK = 16 THROTTLING_TICK_UPPER_LIMIT = 64 THROTTLING_TICK_LOWER_LIMIT = 4 # put a counter and a max_count so can't get stuck? class Task(object): def __init__(self): self.memid = None self.interrupted = False self.finished = False self.name = None self.undone = False self.last_stepped_time = None self.throttling_tick = DEFAULT_THROTTLING_TICK self.stop_condition = NeverCondition(None) def step(self, agent): # todo? make it so something stopped by condition can be resumed? if self.stop_condition.check(): self.finished = True return return def add_child_task(self, t, agent, pass_stop_condition=True): # FIXME, this is ugly and dangerous; some conditions might keep state etc? if pass_stop_condition: t.stop_condition = self.stop_condition agent.memory.task_stack_push(t, parent_memid=self.memid) def interrupt(self): self.interrupted = True def check_finished(self): if self.finished: return self.finished def hurry_up(self): self.throttling_tick /= 4 if self.throttling_tick < THROTTLING_TICK_LOWER_LIMIT: self.throttling_tick = THROTTLING_TICK_LOWER_LIMIT def slow_down(self): self.throttling_tick *= 4 if self.throttling_tick > THROTTLING_TICK_UPPER_LIMIT: self.throttling_tick = THROTTLING_TICK_UPPER_LIMIT def __repr__(self): return str(type(self))
718
1,567
/* * Tencent is pleased to support the open source community by making PaxosStore available. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * https://opensource.org/licenses/BSD-3-Clause * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <sstream> #include <vector> #include <algorithm> #include <cassert> #include "cutils/log_utils.h" #include "dbcomm/db_comm.h" #include "merge_comm.h" namespace memkv { namespace CheckMerge { bool CheckFile(const char* sKvPath) { std::vector<int> vecWriteFile; dbcomm::GatherWriteFilesFromDataPath(sKvPath, vecWriteFile); std::sort(vecWriteFile.begin(), vecWriteFile.end()); if (vecWriteFile.empty() || size_t(1) == vecWriteFile.size()) { return false; } int iMinWriteFileNo = vecWriteFile.front(); int iMaxWriteFileNo = vecWriteFile.back(); logerr("MergeStat DEBUG iMinWriteFileNo %d iMaxWriteFileNo %d", iMinWriteFileNo, iMaxWriteFileNo); return iMinWriteFileNo != iMaxWriteFileNo; } int GetDataFileCountOn(const std::string& sDirPath) { std::vector<int> vecWriteFile; dbcomm::GatherWriteFilesFromDataPath(sDirPath, vecWriteFile); std::vector<int> vecMergeFile; dbcomm::GatherMergeFilesFromDataPath(sDirPath, vecMergeFile); return vecWriteFile.size() + vecMergeFile.size(); } bool CheckUsageAgainstRecycle( const std::string& sKvPath, const std::string& sKvRecyclePath, int iMergeRatio) { iMergeRatio = std::max(iMergeRatio, 0); iMergeRatio = std::min(iMergeRatio, 100); // write file int iKvPathDataFileCnt = GetDataFileCountOn(sKvPath); assert(0 <= iKvPathDataFileCnt); int iKvRecyclePathDataFileCnt = GetDataFileCountOn(sKvRecyclePath); assert(0 <= iKvRecyclePathDataFileCnt); logerr("MERGE iMergeRatio %d iKvPathDataFileCnt %d iKvRecyclePathDataFileCnt %d", iMergeRatio, iKvPathDataFileCnt, iKvRecyclePathDataFileCnt); return iKvRecyclePathDataFileCnt * iMergeRatio <= iKvPathDataFileCnt * 100; } bool CheckDiskRatio( const char* sKvPath, const int iMaxDiskRatio) { int iApproximateDiskRatio = iMaxDiskRatio - 5; iApproximateDiskRatio = 0 > iApproximateDiskRatio ? 0 : iApproximateDiskRatio; if (0 < dbcomm::DiskRatio(sKvPath, iApproximateDiskRatio)) { logerr("MergeStat DEBUG DiskRatio > iMaxDiskRatio %d" " iApproximateDiskRatio %d", iMaxDiskRatio, iApproximateDiskRatio); return true; } return false; } bool CheckTime(const int iMergeCount, const int* arrMergeTime) { int iSleepTime = 0; int iMinSleepTime = 0; int iMergeIndex = 0; for (int i = 0; i < iMergeCount; i++) { iSleepTime = dbcomm::CalcSleepTime(arrMergeTime[i]); if (iSleepTime <= iMinSleepTime) { iMergeIndex = i; iMinSleepTime = iSleepTime; } } iSleepTime = dbcomm::CalcSleepTime(arrMergeTime[iMergeIndex]); if( iSleepTime > 0 ) { logerr("MergeStat DEBUG iSleepTime %d", iSleepTime); return false; } else if( iSleepTime == 0 ) { logerr("MergeStat DEBUG iSleepTime %d", iSleepTime); return true; } else { logerr("MergeStat DEBUG iSleepTime %d", iSleepTime); assert(0); } return true; } } // namespace CheckMerge void Print(const std::vector<int>& vecFile, const char* sMsg) { std::stringstream ss; ss << "size " << vecFile.size(); for (size_t i = 0; i < vecFile.size(); ++i) { ss << " " << vecFile[i]; } std::string sOut = ss.str(); logerr("%s %s", sMsg, sOut.c_str()); } } // namespac memkv
1,452