repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
SanojPunchihewa/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/configure/AddBranchSwitchMediatorAction.java | <reponame>SanojPunchihewa/devstudio-tooling-esb
/*
* Copyright 2009-2010 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.configure;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.wso2.developerstudio.eclipse.gmf.esb.SwitchMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.configure.ui.AddCaseBranchDialog;
public class AddBranchSwitchMediatorAction extends ConfigureEsbNodeAction {
public AddBranchSwitchMediatorAction(IWorkbenchPart part) {
super(part);
setId("add-case-switch-mediator-action-id");
setText("Add/Remove Case..");
setToolTipText("Add or Remove case branches.");
ISharedImages workbenchImages = PlatformUI.getWorkbench().getSharedImages();
setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_OBJ_ADD));
}
/**
* {@inheritDoc}
*/
protected void doRun(IProgressMonitor progressMonitor) {
EditPart selectedEP = getSelectedEditPart();
Assert.isNotNull(selectedEP, "Empty selection.");
EObject selectedObj = ((View) selectedEP.getModel()).getElement();
Assert.isTrue(selectedObj instanceof SwitchMediator, "Invalid selection.");
Shell shell = Display.getDefault().getActiveShell();
Dialog addBranchDialog = new AddCaseBranchDialog(shell, (SwitchMediator) selectedObj, getEditingDomain(),
selectedEP);
addBranchDialog.setBlockOnOpen(true);
addBranchDialog.open();
/*
* SwitchMediator parentMediator = (SwitchMediator) selectedObj;
* TransactionalEditingDomain domain = TransactionUtil.getEditingDomain(parentMediator);
* SwitchCaseBranchOutputConnector cb = EsbFactory.eINSTANCE.createSwitchCaseBranchOutputConnector();
* AddCommand addCmd = new AddCommand(domain,parentMediator,EsbPackage.Literals.SWITCH_MEDIATOR__CASE_BRANCHES,
* cb);
* if (addCmd.canExecute()){
* domain.getCommandStack().execute(addCmd);
* }
*/
}
}
|
AlexanderEggersDivae/aem-core-wcm-components | testing/it/e2e-selenium/src/test/java/com/adobe/cq/wcm/core/components/it/seljup/tests/formbutton/v1/FormButtonIT.java | <gh_stars>0
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright 2021 Adobe
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
package com.adobe.cq.wcm.core.components.it.seljup.tests.formbutton.v1;
import com.adobe.cq.testing.selenium.pageobject.EditorPage;
import com.adobe.cq.wcm.core.components.it.seljup.AuthorBaseUITest;
import com.adobe.cq.wcm.core.components.it.seljup.util.components.formbutton.v1.FormButton;
import com.adobe.cq.wcm.core.components.it.seljup.util.components.formbutton.BaseFormButton;
import com.adobe.cq.wcm.core.components.it.seljup.util.components.button.ButtonEditDialog;
import com.adobe.cq.wcm.core.components.it.seljup.util.constant.RequestConstants;
import com.adobe.cq.wcm.core.components.it.seljup.util.Commons;
import com.adobe.cq.testing.selenium.pageobject.PageEditorPage;
import com.codeborne.selenide.WebDriverRunner;
import java.util.concurrent.TimeoutException;
import org.apache.http.HttpStatus;
import org.apache.sling.testing.clients.ClientException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.WebDriver;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Tag("group1")
public class FormButtonIT extends AuthorBaseUITest {
protected String testPage;
protected String proxyComponentPath;
protected EditorPage editorPage;
protected BaseFormButton formButton;
protected String cmpPath;
protected String componentName = "formbutton";
private ButtonEditDialog openButtonEditDialog() throws TimeoutException {
String component = "[data-type='Editable'][data-path='" + testPage + "/jcr:content/root/responsivegrid/*" +"']";
final WebDriver webDriver = WebDriverRunner.getWebDriver();
new WebDriverWait(webDriver, RequestConstants.TIMEOUT_TIME_SEC).until(ExpectedConditions.elementToBeClickable(By.cssSelector(component)));
return editorPage.openEditableToolbar(cmpPath).clickConfigure().adaptTo(ButtonEditDialog.class);
}
/**
* Before Test Case
*/
@BeforeEach
public void setupBefore() throws ClientException {
testPage = authorClient.createPage("testPage", "Test Page", rootPage, defaultPageTemplate, 200, 201).getSlingPath();
proxyComponentPath = Commons.creatProxyComponent(adminClient, Commons.rtFormButton_v1, "Proxy Form Button", componentName);
addPathtoComponentPolicy(responsiveGridPath, proxyComponentPath);
cmpPath = Commons.addComponent(adminClient, proxyComponentPath,testPage + Commons.relParentCompPath, componentName, null);
formButton = new FormButton();
editorPage = new PageEditorPage(testPage);
editorPage.open();
}
/**
* After Test Case
*/
@AfterEach
public void cleanup() throws ClientException, InterruptedException {
authorClient.deletePageWithRetry(testPage, true,false, RequestConstants.TIMEOUT_TIME_MS, RequestConstants.RETRY_TIME_INTERVAL, HttpStatus.SC_OK);
}
/**
* Test: Check the attributes of the default button rendered without any customisations via the edit dialog
*/
@Test
@DisplayName("Test: Check the attributes of the default button rendered without any customisations via the edit dialog")
public void testCheckDefaultButtonAttributes() {
Commons.switchContext("ContentFrame");
assertTrue(formButton.isButtonPresentByType("Submit"), "Submit button should be present");
assertTrue(formButton.getButtonText().contains("Submit"), "Button should contain 'Submit' text");
}
/**
* Test: Create a button
*/
@Test
@DisplayName("Test: Create a button")
public void testCreateButton() throws TimeoutException, InterruptedException {
ButtonEditDialog buttonEditDialog = openButtonEditDialog();
buttonEditDialog.selectButtonType("button");
buttonEditDialog.setTitleField("Button");
Commons.saveConfigureDialog();
Commons.switchContext("ContentFrame");
assertTrue(formButton.isButtonPresentByType("Button"), "Button button should be present");
assertTrue(formButton.getButtonText().contains("Button"), "Button should contain 'Submit' text");
}
/**
* Test: Set button text
*/
@Test
@DisplayName("Test: Set button text")
public void testSetButtonText() throws TimeoutException, InterruptedException {
String buttonLabel = "Test Button";
ButtonEditDialog buttonEditDialog = openButtonEditDialog();
buttonEditDialog.setTitleField(buttonLabel);
Commons.saveConfigureDialog();
Commons.switchContext("ContentFrame");
assertTrue(formButton.getButtonText().contains(buttonLabel), "Button should contain " + buttonLabel + " text");
}
/**
* Test: Set button name
*/
@Test
@DisplayName("Test: Set button name")
public void testSetButtonName() throws TimeoutException, InterruptedException {
String buttonLabel = "BUTTON WITH NAME";
String buttonName = "button1";
ButtonEditDialog buttonEditDialog = openButtonEditDialog();
buttonEditDialog.setTitleField(buttonLabel);
buttonEditDialog.setNameField(buttonName);
Commons.saveConfigureDialog();
Commons.webDriverWait(RequestConstants.WEBDRIVER_WAIT_TIME_MS);
Commons.switchContext("ContentFrame");
assertTrue(formButton.isButtonPresentByName(buttonName), "Button should be present with name " + buttonName);
assertTrue(formButton.getButtonText().contains(buttonLabel), "Button should contain " + buttonLabel + " text");
}
/**
* Test: Set button value
*/
@Test
@DisplayName("Test: Set button value")
public void testSetButtonValue() throws TimeoutException, InterruptedException {
String buttonLabel = "BUTTON WITH NAME";
String buttonName = "button1";
String buttonValue = "thisisthevalue";
ButtonEditDialog buttonEditDialog = openButtonEditDialog();
buttonEditDialog.setTitleField(buttonLabel);
buttonEditDialog.setNameField(buttonName);
buttonEditDialog.setValueField(buttonValue);
Commons.saveConfigureDialog();
Commons.webDriverWait(RequestConstants.WEBDRIVER_WAIT_TIME_MS);
Commons.switchContext("ContentFrame");
assertTrue(formButton.isButtonPresentByValue(buttonValue), "Button should be present with value " + buttonValue);
assertTrue(formButton.getButtonText().contains(buttonLabel), "Button should contain " + buttonLabel + "text");
}
/**
* Test: Set button value without name
*/
@Test
@DisplayName("Test: Set button value without name")
public void testSetButtonValueWithoutName() throws TimeoutException, InterruptedException {
String buttonLabel = "BUTTON WITH NAME";
String buttonValue = "thisisthevalue";
ButtonEditDialog buttonEditDialog = openButtonEditDialog();
buttonEditDialog.setTitleField(buttonLabel);
buttonEditDialog.setValueField(buttonValue);
Commons.saveConfigureDialog();
assertTrue(buttonEditDialog.isNameFieldInvalid(),"Name field should be invalid");
}
}
|
motor-dev/Motor | mak/libs/pyxx/cxx/grammar/statement/declaration.py | <gh_stars>0
"""
declaration-statement:
block-declaration
"""
import glrp
from ...parser import cxx98
from motor_typing import TYPE_CHECKING
@glrp.rule('declaration-statement : block-declaration')
@cxx98
def declaration_statement(self, p):
# type: (CxxParser, glrp.Production) -> None
pass
if TYPE_CHECKING:
from ...parser import CxxParser |
flovo/goratings | analysis/util/GorAnalytics.py | from goratings.interfaces import GameAnalytics, GameRecord
__all__ = ["GorAnalytics"]
class GorAnalytics(GameAnalytics):
expected_win_rate: float # probability that black will win
black_rating: float
white_rating: float
black_rank: float
white_rank: float
def __init__(
self,
skipped: bool,
game: GameRecord,
expected_win_rate: float = 0,
black_rating: float = 0,
white_rating: float = 0,
black_rank: float = 0,
white_rank: float = 0,
black_games_played: int = 0,
white_games_played: int = 0,
) -> None:
super().__init__(skipped, game)
self.expected_win_rate = expected_win_rate
self.black_rating = black_rating
self.white_rating = white_rating
self.black_rank = black_rank
self.white_rank = white_rank
self.black_games_played = black_games_played
self.white_games_played = white_games_played
def __str__(self) -> str:
return "%.1f vs %.1f (hc: %d) Expected win rate: %.1f" % (
self.black_rating,
self.white_rating,
self.game.handicap,
self.expected_win_rate,
)
|
madworx/SwingLibrary | src/main/java/org/robotframework/swing/util/PropertyExtractor.java | /*
* Copyright 2008-2011 Nokia Siemens Networks Oyj
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.robotframework.swing.util;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class PropertyExtractor {
public Map<String, Object> extractProperties(Object bean) {
try {
return parsePropertyValuesFrom(bean);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Map<String, Object> parsePropertyValuesFrom(Object bean) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
for (Method method : bean.getClass().getMethods()) {
if (isGetter(method)) {
Object value = invoke(bean, method);
String prop = parsePropNameFrom(method);
properties.put(prop, value);
}
}
return properties;
}
private boolean isGetter(Method m) {
String methodName = m.getName();
return methodName.startsWith("get") &&
m.getParameterTypes().length == 0 &&
!methodName.equals("getClass");
}
private Object invoke(Object bean, Method method) {
try {
return method.invoke(bean, new Object[0]);
} catch (Exception ignored) {
return null;
}
}
private String parsePropNameFrom(Method method) {
return Character.toLowerCase(method.getName().charAt(3)) + method.getName().substring(4);
}
}
|
donnoman/cap-recipes | lib/cap_recipes/tasks/datadog/hooks.rb | <reponame>donnoman/cap-recipes
Capistrano::Configuration.instance(true).load do
after "deploy:provision", "datadog:install"
after "datadog:install", "datadog:setup"
after "datadog:setup", "datadog:restart"
end
|
1shenxi/webpack | test/hotCases/recover/recover-after-removal-self-accepted/inner.js | <filename>test/hotCases/recover/recover-after-removal-self-accepted/inner.js
module.hot.accept();
export default "-inner";
|
hanframework/han | han-core/src/main/java/org/hanframework/context/LoadEnvParseContext.java | <gh_stars>0
package org.hanframework.context;
import org.hanframework.env.ConfigurableEnvironment;
import org.hanframework.env.loadstrategy.TypeLoadStrategy;
import org.hanframework.env.loadstrategy.TypeLoadStrategyRegister;
import org.hanframework.env.resolver.source.MutablePropertySources;
import org.hanframework.env.resolver.source.PropertiesPropertySource;
import org.hanframework.env.resource.Resource;
import org.hanframework.env.resource.impl.PathMatchingResourcePatternResolver;
import org.hanframework.tool.extension.CommandLineArgsParser;
import java.io.IOException;
import java.util.Properties;
/**
* @author liuxin
* @version Id: LoadEnvParseContext.java, v 0.1 2019-05-24 11:01
*/
public final class LoadEnvParseContext {
private static final String COMMAND_LINE_ARGS = "commandLineArgs";
/**
* 默认扫描文件的路径
*/
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/";
/**
* 默认的配置名
*/
private static final String DEFAULT_CONFIG_LOCATION = "application";
private static final String PROFILE_NAME = "default";
private final EnvParseContext envParseContext;
private final ConfigurableEnvironment configurableEnvironment;
public LoadEnvParseContext(EnvParseContext envParseContext, ConfigurableEnvironment configurableEnvironment) {
this.envParseContext = envParseContext;
this.configurableEnvironment = configurableEnvironment;
}
public void load() {
CommandLineArgsParser commandLineArgsParser = new CommandLineArgsParser();
Properties commandLineArgsProperties = commandLineArgsParser.parse(envParseContext.getArgs()).getProperties();
MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
propertySources.add(new PropertiesPropertySource(COMMAND_LINE_ARGS, commandLineArgsProperties));
PathMatchingResourcePatternResolver pmr = new PathMatchingResourcePatternResolver();
try {
for (String location : DEFAULT_SEARCH_LOCATIONS.split(",")) {
String config = location + DEFAULT_CONFIG_LOCATION + "*";
Resource[] resources = pmr.getResources(config);
for (Resource resource : resources) {
propertySources.add(loadPropertiesPropertySource(resource));
}
}
} catch (IOException e) {
}
}
private PropertiesPropertySource loadPropertiesPropertySource(Resource resource) {
String profile;
String filename = resource.getFilename();
int lastIndexOf = filename.lastIndexOf("-");
if (lastIndexOf == -1) {
profile = PROFILE_NAME;
} else {
profile = filename.substring(lastIndexOf + 1, resource.getFilename().lastIndexOf("."));
}
//根据后缀名获取解析器
return new PropertiesPropertySource(profile, resource.getFilename(), loadPertiesForFileSuffixName(resource));
}
private Properties loadPertiesForFileSuffixName(Resource resource) {
TypeLoadStrategyRegister typeLoadStrategyRegistory = envParseContext.getTypeLoadStrategyRegistory();
TypeLoadStrategy typeLoadStrategy = typeLoadStrategyRegistory.getLoadStrategy(resource.getFileSuffixName());
return typeLoadStrategy.load(resource, envParseContext.getCharset());
}
}
|
CarolinaAzcona/FreeRTOS | vendors/cypress/MTB/libraries/lpa/docs/lpa_api_reference_manual/html/navtreeindex0.js | var NAVTREEINDEX0 =
{
"index.html":[],
"index.html#apis":[16],
"index.html#group_lpa_changelog":[14],
"index.html#group_lpa_definitions":[3],
"index.html#group_lpa_errata":[13],
"index.html#group_lpa_misra":[12],
"index.html#group_lpa_p1":[4],
"index.html#group_lpa_p1_cc":[4,1],
"index.html#group_lpa_p1_cc_manual_flow":[4,1,1],
"index.html#group_lpa_p1_cc_mt_flow":[4,1,0],
"index.html#group_lpa_p1_cc_mt_flow_host_wake":[5,4,0,0],
"index.html#group_lpa_p1_cc_parameters":[4,1,2],
"index.html#group_lpa_p1_qsg":[4,0,0],
"index.html#group_lpa_p1_qsg_afr":[4,0,2],
"index.html#group_lpa_p1_qsg_anycloud":[4,0,1],
"index.html#group_lpa_p1_qsg_general":[4,0],
"index.html#group_lpa_p2":[5],
"index.html#group_lpa_p2_arp_offload":[5,1],
"index.html#group_lpa_p2_arp_offload_qsg":[5,1,5],
"index.html#group_lpa_p2_arp_offload_qsg_afr":[5,1,5,2],
"index.html#group_lpa_p2_arp_offload_qsg_anycloud":[5,1,5,1],
"index.html#group_lpa_p2_arp_offload_qsg_mbedos":[5,1,5,0],
"index.html#group_lpa_p2_awake_sleeping":[5,1,0],
"index.html#group_lpa_p2_cc":[5,4],
"index.html#group_lpa_p2_cc_limitations":[5,4,2],
"index.html#group_lpa_p2_cc_manual_flow":[5,4,1],
"index.html#group_lpa_p2_cc_mt_flow":[5,4,0],
"index.html#group_lpa_p2_cc_parameters":[5,4,5],
"index.html#group_lpa_p2_filtertypes":[5,2,0],
"index.html#group_lpa_p2_host_wake":[5,0],
"index.html#group_lpa_p2_host_wake_qsg":[5,0,0],
"index.html#group_lpa_p2_host_wake_qsg_afr":[5,0,0,2],
"index.html#group_lpa_p2_host_wake_qsg_anycloud":[5,0,0,1],
"index.html#group_lpa_p2_host_wake_qsg_mbedos":[5,0,0,0],
"index.html#group_lpa_p2_hostautoreply":[5,1,1],
"index.html#group_lpa_p2_hostpeerautoreply":[5,1,3],
"index.html#group_lpa_p2_hostsnoop":[5,1,4],
"index.html#group_lpa_p2_ipv6_filter":[5,4,3],
"index.html#group_lpa_p2_keeptoss":[5,2,1],
"index.html#group_lpa_p2_packet_filter":[5,2],
"index.html#group_lpa_p2_packet_filter_qsg":[5,2,3],
"index.html#group_lpa_p2_peerautoreply":[5,1,2],
"index.html#group_lpa_p2_pf_offload_qsg_afr":[5,2,3,2],
"index.html#group_lpa_p2_pf_offload_qsg_anycloud":[5,2,3,1],
"index.html#group_lpa_p2_pf_offload_qsg_mbedos":[5,2,3,0],
"index.html#group_lpa_p2_sleepwake":[5,2,2],
"index.html#group_lpa_p2_tcp_keepalive":[5,3],
"index.html#group_lpa_p2_tcp_keepalive_qsg":[5,3,0],
"index.html#group_lpa_p2_tcp_keepalive_qsg_afr":[5,3,0,2],
"index.html#group_lpa_p2_tcp_keepalive_qsg_anycloud":[5,3,0,1],
"index.html#group_lpa_p2_tcp_keepalive_qsg_mbedos":[5,3,0,0],
"index.html#group_lpa_p2_wlan_lowpower":[5,4,4],
"index.html#group_lpa_p3":[6],
"index.html#group_lpa_p3_cc":[6,1],
"index.html#group_lpa_p3_cc_manual_flow":[6,1,1],
"index.html#group_lpa_p3_cc_mt_flow":[6,1,0],
"index.html#group_lpa_p3_cc_parameters":[6,1,2],
"index.html#group_lpa_p3_qsg":[6,0],
"index.html#group_lpa_p3_qsg_afr":[6,0,2],
"index.html#group_lpa_p3_qsg_anycloud":[6,0,1],
"index.html#group_lpa_p3_qsg_mbedos":[6,0,0],
"index.html#section_apis":[16,0],
"index.html#section_lpa_Prerequisites":[2],
"index.html#section_lpa_bt_wakeconfig":[10],
"index.html#section_lpa_bt_wakeconfig_CY8CKIT_062S2_43012":[10,1],
"index.html#section_lpa_bt_wakeconfig_CY8CKIT_062_WIFI_BT":[10,0],
"index.html#section_lpa_bt_wakeconfig_CY8CPROTO_062_4343W":[10,2],
"index.html#section_lpa_features":[0,0],
"index.html#section_lpa_getting_started":[1],
"index.html#section_lpa_hostwake":[9],
"index.html#section_lpa_hostwake_CY8CKIT_062S2_43012":[9,1],
"index.html#section_lpa_hostwake_CY8CKIT_062_WIFI_BT":[9,0],
"index.html#section_lpa_hostwake_CY8CPROTO_062_4343W":[9,2],
"index.html#section_lpa_measurement":[7],
"index.html#section_lpa_more_information":[15],
"index.html#section_lpa_overview":[0],
"index.html#section_lpa_performance":[8],
"index.html#section_lpa_toolchain":[11],
"pages.html":[]
};
|
nscodelover/Quickblox-iOS-project-master | External/Quickblox.framework/Versions/A/Headers/QBError.h | <gh_stars>1-10
//
// QBError.h
// Quickblox
//
// Created by <NAME> on 8/18/14.
// Copyright (c) 2014 QuickBlox. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Quickblox/QBNullability.h>
#import <Quickblox/QBGeneric.h>
@interface QBError : NSObject
@property (nonatomic, readonly, QB_NULLABLE_PROPERTY) NSDictionary QB_GENERIC(NSString *, NSString *) * reasons;
@property (nonatomic, readonly, QB_NULLABLE_PROPERTY) NSError* error;
+ (QB_NONNULL instancetype)errorWithError:(QB_NULLABLE NSError *)error;
@end
|
theleapofcode/algorithms-data-structures-java | src/test/java/com/theleapofcode/algosandds/tree/TestBinaryTree.java | package com.theleapofcode.algosandds.tree;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class TestBinaryTree {
@Test
public void testCreate() {
BinaryTreeNode<String> lc = new BinaryTreeNode<>("N11");
BinaryTreeNode<String> rc = new BinaryTreeNode<>("N12");
BinaryTreeNode<String> rootNode = new BinaryTreeNode<>("N0", lc, rc);
BinaryTree<String> bt = new BinaryTree<>(rootNode);
Assert.assertEquals("N0 (N11 (,), N12 (,))", bt.toString());
}
@Test
public void testSize() {
BinaryTreeNode<String> n21 = new BinaryTreeNode<>("N21");
BinaryTreeNode<String> n22 = new BinaryTreeNode<>("N22");
BinaryTreeNode<String> n11 = new BinaryTreeNode<>("N11", n21, n22);
BinaryTreeNode<String> n23 = new BinaryTreeNode<>("N23");
BinaryTreeNode<String> n24 = new BinaryTreeNode<>("N24");
BinaryTreeNode<String> n12 = new BinaryTreeNode<>("N12", n23, n24);
BinaryTreeNode<String> rootNode = new BinaryTreeNode<>("N0", n11, n12);
BinaryTree<String> bt = new BinaryTree<>(rootNode);
int size = bt.size();
Assert.assertEquals(7, size);
}
@Test
public void testHeight() {
BinaryTreeNode<String> n21 = new BinaryTreeNode<>("N21");
BinaryTreeNode<String> n22 = new BinaryTreeNode<>("N22");
BinaryTreeNode<String> n11 = new BinaryTreeNode<>("N11", n21, n22);
BinaryTreeNode<String> n23 = new BinaryTreeNode<>("N23");
BinaryTreeNode<String> n24 = new BinaryTreeNode<>("N24");
BinaryTreeNode<String> n12 = new BinaryTreeNode<>("N12", n23, n24);
BinaryTreeNode<String> rootNode = new BinaryTreeNode<>("N0", n11, n12);
BinaryTree<String> bt = new BinaryTree<>(rootNode);
int height = bt.height();
Assert.assertEquals(2, height);
}
@Test
public void testPostOrderTraversal() {
BinaryTreeNode<String> n21 = new BinaryTreeNode<>("N21");
BinaryTreeNode<String> n22 = new BinaryTreeNode<>("N22");
BinaryTreeNode<String> n11 = new BinaryTreeNode<>("N11", n21, n22);
BinaryTreeNode<String> n23 = new BinaryTreeNode<>("N23");
BinaryTreeNode<String> n24 = new BinaryTreeNode<>("N24");
BinaryTreeNode<String> n12 = new BinaryTreeNode<>("N12", n23, n24);
BinaryTreeNode<String> rootNode = new BinaryTreeNode<>("N0", n11, n12);
BinaryTree<String> bt = new BinaryTree<>(rootNode);
List<BinaryTreeNode<String>> nodes = bt.postOrderTraverse();
Assert.assertEquals("[N21, N22, N11, N23, N24, N12, N0]", nodes.toString());
}
@Test
public void testInOrderTraversal() {
BinaryTreeNode<String> n21 = new BinaryTreeNode<>("N21");
BinaryTreeNode<String> n22 = new BinaryTreeNode<>("N22");
BinaryTreeNode<String> n11 = new BinaryTreeNode<>("N11", n21, n22);
BinaryTreeNode<String> n23 = new BinaryTreeNode<>("N23");
BinaryTreeNode<String> n24 = new BinaryTreeNode<>("N24");
BinaryTreeNode<String> n12 = new BinaryTreeNode<>("N12", n23, n24);
BinaryTreeNode<String> rootNode = new BinaryTreeNode<>("N0", n11, n12);
BinaryTree<String> bt = new BinaryTree<>(rootNode);
List<BinaryTreeNode<String>> nodes = bt.inOrderTraverse();
Assert.assertEquals("[N21, N11, N22, N0, N23, N12, N24]", nodes.toString());
}
@Test
public void testBreadthFirstTraversal() {
BinaryTreeNode<String> n21 = new BinaryTreeNode<>("N21");
BinaryTreeNode<String> n22 = new BinaryTreeNode<>("N22");
BinaryTreeNode<String> n11 = new BinaryTreeNode<>("N11", n21, n22);
BinaryTreeNode<String> n23 = new BinaryTreeNode<>("N23");
BinaryTreeNode<String> n24 = new BinaryTreeNode<>("N24");
BinaryTreeNode<String> n12 = new BinaryTreeNode<>("N12", n23, n24);
BinaryTreeNode<String> rootNode = new BinaryTreeNode<>("N0", n11, n12);
BinaryTree<String> bt = new BinaryTree<>(rootNode);
List<BinaryTreeNode<String>> nodes = bt.breadthFirstTraverse();
Assert.assertEquals("[N0, N11, N12, N21, N22, N23, N24]", nodes.toString());
}
}
|
r-kapoor/Leetcode | src/java1/Constructor.java | package java1;
public class Constructor {
static String str;
public void Contructor(){
System.out.println("In");
str = "Hello World";
}
public static void main(String[] args){
Constructor c = new Constructor();
System.out.println(str);
}
}
|
shaojiankui/iOS10-Runtime-Headers | PrivateFrameworks/iWorkImport.framework/SFUZipException.h | <gh_stars>10-100
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/Memories.framework/Memories
*/
@interface SFUZipException : NSException
@end
|
seanlinc/Playmate | sjtwo-c/projects/lpc40xx_freertos/l3_drivers/sources/mp3_vs1053.c | <filename>sjtwo-c/projects/lpc40xx_freertos/l3_drivers/sources/mp3_vs1053.c
/*********************************************************
* This is a driver for VS1053 Codec board with amplifier
* Designed for SJSU SJ2 dev board
*
* Written by <NAME>(Sean), <NAME>, and <NAME>
*
*********************************************************/
#include "mp3_vs1053.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "delay.h"
#include "ff.h"
#include "gpio.h"
#include "gpio_lab.h"
#include "queue.h"
#include "ssp2.h"
// static QueueHandle_t song_name_queue;
// static QueueHandle_t song_data_queue;
// static QueueHandle_t Q_song_name;
// static QueueHandle_t Q_song_data;
static gpio_s RST, DREQ, XDCS, MP3CS;
void mp3__set_xdcs() { gpio__set(XDCS); }
void mp3__reset_xdcs() { gpio__reset(XDCS); }
bool data_request() { return gpio__get(DREQ); }
void mp3__sci_write(uint8_t address, uint16_t data) {
ssp2__initialize(24 * 100);
while (!data_request()) {
delay__ms(5);
}
gpio__reset(MP3CS);
ssp2__exchange_byte(VS1053_SCI_WRITE);
ssp2__exchange_byte(address);
ssp2__exchange_byte(data >> 8);
ssp2__exchange_byte(data & 0xFF);
gpio__set(MP3CS);
}
uint16_t mp3__sci_read(uint8_t address) {
// printf("sci read\n");
ssp2__initialize(24 * 100);
uint16_t data;
while (!data_request()) {
delay__ms(5);
}
gpio__reset(MP3CS);
ssp2__exchange_byte(VS1053_SCI_READ);
ssp2__exchange_byte(address);
// delay__us(10);
// printf("sci read send address\n");
data = ssp2__exchange_byte(0x00);
data <<= 8;
data |= ssp2__exchange_byte(0x00);
// printf("sci read data\n");
gpio__set(MP3CS);
// printf("sci read finished\n");
return data;
}
bool mp3__init() {
printf("Enter mp3 init\n");
XDCS = gpio__construct_with_function(2, 1, GPIO__FUNCTION0);
gpio__set_as_output(XDCS);
DREQ = gpio__construct_with_function(2, 4, GPIO__FUNCTION0);
gpio__set_as_input(DREQ);
MP3CS = gpio__construct_with_function(2, 6, GPIO__FUNCTION0);
gpio__set_as_output(MP3CS);
RST = gpio__construct_with_function(1, 29, GPIO__FUNCTION0);
gpio__set_as_output(RST);
// gpio__reset(RST);
gpio__set(MP3CS);
gpio__set(XDCS);
printf("Pin init finished\n");
ssp2__initialize(8 * 1000);
// mp3__sci_write(VS1053_REG_CLOCKF, 0x2000);
printf("SSP2 init finished\n");
// mp3__sci_write(VS1053_REG_CLOCKF, 0x2000);
// mp3__sci_write(VS1053_REG_VOLUME, 0x3838);
mp3__hardware_reset();
// printf("mp3 reset finished\n");
printf("sci_read value: 0x%04x\n", mp3__sci_read(VS1053_REG_STATUS));
mp3__sci_write(VS1053_REG_MODE, VS1053_MODE_SM_SDINEW);
printf("SCI Mode: 0x%04x\n", mp3__sci_read(VS1053_REG_MODE));
// VS1053 version B7:B3 = 4, otherwise it is not VS1053
return (mp3__sci_read(VS1053_REG_STATUS) >> 4) & 0x0F;
}
void mp3__software_reset() {
mp3__sci_write(VS1053_REG_MODE, VS1053_MODE_SM_SDINEW | VS1053_MODE_SM_RESET);
delay__ms(100);
}
void mp3__hardware_reset() {
// Using reset pin on the board
gpio__reset(RST);
delay__ms(100);
gpio__set(RST);
if (!data_request()) {
printf("Starting reset\n");
while (!data_request())
;
printf("Reset successful!\n");
}
gpio__set(MP3CS);
gpio__set(XDCS);
delay__ms(100);
mp3__software_reset();
mp3__sci_write(VS1053_REG_CLOCKF, 0xC000);
mp3__set_volume(20, 20);
}
void mp3__set_volume(uint8_t left, uint8_t right) {
uint16_t volume;
volume = left;
volume <<= 8;
volume |= right;
mp3__sci_write(VS1053_REG_VOLUME, volume);
}
void mp3__sine_test(uint8_t n, uint16_t time_ms) {
mp3__hardware_reset();
// uint16_t mode = mp3__sci_read(VS1053_REG_STATUS);
// mode |= 0x0020;
// mp3__sci_write(VS1053_REG_MODE, mode);
while (!data_request()) {
// delay__ms(5);
}
mp3__sci_write(VS1053_REG_MODE, 0x0820);
gpio__reset(XDCS);
ssp2__exchange_byte(0x53);
ssp2__exchange_byte(0xEF);
ssp2__exchange_byte(0x6E);
ssp2__exchange_byte(n);
ssp2__exchange_byte(0x00);
ssp2__exchange_byte(0x00);
ssp2__exchange_byte(0x00);
ssp2__exchange_byte(0x00);
gpio__set(XDCS);
delay__ms(500);
gpio__reset(XDCS);
ssp2__exchange_byte(0x45);
ssp2__exchange_byte(0x78);
ssp2__exchange_byte(0x69);
ssp2__exchange_byte(0x74);
ssp2__exchange_byte(0x00);
ssp2__exchange_byte(0x00);
ssp2__exchange_byte(0x00);
ssp2__exchange_byte(0x00);
gpio__set(XDCS);
printf("Finished sine test\n");
}
void mp3__send_data_block(uint8_t *data) {
size_t bytes_send = 0;
ssp2__initialize(8 * 1000);
while (bytes_send < 512) {
while (!data_request())
;
// Enable SDI transfer
mp3__reset_xdcs();
for (size_t byte = bytes_send; byte < (bytes_send + 32); byte++) {
ssp2__exchange_byte(data[byte]);
// printf("%02x", mp3_data[byte]);
}
bytes_send += 32;
mp3__set_xdcs();
}
}
bool mp3__is_mp3_file(const char *file_name) {
if (strlen(file_name) > 4) {
if ((strstr(file_name, ".mp3") != NULL) && (strstr(file_name, "._") == NULL)) {
printf("File name: %s\n", file_name);
return 1;
}
} else {
return 0;
}
} |
MieskeB/Chess | chessClient/Model/src/main/java/nl/michelbijnen/ChessBoard.java | <filename>chessClient/Model/src/main/java/nl/michelbijnen/ChessBoard.java
package nl.michelbijnen;
import nl.michelbijnen.ChessPieces.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class ChessBoard {
private List<ChessPiece> chessPieces;
private int totalValue;
private PlayerColor playerColor;
private boolean singleplayer;
private List<Log> logs;
private boolean gameFinished;
private PlayerColor winner;
public ChessBoard(PlayerColor playerColor) {
this.logs = new ArrayList<>();
this.playerColor = playerColor;
this.chessPieces = new ArrayList<>();
this.chessPieces.add(new Rook(playerColor, new Point(0, 7)));
this.chessPieces.add(new Knight(playerColor, new Point(1, 7)));
this.chessPieces.add(new Bishop(playerColor, new Point(2, 7)));
this.chessPieces.add(new Queen(playerColor, new Point(3, 7)));
this.chessPieces.add(new King(playerColor, new Point(4, 7)));
this.chessPieces.add(new Bishop(playerColor, new Point(5, 7)));
this.chessPieces.add(new Knight(playerColor, new Point(6, 7)));
this.chessPieces.add(new Rook(playerColor, new Point(7, 7)));
for (int i = 0; i <= 7; i++) {
this.chessPieces.add(new Pawn(playerColor, new Point(i, 6), true));
}
PlayerColor opponentPlayerColor = playerColor == PlayerColor.WHITE ? PlayerColor.BLACK : PlayerColor.WHITE;
this.chessPieces.add(new Rook(opponentPlayerColor, new Point(0, 0)));
this.chessPieces.add(new Knight(opponentPlayerColor, new Point(1, 0)));
this.chessPieces.add(new Bishop(opponentPlayerColor, new Point(2, 0)));
this.chessPieces.add(new Queen(opponentPlayerColor, new Point(3, 0)));
this.chessPieces.add(new King(opponentPlayerColor, new Point(4, 0)));
this.chessPieces.add(new Bishop(opponentPlayerColor, new Point(5, 0)));
this.chessPieces.add(new Knight(opponentPlayerColor, new Point(6, 0)));
this.chessPieces.add(new Rook(opponentPlayerColor, new Point(7, 0)));
for (int i = 0; i <= 7; i++) {
this.chessPieces.add(new Pawn(opponentPlayerColor, new Point(i, 1), false));
}
this.updateTotalValue();
}
public PlayerColor getPlayerColor() {
return this.playerColor;
}
public int getTotalValue() {
this.updateTotalValue();
return this.totalValue;
}
public ChessPiece getChessPieceOfPoint(Point p) {
for (ChessPiece chessPiece : this.chessPieces) {
if (chessPiece.getCurrentLocation().x == p.x && chessPiece.getCurrentLocation().y == p.y) {
return chessPiece;
}
}
return null;
}
public List<ChessPiece> getAllChessPieces() {
return new ArrayList<>(this.chessPieces);
}
public List<ChessPiece> getAllChessPieces(PlayerColor playerColor) {
List<ChessPiece> chessPieces = new ArrayList<>();
for (ChessPiece chessPiece : this.chessPieces) {
if (chessPiece.playerColor == playerColor) {
chessPieces.add(chessPiece);
}
}
return chessPieces;
}
public boolean moveChessPiece(boolean testing, Point start, Point end) {
ChessPiece chessPiece = this.getChessPieceOfPoint(start);
return this.moveChessPiece(testing, chessPiece, end);
}
public boolean moveChessPiece(boolean testing, ChessPiece chessPiece, Point end) {
boolean hasHit = false;
this.logs.add(new Log(chessPiece, new Point(chessPiece.getCurrentLocation()), new Point(end)));
ChessPiece chessPieceDestroyed = this.getChessPieceOfPoint(end);
if (chessPieceDestroyed != null) {
this.logs.add(new Log(chessPieceDestroyed, new Point(end)));
this.destroyChessPiece(chessPieceDestroyed);
if (!testing && chessPieceDestroyed instanceof King) {
this.winner = chessPiece.playerColor;
this.gameFinished = true;
}
hasHit = true;
}
chessPiece.setCurrentLocation(end);
return hasHit;
}
public void destroyChessPiece(ChessPiece chessPiece) {
this.chessPieces.remove(chessPiece);
}
private void updateTotalValue() {
this.totalValue = 0;
for (ChessPiece chessPiece : this.chessPieces) {
this.totalValue += chessPiece.getValue();
}
}
public ArrayList<Point> calculatePossibleLocations(ChessPiece chessPiece) {
Calculate calculate = new Calculate(this);
if (chessPiece instanceof Pawn) {
return calculate.calculate((Pawn) chessPiece);
} else if (chessPiece instanceof Rook) {
return calculate.calculate((Rook) chessPiece);
} else if (chessPiece instanceof Knight) {
return calculate.calculate((Knight) chessPiece);
} else if (chessPiece instanceof Bishop) {
return calculate.calculate((Bishop) chessPiece);
} else if (chessPiece instanceof Queen) {
return calculate.calculate((Queen) chessPiece);
} else if (chessPiece instanceof King) {
return calculate.calculate((King) chessPiece);
}
return null;
}
public List<Log> getLogs() {
return logs;
}
public void undo() {
Log log = this.logs.get(this.logs.size() - 1);
if (log.getLogType().equals("HIT")) {
this.chessPieces.add(log.getChessPiece());
this.logs.remove(log);
}
log = this.logs.get(this.logs.size() - 1);
log.getChessPiece().setCurrentLocation(log.getPointFrom());
this.logs.remove(log);
}
public boolean isGameFinished() {
return gameFinished;
}
public PlayerColor getWinner() {
return winner;
}
public boolean isSingleplayer() {
return singleplayer;
}
public void setSingleplayer(boolean singleplayer) {
this.singleplayer = singleplayer;
}
}
|
Jonathan-Villa/headstart | src/components/QuickLog/grants.js | export const grants = [
{
value: "HS",
label: "HS"
},
{
value: "EHS",
label: "EHS"
},
{
value: "P",
label: "P"
},
{
value: "PI",
label: "PI"
}
] |
aeolusk/utils | src/java/com/bono/utils/PasswordEncoder.java | package com.bono.utils;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
public class PasswordEncoder {
public static final String commonPasswordKey = "<PASSWORD>";
private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";
private static final int TAG_LENGTH_BIT = 128; // must be one of {128, 120, 112, 104, 96}
private static final int IV_LENGTH_BYTE = 12;
private static final int SALT_LENGTH_BYTE = 16;
private static final Charset UTF_8 = StandardCharsets.UTF_8;
public static String encrypt(String normalPassword) throws Exception {
return encrypt(normalPassword.getBytes(), commonPasswordKey);
}
// return a base64 encoded AES encrypted text
public static String encrypt(byte[] pText, String password) throws Exception {
// 16 bytes salt
byte[] salt = CryptoUtils.getRandomNonce(SALT_LENGTH_BYTE);
// GCM recommended 12 bytes iv?
byte[] iv = CryptoUtils.getRandomNonce(IV_LENGTH_BYTE);
// secret key from password
SecretKey aesKeyFromPassword = CryptoUtils.getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
// ASE-GCM needs GCMParameterSpec
cipher.init(Cipher.ENCRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] cipherText = cipher.doFinal(pText);
// prefix IV and Salt to cipher text
byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length).put(iv).put(salt)
.put(cipherText).array();
// string representation, base64, send this string to other for decryption.
return Base64.getEncoder().encodeToString(cipherTextWithIvSalt);
}
public static String decrypt(String encryptPassword) throws Exception {
return decrypt(encryptPassword, commonPasswordKey);
}
// we need the same password, salt and iv to decrypt it
public static String decrypt(String cText, String password) throws Exception {
byte[] decode = Base64.getDecoder().decode(cText.getBytes(UTF_8));
// get back the iv and salt from the cipher text
ByteBuffer bb = ByteBuffer.wrap(decode);
byte[] iv = new byte[IV_LENGTH_BYTE];
bb.get(iv);
byte[] salt = new byte[SALT_LENGTH_BYTE];
bb.get(salt);
byte[] cipherText = new byte[bb.remaining()];
bb.get(cipherText);
// get back the aes key from the same password and salt
SecretKey aesKeyFromPassword = CryptoUtils.getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] plainText = cipher.doFinal(cipherText);
return new String(plainText, UTF_8);
}
}
|
rakenduste-programmeerimine-2021/anonyymne-sonumilaud | src/pages/MyThoughts.js | <gh_stars>0
import React, {PureComponent} from 'react';
import {connect} from 'react-redux';
import { Layout,Typography} from "antd";
import { renderIf } from "../utils/commonUtils";
import axios from "axios";
import ThoughtList from '../components/ThoughtList';
const { Title } = Typography;
const { Content} = Layout;
class MyThoughts extends PureComponent {
constructor(props) {
super(props);
this.state = {
testList: [],
};
}
componentDidMount = () => {
const userId = this.props.user.getIn(["user", "_id"], "");
axios
.get("api/thought/find/" + userId)
.then((res) => {
console.log("aaaa", res.data)
if(!res.data[0].user){
}else{
this.setState({testList: res.data});
}
})
.catch((err) => {
if (err.response) {
//message.error(err.response.status);
} else {
}
});
}
render() {
const data = this.state.testList;
//console.log(data);
return (
<Content style={{ padding: "0 24px", minHeight: 280 }}>
{renderIf(!this.state.testList[0])(
<Title level={2}>No thoughts yet 😥</Title>
)}
{renderIf(data)(
<ThoughtList thoughts={data} owner={true}/>
)}
</Content>
);
}
}
const mapStateToProps = state => {
const {user} = state;
return {user};
};
export default connect(mapStateToProps)(MyThoughts); |
pedropazello/ruby_xml_nfe | lib/ruby_xml_nfe/dest.rb | require 'nokogiri'
require 'ruby_xml_nfe/ender_dest'
module RubyXmlNfe
class Dest
attr_reader :xml, :cnpj, :xNome, :ender_dest_params, :indIEDest, :ie, :email
def initialize(xml, params)
@xml = xml
@cnpj = params[:CNPJ]
@xNome = params[:xNome]
@ender_dest_params = params[:enderDest]
@indIEDest = params[:indIEDest]
@ie = params[:IE]
@email = params[:email]
end
def build
xml.dest do
xml.CNPJ cnpj
xml.xNome xNome
ender_emit = RubyXmlNfe::EnderDest.new(xml, ender_dest_params)
ender_emit.build
xml.indIEDest indIEDest
xml.IE ie if ie
xml.email email if email
end
end
end
end
|
greyp9/arwo | src/main/core/java/io/github/greyp9/arwo/core/io/script/Script.java | <reponame>greyp9/arwo<filename>src/main/core/java/io/github/greyp9/arwo/core/io/script/Script.java
package io.github.greyp9.arwo.core.io.script;
import io.github.greyp9.arwo.core.io.command.Command;
import io.github.greyp9.arwo.core.io.command.CommandDone;
import io.github.greyp9.arwo.core.io.command.CommandToDo;
import io.github.greyp9.arwo.core.io.command.CommandWork;
import io.github.greyp9.arwo.core.text.line.LineU;
import io.github.greyp9.arwo.core.util.PropertiesU;
import io.github.greyp9.arwo.core.util.PropertiesX;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Properties;
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
public class Script {
private final String context;
private final long date;
private final String id;
private final String text;
private final Properties properties;
private final Collection<CommandToDo> commandsToDo;
private final Collection<CommandWork> commandsWork;
private final Collection<CommandDone> commandsDone;
public final String getContext() {
return context;
}
public final Date getDate() {
return new Date(date);
}
public final String getID() {
return id;
}
public final String getText() {
return text;
}
public final Properties getProperties() {
return properties;
}
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public Script(final String context, final Date date, final String id, final String text) throws IOException {
this.context = context;
this.date = date.getTime();
this.id = id;
this.text = text;
this.properties = new Properties();
this.commandsToDo = new ArrayList<CommandToDo>();
this.commandsWork = new ArrayList<CommandWork>();
this.commandsDone = new ArrayList<CommandDone>();
final Collection<String> stdinLines = LineU.toLines(text);
for (final String stdin : stdinLines) {
commandsToDo.add(new CommandToDo(date, stdin));
}
}
public final synchronized boolean isInterrupted() {
return PropertiesU.isBoolean(properties, Const.INTERRUPTED);
}
public final synchronized void setInterrupted() {
PropertiesU.setProperty(properties, Const.INTERRUPTED, Boolean.TRUE.toString());
}
public final synchronized Date getStart() {
final long start = new PropertiesX(properties).getLong(Const.START);
return ((start == 0) ? null : new Date(start));
}
public final synchronized Date getFinish() {
final long finish = new PropertiesX(properties).getLong(Const.FINISH);
return ((finish == 0) ? null : new Date(finish));
}
public final synchronized void start() {
new PropertiesX(properties).setLong(Const.START, new Date().getTime());
}
public final synchronized void finish() {
new PropertiesX(properties).setLong(Const.FINISH, new Date().getTime());
}
public final synchronized Collection<Command> getCommands() {
final Collection<Command> commands = new ArrayList<Command>();
commands.addAll(commandsDone);
commands.addAll(commandsWork);
commands.addAll(commandsToDo);
return commands;
}
public final synchronized CommandToDo getCommandToDo() {
return (commandsToDo.isEmpty() ? null : commandsToDo.iterator().next());
}
public final synchronized CommandWork startCommand(
final CommandToDo command, final String charset, final String dir) {
final CommandWork commandWork = new CommandWork(
dir, command.getStdin(), charset, getID(), command.getScheduled(), new Date(), null);
commandsToDo.remove(command);
commandsWork.add(commandWork);
return commandWork;
}
public final synchronized CommandWork updateCommand(final CommandWork command, final Integer pid) {
final CommandWork commandUpdate = new CommandWork(command, pid);
commandsWork.remove(command);
commandsWork.add(commandUpdate);
return commandUpdate;
}
public final synchronized CommandDone finishCommand(final CommandWork command, final Integer exitValue) {
final CommandDone commandDone = new CommandDone(
command, command.getStdout(), command.getStderr(), new Date(), exitValue);
commandsWork.remove(command);
commandsDone.add(commandDone);
return commandDone;
}
public final synchronized Long getDelay(final Date now) { // how long waiting to start
final Date dateA = new Date(date);
final Date dateZ = ((getStart() == null) ? now : getStart());
final boolean isValue = (dateZ != null);
return (isValue ? (dateZ.getTime() - dateA.getTime()) : null);
}
public final synchronized Long getElapsed(final Date now) {
final Date dateA = getStart();
final Date dateZ = ((getFinish() == null) ? now : getFinish());
final boolean isValue = ((dateA != null) && (dateZ != null));
return (isValue ? (dateZ.getTime() - dateA.getTime()) : null);
}
public final synchronized long getStdoutLength() {
long length = 0L;
final Collection<Command> commands = getCommands();
for (final Command command : commands) {
final String stdout = command.getStdout();
length += ((stdout == null) ? 0L : stdout.length());
}
return length;
}
public final synchronized long getStderrLength() {
long length = 0L;
final Collection<Command> commands = getCommands();
for (final Command command : commands) {
final String stderr = command.getStderr();
length += ((stderr == null) ? 0L : stderr.length());
}
return length;
}
public final synchronized Integer getExitValue() {
Integer exitValue = 0;
final Collection<Command> commands = getCommands();
for (final Command command : commands) {
exitValue = command.getExitValue();
if (exitValue == null) {
break;
} else if (!exitValue.equals(0)) {
break;
}
}
return exitValue;
}
private static class Const {
private static final String START = "start"; // i18n internal
private static final String FINISH = "finish"; // i18n internal
private static final String INTERRUPTED = "interrupted"; // i18n internal
}
}
|
joginder07/baseui | documentation-site/examples/data-table/basic.js | <gh_stars>1000+
// @flow
import React from 'react';
import {useStyletron} from 'baseui';
import {
StatefulDataTable,
BooleanColumn,
CategoricalColumn,
CustomColumn,
NumericalColumn,
StringColumn,
COLUMNS,
NUMERICAL_FORMATS,
} from 'baseui/data-table';
// https://gist.github.com/6174/6062387
function pseudoRandomString(rowIdx, columnIdx) {
return (
(0.88 * rowIdx)
.toString(36)
.replace('.', '')
.substring(2) +
(0.99 * columnIdx).toString(36).replace('.', '')
).slice(0, 10);
}
function makeRowsFromColumns(columns, rowCount) {
const rows = [];
for (let i = 0; i < rowCount; i++) {
rows.push({
id: i,
data: columns.map((column, j) => {
switch (column.kind) {
case COLUMNS.CATEGORICAL:
switch (i % 11) {
case 11:
return 'UberX';
case 10:
return 'UberXL';
case 9:
return 'Uber Select';
case 8:
return 'Uber Comfort';
case 7:
return 'Uber Pool';
case 6:
return 'Uber Black';
case 5:
return 'Uber Assist';
case 4:
return 'Uber WAV';
case 3:
return 'Transit';
case 2:
return 'Taxi';
case 1:
return 'Bike';
case 0:
default:
return 'Scooter';
}
case COLUMNS.NUMERICAL:
return i % 2 ? i - 1 : i + 3;
case COLUMNS.BOOLEAN:
return i % 2 === 0;
case COLUMNS.STRING:
return pseudoRandomString(i, j);
case COLUMNS.CUSTOM:
switch (i % 5) {
case 4:
return {color: 'red'};
case 3:
return {color: 'green'};
case 2:
return {color: 'blue'};
case 1:
return {color: 'purple'};
case 0:
default:
return {color: 'yellow'};
}
default:
return 'default' + pseudoRandomString(i, j);
}
}),
});
}
return rows;
}
type RowDataT = [
string,
string,
number,
number,
number,
{color: string},
boolean,
string,
];
const columns = [
CategoricalColumn({
title: 'categorical',
mapDataToValue: (data: RowDataT) => data[0],
}),
StringColumn({
title: 'string',
mapDataToValue: (data: RowDataT) => data[1],
}),
NumericalColumn({
title: 'three',
mapDataToValue: (data: RowDataT) => data[2],
}),
NumericalColumn({
title: 'neg std',
highlight: n => n < 0,
mapDataToValue: (data: RowDataT) => data[3],
}),
NumericalColumn({
title: 'accounting',
format: NUMERICAL_FORMATS.ACCOUNTING,
mapDataToValue: (data: RowDataT) => data[4],
}),
CustomColumn<{color: string}, {}>({
title: 'custom color',
mapDataToValue: (data: RowDataT) => data[5],
renderCell: function Cell(props) {
const [css] = useStyletron();
return (
<div
className={css({
alignItems: 'center',
fontFamily: '"Comic Sans MS", cursive, sans-serif',
display: 'flex',
})}
>
<div
className={css({
backgroundColor: props.value.color,
height: '12px',
marginRight: '24px',
width: '12px',
})}
/>
<div>{props.value.color}</div>
</div>
);
},
}),
BooleanColumn({
title: 'boolean',
mapDataToValue: (data: RowDataT) => data[6],
}),
CategoricalColumn({
title: 'second category',
mapDataToValue: (data: RowDataT) => data[7],
}),
];
const rows = makeRowsFromColumns(columns, 2000);
export default function Example() {
const [css] = useStyletron();
return (
<div className={css({height: '800px'})}>
<StatefulDataTable columns={columns} rows={rows} />
</div>
);
}
|
hererucis/xyz-qgis-plugin | test/test_basemap.py | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (c) 2019 HERE Europe B.V.
#
# SPDX-License-Identifier: MIT
# License-Filename: LICENSE
#
###############################################################################
from test import mock_iface
from test.utils import (BaseTestAsync, BaseTestWorkerAsync, add_test_fn_params,
get_env)
from qgis.testing import start_app, unittest
from qgis.core import QgsRasterLayer, QgsProject
from XYZHubConnector.modules import basemap
import os
APP_ID=os.environ["APP_ID"]
APP_CODE=os.environ["APP_CODE"]
app = start_app()
class TestBasemap(BaseTestWorkerAsync):
def test_basemap(self):
iface = mock_iface.make_iface_canvas(self)
d = os.path.dirname(basemap.__file__)
t = basemap.load_xml(os.path.join(d,"basemap.xml"))
lst = list(t.values())
for k,v in t.items():
canvas = mock_iface.show_canvas(iface)
canvas.setWindowTitle(k)
basemap.add_auth(v,app_id=APP_ID, app_code=APP_CODE)
u = basemap.parse_uri(v)
self._log_debug(k,u)
layer = QgsRasterLayer( u, k, "wms")
# QgsProject.instance().addMapLayer(layer)
canvas.setLayers([layer])
mock_iface.canvas_zoom_to_layer(canvas, layer)
self._wait_async()
if __name__ == "__main__":
# unittest.main()
tests = [
"TestBasemap.test_basemap"
]
unittest.main(defaultTest = tests)
|
Elyahu41/Terasology | engine/src/main/java/org/terasology/engine/rendering/dag/RenderPipelineTask.java | <reponame>Elyahu41/Terasology
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.rendering.dag;
/**
* TODO: Add javadocs
*/
public interface RenderPipelineTask {
void process();
}
|
alesaadi/fantastic-components | src/List/List/style/TitleStyled.js | /**
* Created by Programmer1 on 12/4/2017.
*/
import styled from 'styled-components';
import {getDarkColor} from './Statics';
const TitleStyled = styled.div`
font-family: ${(props) => props.theme.fontFamily};
color:${(props) => getDarkColor(props)};
margin:15px;
font-size:24px;
direction: ${(props) => (props.rtl || props.theme.rtl) ? 'rtl' : 'ltr' }`;
export default TitleStyled;
|
jekyll-openui5/jekyll-openui5 | assets/sap/ui/mdc/chart/DrillStackHandler-dbg.js | <filename>assets/sap/ui/mdc/chart/DrillStackHandler-dbg.js
/*!
* OpenUI5
* (c) Copyright 2009-2021 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define([
"sap/ui/core/Core",
"sap/m/ResponsivePopover",
"sap/m/List",
"sap/m/Bar",
"sap/m/SearchField",
"sap/m/StandardListItem",
"sap/ui/core/InvisibleText",
"sap/m/library",
"sap/ui/Device",
"sap/ui/mdc/chart/DimensionItem",
"sap/ui/mdc/chart/ChartSettings"
], function(
Core,
ResponsivePopover,
List,
Bar,
SearchField,
StandardListItem,
InvisibleText,
MLibrary,
Device,
DimensionItem,
ChartSettings
) {
"use strict";
var Link;
// shortcut for sap.m.PlacementType
var PlacementType = MLibrary.PlacementType;
// shortcut for sap.m.ListType
var ListType = MLibrary.ListType;
// shortcut for sap.m.ListMode
var ListMode = MLibrary.ListMode;
function _getDrillStackDimensions(oChart) {
var aDrillStack = oChart.getAggregation("_chart").getDrillStack();
var aStackDimensions = [];
aDrillStack.forEach(function(oStackEntry) {
// loop over nested dimension arrays
oStackEntry.dimension.forEach(function(sDimension) {
if (sDimension != null && sDimension != "" && aStackDimensions.indexOf(sDimension) == -1) {
aStackDimensions.push(sDimension);
}
});
});
return aStackDimensions;
}
//Get all dimensions in a sorted manner
function _getSortedDimensions(aProperties) {
var aDimensions = aProperties.filter(function(oItem) {
return oItem.kind == "Dimension";
});
if (aDimensions) {
aDimensions.sort(function(a, b) {
if (a.label && b.label) {
return a.label.localeCompare(b.label);
}
});
}
return aDimensions;
}
/**
* Handles all drill-stack operations on a mdc.Chart instance
* inlcuding drill-downs, drill-ups and updating of depending controls
* like Breadcrumbs.
* @constructor
*/
var DrillStackHandler = function() {
};
/**
* Creates a drill down popover
* @param oChart
* @returns the popover object
*
* @private
* @ui5-restricted sap.ui.mdc
*/
DrillStackHandler.createDrillDownPopover = function(oChart) {
var oList = new List({
mode: ListMode.SingleSelectMaster,
selectionChange: function(oControlEvent) {
var oListItem = oControlEvent.getParameter("listItem");
if (oListItem) {
//Call flex to capture current state before adding an item to the chart aggregation
oChart.getEngine().createChanges({
control: oChart,
key: "Item",
state: [{
name: oListItem.data("dim").name,
position: oChart.getItems().length
}]
});
}
oPopover.close();
}
});
var oSubHeader = new Bar();
//TODO add search field
//var oSearchField = new SearchField({
//placeholder: this._oRb.getText("CHART_DRILLDOWN_SEARCH")
//});
//oSearchField.attachLiveChange(function(oEvent) {
//this._triggerSearchInDrillDownPopover(oEvent, oList);
//}.bind(this));
var oPopover = new ResponsivePopover({
contentWidth: "25rem",
contentHeight: "20rem",
placement: PlacementType.Bottom,
subHeader: oSubHeader
});
var oRb = Core.getLibraryResourceBundle("sap.ui.mdc");
//Show header only in mobile scenarios
//still support screen reader while on desktops.
if (Device.system.desktop) {
var oInvText = new InvisibleText({
text: oRb.getText("chart.CHART_DRILLDOWN_TITLE")
});
oPopover.setShowHeader(false);
oPopover.addContent(oInvText);
oPopover.addAriaLabelledBy(oInvText);
} else {
oPopover.setTitle(oRb.getText("chart.CHART_DRILLDOWN_TITLE"));
}
oPopover.addContent(oList);
oChart._oDrillDownPopover = oPopover;
return oPopover;
};
/**
* Shows the drill-down popover on the toolbar button of an mdc.Chart instance
* @param {sap.ui.mdc.Chart} oChart
*
* @experimental
* @private
* @ui5-restricted sap.ui.mdc
*/
DrillStackHandler.showDrillDownPopover = function(oChart) {
var oFetchPropertiesPromise = oChart.getControlDelegate().fetchProperties(oChart);
return oFetchPropertiesPromise.then(function(aProperties) {
//Remove all prior items from drill-down list
var oDrillDownPopover = oChart._oDrillDownPopover;
var oDrillDownList = oDrillDownPopover.getContent()[1];
var aIgnoreDimensions, aSortedDimensions, oDimension, oListItem;
oDrillDownList.destroyItems();
// Ignore currently applied dimensions from drill-stack for selection
aIgnoreDimensions = _getDrillStackDimensions(oChart);
aSortedDimensions = _getSortedDimensions(aProperties);
for (var i = 0; i < aSortedDimensions.length; i++) {
oDimension = aSortedDimensions[i];
if (aIgnoreDimensions.indexOf(oDimension.name) > -1) {
continue;
}
//TODO: Check if still valid
// If dimension is not filterable and datapoints are selected then skip
/*if (!oViewField.filterable && this._oChart.getSelectedDataPoints().count > 0) {
continue;
}*/
oListItem = new StandardListItem({
title: oDimension.label,
type: ListType.Active
});
oListItem.data("dim", oDimension);
/*sTooltip = this._getFieldTooltip(oDimension.name);
if (sTooltip) {
oListItem.setTooltip(sTooltip);
}*/
//Add item to list within popover
oDrillDownList.addItem(oListItem);
}
return new Promise(function(resolve, reject) {
oDrillDownPopover.attachEventOnce("afterOpen", function onAfterDrillDownPopoverOpen(oControlEvent) {
resolve(oDrillDownPopover);
});
oDrillDownPopover.openBy(oChart._oDrillDownBtn);
});
});
};
/**
* Creates and sets breadcrumps on the MDC chart for the current drill level
*
* @param {sap.ui.mdc.Chart} oChart
*
* @experimental
* @private
* @ui5-protected sap.ui.mdc
*/
DrillStackHandler.createDrillBreadcrumbs = function(oChart) {
return new Promise(function(resolve, reject) {
sap.ui.require([
"sap/m/Breadcrumbs"
], function(Breadcrumbs) {
var oInnerChart = oChart.getAggregation("_chart");
if (oInnerChart) {
var oDrillBreadcrumbs = new Breadcrumbs();
oChart.setAggregation("_breadcrumbs", oDrillBreadcrumbs);
//initial update of current drill-path
this._updateDrillBreadcrumbs(oChart, oDrillBreadcrumbs).then(function() {
resolve(oDrillBreadcrumbs);
});
}
}.bind(this));
}.bind(this));
};
/**
* Creates a breadcrump with given settings
* @param oChart the chart the breadcrump is for
* @param oCrumbSettings settings for the breadcrump
*
* @returns the created breadcrump
*
* @experimental
* @private
* @ui5-restricted sap.ui.mdc
*/
DrillStackHandler.createCrumb = function(oChart, oCrumbSettings) {
var oInnerChart = oChart.getAggregation("_chart");
var oCrumb = new Link({
text: oCrumbSettings.dimensionText,
press: function onCrumbPressed(oControlEvent) {
var oDrillBreadcrumbs = oChart.getAggregation("_breadcrumbs"),
iLinkIndex = oDrillBreadcrumbs.indexOfLink(oControlEvent.getSource());
// get drill-path which was drilled-up and needs to be removed from mdc chart
var aCurrentDrillStack = oInnerChart.getDrillStack()[oInnerChart.getDrillStack().length - 1].dimension,
aDrilledPath = aCurrentDrillStack.slice(iLinkIndex + 1);
oInnerChart.fireDeselectData();
// retrieve the actual items and remove them from mdc chart items aggregation
var aDrilledItems = oChart.getItemsByKeys(aDrilledPath);
// call flex to capture the current state before removing item(s) of the chart aggregation
var aFlexItemChanges = aDrilledItems.map(function(oDrillItem) {
return {
name: oDrillItem.getKey(),
visible: false
};
});
oChart.getEngine().createChanges({
control: oChart,
key: "Item",
state: aFlexItemChanges
});
// don't forget to update the bread crumbs control itself
this._updateDrillBreadcrumbs(oChart, oDrillBreadcrumbs);
}.bind(this)
});
// unique dimension key is needed to remove the item from the mdc chart aggregation on drilling up
oCrumb.data("key", oCrumbSettings.dimensionKey);
return oCrumb;
};
/**
* Updates the breadcrumps shown on the MDC Chart
*
* @param {sap.ui.mdc.Chart} oChart the MDC Chart to update the breadcrumps on
* @param {*} oDrillBreadcrumbs the breadcrumps to show
*
* @experimental
* @private
* @ui5-restricted sap.ui.mdc
*/
DrillStackHandler._updateDrillBreadcrumbs = function(oChart, oDrillBreadcrumbs) {
return new Promise(function(resolve, reject) {
sap.ui.require([
"sap/m/Link"
], function(LinkClass) {
Link = LinkClass;
if (!oDrillBreadcrumbs) {
return;
}
// Get access to drill history
var oInnerChart = oChart.getAggregation("_chart");
if (!oInnerChart) {
return;
}
var aVisibleDimensionsRev = oInnerChart.getDrillStack();
var newLinks = [];
// When chart is bound to non-aggregated entity there is no drill-stack
// existing
if (aVisibleDimensionsRev) {
// Reverse array to display right order of crumbs
aVisibleDimensionsRev.reverse();
aVisibleDimensionsRev.forEach(function(dim, index, array) {
// Check if stack entry has dimension names and if a
// dimension is existing for this name
if (dim.dimension.length > 0 && typeof oInnerChart.getDimensionByName(dim.dimension[dim.dimension.length - 1]) != 'undefined') {
// show breadcrumbs
//If Breadcrumps were set invisible for no drill stack, they need to be set visible again
oDrillBreadcrumbs.setVisible(true);
// use the last entry of each drill-stack entry to built
// up the drill-path
var sDimText = oInnerChart.getDimensionByName(dim.dimension[dim.dimension.length - 1]).getLabel();
var sDimKey = oInnerChart.getDimensionByName(dim.dimension[dim.dimension.length - 1]).getName();
// Set current drill position in breadcrumb control
if (index == 0) {
oDrillBreadcrumbs.setCurrentLocationText(sDimText);
} else {
var oCrumbSettings = {
dimensionKey: sDimKey,
dimensionText: sDimText
};
var oCrumb = this.createCrumb(oChart, oCrumbSettings);
newLinks.push(oCrumb);//note the links are added in an incorrect order need to reverse
}
} else {
// Show no text on breadcrumb if stack contains only one
// entry with no dimension at all (all dims are shown)
if (index == 0) {
// hide breadcrumbs
oDrillBreadcrumbs.setVisible(false);
}
}
}, this);
}
var currLinks = oDrillBreadcrumbs.getLinks();
newLinks.reverse();
var diff = false;
if (currLinks.length !== newLinks.length) {
diff = true;
} else {
for (var i = 0; i < newLinks.length; i++) {
if (newLinks[i].getText() != currLinks[i].getText()) {
diff = true;
break;
}
}
}
if (diff) {
// Clear aggregation before we rebuild it
if (oDrillBreadcrumbs.getLinks()) {
oDrillBreadcrumbs.destroyLinks();
}
for (var i = 0; i < newLinks.length; i++) {
oDrillBreadcrumbs.addLink(newLinks[i]);
}
}
resolve(oDrillBreadcrumbs);
}.bind(this));
}.bind(this));
};
return DrillStackHandler;
});
|
MaximeMorel/opentrack | FTNoIR_Tracker_PT/boost-compat.h | #pragma once
#include <memory>
namespace boost {
using std::shared_ptr;
}
|
ale-cristofori/MapStore2 | web/client/actions/__tests__/playback-test.js | <reponame>ale-cristofori/MapStore2
/*
* Copyright 2022, GeoSolutions Sas.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import expect from "expect";
import {
PLAY, PAUSE, STOP, SET_FRAMES, SET_CURRENT_FRAME, APPEND_FRAMES, FRAMES_LOADING, SELECT_PLAYBACK_RANGE,
CHANGE_SETTING, TOGGLE_ANIMATION_MODE, ANIMATION_STEP_MOVE, UPDATE_METADATA, SET_INTERVAL_DATA,
pause, play, stop, setFrames, setCurrentFrame, appendFrames, framesLoading, selectPlaybackRange,
changeSetting, toggleAnimationMode, animationStepMove, updateMetadata, setIntervalData
} from "../playback";
describe('Test playback actions', () => {
it('Test play action creator', () => {
const retval = play();
expect(retval).toExist();
expect(retval.type).toBe(PLAY);
});
it('Test pause action creator', () => {
const retval = pause();
expect(retval).toExist();
expect(retval.type).toBe(PAUSE);
});
it('Test stop action creator', () => {
const retval = stop();
expect(retval).toExist();
expect(retval.type).toBe(STOP);
});
it('Test setFrames action creator', () => {
const frames = ['1', '2'];
const retval = setFrames(frames);
expect(retval).toExist();
expect(retval.type).toBe(SET_FRAMES);
expect(retval.frames).toBe(frames);
});
it('Test setCurrentFrame action creator', () => {
const retval = setCurrentFrame(1);
expect(retval).toExist();
expect(retval.type).toBe(SET_CURRENT_FRAME);
expect(retval.frame).toBe(1);
});
it('Test appendFrames action creator', () => {
const frames = ['1', '2'];
const retval = appendFrames(frames);
expect(retval).toExist();
expect(retval.type).toBe(APPEND_FRAMES);
expect(retval.frames).toBe(frames);
});
it('Test framesLoading action creator', () => {
const retval = framesLoading(true);
expect(retval).toExist();
expect(retval.type).toBe(FRAMES_LOADING);
expect(retval.loading).toBe(true);
});
it('Test selectPlaybackRange action creator', () => {
const range = { startPlaybackRange: 'start', endPlaybackRange: 'end'};
const retval = selectPlaybackRange(range);
expect(retval).toExist();
expect(retval.type).toBe(SELECT_PLAYBACK_RANGE);
expect(retval.range).toBe(range);
});
it('Test changeSetting action creator', () => {
const retval = changeSetting('test', 'value');
expect(retval).toExist();
expect(retval.type).toBe(CHANGE_SETTING);
expect(retval.name).toBe('test');
expect(retval.value).toBe('value');
});
it('Test toggleAnimationMode action creator', () => {
const retval = toggleAnimationMode();
expect(retval).toExist();
expect(retval.type).toBe(TOGGLE_ANIMATION_MODE);
});
it('Test animationStepMove action creator', () => {
const retval = animationStepMove('asc');
const retval1 = animationStepMove('desc');
expect(retval).toExist();
expect(retval1).toExist();
expect(retval.type).toBe(ANIMATION_STEP_MOVE);
expect(retval1.type).toBe(ANIMATION_STEP_MOVE);
expect(retval.direction).toBe('asc');
expect(retval1.direction).toBe('desc');
});
it('Test updateMetadata action creator', () => {
const retval = updateMetadata({ next: 'next', previous: 'previous', forTime: 'forTime'});
expect(retval).toExist();
expect(retval.type).toBe(UPDATE_METADATA);
expect(retval.next).toBe('next');
expect(retval.previous).toBe('previous');
expect(retval.forTime).toBe('forTime');
});
it('Test setIntervalData action creator', () => {
const retval = setIntervalData(true);
expect(retval).toExist();
expect(retval.type).toBe(SET_INTERVAL_DATA);
expect(retval.timeIntervalData).toBe(true);
});
});
|
RashmicaG/OpenBLAS | relapack/src/zsytrf_rook_rec2.c | <reponame>RashmicaG/OpenBLAS<filename>relapack/src/zsytrf_rook_rec2.c<gh_stars>100-1000
/* -- translated by f2c (version 20100827).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
/* Table of constant values */
static doublecomplex c_b1 = {1.,0.};
static int c__1 = 1;
/** ZSYTRF_ROOK_REC2 computes a partial factorization of a complex symmetric matrix using the bounded Bunch-<NAME> ("rook") diagonal pivoting method.
*
* This routine is a minor modification of LAPACK's zlasyf_rook.
* It serves as an unblocked kernel in the recursive algorithms.
* The blocked BLAS Level 3 updates were removed and moved to the
* recursive algorithm.
* */
/* Subroutine */ void RELAPACK_zsytrf_rook_rec2(char *uplo, int *n,
int *nb, int *kb, doublecomplex *a, int *lda, int *
ipiv, doublecomplex *w, int *ldw, int *info, ftnlen uplo_len)
{
/* System generated locals */
int a_dim1, a_offset, w_dim1, w_offset, i__1, i__2, i__3, i__4;
double d__1, d__2;
doublecomplex z__1, z__2, z__3, z__4;
/* Builtin functions */
double sqrt(double), d_imag(doublecomplex *);
void z_div(doublecomplex *, doublecomplex *, doublecomplex *);
/* Local variables */
static int j, k, p;
static doublecomplex t, r1, d11, d12, d21, d22;
static int ii, jj, kk, kp, kw, jp1, jp2, kkw;
static logical done;
static int imax, jmax;
static double alpha;
extern logical lsame_(char *, char *, ftnlen, ftnlen);
static double dtemp, sfmin;
extern /* Subroutine */ int zscal_(int *, doublecomplex *,
doublecomplex *, int *);
static int itemp, kstep;
extern /* Subroutine */ int zgemv_(char *, int *, int *,
doublecomplex *, doublecomplex *, int *, doublecomplex *,
int *, doublecomplex *, doublecomplex *, int *, ftnlen),
zcopy_(int *, doublecomplex *, int *, doublecomplex *,
int *), zswap_(int *, doublecomplex *, int *,
doublecomplex *, int *);
extern double dlamch_(char *, ftnlen);
static double absakk, colmax;
extern int izamax_(int *, doublecomplex *, int *);
static double rowmax;
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--ipiv;
w_dim1 = *ldw;
w_offset = 1 + w_dim1;
w -= w_offset;
/* Function Body */
*info = 0;
alpha = (sqrt(17.) + 1.) / 8.;
sfmin = dlamch_("S", (ftnlen)1);
if (lsame_(uplo, "U", (ftnlen)1, (ftnlen)1)) {
k = *n;
L10:
kw = *nb + k - *n;
if ((k <= *n - *nb + 1 && *nb < *n) || k < 1) {
goto L30;
}
kstep = 1;
p = k;
zcopy_(&k, &a[k * a_dim1 + 1], &c__1, &w[kw * w_dim1 + 1], &c__1);
if (k < *n) {
i__1 = *n - k;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &k, &i__1, &z__1, &a[(k + 1) * a_dim1 + 1],
lda, &w[k + (kw + 1) * w_dim1], ldw, &c_b1, &w[kw *
w_dim1 + 1], &c__1, (ftnlen)12);
}
i__1 = k + kw * w_dim1;
absakk = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[k + kw *
w_dim1]), abs(d__2));
if (k > 1) {
i__1 = k - 1;
imax = izamax_(&i__1, &w[kw * w_dim1 + 1], &c__1);
i__1 = imax + kw * w_dim1;
colmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[imax +
kw * w_dim1]), abs(d__2));
} else {
colmax = 0.;
}
if (max(absakk,colmax) == 0.) {
if (*info == 0) {
*info = k;
}
kp = k;
zcopy_(&k, &w[kw * w_dim1 + 1], &c__1, &a[k * a_dim1 + 1], &c__1);
} else {
if (! (absakk < alpha * colmax)) {
kp = k;
} else {
done = FALSE_;
L12:
zcopy_(&imax, &a[imax * a_dim1 + 1], &c__1, &w[(kw - 1) *
w_dim1 + 1], &c__1);
i__1 = k - imax;
zcopy_(&i__1, &a[imax + (imax + 1) * a_dim1], lda, &w[imax +
1 + (kw - 1) * w_dim1], &c__1);
if (k < *n) {
i__1 = *n - k;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &k, &i__1, &z__1, &a[(k + 1) *
a_dim1 + 1], lda, &w[imax + (kw + 1) * w_dim1],
ldw, &c_b1, &w[(kw - 1) * w_dim1 + 1], &c__1, (
ftnlen)12);
}
if (imax != k) {
i__1 = k - imax;
jmax = imax + izamax_(&i__1, &w[imax + 1 + (kw - 1) *
w_dim1], &c__1);
i__1 = jmax + (kw - 1) * w_dim1;
rowmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&
w[jmax + (kw - 1) * w_dim1]), abs(d__2));
} else {
rowmax = 0.;
}
if (imax > 1) {
i__1 = imax - 1;
itemp = izamax_(&i__1, &w[(kw - 1) * w_dim1 + 1], &c__1);
i__1 = itemp + (kw - 1) * w_dim1;
dtemp = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[
itemp + (kw - 1) * w_dim1]), abs(d__2));
if (dtemp > rowmax) {
rowmax = dtemp;
jmax = itemp;
}
}
i__1 = imax + (kw - 1) * w_dim1;
if (! ((d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[imax
+ (kw - 1) * w_dim1]), abs(d__2)) < alpha * rowmax)) {
kp = imax;
zcopy_(&k, &w[(kw - 1) * w_dim1 + 1], &c__1, &w[kw *
w_dim1 + 1], &c__1);
done = TRUE_;
} else if (p == jmax || rowmax <= colmax) {
kp = imax;
kstep = 2;
done = TRUE_;
} else {
p = imax;
colmax = rowmax;
imax = jmax;
zcopy_(&k, &w[(kw - 1) * w_dim1 + 1], &c__1, &w[kw *
w_dim1 + 1], &c__1);
}
if (! done) {
goto L12;
}
}
kk = k - kstep + 1;
kkw = *nb + kk - *n;
if (kstep == 2 && p != k) {
i__1 = k - p;
zcopy_(&i__1, &a[p + 1 + k * a_dim1], &c__1, &a[p + (p + 1) *
a_dim1], lda);
zcopy_(&p, &a[k * a_dim1 + 1], &c__1, &a[p * a_dim1 + 1], &
c__1);
i__1 = *n - k + 1;
zswap_(&i__1, &a[k + k * a_dim1], lda, &a[p + k * a_dim1],
lda);
i__1 = *n - kk + 1;
zswap_(&i__1, &w[k + kkw * w_dim1], ldw, &w[p + kkw * w_dim1],
ldw);
}
if (kp != kk) {
i__1 = kp + k * a_dim1;
i__2 = kk + k * a_dim1;
a[i__1].r = a[i__2].r, a[i__1].i = a[i__2].i;
i__1 = k - 1 - kp;
zcopy_(&i__1, &a[kp + 1 + kk * a_dim1], &c__1, &a[kp + (kp +
1) * a_dim1], lda);
zcopy_(&kp, &a[kk * a_dim1 + 1], &c__1, &a[kp * a_dim1 + 1], &
c__1);
i__1 = *n - kk + 1;
zswap_(&i__1, &a[kk + kk * a_dim1], lda, &a[kp + kk * a_dim1],
lda);
i__1 = *n - kk + 1;
zswap_(&i__1, &w[kk + kkw * w_dim1], ldw, &w[kp + kkw *
w_dim1], ldw);
}
if (kstep == 1) {
zcopy_(&k, &w[kw * w_dim1 + 1], &c__1, &a[k * a_dim1 + 1], &
c__1);
if (k > 1) {
i__1 = k + k * a_dim1;
if ((d__1 = a[i__1].r, abs(d__1)) + (d__2 = d_imag(&a[k +
k * a_dim1]), abs(d__2)) >= sfmin) {
z_div(&z__1, &c_b1, &a[k + k * a_dim1]);
r1.r = z__1.r, r1.i = z__1.i;
i__1 = k - 1;
zscal_(&i__1, &r1, &a[k * a_dim1 + 1], &c__1);
} else /* if(complicated condition) */ {
i__1 = k + k * a_dim1;
if (a[i__1].r != 0. || a[i__1].i != 0.) {
i__1 = k - 1;
for (ii = 1; ii <= i__1; ++ii) {
i__2 = ii + k * a_dim1;
z_div(&z__1, &a[ii + k * a_dim1], &a[k + k *
a_dim1]);
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
/* L14: */
}
}
}
}
} else {
if (k > 2) {
i__1 = k - 1 + kw * w_dim1;
d12.r = w[i__1].r, d12.i = w[i__1].i;
z_div(&z__1, &w[k + kw * w_dim1], &d12);
d11.r = z__1.r, d11.i = z__1.i;
z_div(&z__1, &w[k - 1 + (kw - 1) * w_dim1], &d12);
d22.r = z__1.r, d22.i = z__1.i;
z__3.r = d11.r * d22.r - d11.i * d22.i, z__3.i = d11.r *
d22.i + d11.i * d22.r;
z__2.r = z__3.r - 1., z__2.i = z__3.i - 0.;
z_div(&z__1, &c_b1, &z__2);
t.r = z__1.r, t.i = z__1.i;
i__1 = k - 2;
for (j = 1; j <= i__1; ++j) {
i__2 = j + (k - 1) * a_dim1;
i__3 = j + (kw - 1) * w_dim1;
z__4.r = d11.r * w[i__3].r - d11.i * w[i__3].i,
z__4.i = d11.r * w[i__3].i + d11.i * w[i__3]
.r;
i__4 = j + kw * w_dim1;
z__3.r = z__4.r - w[i__4].r, z__3.i = z__4.i - w[i__4]
.i;
z_div(&z__2, &z__3, &d12);
z__1.r = t.r * z__2.r - t.i * z__2.i, z__1.i = t.r *
z__2.i + t.i * z__2.r;
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
i__2 = j + k * a_dim1;
i__3 = j + kw * w_dim1;
z__4.r = d22.r * w[i__3].r - d22.i * w[i__3].i,
z__4.i = d22.r * w[i__3].i + d22.i * w[i__3]
.r;
i__4 = j + (kw - 1) * w_dim1;
z__3.r = z__4.r - w[i__4].r, z__3.i = z__4.i - w[i__4]
.i;
z_div(&z__2, &z__3, &d12);
z__1.r = t.r * z__2.r - t.i * z__2.i, z__1.i = t.r *
z__2.i + t.i * z__2.r;
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
/* L20: */
}
}
i__1 = k - 1 + (k - 1) * a_dim1;
i__2 = k - 1 + (kw - 1) * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
i__1 = k - 1 + k * a_dim1;
i__2 = k - 1 + kw * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
i__1 = k + k * a_dim1;
i__2 = k + kw * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
}
}
if (kstep == 1) {
ipiv[k] = kp;
} else {
ipiv[k] = -p;
ipiv[k - 1] = -kp;
}
k -= kstep;
goto L10;
L30:
j = k + 1;
L60:
kstep = 1;
jp1 = 1;
jj = j;
jp2 = ipiv[j];
if (jp2 < 0) {
jp2 = -jp2;
++j;
jp1 = -ipiv[j];
kstep = 2;
}
++j;
if (jp2 != jj && j <= *n) {
i__1 = *n - j + 1;
zswap_(&i__1, &a[jp2 + j * a_dim1], lda, &a[jj + j * a_dim1], lda)
;
}
jj = j - 1;
if (jp1 != jj && kstep == 2) {
i__1 = *n - j + 1;
zswap_(&i__1, &a[jp1 + j * a_dim1], lda, &a[jj + j * a_dim1], lda)
;
}
if (j <= *n) {
goto L60;
}
*kb = *n - k;
} else {
k = 1;
L70:
if ((k >= *nb && *nb < *n) || k > *n) {
goto L90;
}
kstep = 1;
p = k;
i__1 = *n - k + 1;
zcopy_(&i__1, &a[k + k * a_dim1], &c__1, &w[k + k * w_dim1], &c__1);
if (k > 1) {
i__1 = *n - k + 1;
i__2 = k - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__1, &i__2, &z__1, &a[k + a_dim1], lda, &
w[k + w_dim1], ldw, &c_b1, &w[k + k * w_dim1], &c__1, (
ftnlen)12);
}
i__1 = k + k * w_dim1;
absakk = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[k + k *
w_dim1]), abs(d__2));
if (k < *n) {
i__1 = *n - k;
imax = k + izamax_(&i__1, &w[k + 1 + k * w_dim1], &c__1);
i__1 = imax + k * w_dim1;
colmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[imax +
k * w_dim1]), abs(d__2));
} else {
colmax = 0.;
}
if (max(absakk,colmax) == 0.) {
if (*info == 0) {
*info = k;
}
kp = k;
i__1 = *n - k + 1;
zcopy_(&i__1, &w[k + k * w_dim1], &c__1, &a[k + k * a_dim1], &
c__1);
} else {
if (! (absakk < alpha * colmax)) {
kp = k;
} else {
done = FALSE_;
L72:
i__1 = imax - k;
zcopy_(&i__1, &a[imax + k * a_dim1], lda, &w[k + (k + 1) *
w_dim1], &c__1);
i__1 = *n - imax + 1;
zcopy_(&i__1, &a[imax + imax * a_dim1], &c__1, &w[imax + (k +
1) * w_dim1], &c__1);
if (k > 1) {
i__1 = *n - k + 1;
i__2 = k - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__1, &i__2, &z__1, &a[k + a_dim1]
, lda, &w[imax + w_dim1], ldw, &c_b1, &w[k + (k +
1) * w_dim1], &c__1, (ftnlen)12);
}
if (imax != k) {
i__1 = imax - k;
jmax = k - 1 + izamax_(&i__1, &w[k + (k + 1) * w_dim1], &
c__1);
i__1 = jmax + (k + 1) * w_dim1;
rowmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&
w[jmax + (k + 1) * w_dim1]), abs(d__2));
} else {
rowmax = 0.;
}
if (imax < *n) {
i__1 = *n - imax;
itemp = imax + izamax_(&i__1, &w[imax + 1 + (k + 1) *
w_dim1], &c__1);
i__1 = itemp + (k + 1) * w_dim1;
dtemp = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[
itemp + (k + 1) * w_dim1]), abs(d__2));
if (dtemp > rowmax) {
rowmax = dtemp;
jmax = itemp;
}
}
i__1 = imax + (k + 1) * w_dim1;
if (! ((d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[imax
+ (k + 1) * w_dim1]), abs(d__2)) < alpha * rowmax)) {
kp = imax;
i__1 = *n - k + 1;
zcopy_(&i__1, &w[k + (k + 1) * w_dim1], &c__1, &w[k + k *
w_dim1], &c__1);
done = TRUE_;
} else if (p == jmax || rowmax <= colmax) {
kp = imax;
kstep = 2;
done = TRUE_;
} else {
p = imax;
colmax = rowmax;
imax = jmax;
i__1 = *n - k + 1;
zcopy_(&i__1, &w[k + (k + 1) * w_dim1], &c__1, &w[k + k *
w_dim1], &c__1);
}
if (! done) {
goto L72;
}
}
kk = k + kstep - 1;
if (kstep == 2 && p != k) {
i__1 = p - k;
zcopy_(&i__1, &a[k + k * a_dim1], &c__1, &a[p + k * a_dim1],
lda);
i__1 = *n - p + 1;
zcopy_(&i__1, &a[p + k * a_dim1], &c__1, &a[p + p * a_dim1], &
c__1);
zswap_(&k, &a[k + a_dim1], lda, &a[p + a_dim1], lda);
zswap_(&kk, &w[k + w_dim1], ldw, &w[p + w_dim1], ldw);
}
if (kp != kk) {
i__1 = kp + k * a_dim1;
i__2 = kk + k * a_dim1;
a[i__1].r = a[i__2].r, a[i__1].i = a[i__2].i;
i__1 = kp - k - 1;
zcopy_(&i__1, &a[k + 1 + kk * a_dim1], &c__1, &a[kp + (k + 1)
* a_dim1], lda);
i__1 = *n - kp + 1;
zcopy_(&i__1, &a[kp + kk * a_dim1], &c__1, &a[kp + kp *
a_dim1], &c__1);
zswap_(&kk, &a[kk + a_dim1], lda, &a[kp + a_dim1], lda);
zswap_(&kk, &w[kk + w_dim1], ldw, &w[kp + w_dim1], ldw);
}
if (kstep == 1) {
i__1 = *n - k + 1;
zcopy_(&i__1, &w[k + k * w_dim1], &c__1, &a[k + k * a_dim1], &
c__1);
if (k < *n) {
i__1 = k + k * a_dim1;
if ((d__1 = a[i__1].r, abs(d__1)) + (d__2 = d_imag(&a[k +
k * a_dim1]), abs(d__2)) >= sfmin) {
z_div(&z__1, &c_b1, &a[k + k * a_dim1]);
r1.r = z__1.r, r1.i = z__1.i;
i__1 = *n - k;
zscal_(&i__1, &r1, &a[k + 1 + k * a_dim1], &c__1);
} else /* if(complicated condition) */ {
i__1 = k + k * a_dim1;
if (a[i__1].r != 0. || a[i__1].i != 0.) {
i__1 = *n;
for (ii = k + 1; ii <= i__1; ++ii) {
i__2 = ii + k * a_dim1;
z_div(&z__1, &a[ii + k * a_dim1], &a[k + k *
a_dim1]);
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
/* L74: */
}
}
}
}
} else {
if (k < *n - 1) {
i__1 = k + 1 + k * w_dim1;
d21.r = w[i__1].r, d21.i = w[i__1].i;
z_div(&z__1, &w[k + 1 + (k + 1) * w_dim1], &d21);
d11.r = z__1.r, d11.i = z__1.i;
z_div(&z__1, &w[k + k * w_dim1], &d21);
d22.r = z__1.r, d22.i = z__1.i;
z__3.r = d11.r * d22.r - d11.i * d22.i, z__3.i = d11.r *
d22.i + d11.i * d22.r;
z__2.r = z__3.r - 1., z__2.i = z__3.i - 0.;
z_div(&z__1, &c_b1, &z__2);
t.r = z__1.r, t.i = z__1.i;
i__1 = *n;
for (j = k + 2; j <= i__1; ++j) {
i__2 = j + k * a_dim1;
i__3 = j + k * w_dim1;
z__4.r = d11.r * w[i__3].r - d11.i * w[i__3].i,
z__4.i = d11.r * w[i__3].i + d11.i * w[i__3]
.r;
i__4 = j + (k + 1) * w_dim1;
z__3.r = z__4.r - w[i__4].r, z__3.i = z__4.i - w[i__4]
.i;
z_div(&z__2, &z__3, &d21);
z__1.r = t.r * z__2.r - t.i * z__2.i, z__1.i = t.r *
z__2.i + t.i * z__2.r;
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
i__2 = j + (k + 1) * a_dim1;
i__3 = j + (k + 1) * w_dim1;
z__4.r = d22.r * w[i__3].r - d22.i * w[i__3].i,
z__4.i = d22.r * w[i__3].i + d22.i * w[i__3]
.r;
i__4 = j + k * w_dim1;
z__3.r = z__4.r - w[i__4].r, z__3.i = z__4.i - w[i__4]
.i;
z_div(&z__2, &z__3, &d21);
z__1.r = t.r * z__2.r - t.i * z__2.i, z__1.i = t.r *
z__2.i + t.i * z__2.r;
a[i__2].r = z__1.r, a[i__2].i = z__1.i;
/* L80: */
}
}
i__1 = k + k * a_dim1;
i__2 = k + k * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
i__1 = k + 1 + k * a_dim1;
i__2 = k + 1 + k * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
i__1 = k + 1 + (k + 1) * a_dim1;
i__2 = k + 1 + (k + 1) * w_dim1;
a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i;
}
}
if (kstep == 1) {
ipiv[k] = kp;
} else {
ipiv[k] = -p;
ipiv[k + 1] = -kp;
}
k += kstep;
goto L70;
L90:
j = k - 1;
L120:
kstep = 1;
jp1 = 1;
jj = j;
jp2 = ipiv[j];
if (jp2 < 0) {
jp2 = -jp2;
--j;
jp1 = -ipiv[j];
kstep = 2;
}
--j;
if (jp2 != jj && j >= 1) {
zswap_(&j, &a[jp2 + a_dim1], lda, &a[jj + a_dim1], lda);
}
jj = j + 1;
if (jp1 != jj && kstep == 2) {
zswap_(&j, &a[jp1 + a_dim1], lda, &a[jj + a_dim1], lda);
}
if (j >= 1) {
goto L120;
}
*kb = k - 1;
}
return;
}
|
ExpressApp/pybotx | docs/src/development/logging/logging0.py | <gh_stars>10-100
from loguru import logger
from botx import Bot
bot = Bot()
logger.enable("botx")
|
Dn9x/dn-modbus | src/com/dn9x/modbus/msg/UnityWriteMultipleRegistersResponse.java | <gh_stars>10-100
package com.dn9x.modbus.msg;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class UnityWriteMultipleRegistersResponse extends UnityModbusResponse {
// instance attributes
private int m_WordCount;
private int m_Reference;
/**
* Constructs a new <tt>WriteMultipleRegistersResponse</tt> instance.
*/
public UnityWriteMultipleRegistersResponse(UnityModbusCoupler umc) {
super();
}// constructor
/**
* Constructs a new <tt>WriteMultipleRegistersResponse</tt> instance.
*
* @param reference
* the offset to start reading from.
* @param wordcount
* the number of words (registers) to be read.
*/
public UnityWriteMultipleRegistersResponse(int reference, int wordcount,UnityModbusCoupler umc) {
super();
m_Reference = reference;
m_WordCount = wordcount;
setDataLength(4);
}// constructor
/**
* Sets the reference of the register to start writing to with this
* <tt>WriteMultipleRegistersResponse</tt>.
* <p>
*
* @param ref
* the reference of the register to start writing to as
* <tt>int</tt>.
*/
private void setReference(int ref) {
m_Reference = ref;
}// setReference
/**
* Returns the reference of the register to start writing to with this
* <tt>WriteMultipleRegistersResponse</tt>.
* <p>
*
* @return the reference of the register to start writing to as <tt>int</tt>
* .
*/
public int getReference() {
return m_Reference;
}// getReference
/**
* Returns the number of bytes that have been written.
* <p>
*
* @return the number of bytes that have been read as <tt>int</tt>.
*/
public int getByteCount() {
return m_WordCount * 2;
}// getByteCount
/**
* Returns the number of words that have been read. The returned value
* should be half of the byte count of the response.
* <p>
*
* @return the number of words that have been read as <tt>int</tt>.
*/
public int getWordCount() {
return m_WordCount;
}// getWordCount
/**
* Sets the number of words that have been returned.
* <p>
*
* @param count
* the number of words as <tt>int</tt>.
*/
private void setWordCount(int count) {
m_WordCount = count;
}// setWordCount
public void writeData(DataOutput dout) throws IOException {
dout.writeShort(m_Reference);
dout.writeShort(getWordCount());
}// writeData
public void readData(DataInput din) throws IOException {
setReference(din.readUnsignedShort());
setWordCount(din.readUnsignedShort());
// NOTE: register values are not echoed
// update data length
setDataLength(4);
}// readData
}// class WriteMultipleRegistersResponse
|
streamdp/maintasks | src/test/java/com/epam/streamdp/nine/model/Configuration.java | <filename>src/test/java/com/epam/streamdp/nine/model/Configuration.java
package com.epam.streamdp.nine.model;
public class Configuration {
private String numberOfInstances;
private String idMachineType;
private String countOfGPUs;
private String idGPUType;
private String idLocalSSD;
private String idLocation;
private String idCommittedUsage;
public Configuration(String numberOfInstances, String idMachineType, String countOfGPUs, String idGPUType, String idLocalSSD, String idLocation, String idCommittedUsage) {
this.numberOfInstances = numberOfInstances;
this.idMachineType = idMachineType;
this.countOfGPUs = countOfGPUs;
this.idGPUType = idGPUType;
this.idLocalSSD = idLocalSSD;
this.idLocation = idLocation;
this.idCommittedUsage = idCommittedUsage;
}
public String getNumberOfInstances() {
return numberOfInstances;
}
public String getIdCommittedUsage() {
return idCommittedUsage;
}
public String getIdMachineType() {
return idMachineType;
}
public String getCountOfGPUs() {
return countOfGPUs;
}
public String getIdGPUType() {
return idGPUType;
}
public String getIdLocalSSD() {
return idLocalSSD;
}
public String getIdLocation() {
return idLocation;
}
}
|
hedgepigdaniel/metro | packages/metro/src/DeltaBundler/Serializers/__tests__/getAssets-test.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+javascript_foundation
* @format
*/
'use strict';
jest.mock('../../../Assets');
const getAssets = require('../getAssets');
const {getAssetData} = require('../../../Assets');
beforeEach(() => {
getAssetData.mockImplementation(async (path, localPath) => ({
path,
localPath,
}));
});
it('should return the bundle assets', async () => {
const graph = {
dependencies: new Map([
['/tmp/1.js', {path: '/tmp/1.js', output: [{type: 'js/module'}]}],
['/tmp/2.js', {path: '/tmp/2.js', output: [{type: 'js/module'}]}],
['/tmp/3.png', {path: '/tmp/3.png', output: [{type: 'js/module/asset'}]}],
['/tmp/4.js', {path: '/tmp/2.js', output: [{type: 'js/module'}]}],
['/tmp/5.mov', {path: '/tmp/5.mov', output: [{type: 'js/module/asset'}]}],
]),
};
expect(await getAssets(graph, {watchFolders: ['/tmp']})).toEqual([
{path: '/tmp/3.png', localPath: '3.png'},
{path: '/tmp/5.mov', localPath: '5.mov'},
]);
});
|
egorodet/CML | cml/vector/type_util.h | <filename>cml/vector/type_util.h
/* -*- C++ -*- ------------------------------------------------------------
@@COPYRIGHT@@
*-----------------------------------------------------------------------*/
/** @file
*/
#pragma once
#ifndef cml_vector_type_util_h
#define cml_vector_type_util_h
#include <cml/common/type_util.h>
#include <cml/vector/fwd.h>
namespace cml {
/** Defines typedef @c type as std::true_type if @c T is statically
* polymorphic and derived from @c readable_vector, or std::false_type
* otherwise. The static bool @c value is set to true or false to match @c
* type.
*/
template<class T> struct is_vector {
private:
/* Strip const, volatile, and reference from T to get the type to test: */
typedef cml::unqualified_type_t<T> naked_type;
/* Deduce the derived type (fails if T is not statically polymorphic): */
typedef actual_type_of_t<naked_type> derived_type;
public:
/* std::true_type if T is derived from readable_vector<>, std::false_type
* otherwise:
*/
typedef std::is_base_of<
readable_vector<derived_type>, naked_type> type;
/* True or false, depending upon 'type': */
static const bool value = type::value;
};
/** Wrapper for enable_if to detect vector types (derived from
* readable_vector).
*/
template<class Sub> struct enable_if_vector
: std::enable_if<is_vector<Sub>::value> {};
/** Convenience alias for enable_if_vector. */
template<class Sub> using enable_if_vector_t
= typename enable_if_vector<Sub>::type;
} // namespace cml
#endif
// -------------------------------------------------------------------------
// vim:ft=cpp:sw=2
|
NARUTONXD/autobahn-java-master | kutils/src/main/java/com/zwy/kutils/widget/baseview/BaseActivity.java | <gh_stars>10-100
package com.zwy.kutils.widget.baseview;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import com.zwy.kutils.eventbus.EventBus;
import com.zwy.kutils.utils.AppManager;
import com.zwy.kutils.widget.loadingdialog.DialogUIUtils;
import butterknife.ButterKnife;
/**
* ================================================================
* 创建时间:2017/7/27 下午3:51
* 创建人:Alan
* 文件描述:Activity基类
* 至尊宝:长夜漫漫无心睡眠,我以为只有我睡不着,原来晶晶姑娘你也睡不着 !
* ================================================================
*/
public abstract class BaseActivity extends AppCompatActivity {
protected BaseActivity mContext;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isTranslucentStatus() != 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(isTranslucentStatus());//通知栏所需颜色
}
}
Bundle extras = getIntent().getExtras();
if (null != extras) {
getBundleExtras(extras);
}
mContext = this;
setContentView(getLayoutId());
ButterKnife.bind(this);
AppManager.getAppManager().addActivity(this);
if (isNeedEventBus()) {
EventBus.getDefault().register(mContext);
android.util.Log.d("BaseActivity", "EventBus注册成功");
}
initView(savedInstanceState);
initData();
}
/**
* 是否需要沉浸式状态栏 不需要时返回0 需要时返回颜色
*
* @return StatusBarTintModle(boolean isTranslucentStatus, int color);
*/
protected abstract
@ColorRes
int isTranslucentStatus();
/**
* 是否需要注册eventBus
*
* @return 需要时返回true 页面销毁时会自动注销 子类无需重复注销
*/
protected abstract boolean isNeedEventBus();
/**
* 设置布局ID
*
* @return 资源文件ID
*/
protected abstract
@LayoutRes
int getLayoutId();
/**
* 初始化View
*
* @param savedInstanceState aty销毁时保存的临时参数
*/
protected abstract void initView(Bundle savedInstanceState);
/**
* 初始化数据源
*/
protected abstract void initData();
/**
* Bundle 传递数据
*
* @param extras
*/
protected abstract void getBundleExtras(Bundle extras);
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
//Toast显示
protected void showToast(String string) {
DialogUIUtils.showToast(string);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (isNeedEventBus()){
EventBus.getDefault().unregister(mContext);
android.util.Log.d("BaseActivity", "EventBus已注销");
}
ButterKnife.unbind(this);
AppManager.getAppManager().finishActivity(this);
}
/**
* 界面跳转
*
* @param cls 目标Activity
*/
protected void readyGo(Class<?> cls) {
readyGo(cls, null);
}
/**
* 跳转界面,传参
*
* @param cls 目标Activity
* @param bundle 数据
*/
protected void readyGo(Class<?> cls, Bundle bundle) {
Intent intent = new Intent(this, cls);
if (null != bundle)
intent.putExtras(bundle);
startActivity(intent);
}
/**
* 跳转界面并关闭当前界面
*
* @param cls 目标Activity
*/
protected void readyGoThenKill(Class<?> cls) {
readyGoThenKill(cls, null);
}
/**
* @param cls 目标Activity
* @param bundle 数据
*/
protected void readyGoThenKill(Class<?> cls, Bundle bundle) {
readyGo(cls, bundle);
finish();
}
/**
* startActivityForResult
*
* @param cls 目标Activity
* @param requestCode 发送判断值
*/
protected void readyGoForResult(Class<?> cls, int requestCode) {
Intent intent = new Intent(this, cls);
startActivityForResult(intent, requestCode);
}
/**
* startActivityForResult with bundle
*
* @param cls 目标Activity
* @param requestCode 发送判断值
* @param bundle 数据
*/
protected void readyGoForResult(Class<?> cls, int requestCode, Bundle bundle) {
Intent intent = new Intent(this, cls);
if (null != bundle) {
intent.putExtras(bundle);
}
startActivityForResult(intent, requestCode);
}
} |
nPhil01/o2r-muncher | test/compendium-configuration-file.js | <filename>test/compendium-configuration-file.js
/*
* (C) Copyright 2017 o2r 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.
*
*/
/* eslint-env mocha */
const assert = require('chai').assert;
const config = require('../config/config');
const createCompendiumPostRequest = require('./util').createCompendiumPostRequest;
const publishCandidate = require('./util').publishCandidate;
const waitForJob = require('./util').waitForJob;
const startJob = require('./util').startJob;
const mongojs = require('mongojs');
const request = require('request');
const yaml = require('yamljs');
require("./setup");
const cookie_o2r = 's:C0LIrsxGtHOGHld8Nv2jedjL4evGgEHo.GMsWD5Vveq0vBt7/4rGeoH5Xx7Dd2pgZR9DvhKCyDTY';
describe('configuration file (erc.yml)', () => {
var db = mongojs('localhost/muncher', ['compendia', 'jobs']);
before(function (done) {
db.compendia.drop(function (err, doc) {
db.jobs.drop(function (err, doc) {
done();
});
});
});
after(function (done) {
db.close();
done();
});
describe('validation function', () => {
var is_valid = config.bagtainer.id_is_valid;
it('should correctly identify valid ids', (done) => {
assert.isTrue(is_valid('12345abcde'), 'numbers and text');
assert.isTrue(is_valid('1234-abcde'), 'dash');
assert.isTrue(is_valid('1234_abcde'), 'underscore');
assert.isTrue(is_valid('1234.abcde'), 'period');
assert.isTrue(is_valid('a--.__.--b'), 'multiple separators');
done();
});
it('should correctly identify INvalid ids with separaters at start or end', (done) => {
assert.isFalse(is_valid('.1234abcde'), 'period at start');
assert.isFalse(is_valid('1234abcde.'), 'period at end');
assert.isFalse(is_valid('-1234abcde'), 'dash at start');
assert.isFalse(is_valid('1234abcde-'), 'dash at end');
assert.isFalse(is_valid('_1234abcde'), 'underscore at start');
assert.isFalse(is_valid('1234abcde_'), 'underscore at end');
done();
});
it('should correctly identify INvalid ids with not allowed characters', (done) => {
assert.isFalse(is_valid('abc-öäü-123'), 'umlaut');
done();
});
it('should correctly identify an empty id', (done) => {
assert.isFalse(is_valid(''), 'empty');
done();
});
});
describe('job succeeds with valid id in configuration file', () => {
let job_id;
before(function (done) {
this.timeout(720000);
createCompendiumPostRequest('./test/workspace/with-erc-yml', cookie_o2r, 'workspace', (req) => {
request(req, (err, res, body) => {
compendium_id = JSON.parse(body).id;
publishCandidate(compendium_id, cookie_o2r, () => {
startJob(compendium_id, id => {
job_id = id;
waitForJob(job_id, (finalStatus) => {
done();
});
});
});
});
});
});
it('should complete validate compendium', (done) => {
request(global.test_host + '/api/v1/job/' + job_id, (err, res, body) => {
assert.ifError(err);
let response = JSON.parse(body);
assert.propertyVal(response.steps.validate_compendium, 'status', 'success');
done();
});
});
});
describe('licenses are in created configuration file', () => {
let job_id;
before(function (done) {
this.timeout(90000);
createCompendiumPostRequest('./test/workspace/rmd-data', cookie_o2r, 'workspace', (req) => {
request(req, (err, res, body) => {
compendium_id = JSON.parse(body).id;
let j = request.jar();
let ck = request.cookie('connect.sid=' + cookie_o2r);
j.setCookie(ck, global.test_host);
let req_doc_o2r = {
uri: global.test_host + '/api/v1/compendium/' + compendium_id + '/metadata',
method: 'PUT',
jar: j,
json: {
'o2r': {
'access_right': 'fake',
'creators': [],
'description': 'fake',
'identifier': null,
'title': 'New title on the block',
'keywords': [],
'communities': null,
'license': {
'code': 'a_test_code_license',
'data': 'ODbL-1.0',
'text': 'licenses.txt',
'metadata': 'CC'
},
'publication_date': '1970-01-01',
'publication_type': 'test',
'mainfile': 'test.R',
'displayfile': 'test.html'
}
},
timeout: 30000
};
request(req_doc_o2r, (err, res, body) => {
startJob(compendium_id, id => {
job_id = id;
waitForJob(job_id, (finalStatus) => {
done();
});
});
});
});
});
});
it('should have all licenses in configuration file', (done) => {
request(global.test_host + '/api/v1/compendium/' + compendium_id + '/data/' + config.bagtainer.configFile.name, (err, res, body) => {
assert.ifError(err);
configuration = yaml.parse(body);
assert.hasAllKeys(configuration.licenses, ['code', 'data', 'text', 'metadata']);
done();
});
});
it('should have correct code license in configuration file', (done) => {
request(global.test_host + '/api/v1/compendium/' + compendium_id + '/data/' + config.bagtainer.configFile.name, (err, res, body) => {
assert.ifError(err);
assert.include(body, 'code: a_test_code_license');
done();
});
});
it('should have correct data license in configuration file', (done) => {
request(global.test_host + '/api/v1/compendium/' + compendium_id + '/data/' + config.bagtainer.configFile.name, (err, res, body) => {
assert.ifError(err);
assert.include(body, 'data: ODbL-1.0');
done();
});
});
it('should have correct text license in configuration file', (done) => {
request(global.test_host + '/api/v1/compendium/' + compendium_id + '/data/' + config.bagtainer.configFile.name, (err, res, body) => {
assert.ifError(err);
assert.include(body, 'text: licenses.txt');
done();
});
});
it('should have correct metadata license in configuration file', (done) => {
request(global.test_host + '/api/v1/compendium/' + compendium_id + '/data/' + config.bagtainer.configFile.name, (err, res, body) => {
assert.ifError(err);
assert.include(body, 'metadata: CC');
done();
});
});
});
});
|
Jean1dev/Especialista-JPA | iniciando-jpa/src/main/java/com/curso/model/SexoCliente.java | <gh_stars>0
package com.curso.model;
public enum SexoCliente {
MASCULINO,
FEMININO
}
|
ponder-lab/dari | db/src/test/java/com/psddev/dari/db/AggregateDatabaseTest.java | <reponame>ponder-lab/dari
package com.psddev.dari.db;
import com.google.common.collect.ImmutableMap;
import com.psddev.dari.util.CompactMap;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.mockito.internal.stubbing.defaultanswers.ReturnsMocks;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(Enclosed.class)
public class AggregateDatabaseTest {
public static class General {
@Test
public void implementsAll() throws NoSuchMethodException {
for (Method method : Database.class.getMethods()) {
if (Modifier.isStatic(method.getModifiers())) {
continue;
}
AggregateDatabase.class.getMethod(
method.getName(),
method.getParameterTypes());
}
}
}
// Test getters and setters.
public static class GetSet {
private AggregateDatabase database;
@Before
public void before() {
database = new AggregateDatabase();
}
private <T> void test(
Supplier<T> getter,
Matcher<? super T> getterMatcher,
Consumer<T> setter,
Supplier<T> setterValue) {
assertThat(getter.get(), getterMatcher);
T value = setterValue.get();
setter.accept(value);
assertThat(getter.get(), equalTo(value));
}
@Test
public void defaultDelegate() {
test(
database::getDefaultDelegate,
nullValue(),
database::setDefaultDelegate,
() -> mock(Database.class));
}
@Test
public void defaultReadDelegate() {
test(
database::getDefaultReadDelegate,
nullValue(),
database::setDefaultReadDelegate,
() -> mock(Database.class));
}
@Test
public void delegates() {
test(
database::getDelegates,
equalTo(ImmutableMap.of()),
database::setDelegates,
() -> ImmutableMap.of("delegate", mock(Database.class)));
}
@Test
public void readDelegates() {
test(
database::getReadDelegates,
equalTo(ImmutableMap.of()),
database::setReadDelegates,
() -> ImmutableMap.of("delegate", mock(Database.class)));
}
@Test
public void name() {
test(
database::getName,
nullValue(),
database::setName,
() -> UUID.randomUUID().toString());
}
@Test
public void environment() {
test(
database::getEnvironment,
notNullValue(),
database::setEnvironment,
() -> mock(DatabaseEnvironment.class));
}
}
// Test delegate helper methods.
public static class Delegate {
private Database defaultDelegate;
private Database secondaryDelegate;
private AggregateDatabase database;
@Before
public void before() {
defaultDelegate = mock(DefaultDelegate.class);
secondaryDelegate = mock(SecondaryDelegate.class);
database = new AggregateDatabase();
database.setDefaultDelegate(defaultDelegate);
database.setDelegates(ImmutableMap.of(
"default", defaultDelegate,
"secondary", secondaryDelegate
));
}
@Test(expected = NullPointerException.class)
public void getDelegatesByClassNull() {
database.getDelegatesByClass(null);
}
@Test
public void getDelegatesByClass() {
assertThat(database.getDelegatesByClass(DefaultDelegate.class), contains(defaultDelegate));
assertThat(database.getDelegatesByClass(MissingDelegate.class), empty());
}
@Test(expected = NullPointerException.class)
public void getFirstDelegateByClassNull() {
database.getFirstDelegateByClass(null);
}
@Test
public void getFirstDelegateByClass() {
assertThat(database.getFirstDelegateByClass(DefaultDelegate.class), equalTo(defaultDelegate));
assertThat(database.getFirstDelegateByClass(MissingDelegate.class), nullValue());
}
@Test
public void setDelegatesNull() {
database.setDelegates(null);
assertThat(database.getDelegates().size(), equalTo(0));
}
private interface DefaultDelegate extends Database {
}
private interface SecondaryDelegate extends Database {
}
private interface MissingDelegate extends Database {
}
}
public static abstract class ReadOrWrite {
protected Map<String, Database> goodDelegates;
protected Map<String, Database> badDelegates;
protected DatabaseEnvironment environment;
protected AggregateDatabase database;
@Before
public void beforeReadOrWrite() {
goodDelegates = new CompactMap<>();
for (int i = 0; i < 2; ++ i) {
goodDelegates.put("good" + i, mock(Database.class));
}
badDelegates = new CompactMap<>();
for (int i = 0; i < 2; ++ i) {
Database badDelegate = mock(Database.class, (Answer<Object>) invocation -> {
throw new UnsupportedOperationException("Bad delegate doesn't support any operation!");
});
doReturn("Bad delegate " + i).when(badDelegate).toString();
badDelegates.put("bad" + i, badDelegate);
}
environment = mock(DatabaseEnvironment.class);
when(environment.getTypesByGroup(any())).thenReturn(Collections.emptySet());
database = new AggregateDatabase();
database.setEnvironment(environment);
}
}
// Test read methods.
public static abstract class Read extends ReadOrWrite {
protected Database goodDelegate;
protected Query<Object> query;
@Before
@SuppressWarnings("unchecked")
public void beforeRead() {
goodDelegate = goodDelegates.values().stream().findFirst().get();
Map<String, Database> readDelegates = new CompactMap<>();
readDelegates.put("good", goodDelegate);
readDelegates.putAll(badDelegates);
database.setReadDelegates(readDelegates);
query = (Query<Object>) mock(Query.class);
}
@SuppressWarnings("unchecked")
private <R> void test(Function<Database, R> reader) {
SavesAndReturnsMocks answer = new SavesAndReturnsMocks();
when(reader.apply(goodDelegate)).then(answer);
assertThat(reader.apply(database), equalTo(answer.getLastObject()));
}
@Test
public void readAll() {
test(db -> db.readAll(query));
}
@Test
public void readAllGrouped() {
test(db -> db.readAllGrouped(query));
}
@Test
public void readCount() {
test(db -> db.readCount(query));
}
@Test
public void readFirst() {
test(db -> db.readFirst(query));
}
@Test
public void readIterable() {
test(db -> db.readIterable(query, 0));
}
@Test
public void readPartial() {
test(db -> db.readPartial(query, 0L, 1));
}
@Test
public void readPartialGrouped() {
test(db -> db.readPartialGrouped(query, 0L, 1, "field"));
}
@Test
public void readLastUpdate() {
test(db -> db.readLastUpdate(query));
}
private static class SavesAndReturnsMocks extends ReturnsMocks {
private Object lastObject;
public Object getLastObject() {
return lastObject;
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
lastObject = super.answer(invocation);
return lastObject;
}
}
}
public static class ReadGood extends Read {
@Before
public void before() {
database.setDefaultDelegate(goodDelegate);
}
}
public static class ReadBad extends Read {
@Before
public void before() {
database.setDefaultDelegate(badDelegates.values().stream().findFirst().get());
}
}
// Test batch write methods.
public static class Batch extends ReadOrWrite {
@Before
public void before() {
database.setDefaultDelegate(goodDelegates.values().stream().findFirst().get());
database.setDelegates(goodDelegates);
}
private void test(Consumer<Database> batcher) {
batcher.accept(database);
for (Database delegate : goodDelegates.values()) {
batcher.accept(verify(delegate));
}
}
@Test
public void beginWrites() {
test(Database::beginWrites);
}
@Test
public void beginIsolatedWrites() {
test(Database::beginIsolatedWrites);
}
@Test
public void commitWrites() {
test(Database::commitWrites);
}
@Test
public void commitWritesEventually() {
test(Database::commitWritesEventually);
}
@Test
public void endWrites() {
test(Database::endWrites);
}
}
// Test write methods.
public static class Write extends ReadOrWrite {
private Database defaultDelegate;
private Map<String, Database> delegates;
private State state;
@Before
public void before() {
defaultDelegate = goodDelegates.values().stream().findFirst().get();
database.setDefaultDelegate(defaultDelegate);
delegates = new CompactMap<>();
delegates.putAll(goodDelegates);
delegates.putAll(badDelegates);
database.setDelegates(delegates);
state = mock(State.class);
when(state.getType()).thenReturn(mock(ObjectType.class));
}
@Test
public void save() {
database.save(state);
verify(defaultDelegate).save(state);
delegates.values().stream()
.filter(delegate -> !delegate.equals(defaultDelegate))
.forEach(delegate -> {
verify(delegate, never()).save(state);
verify(delegate).saveUnsafely(state);
});
}
private void testOne(Consumer<Database> writer) {
writer.accept(database);
writer.accept(verify(defaultDelegate));
delegates.values().forEach(delegate -> writer.accept(verify(delegate)));
}
@Test
public void saveUnsafely() {
testOne(db -> db.saveUnsafely(state));
}
@Test
public void index() {
testOne(db -> db.index(state));
}
@Test
public void recalculate() {
testOne(db -> db.recalculate(state));
}
@Test
public void delete() {
testOne(db -> db.delete(state));
}
private void testAll(Consumer<Database> writer) {
writer.accept(database);
writer.accept(verify(defaultDelegate));
delegates.values().forEach(delegate -> writer.accept(verify(delegate)));
}
@Test
public void indexAll() {
ObjectIndex index = mock(ObjectIndex.class);
testAll(db -> db.indexAll(index));
}
@Test
public void deleteByQuery() {
Query<?> query = mock(Query.class);
testAll(db -> db.deleteByQuery(query));
}
}
// Test methods that forward the call to the default delegate.
public static class Forward {
private Database defaultDelegate;
private AggregateDatabase database;
@Before
public void before() {
defaultDelegate = mock(Database.class);
database = new AggregateDatabase();
database.setDefaultDelegate(defaultDelegate);
}
private void test(Consumer<Database> consumer) {
consumer.accept(database);
consumer.accept(verify(defaultDelegate));
}
@Test
public void now() {
test(Database::now);
}
@Test
public void addUpdateNotifier() {
UpdateNotifier<?> notifier = mock(UpdateNotifier.class);
test(db -> db.addUpdateNotifier(notifier));
}
@Test
public void removeUpdateNotifier() {
UpdateNotifier<?> notifier = mock(UpdateNotifier.class);
test(db -> db.removeUpdateNotifier(notifier));
}
}
}
|
mankeyl/elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetScriptContextResponse.java | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.admin.cluster.storedscripts;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.StatusToXContentObject;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.script.ScriptContextInfo;
import org.elasticsearch.xcontent.ConstructingObjectParser;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class GetScriptContextResponse extends ActionResponse implements StatusToXContentObject {
private static final ParseField CONTEXTS = new ParseField("contexts");
final Map<String, ScriptContextInfo> contexts;
@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<GetScriptContextResponse, Void> PARSER = new ConstructingObjectParser<>(
"get_script_context",
true,
(a) -> {
Map<String, ScriptContextInfo> contexts = ((List<ScriptContextInfo>) a[0]).stream()
.collect(Collectors.toMap(ScriptContextInfo::getName, c -> c));
return new GetScriptContextResponse(contexts);
}
);
static {
PARSER.declareObjectArray(
ConstructingObjectParser.constructorArg(),
(parser, ctx) -> ScriptContextInfo.PARSER.apply(parser, ctx),
CONTEXTS
);
}
GetScriptContextResponse(StreamInput in) throws IOException {
super(in);
int size = in.readInt();
HashMap<String, ScriptContextInfo> contexts = new HashMap<>(size);
for (int i = 0; i < size; i++) {
ScriptContextInfo info = new ScriptContextInfo(in);
contexts.put(info.name, info);
}
this.contexts = Collections.unmodifiableMap(contexts);
}
// TransportAction constructor
GetScriptContextResponse(Set<ScriptContextInfo> contexts) {
this.contexts = Map.copyOf(contexts.stream().collect(Collectors.toMap(ScriptContextInfo::getName, Function.identity())));
}
// Parser constructor
private GetScriptContextResponse(Map<String, ScriptContextInfo> contexts) {
this.contexts = Map.copyOf(contexts);
}
private List<ScriptContextInfo> byName() {
return contexts.values().stream().sorted(Comparator.comparing(ScriptContextInfo::getName)).collect(Collectors.toList());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeInt(contexts.size());
for (ScriptContextInfo context : contexts.values()) {
context.writeTo(out);
}
}
@Override
public RestStatus status() {
return RestStatus.OK;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject().startArray(CONTEXTS.getPreferredName());
for (ScriptContextInfo context : byName()) {
context.toXContent(builder, params);
}
builder.endArray().endObject(); // CONTEXTS
return builder;
}
public static GetScriptContextResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.apply(parser, null);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GetScriptContextResponse that = (GetScriptContextResponse) o;
return contexts.equals(that.contexts);
}
@Override
public int hashCode() {
return Objects.hash(contexts);
}
}
|
ankurverma85/stencil | src/templates/3.template.common.struct.h | // Anything here is not part of the generated code
struct ModelDefinition
{};
const int EnumKeyCount = 0;
const int EnumCount = 0;
const int zzFieldType_Idzz = 0;
const int zzStruct_Idzz = 0;
const int zzUnion_Idzz = 0;
const HandlerData zzFieldType_NativeHandlerDatazz{nullptr, nullptr, nullptr};
int resolve_enum(const char** names, int count, const char* name)
{
return 0;
}
struct zzFieldType_NativeTypezz
{
int a;
};
struct zzChildFieldType_NativeTypezz
{
int a;
};
struct zzReturnType_NativeTypezz
{};
typedef void* Target;
class NativeHandler
{
public:
static const ITypeHandler* Make(const ModelDefinition* def, const TypeHandlerFactoryData handlerData) { return (ITypeHandler*)nullptr; }
};
typedef NativeHandler zzFieldType_NativeHandlerzz;
typedef NativeHandler zzReturnType_NativeHandlerzz;
namespace zzProgram_Namezz
{
namespace zzDataSource_Namezz
{
void* GetExtensionData()
{
return nullptr;
}
} // namespace zzDataSource_Namezz
} // namespace zzProgram_Namezz
//<Template file="zzFileNamezz.h">
#pragma once
#include <stencil/stencil.h>
// SECTION START: DECLARATIONS
#if true
//<Struct>
namespace zzProgram_Namezz::zzStruct_Namezz
{
struct Data;
}
template <> struct ReflectionBase::TypeTraits<zzProgram_Namezz::zzStruct_Namezz::Data&>;
//</Struct>
#endif
// SECTION END: DECLARATIONS
// SECTION START: Definitions
#if true
namespace zzProgram_Namezz
{
//<Struct>
namespace zzStruct_Namezz
{
struct Data;
}
//</Struct>
//<Typedef>
typedef zzChildFieldType_NativeTypezz zzNamezz;
//</Typedef>
//<Struct>
namespace zzStruct_Namezz
{
struct Data :
//<RelationshipTag>
public zzTagType_NativeTypezz,
//</RelationshipTag>
public ReflectionBase::ObjMarker
{
/*template <typename...TArgs> Data(TArgs&& ... args)
{
ReflectionBase::Construct<Data>(this, std::forward<TArgs>(args)...);
}*/
enum class FieldIndex
{
Invalid,
//<Field Join=','>
zzField_Namezz
//</Field>
};
static constexpr size_t FieldCount()
{
return 0u
//<Field >
+ 1u
//</Field>
;
}
static constexpr std::string_view FieldAttributeValue(FieldIndex index, const std::string_view& key)
{
switch (index)
{
//<Field>
case FieldIndex::zzField_Namezz:
//<Attribute>
if (key == "zzAttribute_Keyzz") return "zzAttribute_Valuezz";
//</Attribute>
return ::ReflectionServices::EmptyAttributeValue(key);
//</Field>
case FieldIndex::Invalid: break;
default: break;
}
return ::ReflectionServices::EmptyAttributeValue(key);
}
//<Field>
private:
zzFieldType_NativeTypezz _zzNamezz = zzInitialValuezz;
public:
zzFieldType_NativeTypezz& zzNamezz() { return _zzNamezz; }
const zzFieldType_NativeTypezz& zzNamezz() const { return _zzNamezz; }
void zzNamezz(zzFieldType_NativeTypezz&& val) { _zzNamezz = std::move(val); }
zzFieldType_NativeTypezz& get_zzNamezz() { return _zzNamezz; }
bool isset_zzNamezz() const { return Stencil::OptionalPropsT<Data>::IsSet(*this, FieldIndex::zzField_Namezz); }
void set_zzNamezz(zzFieldType_NativeTypezz&& val)
{
Stencil::OptionalPropsT<Data>::OnChangeRequested(*this, FieldIndex::zzField_Namezz, _zzNamezz, val);
_zzNamezz = std::move(val);
}
//</Field>
};
} // namespace zzStruct_Namezz
//</Struct>
//<Union>
namespace zzUnion_Namezz
{
struct Union;
}
//</Union>
//<Typedef>
typedef zzChildFieldType_NativeTypezz zzNamezz;
//</Typedef>
//<Union>
namespace zzUnion_Namezz
{
enum class UnionType
{
Invalid,
//<Field Join=','>
zzField_Namezz
//</Field>
};
struct Data : public ReflectionBase::ObjMarker
{
UnionType _type;
public:
UnionType Type() const { return _type; }
UnionType& get_Type() { return _type; }
void set_Type(UnionType&& val) { _type = std::move(val); }
Data() : _type(UnionType::Invalid) {}
public:
enum class FieldIndex
{
Invalid,
//<Field Join=','>
zzField_Namezz
//</Field>
};
static constexpr std::string_view FieldAttributeValue(FieldIndex index, const std::string_view& key)
{
switch (index)
{
//<Field>
case FieldIndex::zzField_Namezz:
{
//<Attribute>
if (key == "zzAttribute_Keyzz") return "zzAttribute_Valuezz";
//</Attribute>
return ::ReflectionServices::EmptyAttributeValue(key);
}
//</Field>
case FieldIndex::Invalid: break;
default: break;
}
return ::ReflectionServices::EmptyAttributeValue(key);
}
//<FieldAttribute>
template <FieldIndex TFieldType> static constexpr std::string_view FieldAttributeValue_zzFieldAttribute_Namezz();
//</FieldAttribute>
//<Field>
private:
zzFieldType_NativeTypezz _zzNamezz;
public:
zzFieldType_NativeTypezz& zzNamezz() { return _zzNamezz; }
const zzFieldType_NativeTypezz& zzNamezz() const { return _zzNamezz; }
void zzNamezz(const zzFieldType_NativeTypezz& val) { _zzNamezz = val; }
void zzNamezz(zzFieldType_NativeTypezz&& val) { _zzNamezz = std::move(val); }
zzFieldType_NativeTypezz& get_zzNamezz() { return _zzNamezz; }
void set_zzNamezz(zzFieldType_NativeTypezz&& val) { _zzNamezz = std::move(val); }
//</Field>
};
} // namespace zzUnion_Namezz
//</Union>
//<Interface>
struct zzInterface_Namezz : public ReflectionBase::Interface<zzInterface_Namezz>
{
public:
zzInterface_Namezz() = default;
virtual ~zzInterface_Namezz() = default;
DELETE_COPY_AND_MOVE(zzInterface_Namezz);
//<Function>
virtual zzReturnType_NativeTypezz zzFunction_Namezz(
//<Args_Field Join=','>
zzFieldType_NativeTypezz const& zzNamezz
//</Args_Field>
)
= 0;
//</Function>
// static std::unique_ptr<zzInterface_Namezz> Create();
};
struct zzInterface_NamezzFactory : public ReflectionBase::InterfaceFactory<zzInterface_Namezz>
{
public:
virtual std::unique_ptr<zzInterface_Namezz> Activate() = 0;
virtual ~zzInterface_NamezzFactory() = default;
};
//<Function>
struct zzInterface_Namezz_zzFunction_Namezz_Args
{
zzInterface_Namezz* instance = nullptr;
//<Args_Field>
zzFieldType_NativeTypezz arg_zzNamezz{};
zzFieldType_NativeTypezz& get_arg_zzNamezz() { return arg_zzNamezz; }
zzFieldType_NativeTypezz const& get_carg_zzNamezz() const { return arg_zzNamezz; }
void set_arg_zzNamezz(zzFieldType_NativeTypezz&& value) { arg_zzNamezz = std::move(value); }
//</Args_Field>
};
//</Function>
//</Interface>
} // namespace zzProgram_Namezz
#endif
// SECTION END: Definitions
// SECTION START: Template specializations
#if true
// SECTION:
//<Interface>
//<Function>
template <> struct ReflectionBase::TypeTraits<zzProgram_Namezz::zzInterface_Namezz_zzFunction_Namezz_Args&>
{
//<Args_Field>
struct Traits_arg_zzNamezz
{
using TOwner = zzProgram_Namezz::zzInterface_Namezz_zzFunction_Namezz_Args;
using TFieldType = zzFieldType_NativeTypezz;
static constexpr std::string_view Name() { return "zzNamezz"; }
static const ::ReflectionBase::Flags Flags() { return {}; }
static constexpr auto TAttributeValue(const std::string_view& key) { return ::ReflectionServices::EmptyAttributeValue(key); }
static constexpr auto TPropertyGetter() { return &TOwner::get_arg_zzNamezz; }
static constexpr auto TPropertySetter() { return &TOwner::set_arg_zzNamezz; }
};
//</Args_Field>
static constexpr ::ReflectionBase::DataType Type() { return ::ReflectionBase::DataType::Object; }
static constexpr std::string_view Name() { return "zzFunction_Namezz"; }
static constexpr auto TAttributeValue(const std::string_view& key) { return ::ReflectionServices::EmptyAttributeValue(key); }
using ThisType = zzProgram_Namezz::zzInterface_Namezz_zzFunction_Namezz_Args;
static bool AreEqual([[maybe_unused]] ThisType const& obj1, [[maybe_unused]] ThisType const& obj2)
{
return true
//<Args_Field>
&& ReflectionBase::AreEqual(obj1.get_carg_zzNamezz(), obj2.get_carg_zzNamezz())
//</Args_Field>
;
}
using Handler = ::ReflectionServices::ReflectedStructHandler<zzProgram_Namezz::zzInterface_Namezz_zzFunction_Namezz_Args
//<Args_Field>
,
Traits_arg_zzNamezz
//</Args_Field>
>;
};
//</Function>
template <> struct ReflectionBase::InterfaceTraits<zzProgram_Namezz::zzInterface_Namezz>
{
//<Function>
struct ApiTraits_zzNamezz
{
using TOwner = zzProgram_Namezz::zzInterface_Namezz;
static const ::ReflectionBase::Flags Flags() { return {}; }
static constexpr std::string_view Name() { return "zzNamezz"; }
static constexpr bool Static = false;
};
//</Function>
using Apis = ::ReflectionBase::InterfaceApiPack<
//<Function Join=','>
ApiTraits_zzNamezz
//</Function>
>;
};
//<Function>
template <>
struct ReflectionBase::InterfaceApiTraits<ReflectionBase::InterfaceTraits<zzProgram_Namezz::zzInterface_Namezz>::ApiTraits_zzNamezz>
{
using ArgsStruct = zzProgram_Namezz::zzInterface_Namezz_zzFunction_Namezz_Args;
static constexpr bool IsStatic() { return false; }
static constexpr std::string_view Name() { return "zzNamezz"; }
static auto Invoke(ArgsStruct& args)
{
return args.instance->zzNamezz(
//<Args_Field Join=','>
args.get_arg_zzNamezz()
//</Args_Field>
);
}
};
//</Function>
#if ((defined STENCIL_USING_WEBSERVICE) and (STENCIL_USING_WEBSERVICE > 0))
template <> struct WebServiceHandlerTraits<zzProgram_Namezz::zzInterface_Namezz>
{
static constexpr const std::string_view Url() { return std::string_view("zzInterface_Namezz"); }
};
#endif
//</Interface>
//<Struct>
template <> struct ReflectionBase::TypeTraits<zzProgram_Namezz::zzStruct_Namezz::Data&>
{
//<Field>
struct Traits_zzNamezz
{
using TOwner = zzStruct_Program_Namezz::zzStruct_Namezz::Data;
using TFieldType = zzFieldType_NativeTypezz;
static constexpr std::string_view Name() { return "zzNamezz"; }
static constexpr auto TPropertyGetter() { return &TOwner::get_zzNamezz; }
static constexpr auto TPropertySetter() { return &TOwner::set_zzNamezz; }
static constexpr auto TAttributeValue(const std::string_view& key)
{
return TOwner::FieldAttributeValue(TOwner::FieldIndex::zzField_Namezz, key);
}
static const ::ReflectionBase::Flags Flags()
{
return ::ReflectionBase::Flags{//<If HasDefaultValue='true'>
::ReflectionBase::Flag::HasDefaultValue,
//</If>
//<If IsOptional='true'>
::ReflectionBase::Flag::Optional,
//</If>
::ReflectionBase::Flag::Max};
}
};
//</Field>
static constexpr ::ReflectionBase::DataType Type() { return ::ReflectionBase::DataType::Object; }
static constexpr std::string_view Name() { return "zzStruct_Namezz"; }
static constexpr std::string_view AttributeValue(const std::string_view& key)
{
//<Attribute>
if (key == "zzAttribute_Keyzz") return "zzAttribute_Valuezz";
//</Attribute>
return ::ReflectionServices::EmptyAttributeValue(key);
}
using ThisType = zzProgram_Namezz::zzStruct_Namezz::Data;
static bool AreEqual([[maybe_unused]] ThisType const& obj1, [[maybe_unused]] ThisType const& obj2)
{
return true
//<Field>
&& ReflectionBase::AreEqual(obj1.zzNamezz(), obj2.zzNamezz())
//</Field>
;
}
using Handler = ::ReflectionServices::ReflectedStructHandler<zzProgram_Namezz::zzStruct_Namezz::Data,
//<Field Join=','>
Traits_zzNamezz
//</Field>
>;
};
template <>
struct Stencil::Transaction<zzProgram_Namezz::zzStruct_Namezz::Data> : Stencil::TransactionT<zzProgram_Namezz::zzStruct_Namezz::Data>
{
using TData = zzProgram_Namezz::zzStruct_Namezz::Data;
//<Field>
Transaction<zzFieldType_NativeTypezz> _subtracker_zzNamezz;
//</Field>
DELETE_COPY_AND_MOVE(Transaction);
Transaction(TData& ptr) :
Stencil::TransactionT<zzProgram_Namezz::zzStruct_Namezz::Data>(ptr)
//<Field>
,
_subtracker_zzNamezz(Obj().zzNamezz())
//</Field>
{}
//<Field>
auto& zzNamezz()
{
MarkFieldEdited_(TData::FieldIndex::zzField_Namezz);
return _subtracker_zzNamezz;
}
//</Field>
//<Field>
void set_zzNamezz(zzFieldType_NativeTypezz&& val)
{
MarkFieldAssigned_(TData::FieldIndex::zzNamezz, Obj().zzNamezz(), val);
Obj().set_zzNamezz(std::move(val));
}
//<FieldType_Mutator>
zzReturnTypezz zzNamezz_zzField_Namezz(zzArgzz&& args)
{
MarkFieldEdited_(TData::FieldIndex::zzField_Namezz);
return Stencil::Mutators<std::remove_reference_t<decltype(zzField_Namezz())>>::zzNamezz(zzField_Namezz(), std::move(args));
}
//</FieldType_Mutator>
//</Field>
template <typename TLambda> auto Visit(typename TData::FieldIndex index, TLambda&& lambda)
{
switch (index)
{
//<Field>
case TData::FieldIndex::zzNamezz: return lambda("zzNamezz", zzNamezz()); return;
//</Field>
case TData::FieldIndex::Invalid: throw std::invalid_argument("Asked to visit invalid field");
}
}
template <typename TLambda> auto Visit(std::string_view const& fieldName, TLambda&& lambda)
{
//<Field>
if (fieldName == "zzNamezz") { return lambda(TData::FieldIndex::zzNamezz, zzNamezz()); }
//</Field>
throw std::invalid_argument("Asked to visit invalid field");
}
template <typename TLambda> void VisitAll(TLambda&& lambda)
{
//<Field>
lambda("zzNamezz", TData::FieldIndex::zzNamezz, zzNamezz(), Obj().zzNamezz());
//</Field>
}
void Flush()
{
//<Field>
zzNamezz().Flush();
if (IsFieldEdited(TData::FieldIndex::zzNamezz))
{
if (!zzNamezz().IsChanged()) _edittracker.reset(static_cast<uint8_t>(TData::FieldIndex::zzNamezz));
}
//</Field>
Stencil::TransactionT<zzProgram_Namezz::zzStruct_Namezz::Data>::Flush_();
}
};
template <>
struct Stencil::Visitor<zzProgram_Namezz::zzStruct_Namezz::Data, void> : Stencil::VisitorT<zzProgram_Namezz::zzStruct_Namezz::Data>
{
using TData = zzProgram_Namezz::zzStruct_Namezz::Data;
Visitor(TData& obj) : VisitorT<TData>(obj), _ref(obj) {}
template <typename TLambda> void Visit(typename TData::FieldIndex index, TLambda&& lambda)
{
switch (index)
{
//<Field>
case TData::FieldIndex::zzNamezz: lambda("zzNamezz", _ref.get().zzNamezz()); return;
//</Field>
case TData::FieldIndex::Invalid: throw std::invalid_argument("Asked to visit invalid field");
}
}
template <typename TLambda> void Visit(typename TData::FieldIndex index, TLambda&& lambda) const
{
switch (index)
{
//<Field>
case TData::FieldIndex::zzNamezz: lambda("zzNamezz", _ref.get().zzNamezz()); return;
//</Field>
case TData::FieldIndex::Invalid: throw std::invalid_argument("Asked to visit invalid field");
}
}
template <typename TLambda> void VisitAll(TLambda&& lambda) const
{
//<Field>
lambda("zzNamezz", _ref.get().zzNamezz());
//</Field>
}
std::reference_wrapper<TData> _ref;
};
template <>
struct Stencil::Visitor<const zzProgram_Namezz::zzStruct_Namezz::Data, void>
: Stencil::VisitorT<const zzProgram_Namezz::zzStruct_Namezz::Data>
{
using TData = zzProgram_Namezz::zzStruct_Namezz::Data const;
Visitor(TData& obj) : VisitorT<TData>(obj), _ref(obj) {}
template <typename TLambda> void Visit(typename TData::FieldIndex index, TLambda&& lambda) const
{
switch (index)
{
//<Field>
case TData::FieldIndex::zzNamezz: lambda("zzNamezz", _ref.get().zzNamezz()); return;
//</Field>
case TData::FieldIndex::Invalid: throw std::invalid_argument("Asked to visit invalid field");
}
}
template <typename TLambda> void VisitAll(TLambda&& lambda) const
{
//<Field>
lambda("zzNamezz", _ref.get().zzNamezz());
//</Field>
}
std::reference_wrapper<TData> _ref;
};
//</Struct>
//<Union>
template <> struct ReflectionServices::EnumTraits<zzUnion_Program_Namezz::zzUnion_Namezz::UnionType>
{
static constexpr const char* EnumStrings[] = {"Invalid",
//<Field>
"zzField_Namezz",
//</Field>
nullptr};
using ValueType = uint32_t;
};
template <> struct ValueTraits<zzUnion_Program_Namezz::zzUnion_Namezz::UnionType>
{
static constexpr auto ValueType() { return Value::Type::Unsigned; }
[[noreturn]] static void Get(Value& /*obj*/) { throw std::logic_error("Not Implemented"); }
[[noreturn]] static void Get(const Value& /*obj*/) { throw std::logic_error("Not Implemented"); }
[[noreturn]] static void Check() { throw std::logic_error("Not Implemented"); }
};
template <> struct ReflectionBase::TypeTraits<zzUnion_Program_Namezz::zzUnion_Namezz::UnionType&>
{
static constexpr ::ReflectionBase::DataType Type() { return ::ReflectionBase::DataType::Value; }
static constexpr std::string_view Name() { return "zzUnion_Namezz"; }
using Handler = ::ReflectionServices::EnumHandler<zzUnion_Program_Namezz::zzUnion_Namezz::UnionType>;
};
template <> struct ReflectionBase::TypeTraits<zzProgram_Namezz::zzUnion_Namezz::Data&>
{
//<Field>
struct Traits_zzNamezz
{
using TOwner = zzUnion_Program_Namezz::zzUnion_Namezz::Data;
using TFieldType = zzFieldType_NativeTypezz;
static constexpr std::string_view Name() { return "zzNamezz"; }
static constexpr auto TPropertyGetter() { return &TOwner::get_zzNamezz; }
static constexpr auto TPropertySetter() { return &TOwner::set_zzNamezz; }
static constexpr auto TAttributeValue(const std::string_view& key)
{
return TOwner::FieldAttributeValue(TOwner::FieldIndex::zzField_Namezz, key);
}
static const ::ReflectionBase::Flags Flags()
{
return ::ReflectionBase::Flags{//<If HasDefaultValue='true'>
::ReflectionBase::Flag::HasDefaultValue,
//</If>
//<If IsOptional='true'>
::ReflectionBase::Flag::Optional,
//</If>
::ReflectionBase::Flag::Max};
}
};
//</Field>
static constexpr ::ReflectionBase::DataType Type() { return ::ReflectionBase::DataType::Object; }
static constexpr std::string_view Name() { return "zzUnion_Namezz"; }
static constexpr std::string_view AttributeValue(const std::string_view& key)
{
//<Attribute>
if (key == "zzAttribute_Keyzz") return "zzAttribute_Valuezz";
//</Attribute>
return ::ReflectionServices::EmptyAttributeValue(key);
}
using ThisType = zzProgram_Namezz::zzUnion_Namezz::Data;
static bool AreEqual([[maybe_unused]] ThisType const& obj1, [[maybe_unused]] ThisType const& obj2)
{
return true
//<Field>
&& ReflectionBase::AreEqual(obj1.zzNamezz(), obj2.zzNamezz())
//</Field>
;
}
using Handler = ::ReflectionServices::ReflectedUnionHandler<zzProgram_Namezz::zzUnion_Namezz::Data,
zzUnion_Program_Namezz::zzUnion_Namezz::UnionType,
//<Field Join=','>
Traits_zzNamezz
//</Field>
>;
};
template <>
struct Stencil::Visitor<zzProgram_Namezz::zzUnion_Namezz::Data, void> : Stencil::VisitorT<zzProgram_Namezz::zzUnion_Namezz::Data>
{
using TData = zzProgram_Namezz::zzUnion_Namezz::Data;
Visitor(TData& obj) : VisitorT<TData>(obj), _ref(obj) {}
template <typename TLambda> void Visit(typename TData::FieldIndex index, TLambda&& lambda)
{
switch (index)
{
//<Field>
case TData::FieldIndex::zzNamezz: lambda("zzNamezz", _ref.get().zzNamezz()); return;
//</Field>
case TData::FieldIndex::Invalid: throw std::invalid_argument("Asked to visit invalid field");
}
}
template <typename TLambda> void Visit(typename TData::FieldIndex index, TLambda&& lambda) const
{
switch (index)
{
//<Field>
case TData::FieldIndex::zzNamezz: lambda("zzNamezz", _ref.get().zzNamezz()); return;
//</Field>
case TData::FieldIndex::Invalid: throw std::invalid_argument("Asked to visit invalid field");
}
}
template <typename TLambda> void VisitAll(TLambda&& lambda) const
{
//<Field>
lambda("zzNamezz", _ref.get().zzNamezz());
//</Field>
}
std::reference_wrapper<TData> _ref;
};
template <>
struct Stencil::Visitor<const zzProgram_Namezz::zzUnion_Namezz::Data, void>
: Stencil::VisitorT<const zzProgram_Namezz::zzUnion_Namezz::Data>
{
using TData = zzProgram_Namezz::zzUnion_Namezz::Data const;
Visitor(TData& obj) : VisitorT<TData>(obj), _ref(obj) {}
template <typename TLambda> void Visit(typename TData::FieldIndex index, TLambda&& lambda) const
{
switch (index)
{
//<Field>
case TData::FieldIndex::zzNamezz: lambda("zzNamezz", _ref.get().zzNamezz()); return;
//</Field>
case TData::FieldIndex::Invalid: throw std::invalid_argument("Asked to visit invalid field");
}
}
template <typename TLambda> void VisitAll(TLambda&& lambda) const
{
//<Field>
lambda("zzNamezz", _ref.get().zzNamezz());
//</Field>
}
std::reference_wrapper<TData> _ref;
};
//</Union>
#endif
// SECTION END: Template specializations
// SECTION START: Inline Function Definitions
#if true
#endif
// SECTION END: Inline Function Definitions
//</Template>
|
liangxiaoqiao/LeetCodeDay | src/main/java/com/liangxiaoqiao/leetcode/day/medium/ReverseSubstringsBetweenEachPairOfParentheses.java | <gh_stars>0
package com.liangxiaoqiao.leetcode.day.medium;
/*
* English
* id: 1190
* title: Reverse Substrings Between Each Pair of Parentheses
* href: https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses
* desc: You are given a string s that consists of lower case English letters and brackets.
* Reverse the strings in each pair of matching parentheses, starting from the innermost one.
* Your result should not contain any brackets.
* Example 1:
* Input: s = "(abcd)"
* Output: "dcba"
* Example 2:
* Input: s = "(u(love)i)"
* Output: "iloveu"
* Explanation: The substring "love" is reversed first, then the whole string is reversed.
* Example 3:
* Input: s = "(ed(et(oc))el)"
* Output: "leetcode"
* Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.
* Example 4:
* Input: s = "a(bcdefghijkl(mno)p)q"
* Output: "apmnolkjihgfedcbq"
* Constraints:
* 0 <= s.length <= 2000
* s only contains lower case English characters and parentheses.
* It's guaranteed that all parentheses are balanced.
* <p>
* 中文
* 序号: 1190
* 标题: 反转每对括号间的子串
* 链接: https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses
* 描述: 给出一个字符串 s(仅含有小写英文字母和括号)。
* 请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。
* 注意,您的结果中 不应 包含任何括号。
* 示例 1:
* 输入:s = "(abcd)"
* 输出:"dcba"
* 示例 2:
* 输入:s = "(u(love)i)"
* 输出:"iloveu"
* 示例 3:
* 输入:s = "(ed(et(oc))el)"
* 输出:"leetcode"
* 示例 4:
* 输入:s = "a(bcdefghijkl(mno)p)q"
* 输出:"apmnolkjihgfedcbq"
* 提示:
* 0 <= s.length <= 2000
* s 中只有小写英文字母和括号
* 我们确保所有括号都是成对出现的
* <p>
* acceptance: 58.9%
* difficulty: Medium
* private: False
*/
//TODO init
public class ReverseSubstringsBetweenEachPairOfParentheses {
public String reverseParentheses(String s) {
return null;
}
} |
Liangsh7/micro_mall | comment-service/comment-provider/src/main/java/com/mall/comment/dal/entitys/CommentReply.java | <reponame>Liangsh7/micro_mall
package com.mall.comment.dal.entitys;
import lombok.Data;
import java.util.Date;
import javax.persistence.*;
@Table(name = "tb_comment_reply")
@Data
public class CommentReply {
/**
* 评价回复id
*/
@Id
private String id;
/**
* 商品评价id
*/
@Column(name = "comment_id")
private String commentId;
/**
* 评价回复自关联id(针对回复的回复)
*/
@Column(name = "parent_id")
private String parentId;
/**
* 回复意见
*/
private String content;
/**
* 回复时间
*/
@Column(name = "reply_time")
private Date replyTime;
/**
* 回复人昵称
*/
@Column(name = "reply_nick")
private String replyNick;
/**
* 回复人用户id
*/
@Column(name = "user_id")
private Long userId;
/**
* 是否删除
*/
@Column(name = "is_deleted")
private Boolean isDeleted;
/**
* 删除时间
*/
@Column(name = "deletion_time")
private Date deletionTime;
/**
* 删除用户id
*/
@Column(name = "deletion_user_id")
private Long deletionUserId;
/**
* 获取评价回复id
*
* @return id - 评价回复id
*/
public String getId() {
return id;
}
/**
* 设置评价回复id
*
* @param id 评价回复id
*/
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
/**
* 获取商品评价id
*
* @return comment_id - 商品评价id
*/
public String getCommentId() {
return commentId;
}
/**
* 设置商品评价id
*
* @param commentId 商品评价id
*/
public void setCommentId(String commentId) {
this.commentId = commentId == null ? null : commentId.trim();
}
/**
* 获取评价回复自关联id(针对回复的回复)
*
* @return parent_id - 评价回复自关联id(针对回复的回复)
*/
public String getParentId() {
return parentId;
}
/**
* 设置评价回复自关联id(针对回复的回复)
*
* @param parentId 评价回复自关联id(针对回复的回复)
*/
public void setParentId(String parentId) {
this.parentId = parentId == null ? null : parentId.trim();
}
/**
* 获取回复意见
*
* @return content - 回复意见
*/
public String getContent() {
return content;
}
/**
* 设置回复意见
*
* @param content 回复意见
*/
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
/**
* 获取回复时间
*
* @return reply_time - 回复时间
*/
public Date getReplyTime() {
return replyTime;
}
/**
* 设置回复时间
*
* @param replyTime 回复时间
*/
public void setReplyTime(Date replyTime) {
this.replyTime = replyTime;
}
/**
* 获取回复人昵称
*
* @return reply_nick - 回复人昵称
*/
public String getReplyNick() {
return replyNick;
}
/**
* 设置回复人昵称
*
* @param replyNick 回复人昵称
*/
public void setReplyNick(String replyNick) {
this.replyNick = replyNick == null ? null : replyNick.trim();
}
/**
* 获取回复人用户id
*
* @return user_id - 回复人用户id
*/
public Long getUserId() {
return userId;
}
/**
* 设置回复人用户id
*
* @param userId 回复人用户id
*/
public void setUserId(Long userId) {
this.userId = userId;
}
/**
* 获取是否删除
*
* @return is_deleted - 是否删除
*/
public Boolean getIsDeleted() {
return isDeleted;
}
/**
* 设置是否删除
*
* @param isDeleted 是否删除
*/
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
/**
* 获取删除时间
*
* @return deletion_time - 删除时间
*/
public Date getDeletionTime() {
return deletionTime;
}
/**
* 设置删除时间
*
* @param deletionTime 删除时间
*/
public void setDeletionTime(Date deletionTime) {
this.deletionTime = deletionTime;
}
/**
* 获取删除用户id
*
* @return deletion_user_id - 删除用户id
*/
public Long getDeletionUserId() {
return deletionUserId;
}
/**
* 设置删除用户id
*
* @param deletionUserId 删除用户id
*/
public void setDeletionUserId(Long deletionUserId) {
this.deletionUserId = deletionUserId;
}
} |
CamW/servicetalk | servicetalk-http-api/src/main/java/io/servicetalk/http/api/HttpCookiePair.java | /*
* Copyright © 2019 Apple Inc. and the ServiceTalk project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.servicetalk.http.api;
/**
* Interface defining a HTTP <a href="https://tools.ietf.org/html/rfc6265#section-4.2.1">cookie-pair</a>.
*/
public interface HttpCookiePair {
/**
* Returns the name of this {@link HttpCookiePair}.
*
* @return The name of this {@link HttpCookiePair}
*/
CharSequence name();
/**
* Returns the value of this {@link HttpCookiePair}.
*
* @return The value of this {@link HttpCookiePair}
*/
CharSequence value();
/**
* Returns {@code true} if the value should be wrapped in DQUOTE as described in
* <a href="https://tools.ietf.org/html/rfc6265#section-4.1.1">cookie-value</a>.
*
* @return {@code true} if the value should be wrapped in DQUOTE as described in
* <a href="https://tools.ietf.org/html/rfc6265#section-4.1.1">cookie-value</a>.
*/
boolean isWrapped();
/**
* Get the encoded value of this {@link HttpCookiePair}.
*
* @return the encoded value of this {@link HttpCookiePair}.
*/
CharSequence encoded();
}
|
dunham/soaride | com.soartech.soar.ide.ui/src/com/soartech/soar/ide/ui/editors/text/SyntaxColorManager.java | /*
*Copyright (c) 2009, Soar Technology, Inc.
*All rights reserved.
*
*Redistribution and use in source and binary forms, with or without modification, *are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Soar Technology, Inc. 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 HOLDER 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.soartech.soar.ide.ui.editors.text;
import java.util.HashMap;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.texteditor.AbstractTextEditor;
/**
* <code>SyntaxColorManager</code> manages the colors that will be used
* during syntax highlighting and ensures that colors get properly disposed.
*
* @author ann<EMAIL>
* @version $Revision: 578 $ $Date: 2009-06-22 13:05:30 -0400 (Mon, 22 Jun 2009) $
*/
public class SyntaxColorManager implements RGBDefinitions {
private static HashMap<RGB,Color> colors = new HashMap<RGB,Color>();
static {
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), BLOCK_COMMENT_RGB, BLOCK_COMMENT_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), INLINE_COMMENT_RGB, INLINE_COMMENT_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), COMMAND_RGB, COMMAND_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), VARIABLE_RGB, VARIABLE_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), FUNCTION_RGB, FUNCTION_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), ARROW_FG_RGB, ARROW_FG_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), ARROW_BG_RGB, ARROW_BG_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), TCL_FG_RGB, TCL_FG_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), TCL_BG_RGB, TCL_BG_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), STRING_RGB, STRING_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), FLAG_RGB, FLAG_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), DISJUNCT_RGB, DISJUNCT_RGB_VALUE );
PreferenceConverter.setDefault( EditorsUI.getPreferenceStore(), TCL_VAR_RGB, TCL_VAR_RGB_VALUE );
}
/**
* Reset all the colors back to their defaults from the preferences.
*/
public static void reset() {
EditorsUI.getPreferenceStore().setToDefault( BLOCK_COMMENT_RGB );
EditorsUI.getPreferenceStore().setToDefault( INLINE_COMMENT_RGB );
EditorsUI.getPreferenceStore().setToDefault( COMMAND_RGB );
EditorsUI.getPreferenceStore().setToDefault( VARIABLE_RGB );
EditorsUI.getPreferenceStore().setToDefault( FUNCTION_RGB );
EditorsUI.getPreferenceStore().setToDefault( ARROW_FG_RGB );
EditorsUI.getPreferenceStore().setToDefault( ARROW_BG_RGB );
EditorsUI.getPreferenceStore().setToDefault( TCL_FG_RGB );
EditorsUI.getPreferenceStore().setToDefault( STRING_RGB );
EditorsUI.getPreferenceStore().setToDefault( STRING_RGB );
EditorsUI.getPreferenceStore().setToDefault( FLAG_RGB );
EditorsUI.getPreferenceStore().setToDefault( DISJUNCT_RGB );
EditorsUI.getPreferenceStore().setToDefault( TCL_VAR_RGB );
}
/**
* Dispose of color resources.
*/
public static void dispose() {
for ( RGB rgb: colors.keySet() ) {
Color color = colors.get( rgb );
color.dispose();
}
colors.clear();
}
/**
* @param key The <code>RGB</code> preferences key
* @return The associated <code>Color</code> for the given <code>RGB</code>
*/
public static Color getColor( final String key ) {
RGB rgb = PreferenceConverter.getColor( EditorsUI.getPreferenceStore(), key );
Color color = colors.get( rgb );
if ( color == null ) {
color = new Color( Display.getCurrent(), rgb );
colors.put( rgb, color );
}
return color;
}
public static Color getForegroundColor() {
return getColor( AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND );
}
public static Color getBackgroundColor() {
return getColor( AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND );
}
public static Color getBlockCommentColor() {
return getColor( BLOCK_COMMENT_RGB );
}
public static Color getInlineCommentColor() {
return getColor( INLINE_COMMENT_RGB );
}
public static Color getCommandColor() {
return getColor( COMMAND_RGB );
}
public static Color getVariableColor() {
return getColor( VARIABLE_RGB );
}
public static Color getFunctionColor() {
return getColor( FUNCTION_RGB );
}
public static Color getArrowFgColor() {
return getColor( ARROW_FG_RGB );
}
public static Color getArrowBgColor() {
return getColor( ARROW_BG_RGB );
}
public static Color getTclFgColor() {
return getColor( TCL_FG_RGB );
}
public static Color getTclBgColor() {
return getColor( TCL_BG_RGB );
}
public static Color getStringColor() {
return getColor( STRING_RGB );
}
public static Color getFlagColor() {
return getColor( FLAG_RGB );
}
public static Color getDisjunctColor() {
return getColor( DISJUNCT_RGB );
}
public static Color getTclVarColor() {
return getColor( TCL_VAR_RGB );
}
}
|
liningwang/mallplus-cloudok | mall-business/marking-center/src/main/java/com/mallplus/marking/service/impl/SmsDrawServiceImpl.java | <reponame>liningwang/mallplus-cloudok<filename>mall-business/marking-center/src/main/java/com/mallplus/marking/service/impl/SmsDrawServiceImpl.java<gh_stars>10-100
package com.mallplus.marking.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mallplus.common.entity.sms.SmsDraw;
import com.mallplus.marking.mapper.SmsDrawMapper;
import com.mallplus.marking.service.ISmsDrawService;
import org.springframework.stereotype.Service;
/**
* <p>
* 一分钱抽奖 服务实现类
* </p>
*
* @author zscat
* @since 2019-10-17
*/
@Service
public class SmsDrawServiceImpl extends ServiceImpl<SmsDrawMapper, SmsDraw> implements ISmsDrawService {
}
|
nsbasic-archive/NS-Basic-for-WinCE | src/Controls/NSBWin32/src/RAS.h | <filename>src/Controls/NSBWin32/src/RAS.h<gh_stars>1-10
// RAS.h : Declaration of the CRAS
#ifndef __RAS_H_
#define __RAS_H_
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CRAS
class ATL_NO_VTABLE CRAS :
public CComObjectRootEx<CComMultiThreadModel>,
public CComCoClass<CRAS, &CLSID_RAS>,
public ISupportErrorInfo,
public IConnectionPointContainerImpl<CRAS>,
public IProvideClassInfo2Impl<&CLSID_RAS, &DIID__IRASEvents, &LIBID_DESKLib>,
public IDispatchImpl<IRAS, &IID_IRAS, &LIBID_DESKLib>
{
public:
CRAS() {
}
DECLARE_REGISTRY_RESOURCEID(IDR_RAS)
DECLARE_PROTECT_FINAL_CONSTRUCT()
BEGIN_COM_MAP(CRAS)
COM_INTERFACE_ENTRY(IRAS)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(IConnectionPointContainer)
END_COM_MAP()
BEGIN_CONNECTION_POINT_MAP(CRAS)
END_CONNECTION_POINT_MAP()
CComBSTR m_bstrPhoneBook;
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// IRAS
public:
STDMETHOD(get_Entry)(/*[in]*/ BSTR bstrName, /*[out, retval]*/ IDispatch* *pVal);
STDMETHOD(get_Connections)(/*[out, retval]*/ IUnknown* *pVal);
STDMETHOD(get_Version)(/*[out, retval]*/ long *pVal);
STDMETHOD(get_Entries)(/*[out, retval]*/ IUnknown **pVal);
STDMETHOD(get_PhoneBook)(/*[out, retval]*/ BSTR *pVal);
STDMETHOD(put_PhoneBook)(/*[in]*/ BSTR newVal);
};
#endif //__RAS_H_
|
MSalamatov/mongoose | storage/driver/coop/netty/http/s3/src/main/java/com/emc/mongoose/storage/driver/coop/netty/http/s3/BucketXmlListingHandler.java | package com.emc.mongoose.storage.driver.coop.netty.http.s3;
import com.emc.mongoose.base.item.Item;
import com.emc.mongoose.base.item.ItemFactory;
import com.emc.mongoose.base.logging.LogUtil;
import com.emc.mongoose.base.logging.Loggers;
import org.apache.logging.log4j.Level;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.List;
/**
Created by andrey on 02.12.16.
*/
public final class BucketXmlListingHandler<I extends Item>
extends DefaultHandler {
private int count = 0;
private boolean isInsideItem = false;
private boolean itIsItemId = false;
private boolean itIsItemSize = false;
private boolean itIsTruncateFlag = false;
private boolean isTruncatedFlag = false;
private String oid = null, strSize = null;
private long offset;
private I nextItem;
private final List<I> itemsBuffer;
private final String path;
private final ItemFactory<I> itemFactory;
private final int idRadix;
public BucketXmlListingHandler(
final List<I> itemsBuffer, final String path, final ItemFactory<I> itemFactory,
final int idRadix
) {
this.itemsBuffer = itemsBuffer;
this.path = path == null ? "" : (path.endsWith("/") ? path : path + "/");
this.itemFactory = itemFactory;
this.idRadix = idRadix;
}
@Override
public final void startElement(
final String uri, final String localName, final String qName, Attributes attrs
) throws SAXException {
isInsideItem = isInsideItem || AmzS3Api.QNAME_ITEM.equals(qName);
itIsItemId = isInsideItem && AmzS3Api.QNAME_ITEM_ID.equals(qName);
itIsItemSize = isInsideItem && AmzS3Api.QNAME_ITEM_SIZE.equals(qName);
itIsTruncateFlag = AmzS3Api.QNAME_IS_TRUNCATED.equals(qName);
super.startElement(uri, localName, qName, attrs);
}
@Override
@SuppressWarnings("unchecked")
public final void endElement(
final String uri, final String localName, final String qName
) throws SAXException {
itIsItemId = itIsItemId && !AmzS3Api.QNAME_ITEM_ID.equals(qName);
itIsItemSize = itIsItemSize && !AmzS3Api.QNAME_ITEM_SIZE.equals(qName);
itIsTruncateFlag = itIsTruncateFlag && !AmzS3Api.QNAME_IS_TRUNCATED.equals(qName);
if(isInsideItem && AmzS3Api.QNAME_ITEM.equals(qName)) {
isInsideItem = false;
long size = -1;
if(strSize != null && strSize.length() > 0) {
try {
size = Long.parseLong(strSize);
} catch(final NumberFormatException e) {
LogUtil.exception(
Level.WARN, e, "Data object size should be a 64 bit number"
);
}
} else {
Loggers.ERR.trace("No \"{}\" element or empty", AmzS3Api.QNAME_ITEM_SIZE);
}
if(oid != null && oid.length() > 0 && size > -1) {
try {
offset = Long.parseLong(oid, idRadix);
} catch(final NumberFormatException e) {
LogUtil.exception(
Level.WARN, e, "Failed to parse the item id \"{}\"", oid
);
offset = 0;
}
nextItem = itemFactory.getItem(path + oid, offset, size);
itemsBuffer.add(nextItem);
count ++;
} else {
Loggers.ERR.trace("Invalid object id ({}) or size ({})", oid, strSize);
}
}
super.endElement(uri, localName, qName);
}
@Override
public final void characters(final char buff[], final int start, final int length)
throws SAXException {
if(itIsItemId) {
oid = new String(buff, start, length);
} else if(itIsItemSize) {
strSize = new String(buff, start, length);
} else if(itIsTruncateFlag) {
isTruncatedFlag = Boolean.parseBoolean(new String(buff, start, length));
}
super.characters(buff, start, length);
}
public final boolean isTruncated() {
return isTruncatedFlag;
}
}
|
ChristianGreiner/Battleships | src/core/SoundPlayer.java | package core;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
/**
* A wrapper for the swing audio clip.
*/
public class SoundPlayer {
private Clip soundClip;
public SoundPlayer(Clip soundClip) {
this.soundClip = soundClip;
}
/**
* Sets the volume ot the player.
*
* @param value The volume.
*/
public void setVolume(float value) {
if (this.soundClip != null) {
FloatControl gainControl = (FloatControl) this.soundClip.getControl(FloatControl.Type.MASTER_GAIN);
float dB = (float) (Math.log(value) / Math.log(10.0) * 20.0);
gainControl.setValue(dB);
}
}
/**
* Plays the sound clip.
*
* @param volume The volume of the clip.
*/
public void play(float volume) {
this.play();
if (this.soundClip != null)
this.setVolume(volume);
}
/**
* Plays the sound clip.
*/
public void play() {
if (this.soundClip != null) {
this.soundClip.setFramePosition(0);
this.soundClip.start();
}
}
/**
* Plays the sound clip.
*
* @param volume The volume of the clip.
* @param loop Whenever or not the sound clip should be looped.
*/
public void play(float volume, boolean loop) {
this.play();
if (this.soundClip != null) {
this.setVolume(volume);
if (loop)
this.soundClip.loop(Clip.LOOP_CONTINUOUSLY);
}
}
/**
* Stops the sound.
*/
public void stop() {
if (this.soundClip != null)
this.soundClip.stop();
}
}
|
greekwelfaresa/idempiere-test | au.org.greekwelfaresa.idempiere.test.assertj/src/au/org/greekwelfaresa/idempiere/test/assertj/a_asset_change/A_Asset_ChangeAssert.java | /** Generated Assertion Class - DO NOT CHANGE */
package au.org.greekwelfaresa.idempiere.test.assertj.a_asset_change;
import javax.annotation.Generated;
import org.compiere.model.X_A_Asset_Change;
/** Generated assertion class for A_Asset_Change
* @author idempiere-test model assertion generator
* @version Release 6.2 - $Id: ee7ba69c7a3db2e55bc74a6d9a1b13ecc00a3cd7 $ */
@Generated("class au.org.greekwelfaresa.idempiere.test.generator.ModelAssertionGenerator")
public class A_Asset_ChangeAssert extends AbstractA_Asset_ChangeAssert<A_Asset_ChangeAssert, X_A_Asset_Change>
{
/** Standard Constructor */
public A_Asset_ChangeAssert (X_A_Asset_Change actual)
{
super (actual, A_Asset_ChangeAssert.class);
}
} |
clayne/papyrus-debug-server | dependencies/skse64/src/skse64/CommonLibSSE/include/RE/bhkSerializable.h | <reponame>clayne/papyrus-debug-server<gh_stars>1-10
#pragma once
#include "skse64/GameRTTI.h" // RTTI_bhkSerializable
#include "skse64/NiRTTI.h" // NiRTTI_bhkSerializable
#include "RE/bhkRefObject.h" // bhkRefObject
namespace RE
{
class bhkSerializable : public bhkRefObject
{
public:
inline static const void* RTTI = RTTI_bhkSerializable;
inline static const void* Ni_RTTI = NiRTTI_bhkSerializable;
virtual ~bhkSerializable(); // 00
// override (bhkRefObject)
virtual const NiRTTI* GetRTTI() const override; // 02
virtual void LoadBinary(NiStream& a_stream) override; // 18
virtual void LinkObject(NiStream& a_stream) override; // 19
virtual bool RegisterStreamables(NiStream& a_stream) override; // 1A - { return NiObject::RegisterStreamables(a_stream); }
virtual void SaveBinary(NiStream& a_stream) override; // 1B
virtual void Unk_25(void) override; // 25
// add
virtual hkpWorld* GetWorld(); // 27 - { return 0; }
virtual void Unk_28(void); // 28 - { return 0; }
virtual void Unk_29(void); // 29 - { return 0; }
virtual void Unk_2A(void); // 2A - { return 0; }
virtual void Unk_2B(void); // 2B
virtual void Unk_2C(void); // 2C - { return 1; }
virtual void Unk_2D(void); // 2D
virtual void Unk_2E(void) = 0; // 2E
virtual void Unk_2F(void) = 0; // 2F
virtual void Unk_30(void); // 30
virtual void Unk_31(void); // 31
// members
bhkSerializable* serializable; // 18
};
STATIC_ASSERT(sizeof(bhkSerializable) == 0x20);
}
|
classyPimp/FarfrApp | db/migrate/20150418132826_create_comments.rb | class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.integer :commentable_id
t.string :commentable_type
t.references :user
t.references :parent, index: true
t.text :log
t.string :type
t.timestamps null: false
end
add_index :comments, :commentable_id
add_index :comments, :commentable_type
add_index :comments, :type
add_foreign_key :comments, :comments, column: :parent_id
end
end
|
keithtan/main | src/test/java/seedu/superta/logic/parser/DeleteAssignmentCommandParserTest.java | package seedu.superta.logic.parser;
import static seedu.superta.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.superta.logic.parser.CliSyntax.PREFIX_ASSIGNMENT_TITLE;
import static seedu.superta.logic.parser.CliSyntax.PREFIX_GENERAL_ASSIGNMENT_TITLE;
import static seedu.superta.logic.parser.CliSyntax.PREFIX_GENERAL_TUTORIAL_GROUP_ID;
import static seedu.superta.logic.parser.CliSyntax.PREFIX_TUTORIAL_GROUP_ID;
import static seedu.superta.logic.parser.CommandParserTestUtil.assertParseFailure;
import static seedu.superta.logic.parser.CommandParserTestUtil.assertParseSuccess;
import org.junit.Test;
import seedu.superta.logic.commands.DeleteAssignmentCommand;
public class DeleteAssignmentCommandParserTest {
private DeleteAssignmentCommandParser parser = new DeleteAssignmentCommandParser();
@Test
public void parse_emptyArg_throwsParseException() {
assertParseFailure(parser,
" ",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteAssignmentCommand.MESSAGE_USAGE));
}
@Test
public void parse_invalidArg_throwsParseException() {
//wrong tutorial prefix
assertParseFailure(parser,
" " + PREFIX_TUTORIAL_GROUP_ID + "T01 " + PREFIX_GENERAL_ASSIGNMENT_TITLE + "Lab 1",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteAssignmentCommand.MESSAGE_USAGE));
//wrong assignment prefix
assertParseFailure(parser,
" " + PREFIX_GENERAL_TUTORIAL_GROUP_ID + "T01 " + PREFIX_ASSIGNMENT_TITLE + "Lab 1",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteAssignmentCommand.MESSAGE_USAGE));
//wrong tutorial and assignment prefix
assertParseFailure(parser,
" " + PREFIX_TUTORIAL_GROUP_ID + "T01 " + PREFIX_ASSIGNMENT_TITLE + "Lab 1",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteAssignmentCommand.MESSAGE_USAGE));
}
@Test
public void parse_validArg_returnDeleteAssignmentCommand() {
String assignment = "Lab 1";
String tg = "T01";
DeleteAssignmentCommand expected = new DeleteAssignmentCommand(assignment, tg);
String arguments = " " + PREFIX_GENERAL_TUTORIAL_GROUP_ID + tg + " "
+ PREFIX_GENERAL_ASSIGNMENT_TITLE + assignment;
assertParseSuccess(parser , arguments, expected);
arguments = " " + PREFIX_GENERAL_ASSIGNMENT_TITLE + assignment + " "
+ PREFIX_GENERAL_TUTORIAL_GROUP_ID + tg;
assertParseSuccess(parser , arguments, expected);
}
}
|
TheCarvalho/atividades-wikipython | ExerciciosListas/09.py | '''
9. Faça um Programa que leia um vetor A com 10 números inteiros, calcule e mostre a soma dos quadrados dos elementos do vetor.
'''
vetorA = []
soma = 0
for i in range(10):
vetorA.append(int(input(f'Num {i+1}: ')))
for i in range(len(vetorA)):
soma += vetorA[i]**2
print(f'A soma dos quadrados dos elementos é {soma}')
|
paige-ingram/nwhacks2022 | node_modules/@fluentui/react-northstar/dist/dts/test/specs/components/MenuButton/MenuButton-test.js | <reponame>paige-ingram/nwhacks2022<filename>node_modules/@fluentui/react-northstar/dist/dts/test/specs/components/MenuButton/MenuButton-test.js<gh_stars>0
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = require("react");
var MenuButton_1 = require("src/components/MenuButton/MenuButton");
var Box_1 = require("src/components/Box/Box");
var commonTests_1 = require("test/specs/commonTests");
var utils_1 = require("../../../utils");
var a11y_testing_1 = require("@fluentui/a11y-testing");
var mockMenu = { items: ['1', '2', '3'] };
describe('MenuButton', function () {
commonTests_1.isConformant(MenuButton_1.MenuButton, { testPath: __filename, constructorName: 'MenuButton', autoControlledProps: ['open'] });
describe('accessibility', function () {
commonTests_1.handlesAccessibility(MenuButton_1.MenuButton);
describe('onOpenChange', function () {
test('is called on click', function () {
var onOpenChange = jest.fn();
utils_1.mountWithProvider(React.createElement(MenuButton_1.MenuButton, { trigger: React.createElement("button", null), menu: mockMenu, onOpenChange: onOpenChange }))
.find('button')
.simulate('click');
expect(onOpenChange).toHaveBeenCalledTimes(1);
expect(onOpenChange.mock.calls[0][1]).toMatchObject({ open: true });
});
test('is called on click when controlled', function () {
var onOpenChange = jest.fn();
utils_1.mountWithProvider(React.createElement(MenuButton_1.MenuButton, { open: false, trigger: React.createElement("button", null), menu: mockMenu, onOpenChange: onOpenChange }))
.find('button')
.simulate('click');
expect(onOpenChange).toHaveBeenCalledTimes(1);
expect(onOpenChange.mock.calls[0][1]).toMatchObject({ open: true });
});
});
describe('ID handling', function () {
test('trigger id is used', function () {
var menuButton = utils_1.mountWithProvider(React.createElement(MenuButton_1.MenuButton, { trigger: React.createElement("button", { id: "test-id" }), menu: mockMenu }));
var button = menuButton.find('button');
button.simulate('click');
var menu = menuButton.find('ul');
var triggerId = button.prop('id');
expect(triggerId).toEqual('test-id');
expect(menu.prop('aria-labelledby')).toEqual(triggerId);
});
test('trigger id is generated if not provided', function () {
var menuButton = utils_1.mountWithProvider(React.createElement(MenuButton_1.MenuButton, { trigger: React.createElement("button", null), menu: mockMenu }));
var button = menuButton.find('button');
button.simulate('click');
var menu = menuButton.find('ul');
var triggerId = button.prop('id');
expect(triggerId).toMatch(/menubutton-trigger-\d+/);
expect(menu.prop('aria-labelledby')).toEqual(triggerId);
});
test('menu id is used', function () {
var menuId = 'test-id';
var menuButton = utils_1.mountWithProvider(React.createElement(MenuButton_1.MenuButton, { trigger: React.createElement("button", null), menu: tslib_1.__assign(tslib_1.__assign({}, mockMenu), { id: menuId }) }));
menuButton.find('button').simulate('click');
expect(menuButton.find('ul').prop('id')).toEqual(menuId);
expect(menuButton.find('button').prop('aria-controls')).toEqual(menuId);
});
test('menu id is generated if not provided', function () {
var menuButton = utils_1.mountWithProvider(React.createElement(MenuButton_1.MenuButton, { trigger: React.createElement("button", null), menu: mockMenu }));
menuButton.find('button').simulate('click');
var menuId = menuButton.find('ul').prop('id');
expect(menuId).toMatch(/menubutton-menu-\d+/);
expect(menuButton.find('button').prop('aria-controls')).toEqual(menuId);
});
});
});
});
describe('MenuButtonBehavior', function () {
var menuToRender = { id: 'menuID', 'data-slotid': 'menu', items: ['1', '2', '3'] };
var menuToRenderWithoutID = { 'data-slotid': 'menu', items: ['1', '2', '3'] };
var triggerButton = React.createElement("button", { "data-slotid": "trigger", id: "triggerElementID" });
var triggerButtonWithoutID = React.createElement("button", { "data-slotid": "trigger" });
describe('trigger slot - tabbable - Button', function () {
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerButton, menu: menuToRender });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionTriggerSlotTabbable, testFacade);
expect(errors).toEqual([]);
});
describe('trigger slot - tabbable - Box as button', function () {
var triggerWithoutTabIndex = React.createElement(Box_1.Box, { "data-slotid": "trigger", id: "triggerElementID", as: "button" });
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerWithoutTabIndex, menu: menuToRender });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionTriggerSlotTabbable, testFacade);
expect(errors).toEqual([]);
});
describe('trigger slot - tabbable - Anchor', function () {
var triggerWithoutTabIndex = (React.createElement("a", { href: "", "data-slotid": "trigger", id: "triggerElementID" }, "triggerLink"));
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerWithoutTabIndex, menu: menuToRender });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionTriggerSlotTabbable, testFacade);
expect(errors).toEqual([]);
});
describe('trigger slot - NO tabbable - Anchor without href', function () {
var triggerAnchorWtihoutHref = (React.createElement("a", { "data-slotid": "trigger", id: "triggerElementID" }, "triggerLink"));
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerAnchorWtihoutHref, menu: menuToRender });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionTriggerSlotNotTabbable, testFacade);
expect(errors).toEqual([]);
});
describe('trigger slot - NO tabbable - Span', function () {
var triggerWithoutTabIndex = (React.createElement("span", { "data-slotid": "trigger", id: "triggerElementID" }, "text to trigger popup"));
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerWithoutTabIndex, menu: menuToRender });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionTriggerSlotNotTabbable, testFacade);
expect(errors).toEqual([]);
});
describe('trigger slot - doesnt override tabIndex if exists', function () {
var triggerWithTabIndex = React.createElement("button", { "data-slotid": "trigger", id: "triggerElementID", tabIndex: -1 });
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerWithTabIndex, menu: menuToRender });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionTriggerWithTabIndex, testFacade);
expect(errors).toEqual([]);
});
describe('trigger slot - autogenerate ID', function () {
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerButtonWithoutID, menu: menuToRender });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionTriggerSlotWithoutID, testFacade);
expect(errors).toEqual([]);
});
describe('menu slot', function () {
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerButton, menu: menuToRender });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionMenuSlot, testFacade);
expect(errors).toEqual([]);
});
describe('menu slot - autogenerate ID', function () {
var testFacade = new a11y_testing_1.ComponentTestFacade(MenuButton_1.MenuButton, { trigger: triggerButton, menu: menuToRenderWithoutID });
var errors = a11y_testing_1.validateBehavior(a11y_testing_1.menuButtonBehaviorDefinitionMenuSlotWithoutID, testFacade);
expect(errors).toEqual([]);
});
});
|
mss-boot-io/mss-boot | service/tenant/form/doc.go | <reponame>mss-boot-io/mss-boot
/*
* @Author: lwnmengjing
* @Date: 2021/6/23 11:24 上午
* @Last Modified by: lwnmengjing
* @Last Modified time: 2021/6/23 11:24 上午
*/
package form
/**
* ⚠️注意: 该包不能调用其他的业务包(controllers, models)
*/
|
paridhikhaitan/good-news-today | node_modules/roughjs/bin/wrappers/worker.js | import { expose } from 'workly';
import * as renderer from '../renderer';
expose(renderer);
|
Divyanshu075/scala-training | src/main/scala/training/date0208/VectorExample.scala | package training.date0208
object VectorExample extends App {
val a: Vector[Int] = scala.collection.immutable.Vector.apply(1,2,3,4)
val a1 = Vector(1,2,3,4,5,6,7)
}
|
VREMSoftwareDevelopment/travelagency | travelagency-wicket/src/main/java/ca/travelagency/components/formdetail/SaveButtonDetail.java | /**
* Copyright (C) 2010 - 2014 VREM Software Development <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ca.travelagency.components.formdetail;
import org.apache.commons.lang3.Validate;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.markup.html.form.Form;
import ca.travelagency.components.AjaxButtonCallback;
import ca.travelagency.components.decorators.BlockUIDecorator;
import ca.travelagency.components.formheader.DaoEntityModelFactory;
import ca.travelagency.components.javascript.JSUtils;
import ca.travelagency.persistence.DaoEntity;
public class SaveButtonDetail<T extends DaoEntity> extends IndicatingAjaxButton {
private static final long serialVersionUID = 1L;
private AjaxButtonCallback<T> ajaxButtonCallback;
public SaveButtonDetail(String id, Form<T> form, AjaxButtonCallback<T> ajaxButtonCallback) {
super(id, form);
Validate.notNull(ajaxButtonCallback);
this.ajaxButtonCallback = ajaxButtonCallback;
}
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
@SuppressWarnings("unchecked")
Form<T> typedForm = (Form<T>) form;
ajaxButtonCallback.onSubmit(target, typedForm);
target.appendJavaScript(JSUtils.INITIALIZE);
target.appendJavaScript(JSUtils.SHOW_ROW_CONTROLS);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
@SuppressWarnings("unchecked")
Form<T> typedForm = (Form<T>) form;
target.add(typedForm);
target.appendJavaScript(JSUtils.INITIALIZE);
target.appendJavaScript(DaoEntityModelFactory.isPersisted(typedForm.getModelObject())
? JSUtils.HIDE_ROW_CONTROLS : JSUtils.SHOW_ROW_CONTROLS);
}
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new BlockUIDecorator());
}
} |
DKE-Data/agrirouter-sdk-python | agrirouter/utils/uuid_util.py | <reponame>DKE-Data/agrirouter-sdk-python
import uuid
def new_uuid():
return str(uuid.uuid4())
|
UmbrellaMalware/easy_vk | easy_vk/user/api/widgets.py | # This file was autogenerated from vk-api json schema
from typing import List, Union, Optional, overload
from easy_vk.types import objects
from easy_vk.types import responses
from easy_vk.api_category import BaseCategory
try:
from typing import Literal
except Exception:
from typing_extensions import Literal
class Widgets(BaseCategory):
def __init__(self, session, access_token: str, v: str, last_call_timer, delay: float, auto_retry: bool, max_retries: int, timeout: float):
super().__init__(session, access_token, v, last_call_timer, delay, auto_retry, max_retries, timeout)
def get_comments(self, widget_api_id: Optional[int] = None, url: Optional[str] = None, page_id: Optional[str] = None, order: Optional[str] = None, fields: Optional[List[Union[objects.UsersFields, str]]] = None, offset: Optional[int] = None, count: Optional[int] = None) -> responses.WidgetsGetComments:
"""
Gets a list of comments for the page added through the [vk.com/dev/Comments|Comments widget].
:param widget_api_id:
:param url:
:param page_id:
:param order:
:param fields:
:param offset:
:param count:
"""
method_parameters = {k: v for k, v in locals().items() if k not in {'self', 'raw_response'}}
param_aliases = []
method_name = 'widgets.getComments'
response_type = responses.WidgetsGetComments
return self._call(method_name, method_parameters, param_aliases, response_type)
def get_pages(self, widget_api_id: Optional[int] = None, order: Optional[str] = None, period: Optional[str] = None, offset: Optional[int] = None, count: Optional[int] = None) -> responses.WidgetsGetPages:
"""
Gets a list of application/site pages where the [vk.com/dev/Comments|Comments widget] or [vk.com/dev/Like|Like widget] is installed.
:param widget_api_id:
:param order:
:param period:
:param offset:
:param count:
"""
method_parameters = {k: v for k, v in locals().items() if k not in {'self', 'raw_response'}}
param_aliases = []
method_name = 'widgets.getPages'
response_type = responses.WidgetsGetPages
return self._call(method_name, method_parameters, param_aliases, response_type)
|
keerthieaaswar/PDA-MOBILE | src/assets/locales/unicode.js | <reponame>keerthieaaswar/PDA-MOBILE
export let UNICODE = {
'arabic' : /[\u0600-\u06FF]/,
'persian' : /[\u0750-\u077F]/,
'Hebrew' : /[\u0590-\u05FF]/,
'Syriac' : /[\u0700-\u074F]/,
'Bengali' : /[\u0980-\u09FF]/,
'Ethiopic' : /[\u1200-\u137F]/,
'Greek and Coptic' : /[\u0370-\u03FF]/,
'Georgian' : /[\u10A0-\u10FF]/,
'Thai' : /[\u0E00-\u0E7F]/,
'Kannada' : /[\u0C80-\u0CFF]/,
'hi': /[\u0900-\u097F]/,
'en' : /^[a-zA-Z]+$/
// add other languages here
}; |
tedj/QCRI-rheem | rheem-platforms/rheem-spark/src/main/java/org/qcri/rheem/spark/mapping/CountToSparkCountMapping.java | package org.qcri.rheem.spark.mapping;
import org.qcri.rheem.basic.operators.CountOperator;
import org.qcri.rheem.core.mapping.*;
import org.qcri.rheem.core.plan.rheemplan.Operator;
import org.qcri.rheem.core.types.DataSetType;
import org.qcri.rheem.spark.operators.SparkCountOperator;
import org.qcri.rheem.spark.platform.SparkPlatform;
import java.util.Collection;
import java.util.Collections;
/**
* Mapping from {@link CountOperator} to {@link SparkCountOperator}.
*/
public class CountToSparkCountMapping implements Mapping {
@Override
public Collection<PlanTransformation> getTransformations() {
return Collections.singleton(new PlanTransformation(this.createSubplanPattern(), new ReplacementFactory(),
SparkPlatform.getInstance()));
}
private SubplanPattern createSubplanPattern() {
final OperatorPattern operatorPattern = new OperatorPattern(
"count", new CountOperator<>(DataSetType.none()), false);
return SubplanPattern.createSingleton(operatorPattern);
}
private static class ReplacementFactory extends ReplacementSubplanFactory {
@Override
protected Operator translate(SubplanMatch subplanMatch, int epoch) {
final CountOperator<?> originalOperator = (CountOperator<?>) subplanMatch.getMatch("count").getOperator();
return new SparkCountOperator<>(originalOperator.getInputType()).at(epoch);
}
}
}
|
ArkadGamesNetwork/HungerGames | src/fr/mrcubee/hungergames/listeners/player/PlayerJoin.java | package fr.mrcubee.hungergames.listeners.player;
import java.util.ArrayList;
import fr.mrcubee.bukkit.packet.GenericListenerManager;
import fr.mrcubee.bukkit.player.PlayerUtils;
import fr.mrcubee.hungergames.Game;
import fr.mrcubee.util.LangUtil;
import net.arkadgames.hungergames.sql.PlayerData;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import fr.mrcubee.hungergames.GameStats;
import fr.mrcubee.hungergames.HungerGames;
public class PlayerJoin implements Listener {
private final HungerGames survivalGames;
private final ItemStack itemKit;
public PlayerJoin(HungerGames survivalGames) {
ItemMeta itemKitMeta;
this.survivalGames = survivalGames;
this.itemKit = new ItemStack(Material.NETHER_STAR);
itemKitMeta = this.itemKit.getItemMeta();
itemKitMeta.setDisplayName(ChatColor.YELLOW + "Kit");
itemKitMeta.setLore(new ArrayList<String>());
this.itemKit.setItemMeta(itemKitMeta);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void playerJoinEvent(PlayerJoinEvent event) {
Game game = this.survivalGames.getGame();
PlayerData playerData = game.getDataBaseManager().getPlayerData(event.getPlayer().getUniqueId());
Player player = event.getPlayer();
GenericListenerManager genericListenerManager = this.survivalGames.getGenericListenerManager();
LangUtil.updatePlayerLocale(event.getPlayer(), PlayerUtils.getLocale(event.getPlayer()));
if (genericListenerManager != null)
genericListenerManager.addPlayer(event.getPlayer());
game.getPluginScoreBoardManager().getPlayerSideBar(event.getPlayer());
if (game.getGameStats() == GameStats.DURING) {
event.setJoinMessage(null);
player.getInventory().clear();
game.addSpectator(player);
} else {
player.getInventory().clear();
player.getInventory().addItem(this.itemKit);
game.addPlayer(event.getPlayer());
event.setJoinMessage(ChatColor.GREEN + "[+] " + event.getPlayer().getName());
}
event.getPlayer().teleport(survivalGames.getGame().getSpawn());
}
}
|
CrackerCat/iWeChat | header6.6.1/FBSDKGraphRequestBody.h | <filename>header6.6.1/FBSDKGraphRequestBody.h
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
@class NSData, NSMutableData;
@interface FBSDKGraphRequestBody : NSObject
{
NSMutableData *_data;
}
+ (id)mimeContentType;
- (void).cxx_destruct;
- (void)_appendWithKey:(id)arg1 contentBlock:(CDUnknownBlockType)arg2;
@property(readonly, retain, nonatomic) NSData *data;
- (void)appendWithKey:(id)arg1 formValue:(id)arg2;
- (void)appendUTF8:(id)arg1;
- (id)init;
@end
|
norishigefukushima/OpenCP | OpenCP/gif/guidedFilter_Merge_OnePath_Fast.h | #pragma once
#include "guidedFilter_Merge_OnePass.h"
class guidedFilter_Merge_OnePath_Fast : public guidedFilter_Merge_OnePass
{
private:
cv::Mat src_resize;
cv::Mat guide_resize;
int row_resize;
int col_resize;
void filter_Guide1(int cn) override;
void filter_Guide3(int cn) override;
public:
guidedFilter_Merge_OnePath_Fast(cv::Mat& _src, cv::Mat& _guide, cv::Mat& _dest, int _r, float _eps, int _parallelType);
};
|
markelg/ESMValCore | esmvalcore/cmor/_fixes/cmip6/noresm2_lm.py | """Fixes for NorESM2-LM model."""
import numpy as np
from ..common import ClFixHybridPressureCoord
from ..fix import Fix
class AllVars(Fix):
"""Fixes for all variables."""
def fix_metadata(self, cubes):
"""Fix metadata.
Longitude boundary description may be wrong (lon=[0, 2.5, ..., 355,
357.5], lon_bnds=[[0, 1.25], ..., [356.25, 360]]).
Parameters
----------
cubes: iris.cube.CubeList
Input cubes to fix.
Returns
-------
iris.cube.CubeList
"""
for cube in cubes:
coord_names = [cor.standard_name for cor in cube.coords()]
if 'longitude' in coord_names:
if cube.coord('longitude').ndim == 1 and \
cube.coord('longitude').has_bounds():
lon_bnds = cube.coord('longitude').bounds.copy()
if cube.coord('longitude').points[0] == 0. and \
lon_bnds[0][0] == 0.:
lon_bnds[0][0] = -1.25
if cube.coord('longitude').points[-1] == 357.5 and \
lon_bnds[-1][-1] == 360.:
lon_bnds[-1][-1] = 358.75
cube.coord('longitude').bounds = lon_bnds
return cubes
Cl = ClFixHybridPressureCoord
Cli = ClFixHybridPressureCoord
Clw = ClFixHybridPressureCoord
class Siconc(Fix):
"""Fixes for siconc."""
def fix_metadata(self, cubes):
"""Fix metadata.
Some coordinate points vary for different files of this dataset (for
different time range). This fix removes these inaccuracies by rounding
the coordinates.
Parameters
----------
cubes: iris.cube.CubeList
Input cubes to fix.
Returns
-------
iris.cube.CubeList
"""
for cube in cubes:
latitude = cube.coord('latitude')
latitude.bounds = np.round(latitude.bounds, 4)
longitude = cube.coord('longitude')
longitude.bounds = np.round(longitude.bounds, 4)
return cubes
|
patpang71/algorithm | IntervalSetAndOr/src/com/ppang/Interval.java | package com.ppang;
public class Interval {
int start;
int end;
public Interval(int s, int e) {
start = s;
end = e;
}
public Interval(Interval a) {
this.start = a.start;
this.end = a.end;
}
@Override
public String toString() {
return "[" + Integer.toString(start) + ", " + Integer.toString(end) + "]";
}
}
|
p2max34/YHPaaS | YHPaaS/Classes/CMSPaaS.framework/Headers/YHTKeyboardViewDelegate.h | //
// YHTKeyboardViewDelegate.h
// cmsmobilesecurities
//
// Created by 蒲公英 on 2020/11/19.
// Copyright © 2020 cms. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, YHTKeyboardType) {
YHTKeyboardTypeCustomize,
YHTKeyboardTypeSystem
};
@protocol YHTKeyboardViewDelegate <NSObject>
@optional
- (void)confrim;//确定
@end
@protocol YHTKeyboardToolBarDelegate <NSObject>
- (void)toolBarDismissKeyboard;
@optional
- (void)toolBarSwitchKeyboardType:(YHTKeyboardType)keyboardType;
- (void)volumnChange:(NSInteger)volumn;
@end
|
rk400/MDS2 | src/main/java/interfaz/Canciones_visibles_para_cibernauta.java | <filename>src/main/java/interfaz/Canciones_visibles_para_cibernauta.java
package interfaz;
public class Canciones_visibles_para_cibernauta {
public Pagina_de_inicio__Administrador_ _unnamed_Pagina_de_inicio__Administrador__;
public Cancion_visible _unnamed_Cancion_visible_;
} |
guoshucan/mpaas | ghost.framework.data.mongodb/src/main/java/ghost/framework/data/mongodb/core/mapping/event/package-info.java | /**
* Mapping event callback infrastructure for the MongoDB document-to-object mapping subsystem.
*/
package ghost.framework.data.mongodb.core.mapping.event;
|
ebanfa/logix | src/main/java/com/cloderia/helion/client/shared/endpoint/ContactmechanismEndPoint.java | /**
*
*/
package com.cloderia.helion.client.shared.endpoint;
import javax.ws.rs.Path;
import com.cloderia.helion.client.shared.model.Contactmechanism;
import com.cloderia.helion.client.shared.ops.ContactmechanismOperation;
/**
* @author <NAME>
*
*/
@Path("/contactmechanism")
public interface ContactmechanismEndPoint extends BaseEntityEndPoint<Contactmechanism, ContactmechanismOperation> {
}
|
kojilin/kaif | kaif-web/src/main/java/io/kaif/oauth/InvalidTokenException.java | <reponame>kojilin/kaif<gh_stars>10-100
package io.kaif.oauth;
public class InvalidTokenException extends OauthException {
}
|
Appego/fortnox4j | src/main/java/org/notima/api/fortnox/entities3/Authorization.java | package org.notima.api.fortnox.entities3;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Authorization")
public class Authorization {
@XmlElement(name="AccessToken")
private String AccessToken;
public String getAccessToken() {
return AccessToken;
}
public void setAccessToken(String accessToken) {
AccessToken = accessToken;
}
}
|
OotinnyoO1/N64Wasm | code/src/gles2n64/src/gSP_gles2n64.c | #include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <retro_miscellaneous.h>
#include "Common.h"
#include "gles2N64.h"
#include "Debug.h"
#include "RSP.h"
#include "GBI.h"
#include "gSP.h"
#include "gDP.h"
#include "3DMath.h"
#include "OpenGL.h"
#include "CRC.h"
#include <string.h>
#include "convert.h"
#include "S2DEX.h"
#include "VI.h"
#include "FrameBuffer.h"
#include "DepthBuffer.h"
#include "Config.h"
#include "../../Graphics/3dmath.h"
#include "../../Graphics/RDP/gDP_state.h"
#include "../../Graphics/RSP/gSP_state.h"
#include "../../Graphics/image_convert.h"
//Note: 0xC0 is used by 1080 alot, its an unknown command.
float identityMatrix[4][4] =
{
{ 1.0f, 0.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f }
};
static INLINE void gln64gSPFlushTriangles(void)
{
if ((gSP.geometryMode & G_SHADING_SMOOTH) == 0)
{
OGL_DrawTriangles();
return;
}
if (
(__RSP.nextCmd != G_TRI1) &&
(__RSP.nextCmd != G_TRI2) &&
(__RSP.nextCmd != G_TRI4) &&
(__RSP.nextCmd != G_QUAD)
)
OGL_DrawTriangles();
}
void gln64gSPCopyVertex( struct SPVertex *dest, struct SPVertex *src )
{
dest->x = src->x;
dest->y = src->y;
dest->z = src->z;
dest->w = src->w;
dest->r = src->r;
dest->g = src->g;
dest->b = src->b;
dest->a = src->a;
dest->s = src->s;
dest->t = src->t;
}
void gln64gSPInterpolateVertex( struct SPVertex *dest, float percent, struct SPVertex *first, struct SPVertex *second )
{
dest->x = first->x + percent * (second->x - first->x);
dest->y = first->y + percent * (second->y - first->y);
dest->z = first->z + percent * (second->z - first->z);
dest->w = first->w + percent * (second->w - first->w);
dest->r = first->r + percent * (second->r - first->r);
dest->g = first->g + percent * (second->g - first->g);
dest->b = first->b + percent * (second->b - first->b);
dest->a = first->a + percent * (second->a - first->a);
dest->s = first->s + percent * (second->s - first->s);
dest->t = first->t + percent * (second->t - first->t);
}
void gln64gSPTriangle(int32_t v0, int32_t v1, int32_t v2)
{
/* TODO/FIXME - update with gliden64 code */
if ((v0 < INDEXMAP_SIZE) && (v1 < INDEXMAP_SIZE) && (v2 < INDEXMAP_SIZE))
{
OGL_AddTriangle(v0, v1, v2);
}
if (depthBuffer.current) depthBuffer.current->cleared = false;
gDP.colorImage.height = (uint32_t)(MAX( gDP.colorImage.height, (uint32_t)gDP.scissor.lry ));
}
void gln64gSP1Triangle( int32_t v0, int32_t v1, int32_t v2, int flags)
{
gln64gSPTriangle( v0, v1, v2);
gln64gSPFlushTriangles();
}
void gln64gSP2Triangles(const int32_t v00, const int32_t v01, const int32_t v02, const int32_t flag0,
const int32_t v10, const int32_t v11, const int32_t v12, const int32_t flag1 )
{
gln64gSPTriangle( v00, v01, v02);
gln64gSPTriangle( v10, v11, v12);
gln64gSPFlushTriangles();
}
void gln64gSP4Triangles(const int32_t v00, const int32_t v01, const int32_t v02,
const int32_t v10, const int32_t v11, const int32_t v12,
const int32_t v20, const int32_t v21, const int32_t v22,
const int32_t v30, const int32_t v31, const int32_t v32 )
{
gln64gSPTriangle(v00, v01, v02);
gln64gSPTriangle(v10, v11, v12);
gln64gSPTriangle(v20, v21, v22);
gln64gSPTriangle(v30, v31, v32);
gln64gSPFlushTriangles();
}
static void gln64gSPTransformVertex_default(float vtx[4], float mtx[4][4])
{
float x, y, z, w;
x = vtx[0];
y = vtx[1];
z = vtx[2];
w = vtx[3];
vtx[0] = x * mtx[0][0] + y * mtx[1][0] + z * mtx[2][0] + mtx[3][0];
vtx[1] = x * mtx[0][1] + y * mtx[1][1] + z * mtx[2][1] + mtx[3][1];
vtx[2] = x * mtx[0][2] + y * mtx[1][2] + z * mtx[2][2] + mtx[3][2];
vtx[3] = x * mtx[0][3] + y * mtx[1][3] + z * mtx[2][3] + mtx[3][3];
}
static void gln64gSPLightVertex_default(void *data)
{
struct SPVertex * _vtx = (struct SPVertex*)data;
if (!config.generalEmulation.enableHWLighting)
{
unsigned i;
_vtx->HWLight = 0;
_vtx->r = gSP.lights[gSP.numLights].r;
_vtx->g = gSP.lights[gSP.numLights].g;
_vtx->b = gSP.lights[gSP.numLights].b;
for (i = 0; i < gSP.numLights; i++)
{
float intensity = DotProduct( &_vtx->nx, &gSP.lights[i].x );
if (intensity < 0.0f)
intensity = 0.0f;
_vtx->r += gSP.lights[i].r * intensity;
_vtx->g += gSP.lights[i].g * intensity;
_vtx->b += gSP.lights[i].b * intensity;
}
_vtx->r = MIN(1.0f, _vtx->r);
_vtx->g = MIN(1.0f, _vtx->g);
_vtx->b = MIN(1.0f, _vtx->b);
}
else
{
/* TODO/FIXME - update with gliden64 code */
}
}
static void gln64gSPPointLightVertex_default(void *data, float * _vPos)
{
uint32_t l;
float light_intensity = 0.0f;
struct SPVertex *_vtx = (struct SPVertex*)data;
assert(_vPos != NULL);
_vtx->HWLight = 0;
_vtx->r = gSP.lights[gSP.numLights].r;
_vtx->g = gSP.lights[gSP.numLights].g;
_vtx->b = gSP.lights[gSP.numLights].b;
for (l = 0; l < gSP.numLights; ++l)
{
float light_len2, light_len, at;
float lvec[3] = {gSP.lights[l].posx, gSP.lights[l].posy, gSP.lights[l].posz};
lvec[0] -= _vPos[0];
lvec[1] -= _vPos[1];
lvec[2] -= _vPos[2];
light_len2 = lvec[0]*lvec[0] + lvec[1]*lvec[1] + lvec[2]*lvec[2];
light_len = sqrtf(light_len2);
at = gSP.lights[l].ca + light_len/65535.0f*gSP.lights[l].la + light_len2/65535.0f*gSP.lights[l].qa;
if (at > 0.0f)
light_intensity = 1/at;//DotProduct (lvec, nvec) / (light_len * normal_len * at);
else
light_intensity = 0.0f;
if (light_intensity > 0.0f)
{
_vtx->r += gSP.lights[l].r * light_intensity;
_vtx->g += gSP.lights[l].g * light_intensity;
_vtx->b += gSP.lights[l].b * light_intensity;
}
}
if (_vtx->r > 1.0f) _vtx->r = 1.0f;
if (_vtx->g > 1.0f) _vtx->g = 1.0f;
if (_vtx->b > 1.0f) _vtx->b = 1.0f;
}
static void gln64gSPLightVertex_CBFD(void *data)
{
struct SPVertex *_vtx = (struct SPVertex*)data;
uint32_t l;
float r = gSP.lights[gSP.numLights].r;
float g = gSP.lights[gSP.numLights].g;
float b = gSP.lights[gSP.numLights].b;
for (l = 0; l < gSP.numLights; ++l)
{
const struct SPLight *light = (const struct SPLight*)&gSP.lights[l];
const float vx = (_vtx->x + gSP.vertexCoordMod[ 8])*gSP.vertexCoordMod[12] - light->posx;
const float vy = (_vtx->y + gSP.vertexCoordMod[ 9])*gSP.vertexCoordMod[13] - light->posy;
const float vz = (_vtx->z + gSP.vertexCoordMod[10])*gSP.vertexCoordMod[14] - light->posz;
const float vw = (_vtx->w + gSP.vertexCoordMod[11])*gSP.vertexCoordMod[15] - light->posw;
const float len = (vx*vx+vy*vy+vz*vz+vw*vw)/65536.0f;
float intensity = light->ca / len;
if (intensity > 1.0f)
intensity = 1.0f;
r += light->r * intensity;
g += light->g * intensity;
b += light->b * intensity;
}
r = MIN(1.0f, r);
g = MIN(1.0f, g);
b = MIN(1.0f, b);
_vtx->r *= r;
_vtx->g *= g;
_vtx->b *= b;
_vtx->HWLight = 0;
}
static void gln64gSPPointLightVertex_CBFD(void *data, float * _vPos)
{
uint32_t l;
const struct SPLight *light = NULL;
struct SPVertex *_vtx = (struct SPVertex*)data;
float r = gSP.lights[gSP.numLights].r;
float g = gSP.lights[gSP.numLights].g;
float b = gSP.lights[gSP.numLights].b;
float intensity = 0.0f;
for (l = 0; l < gSP.numLights-1; ++l)
{
light = (struct SPLight*)&gSP.lights[l];
intensity = DotProduct( &_vtx->nx, &light->x );
if (intensity < 0.0f)
continue;
if (light->ca > 0.0f)
{
const float vx = (_vtx->x + gSP.vertexCoordMod[ 8])*gSP.vertexCoordMod[12] - light->posx;
const float vy = (_vtx->y + gSP.vertexCoordMod[ 9])*gSP.vertexCoordMod[13] - light->posy;
const float vz = (_vtx->z + gSP.vertexCoordMod[10])*gSP.vertexCoordMod[14] - light->posz;
const float vw = (_vtx->w + gSP.vertexCoordMod[11])*gSP.vertexCoordMod[15] - light->posw;
const float len = (vx*vx+vy*vy+vz*vz+vw*vw)/65536.0f;
float p_i = light->ca / len;
if (p_i > 1.0f) p_i = 1.0f;
intensity *= p_i;
}
r += light->r * intensity;
g += light->g * intensity;
b += light->b * intensity;
}
light = (struct SPLight*)&gSP.lights[gSP.numLights-1];
intensity = DotProduct( &_vtx->nx, &light->x );
if (intensity > 0.0f)
{
r += light->r * intensity;
g += light->g * intensity;
b += light->b * intensity;
}
r = MIN(1.0f, r);
g = MIN(1.0f, g);
b = MIN(1.0f, b);
_vtx->r *= r;
_vtx->g *= g;
_vtx->b *= b;
_vtx->HWLight = 0;
}
static void gln64gSPBillboardVertex_default(uint32_t v, uint32_t i)
{
struct SPVertex *vtx0 = (struct SPVertex*)&OGL.triangles.vertices[i];
struct SPVertex *vtx = (struct SPVertex*)&OGL.triangles.vertices[v];
vtx->x += vtx0->x;
vtx->y += vtx0->y;
vtx->z += vtx0->z;
vtx->w += vtx0->w;
}
void gln64gSPClipVertex(uint32_t v)
{
struct SPVertex *vtx = &OGL.triangles.vertices[v];
vtx->clip = 0;
if (vtx->x > +vtx->w) vtx->clip |= CLIP_POSX;
if (vtx->x < -vtx->w) vtx->clip |= CLIP_NEGX;
if (vtx->y > +vtx->w) vtx->clip |= CLIP_POSY;
if (vtx->y < -vtx->w) vtx->clip |= CLIP_NEGY;
if (vtx->w < 0.01f) vtx->clip |= CLIP_Z;
}
void gln64gSPProcessVertex(uint32_t v)
{
float intensity, r, g, b;
struct SPVertex *vtx = (struct SPVertex*)&OGL.triangles.vertices[v];
if (gSP.changed & CHANGED_MATRIX)
gln64gSPCombineMatrices();
gln64gSPTransformVertex( &vtx->x, gSP.matrix.combined );
if (gSP.viewport.vscale[0] < 0)
vtx->x = -vtx->x;
if (gSP.matrix.billboard)
{
int i = 0;
gln64gSPBillboardVertex(v, i);
}
gln64gSPClipVertex(v);
if (gSP.geometryMode & G_LIGHTING)
{
float vPos[3];
vPos[0] = (float)vtx->x;
vPos[1] = (float)vtx->y;
vPos[2] = (float)vtx->z;
TransformVectorNormalize( &vtx->nx, gSP.matrix.modelView[gSP.matrix.modelViewi] );
if (gSP.geometryMode & G_POINT_LIGHTING)
gln64gSPPointLightVertex(vtx, vPos);
else
gln64gSPLightVertex(vtx);
if (/* GBI.isTextureGen() && */ gSP.geometryMode & G_TEXTURE_GEN)
{
float fLightDir[3] = {vtx->nx, vtx->ny, vtx->nz};
float x, y;
if (gSP.lookatEnable)
{
x = DotProduct(&gSP.lookat[0].x, fLightDir);
y = DotProduct(&gSP.lookat[1].x, fLightDir);
}
else
{
x = fLightDir[0];
y = fLightDir[1];
}
if (gSP.geometryMode & G_TEXTURE_GEN_LINEAR)
{
vtx->s = acosf(x) * 325.94931f;
vtx->t = acosf(y) * 325.94931f;
}
else /* G_TEXTURE_GEN */
{
vtx->s = (x + 1.0f) * 512.0f;
vtx->t = (y + 1.0f) * 512.0f;
}
}
}
else
vtx->HWLight = 0;
}
void gln64gSPLoadUcodeEx( uint32_t uc_start, uint32_t uc_dstart, uint16_t uc_dsize )
{
MicrocodeInfo *ucode;
__RSP.PCi = 0;
gSP.matrix.modelViewi = 0;
gSP.changed |= CHANGED_MATRIX;
gSP.status[0] = gSP.status[1] = gSP.status[2] = gSP.status[3] = 0;
if ((((uc_start & 0x1FFFFFFF) + 4096) > RDRAMSize) || (((uc_dstart & 0x1FFFFFFF) + uc_dsize) > RDRAMSize))
return;
ucode = (MicrocodeInfo*)GBI_DetectMicrocode( uc_start, uc_dstart, uc_dsize );
__RSP.uc_start = uc_start;
__RSP.uc_dstart = uc_dstart;
/* TODO/FIXME - remove this maybe? for gliden64 */
if (ucode->type != 0xFFFFFFFF)
last_good_ucode = ucode->type;
if (ucode->type != NONE)
GBI_MakeCurrent( ucode );
else
{
LOG(LOG_WARNING, "Unknown Ucode\n");
}
}
void gln64gSPCombineMatrices(void)
{
MultMatrix(gSP.matrix.projection, gSP.matrix.modelView[gSP.matrix.modelViewi], gSP.matrix.combined);
gSP.changed &= ~CHANGED_MATRIX;
}
void gln64gSPNoOp(void)
{
gln64gSPFlushTriangles();
}
void gln64gSPMatrix( uint32_t matrix, uint8_t param )
{
float mtx[4][4];
uint32_t address = RSP_SegmentToPhysical( matrix );
if (address + 64 > RDRAMSize)
return;
RSP_LoadMatrix( mtx, address );
if (param & G_MTX_PROJECTION)
{
if (param & G_MTX_LOAD)
CopyMatrix( gSP.matrix.projection, mtx );
else
MultMatrix2( gSP.matrix.projection, mtx );
}
else
{
if ((param & G_MTX_PUSH) && (gSP.matrix.modelViewi < (gSP.matrix.stackSize - 1)))
{
CopyMatrix( gSP.matrix.modelView[gSP.matrix.modelViewi + 1], gSP.matrix.modelView[gSP.matrix.modelViewi] );
gSP.matrix.modelViewi++;
}
if (param & G_MTX_LOAD)
CopyMatrix( gSP.matrix.modelView[gSP.matrix.modelViewi], mtx );
else
MultMatrix2( gSP.matrix.modelView[gSP.matrix.modelViewi], mtx );
}
gSP.changed |= CHANGED_MATRIX;
}
void gln64gSPDMAMatrix( uint32_t matrix, uint8_t index, uint8_t multiply )
{
float mtx[4][4];
uint32_t address = gSP.DMAOffsets.mtx + RSP_SegmentToPhysical( matrix );
if (address + 64 > RDRAMSize)
return;
RSP_LoadMatrix( mtx, address );
gSP.matrix.modelViewi = index;
if (multiply)
MultMatrix(gSP.matrix.modelView[0], mtx, gSP.matrix.modelView[gSP.matrix.modelViewi]);
else
CopyMatrix( gSP.matrix.modelView[gSP.matrix.modelViewi], mtx );
CopyMatrix( gSP.matrix.projection, identityMatrix );
gSP.changed |= CHANGED_MATRIX;
}
void gln64gSPViewport(uint32_t v)
{
uint32_t address = RSP_SegmentToPhysical( v );
if ((address + 16) > RDRAMSize)
return;
gSP.viewport.vscale[0] = _FIXED2FLOAT( *(int16_t*)&gfx_info.RDRAM[address + 2], 2 );
gSP.viewport.vscale[1] = _FIXED2FLOAT( *(int16_t*)&gfx_info.RDRAM[address ], 2 );
gSP.viewport.vscale[2] = _FIXED2FLOAT( *(int16_t*)&gfx_info.RDRAM[address + 6], 10 ); /* * 0.00097847357f; */
gSP.viewport.vscale[3] = *(int16_t*)&gfx_info.RDRAM[address + 4];
gSP.viewport.vtrans[0] = _FIXED2FLOAT( *(int16_t*)&gfx_info.RDRAM[address + 10], 2 );
gSP.viewport.vtrans[1] = _FIXED2FLOAT( *(int16_t*)&gfx_info.RDRAM[address + 8], 2 );
gSP.viewport.vtrans[2] = _FIXED2FLOAT( *(int16_t*)&gfx_info.RDRAM[address + 14], 10 ); /* * 0.00097847357f; */
gSP.viewport.vtrans[3] = *(int16_t*)&gfx_info.RDRAM[address + 12];
gSP.viewport.x = gSP.viewport.vtrans[0] - gSP.viewport.vscale[0];
gSP.viewport.y = gSP.viewport.vtrans[1] - gSP.viewport.vscale[1];
gSP.viewport.width = fabs(gSP.viewport.vscale[0]) * 2;
gSP.viewport.height = fabs(gSP.viewport.vscale[1]) * 2;
gSP.viewport.nearz = gSP.viewport.vtrans[2] - gSP.viewport.vscale[2];
gSP.viewport.farz = (gSP.viewport.vtrans[2] + gSP.viewport.vscale[2]) ;
gSP.changed |= CHANGED_VIEWPORT;
}
void gln64gSPForceMatrix( uint32_t mptr )
{
uint32_t address = RSP_SegmentToPhysical( mptr );
if (address + 64 > RDRAMSize)
return;
RSP_LoadMatrix( gSP.matrix.combined, address);
gSP.changed &= ~CHANGED_MATRIX;
}
void gln64gSPLight( uint32_t l, int32_t n )
{
uint32_t addrByte;
Light *light = NULL;
--n;
addrByte = RSP_SegmentToPhysical( l );
if ((addrByte + sizeof( Light )) > RDRAMSize)
return;
light = (Light*)&gfx_info.RDRAM[addrByte];
if (n < 8)
{
uint32_t addrShort;
gSP.lights[n].r = light->r * 0.0039215689f;
gSP.lights[n].g = light->g * 0.0039215689f;
gSP.lights[n].b = light->b * 0.0039215689f;
gSP.lights[n].x = light->x;
gSP.lights[n].y = light->y;
gSP.lights[n].z = light->z;
NormalizeVector( &gSP.lights[n].x );
addrShort = addrByte >> 1;
gSP.lights[n].posx = (float)(((short*)gfx_info.RDRAM)[(addrShort+4)^1]);
gSP.lights[n].posy = (float)(((short*)gfx_info.RDRAM)[(addrShort+5)^1]);
gSP.lights[n].posz = (float)(((short*)gfx_info.RDRAM)[(addrShort+6)^1]);
gSP.lights[n].ca = (float)(gfx_info.RDRAM[(addrByte + 3) ^ 3]) / 16.0f;
gSP.lights[n].la = (float)(gfx_info.RDRAM[(addrByte + 7) ^ 3]);
gSP.lights[n].qa = (float)(gfx_info.RDRAM[(addrByte + 14) ^ 3]) / 8.0f;
}
if (config.generalEmulation.enableHWLighting != 0)
gSP.changed |= CHANGED_LIGHT;
}
void gln64gSPLightCBFD( uint32_t l, int32_t n )
{
Light *light = NULL;
uint32_t addrByte = RSP_SegmentToPhysical( l );
if ((addrByte + sizeof( Light )) > RDRAMSize)
return;
light = (Light*)&gfx_info.RDRAM[addrByte];
if (n < 12)
{
uint32_t addrShort;
gSP.lights[n].r = light->r * 0.0039215689f;
gSP.lights[n].g = light->g * 0.0039215689f;
gSP.lights[n].b = light->b * 0.0039215689f;
gSP.lights[n].x = light->x;
gSP.lights[n].y = light->y;
gSP.lights[n].z = light->z;
NormalizeVector( &gSP.lights[n].x );
addrShort = addrByte >> 1;
gSP.lights[n].posx = (float)(((int16_t*)gfx_info.RDRAM)[(addrShort+16)^1]);
gSP.lights[n].posy = (float)(((int16_t*)gfx_info.RDRAM)[(addrShort+17)^1]);
gSP.lights[n].posz = (float)(((int16_t*)gfx_info.RDRAM)[(addrShort+18)^1]);
gSP.lights[n].posw = (float)(((int16_t*)gfx_info.RDRAM)[(addrShort+19)^1]);
gSP.lights[n].ca = (float)(gfx_info.RDRAM[(addrByte + 12) ^ 3]) / 16.0f;
}
if (config.generalEmulation.enableHWLighting != 0)
gSP.changed |= CHANGED_LIGHT;
}
void gln64gSPLookAt( uint32_t _l, uint32_t _n )
{
Light *light;
uint32_t address = RSP_SegmentToPhysical(_l);
if ((address + sizeof(Light)) > RDRAMSize)
return;
assert(_n < 2);
light = (Light*)&gfx_info.RDRAM[address];
gSP.lookat[_n].x = light->x;
gSP.lookat[_n].y = light->y;
gSP.lookat[_n].z = light->z;
gSP.lookatEnable = (_n == 0) || (_n == 1 && (light->x != 0 || light->y != 0));
NormalizeVector(&gSP.lookat[_n].x);
}
void gln64gSPVertex( uint32_t v, uint32_t n, uint32_t v0 )
{
unsigned int i;
Vertex *vertex;
uint32_t address = RSP_SegmentToPhysical( v );
if ((address + sizeof( Vertex ) * n) > RDRAMSize)
return;
vertex = (Vertex*)&gfx_info.RDRAM[address];
if ((n + v0) <= INDEXMAP_SIZE)
{
for (i = v0; i < n + v0; i++)
{
uint32_t v = i;
struct SPVertex *vtx = (struct SPVertex*)&OGL.triangles.vertices[v];
vtx->x = vertex->x;
vtx->y = vertex->y;
vtx->z = vertex->z;
vtx->s = _FIXED2FLOAT( vertex->s, 5 );
vtx->t = _FIXED2FLOAT( vertex->t, 5 );
if (gSP.geometryMode & G_LIGHTING)
{
vtx->nx = vertex->normal.x;
vtx->ny = vertex->normal.y;
vtx->nz = vertex->normal.z;
vtx->a = vertex->color.a * 0.0039215689f;
}
else
{
vtx->r = vertex->color.r * 0.0039215689f;
vtx->g = vertex->color.g * 0.0039215689f;
vtx->b = vertex->color.b * 0.0039215689f;
vtx->a = vertex->color.a * 0.0039215689f;
}
gln64gSPProcessVertex(v);
vertex++;
}
}
}
void gln64gSPCIVertex( uint32_t v, uint32_t n, uint32_t v0 )
{
unsigned int i;
PDVertex *vertex;
uint32_t address = RSP_SegmentToPhysical( v );
if ((address + sizeof( PDVertex ) * n) > RDRAMSize)
return;
vertex = (PDVertex*)&gfx_info.RDRAM[address];
if ((n + v0) <= INDEXMAP_SIZE)
{
for(i = v0; i < n + v0; i++)
{
uint8_t *color;
uint32_t v = i;
struct SPVertex *vtx = (struct SPVertex*)&OGL.triangles.vertices[v];
vtx->x = vertex->x;
vtx->y = vertex->y;
vtx->z = vertex->z;
vtx->s = _FIXED2FLOAT( vertex->s, 5 );
vtx->t = _FIXED2FLOAT( vertex->t, 5 );
color = (uint8_t*)&gfx_info.RDRAM[gSP.vertexColorBase + (vertex->ci & 0xff)];
if (gSP.geometryMode & G_LIGHTING)
{
vtx->nx = (int8_t)color[3];
vtx->ny = (int8_t)color[2];
vtx->nz = (int8_t)color[1];
vtx->a = color[0] * 0.0039215689f;
}
else
{
vtx->r = color[3] * 0.0039215689f;
vtx->g = color[2] * 0.0039215689f;
vtx->b = color[1] * 0.0039215689f;
vtx->a = color[0] * 0.0039215689f;
}
gln64gSPProcessVertex(v);
vertex++;
}
}
}
void gln64gSPDMAVertex( uint32_t v, uint32_t n, uint32_t v0 )
{
unsigned int i;
uint32_t address = gSP.DMAOffsets.vtx + RSP_SegmentToPhysical( v );
if ((address + 10 * n) > RDRAMSize)
return;
if ((n + v0) <= INDEXMAP_SIZE)
{
for (i = v0; i < n + v0; i++)
{
uint32_t v = i;
struct SPVertex *vtx = (struct SPVertex*)&OGL.triangles.vertices[v];
vtx->x = *(int16_t*)&gfx_info.RDRAM[address ^ 2];
vtx->y = *(int16_t*)&gfx_info.RDRAM[(address + 2) ^ 2];
vtx->z = *(int16_t*)&gfx_info.RDRAM[(address + 4) ^ 2];
if (gSP.geometryMode & G_LIGHTING)
{
vtx->nx = *(int8_t*)&gfx_info.RDRAM[(address + 6) ^ 3];
vtx->ny = *(int8_t*)&gfx_info.RDRAM[(address + 7) ^ 3];
vtx->nz = *(int8_t*)&gfx_info.RDRAM[(address + 8) ^ 3];
vtx->a = *(uint8_t*)&gfx_info.RDRAM[(address + 9) ^ 3] * 0.0039215689f;
}
else
{
vtx->r = *(uint8_t*)&gfx_info.RDRAM[(address + 6) ^ 3] * 0.0039215689f;
vtx->g = *(uint8_t*)&gfx_info.RDRAM[(address + 7) ^ 3] * 0.0039215689f;
vtx->b = *(uint8_t*)&gfx_info.RDRAM[(address + 8) ^ 3] * 0.0039215689f;
vtx->a = *(uint8_t*)&gfx_info.RDRAM[(address + 9) ^ 3] * 0.0039215689f;
}
gln64gSPProcessVertex(v);
address += 10;
}
}
}
void gln64gSPCBFDVertex( uint32_t a, uint32_t n, uint32_t v0 )
{
Vertex *vertex;
uint32_t address = RSP_SegmentToPhysical(a);
if ((address + sizeof( Vertex ) * n) > RDRAMSize)
return;
vertex = (Vertex*)&gfx_info.RDRAM[address];
if ((n + v0) <= INDEXMAP_SIZE)
{
unsigned int i = v0;
for (; i < n + v0; ++i)
{
uint32_t v = i;
struct SPVertex *vtx = (struct SPVertex*)&OGL.triangles.vertices[v];
vtx->x = vertex->x;
vtx->y = vertex->y;
vtx->z = vertex->z;
vtx->s = _FIXED2FLOAT( vertex->s, 5 );
vtx->t = _FIXED2FLOAT( vertex->t, 5 );
if (gSP.geometryMode & G_LIGHTING)
{
const uint32_t normaleAddrOffset = (v<<1);
vtx->nx = (float)(((int8_t*)gfx_info.RDRAM)[(gSP.vertexNormalBase + normaleAddrOffset + 0)^3]);
vtx->ny = (float)(((int8_t*)gfx_info.RDRAM)[(gSP.vertexNormalBase + normaleAddrOffset + 1)^3]);
vtx->nz = (float)((int8_t)(vertex->flag&0xFF));
}
vtx->r = vertex->color.r * 0.0039215689f;
vtx->g = vertex->color.g * 0.0039215689f;
vtx->b = vertex->color.b * 0.0039215689f;
vtx->a = vertex->color.a * 0.0039215689f;
gln64gSPProcessVertex(v);
vertex++;
}
} else {
LOG(LOG_ERROR, "Using Vertex outside buffer v0=%i, n=%i\n", v0, n);
}
}
void gln64gSPDisplayList( uint32_t dl )
{
uint32_t address = RSP_SegmentToPhysical( dl );
if ((address + 8) > RDRAMSize)
return;
if (__RSP.PCi < (GBI.PCStackSize - 1))
{
__RSP.PCi++;
__RSP.PC[__RSP.PCi] = address;
__RSP.nextCmd = _SHIFTR( *(uint32_t*)&gfx_info.RDRAM[address], 24, 8 );
}
}
void gln64gSPBranchList( uint32_t dl )
{
uint32_t address = RSP_SegmentToPhysical( dl );
if ((address + 8) > RDRAMSize)
return;
__RSP.PC[__RSP.PCi] = address;
__RSP.nextCmd = _SHIFTR( *(uint32_t*)&gfx_info.RDRAM[address], 24, 8 );
}
void gln64gSPBranchLessZ( uint32_t branchdl, uint32_t vtx, float zval )
{
float zTest;
struct SPVertex *v = NULL;
uint32_t address = RSP_SegmentToPhysical( branchdl );
if ((address + 8) > RDRAMSize)
return;
v = (struct SPVertex*)&OGL.triangles.vertices[vtx];
zTest = v->z / v->w;
if (zTest > 1.0f || zTest <= zval)
__RSP.PC[__RSP.PCi] = address;
}
void gln64gSPDlistCount(uint32_t count, uint32_t v)
{
uint32_t address = RSP_SegmentToPhysical( v );
if (address == 0 || (address + 8) > RDRAMSize)
return;
if (__RSP.PCi >= 9)
return;
++__RSP.PCi; /* go to the next PC in the stack */
__RSP.PC[__RSP.PCi] = address; /* jump to the address */
__RSP.nextCmd = _SHIFTR( *(uint32_t*)&gfx_info.RDRAM[address], 24, 8 );
__RSP.count = count + 1;
}
void gln64gSPSetDMAOffsets( uint32_t mtxoffset, uint32_t vtxoffset )
{
gSP.DMAOffsets.mtx = mtxoffset;
gSP.DMAOffsets.vtx = vtxoffset;
}
void gln64gSPSetDMATexOffset(uint32_t _addr)
{
gSP.DMAOffsets.tex_offset = RSP_SegmentToPhysical(_addr);
gSP.DMAOffsets.tex_shift = 0;
gSP.DMAOffsets.tex_count = 0;
}
void gln64gSPSetVertexColorBase( uint32_t base )
{
gSP.vertexColorBase = RSP_SegmentToPhysical( base );
}
void gln64gSPSetVertexNormaleBase( uint32_t base )
{
gSP.vertexNormalBase = RSP_SegmentToPhysical( base );
}
void gln64gSPDMATriangles( uint32_t tris, uint32_t n )
{
unsigned int i;
int32_t v0, v1, v2;
struct SPVertex *pVtx;
DKRTriangle *triangles;
uint32_t address = RSP_SegmentToPhysical( tris );
if (address + sizeof( DKRTriangle ) * n > RDRAMSize)
return;
triangles = (DKRTriangle*)&gfx_info.RDRAM[address];
for (i = 0; i < n; i++)
{
int mode = 0;
if (!(triangles->flag & 0x40))
{
if (gSP.viewport.vscale[0] > 0)
mode |= G_CULL_BACK;
else
mode |= G_CULL_FRONT;
}
if ((gSP.geometryMode&G_CULL_BOTH) != mode)
{
gSP.geometryMode &= ~G_CULL_BOTH;
gSP.geometryMode |= mode;
gSP.changed |= CHANGED_GEOMETRYMODE;
}
v0 = triangles->v0;
v1 = triangles->v1;
v2 = triangles->v2;
OGL.triangles.vertices[v0].s = _FIXED2FLOAT( triangles->s0, 5 );
OGL.triangles.vertices[v0].t = _FIXED2FLOAT( triangles->t0, 5 );
OGL.triangles.vertices[v1].s = _FIXED2FLOAT( triangles->s1, 5 );
OGL.triangles.vertices[v1].t = _FIXED2FLOAT( triangles->t1, 5 );
OGL.triangles.vertices[v2].s = _FIXED2FLOAT( triangles->s2, 5 );
OGL.triangles.vertices[v2].t = _FIXED2FLOAT( triangles->t2, 5 );
triangles++;
}
OGL_DrawTriangles();
}
void gln64gSP1Quadrangle( int32_t v0, int32_t v1, int32_t v2, int32_t v3)
{
gln64gSPTriangle( v0, v1, v2);
gln64gSPTriangle( v0, v2, v3);
gln64gSPFlushTriangles();
}
bool gln64gSPCullVertices( uint32_t v0, uint32_t vn )
{
unsigned int i;
uint32_t clip = 0;
if (vn < v0)
{
// Aidyn Chronicles - The First Mage seems to pass parameters in reverse order.
const uint32_t v = v0;
v0 = vn;
vn = v;
}
for (i = v0 + 1; i <= vn; i++)
{
clip |= (~OGL.triangles.vertices[i].clip) & CLIP_ALL;
if (clip == CLIP_ALL)
return false;
}
return true;
}
static void _loadSpriteImage(const struct uSprite *_pSprite)
{
gSP.bgImage.address = RSP_SegmentToPhysical( _pSprite->imagePtr );
gSP.bgImage.width = _pSprite->stride;
gSP.bgImage.height = _pSprite->imageY + _pSprite->imageH;
gSP.bgImage.format = _pSprite->imageFmt;
gSP.bgImage.size = _pSprite->imageSiz;
gSP.bgImage.palette = 0;
gDP.tiles[0].textureMode = TEXTUREMODE_BGIMAGE;
gSP.bgImage.imageX = _pSprite->imageX;
gSP.bgImage.imageY = _pSprite->imageY;
gSP.bgImage.scaleW = gSP.bgImage.scaleH = 1.0f;
if (config.frameBufferEmulation.enable != 0)
{
struct FrameBuffer *pBuffer = FrameBuffer_FindBuffer(gSP.bgImage.address);
if (pBuffer != NULL)
{
gDP.tiles[0].frameBuffer = pBuffer;
gDP.tiles[0].textureMode = TEXTUREMODE_FRAMEBUFFER_BG;
gDP.tiles[0].loadType = LOADTYPE_TILE;
gDP.changed |= CHANGED_TMEM;
}
}
}
void gln64gSPSprite2DBase( uint32_t _base )
{
float z, w, scaleX, scaleY;
uint32_t flipX, flipY;
//assert(RSP.nextCmd == 0xBE);
const uint32_t address = RSP_SegmentToPhysical( _base );
struct uSprite *pSprite = (struct uSprite*)&gfx_info.RDRAM[address];
if (pSprite->tlutPtr != 0)
{
gln64gDPSetTextureImage( 0, 2, 1, pSprite->tlutPtr );
gln64gDPSetTile( 0, 2, 0, 256, 7, 0, 0, 0, 0, 0, 0, 0 );
gln64gDPLoadTLUT( 7, 0, 0, 1020, 0 );
if (pSprite->imageFmt != G_IM_FMT_RGBA)
gDP.otherMode.textureLUT = G_TT_RGBA16;
else
gDP.otherMode.textureLUT = G_TT_NONE;
} else
gDP.otherMode.textureLUT = G_TT_NONE;
_loadSpriteImage(pSprite);
gln64gSPTexture( 1.0f, 1.0f, 0, 0, true );
gDP.otherMode.texturePersp = 1;
z = (gDP.otherMode.depthSource == G_ZS_PRIM) ? gDP.primDepth.z : gSP.viewport.nearz;
w = 1.0f;
scaleX = 1.0f;
scaleY = 1.0f;
flipX = 0;
flipY = 0;
do
{
float uls, ult, lrs, lrt;
float ulx, uly, lrx, lry;
float frameX, frameY, frameW, frameH;
int32_t v0 = 0, v1 = 1, v2 = 2, v3 = 3;
struct SPVertex *vtx0, *vtx1, *vtx2, *vtx3;
uint32_t w0 = *(uint32_t*)&gfx_info.RDRAM[__RSP.PC[__RSP.PCi]];
uint32_t w1 = *(uint32_t*)&gfx_info.RDRAM[__RSP.PC[__RSP.PCi] + 4];
__RSP.cmd = _SHIFTR( w0, 24, 8 );
__RSP.PC[__RSP.PCi] += 8;
__RSP.nextCmd = _SHIFTR( *(uint32_t*)&gfx_info.RDRAM[__RSP.PC[__RSP.PCi]], 24, 8 );
if (__RSP.cmd == 0xBE )
{
/* gSPSprite2DScaleFlip */
scaleX = _FIXED2FLOAT( _SHIFTR(w1, 16, 16), 10 );
scaleY = _FIXED2FLOAT( _SHIFTR(w1, 0, 16), 10 );
flipX = _SHIFTR(w0, 8, 8);
flipY = _SHIFTR(w0, 0, 8);
continue;
}
/* gSPSprite2DDraw */
frameX = _FIXED2FLOAT(((int16_t)_SHIFTR(w1, 16, 16)), 2);
frameY = _FIXED2FLOAT(((int16_t)_SHIFTR(w1, 0, 16)), 2);
frameW = pSprite->imageW / scaleX;
frameH = pSprite->imageH / scaleY;
if (flipX != 0)
{
ulx = frameX + frameW;
lrx = frameX;
}
else
{
ulx = frameX;
lrx = frameX + frameW;
}
if (flipY != 0)
{
uly = frameY + frameH;
lry = frameY;
}
else
{
uly = frameY;
lry = frameY + frameH;
}
uls = pSprite->imageX;
ult = pSprite->imageY;
lrs = uls + pSprite->imageW - 1;
lrt = ult + pSprite->imageH - 1;
/* Hack for WCW Nitro. TODO : activate it later.
if (WCW_NITRO) {
gSP.bgImage.height /= scaleY;
gSP.bgImage.imageY /= scaleY;
ult /= scaleY;
lrt /= scaleY;
gSP.bgImage.width *= scaleY;
}
*/
vtx0 = (struct SPVertex*)&OGL.triangles.vertices[v0];
vtx0->x = ulx;
vtx0->y = uly;
vtx0->z = z;
vtx0->w = w;
vtx0->s = uls;
vtx0->t = ult;
vtx1 = (struct SPVertex*)&OGL.triangles.vertices[v1];
vtx1->x = lrx;
vtx1->y = uly;
vtx1->z = z;
vtx1->w = w;
vtx1->s = lrs;
vtx1->t = ult;
vtx2 = (struct SPVertex*)&OGL.triangles.vertices[v2];
vtx2->x = ulx;
vtx2->y = lry;
vtx2->z = z;
vtx2->w = w;
vtx2->s = uls;
vtx2->t = lrt;
vtx3 = (struct SPVertex*)&OGL.triangles.vertices[v3];
vtx3->x = lrx;
vtx3->y = lry;
vtx3->z = z;
vtx3->w = w;
vtx3->s = lrs;
vtx3->t = lrt;
OGL_DrawLLETriangle(4);
} while (__RSP.nextCmd == 0xBD || __RSP.nextCmd == 0xBE);
}
void gln64gSPCullDisplayList( uint32_t v0, uint32_t vn )
{
if (gln64gSPCullVertices( v0, vn ))
gSPEndDisplayList();
}
void gln64gSPPopMatrixN( uint32_t param, uint32_t num )
{
if (gSP.matrix.modelViewi > num - 1)
{
gSP.matrix.modelViewi -= num;
gSP.changed |= CHANGED_MATRIX;
}
}
void gln64gSPPopMatrix( uint32_t param )
{
switch (param)
{
case 0: // modelview
if (gSP.matrix.modelViewi > 0)
{
gSP.matrix.modelViewi--;
gSP.changed |= CHANGED_MATRIX;
}
break;
case 1: // projection, can't
break;
default:
break;
}
}
void gln64gSPSegment( int32_t seg, int32_t base )
{
gSP.segment[seg] = base;
}
void gln64gSPClipRatio( uint32_t r )
{
}
void gln64gSPInsertMatrix( uint32_t where, uint32_t num )
{
float fraction, integer;
if (gSP.changed & CHANGED_MATRIX)
gln64gSPCombineMatrices();
if ((where & 0x3) || (where > 0x3C))
return;
if (where < 0x20)
{
fraction = modff( gSP.matrix.combined[0][where >> 1], &integer );
gSP.matrix.combined[0][where >> 1]
= (float)_SHIFTR( num, 16, 16 ) + abs( (int)fraction );
fraction = modff( gSP.matrix.combined[0][(where >> 1) + 1], &integer );
gSP.matrix.combined[0][(where >> 1) + 1]
= (float)_SHIFTR( num, 0, 16 ) + abs( (int)fraction );
}
else
{
float newValue;
fraction = modff( gSP.matrix.combined[0][(where - 0x20) >> 1], &integer );
newValue = integer + _FIXED2FLOAT( _SHIFTR( num, 16, 16 ), 16);
// Make sure the sign isn't lost
if ((integer == 0.0f) && (fraction != 0.0f))
newValue = newValue * (fraction / abs( (int)fraction ));
gSP.matrix.combined[0][(where - 0x20) >> 1] = newValue;
fraction = modff( gSP.matrix.combined[0][((where - 0x20) >> 1) + 1], &integer );
newValue = integer + _FIXED2FLOAT( _SHIFTR( num, 0, 16 ), 16 );
// Make sure the sign isn't lost
if ((integer == 0.0f) && (fraction != 0.0f))
newValue = newValue * (fraction / abs( (int)fraction ));
gSP.matrix.combined[0][((where - 0x20) >> 1) + 1] = newValue;
}
}
void gln64gSPModifyVertex( uint32_t vtx, uint32_t where, uint32_t val )
{
int32_t v = vtx;
struct SPVertex *vtx0 = (struct SPVertex*)&OGL.triangles.vertices[v];
switch (where)
{
case G_MWO_POINT_RGBA:
vtx0->r = _SHIFTR( val, 24, 8 ) * 0.0039215689f;
vtx0->g = _SHIFTR( val, 16, 8 ) * 0.0039215689f;
vtx0->b = _SHIFTR( val, 8, 8 ) * 0.0039215689f;
vtx0->a = _SHIFTR( val, 0, 8 ) * 0.0039215689f;
break;
case G_MWO_POINT_ST:
vtx0->s = _FIXED2FLOAT( (int16_t)_SHIFTR( val, 16, 16 ), 5 ) / gSP.texture.scales;
vtx0->t = _FIXED2FLOAT( (int16_t)_SHIFTR( val, 0, 16 ), 5 ) / gSP.texture.scalet;
break;
case G_MWO_POINT_XYSCREEN:
{
float scrX = _FIXED2FLOAT( (int16_t)_SHIFTR( val, 16, 16 ), 2 );
float scrY = _FIXED2FLOAT( (int16_t)_SHIFTR( val, 0, 16 ), 2 );
vtx0->x = (scrX - gSP.viewport.vtrans[0]) / gSP.viewport.vscale[0];
vtx0->x *= vtx0->w;
vtx0->y = -(scrY - gSP.viewport.vtrans[1]) / gSP.viewport.vscale[1];
vtx0->y *= vtx0->w;
vtx0->clip &= ~(CLIP_POSX | CLIP_NEGX | CLIP_POSY | CLIP_NEGY);
}
break;
case G_MWO_POINT_ZSCREEN:
{
float scrZ = _FIXED2FLOAT((int16_t)_SHIFTR(val, 16, 16), 15);
vtx0->z = (scrZ - gSP.viewport.vtrans[2]) / (gSP.viewport.vscale[2]);
vtx0->z *= vtx0->w;
vtx0->clip &= ~CLIP_Z;
}
break;
}
}
void gln64gSPNumLights( int32_t n )
{
if (n <= 12)
{
gSP.numLights = n;
if (config.generalEmulation.enableHWLighting != 0)
gSP.changed |= CHANGED_LIGHT;
}
}
void gln64gSPLightColor( uint32_t lightNum, uint32_t packedColor )
{
lightNum--;
if (lightNum < 8)
{
gSP.lights[lightNum].r = _SHIFTR( packedColor, 24, 8 ) * 0.0039215689f;
gSP.lights[lightNum].g = _SHIFTR( packedColor, 16, 8 ) * 0.0039215689f;
gSP.lights[lightNum].b = _SHIFTR( packedColor, 8, 8 ) * 0.0039215689f;
if (config.generalEmulation.enableHWLighting != 0)
gSP.changed |= CHANGED_LIGHT;
}
}
void gln64gSPFogFactor( int16_t fm, int16_t fo )
{
gSP.fog.multiplier = fm;
gSP.fog.offset = fo;
gSP.changed |= CHANGED_FOGPOSITION;
}
void gln64gSPPerspNormalize( uint16_t scale )
{
}
void gln64gSPCoordMod(uint32_t _w0, uint32_t _w1)
{
uint32_t idx, pos;
if ((_w0&8) != 0)
return;
idx = _SHIFTR(_w0, 1, 2);
pos = _w0&0x30;
if (pos == 0)
{
gSP.vertexCoordMod[0+idx] = (float)(int16_t)_SHIFTR(_w1, 16, 16);
gSP.vertexCoordMod[1+idx] = (float)(int16_t)_SHIFTR(_w1, 0, 16);
}
else if (pos == 0x10)
{
assert(idx < 3);
gSP.vertexCoordMod[4+idx] = _SHIFTR(_w1, 16, 16)/65536.0f;
gSP.vertexCoordMod[5+idx] = _SHIFTR(_w1, 0, 16)/65536.0f;
gSP.vertexCoordMod[12+idx] = gSP.vertexCoordMod[0+idx] + gSP.vertexCoordMod[4+idx];
gSP.vertexCoordMod[13+idx] = gSP.vertexCoordMod[1+idx] + gSP.vertexCoordMod[5+idx];
} else if (pos == 0x20) {
gSP.vertexCoordMod[8+idx] = (float)(int16_t)_SHIFTR(_w1, 16, 16);
gSP.vertexCoordMod[9+idx] = (float)(int16_t)_SHIFTR(_w1, 0, 16);
}
}
void gln64gSPTexture( float sc, float tc, int32_t level, int32_t tile, int32_t on )
{
gSP.texture.on = on;
if (on == 0)
return;
gSP.texture.scales = sc;
gSP.texture.scalet = tc;
if (gSP.texture.scales == 0.0f)
gSP.texture.scales = 1.0f;
if (gSP.texture.scalet == 0.0f)
gSP.texture.scalet = 1.0f;
gSP.texture.level = level;
gSP.texture.tile = tile;
gSP.textureTile[0] = &gDP.tiles[tile];
gSP.textureTile[1] = &gDP.tiles[(tile + 1) & 7];
gSP.changed |= CHANGED_TEXTURE;
}
void gln64gSPGeometryMode( uint32_t clear, uint32_t set )
{
gSP.geometryMode = (gSP.geometryMode & ~clear) | set;
gSP.changed |= CHANGED_GEOMETRYMODE;
}
void gln64gSPSetGeometryMode( uint32_t mode )
{
gSP.geometryMode |= mode;
gSP.changed |= CHANGED_GEOMETRYMODE;
}
void gln64gSPClearGeometryMode( uint32_t mode )
{
gSP.geometryMode &= ~mode;
gSP.changed |= CHANGED_GEOMETRYMODE;
}
void gln64gSPSetOtherMode_H(uint32_t _length, uint32_t _shift, uint32_t _data)
{
const uint32_t mask = (((uint64_t)1 << _length) - 1) << _shift;
gDP.otherMode.h = (gDP.otherMode.h&(~mask)) | _data;
if (mask & 0x00300000) // cycle type
gDP.changed |= CHANGED_CYCLETYPE;
}
void gln64gSPSetOtherMode_L(uint32_t _length, uint32_t _shift, uint32_t _data)
{
const uint32_t mask = (((uint64_t)1 << _length) - 1) << _shift;
gDP.otherMode.l = (gDP.otherMode.l&(~mask)) | _data;
if (mask & 0xFFFFFFF8) // rendermode / blender bits
gDP.changed |= CHANGED_RENDERMODE;
}
void gln64gSPLine3D( int32_t v0, int32_t v1, int32_t flag )
{
OGL_DrawLine(v0, v1, 1.5f );
}
void gln64gSPLineW3D( int32_t v0, int32_t v1, int32_t wd, int32_t flag )
{
OGL_DrawLine(v0, v1, 1.5f + wd * 0.5f );
}
static
void _loadBGImage(const struct uObjScaleBg * _bgInfo, bool _loadScale)
{
uint32_t imageW, imageH;
gSP.bgImage.address = RSP_SegmentToPhysical( _bgInfo->imagePtr );
imageW = _bgInfo->imageW >> 2;
gSP.bgImage.width = imageW - imageW%2;
imageH = _bgInfo->imageH >> 2;
gSP.bgImage.height = imageH - imageH%2;
gSP.bgImage.format = _bgInfo->imageFmt;
gSP.bgImage.size = _bgInfo->imageSiz;
gSP.bgImage.palette = _bgInfo->imagePal;
gDP.tiles[0].textureMode = TEXTUREMODE_BGIMAGE;
gSP.bgImage.imageX = _FIXED2FLOAT( _bgInfo->imageX, 5 );
gSP.bgImage.imageY = _FIXED2FLOAT( _bgInfo->imageY, 5 );
if (_loadScale) {
gSP.bgImage.scaleW = _FIXED2FLOAT( _bgInfo->scaleW, 10 );
gSP.bgImage.scaleH = _FIXED2FLOAT( _bgInfo->scaleH, 10 );
} else
gSP.bgImage.scaleW = gSP.bgImage.scaleH = 1.0f;
if (config.frameBufferEmulation.enable)
{
struct FrameBuffer *pBuffer = FrameBuffer_FindBuffer(gSP.bgImage.address);
/* TODO/FIXME */
if ((pBuffer != NULL) && pBuffer->m_size == gSP.bgImage.size && (/* !pBuffer->m_isDepthBuffer || */ pBuffer->m_changed))
{
gDP.tiles[0].frameBuffer = pBuffer;
gDP.tiles[0].textureMode = TEXTUREMODE_FRAMEBUFFER_BG;
gDP.tiles[0].loadType = LOADTYPE_TILE;
gDP.changed |= CHANGED_TMEM;
}
}
}
struct ObjCoordinates
{
float ulx, uly, lrx, lry;
float uls, ult, lrs, lrt;
float z, w;
};
struct ObjData
{
float scaleW;
float scaleH;
uint32_t imageW;
uint32_t imageH;
float X0;
float X1;
float Y0;
float Y1;
bool flipS, flipT;
};
void ObjData_new(struct ObjData *obj, const struct uObjSprite *_pObjSprite)
{
obj->scaleW = _FIXED2FLOAT(_pObjSprite->scaleW, 10);
obj->scaleH = _FIXED2FLOAT(_pObjSprite->scaleH, 10);
obj->imageW = _pObjSprite->imageW >> 5;
obj->imageH = _pObjSprite->imageH >> 5;
obj->X0 = _FIXED2FLOAT(_pObjSprite->objX, 2);
obj->X1 = obj->X0 + obj->imageW / obj->scaleW;
obj->Y0 = _FIXED2FLOAT(_pObjSprite->objY, 2);
obj->Y1 = obj->Y0 + obj->imageH / obj->scaleH;
obj->flipS = (_pObjSprite->imageFlags & 0x01) != 0;
obj->flipT = (_pObjSprite->imageFlags & 0x10) != 0;
}
void ObjCoordinates_new(struct ObjCoordinates *obj, const struct uObjSprite *_pObjSprite, bool _useMatrix)
{
struct ObjData data;
ObjData_new(&data, _pObjSprite);
obj->ulx = data.X0;
obj->lrx = data.X1;
obj->uly = data.Y0;
obj->lry = data.Y1;
if (_useMatrix)
{
obj->ulx = obj->ulx / gSP.objMatrix.baseScaleX + gSP.objMatrix.X;
obj->lrx = obj->lrx / gSP.objMatrix.baseScaleX + gSP.objMatrix.X;
obj->uly = obj->uly / gSP.objMatrix.baseScaleY + gSP.objMatrix.Y;
obj->lry = obj->lry / gSP.objMatrix.baseScaleY + gSP.objMatrix.Y;
}
obj->uls = obj->ult = 0;
obj->lrs = data.imageW - 1;
obj->lrt = data.imageH - 1;
if (data.flipS)
{
obj->uls = obj->lrs;
obj->lrs = 0;
}
if (data.flipT)
{
obj->ult = obj->lrt;
obj->lrt = 0;
}
obj->z = (gDP.otherMode.depthSource == G_ZS_PRIM) ? gDP.primDepth.z : gSP.viewport.nearz;
obj->w = 1.0f;
}
void ObjCoordinates2_new(struct ObjCoordinates *obj, const struct uObjScaleBg * _pObjScaleBg)
{
const float frameX = _FIXED2FLOAT(_pObjScaleBg->frameX, 2);
const float frameY = _FIXED2FLOAT(_pObjScaleBg->frameY, 2);
const float frameW = _FIXED2FLOAT(_pObjScaleBg->frameW, 2);
const float frameH = _FIXED2FLOAT(_pObjScaleBg->frameH, 2);
const float imageX = gSP.bgImage.imageX;
const float imageY = gSP.bgImage.imageY;
const float imageW = (float)(_pObjScaleBg->imageW>>2);
const float imageH = (float)(_pObjScaleBg->imageH >> 2);
// const float imageW = (float)gSP.bgImage.width;
// const float imageH = (float)gSP.bgImage.height;
const float scaleW = gSP.bgImage.scaleW;
const float scaleH = gSP.bgImage.scaleH;
obj->ulx = frameX;
obj->uly = frameY;
obj->lrx = frameX + MIN(imageW/scaleW, frameW) - 1.0f;
obj->lry = frameY + MIN(imageH/scaleH, frameH) - 1.0f;
if (gDP.otherMode.cycleType == G_CYC_COPY)
{
obj->lrx += 1.0f;
obj->lry += 1.0f;;
}
obj->uls = imageX;
obj->ult = imageY;
obj->lrs = obj->uls + (obj->lrx - obj->ulx) * scaleW;
obj->lrt = obj->ult + (obj->lry - obj->uly) * scaleH;
if (gDP.otherMode.cycleType != G_CYC_COPY)
{
if ((gSP.objRendermode&G_OBJRM_SHRINKSIZE_1) != 0)
{
obj->lrs -= 1.0f / scaleW;
obj->lrt -= 1.0f / scaleH;
}
else if ((gSP.objRendermode&G_OBJRM_SHRINKSIZE_2) != 0)
{
obj->lrs -= 1.0f;
obj->lrt -= 1.0f;
}
}
if ((_pObjScaleBg->imageFlip & 0x01) != 0)
{
obj->ulx = obj->lrx;
obj->lrx = frameX;
}
obj->z = (gDP.otherMode.depthSource == G_ZS_PRIM) ? gDP.primDepth.z : gSP.viewport.nearz;
obj->w = 1.0f;
}
static void gln64gSPDrawObjRect(const struct ObjCoordinates *_coords)
{
struct SPVertex *vtx0, *vtx1, *vtx2, *vtx3;
uint32_t v0 = 0, v1 = 1, v2 = 2, v3 = 3;
vtx0 = (struct SPVertex*)&OGL.triangles.vertices[v0];
vtx0->x = _coords->ulx;
vtx0->y = _coords->uly;
vtx0->z = _coords->z;
vtx0->w = _coords->w;
vtx0->s = _coords->uls;
vtx0->t = _coords->ult;
vtx1 = (struct SPVertex*)&OGL.triangles.vertices[v1];
vtx1->x = _coords->lrx;
vtx1->y = _coords->uly;
vtx1->z = _coords->z;
vtx1->w = _coords->w;
vtx1->s = _coords->lrs;
vtx1->t = _coords->ult;
vtx2 = (struct SPVertex*)&OGL.triangles.vertices[v2];
vtx2->x = _coords->ulx;
vtx2->y = _coords->lry;
vtx2->z = _coords->z;
vtx2->w = _coords->w;
vtx2->s = _coords->uls;
vtx2->t = _coords->lrt;
vtx3 = (struct SPVertex*)&OGL.triangles.vertices[v3];
vtx3->x = _coords->lrx;
vtx3->y = _coords->lry;
vtx3->z = _coords->z;
vtx3->w = _coords->w;
vtx3->s = _coords->lrs;
vtx3->t = _coords->lrt;
OGL_DrawLLETriangle(4);
gDP.colorImage.height = (uint32_t)(MAX(gDP.colorImage.height, (uint32_t)gDP.scissor.lry));
}
void gln64gSPBgRect1Cyc( uint32_t _bg )
{
struct ObjCoordinates objCoords;
const uint32_t address = RSP_SegmentToPhysical( _bg );
struct uObjScaleBg *objScaleBg = (struct uObjScaleBg*)&gfx_info.RDRAM[address];
_loadBGImage(objScaleBg, true);
#ifdef GL_IMAGE_TEXTURES_SUPPORT
if (gSP.bgImage.address == gDP.depthImageAddress || depthBufferList().findBuffer(gSP.bgImage.address) != NULL)
_copyDepthBuffer();
// Zelda MM uses depth buffer copy in LoT and in pause screen.
// In later case depth buffer is used as temporal color buffer, and usual rendering must be used.
// Since both situations are hard to distinguish, do the both depth buffer copy and bg rendering.
#endif // GL_IMAGE_TEXTURES_SUPPORT
gDP.otherMode.cycleType = G_CYC_1CYCLE;
gDP.changed |= CHANGED_CYCLETYPE;
gln64gSPTexture(1.0f, 1.0f, 0, 0, true);
gDP.otherMode.texturePersp = 1;
ObjCoordinates2_new(&objCoords, objScaleBg);
gln64gSPDrawObjRect(&objCoords);
}
void gln64gSPBgRectCopy( uint32_t _bg )
{
struct ObjCoordinates objCoords;
const uint32_t address = RSP_SegmentToPhysical( _bg );
struct uObjScaleBg *objBg = (struct uObjScaleBg*)&gfx_info.RDRAM[address];
_loadBGImage(objBg, false);
#ifdef GL_IMAGE_TEXTURES_SUPPORT
if (gSP.bgImage.address == gDP.depthImageAddress || depthBufferList().findBuffer(gSP.bgImage.address) != NULL)
_copyDepthBuffer();
// See comment to gSPBgRect1Cyc
#endif // GL_IMAGE_TEXTURES_SUPPORT
gln64gSPTexture( 1.0f, 1.0f, 0, 0, true );
gDP.otherMode.texturePersp = 1;
ObjCoordinates2_new(&objCoords, objBg);
gln64gSPDrawObjRect(&objCoords);
}
void gln64gSPObjLoadTxtr( uint32_t tx )
{
uint32_t address = RSP_SegmentToPhysical( tx );
uObjTxtr *objTxtr = (uObjTxtr*)&gfx_info.RDRAM[address];
if ((gSP.status[objTxtr->block.sid >> 2] & objTxtr->block.mask) != objTxtr->block.flag)
{
switch (objTxtr->block.type)
{
case G_OBJLT_TXTRBLOCK:
gln64gDPSetTextureImage( 0, 1, 0, objTxtr->block.image );
gln64gDPSetTile( 0, 1, 0, objTxtr->block.tmem, 7, 0, 0, 0, 0, 0, 0, 0 );
gln64gDPLoadBlock( 7, 0, 0, ((objTxtr->block.tsize + 1) << 3) - 1, objTxtr->block.tline );
break;
case G_OBJLT_TXTRTILE:
gln64gDPSetTextureImage( 0, 1, (objTxtr->tile.twidth + 1) << 1, objTxtr->tile.image );
gln64gDPSetTile( 0, 1, (objTxtr->tile.twidth + 1) >> 2, objTxtr->tile.tmem, 7, 0, 0, 0, 0, 0, 0, 0 );
gln64gDPLoadTile( 7, 0, 0, (((objTxtr->tile.twidth + 1) << 1) - 1) << 2, (((objTxtr->tile.theight + 1) >> 2) - 1) << 2 );
break;
case G_OBJLT_TLUT:
gln64gDPSetTextureImage( 0, 2, 1, objTxtr->tlut.image );
gln64gDPSetTile( 0, 2, 0, objTxtr->tlut.phead, 7, 0, 0, 0, 0, 0, 0, 0 );
gln64gDPLoadTLUT( 7, 0, 0, objTxtr->tlut.pnum << 2, 0 );
break;
}
gSP.status[objTxtr->block.sid >> 2] = (gSP.status[objTxtr->block.sid >> 2] & ~objTxtr->block.mask) | (objTxtr->block.flag & objTxtr->block.mask);
}
}
static void gln64gSPSetSpriteTile(const struct uObjSprite *_pObjSprite)
{
const uint32_t w = MAX(_pObjSprite->imageW >> 5, 1);
const uint32_t h = MAX(_pObjSprite->imageH >> 5, 1);
gln64gDPSetTile( _pObjSprite->imageFmt, _pObjSprite->imageSiz, _pObjSprite->imageStride, _pObjSprite->imageAdrs, 0, _pObjSprite->imagePal, G_TX_CLAMP, G_TX_CLAMP, 0, 0, 0, 0 );
gln64gDPSetTileSize( 0, 0, 0, (w - 1) << 2, (h - 1) << 2 );
gln64gSPTexture( 1.0f, 1.0f, 0, 0, true );
gDP.otherMode.texturePersp = 1;
}
static void _drawYUVImageToFrameBuffer(const struct ObjCoordinates *_objCoords)
{
uint16_t h, w;
uint32_t width, height, *mb, *dst;
struct FrameBuffer *pBuffer;
const uint32_t ulx = (uint32_t)_objCoords->ulx;
const uint32_t uly = (uint32_t)_objCoords->uly;
const uint32_t lrx = (uint32_t)_objCoords->lrx;
const uint32_t lry = (uint32_t)_objCoords->lry;
const uint32_t ci_width = gDP.colorImage.width;
const uint32_t ci_height = gDP.colorImage.height;
if (ulx >= ci_width)
return;
if (uly >= ci_height)
return;
width = 16;
height = 16;
if (lrx > ci_width)
width = ci_width - ulx;
if (lry > ci_height)
height = ci_height - uly;
mb = (uint32_t*)(gfx_info.RDRAM + gDP.textureImage.address); //pointer to the first macro block
dst = (uint32_t*)(gfx_info.RDRAM + gDP.colorImage.address);
dst += ulx + uly * ci_width;
/* YUV macro block contains 16x16 texture.
* we need to put it in the proper place inside cimg */
for (h = 0; h < 16; h++)
{
for (w = 0; w < 16; w += 2)
{
uint32_t t = *(mb++); //each uint32_t contains 2 pixels
if ((h < height) && (w < width)) //clipping. texture image may be larger than color image
{
uint8_t y0 = (uint8_t)t & 0xFF;
uint8_t v = (uint8_t)(t >> 8) & 0xFF;
uint8_t y1 = (uint8_t)(t >> 16) & 0xFF;
uint8_t u = (uint8_t)(t >> 24) & 0xFF;
*(dst++) = YUVtoRGBA16(y0, u, v);
*(dst++) = YUVtoRGBA16(y1, u, v);
}
}
dst += ci_width - 16;
}
pBuffer = FrameBuffer_GetCurrent();
if (pBuffer != NULL)
{
#if 0
pBuffer->m_isOBScreen = true;
#endif
}
}
void gln64gSPObjRectangle(uint32_t _sp)
{
struct ObjCoordinates objCoords;
const uint32_t address = RSP_SegmentToPhysical(_sp);
struct uObjSprite *objSprite = (struct uObjSprite*)&gfx_info.RDRAM[address];
gln64gSPSetSpriteTile(objSprite);
ObjCoordinates_new(&objCoords, objSprite, false);
gln64gSPDrawObjRect(&objCoords);
}
void gln64gSPObjRectangleR(uint32_t _sp)
{
struct ObjCoordinates objCoords;
const uint32_t address = RSP_SegmentToPhysical(_sp);
const struct uObjSprite *objSprite = (struct uObjSprite*)&gfx_info.RDRAM[address];
gln64gSPSetSpriteTile(objSprite);
ObjCoordinates_new(&objCoords, objSprite, true);
if (objSprite->imageFmt == G_IM_FMT_YUV && (config.generalEmulation.hacks & hack_Ogre64)) //Ogre Battle needs to copy YUV texture to frame buffer
_drawYUVImageToFrameBuffer(&objCoords);
gln64gSPDrawObjRect(&objCoords);
}
void gln64gSPObjSprite( uint32_t _sp )
{
struct SPVertex *vtx0, *vtx1, *vtx2, *vtx3;
float uls, lrs, ult, lrt;
float z;
int32_t v0, v1, v2, v3;
float ulx, uly, lrx, lry;
struct ObjData data;
const uint32_t address = RSP_SegmentToPhysical( _sp );
struct uObjSprite *objSprite = (struct uObjSprite*)&gfx_info.RDRAM[address];
gln64gSPSetSpriteTile(objSprite);
ObjData_new(&data, objSprite);
ulx = data.X0;
uly = data.Y0;
lrx = data.X1;
lry = data.Y1;
uls = 0;
lrs = data.imageW - 1;
ult = 0;
lrt = data.imageH - 1;
if (objSprite->imageFlags & 0x01) { // flipS
uls = lrs;
lrs = 0;
}
if (objSprite->imageFlags & 0x10) { // flipT
ult = lrt;
lrt = 0;
}
z = (gDP.otherMode.depthSource == G_ZS_PRIM) ? gDP.primDepth.z : gSP.viewport.nearz;
v0 = 0;
v1 = 1;
v2 = 2;
v3 = 3;
vtx0 = (struct SPVertex*)&OGL.triangles.vertices[v0];
vtx0->x = gSP.objMatrix.A * ulx + gSP.objMatrix.B * uly + gSP.objMatrix.X;
vtx0->y = gSP.objMatrix.C * ulx + gSP.objMatrix.D * uly + gSP.objMatrix.Y;
vtx0->z = z;
vtx0->w = 1.0f;
vtx0->s = uls;
vtx0->t = ult;
vtx1 = (struct SPVertex*)&OGL.triangles.vertices[v1];
vtx1->x = gSP.objMatrix.A * lrx + gSP.objMatrix.B * uly + gSP.objMatrix.X;
vtx1->y = gSP.objMatrix.C * lrx + gSP.objMatrix.D * uly + gSP.objMatrix.Y;
vtx1->z = z;
vtx1->w = 1.0f;
vtx1->s = lrs;
vtx1->t = ult;
vtx2 = (struct SPVertex*)&OGL.triangles.vertices[v2];
vtx2->x = gSP.objMatrix.A * ulx + gSP.objMatrix.B * lry + gSP.objMatrix.X;
vtx2->y = gSP.objMatrix.C * ulx + gSP.objMatrix.D * lry + gSP.objMatrix.Y;
vtx2->z = z;
vtx2->w = 1.0f;
vtx2->s = uls;
vtx2->t = lrt;
vtx3 = (struct SPVertex*)&OGL.triangles.vertices[v3];
vtx3->x = gSP.objMatrix.A * lrx + gSP.objMatrix.B * lry + gSP.objMatrix.X;
vtx3->y = gSP.objMatrix.C * lrx + gSP.objMatrix.D * lry + gSP.objMatrix.Y;
vtx3->z = z;
vtx3->w = 1.0f;
vtx3->s = lrs;
vtx3->t = lrt;
OGL_DrawLLETriangle(4);
#ifdef NEW
/* TODO/FIXME */
frameBufferList().setBufferChanged();
#endif
gDP.colorImage.height = (uint32_t)(MAX( gDP.colorImage.height, (uint32_t)gDP.scissor.lry ));
}
void gln64gSPObjLoadTxSprite( uint32_t txsp )
{
gln64gSPObjLoadTxtr( txsp );
gln64gSPObjSprite( txsp + sizeof( uObjTxtr ) );
}
void gln64gSPObjLoadTxRect(uint32_t txsp)
{
gln64gSPObjLoadTxtr(txsp);
gln64gSPObjRectangle(txsp + sizeof(uObjTxtr));
}
void gln64gSPObjLoadTxRectR( uint32_t txsp )
{
gln64gSPObjLoadTxtr( txsp );
gln64gSPObjRectangleR( txsp + sizeof( uObjTxtr ) );
}
void gln64gSPObjMatrix( uint32_t mtx )
{
uint32_t address = RSP_SegmentToPhysical( mtx );
uObjMtx *objMtx = (uObjMtx*)&gfx_info.RDRAM[address];
gSP.objMatrix.A = _FIXED2FLOAT( objMtx->A, 16 );
gSP.objMatrix.B = _FIXED2FLOAT( objMtx->B, 16 );
gSP.objMatrix.C = _FIXED2FLOAT( objMtx->C, 16 );
gSP.objMatrix.D = _FIXED2FLOAT( objMtx->D, 16 );
gSP.objMatrix.X = _FIXED2FLOAT( objMtx->X, 2 );
gSP.objMatrix.Y = _FIXED2FLOAT( objMtx->Y, 2 );
gSP.objMatrix.baseScaleX = _FIXED2FLOAT( objMtx->BaseScaleX, 10 );
gSP.objMatrix.baseScaleY = _FIXED2FLOAT( objMtx->BaseScaleY, 10 );
}
void gln64gSPObjSubMatrix( uint32_t mtx )
{
uint32_t address = RSP_SegmentToPhysical(mtx);
uObjSubMtx *objMtx = (uObjSubMtx*)&gfx_info.RDRAM[address];
gSP.objMatrix.X = _FIXED2FLOAT(objMtx->X, 2);
gSP.objMatrix.Y = _FIXED2FLOAT(objMtx->Y, 2);
gSP.objMatrix.baseScaleX = _FIXED2FLOAT(objMtx->BaseScaleX, 10);
gSP.objMatrix.baseScaleY = _FIXED2FLOAT(objMtx->BaseScaleY, 10);
}
void gln64gSPObjRendermode(uint32_t _mode)
{
gSP.objRendermode = _mode;
}
void (*gln64gSPTransformVertex)(float vtx[4], float mtx[4][4]) = gln64gSPTransformVertex_default;
void (*gln64gSPLightVertex)(void *data) = gln64gSPLightVertex_default;
void (*gln64gSPPointLightVertex)(void *data, float * _vPos) = gln64gSPPointLightVertex_default;
void (*gln64gSPBillboardVertex)(uint32_t v, uint32_t i) = gln64gSPBillboardVertex_default;
void gSPSetupFunctions(void)
{
if (GBI_GetCurrentMicrocodeType() != F3DEX2CBFD)
{
gln64gSPLightVertex = gln64gSPLightVertex_default;
gln64gSPPointLightVertex = gln64gSPPointLightVertex_default;
return;
}
gln64gSPLightVertex = gln64gSPLightVertex_CBFD;
gln64gSPPointLightVertex = gln64gSPPointLightVertex_CBFD;
}
|
lcl0512/lcl_Java | donation/src/main/java/com/lcl/donation/service/vo/response/RespDonationInfoVo.java | package com.lcl.donation.service.vo.response;
import com.lcl.donation.entity.ItemList;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
@Setter
@Getter
@ToString
public class RespDonationInfoVo implements Serializable {
private String projectName;
private Integer projectStatus;
private LocalDateTime createTime;
private String status;
private String type;
private List<ItemList> responseItemListVoList;
private Integer id;
private Integer userId;
private Integer projectId;
private String projectDesc;
private String donor;
private LocalDateTime time;
private String donateNum;
private String companyName;
}
|
darosh/gridy-games-lib | dist/es6/games/Hex7Game.js | <reponame>darosh/gridy-games-lib
import { HexagonalGrid, Shape } from 'gridy';
import { landscapeHex } from '../utils';
import { HexGameBase } from './base/HexGameBase';
export class Hex7Game extends HexGameBase {
constructor() {
super(landscapeHex(new HexagonalGrid(1, undefined, Shape.Rhombus, 7)));
}
}
Hex7Game.title = 'Hex 7x7';
Hex7Game.group = 'Hex';
Hex7Game.original = 'HexGame';
Hex7Game.sample = 'c7, c6, c5, a4, f1, e7, c3, g4, g3, g2, a6, e2, d5, f5, f4, d3, e4, g7, b5';
//# sourceMappingURL=Hex7Game.js.map |
jass2/historyforge-1 | app/helpers/census_records_helper.rb | module CensusRecordsHelper
def census_card_edit(title: nil, list: nil)
header = title && content_tag(:div, title, class: 'card-header')
slider = content_tag :div, list.join('').html_safe, class: 'census-slider vertical'
wrapped_slider = content_tag :div, slider, class: 'census-slider-wrapper'
body = content_tag :div, wrapped_slider, class: 'card-body'
content_tag(:div, header + body, class: 'card mb-3')
end
def census_card_show(title: nil, list: nil)
header = title && content_tag(:div, title, class: 'card-header')
body = content_tag(
:ul,
list.map { |item| content_tag(:li, item, class: 'list-group-item')}.join('').html_safe,
class: 'list-group list-group-flush'
)
content_tag(:div, header + body, class: 'card mb-3')
end
def editing_users_for(item)
user_ids = item.versions.map(&:whodunnit).compact.map(&:to_i)
User.where(id: user_ids).each_with_object({}) { |u, o| o[u.id.to_s] = u.login }
end
def census_form_renderer
"Census#{controller.year}FormFields".constantize
end
def translated_label(klass, key)
Translator.label(klass, key)
end
def translated_option(attribute_name, item)
Translator.option(attribute_name, item)
end
def select_options_for(collection)
[%w[blank nil]] + collection.zip(collection)
end
def yes_no_choices
[['Left blank', nil], ['Yes', true], ['No', false]]
end
def yes_no_na(value)
if value.nil?
'blank'
else
value ? 'yes' : 'no'
end
end
def is_1900?
controller.year == 1900
end
def is_1910?
controller.year == 1910
end
def is_1920?
controller.year == 1920
end
def is_1930?
controller.year == 1930
end
def is_1940?
controller.year == 1940
end
def aggregate_chart_data(data)
sorted = data.sort_by(&:last).reverse
if sorted.length < 10
sorted
else
sorted[0..10] << ['Other', sorted[11..].map(&:last).sum]
end
end
end
|
liuxc123/GTUIKit | components/CommonComponent/Dialogs/src/UIViewController+GTUIDialogs.h | <filename>components/CommonComponent/Dialogs/src/UIViewController+GTUIDialogs.h<gh_stars>1-10
//
// UIViewController+GTUIDialogs.h
// GTCatalog
//
// Created by liuxc on 2018/11/22.
//
#import <UIKit/UIKit.h>
@class GTUIDialogPresentationController;
@interface UIViewController (GTUIDialogs)
/**
The dialog presentation controller that is managing the current view controller.
@return nil if the view controller is not managed by a Material dialog presentaiton controller.
*/
@property(nonatomic, nullable, readonly) GTUIDialogPresentationController *gtui_dialogPresentationController;
@end
|
arqex/react-urlstack | react-urlstack-playground/src/components/gallery/ui/ListItem.js | import React from 'react';
import {
StyleSheet,
View,
Text,
} from 'react-native';
import Hoverable from '../interactions/Hoverable'
export default ( props ) => {
let mainContent = props.mainContent;
if( !mainContent ){
mainContent = (
<View style={ [ styles.mainContent, props.mainStyle ] }>
<Text style={ styles.title }>{ props.title }</Text>
{ optionalRender( props.subtitle, 'subtitle', Text ) }
</View>
)
}
let containerStyle = [
styles.container, props.containerStyle
]
return (
<Hoverable onPress={ e => props.onPress && props.onPress(e) } style={ containerStyle } hoverStyle={ props.hoverStyle } >
{ optionalRender( props.leftContent, 'left' ) }
{ mainContent }
{ optionalRender( props.rightContent, 'right' ) }
</Hoverable>
)
}
function optionalRender( content, style, Component = Text ){
if( !content ) return
return (
<Component style={ style[style] }>{ content }</Component>
)
}
const styles = StyleSheet.create({
container: {
padding: 10,
flexDirection: 'row',
backgroundColor: 'white',
borderBottomColor: '#eee',
borderBottomWidth: 1,
alignItems: 'center'
},
mainContent: {
flex: 1,
flexGrow: 1,
flexDirection: 'column',
},
leftContent: {
},
rightContent: {
},
title: {
fontSize: 16,
fontWeight: '400',
},
subtitle: {
fontSize: 14,
fontWeight: '300',
color: '#666'
}
}) |
gimmetm/ncloud-sdk-go-v2 | services/vmssql/cloud_mssql_character_set.go | /*
* vmssql
*
* <br/>https://ncloud.apigw.ntruss.com/vmssql/v2
*
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package vmssql
type CloudMssqlCharacterSet struct {
// 조회된 리스트의 총 개수
TotalRows *int32 `json:"totalRows,omitempty"`
// 문자셋 이름
CharacterSetName *string `json:"characterSetName,omitempty"`
}
|
eniac/MimicNet | simulate/homatransport/src/common/GlobalSignalListener.cc | //
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <algorithm>
#include "GlobalSignalListener.h"
#include "application/WorkloadSynthesizer.h"
#include "transport/HomaTransport.h"
Define_Module(GlobalSignalListener);
simsignal_t GlobalSignalListener::bytesOnWireSignal =
registerSignal("bytesOnWire");
GlobalSignalListener::GlobalSignalListener()
: stabilityRecorder(NULL)
, appStatsListener(NULL)
, activeSchedsListener(NULL)
, selfWastedBwListeners()
, mesgBytesOnWireSignals()
, mesgLatencySignals()
, mesgStretchSignals()
, mesgQueueDelaySignals()
, mesgTransportSchedDelaySignals()
{}
GlobalSignalListener::~GlobalSignalListener()
{
delete stabilityRecorder;
delete appStatsListener;
delete activeSchedsListener;
for (auto iter : selfWastedBwListeners) {
delete iter;
}
}
void
GlobalSignalListener::initialize()
{
stabilityRecorder = new StabilityRecorder(this);
appStatsListener = new AppStatsListener(this);
activeSchedsListener = new ActiveSchedsListener(this);
selfWastedBwListeners.push_back(new SelfWastedBandwidthListener(this,
"higherRxSelfWasteTime", "highrSelfBwWaste"));
selfWastedBwListeners.push_back(new SelfWastedBandwidthListener(this,
"lowerRxSelfWasteTime", "lowerSelfBwWaste"));
}
void
GlobalSignalListener::finish()
{
activeSchedsListener->dumpStats();
}
void
GlobalSignalListener::handleMessage(cMessage *msg)
{
throw cRuntimeError("GlobalSignalListener shouldn't receive any message!");
}
void
GlobalSignalListener::handleMesgStatsObj(cObject* obj)
{
auto* mesgStats = dynamic_cast<MesgStats*>(obj);
uint64_t mesgSizeBin = mesgStats->mesgSizeBin;
simtime_t latency = mesgStats->latency;
double stretch = mesgStats->stretch;
double queueDelay = mesgStats->queuingDelay;
simtime_t transptSchedDelay = mesgStats->transportSchedDelay;
uint64_t mesgSizeOnWire = mesgStats->mesgSizeOnWire;
emit(bytesOnWireSignal, mesgSizeOnWire);
if (mesgLatencySignals.find(mesgSizeBin) == mesgLatencySignals.end()) {
std::string sizeUpperBound;
if (mesgSizeBin != UINT64_MAX) {
sizeUpperBound = std::to_string(mesgSizeBin);
} else {
sizeUpperBound = "Huge";
}
char bytesOnWireSigName[50];
sprintf(bytesOnWireSigName,
"mesg%sBytesOnWire", sizeUpperBound.c_str());
simsignal_t bytesOnWireSig = registerSignal(bytesOnWireSigName);
mesgBytesOnWireSignals[mesgSizeBin] = bytesOnWireSig;
char bytesOnWireStatsName[50];
sprintf(bytesOnWireStatsName, "mesg%sBytesOnWire",
sizeUpperBound.c_str());
cProperty *statisticTemplate =
getProperties()->get("statisticTemplate", "mesgBytesOnWire");
ev.addResultRecorders(this, bytesOnWireSig, bytesOnWireStatsName,
statisticTemplate);
char latencySignalName[50];
sprintf(latencySignalName, "mesg%sDelay", sizeUpperBound.c_str());
simsignal_t latencySignal = registerSignal(latencySignalName);
mesgLatencySignals[mesgSizeBin] = latencySignal;
char latencyStatsName[50];
sprintf(latencyStatsName, "mesg%sDelay", sizeUpperBound.c_str());
statisticTemplate =
getProperties()->get("statisticTemplate", "mesgDelay");
ev.addResultRecorders(this, latencySignal, latencyStatsName,
statisticTemplate);
char stretchSignalName[50];
sprintf(stretchSignalName, "mesg%sStretch", sizeUpperBound.c_str());
simsignal_t stretchSignal = registerSignal(stretchSignalName);
mesgStretchSignals[mesgSizeBin] = stretchSignal;
char stretchStatsName[50];
sprintf(stretchStatsName, "mesg%sStretch", sizeUpperBound.c_str());
statisticTemplate = getProperties()->get("statisticTemplate",
"mesgStretch");
ev.addResultRecorders(this, stretchSignal, stretchStatsName,
statisticTemplate);
char queueDelaySignalName[50];
sprintf(queueDelaySignalName, "mesg%sQueueDelay",
sizeUpperBound.c_str());
simsignal_t queueDelaySignal = registerSignal(queueDelaySignalName);
mesgQueueDelaySignals[mesgSizeBin] = queueDelaySignal;
char queueDelayStatsName[50];
sprintf(queueDelayStatsName, "mesg%sQueueDelay",
sizeUpperBound.c_str());
statisticTemplate = getProperties()->get("statisticTemplate",
"mesgQueueDelay");
ev.addResultRecorders(this, queueDelaySignal, queueDelayStatsName,
statisticTemplate);
char transportSchedDelaySignalName[50];
sprintf(transportSchedDelaySignalName, "mesg%sTransportSchedDelay",
sizeUpperBound.c_str());
simsignal_t transportSchedDelaySignal =
registerSignal(transportSchedDelaySignalName);
mesgTransportSchedDelaySignals[mesgSizeBin] =
transportSchedDelaySignal;
char transportSchedDelayStatsName[50];
sprintf(transportSchedDelayStatsName, "mesg%sTransportSchedDelay",
sizeUpperBound.c_str());
statisticTemplate = getProperties()->get("statisticTemplate",
"mesgTransportSchedDelay");
ev.addResultRecorders(this, transportSchedDelaySignal,
transportSchedDelayStatsName, statisticTemplate);
}
emit(mesgBytesOnWireSignals.at(mesgSizeBin), mesgSizeOnWire);
emit(mesgLatencySignals.at(mesgSizeBin), latency);
emit(mesgStretchSignals.at(mesgSizeBin), stretch);
emit(mesgQueueDelaySignals.at(mesgSizeBin), queueDelay);
emit(mesgTransportSchedDelaySignals.at(mesgSizeBin), transptSchedDelay);
}
GlobalSignalListener::StabilityRecorder::StabilityRecorder(
GlobalSignalListener* parentModule)
: parentModule(parentModule)
, totalSendBacklog(0)
, callCount(0)
, lastSampleTime(SIMTIME_ZERO)
, sendBacklog()
{
// Register this object as a listner to stabilitySignal defined in
// HomaTransport.
simulation.getSystemModule()->subscribe("stabilitySignal", this);
sendBacklog.setName("backlogged transmit messages");
}
/**
* Every time stabilitySignal is emitted, this function is called. It aggregates
* number of the incomplete transmit messages over all transport instances in
* the simulation and records the total number in the vector result file.
*/
void
GlobalSignalListener::StabilityRecorder::receiveSignal(cComponent* src,
simsignal_t id, unsigned long l)
{
simtime_t currentTime = simTime();
totalSendBacklog += l;
callCount++;
if (currentTime != lastSampleTime) {
// record totalSendBacklog at lastSampleTime to result vector.
sendBacklog.recordWithTimestamp(lastSampleTime, totalSendBacklog);
lastSampleTime = currentTime;
totalSendBacklog = 0;
}
}
/**
* Listener for the WorkloadSynthesizer::mesgStatsSignal. This listener collect
* the end-to-end message stats carried in the signal and record the aggregated
* stats for all instances of WorkloadSynthesizer.
*/
GlobalSignalListener::AppStatsListener::AppStatsListener(
GlobalSignalListener* parentMod)
: parentModule(parentMod)
{
// Register this object as a listener to the "msgStats" singal
// WorkloadSynthesizer fire. This signal contains the end-to-end stats
// collected at "WorkloadSynthesizer" instances.
simulation.getSystemModule()->subscribe("mesgStats", this);
}
/**
* Signal receiver implementation.
*/
void
GlobalSignalListener::AppStatsListener::receiveSignal(cComponent* src,
simsignal_t id, cObject* obj)
{
// auto* mesgStats = dynamic_cast<MesgStats*>(obj);
// auto* srcMod = dynamic_cast<cModule*>(src);
// std::cout << "Received MesgStats signal from: " << srcMod->getFullPath() <<
// ", mesg size: " << mesgStats->mesgSize << ", SizeOnWire: " <<
// mesgStats->mesgSizeOnWire << ", size bin: " << mesgStats->mesgSizeBin <<
// ", latency: " << mesgStats->latency << ", stretch: " <<
// mesgStats->stretch << ", queueDelay: " <<
// mesgStats->queuingDelay << // ", transportSchedDelay: " <<
// mesgStats->transportSchedDelay << std::endl;
parentModule->handleMesgStatsObj(obj);
}
/**
* This listener receives signals of type HomaTransport::activeSchedsSignal
* which carries time
*/
GlobalSignalListener::ActiveSchedsListener::ActiveSchedsListener(
GlobalSignalListener* parentMod)
: parentMod(parentMod)
, activeSxTimes()
, activeSenders()
, srcComponents()
, numEmitterTransport(0)
{
// Register this object as a listener to the "activeScheds" singal that
// HomaTransport fires. This signal carries a pointer to an object of type
// HomaTransport::ReceiveScheduler::ActiveScheds.
simulation.getSystemModule()->subscribe("activeScheds", this);
activeSenders.setName("Time division of num active sched senders");
}
/**
* Signal receiver implementation
*/
void
GlobalSignalListener::ActiveSchedsListener::receiveSignal(cComponent* src,
simsignal_t id, cObject* obj)
{
// record time division stats of number of active scheduled in the
// activeSxTimes map
auto activeSxObj =
dynamic_cast<ActiveScheds*>(obj);
uint32_t numActiveSenders = activeSxObj->numActiveSenders;
simtime_t duration = activeSxObj->duration;
auto search = activeSxTimes.find(numActiveSenders);
if (search != activeSxTimes.end()) {
search->second += duration.dbl();
} else {
activeSxTimes[numActiveSenders] = duration.dbl();
}
// check if the emitter source of the signal is transport instance we
// haven't heard from before. If yes, increment the numEmitterTransport.
auto ret = srcComponents.insert(src);
if (ret.second) {
// The src wasn't in the set and is inserted now
numEmitterTransport++;
}
}
/**
* Write the recorded numActiveSenders and their time durations into the output
* vector "activeSenders". The numActiveSenders are asceingly sorted and the
* time duration for each numActiveSenders value is cumulative time durations
* correspondingly to all smaller numActiveSenders values.
*/
void
GlobalSignalListener::ActiveSchedsListener::dumpStats()
{
// Read the hash table in a vector of key-value pairs and sort the vector
// by the key.
std::vector<std::pair<uint32_t, double>> activeCumTimes(
activeSxTimes.begin(), activeSxTimes.end());
std::sort(activeCumTimes.begin(), activeCumTimes.end(),
std::less<std::pair<uint32_t, double>>());
// iterate over all recorded numActiveSenders and the cumulative time
// durations and dmup them in the vector output.
double cumTimes = 0;
for (auto it = activeCumTimes.begin(); it != activeCumTimes.end(); it++) {
cumTimes += (it->second / numEmitterTransport);
activeSenders.recordWithTimestamp(cumTimes, it->first);
}
}
/**
* Constructor for SelfWastedBandwidthListener.
* \param parentMod
* pointer to the GlobalSignalListener instance that owns this listener
* \param srcSigName
* name of one of the HomaTransport::lowerSelfWasteSignal or
* HomaTransport::highrSelfWasteSignal that this listener receives.
* \param destSigName
* signal name of the corresponding lowerSelfWasteSignal or
* highrSelfWasteSignal that this listener fires value for, every time it
* receives signal from srcSigName.
*/
GlobalSignalListener::SelfWastedBandwidthListener::SelfWastedBandwidthListener(
GlobalSignalListener* parentMod, const char* srcSigName,
const char* destSigName)
: parentMod(parentMod)
, srcSigName(srcSigName)
, destSigName(destSigName)
, destSigId(0)
{
simulation.getSystemModule()->subscribe(srcSigName, this);
destSigId = registerSignal(destSigName);
}
/**
* Signal receiver implementation for self inflicted bandwidht wastage.
* Receives the signal and
*/
void
GlobalSignalListener::SelfWastedBandwidthListener::receiveSignal(
cComponent *src, simsignal_t id, const SimTime& v)
{
parentMod->emit(destSigId, v);
}
|
JoranHonig/BTC-Plus | scripts/bsc/deploy_btcb_plus.js | <reponame>JoranHonig/BTC-Plus<filename>scripts/bsc/deploy_btcb_plus.js
const BTCBPlus = artifacts.require("BTCBPlus");
const ERC20Proxy = artifacts.require("ERC20Proxy");
const VBTC_PLUS = "0xcf8D1D3Fce7C2138F85889068e50F0e7a18b5321";
const ACSBTCB_PLUS = "0xD7806143A4206aa9A816b964e4c994F533b830b0";
module.exports = async function (callback) {
try {
const accounts = await web3.eth.getAccounts();
console.log('Deploying BTCB+...');
const btcbPlusImpl = await BTCBPlus.new();
const btcbPlusProxy = await ERC20Proxy.new(btcbPlusImpl.address, accounts[1], Buffer.from(''));
const btcbPlus = await BTCBPlus.at(btcbPlusProxy.address);
await btcbPlus.initialize();
console.log(`Proxy admin: ${accounts[1]}`);
console.log(`btcb+: ${btcbPlus.address}`);
console.log(`btcb+ implementation: ${btcbPlusImpl.address}`);
console.log('Adding vBTC+ to BTCB+...');
await btcbPlus.addToken(VBTC_PLUS);
console.log('Adding avsBTCB+ to BTCB+...');
await btcbPlus.addToken(ACSBTCB_PLUS);
callback();
} catch (e) {
callback(e);
}
} |
Viridity-Energy/vGraph | src/lib.js | <reponame>Viridity-Energy/vGraph
module.exports = {
DomHelper: require('./lib/DomHelper.js'),
Eventing: require('./lib/Eventing.js'),
Hitbox: require('./lib/Hitbox.js'),
makeBlob: require('./lib/makeBlob.js'),
Scheduler: require('./lib/Scheduler.js'),
svgColorize: require('./lib/svgColorize.js')
}; |
ravih18/AD-DL | clinicadl/random_search/random_search_cli.py | <filename>clinicadl/random_search/random_search_cli.py<gh_stars>10-100
import click
@click.command("random-search", no_args_is_help=True)
@click.argument(
"launch_directory",
type=str,
)
@click.argument("name", type=str)
def cli(
launch_directory,
name,
):
"""Hyperparameter exploration using random search.
LAUNCH_DIRECTORY is the path to the parents folder where results of random search will be saved.
NAME is the name of the output folder containing the experiment.
"""
from .random_search import launch_search
launch_search(launch_directory, name)
if __name__ == "__main__":
cli()
|
yone920/rootedinculture | src/pages/archive.js | <filename>src/pages/archive.js<gh_stars>0
import React from 'react'
// import TitleMenu from '../components/TitleMenu'
import Layout from "../components/Layout/layout"
import Listing from "../components/Listing"
import styled from 'styled-components'
import SEO from "../components/seo"
const Archive = () => (
<Layout>
<SEO title="Blog" />
<ArchiveWrapper>
<div className="header-line-wrapper">
<div className="blog-heading">
<h2>Blog</h2>
</div>
<div className="line">
<hr />
</div>
</div>
<ListingWrapper>
<Listing />
</ListingWrapper>
{/* <TitleMenuWrapper>
<TitleMenu />
</TitleMenuWrapper> */}
</ArchiveWrapper>
</Layout>
)
const ArchiveWrapper = styled.div`
display: grid;
grid-template-columns: [ full-start ] minmax(1rem, 1fr) [center-start ] repeat(8, [col-start] minmax(min-content, 13rem) [ col-end ]) [center-end] minmax(1rem, 1fr) [ full-end ];
justify-content: center;
padding: 4rem 0;
@media only screen and (max-width: 425px) {
grid-template-columns: [ full-start ] minmax(0rem, 1fr) [center-start ] repeat(8, [col-start] minmax(min-content, 13rem) [ col-end ]) [center-end] minmax(0rem, 1fr) [ full-end ];
}
.header-line-wrapper {
grid-column: center-start / center-end;
display: flex;
flex-direction: column;
justify-items: center;
padding: 0 0 4rem 0;
.blog-heading {
grid-column: full-start / full-end;
text-align: center;
}
.line {
width: 15rem;
margin: 1rem auto;
hr {
border: 0;
height: 1px;
background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0));
}
}
}
`
const ListingWrapper = styled.div`
grid-column: full-start / full-end;
padding: 0 5rem;
@media only screen and (max-width: 425px) {
padding: 0 2rem;
}
a {
text-decoration: none;
}
`
export default Archive;
|
DanIverson/ovjTools | NDDS/ndds.4.2e/include/ndds/pres/pres_readerQueue.h | <reponame>DanIverson/ovjTools
/*
* @(#)pres_readerQueue.h generated by: makeheader Mon Dec 3 23:08:15 2007
*
* built from: readerQueue.ifc
*/
#ifndef pres_readerQueue_h
#define pres_readerQueue_h
#include "reda/reda_fastBuffer.h"
#include "reda/reda_skiplist.h"
#include "mig/mig_rtps.h"
#include "reda/reda_sequenceNumber.h"
#include "pres/pres_common.h"
#ifdef __cplusplus
extern "C" {
#endif
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_NONE (0x00000000)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_DURABILITY (0x00000001)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_PRESENTATION (0x00000002)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_DEADLINE (0x00000004)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_LATENCY_BUDGET (0x00000008)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_OWNERSHIP (0x00000010)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_OWNERSHIP_STRENGTH (0x00000020)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_LIVELINESS (0x00000040)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_PARTITION (0x00000080)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_RELIABILITY (0x00000100)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_TRANSPORT_PRIORITY (0x00000200)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_LIFESPAN (0x00000400)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_DESTINATION_ORDER (0x00000800)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_COHERENT_SET (0x00001000)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_FILTER_SIGNATURE (0x00002000)
#define PRES_READER_QUEUE_INLINE_QOS_FLAG_UNKNOWN (0x80000000)
#define PRES_READER_QUEUE_STATE_ODBC_DSN_PROPERTY "dds.data_reader.state.odbc.dsn"
#define PRES_READER_QUEUE_STATE_ODBC_USERNAME_PROPERTY "dds.data_reader.state.odbc.username"
#define PRES_READER_QUEUE_STATE_ODBC_PASSWORD_PROPERTY "<PASSWORD>reader.state.odbc.password"
#define PRES_READER_QUEUE_STATE_ODBC_DRIVER_PROPERTY "dds.data_reader.state.odbc.driver"
#define PRES_READER_QUEUE_STATE_RESTORE_PROPERTY "dds.data_reader.state.restore"
#define PRES_READER_QUEUE_STATE_FILTER_REDUNDANT_SAMPLES "dds.data_reader.state.filter_redundant_samples"
#define PRES_READER_QUEUE_STATE_PERSISTENCE_SERVICE_REQUEST_DEPTH "dds.data_reader.state.persistence_service.request_depth"
#define PRES_READER_QUEUE_MAX_VIRTUAL_WRITERS_PER_SAMPLE 5
struct PRESReaderQueueVirtualWriterList;
struct PRESReaderQueueVirtualWriterListEntry {
/*i Virtual GUID */
struct MIGRtpsGuid guid;
struct REDASequenceNumber lastComittedSn;
struct REDASequenceNumber lastApplicationProcessedSn;
};
struct PRESReaderQueueVirtualWriterListProperty {
/*e Control growth in number of entries */
struct REDAFastBufferPoolGrowthProperty entryCount;
/*e*/
RTIBool restore;
};
#define PRES_READER_QUEUE_VIRTUAL_WRITER_LIST_PROPERTY_DEFAULT { \
/* entryCount */ \
{32, REDA_FAST_BUFFER_POOL_UNLIMITED, REDA_FAST_BUFFER_POOL_UNLIMITED} \
}
extern PRESDllExport struct PRESReaderQueueVirtualWriterList *
PRESReaderQueueVirtualWriterList_new(
const struct MIGRtpsGuid * readerVirtualGuid,
const struct PRESReaderQueueVirtualWriterListProperty *property,
const struct PRESOdbcDatabaseConnection * odbcDatabaseCx);
extern PRESDllExport void
PRESReaderQueueVirtualWriterList_preDelete(
struct PRESReaderQueueVirtualWriterList *me);
extern PRESDllExport void
PRESReaderQueueVirtualWriterList_delete(struct PRESReaderQueueVirtualWriterList *me);
extern PRESDllExport struct PRESReaderQueueVirtualWriterListEntry *
PRESReaderQueueVirtualWriterList_assertEntry(
struct PRESReaderQueueVirtualWriterList *me,
const struct MIGRtpsGuid * guid,
RTIBool persist);
extern PRESDllExport struct PRESReaderQueueVirtualWriterListEntry *
PRESReaderQueueVirtualWriterList_findEntry(
struct PRESReaderQueueVirtualWriterList *me,
const struct MIGRtpsGuid * guid);
extern PRESDllExport
RTIBool PRESReaderQueueVirtualWriterList_persistVirtualWriterEntry(
struct PRESReaderQueueVirtualWriterList *me,
struct PRESReaderQueueVirtualWriterListEntry * entry,
RTIBool update);
extern PRESDllExport
RTIBool PRESReaderQueueVirtualWriterList_supportStatePersistence(
struct PRESReaderQueueVirtualWriterList *me);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* pres_readerQueue_h */
|
franz1981/infinispan | commons/all/src/main/java/org/infinispan/counter/api/Handle.java | <filename>commons/all/src/main/java/org/infinispan/counter/api/Handle.java
package org.infinispan.counter.api;
/**
* As a return of {@link StrongCounter#addListener(CounterListener)}, it is used to un-register the {@link CounterListener}.
*
* @author <NAME>
* @since 9.0
*/
public interface Handle<T extends CounterListener> {
/**
* @return the {@link CounterListener} managed by this.
*/
T getCounterListener();
/**
* Removes the {@link CounterListener}.
*/
void remove();
}
|
eliace/chorda | packages/chorda-bulma/src/components/DropdownButton.js | import { Html, Domain } from 'chorda-core'
import { withDropdown } from '../mixins'
import { ButtonWithIcon } from '../extensions'
import DropdownItem from './DropdownItem'
import { Button } from '../elements'
class DropdownModel extends Domain {
config () {
return {
actions: {
open: function () {
this.$value = true
},
close: function () {
this.$value = false
}
}
}
}
}
export default class DropdownButton extends Html {
config () {
return {
sources: {
view: () => '',
dropdown: () => new DropdownModel(),
modals: (ctx, o) => ctx.modals
},
mix: { withDropdown },
styles: {
display: 'inline-flex'
},
text: 'Button',
dropdownChanged: function (v) {
this.opt('components', {dropdown: v})
},
$content: {
as: Button,//WithIcon,
$icon: {
weight: 10,
icon: 'fas fa-caret-down', // переставлено сюда с уровня Button, т.к. addComponent игнорирует повторное добавление
},
components: {
icon: true,
content: true
},
onClick: function (e, {modals, dropdown}) {
dropdown.$toggle()
// if (dropdown.get()) {
// modals.close(dropdown)
// }
// else {
// modals.open(dropdown)
// }
}
// onChange: function (e, {value}) {
// value.set(e.target.value)
// },
// valueChanged: function (v) {
// this.opt('value', v)
// }
},
$dropdown: {
// sources: {
// list: (ctx, o) => ctx.list,
// },
css: 'dropdown-content is-hovered',
styles: {
display: 'block'
},
// listChanged: function (v, stream) {
// this.opt('items', stream)
// },
defaultItem: {
as: DropdownItem,
// listChanged: function (v) {
// this.opt('text', v)
// },
onClick: function (e, {modals, dropdown}) {
dropdown.close()
//modals.close(dropdown)
}
},
allJoined: function ({dropdown, modals}) {
modals.open(dropdown)
return () => {
modals.close(dropdown)
}
}
}
}
}
} |
thumb-tack/ | testsuite/simple/jaxrs/src/main/java/io/thorntail/testsuite/jaxrs/MyExceptionalResource.java | package io.thorntail.testsuite.jaxrs;
/**
* Created by bob on 2/20/18.
*/
public class MyExceptionalResource {
}
|
netigenkluzowicz/api_android | legacy/src/main/java/pl/netigen/legacy/views/SimpleTouchEventsDetector.java | <filename>legacy/src/main/java/pl/netigen/legacy/views/SimpleTouchEventsDetector.java
package pl.netigen.legacy.views;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class SimpleTouchEventsDetector implements View.OnTouchListener {
private final List<Integer> activePointsCount = new ArrayList<>();
private SimpleTouchEventsListener simpleTouchEventsListener;
private TouchState touchState;
public SimpleTouchEventsDetector(SimpleTouchEventsListener simpleTouchEventsListener) {
this.simpleTouchEventsListener = simpleTouchEventsListener;
}
private boolean checkViewState(MotionEvent motionEvent, View view) {
int maskedAction = motionEvent.getActionMasked();
int pointerIndex = motionEvent.getActionIndex();
int pointerId = motionEvent.getPointerId(pointerIndex);
switch (maskedAction) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN: {
return actionDown(motionEvent, pointerIndex, pointerId);
}
case MotionEvent.ACTION_MOVE: {
return actionMove(motionEvent, view, pointerIndex, pointerId);
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP: {
return actionUp(motionEvent, view, pointerIndex, pointerId);
}
case MotionEvent.ACTION_CANCEL:
return actionCancel(pointerId);
}
return true;
}
private boolean actionCancel(int pointerId) {
if (pointerId >= 0 && pointerId < activePointsCount.size()) {
activePointsCount.remove(pointerId);
}
return true;
}
private boolean actionUp(MotionEvent motionEvent, View view, int pointerIndex, Integer pointerId) {
activePointsCount.remove(pointerId);
if (activePointsCount.size() == 0 && touchState == TouchState.PRESSED) {
releaseTouch(motionEvent, pointerIndex);
if (TouchHelper.isTouchInBounds(motionEvent, view, pointerIndex)) {
if (simpleTouchEventsListener != null) {
simpleTouchEventsListener.onClick();
}
}
}
return true;
}
private boolean actionMove(MotionEvent motionEvent, View view, int pointerIndex, Integer pointerId) {
if (!TouchHelper.isTouchInBounds(motionEvent, view, pointerIndex)) {
activePointsCount.remove(pointerId);
if (activePointsCount.size() == 0 && touchState == TouchState.PRESSED) {
releaseTouch(motionEvent, pointerIndex);
}
}
return true;
}
private boolean actionDown(MotionEvent motionEvent, Integer pointerIndex, int pointerId) {
if (touchState != TouchState.PRESSED) {
touchState = TouchState.PRESSED;
if (simpleTouchEventsListener != null) {
simpleTouchEventsListener.onPress(motionEvent.getX(pointerIndex), motionEvent.getY(pointerIndex));
}
}
activePointsCount.add(pointerId);
return true;
}
private void releaseTouch(MotionEvent motionEvent, Integer pointerIndex) {
if (simpleTouchEventsListener != null) {
simpleTouchEventsListener.onRelease(motionEvent.getX(pointerIndex), motionEvent.getY(pointerIndex));
}
touchState = TouchState.RELEASED;
}
@Override
public boolean onTouch(View view, MotionEvent event) {
return checkViewState(event, view);
}
public void setSimpleTouchEventsListener(SimpleTouchEventsListener simpleTouchEventsListener) {
this.simpleTouchEventsListener = simpleTouchEventsListener;
}
public enum TouchState {PRESSED, RELEASED}
}
|
Lothindir/camp-manager | src/icons/font-awesome/git-square.js | /* eslint-disable */
var icon = require('vue-svgicon')
icon.register({
'font-awesome/git-square': {
width: 1792,
height: 1792,
viewBox: '0 0 1792 1792',
data: '<path pid="0" d="M710 1308q0 66-93 66-107 0-107-63 0-64 98-64 102 0 102 61zm-36-466q0 85-74 85-77 0-77-84 0-90 77-90 36 0 55 25.5t19 63.5zm166-75V642q-78 29-135 29-50-29-110-29-86 0-145 57t-59 143q0 50 29.5 102t73.5 67v3q-38 17-38 85 0 53 41 77v3q-113 37-113 139 0 45 20 78.5t54 51 72 25.5 81 8q224 0 224-188 0-67-48-99t-126-46q-27-5-51.5-20.5T585 1088q0-44 49-52 77-15 122-70t45-134q0-24-10-52 37-9 49-13zm59 419h137q-2-27-2-82V717q0-46 2-69H899q3 23 3 71v392q0 50-3 75zm509-16v-121q-30 21-68 21-53 0-53-82V763h52q9 0 26.5 1t26.5 1V648h-105q0-82 3-102h-140q4 24 4 55v47h-60v117q36-3 37-3 3 0 11 .5t12 .5v2h-2v217q0 37 2.5 64t11.5 56.5 24.5 48.5 43.5 31 66 12q64 0 108-24zm-356-706q0-36-24-63.5T968 373t-60.5 27-24.5 64q0 36 25 62.5t60 26.5 59.5-27 24.5-62zm612-48v960q0 119-84.5 203.5T1376 1664H416q-119 0-203.5-84.5T128 1376V416q0-119 84.5-203.5T416 128h960q119 0 203.5 84.5T1664 416z" _fill="#fff"/>'
}
})
|
Mirage20/mesh-security | components/cell/io.cellery.security.cell.sts.server/src/test/java/io/cellery/security/cell/sts/server/core/validators/DefaultCellSTSReqValidatorTest.java | <reponame>Mirage20/mesh-security
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.cellery.security.cell.sts.server.core.validators;
import io.cellery.security.cell.sts.server.core.CellStsUtils;
import io.cellery.security.cell.sts.server.core.Constants;
import io.cellery.security.cell.sts.server.core.exception.CellSTSRequestValidationFailedException;
import io.cellery.security.cell.sts.server.core.model.CellStsRequest;
import io.cellery.security.cell.sts.server.core.model.RequestContext;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.nio.file.Paths;
import java.util.HashMap;
public class DefaultCellSTSReqValidatorTest {
DefaultCellSTSReqValidator defaultCellSTSReqValidator = new DefaultCellSTSReqValidator();
String resourceLocation = Paths.get(System.getProperty("user.dir"), "src", "test",
"resources").toString();
private static final String UNSECURED_PATHS_ENV_VARIABLE = "UNSECURED_CONTEXTS_CONF_PATH";
@Test(expectedExceptions = CellSTSRequestValidationFailedException.class)
public void testValidate() throws Exception {
CellStsRequest.CellStsRequestBuilder cellStsRequestBuilder = new CellStsRequest.CellStsRequestBuilder();
HashMap headers = new HashMap();
headers.put(Constants.CELLERY_AUTH_SUBJECT_HEADER, "Alice");
cellStsRequestBuilder.setRequestHeaders(headers);
defaultCellSTSReqValidator.validate(cellStsRequestBuilder.build());
}
@Test
public void testValidateWithException() throws Exception {
CellStsRequest.CellStsRequestBuilder cellStsRequestBuilder = new CellStsRequest.CellStsRequestBuilder();
HashMap headers = new HashMap();
cellStsRequestBuilder.setRequestHeaders(headers);
defaultCellSTSReqValidator.validate(cellStsRequestBuilder.build());
}
@DataProvider(name = "unsecuredPathDataProvider")
public Object[][] unsecuredPathDataProvider() {
return new Object[][]{
{"/hello-world", false}, {"undefined/path", true},
{"unsecured-path", false}, {"/secured/path", true},
};
}
@Test(dataProvider = "unsecuredPathDataProvider")
public void testIsAuthenticationRequired(String inputPath, boolean isUnsecured) throws Exception {
try {
CellStsRequest.CellStsRequestBuilder cellStsRequestBuilder = new CellStsRequest.CellStsRequestBuilder();
RequestContext requestContext = new RequestContext();
requestContext.setPath(inputPath);
cellStsRequestBuilder.setRequestContext(requestContext);
System.setProperty(UNSECURED_PATHS_ENV_VARIABLE, resourceLocation + "/unsecured-paths.json");
CellStsUtils.readUnsecuredContexts();
Assert.assertEquals(defaultCellSTSReqValidator.isAuthenticationRequired(cellStsRequestBuilder.build()),
isUnsecured);
} finally {
System.getProperties().remove(UNSECURED_PATHS_ENV_VARIABLE);
}
}
}
|
abuterin/BIOINF_OLC | BioInf/BioInf/StringGraphComponent.cpp | #include "StringGraphComponent.hpp"
#include "Graph.hpp"
using namespace std;
// contig extraction params
size_t MAX_BRANCHES = 18;
size_t MAX_START_NODES = 100;
double LENGTH_THRESHOLD = 0.05;
double QUALITY_THRESHOLD = 1.0;
//#define ABS(x) ((x < 0) ? x * (-1) : x)
#define MAX(x,y) ((x > y) ? x : y)
#pragma region pomocneFunkcije
/*************************************************************************************** /
* Title: RNA Assembler source code
* Author : rvaser (<EMAIL>)
* Date : Apr 13, 2015
* Availability : https://github.com/mariokostelac/ra
*************************************************************************************** */
double overlap_score(DovetailOverlap* overlap); //declaration
static int longest_sequence_length(Vertex* from, int direction, std::vector<bool>& visited,
int forks_left); //declaration
static int expandVertex(std::vector<Edge*>& dst, Vertex* start, int start_direction, uint32_t maxId, int max_branches) {
// debug("EXPAND %d\n", start->getId());
int totalLength = start->getLength();
Vertex* vertex = start;
int curr_direction = start_direction;
std::vector<bool> visitedVertices(maxId + 1, false);
while (true) {
visitedVertices[vertex->getId()] = true;
auto& edges = curr_direction == 0 ? vertex->getEdgesB() : vertex->getEdgesE();
Edge* best_edge = nullptr;
if (edges.size() == 1) {
if (!visitedVertices[edges.front()->destinationId]) {
best_edge = edges.front();
}
}
else if (edges.size() > 1) {
int best_length = 0;
double best_qual = 0;
double qual_lo = 0;
for (auto& edge : edges) {
best_qual = max(best_qual, overlap_score(edge->getOverlap()));
}
qual_lo = best_qual * (1 - QUALITY_THRESHOLD);
for (auto& edge : edges) {
Vertex* next = edge->getDst();
if (visitedVertices[next->getId()]) {
continue;
}
double curr_qual = overlap_score(edge->getOverlap());
if (curr_qual >= qual_lo) {
int curr_length = longest_sequence_length(next, edge->getOverlap()->isInnie() ? (curr_direction ^ 1) :
curr_direction, visitedVertices, max_branches) + vertex->getLength() + edge->labelLength();
if (curr_length > best_length) {
best_edge = edge;
best_length = curr_length;
}
}
}
}
if (best_edge == nullptr) {
break;
}
dst.emplace_back(best_edge);
vertex = best_edge->getDst();
totalLength += best_edge->labelLength();
if (best_edge->overlap->isInnie()) {
curr_direction ^= 1;
}
}
return totalLength;
}
static int longest_sequence_length(Vertex* from, int direction, std::vector<bool>& visited,
int forks_left) {
if (forks_left < 0) {
// debug("STOPEXPAND %d because hit max branches %d\n", from->getId(), MAX_BRANCHES);
return 0;
}
if (visited[from->getId()]) {
// debug("STOPEXPAND %d because visited\n", from->getId());
return 0;
}
visited[from->getId()] = true;
auto& edges = direction == 0 ? from->getEdgesB() : from->getEdgesE();
int res_length = 0;
if (edges.size() == 1) {
auto& edge = edges.front();
res_length += edge->labelLength();
res_length += longest_sequence_length(edge->getDst(), edge->getOverlap()->isInnie() ?
(direction ^ 1) : direction, visited, forks_left);
}
else if (edges.size() > 1) {
Edge* best_edge = nullptr;
int best_len = 0;
double best_qual = 0;
double qual_lo = 0;
for (auto& edge : edges) {
best_qual = max(best_qual, overlap_score(edge->getOverlap()));
}
qual_lo = best_qual * (1 - QUALITY_THRESHOLD);
for (auto& edge : edges) {
auto curr_qual = overlap_score(edge->getOverlap());
if (curr_qual >= qual_lo) {
int curr_len = longest_sequence_length(edge->getDst(), edge->getOverlap()->isInnie() ? (direction ^ 1) :
direction, visited, forks_left - 1);
if (curr_len > best_len) {
best_edge = edge;
best_len = curr_len;
}
}
}
if (best_edge != nullptr) {
res_length += best_edge->labelLength();
res_length += best_len;
}
}
visited[from->getId()] = false;
return res_length;
}
double overlap_score(DovetailOverlap* overlap) {
double quality = 1 - overlap->jaccardScore();
return (overlap->coveredPercentageReadA() + overlap->coveredPercentageReadB()) * quality;
};
static int findSingularChain(std::vector<Edge*>* dst, Vertex* start, int start_direction) {
int totalLength = start->getLength();
Vertex* curr_vertex = start;
int curr_direction = start_direction;
while (true) {
auto& edges = curr_direction == 0 ? curr_vertex->getEdgesB() : curr_vertex->getEdgesE();
if (edges.size() == 0) {
// end of chain
break;
}
if (curr_vertex->edges_b.size() + curr_vertex->edges_e.size() > 2) {
// not singular chain anymore
break;
}
Edge* selectedEdge = edges.front();
if (dst != nullptr) dst->emplace_back(selectedEdge);
curr_vertex = selectedEdge->getDst();
totalLength += selectedEdge->labelLength();
if (selectedEdge->getOverlap()->isInnie()) {
curr_direction ^= 1;
}
}
return totalLength;
}
static int countForks(Vertex* start, int start_direction, int depth) {
if (depth <= 0) {
return 0;
}
int forks = 0;
Vertex* curr_vertex = start;
int curr_direction = start_direction;
auto& edges = curr_direction == 0 ? curr_vertex->getEdgesB() : curr_vertex->getEdgesE();
if (curr_vertex->edges_b.size() + curr_vertex->edges_e.size() > 2) {
forks++;
}
for (auto e : edges) {
curr_vertex = e->getDst();
if (e->getOverlap()->isInnie()) {
curr_direction ^= 1;
}
forks += countForks(curr_vertex, curr_direction, depth - 1);
}
return forks;
}
#pragma endregion
StringGraphComponent::StringGraphComponent(set<int> vertexIds, Graph* graph) :
vertices_(), graph_(graph) {
for (auto& id : vertexIds) {
vertices_.emplace_back(graph->getVertexById(id));
}
walk_ = nullptr;
}
StringGraphComponent::~StringGraphComponent() {
delete walk_;
}
void StringGraphComponent::extractSequence(string& dst) {
if (walk_ == nullptr) extractLongestWalk();
if (walk_ != nullptr) walk_->extractSequence(dst);
}
StringGraphWalk* StringGraphComponent::longestWalk() {
if (walk_ == nullptr) extractLongestWalk();
return walk_;
}
void StringGraphComponent::extractLongestWalk() {
typedef std::tuple<Vertex*, int, double> Candidate;
// pick top N start vertices - criterion is the length of the
//contiguous path from a starting vertex to the first branching vertex.
std::vector<Candidate> startCandidates;
uint32_t maxId = 0;
for (auto& vertex : vertices_) {
maxId = max(maxId, vertex->readID);
}
// tips and singular chains could be good candidates
for (int direction = 0; direction <= 1; ++direction) {
for (auto& vertex : vertices_) {
if ((direction == 0 && vertex->edges_b.size() == 1 && vertex->edges_e.size() == 0) ||
(direction == 1 && vertex->edges_e.size() == 1 && vertex->edges_b.size() == 0)) {
vector<bool> visited(maxId + 1, false);
startCandidates.emplace_back(vertex, direction, longest_sequence_length(vertex, direction,
visited, 0));
}
}
}
// forks could be good candidates, too
for (int direction = 0; direction <= 1; ++direction) {
for (auto& vertex : vertices_) {
if ((direction == 0 && vertex->edges_b.size() > 1) ||
(direction == 1 && vertex->edges_e.size() > 1)) {
std::vector<bool> visited(maxId + 1, false);
startCandidates.emplace_back(vertex, direction, longest_sequence_length(vertex, direction,
visited, 1));
}
}
}
// circular component
if (startCandidates.size() == 0) {
std::vector<bool> visited(maxId + 1, false);
int direction = 0;
auto vertex = vertices_.front();
startCandidates.emplace_back(vertex, direction, longest_sequence_length(vertex, direction,
visited, 1));
}
sort(startCandidates.begin(), startCandidates.end(),
[](Candidate left, Candidate right) {
return std::get<2>(left) > std::get<2>(right);
}
);
int n = min(MAX_START_NODES, startCandidates.size());
// expand each of n candidates to a full chain and pick the best one (by length)
StringGraphWalk* selectedContig = nullptr;
int selectedLength = 0;
//Timer timer;
//timer.start();
#pragma omp parallel for default(none), shared(maxId, n, MAX_BRANCHES, startCandidates, selectedLength, selectedContig), schedule(dynamic, 1)
for (int i = 0; i < n; ++i) {
Vertex* start = std::get<0>(startCandidates[i]);
int direction = std::get<1>(startCandidates[i]);
// debug("CREATECONTIG from vertex %d\n", start->getId());
std::vector<Edge*> edges;
int length = expandVertex(edges, start, direction, maxId, MAX_BRANCHES);
#pragma omp critical
if (length > selectedLength) {
selectedLength = length;
if (selectedContig != nullptr) {
delete selectedContig;
}
selectedContig = new StringGraphWalk(start);
for (auto& edge : edges) {
selectedContig->addEdge(edge);
}
}
}
//timer.stop();
//timer.print("SG", "extract longest walk");
walk_ = selectedContig;
}
|
openlab/ODAF-OpenTurf | ODAF.iPhoneApp/route-me/samples/TileIssue/Classes/TileIssueViewController.h | <gh_stars>1-10
//
// TileIssueViewController.h
// TileIssue
//
// Created by olivier on 4/8/09.
// Copyright 2009 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "RMMapView.h"
@interface TileIssueViewController : UIViewController {
RMMapView *mapView;
}
@property (nonatomic, retain) RMMapView *mapView;
@end
|
Artraxon/sgx-radix-hash-join | src/enclave/histograms/GlobalHistogram.cpp | /**
* @author <NAME> <<EMAIL>>
* (c) 2016, ETH Zurich, Systems Group
*
*/
#include "GlobalHistogram.h"
#include <core/Configuration.h>
#include <utils/Debug.h>
#include <Enclave_t.h>
namespace hpcjoin {
namespace histograms {
GlobalHistogram::GlobalHistogram(LocalHistogram* localHistogram) {
this->localHistogram = localHistogram;
this->values = (uint64_t *) calloc(hpcjoin::core::Configuration::NETWORK_PARTITIONING_COUNT, sizeof(uint64_t));
}
GlobalHistogram::~GlobalHistogram() {
free(values);
}
void GlobalHistogram::computeGlobalHistogram() {
#ifdef MEASUREMENT_DETAILS_HISTOGRAM
ocall_startHistogramGlobalHistogramComputation();
//enclave::performance::Measurements::startHistogramGlobalHistogramComputation();
#endif
ocall_MPI_allreduce_sum(this->localHistogram->getLocalHistogram(), this->values, hpcjoin::core::Configuration::NETWORK_PARTITIONING_COUNT);
#ifdef MEASUREMENT_DETAILS_HISTOGRAM
ocall_stopHistogramGlobalHistogramComputation();
//enclave::performance::Measurements::stopHistogramGlobalHistogramComputation();
#endif
}
uint64_t* GlobalHistogram::getGlobalHistogram() {
return this->values;
}
} /* namespace histograms */
} /* namespace enclave */
|
fofr/manage-courses-prototype | app/filters/dates.js | <filename>app/filters/dates.js
// -------------------------------------------------------------------
// Imports and setup
// -------------------------------------------------------------------
const { DateTime } = require('luxon')
// Leave this filters line
const filters = {}
/* ------------------------------------------------------------------
date filter for use in Nunjucks
example: {{ params.date | date("DD/MM/YYYY") }}
outputs: 01/01/1970
------------------------------------------------------------------ */
filters.date = (timestamp, format = 'yyyy-LL-dd') => {
let datetime = DateTime.fromJSDate(timestamp, {
locale: 'en-GB'
}).toFormat(format)
if (datetime === 'Invalid DateTime') {
datetime = DateTime.fromISO(timestamp, {
locale: 'en-GB'
}).toFormat(format)
}
return datetime
}
/*
====================================================================
govukDate
--------------------------------------------------------------------
Process a date and return it in GOV.UK format
Accepts arrays (as provided by design system date inputs) as
well as javascript dates
====================================================================
Usage:
{{ [1,1,1970] | govukDate }}
= 1 January 1970
*/
filters.govukDate = (date, format) => {
let d
if (Array.isArray(date)) {
d = filters.arrayToGovukDate(date, format)
} else {
d = filters.dateToGovukDate(date, format)
}
return d
}
/*
====================================================================
arrayToGovukDate
--------------------------------------------------------------------
Convert array to govuk date
Useful for converting the arrays provided by the govukDate input
pattern to a real date. Primarly an internal function to be used by
the govukDate filter.
====================================================================
Usage:
{{ [1, 2, 2020] | arrayToGovukDate }}
= 1 February 2020
*/
filters.arrayToGovukDate = (array, format) => {
const dateObject = filters.arrayToDateObject(array)
const govukDate = filters.dateToGovukDate(dateObject, format)
return govukDate
}
/*
====================================================================
dateToGovukDate
--------------------------------------------------------------------
Convert js date object to govuk date (1 February 2020)
Internal function to be used by govukDate filter
====================================================================
Usage:
{{ date | dateToGovukDate }}
= 1 February 2020
*/
filters.dateToGovukDate = (date, format = false) => {
// if (date) {
// let d = moment(date)
// if (d.isValid) {
// return d.format(format || 'D MMMM YYYY')
// }
// }
// return ''
}
/*
====================================================================
arrayToDateObject
--------------------------------------------------------------------
Convert array to javascript date object
====================================================================
Usage:
{{ [1,2,2020] | arrayToDateObject }}
= 2020-02-01T00:00:00.000Z
*/
filters.arrayToDateObject = (array) => {
return new Date(array[2], array[1] - 1, array[0])
}
/*
====================================================================
today
--------------------------------------------------------------------
Today's date as javascript date object
====================================================================
Usage:
{{ "" | today }}
= 2020-02-01T00:00:00.000Z
*/
filters.today = () => {
return DateTime.now().toFormat('yyyy-LL-dd')
}
// -------------------------------------------------------------------
// keep the following line to return your filters to the app
// -------------------------------------------------------------------
exports.filters = filters
|
ShigotoShoujin/shigoto.shoujin | src/gui/window.hpp | <reponame>ShigotoShoujin/shigoto.shoujin<filename>src/gui/window.hpp<gh_stars>1-10
#ifndef SHOUJIN_SOURCE_GUI_WINDOW
#define SHOUJIN_SOURCE_GUI_WINDOW
#include "../enum_operators.hpp"
#include "../event.hpp"
#include "layout.hpp"
#include "window_handle.hpp"
#include "window_taborder.hpp"
#include <memory>
#include <vector>
namespace shoujin::gui {
class Window : public Layout {
WNDPROC _default_wndproc;
int _taborder;
std::unique_ptr<WindowHandle> _handle;
std::vector<std::unique_ptr<Window>> _child_vec;
std::unique_ptr<WindowTabOrder> _window_taborder;
Point _previous_mouse_position;
public:
static const bool Handled;
static const bool NotHandled;
struct WindowMessage {
UINT msg;
WPARAM wparam;
LPARAM lparam;
};
struct MessageResult {
bool handled;
LRESULT ret_code;
MessageResult();
MessageResult(bool handled, LRESULT ret_code = {});
operator bool() const;
};
enum class MouseButton : int {
None = 0,
Left = 1,
Right = 2,
Middle = 4,
X1 = 8,
X2 = 16
};
SHOUJIN_DEFINE_ENUM_FLAG_OPERATORS_CLASSMEMBER(MouseButton)
struct KeyEvent {
uint8_t virtual_keycode;
KeyEvent() = default;
explicit KeyEvent(WindowMessage const& message);
};
struct MouseEvent {
MouseButton ButtonFlag{};
Point Position;
Point Delta;
MouseEvent() = default;
explicit MouseEvent(WindowMessage const& message);
};
explicit Window(LayoutParam const& = {});
Window(Window const&);
Window& operator=(Window const&);
Window(Window&&) = default;
Window& operator=(Window&&) = default;
virtual ~Window() = default;
[[nodiscard]] WindowHandle const* handle() const { return _handle.get(); }
[[nodiscard]] HWND hwnd() const { return _handle ? _handle->hwnd() : 0; }
[[nodiscard]] int const& taborder() const { return _taborder; }
static Window* FindWindowByHandle(HWND hwnd);
void AddChild(Window* child);
Window* GetChild(int index);
Window* GetChild(HWND hwnd);
void Close();
void Destroy();
bool ProcessMessageQueue();
void SetFocus();
[[nodiscard]] tstring GetText() const;
void AppendText(tstring_view text);
void AppendLine(tstring_view text);
void SetText(tstring_view text);
void Show();
void ShowModal();
void Invalidate();
Event<bool, MSG const&> OnDispatchMessageEvent;
Event<bool, WindowMessage const&> OnWndProcEvent;
Event<bool, Window const&, CREATESTRUCT const&> OnCreateEvent;
Event<void, Window*> OnInitializeEvent;
Event<void, Window*> OnReadyEvent;
Event<bool> OnCloseEvent;
Event<bool, int> OnCommandEvent;
Event<bool> OnPaintEvent;
Event<bool, WPARAM, Rect*> OnSizingEvent;
Event<bool> OnSizingFinishedEvent;
Event<bool, Window*, KeyEvent const&> OnKeyDownEvent;
Event<bool, Window*, KeyEvent const&> OnKeyUpEvent;
Event<bool, Window*, KeyEvent const&> OnKeyPressEvent;
Event<bool, Window*, MouseEvent const&> OnMouseDownEvent;
Event<bool, Window*, MouseEvent const&> OnMouseUpEvent;
Event<bool, Window*, MouseEvent const&> OnMouseClickEvent;
Event<bool, Window*, MouseEvent const&> OnMouseMoveEvent;
Event<> OnDestroyEvent;
protected:
struct CreateParam {
LPCTSTR classname{};
bool subclass_window{};
};
void CreateHandle(WindowHandle const* parent = nullptr);
virtual void BeforeCreate(CreateParam& create_param);
virtual bool OnDispatchMessage(MSG const& msg);
virtual bool OnWndProc(WindowMessage const& message);
virtual bool OnCreate(CREATESTRUCT const& createparam);
virtual void OnInitialize();
virtual void OnReady();
virtual bool OnClose();
virtual bool OnCommand(int notification_code);
virtual bool OnPaint();
virtual bool OnSizing(WPARAM wparam, Rect* onsizing_rect);
virtual bool OnSizingFinished();
virtual void OnParentSized(Window const& parent);
virtual bool OnKeyDown(KeyEvent const& e);
virtual bool OnKeyUp(KeyEvent const& e);
virtual bool OnKeyPress(KeyEvent const& e);
virtual bool OnMouseDown(MouseEvent const& e);
virtual bool OnMouseUp(MouseEvent const& e);
virtual bool OnMouseMove(MouseEvent const& e);
virtual bool OnMouseClick(MouseEvent const& e);
virtual void OnDestroy();
private:
MessageResult RaiseOnDispatchMessage(MSG const& msg);
MessageResult RaiseOnWndProc(UINT msg, WPARAM wparam, LPARAM lparam);
MessageResult RaiseOnCreate(WindowMessage const& message);
void RaiseOnInitialize();
void RaiseOnReady();
MessageResult RaiseOnClose();
MessageResult RaiseOnCommand(WindowMessage const& message);
MessageResult RaiseOnPaint();
MessageResult RaiseOnSizing(WindowMessage const& message);
MessageResult RaiseOnSizingFinished();
void RaiseOnParentSized();
MessageResult RaiseOnKeyDown(WindowMessage const& message);
MessageResult RaiseOnKeyUp(WindowMessage const& message);
MessageResult RaiseOnKeyPress(WindowMessage const& message);
MessageResult RaiseOnMouseDown(WindowMessage const& message);
MessageResult RaiseOnMouseUp(WindowMessage const& message);
MessageResult RaiseOnMouseClick(WindowMessage const& message);
MessageResult RaiseOnMouseMove(WindowMessage const& message);
MessageResult RaiseOnDestroy();
virtual Window* Clone() const;
void CopyChilds(Window const& rhs);
void ConstructWindow(WindowHandle const* parent);
static LRESULT CALLBACK WndProcStatic(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
static LRESULT CALLBACK WndProcSubclassStatic(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
bool ReadMessage(MSG& msg);
bool ReadMessageAsync(MSG& msg);
void TranslateAndDispatchMessage(MSG const& msg);
std::vector<TCHAR> GetTextVector(size_t extra_char_to_alloc = 0) const;
void AppendText(tstring_view text, bool append_new_line);
};
}
#endif
|
Abjiri/DataGen | backend/data/controllers/cars.js | <filename>backend/data/controllers/cars.js<gh_stars>1-10
const carsJS = require('../datasets/cars.js');
const cars = carsJS.cars
const _ = require('lodash')
const carsAPI = {
get() { return cars },
car_brand(lang, i, sample) {
if (sample > -1) return _.sampleSize(cars, sample)
return cars[Math.floor(Math.random() * cars.length)]
}
}
module.exports = carsAPI |
JenerikMind/Restaurant-Seating-Reservation | back-end/src/db/seeds/01-tables.js | const tablesData = require("../fixtures/01-tables-data");
exports.seed = function (knex) {
return knex.raw("TRUNCATE TABLE tables RESTART IDENTITY CASCADE")
.then(()=>{
return knex("tables").insert(tablesData);
})
}; |
jefftc/changlab | Betsy/Betsy/modules/fill_missing_with_median.py | from Module import AbstractModule
class Module(AbstractModule):
def __init__(self):
AbstractModule.__init__(self)
def run(
self, network, antecedents, out_attributes, user_options, num_cores,
outfile):
import numpy
import arrayio
from genomicode import filelib
from Betsy import module_utils
in_data = antecedents
assert module_utils.is_missing(in_data.identifier), 'no missing values'
M = arrayio.read(in_data.identifier)
f_out = file(outfile, 'w')
X = M.slice()
for i in range(M.dim()[0]):
med = numpy.median([j for j in X[i] if j])
for j in range(M.dim()[1]):
if M._X[i][j] is None:
M._X[i][j] = med
arrayio.tab_delimited_format.write(M, f_out)
f_out.close()
assert filelib.exists_nz(outfile), (
'the output file %s for median_fill_if_missing does not exist' % outfile
)
def name_outfile(self, antecedents, user_options):
from Betsy import module_utils
original_file = module_utils.get_inputid(antecedents.identifier)
filename = 'signal_median_fill_' + original_file + '.tdf'
return filename
|
richung99/digitizePlots | venv/Lib/site-packages/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ..utils import SurfaceSnapshots
def test_SurfaceSnapshots_inputs():
input_map = dict(
annot_file=dict(
argstr="-annotation %s",
extensions=None,
xor=["annot_name"],
),
annot_name=dict(
argstr="-annotation %s",
xor=["annot_file"],
),
args=dict(
argstr="%s",
),
colortable=dict(
argstr="-colortable %s",
extensions=None,
),
demean_overlay=dict(
argstr="-zm",
),
environ=dict(
nohash=True,
usedefault=True,
),
hemi=dict(
argstr="%s",
mandatory=True,
position=2,
),
identity_reg=dict(
argstr="-overlay-reg-identity",
xor=["overlay_reg", "identity_reg", "mni152_reg"],
),
invert_overlay=dict(
argstr="-invphaseflag 1",
),
label_file=dict(
argstr="-label %s",
extensions=None,
xor=["label_name"],
),
label_name=dict(
argstr="-label %s",
xor=["label_file"],
),
label_outline=dict(
argstr="-label-outline",
),
label_under=dict(
argstr="-labels-under",
),
mni152_reg=dict(
argstr="-mni152reg",
xor=["overlay_reg", "identity_reg", "mni152_reg"],
),
orig_suffix=dict(
argstr="-orig %s",
),
overlay=dict(
argstr="-overlay %s",
extensions=None,
requires=["overlay_range"],
),
overlay_range=dict(
argstr="%s",
),
overlay_range_offset=dict(
argstr="-foffset %.3f",
),
overlay_reg=dict(
argstr="-overlay-reg %s",
extensions=None,
xor=["overlay_reg", "identity_reg", "mni152_reg"],
),
patch_file=dict(
argstr="-patch %s",
extensions=None,
),
reverse_overlay=dict(
argstr="-revphaseflag 1",
),
screenshot_stem=dict(),
show_color_scale=dict(
argstr="-colscalebarflag 1",
),
show_color_text=dict(
argstr="-colscaletext 1",
),
show_curv=dict(
argstr="-curv",
xor=["show_gray_curv"],
),
show_gray_curv=dict(
argstr="-gray",
xor=["show_curv"],
),
six_images=dict(),
sphere_suffix=dict(
argstr="-sphere %s",
),
stem_template_args=dict(
requires=["screenshot_stem"],
),
subject_id=dict(
argstr="%s",
mandatory=True,
position=1,
),
subjects_dir=dict(),
surface=dict(
argstr="%s",
mandatory=True,
position=3,
),
tcl_script=dict(
argstr="%s",
extensions=None,
genfile=True,
),
truncate_overlay=dict(
argstr="-truncphaseflag 1",
),
)
inputs = SurfaceSnapshots.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_SurfaceSnapshots_outputs():
output_map = dict(
snapshots=dict(),
)
outputs = SurfaceSnapshots.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.