repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
AndreaOrru/Gilgamesh
tests/test_analysis.cpp
<reponame>AndreaOrru/Gilgamesh #include <catch2/catch.hpp> #include "asar.hpp" #include "analysis.hpp" #include "assertion.hpp" #include "cpu.hpp" using namespace std; TEST_CASE("Assertions work correctly", "[analysis]") { Analysis analysis(*assemble("assertions")); analysis.run(); // Test there are two subroutines (+ NMI). REQUIRE(analysis.subroutines.size() - 1 == 2); // Test there's a `reset` subroutine with the correct number of instructions. auto& resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.label == "reset"); REQUIRE(resetSubroutine.instructions.size() == 1); // Test that the subroutine is unknown because it's calling an unknown sub. REQUIRE(resetSubroutine.isUnknownBecauseOf(UnknownReason::Unknown)); // Check that there's an unknown subroutine with an indirect jump. auto& unknownSubroutine = analysis.subroutines.at(0x8005); REQUIRE(unknownSubroutine.instructions.size() == 1); REQUIRE(unknownSubroutine.isUnknownBecauseOf(UnknownReason::IndirectJump)); // Add an instruction assertion to the call in `reset`. analysis.addAssertion(Assertion(AssertionType::Instruction), 0x8000, 0x8000); analysis.run(); // Check that it removes the unknown state change status. resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.instructions.size() == 2); REQUIRE(resetSubroutine.unknownStateChanges.empty()); // Add a subroutine assertion to the unknown subroutine. analysis.addAssertion(Assertion(AssertionType::Subroutine), 0x8005, 0x8005); analysis.run(); // Check that it removes the unknown state change status. unknownSubroutine = analysis.subroutines.at(0x8000); REQUIRE(unknownSubroutine.unknownStateChanges.empty()); // Remove the first instruction assertion. analysis.removeAssertion(0x8000, 0x8000); analysis.run(); // Check that there's still no unknown status. resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.instructions.size() == 2); REQUIRE(resetSubroutine.unknownStateChanges.empty()); } TEST_CASE("Instructions that change A/X work correctly", "[analysis]") { Analysis analysis(*assemble("change_registers")); analysis.run(); analysis.instructions.clear(); CPU cpu(&analysis, 0x8000, 0x8000, State()); cpu.step(); // rep #$20 cpu.step(); // lda #$1234 REQUIRE(cpu.A.get() == 0x1234); cpu.step(); // pha cpu.step(); // clc cpu.step(); // adc #$0003 REQUIRE(cpu.A.get() == 0x1237); cpu.step(); // sei cpu.step(); // sbc #$0002 REQUIRE(cpu.A.get() == 0x1235); cpu.step(); // lda $7E0000 REQUIRE(cpu.A.get() == nullopt); cpu.step(); // pla REQUIRE(cpu.A.get() == 0x1234); cpu.step(); // sep #$10 cpu.step(); // ldx #$91 REQUIRE(cpu.X.get() == 0x91); cpu.step(); // tax REQUIRE(cpu.X.getWhole() == 0x1234); } TEST_CASE("State inference correctly simplifies state changes", "[analysis]") { Analysis analysis(*assemble("elidable_state_change")); analysis.run(); // Test there are two subroutines (+ NMI). REQUIRE(analysis.subroutines.size() - 1 == 2); // Test there's a `reset` subroutine with the correct number of instructions. auto& resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.label == "reset"); REQUIRE(resetSubroutine.instructions.size() == 4); // Test there's a subroutine with the correct number of instructions. auto& elidableChangeSubroutine = analysis.subroutines.at(0x800A); REQUIRE(elidableChangeSubroutine.instructions.size() == 6); // Test that the state is preserved. auto stateChanges = elidableChangeSubroutine.knownStateChanges; REQUIRE(stateChanges.size() == 1); auto stateChange = stateChanges.begin()->second; REQUIRE(stateChange.isEmpty()); } TEST_CASE("Loops do not cause the analysis to hang", "[analysis]") { Analysis analysis(*assemble("infinite_loop")); analysis.run(); // Check there is a single subroutine (+ NMI) with one instruction. REQUIRE(analysis.subroutines.size() - 1 == 1); REQUIRE(analysis.subroutines.at(0x8000).pc == 0x8000); REQUIRE(analysis.subroutines.at(0x8000).instructions.size() == 1); // Check there is a single instruction in the analysis. auto& instructions = analysis.instructions; REQUIRE(instructions.size() == 1); REQUIRE(instructions.at(0x8000).size() == 1); // Check the instruction is a jump. auto jmp = instructions.at(0x8000).begin(); REQUIRE(jmp->pc == 0x8000); REQUIRE(jmp->subroutinePC == 0x8000); REQUIRE(jmp->operation() == Op::JMP); // Check the instruction points to itself. REQUIRE(analysis.references.size() == 1); REQUIRE(analysis.references.at(0x8000).count({0x8000, 0x8000})); } TEST_CASE("Jump tables are handled correctly", "[analysis]") { Analysis analysis(*assemble("jump_tables")); analysis.run(); // Test that there's a single subroutine, which is unknown // because of an unexplored indirect jump instruction. auto& resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.label == "reset"); REQUIRE(resetSubroutine.instructions.size() == 1); REQUIRE(resetSubroutine.isUnknownBecauseOf(UnknownReason::IndirectJump)); // Specify the limits of the jump table. analysis.defineJumpTable(0x8000, {0, 2}); analysis.run(); // Verify that the subroutines pointed by // the jumptable have been explored. { REQUIRE(analysis.subroutines.size() - 1 == 3); REQUIRE(analysis.subroutines.count(0x8100) == 1); REQUIRE(analysis.subroutines.count(0x8200) == 1); } } TEST_CASE("PHP and PLP correctly preserve state", "[analysis]") { Analysis analysis(*assemble("php_plp")); analysis.run(); // Test there are two subroutines (+ NMI). REQUIRE(analysis.subroutines.size() - 1 == 2); // Test there's a `reset` subroutine with the correct number of instructions. auto& resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.label == "reset"); REQUIRE(resetSubroutine.instructions.size() == 4); REQUIRE(!resetSubroutine.savesStateInIncipit()); // Test there's a PHP/PLP subroutine with the correct number of instructions. auto& phpPlpSubroutine = analysis.subroutines.at(0x800A); REQUIRE(phpPlpSubroutine.instructions.size() == 5); REQUIRE(phpPlpSubroutine.savesStateInIncipit()); // Test that the state is preserved. auto stateChanges = phpPlpSubroutine.knownStateChanges; REQUIRE(stateChanges.size() == 1); auto stateChange = stateChanges.begin()->second; REQUIRE(stateChange.isEmpty()); } TEST_CASE("Overlapping StateChanges are simplified when propagating", "[analysis]") { Analysis analysis(*assemble("simplified_state_changes")); analysis.run(); // Test there are two subroutines (+ NMI). REQUIRE(analysis.subroutines.size() - 1 == 2); // Test there's a `reset` subroutine with the correct number of instructions. auto& resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.label == "reset"); REQUIRE(resetSubroutine.instructions.size() == 5); // Test there's a `double_state_change` subroutine // with the correct number of instructions. auto& doubleStateSubroutine = analysis.subroutines.at(0x800E); REQUIRE(doubleStateSubroutine.instructions.size() == 5); // Test that the state is simplified. REQUIRE(doubleStateSubroutine.knownStateChanges.size() == 2); REQUIRE(doubleStateSubroutine.unknownStateChanges.empty()); } TEST_CASE("StateChange is propagated correctly between subroutines", "[analysis]") { Analysis analysis(*assemble("state_change")); analysis.run(); // Test there are two subroutines (+ NMI). REQUIRE(analysis.subroutines.size() - 1 == 2); // Check the subroutines have the right name and number of instructions. auto& resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.label == "reset"); REQUIRE(resetSubroutine.instructions.size() == 5); auto& stateChangeSubroutine = analysis.subroutines.at(0x800E); REQUIRE(stateChangeSubroutine.label == "sub_00800E"); REQUIRE(stateChangeSubroutine.instructions.size() == 2); // Check the `state_change` subroutine sets M/X to 0. auto stateChange = stateChangeSubroutine.knownStateChanges.begin()->second; REQUIRE(stateChangeSubroutine.knownStateChanges.size() == 1); REQUIRE(stateChange.m == false); REQUIRE(stateChange.x == false); // Check LDA and LDX have the right operand size. auto lda = analysis.instructions.at(0x8005).begin(); REQUIRE(lda->operation() == Op::LDA); REQUIRE(lda->argument() == 0x1234); auto ldx = analysis.instructions.at(0x8008).begin(); REQUIRE(ldx->operation() == Op::LDX); REQUIRE(ldx->argument() == 0x1234); } TEST_CASE("Entry points can be added and analyzed", "[analysis]") { Analysis analysis(*assemble("unknown_call_jump")); analysis.run(); // Test there are two subroutines (including NMI). REQUIRE(analysis.subroutines.size() == 2); // Check the subroutines have the right name and number of instructions. auto& resetSubroutine = analysis.subroutines.at(0x8000); REQUIRE(resetSubroutine.label == "reset"); REQUIRE(resetSubroutine.instructions.size() == 1); REQUIRE(resetSubroutine.unknownStateChanges.size() == 1); auto& nmiSubroutine = analysis.subroutines.at(0x8003); REQUIRE(nmiSubroutine.label == "nmi"); REQUIRE(nmiSubroutine.instructions.size() == 2); REQUIRE(nmiSubroutine.unknownStateChanges.size() == 1); // Test adding a custom entry point. analysis.addEntryPoint("loop", 0x9002); analysis.run(); auto& loopSubroutine = analysis.subroutines.at(0x9002); REQUIRE(loopSubroutine.label == "loop"); REQUIRE(loopSubroutine.instructions.size() == 1); }
wolf0931/WenWenClinic
src/com/wenwen/clinic/chatuidemo/activity/MyConsultation.java
package com.wenwen.clinic.chatuidemo.activity; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Hashtable; import java.util.List; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMConversation; import com.easemob.chat.EMMessage; import com.easemob.exceptions.EaseMobException; import com.wenwen.clinic.chatuidemo.DemoApplication; import com.wenwen.clinic.chatuidemo.R; import com.wenwen.clinic.chatuidemo.adapter.ChatAllHistoryAdapter; import com.wenwen.clinic.debug.DebugLog; public class MyConsultation extends BaseActivity { private final String TAG = "ClinicOrder"; private InputMethodManager inputMethodManager; private ListView listView; private ChatAllHistoryAdapter adapter; public RelativeLayout errorItem; public TextView errorText; private boolean hidden; private List<EMConversation> conversationList; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); DebugLog.i(TAG, "onCreate"); setContentView(R.layout.myconsultation); DemoApplication.register(this); inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); errorItem = (RelativeLayout)findViewById(R.id.rl_error_item); errorText = (TextView) errorItem.findViewById(R.id.tv_connect_errormsg); conversationList = loadConversationsWithRecentChat(); listView = (ListView)findViewById(R.id.list); adapter = new ChatAllHistoryAdapter(MyConsultation.this, 1, conversationList); // 设置adapter listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { EMConversation conversation = adapter.getItem(position); String username = conversation.getUserName(); DebugLog.i(TAG, "username==="+username); String acountname =null; String toacountname =null; try { acountname = conversation.getLastMessage().getStringAttribute("accountname"); toacountname = conversation.getLastMessage().getStringAttribute("toaccountname"); if (username.equals(DemoApplication.getInstance().getUserName())) Toast.makeText(MyConsultation.this, "不能和自己聊天", 0).show(); else { Intent intent = new Intent(MyConsultation.this,ChatActivity.class); intent.putExtra("username", username); if (conversation.getLastMessage().getStringAttribute("type").equals("2")) { intent.putExtra("accountname", toacountname); }else{ intent.putExtra("accountname", acountname); } intent.putExtra("type", "1"); startActivity(intent); } } catch (EaseMobException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); listView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // 隐藏软键盘 hideSoftKeyboard(); return false; } }); } void hideSoftKeyboard() { if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getCurrentFocus() != null) inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } /** * 获取所有会话 * * @param context * @return */ private List<EMConversation> loadConversationsWithRecentChat() { // 获取所有会话,包括陌生人 Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations(); List<EMConversation> list = new ArrayList<EMConversation>(); // 过滤掉messages seize为0的conversation for (EMConversation conversation : conversations.values()) { if (conversation.getAllMessages().size() != 0) list.add(conversation); } // 排序 sortConversationByLastChatTime(list); return list; } /** * 根据最后一条消息的时间排序 * * @param usernames */ private void sortConversationByLastChatTime(List<EMConversation> conversationList) { Collections.sort(conversationList, new Comparator<EMConversation>() { @Override public int compare(final EMConversation con1, final EMConversation con2) { EMMessage con2LastMessage = con2.getLastMessage(); EMMessage con1LastMessage = con1.getLastMessage(); if (con2LastMessage.getMsgTime() == con1LastMessage.getMsgTime()) { return 0; } else if (con2LastMessage.getMsgTime() > con1LastMessage.getMsgTime()) { return 1; } else { return -1; } } }); } /** * 刷新页面 */ public void refresh() { conversationList.clear(); conversationList.addAll(loadConversationsWithRecentChat()); adapter.notifyDataSetChanged(); } public void back(View view) { finish(); } }
mbenson/therian
core/src/main/java/therian/operator/immutablecheck/DefaultImmutableChecker.java
/* * Copyright the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package therian.operator.immutablecheck; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.StringUtils; import therian.buildweaver.StandardOperator; /** * Checks for types universally known to be immutable. */ @StandardOperator public class DefaultImmutableChecker extends ImmutableChecker { private static final String[] KNOWN_IMMUTABLE_PREFIXES; private static final Set<Class<?>> KNOWN_IMMUTABLE_TYPES; static { KNOWN_IMMUTABLE_PREFIXES = new String[] { "immutable", "unmodifiable", "empty" }; final Set<Class<?>> s = new HashSet<>(); Collections.<Class<?>> addAll(s, String.class, Enum.class, Annotation.class, Class.class, Arrays.asList() .getClass()); addTypeTo(s, Collections.emptySet()); addTypeTo(s, Collections.unmodifiableSet(new HashSet<>())); addTypeTo(s, Collections.emptyList()); addTypeTo(s, Collections.unmodifiableList(new ArrayList<>())); addTypeTo(s, Collections.unmodifiableSortedSet(new TreeSet<String>())); addTypeTo(s, Collections.emptyMap()); addTypeTo(s, Collections.unmodifiableMap(new HashMap<>())); addTypeTo(s, Collections.unmodifiableSortedMap(new TreeMap<String, Object>())); Collections.addAll(s, Collections.singleton(null).getClass(), Collections.singletonList(null).getClass(), Collections.singletonMap(null, null).getClass()); KNOWN_IMMUTABLE_TYPES = Collections.unmodifiableSet(s); } private static void addTypeTo(final Set<Class<?>> target, final Collection<?> coll) { addImmutableTypeTo(target, coll.getClass()); addImmutableTypeTo(target, coll.iterator().getClass()); } private static void addTypeTo(final Set<Class<?>> target, final List<?> list) { addTypeTo(target, (Collection<?>) list); addImmutableTypeTo(target, list.listIterator().getClass()); } private static void addTypeTo(final Set<Class<?>> target, final SortedSet<String> sortedSet) { addTypeTo(target, (Collection<?>) sortedSet); addTypeTo(target, (Set<String>) sortedSet.headSet("foo")); addTypeTo(target, (Set<String>) sortedSet.tailSet("foo")); addTypeTo(target, (Set<String>) sortedSet.subSet("foo", "foo")); } private static void addTypeTo(final Set<Class<?>> target, final Map<?, ?> map) { addImmutableTypeTo(target, map.getClass()); addTypeTo(target, map.keySet()); addTypeTo(target, map.values()); } private static void addTypeTo(final Set<Class<?>> target, final SortedMap<String, ?> sortedMap) { addTypeTo(target, (Map<String, ?>) sortedMap); addTypeTo(target, (Map<String, ?>) sortedMap.headMap("foo")); addTypeTo(target, (Map<String, ?>) sortedMap.tailMap("foo")); addTypeTo(target, (Map<String, ?>) sortedMap.subMap("foo", "foo")); } private static void addImmutableTypeTo(final Set<Class<?>> target, final Class<?> type) { if (target.contains(type)) { return; } Class<?> c = type; while (c.isAnonymousClass()) { c = c.getEnclosingClass(); } if (target.contains(c) && !type.equals(c) || StringUtils.startsWithAny(c.getSimpleName().toLowerCase(Locale.US), KNOWN_IMMUTABLE_PREFIXES)) { target.add(type); } } @Override protected boolean isImmutable(Object object) { if (object == null) { return true; } final Class<?> cls = object.getClass(); if (cls.isPrimitive()) { return true; } if (ClassUtils.wrapperToPrimitive(cls) != null) { return true; } // quick check: if (KNOWN_IMMUTABLE_TYPES.contains(cls)) { return true; } // inheritance too: for (final Class<?> type : KNOWN_IMMUTABLE_TYPES) { if (type.isInstance(object)) { return true; } } return cls.equals(Object.class); } }
Marknjo/nextjs-lab
01.file/pages/index.js
import Link from 'next/link'; const HomePage = function () { return ( <> <h1>Home Page</h1> <nav> <ul> <li> <Link href="/portfolio">Portfolio</Link> </li> <li> <Link href="/clients">Clients</Link> </li> <li></li> </ul> </nav> </> ); }; export default HomePage;
PRASAD-DANGARE/PYTHON
stringtest.py
# Python Program To Use The String Testing Methods ''' Function Name : String Testing Methods . Function Date : 3 Sep 2020 Function Author : <NAME> Input : Integer,String Output : Integer,String ''' # Check If All The Characters In The Text Are Alphanumeric Using isalnum() Method txt = "Company12" x = txt.isalnum() print(x) print("Next \n") # Check If All The Characters In The Text Are Letters Using isalpha() Method txt = "CompanyX" x = txt.isalpha() print(x) print("Next \n") # Check If All The Characters In The Text Are Digits Using isdigit() Method txt = "50800" x = txt.isdigit() print(x) print("Next \n") # Check If All The Characters In The Text Are In Lower Case Using islower() Method txt = "hello world!" x = txt.islower() print(x) print("Next \n") # Check If All The Characters In The Text Are In Upper Case Using isupper() Method txt = "THIS IS NOW!" x = txt.isupper() print(x) print("Next \n") # Check If Each Word Start With An Upper Case Letter Using istitle() Method txt = "Hello, And Welcome To My World!" x = txt.istitle() print(x) print("Next \n") # Check If All The Characters In The Text Are Whitespaces Using isspace() Method txt = " " x = txt.isspace() print(x) print("Last \n")
ScalablyTyped/SlinkyTyped
o/office-js/src/main/scala/typingsSlinky/officeJs/global/Excel/SortOn.scala
<filename>o/office-js/src/main/scala/typingsSlinky/officeJs/global/Excel/SortOn.scala package typingsSlinky.officeJs.global.Excel import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** * [Api set: ExcelApi 1.2] */ @JSGlobal("Excel.SortOn") @js.native object SortOn extends StObject { @JSBracketAccess def apply(value: String): js.UndefOr[typingsSlinky.officeJs.Excel.SortOn with String] = js.native /* "CellColor" */ val cellColor: typingsSlinky.officeJs.Excel.SortOn.cellColor with String = js.native /* "FontColor" */ val fontColor: typingsSlinky.officeJs.Excel.SortOn.fontColor with String = js.native /* "Icon" */ val icon: typingsSlinky.officeJs.Excel.SortOn.icon with String = js.native /* "Value" */ val value: typingsSlinky.officeJs.Excel.SortOn.value with String = js.native }
uzhyhala/IBA-Group-Workfusion-Framework
ia_system_invoiceplane/src/main/java/com/ibagroup/workfusion/rpa/systems/invoiceplane/pages/MainPage.java
package com.ibagroup.workfusion.rpa.systems.invoiceplane.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import com.ibagroup.workfusion.rpa.core.clients.RobotDriverWrapper; import com.ibagroup.workfusion.rpa.core.config.ConfigurationManager; import com.ibagroup.workfusion.rpa.core.pagefactory.Wait; import com.ibagroup.workfusion.rpa.core.pagefactory.Wait.WaitFunc; public class MainPage extends RobotDriverWrapper { @FindBy(xpath = "//div[@id='panel-quick-actions']//a//span[text()='Add Client']/parent::*") @Wait(waitFunc = WaitFunc.CLICKABLE, value = 20) private WebElement addClientButton; public MainPage(ConfigurationManager cmn) { super(cmn); } public void addClient() { addClientButton.click(); } }
Thlamz/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/slm/action/StartSLMAction.java
<reponame>Thlamz/elasticsearch<gh_stars>1-10 /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.slm.action; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ActionType; import org.elasticsearch.action.support.master.AcknowledgedRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.common.io.stream.StreamInput; import java.io.IOException; public class StartSLMAction extends ActionType<AcknowledgedResponse> { public static final StartSLMAction INSTANCE = new StartSLMAction(); public static final String NAME = "cluster:admin/slm/start"; protected StartSLMAction() { super(NAME, AcknowledgedResponse::readFrom); } public static class Request extends AcknowledgedRequest<StartSLMAction.Request> { public Request(StreamInput in) throws IOException { super(in); } public Request() { } @Override public ActionRequestValidationException validate() { return null; } @Override public int hashCode() { return 86; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj.getClass() != getClass()) { return false; } return true; } } }
momofoolish/sss-rbac-admin
sra-common/src/main/java/com/jwss/sra/common/enums/ApiResultEnum.java
package com.jwss.sra.common.enums; /** * @date 2022-1-12 16:30:04 * @author jwss */ public enum ApiResultEnum { /** * 成功 */ SUCCESS(200, "请求成功"), /** * 内部错误 */ ERROR(500, "内部错误"), /** * 未找到资源 */ NOT_FOUNT(404, "未找到资源"), /** * 拒绝请求 */ REFUSE(401, "拒绝请求"), /** * 未登录 */ NOT_LOGIN(4001, "未登录"), /** * 无权限访问 */ NOT_PERMISSION(4002, "无权限访问"), /** * token失效 */ TOKEN_INVALID(4003, "TOKEN失效") ; Integer code; String desc; ApiResultEnum(Integer code, String desc) { this.code = code; this.desc = desc; } public Integer getCode() { return code; } public String getDesc() { return desc; } }
medismailben/llvm-project
libcxx/test/std/re/re.results/re.results.const/move.pass.cpp
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <regex> // class match_results<BidirectionalIterator, Allocator> // match_results(match_results&& m) noexcept; // // Additionally, the stored Allocator value is move constructed from m.get_allocator(). #include <regex> #include <cassert> #include "test_macros.h" #include "test_allocator.h" template <class CharT, class Allocator> void test(const Allocator& a) { typedef std::match_results<const CharT*, Allocator> SM; ASSERT_NOEXCEPT(SM(std::declval<SM&&>())); SM m0(a); assert(m0.get_allocator() == a); SM m1(std::move(m0)); assert(m1.size() == 0); assert(!m1.ready()); assert(m1.get_allocator() == a); } int main(int, char**) { test<char> (std::allocator<std::sub_match<const char *> >()); test<wchar_t>(std::allocator<std::sub_match<const wchar_t *> >()); test<char> (test_allocator<std::sub_match<const char*> >(3)); assert(test_alloc_base::moved == 1); test<wchar_t>(test_allocator<std::sub_match<const wchar_t*> >(3)); assert(test_alloc_base::moved == 2); return 0; }
yuyunliuhen/quick_test
node.js/test/pay_server/httpServer.js
<filename>node.js/test/pay_server/httpServer.js<gh_stars>0 var http = require("http"); var qs = require( 'querystring' ); var log4js = require('log4js'); var json2xml = require('json2xml'); var log_json = require('./config/log.json'); log4js.configure(log_json); var http_logger = log4js.getLogger('http-logger'); var parse_string = require('xml2js').parseString; var pay_message = require('./config/pay_message'); /** * construct function * @param host * @param port */ var connector = function(host,port) { this.server = null; this.host = host; this.port = port; }; /** * create a http server */ connector.prototype.createHttpServer = function() { var self = this; this.server = http.createServer(function(req, res) { var url = req.url; var client_ip = req.connection.remoteAddress; http_logger.debug("new client coming ip:" + client_ip + " method:" + req.method + " url:" + url); switch(req.method){ case 'GET':{ var args = self.parseGet(req, res); args && self.dispatchMessage(args[1], args[0], req, res); break; } case 'POST':{ self.parsePost(req,res,function(data){ self.dispatchMessage(data,url,req,res); }); break; } default:{ res.end(); break; } } }); this.server.listen( this.port ); http_logger.debug("server listen at " + this.port); }; /** * paese data for http get * @param req * @param res * @returns {*} */ connector.prototype.parseGet = function(req, res){ var str = req.url; if (str.indexOf('?') > -1) { var arr = String.prototype.split.call(req.url, '?'); return [arr[0],qs.parse(arr[1])]; } else { return [str, null]; } }; /** * parse data for http post * @param req * @param res * @param cb */ connector.prototype.parsePost = function(req,res,cb){ var chunks = []; req.on('data', function(chunk) { chunks.push(chunk); }); req.on('end', function() { // convert array to string,delimiter is ""; var data = chunks.join(''); // convert url format to normal!! cb(/*qs.parse(data)*/data); }); req.on('error',function(err){ http_logger.debug('problem with request: ' + err.message); }); }; /** * dispatch message for the format : account=king_lee&account=king_lee * @param data * @param url * @param req * @param res */ connector.prototype.dispatchMessage = function(data,url,req,res){ http_logger.debug(data); if(null == data) { return; } if(url == "/wo_shop") { parse_string(data, function (err, result) { for(var v in result){ if(v == "callbackReq"){ var orderid = result[v].orderid; var pay_message_res = {}; pay_message_res.callbackRsp = 1; var xml_pay_message_res = json2xml(pay_message_res,{ header: true }); res.writeHead(200, { 'Content-Type': 'application/text/xml; charset=utf-8' }); res.end(xml_pay_message_res); } } }); } else if(url == "/wo_shop?serviceid=validateorderid"){ parse_string(data, function (err, result) { for(var v in result){ if(v == "checkOrderIdReq"){ var orderid = result[v].orderid; var orderid_real = orderid[0].substr(33,3); var ordertime = format_time(); var pay_message_res = {}; for(var v in pay_message){ if(orderid_real == pay_message[v].iapid){ pay_message_res.checkOrderIdRsp = 0; pay_message_res.appname = pay_message[v].appname; pay_message_res.feename = pay_message[v].feename; pay_message_res.payfee = pay_message[v].payfee ; pay_message_res.appdeveloper = pay_message[v].appdeveloper ; pay_message_res.gameaccount = "" ; pay_message_res.macaddress = "" ; pay_message_res.appid = pay_message[v].appid ; pay_message_res.ipaddress = "" ; pay_message_res.serviceid = pay_message[v].serviceid ; pay_message_res.channelid = pay_message[v].channelid ; pay_message_res.cpid = pay_message[v].cpid ; pay_message_res.ordertime = ordertime ; pay_message_res.imei = "" ; pay_message_res.appversion = pay_message[v].appversion ; } } var json_pay_message_res = {"paymessages":pay_message_res}; var xml_pay_message_res = json2xml(json_pay_message_res,{ header: true }); res.writeHead(200, { 'Content-Type': 'application/text/xml; charset=utf-8' }); res.end(xml_pay_message_res); } } }); } }; var format_time = function() { var time_format = ''; var cur_time = new Date(); time_format += cur_time.getFullYear(); if(parseInt((cur_time.getMonth() + 1)) < 10){ time_format += '0'; } time_format += (cur_time.getMonth() + 1); if(parseInt(cur_time.getDate()) < 10){ time_format += '0'; } time_format += cur_time.getDate(); if(parseInt(cur_time.getHours()) < 10){ time_format += '0'; } time_format += cur_time.getHours(); if(parseInt(cur_time.getMinutes()) < 10){ time_format += '0'; } time_format += cur_time.getMinutes(); if(parseInt(cur_time.getSeconds()) < 10){ time_format += '0'; } time_format += cur_time.getSeconds(); return time_format; }; module.exports = connector;
codefacts/elasta
elasta-orm/src/main/java/elasta/orm/upsert/impl/DirectDependencyHandlerImpl.java
package elasta.orm.upsert.impl; import elasta.orm.upsert.DirectDependencyHandler;import elasta.orm.upsert.TableData;import elasta.orm.upsert.UpsertContext;import elasta.orm.upsert.UpsertFunction;import io.vertx.core.json.JsonObject; import java.util.Objects; /** * Created by Jango on 2017-01-09. */ final public class DirectDependencyHandlerImpl implements DirectDependencyHandler { final UpsertFunction upsertFunction; public DirectDependencyHandlerImpl(UpsertFunction upsertFunction) { Objects.requireNonNull(upsertFunction); this.upsertFunction = upsertFunction; } @Override public TableData requireUpsert(JsonObject entity, UpsertContext upsertContext) { return upsertFunction.upsert(entity, upsertContext); } }
Jeongseo21/Algorithm-1
programmers/월간 코드 챌린지 시즌1/트리 트리오 중간값.cpp
/** * problem : https://programmers.co.kr/learn/courses/30/lessons/68937 * algorithm : dijkstra(bfs) * time complexity : O(E) */ #include <string> #include <algorithm> #include <iostream> #include <vector> #include <queue> using namespace std; int V; // return (unique, (the longest edge from start edge, max dist)) pair<bool, pair<int, int>> dijkstra(vector<vector<int>>& edges, int start) { queue<int> q; vector<int> dist(V, 0); vector<bool> visit(V, false); dist[start] = 0; // set start edge dist q.push(start); visit[start] = true; while(!q.empty()) { int vertex = q.front(); q.pop(); for(auto nextVertex: edges[vertex]) { if(visit[nextVertex]) continue; visit[nextVertex] = true; if(dist[nextVertex] < dist[vertex] + 1) { dist[nextVertex] = dist[vertex] + 1; q.push(nextVertex); } } } bool isUnique = true; int lastEdge = 0; for(int i=1; i<V; i++){ if(dist[lastEdge] < dist[i]) { lastEdge = i; isUnique = true; } else if(dist[lastEdge] == dist[i]){ isUnique = false; } } return {isUnique, {lastEdge, dist[lastEdge]}}; } int solution(int n, vector<vector<int>> edges) { vector<vector<int>> newEdges(n); V = n; for(int i = 0; i < edges.size(); i++) { vector<int> edge = edges[i]; newEdges[edge[0]-1].push_back(edge[1]-1); newEdges[edge[1]-1].push_back(edge[0]-1); } int edge = dijkstra(newEdges, 0).second.first; auto first = dijkstra(newEdges, edge); if(!first.first) return first.second.second; auto answer = dijkstra(newEdges, first.second.first); int maxDist = answer.second.second; bool isUnique = answer.first; return isUnique ? maxDist - 1 : maxDist; }
TakayukiHoshi1984/DeviceConnect-Old
Android/dConnectDeviceHeartRate/app/src/main/java/org/deviceconnect/android/deviceplugin/heartrate/activity/package-info.java
/* org.deviceconnect.android.deviceplugin.heartrate.activity Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ /** * Activity of this device plug-in. */ package org.deviceconnect.android.deviceplugin.heartrate.activity;
tildeio/heliotrope
spec/features/epub_access_spec.rb
# frozen_string_literal: true require 'rails_helper' describe 'EPUB access page' do context 'restricted access page for protected ebooks' do let(:press) { create(:press) } let(:monograph) { create(:public_monograph, press: press.subdomain) } let(:file_set) { create(:public_file_set, id: '999999999', content: File.open(File.join(fixture_path, 'fake_epub01.epub'))) } let!(:fr) { create(:featured_representative, work_id: monograph.id, file_set_id: file_set.id, kind: 'epub') } let(:epub) { Sighrax.from_noid(file_set.id) } before do monograph.ordered_members << file_set monograph.save! file_set.save! fr end after { FeaturedRepresentative.destroy_all } context 'generic message' do it 'shows the message' do visit epub_access_path(file_set.id) expect(page).to have_http_status(:success) end end context 'custom message' do let(:press) { create(:press, subdomain: subdomain, restricted_message: '<b>No. Just No.</b>') } context 'in michigan press' do let(:subdomain) { 'michigan' } it 'shows the message' do visit epub_access_path(file_set.id) expect(page).to have_http_status(:success) end end context 'in heb press' do let(:subdomain) { 'heb' } it 'shows the message' do visit epub_access_path(file_set.id) expect(page).to have_http_status(:success) end end context 'in barpublishing press' do let(:subdomain) { 'barpublishing' } it 'shows the message' do visit epub_access_path(file_set.id) expect(page).to have_http_status(:success) end end end end end
zlsh80826/osdi2020
05_virtual_memory/include/arm/sysregs.h
<filename>05_virtual_memory/include/arm/sysregs.h<gh_stars>0 #ifndef _SYSREGS_H #define _SYSREGS_H // *************************************** // SCTLR_EL1, System Control Register (EL1), Page 2654 of // AArch64-Reference-Manual. // *************************************** #define SCTLR_RESERVED (3 << 28) | (3 << 22) | (1 << 20) | (1 << 11) #define SCTLR_EE_LITTLE_ENDIAN (0 << 25) #define SCTLR_EOE_LITTLE_ENDIAN (0 << 24) #define SCTLR_I_CACHE_DISABLED (0 << 12) #define SCTLR_D_CACHE_DISABLED (0 << 2) #define SCTLR_MMU_DISABLED (0 << 0) #define SCTLR_MMU_ENABLED (1 << 0) #define SCTLR_VALUE_MMU_DISABLED \ (SCTLR_RESERVED | SCTLR_EE_LITTLE_ENDIAN | SCTLR_I_CACHE_DISABLED | \ SCTLR_D_CACHE_DISABLED | SCTLR_MMU_DISABLED) // *************************************** // HCR_EL2, Hypervisor Configuration Register (EL2), Page 2487 of // AArch64-Reference-Manual. // *************************************** #define HCR_RW (1 << 31) #define HCR_VALUE HCR_RW // *************************************** // SCR_EL3, Secure Configuration Register (EL3), Page 2648 of // AArch64-Reference-Manual. // *************************************** #define SCR_RESERVED (3 << 4) #define SCR_RW (1 << 10) #define SCR_NS (1 << 0) #define SCR_VALUE (SCR_RESERVED | SCR_RW | SCR_NS) // *************************************** // SPSR_EL3, Saved Program Status Register (EL3) Page 389 of // AArch64-Reference-Manual. // *************************************** #define SPSR_MASK_ALL (7 << 6) #define SPSR_EL1h (5 << 0) #define SPSR_VALUE (SPSR_MASK_ALL | SPSR_EL1h) // *************************************** // SPSR_EL1 // *************************************** #define EL1_SPSR_MASK (1 << 6) #define EL1_SPSR_EL0 (15 << 0) #define EL1_SPSR_VALUE (EL1_SPSR_MASK & ~EL1_SPSR_EL0) // *************************************** // ESR_EL1, Exception Syndrome Register (EL1). Page 2431 of AArch64-Reference-Manual. // *************************************** #define ESR_ELx_EC_SHIFT 26 #define ESR_ELx_EC_SVC64 0x15 // *************************************** // TCR_EL1, Translation Control Register // *************************************** #define TCR_CONFIG_REGION_48bit (((64 - 48) << 0) | ((64 - 48) << 16)) #define TCR_CONFIG_4KB ((0b00 << 14) | (0b10 << 30)) #define TCR_CONFIG_DEFAULT (TCR_CONFIG_REGION_48bit | TCR_CONFIG_4KB) // *************************************** // MAIR_EL1, Memory Attribute Indirection Register // *************************************** #define MAIR_DEVICE_nGnRnE 0b00000000 #define MAIR_NORMAL_NOCACHE 0b01000100 #define MAIR_IDX_DEVICE_nGnRnE 0 #define MAIR_IDX_NORMAL_NOCACHE 1 #define MAIR_CONFIG_DEFAULT (MAIR_DEVICE_nGnRnE << (MAIR_IDX_DEVICE_nGnRnE * 8)) | (MAIR_NORMAL_NOCACHE << (MAIR_IDX_NORMAL_NOCACHE * 8)) // *************************************** // TTBR // *************************************** #define PD_TABLE 0b11 #define PD_BLOCK 0b01 #define PD_PAGE 0b11 #define PD_ACCESS (1 << 10) #define PGD_ATTR PD_TABLE #define PUD_ATTR PD_TABLE #define PMD_ATTR PD_TABLE #define NORMAL_MEM_FLAGS (PD_ACCESS | (MAIR_IDX_NORMAL_NOCACHE << 2) | PD_PAGE) #define DEVICE_MEM_FLAGS (PD_ACCESS | (MAIR_IDX_DEVICE_nGnRnE << 2) | PD_PAGE) #endif
hyperion-ml/hyperion
hyperion/torch/utils/data_parallel.py
""" Copyright 2019 Johns Hopkins University (Author: <NAME>) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ import torch import torch.nn as nn class TorchDataParallel(nn.DataParallel): def __getattr__(self, name): try: return super().__getattr__(name) except AttributeError: return getattr(self.module, name)
gstackio/spiff
dynaml/division.go
<gh_stars>0 package dynaml import ( "fmt" "github.com/cloudfoundry-incubator/spiff/yaml" ) type DivisionExpr struct { A Expression B Expression } func (e DivisionExpr) Evaluate(binding Binding) (yaml.Node, EvaluationInfo, bool) { resolved := true aint, info, ok := ResolveIntegerExpressionOrPushEvaluation(&e.A, &resolved, nil, binding) if !ok { return nil, info, false } bint, info, ok := ResolveIntegerExpressionOrPushEvaluation(&e.B, &resolved, &info, binding) if !ok { return nil, info, false } if !resolved { return node(e), info, true } if bint == 0 { info.Issue = "division by zero" return nil, info, false } return node(aint / bint), info, true } func (e DivisionExpr) String() string { return fmt.Sprintf("%s / %s", e.A, e.B) }
Lulzx/material-ui
packages/material-ui-icons/src/Delete.js
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Delete = props => <SvgIcon {...props}> <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" /> </SvgIcon>; Delete = pure(Delete); Delete.muiName = 'SvgIcon'; export default Delete;
ferhatelmas/algo
leetCode/algorithms/easy/sum_of_root_to_leaf_binary_numbers.py
<gh_stars>10-100 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sum(self, node: TreeNode, num: str) -> int: if node is None: return 0 if node.left is None and node.right is None: return int(num + str(node.val), 2) num += str(node.val) return self.sum(node.left, num) + self.sum(node.right, num) def sumRootToLeaf(self, root: TreeNode) -> int: return self.sum(root, "")
delftdata/Metanome
backend/src/main/java/de/metanome/backend/result_postprocessing/result_ranking/UniqueColumnCombinationRanking.java
<filename>backend/src/main/java/de/metanome/backend/result_postprocessing/result_ranking/UniqueColumnCombinationRanking.java /** * Copyright 2015-2016 by Metanome 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 de.metanome.backend.result_postprocessing.result_ranking; import de.metanome.algorithm_integration.ColumnIdentifier; import de.metanome.backend.result_postprocessing.helper.ColumnInformation; import de.metanome.backend.result_postprocessing.helper.TableInformation; import de.metanome.backend.result_postprocessing.results.UniqueColumnCombinationResult; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Calculates the rankings for unique column combination results. */ public class UniqueColumnCombinationRanking extends Ranking { protected List<UniqueColumnCombinationResult> results; public UniqueColumnCombinationRanking(List<UniqueColumnCombinationResult> results, Map<String, TableInformation> tableInformationMap) { super(tableInformationMap); this.results = results; this.occurrenceMap = new HashMap<>(); createOccurrenceList(); } /** * The occurrence list stores how often a column occurs in the results. */ protected void createOccurrenceList() { initializeOccurrenceList(); for (UniqueColumnCombinationResult result : this.results) { for (ColumnIdentifier column : result.getColumnCombination().getColumnIdentifiers()) { updateOccurrenceList(column); } } } @Override public void calculateDataIndependentRankings() { for (UniqueColumnCombinationResult result : this.results) { calculateColumnRatio(result); calculateOccurrenceRatio(result); } } @Override public void calculateDataDependentRankings() { for (UniqueColumnCombinationResult result : this.results) { calculateColumnRatio(result); calculateOccurrenceRatio(result); calculateUniquenessRatio(result); calculateRandomness(result); } } /** * Calculates the ratio of the size of the column combination and the column count of the * corresponding table. * * @param result the result */ protected void calculateColumnRatio(UniqueColumnCombinationResult result) { Integer columnCount = result.getColumnCombination().getColumnIdentifiers().size(); Integer tableColumnCount = this.tableInformationMap.get(result.getTableName()).getColumnCount(); result.setColumnRatio((float) columnCount / tableColumnCount); } /** * Calculates the ratio of the unique column combination count and the overall occurrence of the * columns in the result. * * @param result the result */ protected void calculateOccurrenceRatio(UniqueColumnCombinationResult result) { Set<ColumnIdentifier> columns = result.getColumnCombination().getColumnIdentifiers(); String tableName = result.getTableName(); result.setOccurrenceRatio(calculateOccurrenceRatio(columns, tableName)); } /** * Calculate the ratio of the number of almost unique columns and all columns. * * @param result the result */ protected void calculateUniquenessRatio(UniqueColumnCombinationResult result) { TableInformation table = this.tableInformationMap.get(result.getTableName()); Set<ColumnIdentifier> columns = result.getColumnCombination().getColumnIdentifiers(); result.setUniquenessRatio(calculateUniquenessRatio(table, columns)); } /** * Calculates how unique the given column combination is. Therefor the uniqueness of each column * of the column combination is determined and multiplied. Afterward this value is normalized. * * @param result the result */ protected void calculateRandomness(UniqueColumnCombinationResult result) { TableInformation table = this.tableInformationMap.get(result.getTableName()); Map<String, ColumnInformation> columnInformationMap = table.getColumnInformationMap(); Set<ColumnIdentifier> columns = result.getColumnCombination().getColumnIdentifiers(); long min = table.getRowCount(); long max = (min - 1) ^ columns.size(); float distinctValue = 1; for (ColumnIdentifier column : columns) { distinctValue = distinctValue * columnInformationMap.get(column.getColumnIdentifier()) .getDistinctValuesCount(); } float randomness = (distinctValue - min) / (max - min); result.setRandomness(randomness); } }
Futuremappermydud/Naluluna-Modifier-Quest
include/codegen/include/System/IO/Directory.hpp
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:44 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: SearchOption struct SearchOption; // Forward declaring type: DirectoryInfo class DirectoryInfo; } // Completed forward declares // Type namespace: System.IO namespace System::IO { // Autogenerated type: System.IO.Directory class Directory : public ::Il2CppObject { public: // Nested type: System::IO::Directory::SearchData class SearchData; // static public System.String[] GetFiles(System.String path) // Offset: 0x111A010 static ::Array<::Il2CppString*>* GetFiles(::Il2CppString* path); // static public System.String[] GetFiles(System.String path, System.String searchPattern) // Offset: 0x111A0D0 static ::Array<::Il2CppString*>* GetFiles(::Il2CppString* path, ::Il2CppString* searchPattern); // static private System.String[] InternalGetFiles(System.String path, System.String searchPattern, System.IO.SearchOption searchOption) // Offset: 0x111A0B4 static ::Array<::Il2CppString*>* InternalGetFiles(::Il2CppString* path, ::Il2CppString* searchPattern, System::IO::SearchOption searchOption); // static public System.String[] GetDirectories(System.String path) // Offset: 0x111A270 static ::Array<::Il2CppString*>* GetDirectories(::Il2CppString* path); // static public System.String[] GetDirectories(System.String path, System.String searchPattern) // Offset: 0x111A330 static ::Array<::Il2CppString*>* GetDirectories(::Il2CppString* path, ::Il2CppString* searchPattern); // static private System.String[] InternalGetDirectories(System.String path, System.String searchPattern, System.IO.SearchOption searchOption) // Offset: 0x111A314 static ::Array<::Il2CppString*>* InternalGetDirectories(::Il2CppString* path, ::Il2CppString* searchPattern, System::IO::SearchOption searchOption); // static public System.String[] GetFileSystemEntries(System.String path, System.String searchPattern) // Offset: 0x111A3F8 static ::Array<::Il2CppString*>* GetFileSystemEntries(::Il2CppString* path, ::Il2CppString* searchPattern); // static private System.String[] InternalGetFileSystemEntries(System.String path, System.String searchPattern, System.IO.SearchOption searchOption) // Offset: 0x111A4C0 static ::Array<::Il2CppString*>* InternalGetFileSystemEntries(::Il2CppString* path, ::Il2CppString* searchPattern, System::IO::SearchOption searchOption); // static System.String[] InternalGetFileDirectoryNames(System.String path, System.String userPathOriginal, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) // Offset: 0x111A198 static ::Array<::Il2CppString*>* InternalGetFileDirectoryNames(::Il2CppString* path, ::Il2CppString* userPathOriginal, ::Il2CppString* searchPattern, bool includeFiles, bool includeDirs, System::IO::SearchOption searchOption, bool checkHost); // static public System.IO.DirectoryInfo CreateDirectory(System.String path) // Offset: 0x111A5B0 static System::IO::DirectoryInfo* CreateDirectory(::Il2CppString* path); // static private System.IO.DirectoryInfo CreateDirectoriesInternal(System.String path) // Offset: 0x111A89C static System::IO::DirectoryInfo* CreateDirectoriesInternal(::Il2CppString* path); // static public System.Void Delete(System.String path) // Offset: 0x111B300 static void Delete(::Il2CppString* path); // static private System.Void RecursiveDelete(System.String path) // Offset: 0x111B6E0 static void RecursiveDelete(::Il2CppString* path); // static public System.Void Delete(System.String path, System.Boolean recursive) // Offset: 0x111BA98 static void Delete(::Il2CppString* path, bool recursive); // static public System.Boolean Exists(System.String path) // Offset: 0x111BB30 static bool Exists(::Il2CppString* path); // static public System.String GetCurrentDirectory() // Offset: 0x111BD04 static ::Il2CppString* GetCurrentDirectory(); // static System.String InsecureGetCurrentDirectory() // Offset: 0x111BD1C static ::Il2CppString* InsecureGetCurrentDirectory(); // static public System.String[] GetLogicalDrives() // Offset: 0x111BEC8 static ::Array<::Il2CppString*>* GetLogicalDrives(); // static System.String GetDemandDir(System.String fullPath, System.Boolean thisDirOnly) // Offset: 0x111BED0 static ::Il2CppString* GetDemandDir(::Il2CppString* fullPath, bool thisDirOnly); }; // System.IO.Directory } DEFINE_IL2CPP_ARG_TYPE(System::IO::Directory*, "System.IO", "Directory"); #pragma pack(pop)
gingerich/mesa
packages/mesa-http/src/Server.js
<gh_stars>0 import Koa from 'koa'; import body from 'koa-bodyparser'; import compress from 'koa-compress'; import helmet from 'koa-helmet'; import morgan from 'koa-morgan'; import mount from 'koa-mount'; import responseTime from 'koa-response-time'; import { compose } from '@mesa/component'; // import { Stack } from '@mesa/core' import Mesa from '@mesa/core'; export class Server { static listen(component, ...args) { return new Server().use(component).listen(...args); } constructor(options = {}) { this.options = options; const upstream = []; if (options.msgFromRequest) { const transform = (ctx, next) => next(options.msgFromRequest(ctx)); upstream.push(Mesa.use(transform)); } this.service = Mesa.createService({ upstream }); // this.middleware = [] } use(...middleware) { this.service.use(...middleware); // this.middleware.push(...middleware) return this; } action(pattern, handler) { this.service.action(pattern, handler); return this; } // rawMode () { // this.options.msgFromRequest = ExtractMsg.rawRequest() // return this // } listen(...args) { const server = new Koa() // Set X-Response-Time header .use(responseTime()) // HTTP request logging .use(morgan('combined', this.options.morgan)) // Request body parser .use(body(this.options.bodyParser)) // Allow compression .use(compress(this.options.compress)) // Simple security configuration .use(helmet(this.options.helmet)); // const { msgFromRequest = ExtractMsg.fromBody() } = this.options // const middleware = compose(Stack.spec().use(this.middleware)) const serviceMiddleware = async (ctx, next) => { const response = await this.service.call(ctx, msg => next().then(() => msg)); // const response = await this.service.call(msgFromRequest(ctx), function (msg) { // return next().then(() => msg) // }) // if (response) { ctx.body = response || null; // } }; const serviceMount = this.options.prefix ? mount(this.options.prefix, serviceMiddleware) : serviceMiddleware; server.use(serviceMount); return server.listen(...args); } } export const ExtractMsg = { rawRequest: () => ctx => next(ctx), fromBody: () => ctx => ctx.request.body };
code4tomorrow/Python
2_intermediate/chapter9/solutions/catalog.py
""" Catalog Write a program that takes asks the user whether they'd like to add, delete, or clear the entries in a store catalog. After they perform some action, the program should display the updated dictionary in the format: item1: price1 item2: price2 etc. Keep asking them if they'd like to add, delete, or clear entries until they enter "q". Possible actions: If they enter "add": Ask them to enter an item. Ask them to enter a price. The item should be the key, and the price should be the value in the dictionary. If they enter "delete": Ask them to to enter which item they'd like to delete. If they enter "clear": Clear all the entries from the dictionary. If they enter "q": Display the final dictionary and end the program. """ catalog = {} while True: # Display catalog print("Current catalog:") if len(catalog) != 0: for item, price in catalog.items(): print(item + ": $" + price) else: print("Your catalog is empty.") print() ans = input( "Would you like to add, delete, " "or clear entries from your catalog? " ) # Perform actions depending on input if ans == "q": break elif ans == "add": item = input("Enter an item to add: ") price = input("Enter the price: $") catalog[item] = price elif ans == "delete": item = input("Enter an item to delete: ") del catalog[item] elif ans == "clear": catalog.clear() print()
bioinformatics-ua/BIcenter
app/kettleExt/trans/steps/ExecSQL.java
<gh_stars>10-100 package kettleExt.trans.steps; import java.util.List; import kettleExt.trans.step.AbstractStep; import kettleExt.utils.JSONArray; import kettleExt.utils.JSONObject; import kettleExt.utils.StringEscapeHelper; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.steps.sql.ExecSQLMeta; import org.pentaho.metastore.api.IMetaStore; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.mxgraph.model.mxCell; import com.mxgraph.util.mxUtils; public class ExecSQL extends AbstractStep { @Override public void decode(StepMetaInterface stepMetaInterface, mxCell cell, List<DatabaseMeta> databases, IMetaStore metaStore) throws Exception { ExecSQLMeta execSQLMeta = (ExecSQLMeta) stepMetaInterface; String con = cell.getAttribute( "connection" ); execSQLMeta.setDatabaseMeta(DatabaseMeta.findDatabase( databases, con )); execSQLMeta.setSql(StringEscapeHelper.decode(cell.getAttribute( "sql" ))); execSQLMeta.setExecutedEachInputRow("true".equalsIgnoreCase(cell.getAttribute( "executedEachInputRow" ))); execSQLMeta.setSingleStatement("true".equalsIgnoreCase(cell.getAttribute( "singleStatement" ))); execSQLMeta.setVariableReplacementActive("true".equalsIgnoreCase(cell.getAttribute( "replaceVariables" ))); execSQLMeta.setParams("true".equalsIgnoreCase(cell.getAttribute( "setParams" ))); execSQLMeta.setQuoteString("true".equalsIgnoreCase(cell.getAttribute( "quoteString" ))); // insertField = cell.getAttribute( "insert_field" ); // updateField = cell.getAttribute( "update_field" ); // deleteField = cell.getAttribute( "delete_field" ); // readField = cell.getAttribute( "read_field" ); JSONArray jsonArray = JSONArray.fromObject(cell.getAttribute( "arguments" )); execSQLMeta.allocate( jsonArray.size() ); for(int i=0; i<jsonArray.size(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); execSQLMeta.getArguments()[i] = jsonObject.optString("name"); } } @Override public Element encode(StepMetaInterface stepMetaInterface) throws Exception { ExecSQLMeta execSQLMeta = (ExecSQLMeta) stepMetaInterface; Document doc = mxUtils.createDocument(); Element e = doc.createElement("Step"); e.setAttribute("connection", execSQLMeta.getDatabaseMeta() == null ? "" : execSQLMeta.getDatabaseMeta().getName()); e.setAttribute("sql", StringEscapeHelper.encode(execSQLMeta.getSql())); e.setAttribute("executedEachInputRow", Boolean.toString(execSQLMeta.isExecutedEachInputRow())); e.setAttribute("singleStatement", Boolean.toString(execSQLMeta.isSingleStatement())); e.setAttribute("replaceVariables", Boolean.toString(execSQLMeta.isReplaceVariables())); e.setAttribute("setParams", Boolean.toString(execSQLMeta.isParams())); e.setAttribute("quoteString", Boolean.toString(execSQLMeta.isQuoteString())); JSONArray arguments = new JSONArray(); for ( int i = 0; i < execSQLMeta.getArguments().length; i++ ) { String name = execSQLMeta.getArguments()[i]; JSONObject jsonObject = new JSONObject(); jsonObject.put("name", name); arguments.add(jsonObject); } e.setAttribute("arguments", arguments.toString()); return e; } }
pederpansen/dune-ax1
dune/ax1/acme1MD/configurations/all_configurations.hh
<filename>dune/ax1/acme1MD/configurations/all_configurations.hh /* * all_configurations.hh * * Created on: Feb 14, 2012 * Author: jpods */ #ifndef DUNE_AX1_ALL_CONFIGURATIONS_HH #define DUNE_AX1_ALL_CONFIGURATIONS_HH #include <dune/ax1/acme1MD/configurations/default/default_config.hh> #include <dune/ax1/acme1MD/configurations/hamburger/hamburger_config.hh> #include <dune/ax1/acme1MD/configurations/cheeseburger/cheeseburger_config.hh> #include <dune/ax1/acme1MD/configurations/bigmac/bigmac_config.hh> #include <dune/ax1/acme1MD/configurations/step/step_config.hh> #endif /* DUNE_AX1_ALL_CONFIGURATIONS_HH */
mitchkaden/meteostat-python
tests/test_normals.py
""" Tests - Normals Class The code is licensed under the MIT license. """ import unittest from meteostat import Normals class TestNormals(unittest.TestCase): """ Normals class tests """ def test_normals(self): """ Test: Fetch climate normals """ # Get normals for Frankfurt Airport data = Normals('10637', (1961, 1990)) # Count rows count = data.count() # Check if count matches 48 self.assertEqual( count, 48, 'Normals returns count of ' + str(count) + ', should be 48') if __name__ == '__main__': unittest.main()
rvhub/MultipathODL
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChangeListener.java
<filename>opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChangeListener.java /* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.md.sal.common.api.data; import java.util.EventListener; import org.opendaylight.yangtools.concepts.Path; /** * * * @deprecated Replaced by {@link AsyncDataChangeEvent} */ @Deprecated public interface DataChangeListener<P extends Path<P>, D> extends EventListener { /** * Note that this method may be invoked from a shared thread pool, so * implementations SHOULD NOT perform CPU-intensive operations and they * definitely MUST NOT invoke any potentially blocking operations. * * @param change Data Change Event being delivered. **/ void onDataChanged(DataChangeEvent<P, D> change); }
Nilexplr/my_world
src/objets/text/manage_font.c
/* ** EPITECH PROJECT, 2018 ** my_world_2018 ** File description: ** manage_font.c */ #include "text.h" sfFont *manage_font(int mode) { static sfFont *font = NULL; if (mode) { if (!font) font = sfFont_createFromFile( "./ressources/goodMorning.ttf"); return font; } else { if (font) sfFont_destroy(font); } return NULL; }
leftmike/maho
storage/test/minmax.go
<gh_stars>1-10 package test import ( "strings" "testing" "github.com/leftmike/maho/sql" "github.com/leftmike/maho/storage" "github.com/leftmike/maho/testutil" ) var ( minMaxRows = makeValues(100) createMinMax = []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdCreateTable, name: sql.ID("tbl-b"), cols: []sql.Identifier{sql.ID("ID"), sql.ID("col2"), sql.ID("col3"), sql.ID("col4"), sql.ID("col5")}, colTypes: []sql.ColumnType{int32ColType, int64ColType, stringColType, int64ColType, stringColType}, key: []sql.ColumnKey{sql.MakeColumnKey(0, false)}, }, {fln: fln(), cmd: cmdAddIndex, name: sql.ID("tbl-b"), idxname: sql.ID("idx-1"), key: []sql.ColumnKey{sql.MakeColumnKey(1, true)}, unique: true}, {fln: fln(), cmd: cmdNextStmt}, {fln: fln(), cmd: cmdAddIndex, name: sql.ID("tbl-b"), idxname: sql.ID("idx-2"), key: []sql.ColumnKey{sql.MakeColumnKey(2, false), sql.MakeColumnKey(3, false)}}, {fln: fln(), cmd: cmdNextStmt}, {fln: fln(), cmd: cmdAddIndex, name: sql.ID("tbl-b"), idxname: sql.ID("idx-3"), key: []sql.ColumnKey{sql.MakeColumnKey(4, false)}}, {fln: fln(), cmd: cmdCommit}, } checkMinMaxRows = []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, values: minMaxRows}, {fln: fln(), cmd: cmdCommit}, } primaryMinMaxTests = []interface{}{ "createDatabase", createMinMax, insertRows(sql.ID("tbl-b"), minMaxRows), checkMinMaxRows, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: nil, maxRow: []sql.Value{i64Val(1), nil, nil, nil}, values: nil}, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(0), nil, nil, nil}, maxRow: []sql.Value{i64Val(1), nil, nil, nil}, values: nil}, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(0), nil, nil, nil}, maxRow: []sql.Value{i64Val(2), nil, nil, nil}, values: [][]sql.Value{ {i64Val(2), i64Val(5), strVal(`""`), i64Val(1), strVal("yy")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(0), nil, nil, nil}, maxRow: []sql.Value{i64Val(3), nil, nil, nil}, values: [][]sql.Value{ {i64Val(2), i64Val(5), strVal(`""`), i64Val(1), strVal("yy")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(0), nil, nil, nil}, maxRow: []sql.Value{i64Val(4), nil, nil, nil}, values: [][]sql.Value{ {i64Val(2), i64Val(5), strVal(`""`), i64Val(1), strVal("yy")}, {i64Val(4), i64Val(10), strVal("###"), i64Val(2), strVal("xxx")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(13), nil, nil, nil}, maxRow: []sql.Value{i64Val(13), nil, nil, nil}, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(25), nil, nil, nil}, maxRow: []sql.Value{i64Val(26), nil, nil, nil}, values: [][]sql.Value{ {i64Val(26), i64Val(65), strVal("......"), i64Val(3), strVal("mmmmmmmmmmmmmm")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(30), nil, nil, nil}, maxRow: []sql.Value{i64Val(30), nil, nil, nil}, values: [][]sql.Value{ {i64Val(30), i64Val(75), strVal("00000000"), i64Val(5), strVal("kkkkkkkkkkkkkkkk")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(31), nil, nil, nil}, maxRow: []sql.Value{i64Val(33), nil, nil, nil}, values: [][]sql.Value{ {i64Val(32), i64Val(80), strVal("1"), i64Val(6), strVal("z")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(31), nil, nil, nil}, maxRow: []sql.Value{i64Val(37), nil, nil, nil}, values: [][]sql.Value{ {i64Val(32), i64Val(80), strVal("1"), i64Val(6), strVal("z")}, {i64Val(34), i64Val(85), strVal("22"), i64Val(7), strVal("yy")}, {i64Val(36), i64Val(90), strVal("333"), i64Val(8), strVal("xxx")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(40), nil, nil, nil}, maxRow: []sql.Value{i64Val(41), nil, nil, nil}, values: [][]sql.Value{ {i64Val(40), i64Val(100), strVal("55555"), i64Val(0), strVal("vvvvv")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(50), nil, nil, nil}, maxRow: []sql.Value{i64Val(59), nil, nil, nil}, values: [][]sql.Value{ {i64Val(50), i64Val(125), strVal("::"), i64Val(5), strVal("qqqqqqqqqq")}, {i64Val(52), i64Val(130), strVal(";;;"), i64Val(6), strVal("ppppppppppp")}, {i64Val(54), i64Val(135), strVal("<<<<"), i64Val(7), strVal("oooooooooooo")}, {i64Val(56), i64Val(140), strVal("====="), i64Val(8), strVal("nnnnnnnnnnnnn")}, {i64Val(58), i64Val(145), strVal(">>>>>>"), i64Val(9), strVal("mmmmmmmmmmmmmm")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(197), nil, nil, nil}, maxRow: nil, values: [][]sql.Value{ {i64Val(198), i64Val(495), strVal("****"), i64Val(9), strVal("wwww")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(197), nil, nil, nil}, maxRow: []sql.Value{i64Val(199), nil, nil, nil}, values: [][]sql.Value{ {i64Val(198), i64Val(495), strVal("****"), i64Val(9), strVal("wwww")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(198), nil, nil, nil}, maxRow: []sql.Value{i64Val(199), nil, nil, nil}, values: [][]sql.Value{ {i64Val(198), i64Val(495), strVal("****"), i64Val(9), strVal("wwww")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdRows, minRow: []sql.Value{i64Val(199), nil, nil, nil}, maxRow: []sql.Value{i64Val(199), nil, nil, nil}, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, } index1MinMaxTests = []interface{}{ "createDatabase", createMinMax, insertRows(sql.ID("tbl-b"), minMaxRows), checkMinMaxRows, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), idxValues: sortValues([]sql.ColumnKey{sql.MakeColumnKey(0, true)}, pickColumns([]int{1, 0}, minMaxRows)), values: sortValues([]sql.ColumnKey{sql.MakeColumnKey(1, true)}, pickColumns([]int{0, 1, 2, 3, 4}, minMaxRows)), }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: nil, maxRow: []sql.Value{nil, i64Val(500), nil, nil, nil}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(505), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(500), nil, nil, nil}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(500), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(495), nil, nil, nil}, idxValues: [][]sql.Value{ {i64Val(495), i64Val(198)}, }, values: [][]sql.Value{ {i64Val(198), i64Val(495), strVal("****"), i64Val(9), strVal("wwww")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: nil, maxRow: []sql.Value{nil, i64Val(491), nil, nil, nil}, idxValues: [][]sql.Value{ {i64Val(495), i64Val(198)}, }, values: [][]sql.Value{ {i64Val(198), i64Val(495), strVal("****"), i64Val(9), strVal("wwww")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(404), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(401), nil, nil, nil}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(353), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(350), nil, nil, nil}, idxValues: [][]sql.Value{ {i64Val(350), i64Val(140)}, }, values: [][]sql.Value{ {i64Val(140), i64Val(350), strVal("ggggggg"), i64Val(0), strVal("ttttttt")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(335), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(335), nil, nil, nil}, idxValues: [][]sql.Value{ {i64Val(335), i64Val(134)}, }, values: [][]sql.Value{ {i64Val(134), i64Val(335), strVal("dddd"), i64Val(7), strVal("wwww")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(299), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(253), nil, nil, nil}, idxValues: [][]sql.Value{ {i64Val(295), i64Val(118)}, {i64Val(290), i64Val(116)}, {i64Val(285), i64Val(114)}, {i64Val(280), i64Val(112)}, {i64Val(275), i64Val(110)}, {i64Val(270), i64Val(108)}, {i64Val(265), i64Val(106)}, {i64Val(260), i64Val(104)}, {i64Val(255), i64Val(102)}, }, values: [][]sql.Value{ {i64Val(118), i64Val(295), strVal(`\\\\`), i64Val(9), strVal("oooooooooooo")}, {i64Val(116), i64Val(290), strVal("[[["), i64Val(8), strVal("ppppppppppp")}, {i64Val(114), i64Val(285), strVal("ZZ"), i64Val(7), strVal("qqqqqqqqqq")}, {i64Val(112), i64Val(280), strVal("Y"), i64Val(6), strVal("rrrrrrrrr")}, {i64Val(110), i64Val(275), strVal("XXXXXXXX"), i64Val(5), strVal("ssssssss")}, {i64Val(108), i64Val(270), strVal("WWWWWWW"), i64Val(4), strVal("ttttttt")}, {i64Val(106), i64Val(265), strVal("VVVVVV"), i64Val(3), strVal("uuuuuu")}, {i64Val(104), i64Val(260), strVal("UUUUU"), i64Val(2), strVal("vvvvv")}, {i64Val(102), i64Val(255), strVal("TTTT"), i64Val(1), strVal("wwww")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(200), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(199), nil, nil, nil}, idxValues: [][]sql.Value{ {i64Val(200), i64Val(80)}, }, values: [][]sql.Value{ {i64Val(80), i64Val(200), strVal("I"), i64Val(0), strVal("rrrrrrrrr")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(12), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(0), nil, nil, nil}, idxValues: [][]sql.Value{ {i64Val(10), i64Val(4)}, {i64Val(5), i64Val(2)}, }, values: [][]sql.Value{ {i64Val(4), i64Val(10), strVal("###"), i64Val(2), strVal("xxx")}, {i64Val(2), i64Val(5), strVal(`""`), i64Val(1), strVal("yy")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(7), nil, nil, nil}, maxRow: nil, idxValues: [][]sql.Value{ {i64Val(5), i64Val(2)}, }, values: [][]sql.Value{ {i64Val(2), i64Val(5), strVal(`""`), i64Val(1), strVal("yy")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(5), nil, nil, nil}, maxRow: nil, idxValues: [][]sql.Value{ {i64Val(5), i64Val(2)}, }, values: [][]sql.Value{ {i64Val(2), i64Val(5), strVal(`""`), i64Val(1), strVal("yy")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(3), nil, nil, nil}, maxRow: []sql.Value{nil, i64Val(3), nil, nil, nil}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-1"), minRow: []sql.Value{nil, i64Val(2), nil, nil, nil}, maxRow: nil, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, } index2MinMaxTests = []interface{}{ "createDatabase", createMinMax, insertRows(sql.ID("tbl-b"), minMaxRows), checkMinMaxRows, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), idxValues: sortValues([]sql.ColumnKey{sql.MakeColumnKey(0, false), sql.MakeColumnKey(1, false), sql.MakeColumnKey(2, false)}, pickColumns([]int{2, 3, 0}, minMaxRows)), values: sortValues([]sql.ColumnKey{sql.MakeColumnKey(2, false), sql.MakeColumnKey(3, false), sql.MakeColumnKey(0, false)}, pickColumns([]int{0, 1, 2, 3, 4}, minMaxRows)), }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: nil, maxRow: []sql.Value{nil, nil, strVal("!!!"), i64Val(-1), nil}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: []sql.Value{nil, nil, strVal("!!"), i64Val(0), nil}, maxRow: []sql.Value{nil, nil, strVal("!!!"), i64Val(-1), nil}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: nil, maxRow: []sql.Value{nil, nil, strVal("!!!"), i64Val(1), nil}, idxValues: [][]sql.Value{ {strVal("!!!"), i64Val(0), i64Val(180)}, }, values: [][]sql.Value{ {i64Val(180), i64Val(450), strVal("!!!"), i64Val(0), strVal("ppppppppppp")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: []sql.Value{nil, nil, nil, i64Val(0), nil}, maxRow: []sql.Value{nil, nil, strVal(`""`), i64Val(2), nil}, idxValues: [][]sql.Value{ {strVal("!!!"), i64Val(0), i64Val(180)}, {strVal(`""`), i64Val(1), i64Val(2)}, }, values: [][]sql.Value{ {i64Val(180), i64Val(450), strVal("!!!"), i64Val(0), strVal("ppppppppppp")}, {i64Val(2), i64Val(5), strVal(`""`), i64Val(1), strVal("yy")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: []sql.Value{nil, nil, strVal("&&&&&&&&"), i64Val(6), nil}, maxRow: []sql.Value{nil, nil, strVal("'"), i64Val(5), nil}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: []sql.Value{nil, nil, strVal("9"), i64Val(4), nil}, maxRow: []sql.Value{nil, nil, strVal("A"), i64Val(3), nil}, idxValues: [][]sql.Value{ {strVal("9"), i64Val(4), i64Val(48)}, {strVal("::"), i64Val(5), i64Val(50)}, {strVal(";;;"), i64Val(6), i64Val(52)}, {strVal("<<<<"), i64Val(7), i64Val(54)}, {strVal("====="), i64Val(8), i64Val(56)}, {strVal(">>>>>>"), i64Val(9), i64Val(58)}, {strVal("???????"), i64Val(0), i64Val(60)}, {strVal("@@@@@@@@"), i64Val(1), i64Val(62)}, {strVal("A"), i64Val(2), i64Val(64)}, }, values: [][]sql.Value{ {i64Val(48), i64Val(120), strVal("9"), i64Val(4), strVal("rrrrrrrrr")}, {i64Val(50), i64Val(125), strVal("::"), i64Val(5), strVal("qqqqqqqqqq")}, {i64Val(52), i64Val(130), strVal(";;;"), i64Val(6), strVal("ppppppppppp")}, {i64Val(54), i64Val(135), strVal("<<<<"), i64Val(7), strVal("oooooooooooo")}, {i64Val(56), i64Val(140), strVal("====="), i64Val(8), strVal("nnnnnnnnnnnnn")}, {i64Val(58), i64Val(145), strVal(">>>>>>"), i64Val(9), strVal("mmmmmmmmmmmmmm")}, {i64Val(60), i64Val(150), strVal("???????"), i64Val(0), strVal("lllllllllllllll")}, {i64Val(62), i64Val(155), strVal("@@@@@@@@"), i64Val(1), strVal("kkkkkkkkkkkkkkkk")}, {i64Val(64), i64Val(160), strVal("A"), i64Val(2), strVal("z")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: []sql.Value{nil, nil, strVal("zz"), i64Val(9), nil}, maxRow: []sql.Value{nil, nil, strVal("zz"), i64Val(10), nil}, idxValues: [][]sql.Value{ {strVal("zz"), i64Val(9), i64Val(178)}, }, values: [][]sql.Value{ {i64Val(178), i64Val(445), strVal("zz"), i64Val(9), strVal("qqqqqqqqqq")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: []sql.Value{nil, nil, strVal("zz"), i64Val(9), nil}, maxRow: nil, idxValues: [][]sql.Value{ {strVal("zz"), i64Val(9), i64Val(178)}, }, values: [][]sql.Value{ {i64Val(178), i64Val(445), strVal("zz"), i64Val(9), strVal("qqqqqqqqqq")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-2"), minRow: []sql.Value{nil, nil, strVal("zzz"), i64Val(9), nil}, maxRow: nil, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, } index3MinMaxTests = []interface{}{ "createDatabase", createMinMax, insertRows(sql.ID("tbl-b"), minMaxRows), checkMinMaxRows, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-3"), idxValues: sortValues( []sql.ColumnKey{sql.MakeColumnKey(0, false), sql.MakeColumnKey(1, false)}, pickColumns([]int{4, 0}, minMaxRows)), values: sortValues( []sql.ColumnKey{sql.MakeColumnKey(4, false), sql.MakeColumnKey(0, false)}, pickColumns([]int{0, 1, 2, 3, 4}, minMaxRows)), }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-3"), minRow: nil, maxRow: []sql.Value{nil, nil, nil, nil, strVal("jjj")}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-3"), minRow: []sql.Value{nil, nil, nil, nil, strVal("iii")}, maxRow: []sql.Value{nil, nil, nil, nil, strVal("jjj")}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-3"), minRow: []sql.Value{nil, nil, nil, nil, strVal("iii")}, maxRow: []sql.Value{nil, nil, nil, nil, strVal("l")}, idxValues: [][]sql.Value{ {strVal("kkkkkkkkkkkkkkkk"), i64Val(30)}, {strVal("kkkkkkkkkkkkkkkk"), i64Val(62)}, {strVal("kkkkkkkkkkkkkkkk"), i64Val(94)}, {strVal("kkkkkkkkkkkkkkkk"), i64Val(126)}, {strVal("kkkkkkkkkkkkkkkk"), i64Val(158)}, {strVal("kkkkkkkkkkkkkkkk"), i64Val(190)}, }, values: [][]sql.Value{ {i64Val(30), i64Val(75), strVal("00000000"), i64Val(5), strVal("kkkkkkkkkkkkkkkk")}, {i64Val(62), i64Val(155), strVal("@@@@@@@@"), i64Val(1), strVal("kkkkkkkkkkkkkkkk")}, {i64Val(94), i64Val(235), strVal("PPPPPPPP"), i64Val(7), strVal("kkkkkkkkkkkkkkkk")}, {i64Val(126), i64Val(315), strVal("````````"), i64Val(3), strVal("kkkkkkkkkkkkkkkk")}, {i64Val(158), i64Val(395), strVal("pppppppp"), i64Val(9), strVal("kkkkkkkkkkkkkkkk")}, {i64Val(190), i64Val(475), strVal("&&&&&&&&"), i64Val(5), strVal("kkkkkkkkkkkkkkkk")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-3"), minRow: []sql.Value{nil, nil, nil, nil, strVal("ssssssss")}, maxRow: []sql.Value{nil, nil, nil, nil, strVal("tttttttt")}, idxValues: [][]sql.Value{ {strVal("ssssssss"), i64Val(14)}, {strVal("ssssssss"), i64Val(46)}, {strVal("ssssssss"), i64Val(78)}, {strVal("ssssssss"), i64Val(110)}, {strVal("ssssssss"), i64Val(142)}, {strVal("ssssssss"), i64Val(174)}, {strVal("ttttttt"), i64Val(12)}, {strVal("ttttttt"), i64Val(44)}, {strVal("ttttttt"), i64Val(76)}, {strVal("ttttttt"), i64Val(108)}, {strVal("ttttttt"), i64Val(140)}, {strVal("ttttttt"), i64Val(172)}, }, values: [][]sql.Value{ {i64Val(14), i64Val(35), strVal("(((((((("), i64Val(7), strVal("ssssssss")}, {i64Val(46), i64Val(115), strVal("88888888"), i64Val(3), strVal("ssssssss")}, {i64Val(78), i64Val(195), strVal("HHHHHHHH"), i64Val(9), strVal("ssssssss")}, {i64Val(110), i64Val(275), strVal("XXXXXXXX"), i64Val(5), strVal("ssssssss")}, {i64Val(142), i64Val(355), strVal("hhhhhhhh"), i64Val(1), strVal("ssssssss")}, {i64Val(174), i64Val(435), strVal("xxxxxxxx"), i64Val(7), strVal("ssssssss")}, {i64Val(12), i64Val(30), strVal("'''''''"), i64Val(6), strVal("ttttttt")}, {i64Val(44), i64Val(110), strVal("7777777"), i64Val(2), strVal("ttttttt")}, {i64Val(76), i64Val(190), strVal("GGGGGGG"), i64Val(8), strVal("ttttttt")}, {i64Val(108), i64Val(270), strVal("WWWWWWW"), i64Val(4), strVal("ttttttt")}, {i64Val(140), i64Val(350), strVal("ggggggg"), i64Val(0), strVal("ttttttt")}, {i64Val(172), i64Val(430), strVal("wwwwwww"), i64Val(6), strVal("ttttttt")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-3"), minRow: []sql.Value{nil, nil, nil, nil, strVal("z")}, maxRow: []sql.Value{nil, nil, nil, nil, strVal("zz")}, idxValues: [][]sql.Value{ {strVal("z"), i64Val(32)}, {strVal("z"), i64Val(64)}, {strVal("z"), i64Val(96)}, {strVal("z"), i64Val(128)}, {strVal("z"), i64Val(160)}, {strVal("z"), i64Val(192)}, }, values: [][]sql.Value{ {i64Val(32), i64Val(80), strVal("1"), i64Val(6), strVal("z")}, {i64Val(64), i64Val(160), strVal("A"), i64Val(2), strVal("z")}, {i64Val(96), i64Val(240), strVal("Q"), i64Val(8), strVal("z")}, {i64Val(128), i64Val(320), strVal("a"), i64Val(4), strVal("z")}, {i64Val(160), i64Val(400), strVal("q"), i64Val(0), strVal("z")}, {i64Val(192), i64Val(480), strVal("'"), i64Val(6), strVal("z")}, }, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-3"), minRow: []sql.Value{nil, nil, nil, nil, strVal("zz")}, maxRow: []sql.Value{nil, nil, nil, nil, strVal("zzz")}, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, []storeCmd{ {fln: fln(), cmd: cmdBegin}, {fln: fln(), cmd: cmdLookupTable, name: sql.ID("tbl-b")}, {fln: fln(), cmd: cmdIndexRows, idxname: sql.ID("idx-3"), minRow: []sql.Value{nil, nil, nil, nil, strVal("zz")}, maxRow: nil, idxValues: nil, values: nil, }, {fln: fln(), cmd: cmdCommit}, }, } ) func makeValues(cnt int) [][]sql.Value { var vals [][]sql.Value for n := 1; n < cnt; n += 1 { vals = append(vals, []sql.Value{ i64Val(n * 2), i64Val(n * 5), strVal(strings.Repeat(string([]byte{byte((n % 90) + 33)}), (n%8)+1)), i64Val(n % 10), strVal(strings.Repeat(string([]byte{byte(122 - (n % 16))}), (n%16)+1)), }) } return vals } func pickColumns(cols []int, vals [][]sql.Value) [][]sql.Value { var rows [][]sql.Value for _, val := range vals { row := make([]sql.Value, len(cols)) for cdx, col := range cols { row[cdx] = val[col] } rows = append(rows, row) } return rows } func sortValues(key []sql.ColumnKey, vals [][]sql.Value) [][]sql.Value { testutil.SortValues(key, vals) return vals } func insertRows(nam sql.Identifier, rows [][]sql.Value) []storeCmd { var cmds []storeCmd cmds = append(cmds, storeCmd{fln: fln(), cmd: cmdBegin}) cmds = append(cmds, storeCmd{fln: fln(), cmd: cmdLookupTable, name: nam}) for _, row := range rows { cmds = append(cmds, storeCmd{fln: fln(), cmd: cmdInsert, row: row}) } cmds = append(cmds, storeCmd{fln: fln(), cmd: cmdCommit}) return cmds } func RunPrimaryMinMaxTest(t *testing.T, st *storage.Store) { t.Helper() dbname := sql.ID("primary_min_max_test") for _, test := range primaryMinMaxTests { runTest(t, st, dbname, test) } } func RunIndexMinMaxTest(t *testing.T, st *storage.Store) { t.Helper() for _, test := range index1MinMaxTests { runTest(t, st, sql.ID("index1_min_max_test"), test) } for _, test := range index2MinMaxTests { runTest(t, st, sql.ID("index2_min_max_test"), test) } for _, test := range index3MinMaxTests { runTest(t, st, sql.ID("index3_min_max_test"), test) } }
ralic/gnu_comma
include/comma/ast/AstRewriter.h
<reponame>ralic/gnu_comma //===-- ast/AstRewriter.h ------------------------------------- -*- C++ -*-===// // // This file is distributed under the MIT license. See LICENSE.txt for details. // // Copyright (C) 2008-2010, <NAME> // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// /// \file /// /// \brief Defines the AstRewriter class. //===----------------------------------------------------------------------===// #ifndef COMMA_AST_ASTREWRITER_HDR_GUARD #define COMMA_AST_ASTREWRITER_HDR_GUARD #include "comma/ast/AstBase.h" #include <map> namespace comma { /// \class AstRewriter /// \brief Rewrites Ast nodes. /// /// This class implements a map from one set of nodes to another. In some ways, /// it is like a scope where the components of an AST can be resolved with /// respect to the "bindings" established in the rewriter. For example, the /// AstRewriter can encapsulate the mappings from the formal to actual /// parameters of a generic package. /// /// Methods are provided to build and interrogate the set of mappings, and to /// create new nodes using the installed set of rules. class AstRewriter { public: /// Constructs an empty rewriter with no rewrite rules. AstRewriter(AstResource &resource) : resource(resource) { } /// Adds a rewrite rule from \p source to \p target. /// /// If a mapping from the given source already exists, this method will /// unconditionally re-target the rule -- it is the responsibility of the /// programmer to ensure that established rules are not mistakenly /// overwritten. void addTypeRewrite(Type *source, Type *target) { rewrites[source] = target; } /// \brief Adds a set of rewrites given by iterators over std::pair<Type*, /// Type*>. template <class Iter> void addTypeRewrites(Iter I, Iter E) { for ( ; I != E; ++I) rewrites[I->first] = I->second; } /// Returns true if a rewrite rule is associated with \p source. bool hasRewriteRule(Type *source) const { return getRewrite(source) != source; } /// Remove all rewrite rules. void clear() { rewrites.clear(); } /// \name Type Rewriters. /// /// \brief Rewrites the given type using the installed rules. /// /// If no rules apply to any component of the argument type, the argument is /// returned unchanged. If a rewrite rule does apply, then the a new /// rewritten type node is returned. //@{ Type *rewriteType(Type *type) const; SubroutineType *rewriteType(SubroutineType *srType) const; FunctionType *rewriteType(FunctionType *ftype) const; ProcedureType *rewriteType(ProcedureType *ftype) const; //@} // Returns the AstResource used to construct rewritten nodes. AstResource &getAstResource() const { return resource; } protected: /// Returns a rewrite if it exists, otherwise null. Type *findRewrite(Type *source) const; private: AstResource &resource; typedef std::map<Type*, Type*> RewriteMap; RewriteMap rewrites; /// \brief Returns a reference to a target entry in the rewriter /// corresponding to source. /// /// If a mapping for \p source has not been installed the returned value is /// null. Type *&operator [](Type *source) { return rewrites[source]; } /// \brief Maps \p source to a new target if a rewrite rule exists, /// otherwise returns \p source. Type *getRewrite(Type *source) const; /// \brief Rewrites \p count parameter types of the given subroutine, /// placing the results of the rewrite in \p params. void rewriteParameters(SubroutineType *srType, unsigned count, Type **params) const; }; } // End comma namespace #endif
pandashuai/ddpAdmin
plugins/photoswipe.js
import Vue from 'vue'; import PhotoSwipe from 'photoswipe'; import PhotoswipeDefault from 'photoswipe/dist/photoswipe-ui-default.js'; Vue.prototype.onImgBd = function(e) { const pswpElement = document.getElementById('onImgBd'); const w = e.currentTarget.naturalWidth; const h = e.currentTarget.naturalHeight; const src = e.currentTarget.src; const items = [{ src, w, h }]; const options = { index: 0, closeOnScroll: false, shareEl: false }; const gallery = new PhotoSwipe(pswpElement, PhotoswipeDefault, items, options); gallery.init(); } export default { PhotoSwipe, PhotoswipeDefault }
MoeOrganization/moe
src/main/scala/org/moe/interpreter/guts/Subroutines.scala
package org.moe.interpreter.guts import org.moe.interpreter._ import org.moe.runtime._ import org.moe.runtime.nativeobjects._ import org.moe.ast._ object Subroutines extends Utils { def declaration (i: MoeInterpreter, r: MoeRuntime): PartialFunction[(MoeEnvironment, AST), MoeObject] = { case (env, SubroutineDeclarationNode(name, signature, body, traits)) => { val sig = i.compile(env, signature).asInstanceOf[MoeSignature] throwForUndeclaredVars(env, sig, body) val pkg = getCurrentPackage(env) val decl_env = new MoeEnvironment(Some(env)) decl_env.setCurrentPackage(pkg) val sub = r.NativeObjects.fixupSubroutine( new MoeSubroutine( name = name, signature = sig, declaration_env = decl_env, body = (e) => i.evaluate(e, body), traits = traits.getOrElse(List()).map(MoeSubroutineTraits.withName(_)) ) ) pkg.addSubroutine(sub) sub } } def apply (i: MoeInterpreter, r: MoeRuntime): PartialFunction[(MoeEnvironment, AST), MoeObject] = { case (env, SubroutineCallNode(function_name, args)) => { val sub = r.lookupSubroutine(function_name, getCurrentPackage(env)).getOrElse( throw new MoeErrors.SubroutineNotFound(function_name) ) val evaluated_args = args.map(i.evaluate(env, _)) i.pushCallStack(new MoeStackFrame(sub, evaluated_args, env)) val result = sub.execute(new MoeArguments(evaluated_args)) i.popCallStack result } } }
jpederzolli/finagle
finagle-httpx/src/main/scala/com/twitter/finagle/httpx/Cookie.scala
package com.twitter.finagle.httpx import com.twitter.conversions.time._ import com.twitter.util.Duration import org.jboss.netty.handler.codec.http.{Cookie => NettyCookie, DefaultCookie} import scala.collection.JavaConverters._ /** Scala wrapper around Netty cookies. */ class Cookie(private[httpx] val underlying: NettyCookie) { def this(name: String, value: String) = { this(new DefaultCookie(name, value)) } def comment: String = underlying.getComment def commentUrl: String = underlying.getCommentUrl def domain: String = underlying.getDomain def maxAge: Duration = underlying.getMaxAge.seconds def name: String = underlying.getName def path: String = underlying.getPath def ports: Set[Int] = underlying.getPorts.asScala.toSet map { i: Integer => i.intValue } def value: String = underlying.getValue def version: Int = underlying.getVersion def httpOnly: Boolean = underlying.isHttpOnly def isDiscard: Boolean = underlying.isDiscard def isSecure: Boolean = underlying.isSecure def comment_=(comment: String) { underlying.setComment(comment) } def commentUrl_=(commentUrl: String) { underlying.setCommentUrl(commentUrl) } def domain_=(domain: String) { underlying.setDomain(domain) } def maxAge_=(maxAge: Duration) { underlying.setMaxAge(maxAge.inSeconds) } def path_=(path: String) { underlying.setPath(path) } def ports_=(ports: Seq[Int]) { underlying.setPorts(ports: _*) } def value_=(value: String) { underlying.setValue(value) } def version_=(version: Int) { underlying.setVersion(version) } def httpOnly_=(httpOnly: Boolean) { underlying.setHttpOnly(httpOnly) } def isDiscard_=(discard: Boolean) { underlying.setDiscard(discard) } def isSecure_=(secure: Boolean) { underlying.setSecure(secure) } override def equals(obj: Any): Boolean = obj match { case c: Cookie => underlying.equals(c.underlying) case _ => false } override def hashCode(): Int = underlying.hashCode() }
suy/frida-gum
bindings/gumjs/gumquickthread.c
/* * Copyright (C) 2020 <NAME> <<EMAIL>> * * Licence: wxWindows Library Licence, Version 3.1 */ #include "gumquickthread.h" #include "gumquickmacros.h" enum _GumBacktracerType { GUM_BACKTRACER_ACCURATE = 1, GUM_BACKTRACER_FUZZY = 2 }; GUMJS_DECLARE_FUNCTION (gumjs_thread_backtrace) GUMJS_DECLARE_FUNCTION (gumjs_thread_sleep) static const JSCFunctionListEntry gumjs_thread_entries[] = { JS_CFUNC_DEF ("backtrace", 0, gumjs_thread_backtrace), JS_CFUNC_DEF ("sleep", 0, gumjs_thread_sleep), }; static const JSCFunctionListEntry gumjs_backtracer_entries[] = { JS_PROP_INT32_DEF ("ACCURATE", GUM_BACKTRACER_ACCURATE, JS_PROP_C_W_E), JS_PROP_INT32_DEF ("FUZZY", GUM_BACKTRACER_FUZZY, JS_PROP_C_W_E), }; void _gum_quick_thread_init (GumQuickThread * self, JSValue ns, GumQuickCore * core) { JSContext * ctx = core->ctx; JSValue obj; self->core = core; _gum_quick_core_store_module_data (core, "thread", self); obj = JS_NewObject (ctx); JS_SetPropertyFunctionList (ctx, obj, gumjs_thread_entries, G_N_ELEMENTS (gumjs_thread_entries)); JS_DefinePropertyValueStr (ctx, ns, "Thread", obj, JS_PROP_C_W_E); obj = JS_NewObject (ctx); JS_SetPropertyFunctionList (ctx, obj, gumjs_backtracer_entries, G_N_ELEMENTS (gumjs_backtracer_entries)); JS_DefinePropertyValueStr (ctx, ns, "Backtracer", obj, JS_PROP_C_W_E); } void _gum_quick_thread_dispose (GumQuickThread * self) { } void _gum_quick_thread_finalize (GumQuickThread * self) { g_clear_pointer (&self->accurate_backtracer, g_object_unref); g_clear_pointer (&self->fuzzy_backtracer, g_object_unref); } static GumQuickThread * gumjs_get_parent_module (GumQuickCore * core) { return _gum_quick_core_load_module_data (core, "thread"); } GUMJS_DEFINE_FUNCTION (gumjs_thread_backtrace) { JSValue result; GumQuickThread * self; GumCpuContext * cpu_context = NULL; gint selector = GUM_BACKTRACER_ACCURATE; GumBacktracer * backtracer; GumReturnAddressArray ret_addrs; guint i; self = gumjs_get_parent_module (core); if (!_gum_quick_args_parse (args, "|C?i", &cpu_context, &selector)) return JS_EXCEPTION; if (selector != GUM_BACKTRACER_ACCURATE && selector != GUM_BACKTRACER_FUZZY) goto invalid_selector; if (selector == GUM_BACKTRACER_ACCURATE) { if (self->accurate_backtracer == NULL) self->accurate_backtracer = gum_backtracer_make_accurate (); backtracer = self->accurate_backtracer; } else { if (self->fuzzy_backtracer == NULL) self->fuzzy_backtracer = gum_backtracer_make_fuzzy (); backtracer = self->fuzzy_backtracer; } if (backtracer == NULL) goto not_available; gum_backtracer_generate (backtracer, cpu_context, &ret_addrs); result = JS_NewArray (ctx); for (i = 0; i != ret_addrs.len; i++) { JS_DefinePropertyValueUint32 (ctx, result, i, _gum_quick_native_pointer_new (ctx, ret_addrs.items[i], core), JS_PROP_C_W_E); } return result; invalid_selector: { return _gum_quick_throw_literal (ctx, "invalid backtracer enum value"); } not_available: { return _gum_quick_throw_literal (ctx, (selector == GUM_BACKTRACER_ACCURATE) ? "backtracer not yet available for this platform; " "please try Thread.backtrace(context, Backtracer.FUZZY)" : "backtracer not yet available for this platform; " "please try Thread.backtrace(context, Backtracer.ACCURATE)"); } } GUMJS_DEFINE_FUNCTION (gumjs_thread_sleep) { GumQuickScope scope = GUM_QUICK_SCOPE_INIT (core); gdouble delay; if (!_gum_quick_args_parse (args, "n", &delay)) return JS_EXCEPTION; if (delay < 0) return JS_UNDEFINED; _gum_quick_scope_suspend (&scope); g_usleep (delay * G_USEC_PER_SEC); _gum_quick_scope_resume (&scope); return JS_UNDEFINED; }
jhannes/action-controller
action-controller/src/main/java/org/actioncontroller/actions/POST.java
<gh_stars>1-10 package org.actioncontroller.actions; import org.actioncontroller.ApiControllerContext; import org.actioncontroller.ApiControllerMethodAction; import org.actioncontroller.meta.ApiControllerActionFactory; import org.actioncontroller.meta.HttpRouterMapping; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; /** * Specifies that this method should handle HTTP POST requests * * @see HttpRouterMapping */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @HttpRouterMapping(POST.ActionFactory.class) public @interface POST { String value(); class ActionFactory implements ApiControllerActionFactory<POST> { @Override public ApiControllerMethodAction create(POST annotation, Object controller, Method action, ApiControllerContext context) { return new ApiControllerMethodAction("POST", annotation.value(), controller, action, context); } } }
moisespsena-go/aorm
modelstruct.go
package aorm import ( "context" "fmt" "reflect" "strings" "github.com/pkg/errors" "github.com/jinzhu/inflection" ) // DefaultTableNameHandler default table name handler var DefaultTableNameHandler = func(ctx context.Context, singular bool, modelStruct *ModelStruct) (tableName string) { if singular { return modelStruct.SingularTableName } return modelStruct.PluralTableName } // ModelStruct model definition type ModelStruct struct { storage *ModelStructStorage TableNameResolver func(ctx context.Context, singular bool) (tableName string) Value interface{} PrimaryFields []*StructField Fields []*StructField RelatedFields []*StructField ReadOnlyFields []*StructField DynamicFieldsByName map[string]*StructField Type reflect.Type PluralTableName string SingularTableName string FieldsByName map[string]*StructField IgnoredFieldsCount int BeforeRelatedCallbacks []func(fromScope *Scope, toScope *Scope, db *DB, fromField *Field) *DB virtualFields map[string]*VirtualField virtualFieldsByIndex []*VirtualField virtualFieldsAutoInlinePreload []string softDelete bool Indexes IndexMap UniqueIndexes IndexMap } func (this *ModelStruct) Fqn() string { return this.Type.PkgPath() + "." + this.Type.Name() } func (this *ModelStruct) BeforeRelatedCallback(cb ...func(fromScope *Scope, toScope *Scope, db *DB, fromField *Field) *DB) { this.BeforeRelatedCallbacks = append(this.BeforeRelatedCallbacks, cb...) } // tableName get model's table name func (this *ModelStruct) TableName(ctx context.Context, singular bool) string { if ctx == nil { ctx = context.Background() } if this.TableNameResolver != nil { if tableName := this.TableNameResolver(ctx, singular); tableName != "" { return tableName } } if this.PluralTableName == "" && this.Type != nil { // Set default table name if tabler, ok := this.Value.(TableNamePlurabler); ok { this.PluralTableName = tabler.TableName(false) this.SingularTableName = tabler.TableName(true) } else if tabler, ok := this.Value.(TableNamer); ok { this.PluralTableName = tabler.TableName() this.SingularTableName = this.PluralTableName } else { this.SingularTableName = ToDBName(this.Type.Name()) this.PluralTableName = inflection.Plural(this.SingularTableName) } } return DefaultTableNameHandler(ctx, singular, this) } func (this *ModelStruct) IsSoftDelete() bool { return this.softDelete } func (this *ModelStruct) SetVirtualField(fieldName string, value interface{}) *VirtualField { if this.virtualFields != nil { if _, ok := this.virtualFields[fieldName]; ok { panic(fmt.Errorf("Duplicate virtual field %q", fieldName)) } } else { this.virtualFields = map[string]*VirtualField{} } var ms, err = this.storage.GetOrNew(value) if err != nil { panic(err) } vf := &VirtualField{ ModelStruct: ms, FieldName: fieldName, StructIndex: len(this.virtualFieldsByIndex), Value: value, Options: map[interface{}]interface{}{}, } this.virtualFieldsByIndex = append(this.virtualFieldsByIndex, vf) this.virtualFields[fieldName] = vf return vf } func (this *ModelStruct) GetVirtualField(fieldName string) *VirtualField { if this.virtualFields == nil { return nil } return this.virtualFields[fieldName] } // GetNonIgnoredStructFields get non ignored model's field structs func (this *ModelStruct) NonIgnoredStructFields() []*StructField { fields := make([]*StructField, len(this.Fields)-this.IgnoredFieldsCount) var i int for _, field := range this.Fields { if !field.IsIgnored { fields[i] = field i++ } } return fields } // NonRelatedStructFields get non ignored model's field structs func (this *ModelStruct) NonRelatedStructFields() []*StructField { fields := make([]*StructField, len(this.Fields)-this.IgnoredFieldsCount) var i int for _, field := range this.Fields { if !field.IsIgnored && field.Relationship == nil && field.TagSettings["FOREIGNKEY"] == "" { fields[i] = field i++ } } return fields[0:i] } // GetNonIgnoredStructFields get non ignored model's field structs func (this *ModelStruct) NormalStructFields() (fields []*StructField) { for _, field := range this.Fields { if !field.IsIgnored && !field.IsForeignKey { fields = append(fields, field) } } return fields } // AutoInlinePreload set default auto inline preload virtual field names func (this *ModelStruct) AutoInlinePreload(virtualFieldName ...string) { this.virtualFieldsAutoInlinePreload = append(this.virtualFieldsAutoInlinePreload, virtualFieldName...) } // FieldDiscovery discovery field from name or path func (this *ModelStruct) FieldDiscovery(pth string) (field *StructField, virtualField *VirtualField) { currentModelStruct := this parts := strings.Split(pth, ".") for _, fieldName := range parts[0 : len(parts)-1] { if f, ok := currentModelStruct.FieldsByName[fieldName]; ok { typ := f.Struct.Type switch typ.Kind() { case reflect.Slice, reflect.Ptr: typ = typ.Elem() } currentModelStruct = modelStructsMap.Get(typ) } else { if vfield := currentModelStruct.GetVirtualField(fieldName); vfield == nil { return } else { currentModelStruct = vfield.ModelStruct } } } fieldName := parts[len(parts)-1] var ok bool if field, ok = currentModelStruct.FieldsByName[fieldName]; !ok { virtualField = currentModelStruct.GetVirtualField(fieldName) } return } func (this *ModelStruct) SetIdFromString(record interface{}, idstr string) (err error) { var id ID if id, err = this.ParseIDString(idstr); err != nil { return } id.SetTo(record) return } func (this *ModelStruct) GetID(record interface{}) ID { if record == nil { return nil } var ( rv reflect.Value ok bool ) if rv, ok = record.(reflect.Value); !ok { rv = reflect.ValueOf(record) } rv = indirect(rv) switch len(this.PrimaryFields) { case 0: return nil default: var values []IDValuer for _, f := range this.PrimaryFields { rv := rv.FieldByIndex(f.StructIndex) if valuer, err := f.IDOf(rv.Interface()); err != nil { panic(errors.Wrapf(err, "field %s#%q", this.Fqn(), f.Name)) } else { values = append(values, valuer) } } return NewId(this.PrimaryFields, values) } } func (this *ModelStruct) PrimaryFieldsInstance(value interface{}) (fields []*Field) { if value == nil { return } var ( indirectScopeValue = indirect(reflect.ValueOf(value)) ) if indirectScopeValue.Kind() != reflect.Struct { return } for _, structField := range this.PrimaryFields { fieldValue := indirectScopeValue.FieldByIndex(structField.StructIndex) fields = append(fields, &Field{StructField: structField, Field: fieldValue, IsBlank: IsBlank(fieldValue)}) } return } // RealTableName get real table name func (this *ModelStruct) RealTableName(ctx context.Context, singular bool) (name string) { if tabler, ok := this.Value.(TableNamer); ok { return tabler.TableName() } return this.TableName(ctx, singular) } // PrimaryField return main primary field, if defined more that one primary fields, will return the one having column name `id` or the first one func (this *ModelStruct) PrimaryField() *StructField { if len(this.PrimaryFields) > 0 { for _, f := range this.PrimaryFields { if f.DBName == "id" { return f } } return this.PrimaryFields[0] } return nil } // HasID returns if has main primary field func (this *ModelStruct) HasID() bool { return len(this.PrimaryFields) > 0 } // FieldByPath return field byte path func (this *ModelStruct) FieldByPath(pth string) (field *StructField) { fields := strings.Split(pth, ".") self := this var err error for i, field := range fields[:len(fields)-1] { if self, err = this.storage.GetOrNew(self.FieldsByName[field].Struct.Type); err != nil { panic(errors.Wrapf(err, "path %q", strings.Join(fields[0:i], "."))) } } return self.FieldsByName[fields[len(fields)-1]] } // UniqueIdexesNamesMap return unique idexes by index name map func (this *ModelStruct) UniqueIdexesNamesMap(namer KeyNamer, tableName string) map[string]*StructIndex { var result = make(map[string]*StructIndex) for _, ix := range this.UniqueIndexes { result[ix.BuildName(namer, tableName)] = ix } return result } func (this *ModelStruct) DefaultID() ID { var values = make([]IDValuer, len(this.PrimaryFields), len(this.PrimaryFields)) for i, f := range this.PrimaryFields { var err error values[i], err = f.DefaultID() if err != nil { panic(err) } } return NewId(this.PrimaryFields, values) }
ProjectBuddyTeam/ProjectBuddy
app/policies/project/question_policy.rb
class Project::QuestionPolicy < ApplicationPolicy attr_reader :member, :question, :project def initialize(member, question) @member = member @project = question.project @question = question end def create? member != project.member end def update? member == question.member end def update_answer? member == project.member end def edit_answer? update_answer? end class Scope < Scope def resolve scope end end end
Maufeat/LeagueAPI
include/lol/op/PutLolCollectionsV1InventoriesBySummonerIdRuneBookPagesByPageId.hpp
<reponame>Maufeat/LeagueAPI<filename>include/lol/op/PutLolCollectionsV1InventoriesBySummonerIdRuneBookPagesByPageId.hpp #pragma once #include "../base_op.hpp" #include <functional> #include "../def/LolCollectionsCollectionsRunePage.hpp" namespace lol { template<typename T> inline Result<LolCollectionsCollectionsRunePage> PutLolCollectionsV1InventoriesBySummonerIdRuneBookPagesByPageId(T& _client, const uint64_t& summonerId, const uint32_t& pageId, const LolCollectionsCollectionsRunePage& resource) { try { return ToResult<LolCollectionsCollectionsRunePage>(_client.https.request("put", "/lol-collections/v1/inventories/"+to_string(summonerId)+"/rune-book/pages/"+to_string(pageId)+"?" + SimpleWeb::QueryString::create(Args2Headers({ })), json(resource).dump(), Args2Headers({ {"content-type", "application/json"}, {"Authorization", _client.auth}, }))); } catch(const SimpleWeb::system_error &e) { return ToResult<LolCollectionsCollectionsRunePage>(e.code()); } } template<typename T> inline void PutLolCollectionsV1InventoriesBySummonerIdRuneBookPagesByPageId(T& _client, const uint64_t& summonerId, const uint32_t& pageId, const LolCollectionsCollectionsRunePage& resource, std::function<void(T&, const Result<LolCollectionsCollectionsRunePage>&)> cb) { _client.httpsa.request("put", "/lol-collections/v1/inventories/"+to_string(summonerId)+"/rune-book/pages/"+to_string(pageId)+"?" + SimpleWeb::QueryString::create(Args2Headers({ })), json(resource).dump(), Args2Headers({ {"content-type", "application/json"}, {"Authorization", _client.auth}, }),[cb,&_client](std::shared_ptr<HttpsClient::Response> response, const SimpleWeb::error_code &e) { if(e) cb(_client, ToResult<LolCollectionsCollectionsRunePage>(e)); else cb(_client, ToResult<LolCollectionsCollectionsRunePage>(response)); }); } }
indraai/IndraMind
_archive/modules/SpreadAct.js
<gh_stars>1-10 function SpreadAct() { // http://ai.neocities.org/SpreadAct.html PsiDecay(); // 2018-01-23: reduce conceptual activation in general. // 2018-11-13: SpreadAct, called from EnVerbPhrase, activates a prepositional phrase. if (wherecon == 0) { // 2018-11-13: if not answering a where-query... if (tselp > 0 && prep > 0 && wherecon == 0) { // 2018-11-13: fpr prep. phrase Psy[tselp].psyExam(); // 2018-11-13: Examine the Psy concept-array. tselo = psi13; // 2018-11-13: time of selection of object of preposition. aud = psi14; // 2018-11-13: fetch the "aud" recall-tag for sake of Speech() if (aud > 0) Speech(); // 20-18-11-13: speak the preposition. EnArticle(); // 2018-11-13: say "A" or "THE" before object of preposition. Psy[tselo].psyExam(); // 2018-11-13: examine concept-array at time of object. aud = psi14; // 2018-11-13: fetch the "aud" tag for the sake of Speech() if (aud > 0) Speech(); // 2018-11-13: speak the object of the preposition. aud = 0; // 2018-11-13: reset for safety. prep = 0; // 2018-11-13: reset for safety. tselo = 0; // 2018-11-13: reset for safety. tselp = 0; // 2018-11-13: reset for safety. return; // 2018-11-13: skip the remainder of SpreadAct() } // 2018-11-13: end of test for time-point and concept-number of preposition. } // 2018-11-13: end of test for a positive "wherecon". // 2018-10-28: segment of SpreaAct() responds to where-queries. if (wherecon==1) { // 2018-10-28: if (qv1psi > 0) { // 2018-10-28: if there is an activand subject... for (i=tpu; i>midway; i--) { // 2018-10-28: search backwards in time. Psy[i].psyExam(); // 2018-01-23: examine the Psy concept array... if (psi1 == qv1psi && psi13 > 0) { // 2018-10-28: require verblock. if (psi1 == qv1psi && psi12 == qv2psi) { // 2018-10-28: if correct verb psi3 = (psi3 + 256); // 2018-10-28: impose an overriding activation. Psy[i] = new // 2018-10-28: inserting [psi3]act with higher activation: psyNode(psi0,psi1,psi2,psi3,psi4,psi5,psi6,psi7,psi8,psi9,psi10,psi11,psi12,psi13,psi14); } // 2018-10-28: end of test for finding both subject and verb of query. } // 2018-10-28: end of test for presence of a psi13 tkb verblock. } // 2018-10-28: end of (for loop) searching for qv1psi subject concept. } // 2018-10-28: end of test for a positive qv1psi. return; // 2018-10-28: skip the remainder of SpreadAct() } // 2018-10-28: end of test for a positive "wherecon". // 2018-10-02: segment of SpreaAct() responds to WHO-queries. if (qucon > 0 && qvdocon == 0) { // 2018-01-23: only for 800=BE who-queries. if (qv1psi > 0) { // 2018-01-28: if there is an activand subject... for (i=tpu; i>midway; i--) { // 2018-01-23: search backwards in time. Psy[i].psyExam(); // 2018-01-23: examine the Psy concept array... if (psi1 == qv1psi && psi13 > 0) { // 2018-01-23: require verblock. if (psi1 == qv1psi && psi12 == qv2psi) { // 2018-01-23: if correct verb psi3 = (psi3 + 64); // 2018-01-23: impose an overriding activation. Psy[i] = new // 2018-01-23: inserting [psi3]act with higher activation: psyNode(psi0,psi1,psi2,psi3,psi4,psi5,psi6,psi7,psi8,psi9,psi10,psi11,psi12,psi13,psi14); } // 2018-01-23: end of test for finding both subject and verb of query. } // 2018-01-23: end of test for presence of a psi13 tkb verblock. } // 2018-01-23: end of (for loop) searching for qv1psi subject concept. } // 2018-01-23: end of test for a positive qv1psi. qvdocon = 0; // 2018-06-16: TEST return; // 2018-06-05: skip the remainder of SpreadAct() } // 2018-01-23: end of test of qucon to indicate processing of a query. // 2018-10-02: segment of SpreaAct() responds to WHAT-think-queries. if (whatcon > 0 && qv2psi==840) { // 2018-10-01: for a what-think query... // alert("SpreadAct: qv2psi= "+qv2psi); // 2018-10-01: TEST } // 2018-10-01: end of test of whatcon so as to answer a what-think query. // 2018-10-02: segment of SpreaAct() responds to WHAT-queries. if (whatcon > 0) { // 2018-10-01: for a what-query... dunnocon = 1; // 2018-10-01: set positive so long as no answer emerges. for (i=tpu; i>midway; i--) { // 2018-10-02: search backwards in time. Psy[i].psyExam(); // 2018-10-02: examine conceptual Psy array; if (psi1==qv1psi && psi12==qv2psi) { // 2018-10-02: subj. with query-verb? dunnocon = 0; // 2018-02-10: even one correct answer disables dunnocon. psi3 = (psi3 + 64); // 2018-10-02: impose activation on the found subject. Psy[i] = new // 2018-10-02: inserting [psi3]act with higher activation: psyNode(psi0,psi1,psi2,psi3,psi4,psi5,psi6,psi7,psi8,psi9,psi10,psi11,psi12,psi13,psi14); } // 2018-10-02: end of test for subject and verb answer-concepts. } // 2018-10-02: end of (for loop) searching for qv1psi subject-noun concept. return; // 2018-10-02: skip the remainder of SpreadAct() } // 2018-10-01: end of test of whatcon so as to answer a what-query. if (whatcon > 0) { // 2018-01-23: for a what-query... for (i=tpu; i>midway; i--) { // 2018-01-23: search backwards in time. if (psi1==qv1psi && psi13==0 && qv2psi==840) { // 2018-05-13: if subj of THINK query... psi3 = (psi3 + 64); // 2018-06-11: impose activation on the found subject. Psy[i] = new // 2018-05-13: inserting [psi3]act with higher activation: psyNode(psi0,psi1,psi2,psi3,psi4,psi5,psi6,psi7,psi8,psi9,psi10,psi11,psi12,psi13,psi14); } // 2018-06-03: end of test for WHAT... 840=THINK. if (psi1==840 && qv2psi==840) { // 2018-05-13: if 840=THINK query... psi3 = (psi3 + 64); // 2018-06-11: impose activation on the found verb. Psy[i] = new // 2018-05-13: inserting [psi3]act with higher activation: psyNode(psi0,psi1,psi2,psi3,psi4,psi5,psi6,psi7,psi8,psi9,psi10,psi11,psi12,psi13,psi14); } // 2018-05-13: end of test for WHAT... 840=THINK. } // 2018-01-23: end of (for loop) searching for qv1psi subject-noun concept. for (i = idle; i<1000; i++) { // 2018-01-23: delay for user to see question if (i > 1) { apb = "Ask the AI what it thinks!"; Voice() } // 2018-05-13 } // 2018-01-23: end of delay for TEST return; // 2018-06-05: skip the remainder of SpreadAct() } // 2018-01-23: end of test of whatcon so as to answer a what-query. if (qvdocon > 0) { // 2018-01-23: for a who+verb+dir.object query... dunnocon = 1; // 2018-01-23: set positive so long as no answer emerges. for (i=tpu; i>midway; i--) { // 2018-01-23: search backwards in time. Psy[i].psyExam(); // 2018-01-23: inspect the Psy concept flag-panel if (psi1==qv2psi && psi10>0 && psi12==qv4psi && psi13>0) { // 2018-01-23 qv2num = psi8; // 2018-01-23: latch onto psi8 "num" of the response-verb. qv1psi = psi10; // 2018-01-23: latch onto psi10 "pre" as the subject (answer) psi3 = (psi3 + 64); // 2018-06-11: somewhat activate the answer-concept Psy[i] = new // 2018-01-23: inserting [psi3]act with higher activation: psyNode(psi0,psi1,psi2,psi3,psi4,psi5,psi6,psi7,psi8,psi9,psi10,psi11,psi12,psi13,psi14); } // 2018-01-23: end of test for presence of a psi13 "tkb" nounlock. } // 2018-01-23: end of (for loop) searching for qv2psi verb concept. qucon = 0; // 2018-01-23: prevent infinite loop? // if (dunnocon == 1) output = "I DO NOT KNOW"; // 2018-01-23: temporary for (i=tpu; i>midway; i--) { // 2018-01-23: search backwards in time. Psy[i].psyExam(); // 2018-01-23: inspect the Psy concept flag-panel if (psi1==qv1psi) { // 2018-06-16: if correct subject aud = psi14; // 2018-01-23: fetch auditory recall tag for Speech() Speech(); // 2018-01-23: speak the answer concept, thus activating it. break; // 2018-01-23: one utterance is enough. } // 2018-01-23: end of test for subject answer-concept } // 2018-01-23: end of (for loop) searching for the subject answer-concept. for (i=tpu; i>midway; i--) { // 2018-01-23: search backwards in time. Psy[i].psyExam(); // 2018-01-23: inspect the Psy concept flag-panel if (psi1==qv1psi && psi12==qv4psi) { // 2018-01-23: subj. with dir.obj. psi3 = (psi3 + 64); // 2018-01-23: impose an overriding activation. Psy[i] = new // 2018-01-23: inserting [psi3]act with higher activation: psyNode(psi0,psi1,psi2,psi3,psi4,psi5,psi6,psi7,psi8,psi9,psi10,psi11,psi12,psi13,psi14); } // 2018-01-23: end of test for subject answer-concept } // 2018-01-23: end of (for loop) searching for the subject answer-concept. qvdocon = 0; // 2018-06-16: reset for safety. return; // 2018-06-05: skip the remainder of SpreadAct() } // 2018-01-23: end of test for who+verb+direct-object query condition. if (qviocon > 0) { // 2018-01-23: prepare for indirect-object queries... // alert("SpreadAct has been called."); // 2018-01-23: for future implementation } // 2018-01-23: end of test for who+verb+indirect-object query condition. if (hlc != "ru") { // 2018-01-20: English by default, but for any language. if (nucon > 0) { // 2018-01-23: if there is a new-concept condition... moot = 1; // 2018-01-23: prevent associative tags within question. output = ""; // 2018-01-23: clear the display of output. for (i=tpu; i>midway; i--) { // 2018-01-23: search backwards in time. Psy[i].psyExam(); // 2018-01-23: inspect the Psy concept flag-panel if (psi1 == 781 && psi13 == 0) { // 2018-01-23: WHAT without verblock. aud = psi14; // 2018-01-23: fetch auditory recall tag for Speech() Speech(); // 2018-01-23: speak the 781=WHAT break; // 2018-01-23: one utterance is enough. } // 2018-01-23: end of test for 781=WHAT with no overriding verblock. } // 2018-01-23: end of (for loop) searching for 781=WHAT concept. // if (endpho == "S") qusubnum = 2; // 2018-10-14: assume plural if "-S" if (b16 == "S") qusubnum = 2; // 2018-10-14: if "-S" in OutBuffer for (i=vault; i>midway; i--) { // 2018-01-23: search backwards in "vault" Psy[i].psyExam(); // 2018-01-23: inspect the Psy concept flag-panel if (qusubnum == 0) qusubnum = 1; // 2018-10-03: default to singular. if (psi1==800 && psi7==3 && psi8==qusubnum) { // 2018-10-03 aud = psi14; // 2018-01-23: fetch auditory recall tag for Speech() Speech(); // 2018-01-23: speak the 800=BE break; // 2018-01-23: one utterance is enough. } // 2018-01-23: end of test for 800=BE } // 2018-01-23: end of (for loop) searching for correct form of 800=BE. for (i=t; i>midway; i--) { // 2018-10-03: must include new input. Psy[i].psyExam(); // 2018-01-23: inspect the Psy concept flag-panel if (psi1 == qusub) { // 2018-01-23: look for the new concept. aud = psi14; // 2018-01-23: fetch auditory recall tag for Speech() Speech(); // 2018-01-23: speak the new concept qusub = 0; // 2018-06-11: reset for safety. break; // 2018-01-23: one utterance is enough. } // 2018-01-23: end of test for engram of new concept. } // 2018-01-23: end of (for loop) searching for the new concept. Voice(); // 2018-09-21: makes the question appear on-screen. moot = 0; // 2018-01-23: finish preventing associative tags within question. return; // 2018-06-05: skip the remainder of SpreadAct() } // 2018-01-23: end of test of nucon so as to cause asking of a question. } // 2018-01-23: end of English by default while preserving option of language. if (actpsi > 0 && qucon == 0) { // 2018-01-12: not with who-queries for (i=tpu; i>midway; --i) { // 2018-01-12: search backward from tpu Psy[i].psyExam(); // 2018-01-12: examine the Psy concept array... if (psi1 == actpsi && psi12 > 0) seqpsi = psi12; // 2018-01-12: if seq, seqpsi if (psi1 == actpsi && psi13 > 0) { // 2018-01-12: require verblock. psi3 = (psi3 + 64); // 2018-06-03: impose plenty of activation. Psy[i] = new // 2018-06-11: moving "new" up from next line: psyNode(psi0,psi1,psi2,psi3,psi4,psi5,psi6,psi7,psi8,psi9,psi10,psi11,psi12,psi13,psi14); } // 2018-01-12: end of test requiring tkb verblock. } // 2018-01-12: end of (for loop) searching for actpsi concept. } // 2018-01-12: end of test for a positive actpsi. qvdocon = 0; // 2018-06-16: reset for safety. } // 2018-10-02: SpreadAct() returns to Sensorium() or to.... module.exports = SpreadAct;
iugu-for-devs/codeplay
spec/fabricators/subscription_course_fabricator.rb
<filename>spec/fabricators/subscription_course_fabricator.rb<gh_stars>1-10 Fabricator(:subscription_course) do course nil subscription nil end
sgholamian/log-aware-clone-detection
NLPCCd/Camel/562_2.java
//,temp,sample_3270.java,2,9,temp,sample_4992.java,2,8 //,3 public class xxx { protected void doStart() throws Exception { ObjectHelper.notNull(executorService, "executorService", this); ObjectHelper.notNull(endpoint, "endpoint", this); log.info("using timeout checker interval with millis"); } };
megadotnet/talk-android
app/src/main/java/com/teambition/talk/view/RepostView.java
package com.teambition.talk.view; import com.teambition.talk.entity.Message; import com.teambition.talk.entity.Team; /** * Created by wlanjie on 15/8/3. */ public interface RepostView extends TeamView { void onRepostFinish(Message message); void onGetTeamDetailFinish(Team data); }
aevum/libgdx-cpp
src/gdx-cpp/graphics/g3d/materials/TextureAttribute.hpp
<gh_stars>10-100 /* * TextureAttribute.hpp * * Created on: Feb 20, 2013 * Author: toha */ #ifndef TEXTUREATTRIBUTE_HPP_ #define TEXTUREATTRIBUTE_HPP_ #include "MaterialAttribute.hpp" #include "gdx-cpp/graphics/Texture.hpp" #include "gdx-cpp/utils/Pool.hpp" using namespace gdx; class TextureAttribute: public MaterialAttribute { public: const static int MAX_TEXTURE_UNITS = 16; const static char* diffuseTexture; const static char* lightmapTexture; const static char* specularTexture; Texture* texture; int unit; int minFilter; int magFilter; int uWrap; int vWrap; TextureAttribute ( const Texture& texture, int unit, const char* name, const Texture::TextureFilter& minFilter, const Texture::TextureFilter& magFilter, const Texture::TextureWrap& uWarp, const Texture::TextureWrap& vWarp ); TextureAttribute ( const Texture& texture, int unit, const char* name, int minFilter, int magFilter,int uWrap, int vWrap ); TextureAttribute ( const Texture& texture, int unit, const char* name ); void bind() override; void bind ( ShaderProgram& program ) override; MaterialAttribute& copy() override; void set ( MaterialAttribute& attr ) override; bool texturePortionEquals ( const TextureAttribute* other ); MaterialAttribute& pooledCopy() override; void free() override; virtual ~TextureAttribute(); private: static Pool<TextureAttribute> pool; public: TextureAttribute(); }; #endif /* TEXTUREATTRIBUTE_HPP_ */
Lakshamana/spm-mini
src/main/java/br/ufpa/labes/spm/service/interfaces/JoinConServices.java
<filename>src/main/java/br/ufpa/labes/spm/service/interfaces/JoinConServices.java package br.ufpa.labes.spm.service.interfaces; import br.ufpa.labes.spm.domain.JoinCon; import br.ufpa.labes.spm.service.dto.JoinConDTO; /** JoinConServices */ public interface JoinConServices { JoinCon updateJoinCon(JoinConDTO joinConDTO); }
tahoeRobbo/toyProblems
codeWars/__cutTheWire.js
<gh_stars>1-10 { ArrayBuffer: [Function: ArrayBuffer], Int8Array: { [Function: Int8Array] BYTES_PER_ELEMENT: 1 }, Uint8Array: { [Function: Uint8Array] BYTES_PER_ELEMENT: 1 }, Uint8ClampedArray: { [Function: Uint8ClampedArray] BYTES_PER_ELEMENT: 1 }, Int16Array: { [Function: Int16Array] BYTES_PER_ELEMENT: 2 }, Uint16Array: { [Function: Uint16Array] BYTES_PER_ELEMENT: 2 }, Int32Array: { [Function: Int32Array] BYTES_PER_ELEMENT: 4 }, Uint32Array: { [Function: Uint32Array] BYTES_PER_ELEMENT: 4 }, Float32Array: { [Function: Float32Array] BYTES_PER_ELEMENT: 4 }, Float64Array: { [Function: Float64Array] BYTES_PER_ELEMENT: 8 }, DataView: [Function: DataView], global: [Circular], process: { title: 'node', version: 'v0.10.37', moduleLoadList: [ 'Binding evals', 'Binding natives', 'NativeModule events', 'NativeModule buffer', 'Binding buffer', 'NativeModule assert', 'NativeModule util', 'NativeModule module', 'NativeModule path', 'NativeModule vm', 'NativeModule fs', 'Binding fs', 'Binding constants', 'NativeModule stream', 'NativeModule _stream_readable', 'NativeModule _stream_writable', 'NativeModule _stream_duplex', 'NativeModule _stream_transform', 'NativeModule _stream_passthrough', 'NativeModule console', 'Binding tty_wrap', 'NativeModule net', 'NativeModule timers', 'Binding timer_wrap', 'NativeModule _linklist', 'Binding cares_wrap', 'Binding pipe_wrap' ], versions: { http_parser: '1.0', node: '0.10.37', v8: '3.14.5.9', ares: '1.9.0-DEV', uv: '0.10.36', zlib: '1.2.8', modules: '11', openssl: '1.0.1l' }, arch: 'x64', platform: 'linux', argv: [ 'node' ], execArgv: null, env: { PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', HOSTNAME: '8cc5f5a6187c', HOME: '/home/codewarrior', DEBIAN_FRONTEND: 'noninteractive', DEBIAN_PRIORITY: 'critical', DEBCONF_NOWARNINGS: 'yes', TERM: 'linux', NODE_PATH: '/usr/lib/node_modules', USER: 'codewarrior' }, pid: 42, features: { debug: false, uv: true, ipv6: true, tls_npn: true, tls_sni: true, tls: true }, _needImmediateCallback: false, _eval: null, execPath: '/usr/bin/nodejs', debugPort: 5858, _getActiveRequests: [Function], _getActiveHandles: [Function], _needTickCallback: [Function], reallyExit: [Function], abort: [Function], chdir: [Function], cwd: [Function], umask: [Function], getuid: [Function], setuid: [Function], setgid: [Function], getgid: [Function], getgroups: [Function], setgroups: [Function], initgroups: [Function], _kill: [Function], _debugProcess: [Function], _debugPause: [Function], _debugEnd: [Function], hrtime: [Function], dlopen: [Function], uptime: [Function], memoryUsage: [Function], binding: [Function], _usingDomains: [Function], _tickInfoBox: { '0': 0, '1': 0, '2': 0 }, _events: {}, _emittingTopLevelDomainError: false, domain: null, _maxListeners: 10, EventEmitter: { [Function: EventEmitter] listenerCount: [Function] }, _fatalException: [Function], _exiting: false, assert: [Function], config: { target_defaults: [Object], variables: [Object] }, nextTick: [Function: nextTick], _currentTickHandler: [Function: _nextTick], _nextDomainTick: [Function: _nextDomainTick], _tickCallback: [Function: _tickCallback], _tickDomainCallback: [Function: _tickDomainCallback], _tickFromSpinner: [Function: _tickFromSpinner], maxTickDepth: 1000, stdout: [Getter], stderr: [Getter], stdin: [Getter], openStdin: [Function], exit: [Function], kill: [Function], addListener: [Function], on: [Function], removeListener: [Function] }, GLOBAL: [Circular], root: [Circular], Buffer: { [Function: Buffer] isEncoding: [Function], poolSize: 8192, isBuffer: [Function: isBuffer], byteLength: [Function], concat: [Function] }, setTimeout: [Function], setInterval: [Function], clearTimeout: [Function], clearInterval: [Function], setImmediate: [Function], clearImmediate: [Function], console: [Getter], __filename: '[eval]', exports: {}, module: { id: '[eval]', exports: {}, parent: undefined, filename: '/runner/[eval]', loaded: false, children: [ [Object] ], paths: [ '/runner/node_modules', '/node_modules' ] }, __dirname: '.', require: { [Function: require] resolve: [Function], main: undefined, extensions: { '.js': [Function], '.json': [Function], '.node': [Function] }, registerExtension: [Function], cache: { '/runner/frameworks/javascript/cw-2.js': [Object] } }, assert: { [Function: ok] AssertionError: { [Function: AssertionError] super_: [Object] }, fail: [Function: fail], ok: [Circular], equal: [Function: equal], notEqual: [Function: notEqual], deepEqual: [Function: deepEqual], notDeepEqual: [Function: notDeepEqual], strictEqual: [Function: strictEqual], notStrictEqual: [Function: notStrictEqual], throws: [Function], doesNotThrow: [Function], ifError: [Function] }, '$$_SUCCESS__': null, '$STDOUT': [], djkpdyuruygb: 0.7144070907961577 } BOOM! You have to specify which wire to cut!
ditekunov/Purity-Project
src/main/scala/cryptographyOperations/encoders/GrayEncoder.scala
package cryptographyOperations.encoders import utils.InputException import utils.ExceptionMessages.NegativeOrZeroInput /** * Contains realisation of a Gray encoding: https://en.wikipedia.org/wiki/Gray_code * * Purity project by <NAME>. */ object GrayEncoder { def encode(input: Int): Int = { if (input >= 0) input ^ (input >> 1) else throw new InputException("\"Gray encode\" " + NegativeOrZeroInput) } }
kyoujuro/istio
galley/pkg/testing/mock/endpoints.go
// Copyright Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package mock import ( "context" "fmt" "sync" apicorev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/watch" corev1 "k8s.io/client-go/kubernetes/typed/core/v1" ) var _ corev1.EndpointsInterface = &endpointsImpl{} type endpointsImpl struct { mux sync.Mutex endpoints map[string]*apicorev1.Endpoints watches Watches } func newEndpointsInterface() corev1.EndpointsInterface { return &endpointsImpl{ endpoints: make(map[string]*apicorev1.Endpoints), } } func (e *endpointsImpl) Create(ctx context.Context, obj *apicorev1.Endpoints, opts metav1.CreateOptions) (*apicorev1.Endpoints, error) { e.mux.Lock() defer e.mux.Unlock() e.endpoints[obj.Name] = obj e.watches.Send(watch.Event{ Type: watch.Added, Object: obj, }) return obj, nil } func (e *endpointsImpl) Update(ctx context.Context, obj *apicorev1.Endpoints, opts metav1.UpdateOptions) (*apicorev1.Endpoints, error) { e.mux.Lock() defer e.mux.Unlock() e.endpoints[obj.Name] = obj e.watches.Send(watch.Event{ Type: watch.Modified, Object: obj, }) return obj, nil } func (e *endpointsImpl) Delete(ctx context.Context, name string, options metav1.DeleteOptions) error { e.mux.Lock() defer e.mux.Unlock() obj := e.endpoints[name] if obj == nil { return fmt.Errorf("unable to delete endpoints %s", name) } delete(e.endpoints, name) e.watches.Send(watch.Event{ Type: watch.Deleted, Object: obj, }) return nil } func (e *endpointsImpl) List(ctx context.Context, opts metav1.ListOptions) (*apicorev1.EndpointsList, error) { e.mux.Lock() defer e.mux.Unlock() out := &apicorev1.EndpointsList{} for _, v := range e.endpoints { out.Items = append(out.Items, *v) } return out, nil } func (e *endpointsImpl) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { e.mux.Lock() defer e.mux.Unlock() w := NewWatch() e.watches = append(e.watches, w) // Send add events for all current resources. for _, pod := range e.endpoints { w.Send(watch.Event{ Type: watch.Added, Object: pod, }) } return w, nil } func (e *endpointsImpl) DeleteCollection(ctx context.Context, options metav1.DeleteOptions, listOptions metav1.ListOptions) error { panic("not implemented") } func (e *endpointsImpl) Get(ctx context.Context, name string, options metav1.GetOptions) (*apicorev1.Endpoints, error) { panic("not implemented") } func (e *endpointsImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *apicorev1.Endpoints, err error) { panic("not implemented") }
metux/chromium-deb
chrome/browser/media/router/discovery/dial/safe_dial_device_description_parser.h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_MEDIA_ROUTER_DISCOVERY_DIAL_SAFE_DIAL_DEVICE_DESCRIPTION_PARSER_H_ #define CHROME_BROWSER_MEDIA_ROUTER_DISCOVERY_DIAL_SAFE_DIAL_DEVICE_DESCRIPTION_PARSER_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/optional.h" #include "base/threading/thread_checker.h" #include "chrome/common/media_router/mojo/dial_device_description_parser.mojom.h" #include "content/public/browser/utility_process_mojo_client.h" namespace media_router { // SafeDialDeviceDescriptionParser parses the given device description XML file // safely via a utility process. This class runs on IO thread. class SafeDialDeviceDescriptionParser { public: // Callback function to be invoked when utility process finishes parsing // device description XML. // |success|: returns false if parsing fails. // |device_description|: device description object. Empty if parsing fails. using DeviceDescriptionCallback = base::Callback<void(chrome::mojom::DialDeviceDescriptionPtr)>; SafeDialDeviceDescriptionParser(); virtual ~SafeDialDeviceDescriptionParser(); // Start parsing device description XML file in utility process. // TODO(crbug.com/702766): Add an enum type describing why utility process // fails to parse device description xml. virtual void Start(const std::string& xml_text, const DeviceDescriptionCallback& callback); private: // Utility client used to send device description parsing task to the utility // process. std::unique_ptr<content::UtilityProcessMojoClient< chrome::mojom::DialDeviceDescriptionParser>> utility_process_mojo_client_; base::ThreadChecker thread_checker_; DISALLOW_COPY_AND_ASSIGN(SafeDialDeviceDescriptionParser); }; } // namespace media_router #endif // CHROME_BROWSER_MEDIA_ROUTER_DISCOVERY_DIAL_SAFE_DIAL_DEVICE_DESCRIPTION_PARSER_H_
zhongxinghong/sysyc
src/__include_this_directory.h
//------------------------------------------------------------------------------ // A SysY Compiler for PKU Compiling Principles Practice Course (2021 Spring) //------------------------------------------------------------------------------ // Project: sysyc // File: __include_this_directory.h // Created Date: 2021-05-24 // Author: <NAME> (1700012608) // Email: <EMAIL> //------------------------------------------------------------------------------ // Copyright (c) 2021 <NAME> //------------------------------------------------------------------------------
Tanych/CodeTracking
74-Search-a-2D-Matrix/solution.py
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ i,j=0,len(matrix[0])-1 while i<len(matrix) and j>=0: if matrix[i][j]==target: return True elif matrix[i][j]>target: j-=1 else: i+=1 return False
SwarmUS/HiveMind
src/bsp/src/stm32/src/interloc/src/UWBRxFrame.cpp
<gh_stars>1-10 #include "interloc/UWBRxFrame.h" #include <cmath> float UWBRxFrame::getSFDAngle() const { // RCPHASE register is only 7 bits, so mask off the highest bit return (((float)(m_sfdAngleRegister & 0x7F)) / 64.0F) * M_PI; } float UWBRxFrame::getAccumulatorAngle() const { // Accumulator data has a dummy byte at the first index int16_t accumulatorQ = *((int16_t*)(m_firstPathAccumulator + 1)); int16_t accumulatorI = *((int16_t*)(m_firstPathAccumulator + 3)); // TODO: Maybe change for LUT return atan2f((float)accumulatorI, (float(accumulatorQ))); }
pigzhuzhu55/NutzSite
src/main/java/io/nutz/nutzsite/module/sys/models/User.java
package io.nutz.nutzsite.module.sys.models; import io.nutz.nutzsite.common.base.BaseModel; import org.apache.shiro.crypto.RandomNumberGenerator; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.Sha256Hash; import org.nutz.dao.entity.annotation.*; import org.nutz.plugins.validation.annotation.Validations; import java.io.Serializable; import java.util.Date; import java.util.List; /** * 用户信息 * @author haiming */ @Table("sys_user") public class User extends BaseModel implements Serializable { private static final long serialVersionUID = 1L; @Name @Column @Comment("ID") @ColDefine(type = ColType.VARCHAR, width = 32) @Prev(els = {@EL("uuid()")}) private String id; /** * 部门ID */ @Column("dept_id") @Comment("部门ID") @Validations(required=true,errorMsg = "部门不能为空") private String deptId; /** * 部门父ID */ private String parentId; /** * 登录名称 */ @Column("login_name") @Comment("登录名称") @Validations(required=true,errorMsg = "登录名称不能为空") private String loginName; /** * 用户名称 */ @Column("user_name") @Comment("用户名称") @Validations(required=true,errorMsg = "用户名称不能为空") private String userName; /** * 密码 */ @Column("password") @Comment("密码") @Validations(required=true,errorMsg = "密码不能为空") private String password; /** * 盐加密 */ @Column("salt") @Comment("盐加密") private String salt; /** * 用户邮箱 */ @Column("email") @Comment("用户邮箱") private String email; /** * 手机号码 */ @Column("phonenumber") @Comment("手机号码") private String phonenumber; /** * 用户性别 */ @Column @Comment("用户性别") private String gender; /** * 用户头像 */ @Column @Comment("用户头像") private String avatar; @One(field = "avatar") private Image image; /** * 帐号状态(0正常 1停用) */ @Column @Comment("帐号状态(0正常 1停用) ") private boolean status; /** * 删除标志(0代表存在 1代表删除) */ @Column("del_flag") @Comment("删除标记") @ColDefine(type = ColType.BOOLEAN) private boolean delFlag; /** * 最后登陆IP */ @Column("login_ip") @Comment("最后登陆IP") private String loginIp; /** * 最后登陆时间 */ @Column("login_date") @Comment("最后登陆时间") private Date loginDate; /** * 部门对象 */ @One(field = "deptId") private Dept dept; /** * 角色集合 */ @ManyMany(from = "user_id", relation = "sys_user_role", to = "role_id") private List<Role> roles; /** * 角色组 */ private String roleIds; /** * 岗位组 */ private String postIds; /** * 创建者 */ @Column("create_by") @Comment("创建者 ") @Prev(els = @EL("$me.uid()")) private String createBy; /** * 创建时间 */ @Column("create_time") @Comment("创建时间 ") @Prev(els = {@EL("$me.now()")}) private Date createTime; /** * 更新者 */ @Column("update_by") @Comment("更新者 ") @Prev(els = @EL("$me.uid()")) private String updateBy; /** * 更新时间 */ @Column("update_time") @Comment("更新时间 ") @Prev(els = {@EL("$me.now()")}) private Date updateTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeptId() { return deptId; } public void setDeptId(String deptId) { this.deptId = deptId; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhonenumber() { return phonenumber; } public void setPhonenumber(String phonenumber) { this.phonenumber = phonenumber; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public boolean isDelFlag() { return delFlag; } public void setDelFlag(boolean delFlag) { this.delFlag = delFlag; } public String getLoginIp() { return loginIp; } public void setLoginIp(String loginIp) { this.loginIp = loginIp; } public Date getLoginDate() { return loginDate; } public void setLoginDate(Date loginDate) { this.loginDate = loginDate; } public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public String getRoleIds() { return roleIds; } public void setRoleIds(String roleIds) { this.roleIds = roleIds; } public String getPostIds() { return postIds; } public void setPostIds(String postIds) { this.postIds = postIds; } public Image getImage() { return image; } public void setImage(Image image) { this.image = image; } @Override public String getCreateBy() { return createBy; } @Override public void setCreateBy(String createBy) { this.createBy = createBy; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String getUpdateBy() { return updateBy; } @Override public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } @Override public Date getUpdateTime() { return updateTime; } @Override public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
lechium/iOS1351Headers
System/Library/PrivateFrameworks/AssistantServices.framework/AFAudioPowerXPCProvider.h
/* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:36:18 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/AssistantServices.framework/AssistantServices * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ #import <libobjc.A.dylib/AFAudioPowerProviding.h> @class AFXPCWrapper, _AFAudioPowerXPCSharedMemory, NSString; @interface AFAudioPowerXPCProvider : NSObject <AFAudioPowerProviding> { AFXPCWrapper* _wrapper; _AFAudioPowerXPCSharedMemory* _sharedMemory; } @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; -(id)initWithXPCWrapper:(id)arg1 ; -(void)willBeginAccessPower; -(BOOL)getAveragePower:(float*)arg1 andPeakPower:(float*)arg2 ; -(void)didEndAccessPower; @end
UV-CDAT/ParaView
Plugins/SciberQuestToolKit/vtkSQRandomSeedPoints.h
<gh_stars>0 /* ____ _ __ ____ __ ____ / __/___(_) / ___ ____/ __ \__ _____ ___ / /_ / _/__ ____ _\ \/ __/ / _ \/ -_) __/ /_/ / // / -_|_-</ __/ _/ // _ \/ __/ /___/\__/_/_.__/\__/_/ \___\_\_,_/\__/___/\__/ /___/_//_/\__(_) Copyright 2012 SciberQuest Inc. */ // .NAME vtkSQRandomSeedPoints - create a random cloud of points // .SECTION Description // vtkSQRandomSeedPoints is a source object that creates a user-specified number // of points within a specified radius about a specified center point. // By default location of the points is random within the sphere. It is // also possible to generate random points only on the surface of the // sphere. #ifndef __vtkSQRandomSeedPoints_h #define __vtkSQRandomSeedPoints_h #include "vtkPolyDataAlgorithm.h" class VTK_EXPORT vtkSQRandomSeedPoints : public vtkPolyDataAlgorithm { public: static vtkSQRandomSeedPoints *New(); vtkTypeMacro(vtkSQRandomSeedPoints,vtkPolyDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the number of points to generate. vtkSetClampMacro(NumberOfPoints,int,1,VTK_INT_MAX); vtkGetMacro(NumberOfPoints,int); // Description: // Set the bounding box the seed points are generated // inside. vtkSetVector6Macro(Bounds,double); vtkGetVector6Macro(Bounds,double); protected: /// Pipeline internals. int FillInputPortInformation(int port,vtkInformation *info); int RequestData(vtkInformation *req, vtkInformationVector **input, vtkInformationVector *output); int RequestInformation(vtkInformation *req, vtkInformationVector **input, vtkInformationVector *output); vtkSQRandomSeedPoints(); ~vtkSQRandomSeedPoints(); int NumberOfPoints; double Bounds[6]; private: vtkSQRandomSeedPoints(const vtkSQRandomSeedPoints&); // Not implemented. void operator=(const vtkSQRandomSeedPoints&); // Not implemented. }; #endif
zk20/libsbp
c/test/cpp/auto_check_sbp_navigation_MsgVelNEDDepA.cc
/* * Copyright (C) 2015-2021 Swift Navigation Inc. * Contact: https://support.swiftnav.com * * This source is subject to the license found in the file 'LICENSE' which must * be be distributed together with this source. All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. */ // This file was auto-generated from // spec/tests/yaml/swiftnav/sbp/navigation/test_MsgVelNEDDepA.yaml by // generate.py. Do not modify by hand! #include <gtest/gtest.h> #include <libsbp/cpp/message_handler.h> #include <libsbp/cpp/message_traits.h> #include <libsbp/cpp/state.h> class Test_auto_check_sbp_navigation_MsgVelNEDDepA0 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA0() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA0, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 246, 215, 22, 20, 46, 39, 0, 198, 251, 255, 255, 156, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 161, 92, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = 0; test_msg->e = 3996; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -1082; test_msg->n_sats = 9; test_msg->tow = 2567700; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 55286, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 55286); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, 0) << "incorrect value for d, expected 0, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, 3996) << "incorrect value for e, expected 3996, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -1082) << "incorrect value for n, expected -1082, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 9) << "incorrect value for n_sats, expected 9, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 2567700) << "incorrect value for tow, expected 2567700, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA1 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA1() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA1, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 246, 215, 22, 120, 46, 39, 0, 14, 252, 255, 255, 207, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 125, 160, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = 0; test_msg->e = 3791; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -1010; test_msg->n_sats = 9; test_msg->tow = 2567800; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 55286, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 55286); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, 0) << "incorrect value for d, expected 0, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, 3791) << "incorrect value for e, expected 3791, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -1010) << "incorrect value for n, expected -1010, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 9) << "incorrect value for n_sats, expected 9, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 2567800) << "incorrect value for tow, expected 2567800, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA2 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA2() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA2, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 246, 215, 22, 220, 46, 39, 0, 48, 252, 255, 255, 140, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 179, 135, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = 0; test_msg->e = 3724; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -976; test_msg->n_sats = 9; test_msg->tow = 2567900; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 55286, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 55286); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, 0) << "incorrect value for d, expected 0, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, 3724) << "incorrect value for e, expected 3724, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -976) << "incorrect value for n, expected -976, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 9) << "incorrect value for n_sats, expected 9, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 2567900) << "incorrect value for tow, expected 2567900, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA3 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA3() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA3, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 246, 215, 22, 64, 47, 39, 0, 32, 252, 255, 255, 8, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 51, 177, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = 0; test_msg->e = 3848; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -992; test_msg->n_sats = 9; test_msg->tow = 2568000; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 55286, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 55286); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, 0) << "incorrect value for d, expected 0, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, 3848) << "incorrect value for e, expected 3848, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -992) << "incorrect value for n, expected -992, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 9) << "incorrect value for n_sats, expected 9, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 2568000) << "incorrect value for tow, expected 2568000, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA4 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA4() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA4, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 246, 215, 22, 164, 47, 39, 0, 80, 252, 255, 255, 140, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 23, 0, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = 0; test_msg->e = 3724; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -944; test_msg->n_sats = 9; test_msg->tow = 2568100; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 55286, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 55286); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, 0) << "incorrect value for d, expected 0, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, 3724) << "incorrect value for e, expected 3724, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -944) << "incorrect value for n, expected -944, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 9) << "incorrect value for n_sats, expected 9, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 2568100) << "incorrect value for tow, expected 2568100, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA5 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA5() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA5, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 195, 4, 22, 212, 157, 67, 24, 229, 255, 255, 255, 26, 0, 0, 0, 25, 0, 0, 0, 0, 0, 0, 0, 8, 0, 132, 25, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = 25; test_msg->e = 26; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -27; test_msg->n_sats = 8; test_msg->tow = 407084500; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 1219, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 1219); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, 25) << "incorrect value for d, expected 25, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, 26) << "incorrect value for e, expected 26, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -27) << "incorrect value for n, expected -27, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 8) << "incorrect value for n_sats, expected 8, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 407084500) << "incorrect value for tow, expected 407084500, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA6 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA6() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA6, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 195, 4, 22, 56, 158, 67, 24, 4, 0, 0, 0, 15, 0, 0, 0, 232, 255, 255, 255, 0, 0, 0, 0, 8, 0, 42, 14, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = -24; test_msg->e = 15; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = 4; test_msg->n_sats = 8; test_msg->tow = 407084600; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 1219, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 1219); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, -24) << "incorrect value for d, expected -24, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, 15) << "incorrect value for e, expected 15, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, 4) << "incorrect value for n, expected 4, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 8) << "incorrect value for n_sats, expected 8, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 407084600) << "incorrect value for tow, expected 407084600, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA7 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA7() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA7, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 195, 4, 22, 156, 158, 67, 24, 251, 255, 255, 255, 232, 255, 255, 255, 247, 255, 255, 255, 0, 0, 0, 0, 8, 0, 218, 148, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = -9; test_msg->e = -24; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -5; test_msg->n_sats = 8; test_msg->tow = 407084700; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 1219, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 1219); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, -9) << "incorrect value for d, expected -9, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, -24) << "incorrect value for e, expected -24, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -5) << "incorrect value for n, expected -5, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 8) << "incorrect value for n_sats, expected 8, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 407084700) << "incorrect value for tow, expected 407084700, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA8 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA8() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA8, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 195, 4, 22, 0, 159, 67, 24, 10, 0, 0, 0, 2, 0, 0, 0, 222, 255, 255, 255, 0, 0, 0, 0, 8, 0, 148, 16, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = -34; test_msg->e = 2; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = 10; test_msg->n_sats = 8; test_msg->tow = 407084800; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 1219, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 1219); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, -34) << "incorrect value for d, expected -34, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, 2) << "incorrect value for e, expected 2, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, 10) << "incorrect value for n, expected 10, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 8) << "incorrect value for n_sats, expected 8, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 407084800) << "incorrect value for tow, expected 407084800, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA9 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA9() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA9, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 195, 4, 22, 100, 159, 67, 24, 248, 255, 255, 255, 254, 255, 255, 255, 7, 0, 0, 0, 0, 0, 0, 0, 8, 0, 255, 236, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = 7; test_msg->e = -2; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -8; test_msg->n_sats = 8; test_msg->tow = 407084900; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 1219, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 1219); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, 7) << "incorrect value for d, expected 7, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, -2) << "incorrect value for e, expected -2, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -8) << "incorrect value for n, expected -8, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 8) << "incorrect value for n_sats, expected 8, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 407084900) << "incorrect value for tow, expected 407084900, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; } class Test_auto_check_sbp_navigation_MsgVelNEDDepA10 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<msg_vel_ned_dep_a_t> { public: Test_auto_check_sbp_navigation_MsgVelNEDDepA10() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<msg_vel_ned_dep_a_t>(this), last_msg_storage_(), last_msg_(reinterpret_cast<msg_vel_ned_dep_a_t *>(last_msg_storage_)), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, uint8_t message_length, const msg_vel_ned_dep_a_t &msg) override { memcpy(last_msg_storage_, &msg, message_length); last_msg_len_ = message_length; last_sender_id_ = sender_id; n_callbacks_logged_++; } uint8_t last_msg_storage_[SBP_MAX_PAYLOAD_LEN]; msg_vel_ned_dep_a_t *last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_navigation_MsgVelNEDDepA10, Test) { uint8_t encoded_frame[] = { 85, 5, 2, 195, 4, 22, 46, 162, 68, 24, 255, 255, 255, 255, 253, 255, 255, 255, 148, 255, 255, 255, 0, 0, 0, 0, 5, 0, 166, 189, }; uint8_t test_msg_storage[SBP_MAX_PAYLOAD_LEN]{}; uint8_t test_msg_len = 0; msg_vel_ned_dep_a_t *test_msg = (msg_vel_ned_dep_a_t *)test_msg_storage; test_msg_len = (uint8_t)sizeof(*test_msg); test_msg->d = -108; test_msg->e = -3; test_msg->flags = 0; test_msg->h_accuracy = 0; test_msg->n = -1; test_msg->n_sats = 5; test_msg->tow = 407151150; test_msg->v_accuracy = 0; EXPECT_EQ(send_message(0x205, 1219, test_msg_len, test_msg_storage), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 1219); EXPECT_EQ(last_msg_len_, test_msg_len); EXPECT_EQ(last_msg_->d, -108) << "incorrect value for d, expected -108, is " << last_msg_->d; EXPECT_EQ(last_msg_->e, -3) << "incorrect value for e, expected -3, is " << last_msg_->e; EXPECT_EQ(last_msg_->flags, 0) << "incorrect value for flags, expected 0, is " << last_msg_->flags; EXPECT_EQ(last_msg_->h_accuracy, 0) << "incorrect value for h_accuracy, expected 0, is " << last_msg_->h_accuracy; EXPECT_EQ(last_msg_->n, -1) << "incorrect value for n, expected -1, is " << last_msg_->n; EXPECT_EQ(last_msg_->n_sats, 5) << "incorrect value for n_sats, expected 5, is " << last_msg_->n_sats; EXPECT_EQ(last_msg_->tow, 407151150) << "incorrect value for tow, expected 407151150, is " << last_msg_->tow; EXPECT_EQ(last_msg_->v_accuracy, 0) << "incorrect value for v_accuracy, expected 0, is " << last_msg_->v_accuracy; }
nistefan/cmssw
L1Trigger/L1TMuon/interface/L1TMuonGlobalParamsHelper.h
<reponame>nistefan/cmssw /// /// \class L1TMuonGlobalParamsHelper /// /// Description: Wrapper for L1TMuonGlobalParams /// /// Implementation: /// /// \author: <NAME> /// #ifndef L1TMuonGlobalParamsHelper_h #define L1TMuonGlobalParamsHelper_h #include <memory> #include <iostream> #include <vector> //this is temp hack to avoid ALCA/DB signoff requirement for now: #include "L1Trigger/L1TMuon/interface/L1TMuonGlobalParams_PUBLIC.h" #include "L1Trigger/L1TCommon/interface/TriggerSystem.h" #include "L1Trigger/L1TCommon/interface/Parameter.h" #include "L1Trigger/L1TCommon/interface/Mask.h" class L1TMuonGlobalParamsHelper : public L1TMuonGlobalParams_PUBLIC { public: enum {absIsoCheckMem=0, relIsoCheckMem=1, idxSelMemPhi=2, idxSelMemEta=3, fwdPosSingleMatchQual=4, fwdNegSingleMatchQual=5, ovlPosSingleMatchQual=6, ovlNegSingleMatchQual=7, bOPosMatchQual=8, bONegMatchQual=9, fOPosMatchQual=10, fONegMatchQual=11, bPhiExtrapolation=12, oPhiExtrapolation=13, fPhiExtrapolation=14, bEtaExtrapolation=15, oEtaExtrapolation=16, fEtaExtrapolation=17, sortRank=18, FWVERSION=19, INPUTS_TO_DISABLE=20, MASKED_INPUTS=21, NUM_GMTPARAMNODES=22 }; // string parameters indices enum spIdx {fname=0}; // unsigned parameters indices enum upIdx {ptFactor=0, qualFactor=1, FWVERSION_IDX=0, CALOINPUTS=0, BMTFINPUTS=1, OMTFINPUTS=2, EMTFINPUTS=3}; // double parameters indices enum dpIdx {maxdr=0, fEta=1, fEtaCoarse=2, fPhi=3}; // input enable indices enum linkNr {CALOLINK1=8, EMTFPLINK1=36, OMTFPLINK1=42, BMTFLINK1=48, OMTFNLINK1=60, EMTFNLINK1=66}; // link numbers start at 0 L1TMuonGlobalParamsHelper():L1TMuonGlobalParams_PUBLIC() { pnodes_.resize(NUM_GMTPARAMNODES); } L1TMuonGlobalParamsHelper(const L1TMuonGlobalParams &); ~L1TMuonGlobalParamsHelper() {} // FW version unsigned fwVersion() const { return pnodes_[FWVERSION].uparams_.size() > FWVERSION_IDX ? pnodes_[FWVERSION].uparams_[FWVERSION_IDX] : 0; } void setFwVersion(unsigned fwVersion); // Input disables std::bitset<72> inputsToDisable() const { return inputFlags(INPUTS_TO_DISABLE); }; std::bitset<28> caloInputsToDisable() const { return caloInputFlags(INPUTS_TO_DISABLE); }; std::bitset<12> bmtfInputsToDisable() const { return tfInputFlags(INPUTS_TO_DISABLE, BMTFINPUTS); }; std::bitset<12> omtfInputsToDisable() const { return tfInputFlags(INPUTS_TO_DISABLE, OMTFINPUTS); }; std::bitset<12> emtfInputsToDisable() const { return tfInputFlags(INPUTS_TO_DISABLE, EMTFINPUTS); }; std::bitset<6> omtfpInputsToDisable() const { return eomtfInputFlags(INPUTS_TO_DISABLE, 0, OMTFINPUTS); }; std::bitset<6> omtfnInputsToDisable() const { return eomtfInputFlags(INPUTS_TO_DISABLE, 6, OMTFINPUTS); }; std::bitset<6> emtfpInputsToDisable() const { return eomtfInputFlags(INPUTS_TO_DISABLE, 0, EMTFINPUTS); }; std::bitset<6> emtfnInputsToDisable() const { return eomtfInputFlags(INPUTS_TO_DISABLE, 6, EMTFINPUTS); }; void setInputsToDisable(const std::bitset<72> &inputsToDisable) { setInputFlags(INPUTS_TO_DISABLE, inputsToDisable); }; void setCaloInputsToDisable(const std::bitset<28> &disables) { setCaloInputFlags(INPUTS_TO_DISABLE, disables); }; void setBmtfInputsToDisable(const std::bitset<12> &disables) { setTfInputFlags(INPUTS_TO_DISABLE, BMTFINPUTS, disables); }; void setOmtfpInputsToDisable(const std::bitset<6> &disables) { setEOmtfInputFlags(INPUTS_TO_DISABLE, 0, OMTFINPUTS, disables); }; void setOmtfnInputsToDisable(const std::bitset<6> &disables) { setEOmtfInputFlags(INPUTS_TO_DISABLE, 6, OMTFINPUTS, disables); }; void setEmtfpInputsToDisable(const std::bitset<6> &disables) { setEOmtfInputFlags(INPUTS_TO_DISABLE, 0, EMTFINPUTS, disables); }; void setEmtfnInputsToDisable(const std::bitset<6> &disables) { setEOmtfInputFlags(INPUTS_TO_DISABLE, 6, EMTFINPUTS, disables); }; // masked inputs std::bitset<72> maskedInputs() const { return inputFlags(MASKED_INPUTS); }; std::bitset<28> maskedCaloInputs() const { return caloInputFlags(MASKED_INPUTS); }; std::bitset<12> maskedBmtfInputs() const { return tfInputFlags(MASKED_INPUTS, BMTFINPUTS); }; std::bitset<12> maskedOmtfInputs() const { return tfInputFlags(MASKED_INPUTS, OMTFINPUTS); }; std::bitset<12> maskedEmtfInputs() const { return tfInputFlags(MASKED_INPUTS, EMTFINPUTS); }; std::bitset<6> maskedOmtfpInputs() const { return eomtfInputFlags(MASKED_INPUTS, 0, OMTFINPUTS); }; std::bitset<6> maskedOmtfnInputs() const { return eomtfInputFlags(MASKED_INPUTS, 6, OMTFINPUTS); }; std::bitset<6> maskedEmtfpInputs() const { return eomtfInputFlags(MASKED_INPUTS, 0, EMTFINPUTS); }; std::bitset<6> maskedEmtfnInputs() const { return eomtfInputFlags(MASKED_INPUTS, 6, EMTFINPUTS); }; void setMaskedInputs(const std::bitset<72> &masked) { setInputFlags(MASKED_INPUTS, masked); }; void setMaskedCaloInputs(const std::bitset<28> &masked) { setCaloInputFlags(MASKED_INPUTS, masked); }; void setMaskedBmtfInputs(const std::bitset<12> &masked) { setTfInputFlags(MASKED_INPUTS, BMTFINPUTS, masked); }; void setMaskedOmtfpInputs(const std::bitset<6> &masked) { setEOmtfInputFlags(MASKED_INPUTS, 0, OMTFINPUTS, masked); }; void setMaskedOmtfnInputs(const std::bitset<6> &masked) { setEOmtfInputFlags(MASKED_INPUTS, 6, OMTFINPUTS, masked); }; void setMaskedEmtfpInputs(const std::bitset<6> &masked) { setEOmtfInputFlags(MASKED_INPUTS, 0, EMTFINPUTS, masked); }; void setMaskedEmtfnInputs(const std::bitset<6> &masked) { setEOmtfInputFlags(MASKED_INPUTS, 6, EMTFINPUTS, masked); }; // LUTs l1t::LUT* absIsoCheckMemLUT() { return &pnodes_[absIsoCheckMem].LUT_; } l1t::LUT* relIsoCheckMemLUT() { return &pnodes_[relIsoCheckMem].LUT_; } l1t::LUT* idxSelMemPhiLUT() { return &pnodes_[idxSelMemPhi].LUT_; } l1t::LUT* idxSelMemEtaLUT() { return &pnodes_[idxSelMemEta].LUT_; } l1t::LUT* fwdPosSingleMatchQualLUT() { return &pnodes_[fwdPosSingleMatchQual].LUT_; } l1t::LUT* fwdNegSingleMatchQualLUT() { return &pnodes_[fwdNegSingleMatchQual].LUT_; } l1t::LUT* ovlPosSingleMatchQualLUT() { return &pnodes_[ovlPosSingleMatchQual].LUT_; } l1t::LUT* ovlNegSingleMatchQualLUT() { return &pnodes_[ovlNegSingleMatchQual].LUT_; } l1t::LUT* bOPosMatchQualLUT() { return &pnodes_[bOPosMatchQual].LUT_; } l1t::LUT* bONegMatchQualLUT() { return &pnodes_[bONegMatchQual].LUT_; } l1t::LUT* fOPosMatchQualLUT() { return &pnodes_[fOPosMatchQual].LUT_; } l1t::LUT* fONegMatchQualLUT() { return &pnodes_[fONegMatchQual].LUT_; } l1t::LUT* bPhiExtrapolationLUT() { return &pnodes_[bPhiExtrapolation].LUT_; } l1t::LUT* oPhiExtrapolationLUT() { return &pnodes_[oPhiExtrapolation].LUT_; } l1t::LUT* fPhiExtrapolationLUT() { return &pnodes_[fPhiExtrapolation].LUT_; } l1t::LUT* bEtaExtrapolationLUT() { return &pnodes_[bEtaExtrapolation].LUT_; } l1t::LUT* oEtaExtrapolationLUT() { return &pnodes_[oEtaExtrapolation].LUT_; } l1t::LUT* fEtaExtrapolationLUT() { return &pnodes_[fEtaExtrapolation].LUT_; } l1t::LUT* sortRankLUT() { return &pnodes_[sortRank].LUT_; } void setAbsIsoCheckMemLUT (const l1t::LUT & lut) { pnodes_[absIsoCheckMem].type_ = "LUT"; pnodes_[absIsoCheckMem].LUT_ = lut; } void setRelIsoCheckMemLUT (const l1t::LUT & lut) { pnodes_[relIsoCheckMem].type_ = "LUT"; pnodes_[relIsoCheckMem].LUT_ = lut; } void setIdxSelMemPhiLUT (const l1t::LUT & lut) { pnodes_[idxSelMemPhi].type_ = "LUT"; pnodes_[idxSelMemPhi].LUT_ = lut; } void setIdxSelMemEtaLUT (const l1t::LUT & lut) { pnodes_[idxSelMemEta].type_ = "LUT"; pnodes_[idxSelMemEta].LUT_ = lut; } void setFwdPosSingleMatchQualLUT (const l1t::LUT & lut) { pnodes_[fwdPosSingleMatchQual].type_ = "LUT"; pnodes_[fwdPosSingleMatchQual].LUT_ = lut; } void setFwdNegSingleMatchQualLUT (const l1t::LUT & lut) { pnodes_[fwdNegSingleMatchQual].type_ = "LUT"; pnodes_[fwdNegSingleMatchQual].LUT_ = lut; } void setOvlPosSingleMatchQualLUT (const l1t::LUT & lut) { pnodes_[ovlPosSingleMatchQual].type_ = "LUT"; pnodes_[ovlPosSingleMatchQual].LUT_ = lut; } void setOvlNegSingleMatchQualLUT (const l1t::LUT & lut) { pnodes_[ovlNegSingleMatchQual].type_ = "LUT"; pnodes_[ovlNegSingleMatchQual].LUT_ = lut; } void setBOPosMatchQualLUT (const l1t::LUT & lut) { pnodes_[bOPosMatchQual].type_ = "LUT"; pnodes_[bOPosMatchQual].LUT_ = lut; } void setBONegMatchQualLUT (const l1t::LUT & lut) { pnodes_[bONegMatchQual].type_ = "LUT"; pnodes_[bONegMatchQual].LUT_ = lut; } void setFOPosMatchQualLUT (const l1t::LUT & lut) { pnodes_[fOPosMatchQual].type_ = "LUT"; pnodes_[fOPosMatchQual].LUT_ = lut; } void setFONegMatchQualLUT (const l1t::LUT & lut) { pnodes_[fONegMatchQual].type_ = "LUT"; pnodes_[fONegMatchQual].LUT_ = lut; } void setBPhiExtrapolationLUT (const l1t::LUT & lut) { pnodes_[bPhiExtrapolation].type_ = "LUT"; pnodes_[bPhiExtrapolation].LUT_ = lut; } void setOPhiExtrapolationLUT (const l1t::LUT & lut) { pnodes_[oPhiExtrapolation].type_ = "LUT"; pnodes_[oPhiExtrapolation].LUT_ = lut; } void setFPhiExtrapolationLUT (const l1t::LUT & lut) { pnodes_[fPhiExtrapolation].type_ = "LUT"; pnodes_[fPhiExtrapolation].LUT_ = lut; } void setBEtaExtrapolationLUT (const l1t::LUT & lut) { pnodes_[bEtaExtrapolation].type_ = "LUT"; pnodes_[bEtaExtrapolation].LUT_ = lut; } void setOEtaExtrapolationLUT (const l1t::LUT & lut) { pnodes_[oEtaExtrapolation].type_ = "LUT"; pnodes_[oEtaExtrapolation].LUT_ = lut; } void setFEtaExtrapolationLUT (const l1t::LUT & lut) { pnodes_[fEtaExtrapolation].type_ = "LUT"; pnodes_[fEtaExtrapolation].LUT_ = lut; } void setSortRankLUT (const l1t::LUT & lut) { pnodes_[sortRank].type_ = "LUT"; pnodes_[sortRank].LUT_ = lut; } // LUT paths std::string absIsoCheckMemLUTPath() const { return pnodes_[absIsoCheckMem].sparams_.size() > spIdx::fname ? pnodes_[absIsoCheckMem].sparams_[spIdx::fname] : ""; } std::string relIsoCheckMemLUTPath() const { return pnodes_[relIsoCheckMem].sparams_.size() > spIdx::fname ? pnodes_[relIsoCheckMem].sparams_[spIdx::fname] : ""; } std::string idxSelMemPhiLUTPath() const { return pnodes_[idxSelMemPhi].sparams_.size() > spIdx::fname ? pnodes_[idxSelMemPhi].sparams_[spIdx::fname] : ""; } std::string idxSelMemEtaLUTPath() const { return pnodes_[idxSelMemEta].sparams_.size() > spIdx::fname ? pnodes_[idxSelMemEta].sparams_[spIdx::fname] : ""; } std::string fwdPosSingleMatchQualLUTPath() const { return pnodes_[fwdPosSingleMatchQual].sparams_.size() > spIdx::fname ? pnodes_[fwdPosSingleMatchQual].sparams_[spIdx::fname] : ""; } std::string fwdNegSingleMatchQualLUTPath() const { return pnodes_[fwdNegSingleMatchQual].sparams_.size() > spIdx::fname ? pnodes_[fwdNegSingleMatchQual].sparams_[spIdx::fname] : ""; } std::string ovlPosSingleMatchQualLUTPath() const { return pnodes_[ovlPosSingleMatchQual].sparams_.size() > spIdx::fname ? pnodes_[ovlPosSingleMatchQual].sparams_[spIdx::fname] : ""; } std::string ovlNegSingleMatchQualLUTPath() const { return pnodes_[ovlNegSingleMatchQual].sparams_.size() > spIdx::fname ? pnodes_[ovlNegSingleMatchQual].sparams_[spIdx::fname] : ""; } std::string bOPosMatchQualLUTPath() const { return pnodes_[bOPosMatchQual].sparams_.size() > spIdx::fname ? pnodes_[bOPosMatchQual].sparams_[spIdx::fname] : ""; } std::string bONegMatchQualLUTPath() const { return pnodes_[bONegMatchQual].sparams_.size() > spIdx::fname ? pnodes_[bONegMatchQual].sparams_[spIdx::fname] : ""; } std::string fOPosMatchQualLUTPath() const { return pnodes_[fOPosMatchQual].sparams_.size() > spIdx::fname ? pnodes_[fOPosMatchQual].sparams_[spIdx::fname] : ""; } std::string fONegMatchQualLUTPath() const { return pnodes_[fONegMatchQual].sparams_.size() > spIdx::fname ? pnodes_[fONegMatchQual].sparams_[spIdx::fname] : ""; } std::string bPhiExtrapolationLUTPath() const { return pnodes_[bPhiExtrapolation].sparams_.size() > spIdx::fname ? pnodes_[bPhiExtrapolation].sparams_[spIdx::fname] : ""; } std::string oPhiExtrapolationLUTPath() const { return pnodes_[oPhiExtrapolation].sparams_.size() > spIdx::fname ? pnodes_[oPhiExtrapolation].sparams_[spIdx::fname] : ""; } std::string fPhiExtrapolationLUTPath() const { return pnodes_[fPhiExtrapolation].sparams_.size() > spIdx::fname ? pnodes_[fPhiExtrapolation].sparams_[spIdx::fname] : ""; } std::string bEtaExtrapolationLUTPath() const { return pnodes_[bEtaExtrapolation].sparams_.size() > spIdx::fname ? pnodes_[bEtaExtrapolation].sparams_[spIdx::fname] : ""; } std::string oEtaExtrapolationLUTPath() const { return pnodes_[oEtaExtrapolation].sparams_.size() > spIdx::fname ? pnodes_[oEtaExtrapolation].sparams_[spIdx::fname] : ""; } std::string fEtaExtrapolationLUTPath() const { return pnodes_[fEtaExtrapolation].sparams_.size() > spIdx::fname ? pnodes_[fEtaExtrapolation].sparams_[spIdx::fname] : ""; } std::string sortRankLUTPath() const { return pnodes_[sortRank].sparams_.size() > spIdx::fname ? pnodes_[sortRank].sparams_[spIdx::fname] : ""; } void setAbsIsoCheckMemLUTPath (const std::string &path) { pnodes_[absIsoCheckMem].sparams_.push_back(path); } void setRelIsoCheckMemLUTPath (const std::string &path) { pnodes_[relIsoCheckMem].sparams_.push_back(path); } void setIdxSelMemPhiLUTPath (const std::string &path) { pnodes_[idxSelMemPhi].sparams_.push_back(path); } void setIdxSelMemEtaLUTPath (const std::string &path) { pnodes_[idxSelMemEta].sparams_.push_back(path); } void setFwdPosSingleMatchQualLUTPath (const std::string &path) { pnodes_[fwdPosSingleMatchQual].sparams_.push_back(path); } void setFwdNegSingleMatchQualLUTPath (const std::string &path) { pnodes_[fwdNegSingleMatchQual].sparams_.push_back(path); } void setOvlPosSingleMatchQualLUTPath (const std::string &path) { pnodes_[ovlPosSingleMatchQual].sparams_.push_back(path); } void setOvlNegSingleMatchQualLUTPath (const std::string &path) { pnodes_[ovlNegSingleMatchQual].sparams_.push_back(path); } void setBOPosMatchQualLUTPath (const std::string &path) { pnodes_[bOPosMatchQual].sparams_.push_back(path); } void setBONegMatchQualLUTPath (const std::string &path) { pnodes_[bONegMatchQual].sparams_.push_back(path); } void setFOPosMatchQualLUTPath (const std::string &path) { pnodes_[fOPosMatchQual].sparams_.push_back(path); } void setFONegMatchQualLUTPath (const std::string &path) { pnodes_[fONegMatchQual].sparams_.push_back(path); } void setBPhiExtrapolationLUTPath (const std::string &path) { pnodes_[bPhiExtrapolation].sparams_.push_back(path); } void setOPhiExtrapolationLUTPath (const std::string &path) { pnodes_[oPhiExtrapolation].sparams_.push_back(path); } void setFPhiExtrapolationLUTPath (const std::string &path) { pnodes_[fPhiExtrapolation].sparams_.push_back(path); } void setBEtaExtrapolationLUTPath (const std::string &path) { pnodes_[bEtaExtrapolation].sparams_.push_back(path); } void setOEtaExtrapolationLUTPath (const std::string &path) { pnodes_[oEtaExtrapolation].sparams_.push_back(path); } void setFEtaExtrapolationLUTPath (const std::string &path) { pnodes_[fEtaExtrapolation].sparams_.push_back(path); } void setSortRankLUTPath (const std::string &path) { pnodes_[sortRank].sparams_.push_back(path); } // Cancel out LUT max dR double fwdPosSingleMatchQualLUTMaxDR() const { return pnodes_[fwdPosSingleMatchQual].dparams_.size() > dpIdx::maxdr ? pnodes_[fwdPosSingleMatchQual].dparams_[dpIdx::maxdr] : 0.; } double fwdNegSingleMatchQualLUTMaxDR() const { return pnodes_[fwdNegSingleMatchQual].dparams_.size() > dpIdx::maxdr ? pnodes_[fwdNegSingleMatchQual].dparams_[dpIdx::maxdr] : 0.; } double ovlPosSingleMatchQualLUTMaxDR() const { return pnodes_[ovlPosSingleMatchQual].dparams_.size() > dpIdx::maxdr ? pnodes_[ovlPosSingleMatchQual].dparams_[dpIdx::maxdr] : 0.; } double ovlNegSingleMatchQualLUTMaxDR() const { return pnodes_[ovlNegSingleMatchQual].dparams_.size() > dpIdx::maxdr ? pnodes_[ovlNegSingleMatchQual].dparams_[dpIdx::maxdr] : 0.; } double bOPosMatchQualLUTMaxDR() const { return pnodes_[bOPosMatchQual].dparams_.size() > dpIdx::maxdr ? pnodes_[bOPosMatchQual].dparams_[dpIdx::maxdr] : 0.; } double bONegMatchQualLUTMaxDR() const { return pnodes_[bONegMatchQual].dparams_.size() > dpIdx::maxdr ? pnodes_[bONegMatchQual].dparams_[dpIdx::maxdr] : 0.; } double fOPosMatchQualLUTMaxDR() const { return pnodes_[fOPosMatchQual].dparams_.size() > dpIdx::maxdr ? pnodes_[fOPosMatchQual].dparams_[dpIdx::maxdr] : 0.; } double fONegMatchQualLUTMaxDR() const { return pnodes_[fONegMatchQual].dparams_.size() > dpIdx::maxdr ? pnodes_[fONegMatchQual].dparams_[dpIdx::maxdr] : 0.; } double fwdPosSingleMatchQualLUTfEta() const { return pnodes_[fwdPosSingleMatchQual].dparams_.size() > dpIdx::fEta ? pnodes_[fwdPosSingleMatchQual].dparams_[dpIdx::fEta] : 0.; } double fwdNegSingleMatchQualLUTfEta() const { return pnodes_[fwdNegSingleMatchQual].dparams_.size() > dpIdx::fEta ? pnodes_[fwdNegSingleMatchQual].dparams_[dpIdx::fEta] : 0.; } double ovlPosSingleMatchQualLUTfEta() const { return pnodes_[ovlPosSingleMatchQual].dparams_.size() > dpIdx::fEta ? pnodes_[ovlPosSingleMatchQual].dparams_[dpIdx::fEta] : 0.; } double ovlNegSingleMatchQualLUTfEta() const { return pnodes_[ovlNegSingleMatchQual].dparams_.size() > dpIdx::fEta ? pnodes_[ovlNegSingleMatchQual].dparams_[dpIdx::fEta] : 0.; } double ovlPosSingleMatchQualLUTfEtaCoarse() const { return pnodes_[ovlPosSingleMatchQual].dparams_.size() > dpIdx::fEtaCoarse ? pnodes_[ovlPosSingleMatchQual].dparams_[dpIdx::fEtaCoarse] : 0.; } double ovlNegSingleMatchQualLUTfEtaCoarse() const { return pnodes_[ovlNegSingleMatchQual].dparams_.size() > dpIdx::fEtaCoarse ? pnodes_[ovlNegSingleMatchQual].dparams_[dpIdx::fEtaCoarse] : 0.; } double bOPosMatchQualLUTfEta() const { return pnodes_[bOPosMatchQual].dparams_.size() > dpIdx::fEta ? pnodes_[bOPosMatchQual].dparams_[dpIdx::fEta] : 0.; } double bONegMatchQualLUTfEta() const { return pnodes_[bONegMatchQual].dparams_.size() > dpIdx::fEta ? pnodes_[bONegMatchQual].dparams_[dpIdx::fEta] : 0.; } double bOPosMatchQualLUTfEtaCoarse() const { return pnodes_[bOPosMatchQual].dparams_.size() > dpIdx::fEtaCoarse ? pnodes_[bOPosMatchQual].dparams_[dpIdx::fEtaCoarse] : 0.; } double bONegMatchQualLUTfEtaCoarse() const { return pnodes_[bONegMatchQual].dparams_.size() > dpIdx::fEtaCoarse ? pnodes_[bONegMatchQual].dparams_[dpIdx::fEtaCoarse] : 0.; } double fOPosMatchQualLUTfEta() const { return pnodes_[fOPosMatchQual].dparams_.size() > dpIdx::fEta ? pnodes_[fOPosMatchQual].dparams_[dpIdx::fEta] : 0.; } double fONegMatchQualLUTfEta() const { return pnodes_[fONegMatchQual].dparams_.size() > dpIdx::fEta ? pnodes_[fONegMatchQual].dparams_[dpIdx::fEta] : 0.; } double fOPosMatchQualLUTfEtaCoarse() const { return pnodes_[fOPosMatchQual].dparams_.size() > dpIdx::fEtaCoarse ? pnodes_[fOPosMatchQual].dparams_[dpIdx::fEtaCoarse] : 0.; } double fONegMatchQualLUTfEtaCoarse() const { return pnodes_[fONegMatchQual].dparams_.size() > dpIdx::fEtaCoarse ? pnodes_[fONegMatchQual].dparams_[dpIdx::fEtaCoarse] : 0.; } double fwdPosSingleMatchQualLUTfPhi() const { return pnodes_[fwdPosSingleMatchQual].dparams_.size() > dpIdx::fPhi ? pnodes_[fwdPosSingleMatchQual].dparams_[dpIdx::fPhi] : 0.; } double fwdNegSingleMatchQualLUTfPhi() const { return pnodes_[fwdNegSingleMatchQual].dparams_.size() > dpIdx::fPhi ? pnodes_[fwdNegSingleMatchQual].dparams_[dpIdx::fPhi] : 0.; } double ovlPosSingleMatchQualLUTfPhi() const { return pnodes_[ovlPosSingleMatchQual].dparams_.size() > dpIdx::fPhi ? pnodes_[ovlPosSingleMatchQual].dparams_[dpIdx::fPhi] : 0.; } double ovlNegSingleMatchQualLUTfPhi() const { return pnodes_[ovlNegSingleMatchQual].dparams_.size() > dpIdx::fPhi ? pnodes_[ovlNegSingleMatchQual].dparams_[dpIdx::fPhi] : 0.; } double bOPosMatchQualLUTfPhi() const { return pnodes_[bOPosMatchQual].dparams_.size() > dpIdx::fPhi ? pnodes_[bOPosMatchQual].dparams_[dpIdx::fPhi] : 0.; } double bONegMatchQualLUTfPhi() const { return pnodes_[bONegMatchQual].dparams_.size() > dpIdx::fPhi ? pnodes_[bONegMatchQual].dparams_[dpIdx::fPhi] : 0.; } double fOPosMatchQualLUTfPhi() const { return pnodes_[fOPosMatchQual].dparams_.size() > dpIdx::fPhi ? pnodes_[fOPosMatchQual].dparams_[dpIdx::fPhi] : 0.; } double fONegMatchQualLUTfPhi() const { return pnodes_[fONegMatchQual].dparams_.size() > dpIdx::fPhi ? pnodes_[fONegMatchQual].dparams_[dpIdx::fPhi] : 0.; } void setFwdPosSingleMatchQualLUTMaxDR (double maxDR, double fEta, double fPhi); void setFwdNegSingleMatchQualLUTMaxDR (double maxDR, double fEta, double fPhi); void setOvlPosSingleMatchQualLUTMaxDR (double maxDR, double fEta, double fEtaCoarse, double fPhi); void setOvlNegSingleMatchQualLUTMaxDR (double maxDR, double fEta, double fEtaCoarse, double fPhi); void setBOPosMatchQualLUTMaxDR (double maxDR, double fEta, double fEtaCoarse, double fPhi); void setBONegMatchQualLUTMaxDR (double maxDR, double fEta, double fEtaCoarse, double fPhi); void setFOPosMatchQualLUTMaxDR (double maxDR, double fEta, double fEtaCoarse, double fPhi); void setFONegMatchQualLUTMaxDR (double maxDR, double fEta, double fEtaCoarse, double fPhi); // Sort rank LUT factors for pT and quality unsigned sortRankLUTPtFactor() const { return pnodes_[sortRank].uparams_.size() > upIdx::ptFactor ? pnodes_[sortRank].uparams_[upIdx::ptFactor] : 0; } unsigned sortRankLUTQualFactor() const { return pnodes_[sortRank].uparams_.size() > upIdx::qualFactor ? pnodes_[sortRank].uparams_[upIdx::qualFactor] : 0; } void setSortRankLUTFactors(unsigned ptFactor, unsigned qualFactor) { pnodes_[sortRank].uparams_.push_back(ptFactor); pnodes_[sortRank].uparams_.push_back(qualFactor); } // set parameters with a trigSystem object built from the online DB void loadFromOnline(l1t::TriggerSystem& trgSys, const std::string& processorId = ""); // print parameters to stream: void print(std::ostream&) const; friend std::ostream& operator<<(std::ostream& o, const L1TMuonGlobalParamsHelper & p) { p.print(o); return o; } private: // Input disables std::bitset<72> inputFlags(const int &nodeIdx) const; std::bitset<28> caloInputFlags(const int &nodeIdx) const; std::bitset<12> tfInputFlags(const int &nodeIdx, const int &tfIdx) const; std::bitset<6> eomtfInputFlags(const int &nodeIdx, const size_t &startIdx, const int &tfIdx) const; void setInputFlags(const int &nodeIdx, const std::bitset<72> &flags); void setCaloInputFlags(const int &nodeIdx, const std::bitset<28> &flags); void setTfInputFlags(const int &nodeIdx, const int &tfIdx, const std::bitset<12> &flags); void setEOmtfInputFlags(const int &nodeIdx, const size_t &startIdx, const int &tfIdx, const std::bitset<6> &flags); }; #endif
yejf/poll
trunk/src/main/java/com/tarena/poll/dao/impl/PollContentImpl.java
package com.tarena.poll.dao.impl; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import com.tarena.poll.dao.IPollContentDao; import com.tarena.poll.entity.TPollContent; import com.tarena.poll.util.HBDaoFactory; /** *本来用来演示 *author datong */ public class PollContentImpl implements IPollContentDao{ @Override public void savePollContent(TPollContent content) { Session s =HBDaoFactory.getSession(); Transaction ts =s.getTransaction(); try { ts.begin(); s.save(content); ts.commit(); } catch (Exception e) { ts.rollback(); e.printStackTrace(); }finally{ s.close(); } } @Override public List<TPollContent> getByTypeAndStatus(String type,int status) { Session s = HBDaoFactory.getSession(); String hql = "from TPollContent where type=:type and status=:status"; List<TPollContent> contents =s.createQuery(hql).setParameter("type", type).setParameter("status", status).list(); s.close(); return contents; } @Override public List<TPollContent> getByStatus(int status) { Session s = HBDaoFactory.getSession(); String hql = "from TPollContent where status=:status"; List<TPollContent> contents =s.createQuery(hql).setParameter("status", status).list(); s.close(); return contents; } @Override public void modifyContentAllClose() { Session s = HBDaoFactory.getSession(); String hql="update TPollContent set status=1"; s.beginTransaction(); s.createQuery(hql).executeUpdate(); s.getTransaction().commit(); s.close(); } @Override public void modifyContentByIdAndStatus(int id, int status) { Session s = HBDaoFactory.getSession(); String hql="update TPollContent set status=:status where id=:id"; s.beginTransaction(); s.createQuery(hql).setParameter("id", id).setParameter("status", status).executeUpdate(); s.getTransaction().commit(); s.close(); } @Override public void modifyContentByIdAndName(int id, String name) { Session s = HBDaoFactory.getSession(); String hql="update TPollContent set content=:name where id=:id"; s.beginTransaction(); s.createQuery(hql).setParameter("id", id).setParameter("name", name).executeUpdate(); s.getTransaction().commit(); s.close(); } @Override public List<String> selectTypes() { Session s = HBDaoFactory.getSession(); String hql="select distinct type from TPollContent"; List<String> list= s.createQuery(hql).list(); s.close(); return list; } @Override public List<TPollContent> getAll() { Session s = HBDaoFactory.getSession(); String hql="from TPollContent order by type"; List<TPollContent> list = s.createQuery(hql).list(); s.close(); return null; } }
GWT-M3O-TEST/GWT-m3o-js
examples/db/create/createARecord.js
const m3o = require("m3o")(process.env.M3O_API_TOKEN); async function main() { let rsp = await m3o.db.create({ record: { age: 42, id: "1", isActive: true, name: "Jane", }, table: "example", }); console.log(rsp); } main();
Mindhome/field_service
mindhome_alpha/erpnext/manufacturing/report/bom_variance_report/bom_variance_report.py
<filename>mindhome_alpha/erpnext/manufacturing/report/bom_variance_report/bom_variance_report.py # Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ def execute(filters=None): columns, data = [], [] columns = get_columns(filters) data = get_data(filters) return columns, data def get_columns(filters): columns = [{ "label": _("Work Order"), "fieldname": "work_order", "fieldtype": "Link", "options": "Work Order", "width": 120 }] if not filters.get('bom_no'): columns.extend([ { "label": _("BOM No"), "fieldname": "bom_no", "fieldtype": "Link", "options": "BOM", "width": 180 } ]) columns.extend([ { "label": _("Finished Good"), "fieldname": "production_item", "fieldtype": "Link", "options": "Item", "width": 120 }, { "label": _("Ordered Qty"), "fieldname": "qty", "fieldtype": "Float", "width": 120 }, { "label": _("Produced Qty"), "fieldname": "produced_qty", "fieldtype": "Float", "width": 120 }, { "label": _("Raw Material"), "fieldname": "raw_material_code", "fieldtype": "Link", "options": "Item", "width": 120 }, { "label": _("Required Qty"), "fieldname": "required_qty", "fieldtype": "Float", "width": 120 }, { "label": _("Consumed Qty"), "fieldname": "consumed_qty", "fieldtype": "Float", "width": 120 } ]) return columns def get_data(filters): cond = "1=1" if filters.get('bom_no') and not filters.get('work_order'): cond += " and bom_no = '%s'" % filters.get('bom_no') if filters.get('work_order'): cond += " and name = '%s'" % filters.get('work_order') results = [] for d in frappe.db.sql(""" select name as work_order, qty, produced_qty, production_item, bom_no from `tabWork Order` where produced_qty > qty and docstatus = 1 and {0}""".format(cond), as_dict=1): results.append(d) for data in frappe.get_all('Work Order Item', fields=["item_code as raw_material_code", "required_qty", "consumed_qty"], filters={'parent': d.work_order, 'parenttype': 'Work Order'}): results.append(data) return results @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs def get_work_orders(doctype, txt, searchfield, start, page_len, filters): cond = "1=1" if filters.get('bom_no'): cond += " and bom_no = '%s'" % filters.get('bom_no') return frappe.db.sql("""select name from `tabWork Order` where name like %(name)s and {0} and produced_qty > qty and docstatus = 1 order by name limit {1}, {2}""".format(cond, start, page_len),{ 'name': "%%%s%%" % txt }, as_list=1)
ifwe/digsby
digsby/src/jabber/objects/shared_status/__init__.py
<reponame>ifwe/digsby<filename>digsby/src/jabber/objects/shared_status/__init__.py from pyxmpp.iq import Iq SHARED_STATUS_NS = 'google:shared-status' def make_get(gtalk_protocol): iq = Iq(stanza_type="get") q = iq.new_query(SHARED_STATUS_NS) q.setProp("version", '2') return iq
iTeam-co/pytglib
pytglib/api/utils/__init__.py
from .object import Object from importlib import import_module from .all_types import all_types for k, v in all_types.items(): Object.all[k[:1].lower() + k[1:]] = getattr(import_module("pytglib.api.types." + v), k)
ThoTischner/infra-ecosphere
ipmi/ipmi_server.go
<filename>ipmi/ipmi_server.go package ipmi import ( "bytes" "fmt" "io" "log" "net" "os" "os/signal" "syscall" "time" ) import ( "../utils" "../bmc" ) var running bool = false func DeserializeAndExecute(buf io.Reader, addr *net.UDPAddr, server *net.UDPConn) { RMCPDeserializeAndExecute(buf, addr, server) } func IPMIServerHandler(BMCIP string, BMCPORT string) { addr := fmt.Sprintf("%s:%s", BMCIP, BMCPORT) serverAddr, err := net.ResolveUDPAddr("udp", addr) utils.CheckError(err) server, err := net.ListenUDP("udp", serverAddr) utils.CheckError(err) defer server.Close() buf := make([]byte, 1024) for running { _, addr, _ := server.ReadFromUDP(buf) log.Println("Receive a UDP packet from ", addr.IP.String(), ":", addr.Port) bytebuf := bytes.NewBuffer(buf) DeserializeAndExecute(bytebuf, addr, server) } } func IPMIServerServiceRun() { signalChan := make(chan os.Signal, 1) exitChan := make(chan bool, 1) signal.Notify(signalChan, os.Interrupt, syscall.SIGINT) go func() { <- signalChan log.Println("Capture Interrupt from System, terminate this server.") running = false exitChan <- true }() running = true config := utils.LoadConfig("infra-ecosphere.cfg") if config.BmcNet == "true" { for ip, _ := range bmc.BMCs { port := bmc.BMCs[ip].Port go func(ip string, port string) { log.Println("Start BMC Listener for BMC foo ", ip) IPMIServerHandler(ip, port) log.Println("BMC Listener ", ip, " is terminated.") }(ip, string(port)) } } else { log.Println("Dont start BMC loopback ips, cause BmcNet config set to false") } <- exitChan log.Println("Wait for Listener terminating...") time.Sleep(3 * time.Second) }
collectiveidea/ember-helpers
app/helpers/length.js
export { default, length } from '@abcum/ember-helpers/helpers/length';
flyinskyin2013/yLib_Docs
doxygen_docs/html/search/typedefs_0.js
var searchData= [ ['const_5fpointer_1053',['const_pointer',['../classyLib_1_1yBasicAllocator.html#a7cb0b3a23165aeab48a8cfa790b11560',1,'yLib::yBasicAllocator']]], ['const_5freference_1054',['const_reference',['../classyLib_1_1yBasicAllocator.html#aa89d64c8f2e2bfa3421c635d6f4e54db',1,'yLib::yBasicAllocator']]], ['const_5frreference_1055',['const_rreference',['../classyLib_1_1yBasicAllocator.html#ad773fe9868b90172228552c538bbfa91',1,'yLib::yBasicAllocator']]] ];
philosophy912/Sophia
src/test/java/com/philosophy/base/util/StringsUtilsTest.java
<gh_stars>0 package com.philosophy.base.util; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class StringsUtilsTest { @Test void test() { assertEquals("", StringsUtils.trimToEmpty(null)); } }
20minutes/phpcr-browser
web/assets/js/app/Browser/component/directive/Draggable.js
define([], function() { 'use strict'; // From http://blog.parkji.co.uk/2013/08/11/native-drag-and-drop-in-angularjs.html function Draggable($parse) { return { restrict: 'A', link: function(scope, element, attrs) { if (!$parse(attrs.draggable)(scope)) { return; } var el = element[0]; scope.draggableData = $parse(attrs.draggableData)(scope) || {}; el.draggable = true; el.addEventListener( 'dragstart', function(e) { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('Text', this.id); this.classList.add('drag'); return false; }, false ); el.addEventListener( 'dragend', function() { this.classList.remove('drag'); return false; }, false ); } }; } Draggable.$inject = ['$parse']; return Draggable; });
jcalendo/K_and_R
kn_king/chapter_7/7-2.c
#include <stdio.h> // Modify squares2.c so that it pauses after every 24 squares int main(void) { int n; printf("This program prints a table of squares.\n"); printf("Enter the number of entries in the table: "); scanf("%d", &n); getchar(); // get the new line character left hanging from scanf for (int i = 1; i <= n; i++) { if (i % 24 == 0) { printf("%10d\t%10d\n", i, i * i); printf("Press Enter to Continue..."); getchar(); } printf("%10d\t%10d\n", i, i * i); } return 0; }
Lembed/Cortex-M3-Projects
dtmf_decoder/inc/platform.h
<filename>dtmf_decoder/inc/platform.h #ifndef PLATFORM_h_ #define PLATFORM_h_ #define LIKELY(x) __builtin_expect(!!(x), 1) #define UNLIKELY(x) __builtin_expect(!!(x), 0) #define ARRAY_SIZE(x) ((sizeof(x)/sizeof(x[0]))) #define BV(x) (1 << (x)) #ifndef NULL #define NULL 0 #endif #endif
hunjixin/ShootGame
src/lib/common/EventWell.js
class EventWell { constructor(losEvent,num) { this.eventWell = [] this.losEvent=losEvent this.wellDepth = num this.timer = setInterval(() => { this.eventWell.shift() }, 1000) } attach(event) { if (this.eventWell.length > this.wellDepth) this.eventWell.shift() this.eventWell.push(event) this.triggerComplexEvent() } triggerComplexEvent() { if (2 > this.eventWell.length) return var action = this.eventWell[0].action for (var i = 1; i < this.eventWell.length; i++) { var eventItem = this.eventWell[i] action = action + ' ' + eventItem.action this.losEvent.triggerNamedEvent(action, eventItem.eventInfo) } } } export default EventWell module.exports = EventWell
mezae/pfpaa
public/modules/letters/controllers/labels.js
<gh_stars>0 'use strict'; /* global _: false */ /* global LZString: false */ angular.module('letters').controller('LabelController', ['$scope', '$window', '$interval', '$http', '$location', '$modal', '$filter', 'Authentication', function($scope, $window, $interval, $http, $location, $modal, $filter, Authentication) { $scope.user = Authentication.user; if (!$scope.user || $scope.user.role === 'user') $location.path('/').replace(); $scope.fileURLs = []; $scope.hideDropzone = false; $scope.alert = { active: false, type: '', msg: '' }; //Allows admin to create new accounts function signup(credentials) { $http.post('/auth/signup', credentials).success(function(response) { console.log(response.message); }).error(function(response) { $scope.alert = { active: true, type: 'danger', msg: response.message }; }); } function makeid(){ var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for( var i=0; i < 12; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } //Helps create a downloadable csv version of the tracking form function downloadCSV(vids) { var headers = ['VoterID']; var csvString = headers.join(',') + '\r\n'; _.forEach(vids, function(vid) { signup({username: vid}); csvString += vid + '\r\n'; }); var date = $filter('date')(new Date(), 'MM-dd'); $scope.fileName = ('VoterIDs_' + date + '.csv'); var blob = new Blob([csvString], { type: 'text/csv;charset=UTF-8' }); var fileURL = $window.URL.createObjectURL(blob); $window.location.href = fileURL; } $scope.generateVoterIDs = function() { var vids = []; for(var i = 0; i < $scope.voters; i++) { var newID = makeid(); if (vids.indexOf(newID) < 0) { vids.push(newID); } } downloadCSV(vids); }; } ]);
ahmadiqbal1/vuetify
packages/api-generator/src/maps/v-alert.js
module.exports = { 'v-alert': { slots: [ { name: 'append', props: undefined, }, { name: 'close', props: { toggle: 'Function', }, }, { name: 'prepend', props: undefined, }, ], events: [ { name: 'input', value: 'boolean', }, ], functions: [ { name: 'toggle', signature: '(): void', }, ], }, }
poikilos/golgotha
loaders/dir_save.h
<filename>loaders/dir_save.h /********************************************************************** <BR> This file is part of Crack dot Com's free source code release of Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for information about compiling & licensing issues visit this URL</a> <PRE> If that doesn't help, contact <NAME> at <EMAIL> (Subject should have "GOLG" in it) ***********************************************************************/ #ifndef I4_DIR_SAVE_HH #define I4_DIR_SAVE_HH #include "file/file.h" #include "memory/array.h" struct i4_saver_section_type { w32 section_id; w32 section_offset; i4_saver_section_type(w32 section_id, w32 section_offset) : section_offset(section_offset), section_id(section_id) { } }; class i4_saver_class : public i4_file_class { protected: //Raw write is used if no directory is needed and skips should be ignored enum { DIRECTORY_CREATE, DATA_WRITE, DATA_LOAD, RAW_WRITE } state; w32 current_offset, last_version_start, current_skip; i4_file_class * out; i4_bool close_on_delete; i4_array<w16> skips; i4_array<i4_saver_section_type> sections; i4_array<w32> sizes; int marker_on; public: i4_saver_class(i4_file_class * out, i4_bool close_on_delete=i4_T); int mark_size(); void end_mark_size(int marker_number); void mark_section(w32 section_id); void mark_section(char * section_name); // calls above with checksum of name void start_version(w16 version); void end_version(); i4_bool begin_data_write(); // returns false if error occured virtual w32 read(void * buffer, w32 size); virtual w32 write(const void * buffer, w32 size); virtual w32 seek(w32 offset) { return out->seek(offset); } virtual w32 size() { return out->size(); } virtual w32 tell(); virtual ~i4_saver_class(); }; #endif
bdurrer/calendarizator
cal.web/src/components/application/bootstrap-breakpoint-directive.js
<gh_stars>1-10 import angular from 'angular'; const dependencies = []; export default angular .module('bootstrap-breakpoint', dependencies) .directive('bpListener', ['$window', '$timeout', '$rootScope', '$log', function ($window, $timeout, $rootScope, $log) { return { restrict: 'A', scope: { bpListener: '=?' }, template: '<div class="visible-xs"></div><div class="visible-sm"></div>' + '<div class="visible-md"></div><div class="visible-lg"></div>', link(directiveScope, iElement) { const scope = directiveScope; let t; const markers = iElement.find('div'); let currentVal = null; // map the bootstrap size names to numbers, to make comparison easier const sizeMap = { lg: 3, md: 2, sm: 1, xs: 0 }; /** * function to send an event when the size value changes */ function broadcastChange(newValue) { const oldValue = currentVal; currentVal = newValue; const paramOldVal = oldValue === null ? null : oldValue.substring(8); const paramNewVal = currentVal.substring(8); const valueObj = { sizeName: paramNewVal, size: sizeMap[paramNewVal], oldSizeName: paramOldVal, oldSize: sizeMap[paramOldVal] }; scope.bpListener = valueObj; $rootScope.$broadcast('bp-changed', valueObj); } /** * function to update the internal state value and trigger an event, when the value actually changes */ function updateDisplayMode(force) { angular.forEach(markers, (elem) => { if (elem.offsetParent !== null) { if (force || elem.className !== currentVal) { broadcastChange(elem.className); } } }); } /** * event listener for window.resize. * This is debounced by 300ms to prevent event-spam */ function onResize() { $timeout.cancel(t); t = $timeout(() => { updateDisplayMode(false); }, 300); // check if resize event is still happening } angular.element($window).on('resize', onResize); // send an event so that other components can enforce an bp-changed event. /* const unregisterFn = $rootScope.$on('bp-ping', () => { broadcastChange(currentVal); }); */ // unbind the event handlers when this component is destroyed function onDestroy() { $log.debug('unregistering listeners of directive bpListener upon destruction'); angular.element($window).off('resize', onResize); // unregisterFn(); } scope.$on('$destroy', onDestroy); updateDisplayMode(true); // fire it at least once } }; }]);
egg82/TrollCommandsPlusPlus
src/main/java/me/egg82/tcpp/tasks/TaskBurn.java
<reponame>egg82/TrollCommandsPlusPlus package me.egg82.tcpp.tasks; import java.util.Set; import java.util.UUID; import me.egg82.tcpp.services.CollectionProvider; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class TaskBurn implements Runnable { public TaskBurn() { } public void run() { Set<UUID> set = CollectionProvider.getSet("burn"); for (UUID u : set) { Player player = Bukkit.getPlayer(u); if (player == null) { continue; } player.setFireTicks(41); } } }
BradWhitlock/openvkl
openvkl/drivers/ispc/volume/amr/AMRVolume.cpp
<reponame>BradWhitlock/openvkl // Copyright 2019-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "AMRVolume.h" #include "../common/Data.h" #include "../../common/export_util.h" // ospcommon #include "ospcommon/tasking/parallel_for.h" #include "ospcommon/utility/getEnvVar.h" // ispc exports #include "AMRVolume_ispc.h" #include "method_current_ispc.h" #include "method_finest_ispc.h" #include "method_octant_ispc.h" // stl #include <map> #include <set> namespace openvkl { namespace ispc_driver { template <int W> AMRVolume<W>::AMRVolume() { this->ispcEquivalent = CALL_ISPC(AMRVolume_create, this); } template <int W> std::string AMRVolume<W>::toString() const { return "openvkl::AMRVolume"; } template <int W> void AMRVolume<W>::commit() { amrMethod = (VKLAMRMethod)this->template getParam<int>("method", VKL_AMR_CURRENT); if (amrMethod == VKL_AMR_CURRENT) CALL_ISPC(AMR_install_current, this->ispcEquivalent); else if (amrMethod == VKL_AMR_FINEST) CALL_ISPC(AMR_install_finest, this->ispcEquivalent); else if (amrMethod == VKL_AMR_OCTANT) CALL_ISPC(AMR_install_octant, this->ispcEquivalent); if (data != nullptr) // TODO: support data updates return; blockBoundsData = (Data *)this->template getParam<ManagedObject::VKL_PTR>( "block.bounds", nullptr); if (blockBoundsData.ptr == nullptr) throw std::runtime_error("amr volume must have 'block.bounds' array"); refinementLevelsData = (Data *)this->template getParam<ManagedObject::VKL_PTR>("block.level", nullptr); if (refinementLevelsData.ptr == nullptr) throw std::runtime_error("amr volume must have 'block.level' array"); cellWidthsData = (Data *)this->template getParam<ManagedObject::VKL_PTR>( "cellWidth", nullptr); if (cellWidthsData.ptr == nullptr) throw std::runtime_error("amr volume must have 'cellWidth' array"); blockDataData = (Data *)this->template getParam<ManagedObject::VKL_PTR>( "block.data", nullptr); if (blockDataData.ptr == nullptr) throw std::runtime_error("amr volume must have 'block.data' array"); // create the AMR data structure. This creates the logical blocks, which // contain the actual data and block-level metadata, such as cell width // and refinement level data = make_unique<amr::AMRData>(*blockBoundsData, *refinementLevelsData, *cellWidthsData, *blockDataData); // create the AMR acceleration structure. This creates a k-d tree // representation of the blocks in the AMRData object. In short, blocks at // the highest refinement level (i.e. with the most detail) are leaf // nodes, and parents have progressively lower resolution accel = make_unique<amr::AMRAccel>(*data); float coarsestCellWidth = *std::max_element( cellWidthsData->begin<float>(), cellWidthsData->end<float>()); float samplingStep = 0.1f * coarsestCellWidth; bounds = accel->worldBounds; const vec3f gridSpacing = this->template getParam<vec3f>("gridSpacing", vec3f(1.f)); const vec3f gridOrigin = this->template getParam<vec3f>("gridOrigin", vec3f(0.f)); // determine voxelType from set of block data; they must all be the same std::set<VKLDataType> blockDataTypes; for (int i = 0; i < blockDataData->numItems; i++) blockDataTypes.insert(((Data **)blockDataData->data)[i]->dataType); if (blockDataTypes.size() != 1) throw std::runtime_error( "all block.data entries must have same VKLDataType"); voxelType = *blockDataTypes.begin(); switch (voxelType) { case VKL_UCHAR: break; case VKL_SHORT: break; case VKL_USHORT: break; case VKL_FLOAT: break; case VKL_DOUBLE: break; default: throw std::runtime_error( "AMR volume 'block.data' entries have invalid VKLDataType. " "must be one of: VKL_UCHAR, VKL_SHORT, " "VKL_USHORT, VKL_FLOAT, VKL_DOUBLE"); } CALL_ISPC(AMRVolume_set, this->ispcEquivalent, (ispc::box3f &)bounds, samplingStep, (const ispc::vec3f &)gridOrigin, (const ispc::vec3f &)gridSpacing); CALL_ISPC(AMRVolume_setAMR, this->ispcEquivalent, accel->node.size(), &accel->node[0], accel->leaf.size(), &accel->leaf[0], accel->level.size(), &accel->level[0], voxelType, (ispc::box3f &)bounds); // parse the k-d tree to compute the voxel range of each leaf node. // This enables empty space skipping within the hierarchical structure tasking::parallel_for(accel->leaf.size(), [&](size_t leafID) { CALL_ISPC( AMRVolume_computeValueRangeOfLeaf, this->ispcEquivalent, leafID); }); // compute value range over the full volume for (const auto &l : accel->leaf) { valueRange.extend(l.valueRange); } } template <int W> void AMRVolume<W>::computeSampleV(const vintn<W> &valid, const vvec3fn<W> &objectCoordinates, vfloatn<W> &samples) const { CALL_ISPC(AMRVolume_sample_export, static_cast<const int *>(valid), this->ispcEquivalent, &objectCoordinates, &samples); } template <int W> void AMRVolume<W>::computeGradientV(const vintn<W> &valid, const vvec3fn<W> &objectCoordinates, vvec3fn<W> &gradients) const { THROW_NOT_IMPLEMENTED; } template <int W> box3f AMRVolume<W>::getBoundingBox() const { return bounds; } template <int W> range1f AMRVolume<W>::getValueRange() const { return valueRange; } VKL_REGISTER_VOLUME(AMRVolume<VKL_TARGET_WIDTH>, CONCAT1(internal_amr_, VKL_TARGET_WIDTH)) } // namespace ispc_driver } // namespace openvkl
gesucca-official/bm-server
src/main/java/com/gsc/bm/service/factories/ValueNotFoundException.java
package com.gsc.bm.service.factories; public class ValueNotFoundException extends RuntimeException { public ValueNotFoundException(String what) { super(what); } }
azadmanesh/jt-tracer
truffle/src/main/java/org/jruby/truffle/parser/ast/KeywordArgParseNode.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.jruby.truffle.parser.ast; import org.jruby.truffle.parser.ast.visitor.NodeVisitor; import org.jruby.truffle.parser.lexer.ISourcePosition; import java.util.List; /** * * @author enebo */ public class KeywordArgParseNode extends ParseNode { private AssignableParseNode assignable; public KeywordArgParseNode(ISourcePosition position, AssignableParseNode assignable) { super(position, true); this.assignable = assignable; } @Override public <T> T accept(NodeVisitor<T> visitor) { return visitor.visitKeywordArgNode(this); } @Override public List<ParseNode> childNodes() { return ParseNode.createList(assignable); } public int getIndex() { return ((IScopedNode) assignable).getIndex(); } @Override public NodeType getNodeType() { return NodeType.KEYWORDARGNODE; } public AssignableParseNode getAssignable() { return assignable; } }
eostermueller/havoc2
backend/src/main/java/com/github/eostermueller/snail4j/launcher/Event.java
package com.github.eostermueller.snail4j.launcher; import com.github.eostermueller.snail4j.DefaultFactory; import com.github.eostermueller.snail4j.FixedLengthQueue; import com.github.eostermueller.snail4j.Snail4jException; public class Event { private static int maxExceptionsPerEvent; long timestamp = -1; public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } static { try { maxExceptionsPerEvent = DefaultFactory.getFactory() .getConfiguration() .getMaxExceptionCountPerEvent(); } catch ( Snail4jException e) { e.printStackTrace(); } } public static Event create(String desc, Snail4jException exception) { Event e = new Event(); e.exceptions.add(exception); e.setDescription(desc); e.setTimestamp(System.currentTimeMillis()); return e; } public static Event create(String desc) { Event e = new Event(); e.setDescription(desc); e.setTimestamp(System.currentTimeMillis()); return e; } FixedLengthQueue<Exception> exceptions = new FixedLengthQueue<Exception>( maxExceptionsPerEvent ); public FixedLengthQueue<Exception> getExceptions() { return exceptions; } public void setExceptions(FixedLengthQueue<Exception> exceptions) { this.exceptions = exceptions; } String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String debug() { StringBuilder sb = new StringBuilder(); sb.append("Event [" + this.getDescription() + "] timestamp[" + String.valueOf(this.getTimestamp()) + "]"); for(Snail4jException te : this.getExceptions().toArray( new Snail4jException[] {} ) ) { sb.append( te.toHumanReadableString() ); } return sb.toString(); } }
nellochen/springboot-start
utils/src/main/java/com/xiaofeng/utils/designpatterns/interpreter/context/ExpressionNode.java
<gh_stars>1-10 package com.xiaofeng.utils.designpatterns.interpreter.context; import java.util.ArrayList; import java.util.Iterator; /** * @author <NAME> * @version 1.0.0 * @date 2017/07/28 * @email <EMAIL> */ public class ExpressionNode extends Node { private ArrayList<Node> list = new ArrayList<Node>(); //定义一个集合用于存储多条命令 public void interpret(Context context) { //循环处理Context中的标记 while (true) { //如果已经没有任何标记,则退出解释 if (context.currentToken() == null) { break; } //如果标记为END,则不解释END并结束本次解释过程,可以继续之后的解释 else if (context.currentToken().equals("END")) { context.skipToken("END"); break; } //如果为其他标记,则解释标记并将其加入命令集合 else { Node commandNode = new CommandNode(); commandNode.interpret(context); list.add(commandNode); } } } //循环执行命令集合中的每一条命令 public void execute() { Iterator iterator = list.iterator(); while (iterator.hasNext()) { ((Node) iterator.next()).execute(); } } }
ioggstream/armeria
core/src/main/java/com/linecorp/armeria/common/stream/DefaultHttpDeframer.java
/* * Copyright 2020 LINE Corporation * * LINE Corporation 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.common.stream; import static java.util.Objects.requireNonNull; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.function.Function; import javax.annotation.Nullable; import org.reactivestreams.Subscription; import com.linecorp.armeria.common.HttpData; import com.linecorp.armeria.common.HttpHeaders; import com.linecorp.armeria.common.HttpObject; import com.linecorp.armeria.common.ResponseHeaders; import com.linecorp.armeria.common.util.Exceptions; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.util.concurrent.EventExecutor; /** * The default {@link HttpDeframer} implementation. */ final class DefaultHttpDeframer<T> extends DefaultStreamMessage<T> implements HttpDeframer<T>, HttpDeframerOutput<T> { @SuppressWarnings("rawtypes") private static final AtomicReferenceFieldUpdater<DefaultHttpDeframer, Subscription> upstreamUpdater = AtomicReferenceFieldUpdater.newUpdater(DefaultHttpDeframer.class, Subscription.class, "upstream"); @SuppressWarnings("rawtypes") private static final AtomicIntegerFieldUpdater<DefaultHttpDeframer> initializedUpdater = AtomicIntegerFieldUpdater.newUpdater(DefaultHttpDeframer.class, "initialized"); @SuppressWarnings("rawtypes") private static final AtomicIntegerFieldUpdater<DefaultHttpDeframer> askedUpstreamForElementUpdater = AtomicIntegerFieldUpdater.newUpdater(DefaultHttpDeframer.class, "askedUpstreamForElement"); private final HttpDeframerHandler<T> handler; private final ByteBufDeframerInput input; private final Function<? super HttpData, ? extends ByteBuf> byteBufConverter; private boolean handlerProduced; private boolean sawLeadingHeaders; @Nullable private volatile EventExecutor eventLoop; @Nullable private volatile Subscription upstream; private volatile int initialized; private volatile int askedUpstreamForElement; @Nullable private volatile Throwable cause; private volatile boolean cancelled; private volatile boolean completing; /** * Returns a new {@link DefaultHttpDeframer} with the specified {@link HttpDeframerHandler}, * {@link ByteBufAllocator} and {@code byteBufConverter}. */ DefaultHttpDeframer(HttpDeframerHandler<T> handler, ByteBufAllocator alloc, Function<? super HttpData, ? extends ByteBuf> byteBufConverter) { this.handler = requireNonNull(handler, "handler"); input = new ByteBufDeframerInput(requireNonNull(alloc, "alloc")); this.byteBufConverter = requireNonNull(byteBufConverter, "byteBufConverter"); whenComplete().handle((unused1, unused2) -> { // In addition to 'onComplete()', 'onError()' and 'cancel()', // make sure to call 'cleanup()' even when 'abort()' or 'close()' is invoked directly cleanup(); return null; }); } @Override public void add(T e) { if (tryWrite(e)) { handlerProduced = true; } } @Override SubscriptionImpl subscribe(SubscriptionImpl subscription) { final SubscriptionImpl subscriptionImpl = super.subscribe(subscription); if (subscriptionImpl == subscription) { final EventExecutor eventLoop = subscription.executor(); this.eventLoop = eventLoop; deferredInit(eventLoop); } return subscriptionImpl; } private void deferredInit(@Nullable EventExecutor eventLoop) { final Subscription upstream = this.upstream; if (upstream != null && eventLoop != null) { if (initializedUpdater.compareAndSet(this, 0, 1)) { if (cancelled) { upstream.cancel(); return; } final Throwable cause = this.cause; if (cause != null) { if (eventLoop.inEventLoop()) { onError0(cause); } else { eventLoop.execute(() -> onError0(cause)); } return; } if (completing) { if (eventLoop.inEventLoop()) { onComplete0(); } else { eventLoop.execute(this::onComplete0); } return; } if (demand() > 0) { askUpstreamForElement(); } } } } @Override void request(long n) { // Fetch from upstream only when this deframer is initialized and the given demand is valid. if (initialized != 0 && n > 0) { askUpstreamForElement(); } super.request(n); } private void askUpstreamForElement() { if (askedUpstreamForElementUpdater.compareAndSet(this, 0, 1)) { final Subscription upstream = this.upstream; assert upstream != null; upstream.request(1); } } @Override void cancel() { cancelAndCleanup(); super.cancel(); } @Override public void onSubscribe(Subscription subscription) { requireNonNull(subscription, "subscription"); if (upstreamUpdater.compareAndSet(this, null, subscription)) { deferredInit(eventLoop); } else { subscription.cancel(); } } @Override public void onNext(HttpObject data) { final EventExecutor eventLoop = this.eventLoop; assert eventLoop != null; if (eventLoop.inEventLoop()) { onNext0(data); } else { eventLoop.execute(() -> onNext0(data)); } } private void onNext0(HttpObject obj) { askedUpstreamForElement = 0; handlerProduced = false; try { // Call the handler so that it publishes something. if (obj instanceof HttpHeaders) { final HttpHeaders headers = (HttpHeaders) obj; if (headers instanceof ResponseHeaders && ((ResponseHeaders) headers).status().isInformational()) { handler.processInformationalHeaders((ResponseHeaders) headers, this); } else if (!sawLeadingHeaders) { sawLeadingHeaders = true; handler.processHeaders((HttpHeaders) obj, this); } else { handler.processTrailers((HttpHeaders) obj, this); } } else if (obj instanceof HttpData) { final HttpData data = (HttpData) obj; final ByteBuf byteBuf = byteBufConverter.apply(data); requireNonNull(byteBuf, "byteBufConverter.apply() returned null"); if (input.add(byteBuf)) { handler.process(input, this); } } if (handlerProduced) { // Handler produced something. if (askedUpstreamForElement == 0) { // Ask the upstream for more elements after the produced elements are fully consumed and // there are still demands left. whenConsumed().handle((unused1, unused2) -> { if (demand() > 0) { askUpstreamForElement(); } return null; }); } else { // No need to ask the upstream for more elements because: // - The handler triggered Subscription.request(); or // - Subscription.request() was called from another thread. } } else { // Handler didn't produce anything, which means it needs more elements from the upstream // to produce something. askUpstreamForElement(); } } catch (Throwable ex) { handler.processOnError(ex); cancelAndCleanup(); abort(ex); Exceptions.throwIfFatal(ex); } } private void cancelAndCleanup() { if (cancelled) { return; } cancelled = true; final Subscription upstream = this.upstream; if (upstream != null) { upstream.cancel(); } cleanup(); } @Override public void onError(Throwable cause) { requireNonNull(cause, "cause"); if (cancelled) { return; } this.cause = cause; final EventExecutor eventLoop = this.eventLoop; if (eventLoop != null) { if (eventLoop.inEventLoop()) { onError0(cause); } else { eventLoop.execute(() -> onError0(cause)); } } } private void onError0(Throwable cause) { if (!(cause instanceof AbortedStreamException)) { handler.processOnError(cause); } abort(cause); cleanup(); } @Override public void onComplete() { if (cancelled) { return; } completing = true; final EventExecutor eventLoop = this.eventLoop; if (eventLoop != null) { if (eventLoop.inEventLoop()) { onComplete0(); } else { eventLoop.execute(this::onComplete0); } } } private void onComplete0() { cleanup(); close(); } private void cleanup() { input.close(); } }
jitwxs/addax
easydata/src/main/java/io/github/jitwxs/easydata/core/mybatis/MyBatisMapperInspect.java
<reponame>jitwxs/addax<gh_stars>1-10 package io.github.jitwxs.easydata.core.mybatis; import io.github.jitwxs.easydata.common.exception.EasyDataException; import io.github.jitwxs.easydata.common.util.ReflectionUtils; import io.github.jitwxs.easydata.core.mybatis.action.IMapperInspectAction; import io.github.jitwxs.easydata.core.mybatis.action.IMapperInspectRuntimeAction; import io.github.jitwxs.easydata.core.mybatis.action.IMapperInspectStaticAction; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.session.Configuration; import org.mockito.Mockito; import org.reflections.Reflections; import org.reflections.scanners.Scanners; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Set; import static io.github.jitwxs.easydata.common.util.CollectionUtils.randomElement; /** * inspect for mybatis mapper file * * @author <EMAIL> * @since 2022-06-04 23:27 */ @Slf4j public abstract class MyBatisMapperInspect<T> { /** * the mybatis mapper object */ public final T target; /** * the mybatis mapper class */ private final Class<T> targetClass; private final XMLMapperBuilder xmlMapperBuilder; private final List<IMapperInspectRuntimeAction> runtimeActions = new ArrayList<>(); public abstract List<IMapperInspectAction> actionList(); public MyBatisMapperInspect() { // initial targetClass this.targetClass = (Class<T>) ReflectionUtils.getGenericSuperClass(this.getClass())[0]; if (!this.targetClass.isInterface()) { throw new EasyDataException("MyBatis mapper T must be interface"); } // initial target this.target = Mockito.mock(this.targetClass, invocation -> { this.interceptorInvoke(invocation.getMethod(), invocation.getArguments()); return null; }); // initial xmlMapperBuilder final String xmlLocation = xmlLocation(); try (final InputStream is = targetClass.getResourceAsStream(xmlLocation)) { final Configuration configuration = new Configuration(); this.xmlMapperBuilder = new XMLMapperBuilder(is, configuration, xmlLocation, configuration.getSqlFragments()); this.xmlMapperBuilder.parse(); } catch (IOException e) { throw new EasyDataException(e); } // initial runtimeActions for (IMapperInspectAction action : CollectionUtils.emptyIfNull(actionList())) { if (action instanceof IMapperInspectStaticAction) { ((IMapperInspectStaticAction) action).doAction(xmlMapperBuilder); } else if (action instanceof IMapperInspectRuntimeAction) { runtimeActions.add((IMapperInspectRuntimeAction) action); } } } /** * return the mapper xml file location in system, the default implements will find same name file in classpath, * when find nothing, will throw {@link EasyDataException}; when find more than one, will return random one. * you can override this method, to specify actual implements. * * @return mapper xml file location * @throws EasyDataException not fond xml file in classpath */ public String xmlLocation() { final Reflections reflections = new Reflections(Scanners.Resources); final Set<String> resources = reflections.getResources(String.format(".*%s\\.xml", targetClass.getSimpleName())); if (CollectionUtils.isEmpty(resources)) { throw new EasyDataException("MyBatis mapper xml file location not exist"); } final String location = randomElement(resources); return "/" + location; } /** * do interceptor when invoke mapper's method * * @param method invoked method * @param arguments invoked method arguments */ private void interceptorInvoke(final Method method, final Object[] arguments) { for (IMapperInspectRuntimeAction action : runtimeActions) { action.doAction(xmlMapperBuilder, method, arguments); } } }
eDanilovich-qa/aquality-tracking-api
src/test/java/tests/workers/dao/IDaoTest.java
package tests.workers.dao; import main.exceptions.AqualityException; public interface IDaoTest { void searchAllTest() throws AqualityException; void insertTest() throws AqualityException; void removeTest() throws AqualityException; }
MarkieMark/fastrl
src/behavior/singleagent/options/environment_option_outcome.hpp
/** * <NAME> 1st June 2017 */ #ifndef FASTRL_BEHAVIOR_SINGLEAGENT_OPTIONS_ENVIRONMENT_OPTION_OUTCOME_HPP #define FASTRL_BEHAVIOR_SINGLEAGENT_OPTIONS_ENVIRONMENT_OPTION_OUTCOME_HPP #include <cmath> #include "../../../mdp/singleagent/environment/environment_outcome.hpp" #include "../episode.h" class EnvironmentOptionOutcome : public EnvironmentOutcome { public: double discount; Episode * episode; EnvironmentOptionOutcome(State *s, Action *a, State *sp, double reward, bool done, double discountFactor, Episode * episode_) : EnvironmentOutcome(s, a, sp, reward, done) { discount = pow(discountFactor, episode->actionSequence.size()); episode = episode_; } long nIterations() override { return episode->actionSequence.size(); } }; #endif // FASTRL_BEHAVIOR_SINGLEAGENT_OPTIONS_ENVIRONMENT_OPTION_OUTCOME_HPP
xmanjack/bk-bcs
bcs-services/bcs-api/pkg/server/proxier/utils.go
<reponame>xmanjack/bk-bcs<gh_stars>0 /* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 proxier import ( "context" "crypto/tls" "net" "net/url" "strings" "time" restclient "k8s.io/client-go/rest" m "bk-bcs/bcs-services/bcs-api/pkg/models" "fmt" ) func ExtractIpAddress(serverAddress string) (*url.URL, error) { if !strings.HasSuffix(serverAddress, "/") { serverAddress = serverAddress + "/" } ipAddress, err := url.Parse(serverAddress) if err != nil { return nil, err } return ipAddress, nil } func TurnCredentialsIntoConfig(clusterCredentials *m.ClusterCredentials) (*restclient.Config, error) { tlsClientConfig := restclient.TLSClientConfig{ CAData: []byte(clusterCredentials.CaCertData), } dialer := &net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 0 * time.Second, } ipAddress, err := ExtractIpAddress(clusterCredentials.ServerAddresses) if err != nil { return nil, err } return &restclient.Config{ Host: clusterCredentials.ServerAddresses, BearerToken: clusterCredentials.UserToken, TLSClientConfig: tlsClientConfig, Dial: func(ctx context.Context, network, addr string) (net.Conn, error) { // resolve domain to real apiserver address addr = ipAddress.Host return dialer.DialContext(ctx, network, addr) }, }, nil } // check tcp connection to addr func CheckTcpConn(addr string) error { checkUrl, err := url.Parse(addr) if err != nil { return err } err = dialTls(checkUrl.Host) if err != nil { return fmt.Errorf("connection to "+addr+" failed: %s", err.Error()) } return nil } func dialTls(host string) error { conf := &tls.Config{ InsecureSkipVerify: true, } conn, err := tls.Dial("tcp", host, conf) if err != nil { return err } defer conn.Close() return nil }
nelsoncole/sirius-x86-64
user/lib/sys/include/netinet/in.h
#ifndef __IN_H__ #define __IN_H__ #include <sys/socket.h> #define IPPROTO_IP 0 #define IPPROTO_ICMP 1 #define IPPROTO_IGMP 2 #define IPPROTO_TCP 6 #define IPPROTO_UDP 17 #define IPPROTO_IPV6 41 typedef unsigned int in_addr_t; struct in_addr { in_addr_t s_addr; }; struct sockaddr_in { sa_family_t sin_family; unsigned short sin_port; struct in_addr sin_addr; }; #define INADDR_ANY 0x00000000 #define INADDR_BROADCAST 0xFFFFFFFF #define IPPORT_RESERVED 1024 #define IPPORT_UNRESERVED 0xC000 #define INET_ADDRSTRLEN 16 #endif
tannerwelsh/sandbox
find_missing_number.rb
<gh_stars>0 # Setup an array of randomly sorted numbers @numbers = (1..1_000_000).to_a.shuffle @numbers.delete_at(rand(1_000_000)) def sort_find sorted = @numbers.sort sorted.each_with_index do |n, i| next if n == sorted[i-1] + 1 || n == 0 return n-1 end end def inject_find (1..1_000_000).inject(&:+) - @numbers.inject(&:+) end def new_array_find new_array = [] # Array.new(1_000_000) @numbers.each { |n| new_array[n-1] = n } new_array.index(nil) + 1 end t1 = Time.now sort_find t2 = Time.now p "Time to execute sort_find: #{t2 - t1}" p "Found the missing number: #{@numbers.index(sort_find) == nil}" t3 = Time.now inject_find t4 = Time.now p "Time to execute inject_find: #{t4 - t3}" p "Found the missing number: #{@numbers.index(inject_find) == nil}" t5 = Time.now new_array_find t6 = Time.now p "Time to execute new_array_find: #{t6 - t5}" p "Found the missing number: #{@numbers.index(new_array_find) == nil}" case [(t6-t5),(t4-t3),(t2-t1)].min when t2-t1 then fastest = :sort_find when t4-t3 then fastest = :inject_find when t6-t5 then fastest = :new_array_find end p "-----------------\nFASTEST METHOD: #{fastest}"
alexeyche/vespa
searchlib/src/vespa/searchlib/features/distancefeature.cpp
<gh_stars>0 // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "distancefeature.h" #include <vespa/searchcommon/common/schema.h> #include <vespa/searchlib/common/geo_location_spec.h> #include <vespa/searchlib/fef/matchdata.h> #include <vespa/document/datatype/positiondatatype.h> #include <vespa/vespalib/geo/zcurve.h> #include <vespa/vespalib/util/issue.h> #include <vespa/vespalib/util/stash.h> #include <cmath> #include <limits> #include "utils.h" #include <vespa/log/log.h> LOG_SETUP(".features.distancefeature"); using namespace search::fef; using namespace search::index::schema; using vespalib::Issue; namespace search::features { /** Implements the executor for converting NNS rawscore to a distance feature. */ class ConvertRawscoreToDistance : public fef::FeatureExecutor { private: std::vector<fef::TermFieldHandle> _handles; const fef::MatchData *_md; void handle_bind_match_data(const fef::MatchData &md) override { _md = &md; } public: ConvertRawscoreToDistance(const fef::IQueryEnvironment &env, uint32_t fieldId); ConvertRawscoreToDistance(const fef::IQueryEnvironment &env, const vespalib::string &label); void execute(uint32_t docId) override; }; ConvertRawscoreToDistance::ConvertRawscoreToDistance(const fef::IQueryEnvironment &env, uint32_t fieldId) : _handles(), _md(nullptr) { _handles.reserve(env.getNumTerms()); for (uint32_t i = 0; i < env.getNumTerms(); ++i) { search::fef::TermFieldHandle handle = util::getTermFieldHandle(env, i, fieldId); if (handle != search::fef::IllegalHandle) { _handles.push_back(handle); } } } ConvertRawscoreToDistance::ConvertRawscoreToDistance(const fef::IQueryEnvironment &env, const vespalib::string &label) : _handles(), _md(nullptr) { const ITermData *term = util::getTermByLabel(env, label); if (term != nullptr) { // expect numFields() == 1 for (uint32_t i = 0; i < term->numFields(); ++i) { TermFieldHandle handle = term->field(i).getHandle(); if (handle != IllegalHandle) { _handles.push_back(handle); } } } } void ConvertRawscoreToDistance::execute(uint32_t docId) { feature_t min_distance = std::numeric_limits<feature_t>::max(); assert(_md); for (auto handle : _handles) { const TermFieldMatchData *tfmd = _md->resolveTermField(handle); if (tfmd->getDocId() == docId) { feature_t invdist = tfmd->getRawScore(); feature_t converted = (1.0 / invdist) - 1.0; min_distance = std::min(min_distance, converted); } } outputs().set_number(0, min_distance); } feature_t DistanceExecutor::calculateDistance(uint32_t docId) { _best_index = -1.0; _best_x = -180.0 * 1.0e6; _best_y = 90.0 * 1.0e6; if ((! _locations.empty()) && (_pos != nullptr)) { LOG(debug, "calculate 2D Z-distance from %zu locations", _locations.size()); return calculate2DZDistance(docId); } return DEFAULT_DISTANCE; } feature_t DistanceExecutor::calculate2DZDistance(uint32_t docId) { _intBuf.fill(*_pos, docId); uint32_t numValues = _intBuf.size(); uint64_t sqabsdist = std::numeric_limits<uint64_t>::max(); int32_t docx = 0; int32_t docy = 0; for (auto loc : _locations) { assert(loc); assert(loc->location.valid()); for (uint32_t i = 0; i < numValues; ++i) { vespalib::geo::ZCurve::decode(_intBuf[i], &docx, &docy); uint64_t sqdist = loc->location.sq_distance_to({docx, docy}); if (sqdist < sqabsdist) { _best_index = i; _best_x = docx; _best_y = docy; sqabsdist = sqdist; } } } return static_cast<feature_t>(std::sqrt(static_cast<feature_t>(sqabsdist))); } DistanceExecutor::DistanceExecutor(GeoLocationSpecPtrs locations, const search::attribute::IAttributeVector * pos) : FeatureExecutor(), _locations(locations), _pos(pos), _intBuf() { if (_pos != nullptr) { _intBuf.allocate(_pos->getMaxValueCount()); } } void DistanceExecutor::execute(uint32_t docId) { static constexpr double earth_mean_radius = 6371.0088; static constexpr double deg_to_rad = M_PI / 180.0; static constexpr double km_from_internal = 1.0e-6 * deg_to_rad * earth_mean_radius; feature_t internal_d = calculateDistance(docId); outputs().set_number(0, internal_d); outputs().set_number(1, _best_index); outputs().set_number(2, _best_y * 1.0e-6); // latitude outputs().set_number(3, _best_x * 1.0e-6); // longitude outputs().set_number(4, internal_d * km_from_internal); // km } const feature_t DistanceExecutor::DEFAULT_DISTANCE(6400000000.0); DistanceBlueprint::DistanceBlueprint() : Blueprint("distance"), _field_name(), _arg_string(), _attr_id(search::index::Schema::UNKNOWN_FIELD_ID), _use_geo_pos(false), _use_nns_tensor(false), _use_item_label(false) { } DistanceBlueprint::~DistanceBlueprint() = default; void DistanceBlueprint::visitDumpFeatures(const IIndexEnvironment &, IDumpFeatureVisitor &) const { } Blueprint::UP DistanceBlueprint::createInstance() const { return std::make_unique<DistanceBlueprint>(); } bool DistanceBlueprint::setup_geopos(const IIndexEnvironment & env, const vespalib::string &attr) { _arg_string = attr; _use_geo_pos = true; describeOutput("out", "The euclidean distance from the query position."); describeOutput("index", "Index in array of closest point"); describeOutput("latitude", "Latitude of closest point"); describeOutput("longitude", "Longitude of closest point"); describeOutput("km", "Distance in kilometer units"); env.hintAttributeAccess(_arg_string); return true; } bool DistanceBlueprint::setup_nns(const IIndexEnvironment & env, const vespalib::string &attr) { _arg_string = attr; _use_nns_tensor = true; describeOutput("out", "The euclidean distance from the query position."); env.hintAttributeAccess(_arg_string); return true; } bool DistanceBlueprint::setup(const IIndexEnvironment & env, const ParameterList & params) { // params[0] = attribute name vespalib::string arg = params[0].getValue(); bool allow_bad_field = true; if (params.size() == 2) { // params[0] = field / label // params[1] = attribute name / label value if (arg == "label") { _arg_string = params[1].getValue(); _use_item_label = true; describeOutput("out", "The euclidean distance from the labeled query item."); return true; } else if (arg == "field") { arg = params[1].getValue(); allow_bad_field = false; } else { LOG(error, "first argument must be 'field' or 'label', but was '%s'", arg.c_str()); return false; } } _field_name = arg; vespalib::string z = document::PositionDataType::getZCurveFieldName(arg); const FieldInfo *fi = env.getFieldByName(z); if (fi != nullptr && fi->hasAttribute()) { // can't check anything here because streaming has wrong information return setup_geopos(env, z); } fi = env.getFieldByName(arg); if (fi != nullptr && fi->hasAttribute()) { auto dt = fi->get_data_type(); auto ct = fi->collection(); if (dt == DataType::TENSOR && ct == CollectionType::SINGLE) { _attr_id = fi->id(); return setup_nns(env, arg); } // could check if ct is CollectionType::SINGLE or CollectionType::ARRAY) if (dt == DataType::INT64) { return setup_geopos(env, arg); } } if (allow_bad_field) { // TODO remove on Vespa 8 // backwards compatibility fallback: return setup_geopos(env, arg); } if (env.getFieldByName(arg) == nullptr) { LOG(error, "unknown field '%s' for rank feature %s\n", arg.c_str(), getName().c_str()); } else { LOG(error, "field '%s' must be an attribute for rank feature %s\n", arg.c_str(), getName().c_str()); } return false; } FeatureExecutor & DistanceBlueprint::createExecutor(const IQueryEnvironment &env, vespalib::Stash &stash) const { if (_use_nns_tensor) { return stash.create<ConvertRawscoreToDistance>(env, _attr_id); } if (_use_item_label) { return stash.create<ConvertRawscoreToDistance>(env, _arg_string); } // expect geo pos: const search::attribute::IAttributeVector * pos = nullptr; GeoLocationSpecPtrs matching_locs; GeoLocationSpecPtrs other_locs; for (auto loc_ptr : env.getAllLocations()) { if (_use_geo_pos && loc_ptr && loc_ptr->location.valid()) { if (loc_ptr->field_name == _arg_string || loc_ptr->field_name == _field_name) { LOG(debug, "found loc from query env matching '%s'", _arg_string.c_str()); matching_locs.push_back(loc_ptr); } else { LOG(debug, "found loc(%s) from query env not matching arg(%s)", loc_ptr->field_name.c_str(), _arg_string.c_str()); other_locs.push_back(loc_ptr); } } } if (matching_locs.empty() && other_locs.empty()) { LOG(debug, "createExecutor: no valid locations"); return stash.create<DistanceExecutor>(matching_locs, nullptr); } LOG(debug, "createExecutor: valid location, attribute='%s'", _arg_string.c_str()); if (_use_geo_pos) { pos = env.getAttributeContext().getAttribute(_arg_string); if (pos != nullptr) { if (!pos->isIntegerType()) { Issue::report("distance feature: The position attribute '%s' is not an integer attribute. Will use default distance.", pos->getName().c_str()); pos = nullptr; } else if (pos->getCollectionType() == attribute::CollectionType::WSET) { Issue::report("distance feature: The position attribute '%s' is a weighted set attribute. Will use default distance.", pos->getName().c_str()); pos = nullptr; } } else { Issue::report("distance feature: The position attribute '%s' was not found. Will use default distance.", _arg_string.c_str()); } } LOG(debug, "use '%s' locations with pos=%p", matching_locs.empty() ? "other" : "matching", pos); return stash.create<DistanceExecutor>(matching_locs.empty() ? other_locs : matching_locs, pos); } }
anphil/mattermost-server
model/team_test.go
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package model import ( "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTeamJson(t *testing.T) { o := Team{Id: NewId(), DisplayName: NewId()} json := o.ToJson() ro := TeamFromJson(strings.NewReader(json)) require.Equal(t, o.Id, ro.Id, "Ids do not match") } func TestTeamIsValid(t *testing.T) { o := Team{} err := o.IsValid() require.NotNil(t, err, "should be invalid") o.Id = NewId() err = o.IsValid() require.NotNil(t, err, "should be invalid") o.CreateAt = GetMillis() err = o.IsValid() require.NotNil(t, err, "should be invalid") o.UpdateAt = GetMillis() err = o.IsValid() require.NotNil(t, err, "should be invalid") o.Email = strings.Repeat("01234567890", 20) err = o.IsValid() require.NotNil(t, err, "should be invalid") o.Email = "<EMAIL>" o.DisplayName = strings.Repeat("01234567890", 20) err = o.IsValid() require.NotNil(t, err, "should be invalid") o.DisplayName = "1234" o.Name = "ZZZZZZZ" err = o.IsValid() require.NotNil(t, err, "should be invalid") o.Name = "zzzzz" o.Type = TeamOpen o.InviteId = NewId() err = o.IsValid() require.Nil(t, err, err) } func TestTeamPreSave(t *testing.T) { o := Team{DisplayName: "test"} o.PreSave() o.Etag() } func TestTeamPreUpdate(t *testing.T) { o := Team{DisplayName: "test"} o.PreUpdate() } var domains = []struct { value string expected bool }{ {"spin-punch", true}, {"-spin-punch", false}, {"spin-punch-", false}, {"spin_punch", false}, {"a", false}, {"aa", true}, {"aaa", true}, {"aaa-999b", true}, {"b00b", true}, {"b)", false}, {"test", true}, } func TestValidTeamName(t *testing.T) { for _, v := range domains { actual := IsValidTeamName(v.value) assert.Equal(t, v.expected, actual) } } var tReservedDomains = []struct { value string expected bool }{ {"admin", true}, {"Admin-punch", true}, {"spin-punch-admin", false}, {"playbooks", true}, {"boards", true}, } func TestReservedTeamName(t *testing.T) { for _, v := range tReservedDomains { actual := IsReservedTeamName(v.value) assert.Equal(t, v.expected, actual) } } func TestCleanTeamName(t *testing.T) { actual := CleanTeamName("Jimbo's Admin") require.Equal(t, "jimbos-admin", actual, "didn't clean name properly") actual = CleanTeamName("Admin Really cool") require.Equal(t, "really-cool", actual, "didn't clean name properly") actual = CleanTeamName("super-duper-guys") require.Equal(t, "super-duper-guys", actual, "didn't clean name properly") } func TestTeamPatch(t *testing.T) { p := &TeamPatch{ DisplayName: new(string), Description: new(string), CompanyName: new(string), AllowedDomains: new(string), AllowOpenInvite: new(bool), GroupConstrained: new(bool), } *p.DisplayName = NewId() *p.Description = NewId() *p.CompanyName = NewId() *p.AllowedDomains = NewId() *p.AllowOpenInvite = true *p.GroupConstrained = true o := Team{Id: NewId()} o.Patch(p) require.Equal(t, *p.DisplayName, o.DisplayName, "DisplayName did not update") require.Equal(t, *p.Description, o.Description, "Description did not update") require.Equal(t, *p.CompanyName, o.CompanyName, "CompanyName did not update") require.Equal(t, *p.AllowedDomains, o.AllowedDomains, "AllowedDomains did not update") require.Equal(t, *p.AllowOpenInvite, o.AllowOpenInvite, "AllowOpenInvite did not update") require.Equal(t, *p.GroupConstrained, *o.GroupConstrained) }
chachi21/owl-s
src/org/mindswap/owl/vocabulary/KIF.java
/* * Created on Jul 31, 2004 */ package org.mindswap.owl.vocabulary; import java.net.URI; /** * @author <NAME> */ public class KIF { public final static String ns = "http://logic.stanford.edu/kif/kif.html"; public final static URI getURI() { return URI.create(ns); } }
Miaocool/MYG-NewVersion
myg/Src/Treasure/Controller/ChanceofViewController.h
// // ChanceofViewController.h // myg // // Created by Apple on 16/10/20. // Copyright © 2016年 bxs. All rights reserved. // #import <UIKit/UIKit.h> @interface ChanceofViewController : UIViewController @end
Eunoians/McMMOx
src/main/java/us/eunoians/mcrpg/commands/McUnlink.java
<gh_stars>1-10 package us.eunoians.mcrpg.commands; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import us.eunoians.mcrpg.McRPG; import us.eunoians.mcrpg.abilities.mining.RemoteTransfer; import us.eunoians.mcrpg.api.exceptions.McRPGPlayerNotFoundException; import us.eunoians.mcrpg.api.util.Methods; import us.eunoians.mcrpg.api.util.RemoteTransferTracker; import us.eunoians.mcrpg.players.McRPGPlayer; import us.eunoians.mcrpg.players.PlayerManager; import us.eunoians.mcrpg.types.UnlockedAbilities; public class McUnlink implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String s, String[] strings) { if(sender instanceof Player) { if(PlayerManager.isPlayerFrozen(((Player) sender).getUniqueId())){ return true; } //Disabled Worlds String world = ((Player) sender).getWorld().getName(); if(McRPG.getInstance().getConfig().contains("Configuration.DisabledWorlds") && McRPG.getInstance().getConfig().getStringList("Configuration.DisabledWorlds").contains(world)) { return true; } McRPGPlayer mp; try{ mp = PlayerManager.getPlayer(((Player) sender).getUniqueId()); } catch(McRPGPlayerNotFoundException exception){ return true; } if(!mp.isLinkedToRemoteTransfer()) { mp.getPlayer().sendMessage(Methods.color(McRPG.getInstance().getPluginPrefix() + McRPG.getInstance().getLangFile().getString("Messages.Abilities.RemoteTransfer.IsNotLinked"))); return true; } mp.setLinkedToRemoteTransfer(false); ((RemoteTransfer) mp.getBaseAbility(UnlockedAbilities.REMOTE_TRANSFER)).setLinkedChestLocation(null); RemoteTransferTracker.removeLocation(mp.getUuid()); mp.getPlayer().sendMessage(Methods.color(McRPG.getInstance().getPluginPrefix() + McRPG.getInstance().getLangFile().getString("Messages.Abilities.RemoteTransfer.Unlinked"))); } return false; } }
amoshydra/cypress
system-tests/test/screenshot_element_capture_spec.js
<reponame>amoshydra/cypress<gh_stars>1000+ const systemTests = require('../lib/system-tests').default const onServer = (app) => { return app.get('/element', systemTests.sendHtml(`\ <style>body { margin: 0; }</style> <div class="capture-me" style="height: 300px; border: solid 1px black; margin: 20px;"> <div style="background: black; height: 150px;"></div> </div>\ `)) } describe('e2e screenshot element capture', () => { systemTests.setup({ servers: { port: 3322, onServer, }, }) // this tests that consistent screenshots are taken for element captures, // that the runner UI is hidden and that the page is scrolled properly systemTests.it('passes', { spec: 'screenshot_element_capture_spec.js', snapshot: true, }) })
ToraNova/library
prodtools/test/support_test.c
<gh_stars>0 /* Project Prodtools Test driver module module for csv testing ToraNova 2019 <EMAIL> */ #include "testlist.h" #include <prodtools/arrayutil/all.h> #include <prodtools/support/suprint.h> void support_test0(){ arrayutil_doubles_libtest(); suprint_libtest(); return; }
tomgilbertson/script-server-v1
src/execution/id_generator.py
import threading class IdGenerator: def __init__(self, existing_ids): self._next_id = self._calc_next_id(existing_ids) self.lock = threading.Lock() @staticmethod def _calc_next_id(existing_ids): max_id = 0 for existing_id in existing_ids: try: numeric_id = int(existing_id) if numeric_id > max_id: max_id = numeric_id except ValueError: continue return max_id + 1 def next_id(self): with self.lock: id = self._next_id self._next_id += 1 return str(id)
Eo300/react_flask_pdb2pqr
src/uid/service/uid_service.py
<filename>src/uid/service/uid_service.py from __future__ import print_function from flask import request, Blueprint from pprint import pformat from random import choices from string import ascii_lowercase, digits import logging from .uid_registry import uid_register_job, uid_validate_job uid_gen = Blueprint('uid_gen', __name__) ''' Below is the endpoint to generate a unique job ID string. This would be used to provide a client with an ID with which to start a workflow job. ''' @uid_gen.route('/', methods=['GET']) @uid_gen.route('/check/', methods=['GET']) def liveness(): """Probes server to check if alive""" return '', 200 @uid_gen.route('/api/uid/', methods=['GET']) def uid_generator(): """On GET, generate a unique ID string""" if request.method == 'GET': # job_id = uuid.uuid4().hex # job_id = uuid.uuid4().int job_id = ''.join(choices(ascii_lowercase+digits, k=10)) # random 10-character alphanumeric string # TODO: 2020/07/02, Elvis - Leave uid_register_job() commented until Storage service is updated to validate jobIDs uid_register_job(job_id) http_code = 200 response = {'job_id': str(job_id)} # logging.info('job_id - %s' % str(job_id)) # logging.info(pformat(response)) return response, http_code @uid_gen.route('/api/uid/validate/<job_id>', methods=['GET']) def uid_validate(job_id): """On GET validate job_id""" # logging.info("in uid validate") logging.info(f"{job_id}: Validating") if request.method == 'GET': metadata = uid_validate_job(job_id) http_code = 200 response = {'job_id': str(job_id), 'valid': metadata is not None, 'metadata': metadata} # logging.info('job_id - %s' % str(job_id)) # logging.info(pformat(response)) return response, http_code
Yannic/chromium
gpu/command_buffer/service/shared_image_backing_factory_d3d.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_BACKING_FACTORY_D3D_H_ #define GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_BACKING_FACTORY_D3D_H_ #include <d3d11.h> #include <dxgi1_2.h> #include <windows.h> #include <wrl/client.h> #include <memory> #include "base/macros.h" #include "components/viz/common/resources/resource_format.h" #include "gpu/command_buffer/service/shared_image_backing_factory.h" #include "gpu/gpu_gles2_export.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace gfx { class Size; class ColorSpace; } // namespace gfx namespace gpu { class SharedImageBacking; struct Mailbox; class GPU_GLES2_EXPORT SharedImageBackingFactoryD3D : public SharedImageBackingFactory { public: explicit SharedImageBackingFactoryD3D( Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device); SharedImageBackingFactoryD3D(const SharedImageBackingFactoryD3D&) = delete; SharedImageBackingFactoryD3D& operator=(const SharedImageBackingFactoryD3D&) = delete; ~SharedImageBackingFactoryD3D() override; // Returns true if DXGI swap chain shared images for overlays are supported. static bool IsSwapChainSupported(); struct GPU_GLES2_EXPORT SwapChainBackings { SwapChainBackings(std::unique_ptr<SharedImageBacking> front_buffer, std::unique_ptr<SharedImageBacking> back_buffer); SwapChainBackings(const SwapChainBackings&) = delete; SwapChainBackings& operator=(const SwapChainBackings&) = delete; ~SwapChainBackings(); SwapChainBackings(SwapChainBackings&&); SwapChainBackings& operator=(SwapChainBackings&&); std::unique_ptr<SharedImageBacking> front_buffer; std::unique_ptr<SharedImageBacking> back_buffer; }; // Creates IDXGI Swap Chain and exposes front and back buffers as Shared Image // mailboxes. SwapChainBackings CreateSwapChain(const Mailbox& front_buffer_mailbox, const Mailbox& back_buffer_mailbox, viz::ResourceFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage); std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, viz::ResourceFormat format, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage, bool is_thread_safe) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, viz::ResourceFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage, base::span<const uint8_t> pixel_data) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, int client_id, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat format, gfx::BufferPlane plane, SurfaceHandle surface_handle, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage) override; std::vector<std::unique_ptr<SharedImageBacking>> CreateSharedImageVideoPlanes( base::span<const Mailbox> mailboxes, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat format, const gfx::Size& size, uint32_t usage) override; bool IsSupported(uint32_t usage, viz::ResourceFormat format, bool thread_safe, gfx::GpuMemoryBufferType gmb_type, GrContextType gr_context_type, bool* allow_legacy_mailbox, bool is_pixel_used) override; // Returns true if the specified GpuMemoryBufferType can be imported using // this factory. bool CanImportGpuMemoryBuffer(gfx::GpuMemoryBufferType memory_buffer_type, viz::ResourceFormat format); Microsoft::WRL::ComPtr<ID3D11Device> GetDeviceForTesting() const { return d3d11_device_; } private: bool UseMapOnDefaultTextures(); Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_; absl::optional<bool> map_on_default_textures_; }; } // namespace gpu #endif // GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_BACKING_FACTORY_D3D_H_
radu-vtv/cubrid
src/jdbc/com/cubrid/jsp/Server.java
<reponame>radu-vtv/cubrid /* * Copyright (C) 2008 Search Solution Corporation. * Copyright (c) 2016 CUBRID Corporation. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the <ORGANIZATION> nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ package com.cubrid.jsp; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.concurrent.atomic.AtomicBoolean; public class Server { private static final Logger logger = Logger.getLogger("com.cubrid.jsp"); private static final String LOG_DIR = "log"; private static String serverName; private static String spPath; private static String rootPath; private static List<String> jvmArguments = null; private ServerSocket serverSocket; private Thread socketListener; private AtomicBoolean shutdown; private static Server serverInstance = null; private Server(String name, String path, String version, String rPath, String port) throws IOException { serverName = name; spPath = path; rootPath = rPath; shutdown = new AtomicBoolean(false); try { int port_number = Integer.parseInt(port); serverSocket = new ServerSocket(port_number); Class.forName("cubrid.jdbc.driver.CUBRIDDriver"); System.setSecurityManager(new SpSecurityManager()); System.setProperty("cubrid.server.version", version); getJVMArguments (); /* store jvm options */ } catch (Exception e) { log(e); e.printStackTrace(); } socketListener = new Thread (new Runnable() { public void run() { Socket client = null; while (true) { try { client = serverSocket.accept(); client.setTcpNoDelay(true); new ExecuteThread(client).start(); } catch (IOException e) { log(e); break; } } } }); } private void startSocketListener() { socketListener.setDaemon(true); socketListener.start(); } private void stopSocketListener() { try { serverSocket.close(); serverSocket = null; } catch (IOException e) { log(e); } } public ServerSocket getServerSocket() { return serverSocket; } public static Server getServer() { return serverInstance; } public static String getServerName() { return serverName; } public static int getServerPort() { try { return getServer().getServerSocket().getLocalPort(); } catch (Exception e) { return -1; } } public static String getSpPath() { return spPath; } public static List<String> getJVMArguments() { if (jvmArguments == null) { RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); jvmArguments = runtimeMxBean.getInputArguments(); } return jvmArguments; } public static int start(String[] args) { try { serverInstance = new Server(args[0], args[1], args[2], args[3], args[4]); serverInstance.startSocketListener(); return serverInstance.getServerSocket().getLocalPort(); } catch (Exception e) { e.printStackTrace(); } return -1; } public static void stop(int status) { getServer().setShutdown(); getServer().stopSocketListener(); System.exit (status); } public static void main (String[] args) { Server.start(args); } public static void log(Throwable ex) { FileHandler logHandler = null; try { logHandler = new FileHandler(rootPath + File.separatorChar + LOG_DIR + File.separatorChar + serverName + "_java.log", true); logger.addHandler(logHandler); logger.log(Level.SEVERE, "", ex); } catch (Throwable e) { } finally { if (logHandler != null) { try { logHandler.close(); logger.removeHandler(logHandler); } catch (Throwable e) { } } } } public void setShutdown() { shutdown.set(true); } public boolean getShutdown() { return shutdown.get(); } }
megahertz0/android_thunder
dex_src/android/support/v7/widget/bz.java
<gh_stars>10-100 package android.support.v7.widget; import android.view.KeyEvent; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; // compiled from: SearchView.java final class bz implements OnEditorActionListener { final /* synthetic */ SearchView a; bz(SearchView searchView) { this.a = searchView; } public final boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { SearchView.j(this.a); return true; } }
wdr-data/code4maus
src/lib/edu/video-06-hallo-welt/video.js
import aL00 from '../shared_assets/L00.jpg' const url = 'https://wdradaptiv-vh.akamaihd.net/i/medp/ondemand/weltweit/fsk0/213/2136903/,2136903_26555464,2136903_26555459,2136903_26555461,2136903_26555460,2136903_26555463,2136903_26555462,.mp4.csmil/master.m3u8' export default { id: '06', name: '<NAME> (1/10)', subtitle: 'Starte mit den ersten Blöcken', image: aL00, video: url, }