repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
caveguy/AliOS-Things
|
platform/mcu/moc108/aos/framework_runtime/framework_runtime.c
|
<gh_stars>1-10
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <aos/aos.h>
#include "hal/soc/soc.h"
#ifdef AOS_BINS
const int *syscall_ktbl = NULL;
extern void *syscall_ftbl[];
extern char app_info_addr;
struct app_info_t *app_info = (struct app_info_t *)&app_info_addr;
extern unsigned int _framework_data_ram_begin;
extern unsigned int _framework_data_ram_end;
extern unsigned int _framework_data_flash_begin;
extern unsigned int _framework_bss_start;
extern unsigned int _framework_bss_end;
extern unsigned int _framework_heap_start;
extern unsigned int _framework_heap_end;
static void framework_entry(void *syscall_tbl, int argc, char *argv[])
{
/* syscall_ktbl assignment must be first */
syscall_ktbl = (int *)syscall_tbl;
aos_framework_init();
/*app_pre_init();*/
if (app_info->app_entry) {
app_info->app_entry(syscall_tbl, (void *)syscall_ftbl, 0, NULL);
}
}
__attribute__ ((used, section(".framework_info"))) struct framework_info_t framework_info = {
framework_entry,
&_framework_data_ram_begin,
&_framework_data_ram_end,
&_framework_data_flash_begin,
&_framework_bss_start,
&_framework_bss_end,
&_framework_heap_start,
&_framework_heap_end
};
#endif
|
CBIIT/HPC_DME_APIs
|
src/hpc-web/src/main/java/gov/nih/nci/hpc/web/util/HpcIdentityUtil.java
|
<filename>src/hpc-web/src/main/java/gov/nih/nci/hpc/web/util/HpcIdentityUtil.java
package gov.nih.nci.hpc.web.util;
import gov.nih.nci.hpc.dto.security.HpcUserDTO;
import javax.servlet.http.HttpSession;
/**
* Utility class for methods supporting User identity related logic.
*
* @author liuwy
*/
public class HpcIdentityUtil {
/**
* Check if current authenticated User has the Role of Group Admin.
*
* @param session The HTTP session
* @return true if User has Group Admin Role, false otherwise
*/
public static boolean isUserGroupAdmin(HttpSession session) {
boolean retVal = false;
if (null != session &&
session.getAttribute("hpcUser") instanceof HpcUserDTO)
{
HpcUserDTO userDto = (HpcUserDTO) session.getAttribute("hpcUser");
//TODO query against data_curator metadata
retVal = "GROUP_ADMIN".equals(userDto.getUserRole());
}
return retVal;
}
/**
* Check if current authenticated User has the Role of System Admin.
*
* @param session The HTTP session
* @return true if User has System Admin Role, false otherwise
*/
public static boolean isUserSystemAdmin(HttpSession session) {
boolean retVal = false;
if (null != session &&
session.getAttribute("hpcUser") instanceof HpcUserDTO)
{
HpcUserDTO userDto = (HpcUserDTO) session.getAttribute("hpcUser");
retVal = "SYSTEM_ADMIN".equals(userDto.getUserRole());
}
return retVal;
}
/**
* Check if current authenticated User has the Role of System Admin or
* the Role of Group Admin.
*
* @param session The HTTP session
* @return true if User has System Admin Role or Group Admin Role, false
* otherwise
*/
public static boolean iUserSystemAdminOrGroupAdmin(HttpSession session) {
boolean retVal = false;
if (null != session &&
session.getAttribute("hpcUser") instanceof HpcUserDTO)
{
HpcUserDTO userDto = (HpcUserDTO) session.getAttribute("hpcUser");
retVal = "SYSTEM_ADMIN".equals(userDto.getUserRole()) ||
"GROUP_ADMIN".equals(userDto.getUserRole());
}
return retVal;
}
/**
* Check if current authenticated User is a curator of any project
*
* @param session The HTTP session
* @return true if User is a curator, false otherwise
*/
public static boolean isUserCurator(HttpSession session) {
boolean retVal = false;
if (null != session &&
session.getAttribute("hpcUser") instanceof HpcUserDTO)
{
HpcUserDTO userDto = (HpcUserDTO) session.getAttribute("hpcUser");
retVal = userDto.getDataCurator();
}
return retVal;
}
}
|
DonIsaac/Java-Raytracer
|
src/model/Model.java
|
<reponame>DonIsaac/Java-Raytracer
package model;
import java.util.ArrayList;
import geometry.Sphere;
import geometry.Transform;
import geometry.Vector3;
import lighting.Material;
public class Model {
protected Material mat;
protected ArrayList<Vector3> verticies = new ArrayList<Vector3>();
protected ArrayList<Vector3> normals = new ArrayList<Vector3>();
protected ArrayList<Face> faces = new ArrayList<Face>();
public Sphere boundingSphere;
}
|
VeryGame/XUE
|
xue/src/main/java/org/rschrage/xue/mapping/tag/attribute/SimpleGenericAttribute.java
|
<reponame>VeryGame/XUE
package org.rschrage.xue.mapping.tag.attribute;
import org.rschrage.util.ReflectionUtils;
import java.lang.reflect.Method;
/**
* @author <NAME>
*/
public class SimpleGenericAttribute<T, V> extends AbstractAttribute<T, V> {
private String name;
public SimpleGenericAttribute(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public void apply(T element, V value) {
//makes it possible to address methods with a primitive parameter
Class<?> c = value.getClass();
if (c == Float.class) {
c = float.class;
}
else if (c == Integer.class) {
c = int.class;
}
Method targetMethod = ReflectionUtils.retrieveMethod(element.getClass(), "set" + name.substring(0,1).toUpperCase() + name.substring(1), c);
ReflectionUtils.invokeMethod(targetMethod, element, value);
}
}
|
khoih-prog/miniwinwm
|
MiniWin/ui/ui_radio_button.c
|
<reponame>khoih-prog/miniwinwm<filename>MiniWin/ui/ui_radio_button.c<gh_stars>10-100
/*
MIT License
Copyright (c) <NAME> 2019 miniwin Embedded Window Manager
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/***************
*** INCLUDES ***
***************/
#include <stdlib.h>
#include "miniwin.h"
/****************
*** CONSTANTS ***
****************/
/************
*** TYPES ***
************/
/***********************
*** GLOBAL VARIABLES ***
***********************/
/**********************
*** LOCAL VARIABLES ***
**********************/
/********************************
*** LOCAL FUNCTION PROTOTYPES ***
********************************/
static void radio_button_paint_function(mw_handle_t control_handle, const mw_gl_draw_info_t *draw_info);
static void radio_button_message_function(const mw_message_t *message);
/**********************
*** LOCAL FUNCTIONS ***
**********************/
/**
* Control paint routine, called by window manager.
*
* @param control_handle The control identifier in the array of controls
* @param draw_info Draw info structure describing offset and clip region
*/
static void radio_button_paint_function(mw_handle_t control_handle, const mw_gl_draw_info_t *draw_info)
{
int16_t i;
mw_ui_radio_button_data_t *this_radio_radio_button = (mw_ui_radio_button_data_t*)mw_get_control_instance_data(control_handle);
int16_t height;
int16_t box_size;
MW_ASSERT(draw_info != (void*)0, "Null pointer argument");
mw_gl_set_fill(MW_GL_FILL);
mw_gl_set_line(MW_GL_SOLID_LINE);
mw_gl_set_border(MW_GL_BORDER_ON);
mw_gl_clear_pattern();
mw_gl_set_bg_transparency(MW_GL_BG_TRANSPARENT);
mw_gl_set_text_rotation(MW_GL_TEXT_ROTATION_0);
/* set size dependent values */
if ((mw_get_control_flags(control_handle) & MW_CONTROL_FLAG_LARGE_SIZE) == MW_CONTROL_FLAG_LARGE_SIZE)
{
height = MW_UI_RADIO_BUTTON_LARGE_HEIGHT;
box_size = MW_UI_RADIO_BUTTON_LARGE_BOX_SIZE;
mw_gl_set_font(MW_GL_TITLE_FONT);
}
else
{
height = MW_UI_RADIO_BUTTON_HEIGHT;
box_size = MW_UI_RADIO_BUTTON_BOX_SIZE;
mw_gl_set_font(MW_GL_FONT_9);
}
for (i = 0; i < (int16_t)this_radio_radio_button->number_of_items; i++)
{
/* set the box outline and text colour depending on enabled state */
if ((mw_get_control_flags(control_handle) & MW_CONTROL_FLAG_IS_ENABLED) == MW_CONTROL_FLAG_IS_ENABLED)
{
mw_gl_set_fg_colour(MW_HAL_LCD_BLACK);
}
else
{
mw_gl_set_fg_colour(MW_CONTROL_DISABLED_COLOUR);
}
/* check size this control is being drawn at and draw appropriate text*/
if ((mw_get_control_flags(control_handle) & MW_CONTROL_FLAG_LARGE_SIZE) == MW_CONTROL_FLAG_LARGE_SIZE)
{
/* draw the label text */
mw_gl_string(draw_info,
MW_UI_RADIO_BUTTON_LARGE_LABEL_X_OFFSET,
MW_UI_RADIO_BUTTON_LARGE_LABEL_Y_OFFSET + i * MW_UI_RADIO_BUTTON_LARGE_HEIGHT,
this_radio_radio_button->radio_button_labels[i]);
}
else
{
/* draw the label text */
mw_gl_string(draw_info,
MW_UI_RADIO_BUTTON_LABEL_X_OFFSET,
MW_UI_RADIO_BUTTON_LABEL_Y_OFFSET + i * MW_UI_RADIO_BUTTON_HEIGHT,
this_radio_radio_button->radio_button_labels[i]);
}
/* draw the empty box */
mw_gl_set_solid_fill_colour(MW_CONTROL_UP_COLOUR);
mw_gl_rectangle(draw_info,
0,
i * height,
box_size,
box_size);
/* draw 3d effect */
mw_gl_set_fg_colour(MW_HAL_LCD_WHITE);
mw_gl_vline(draw_info,
1,
1 + i * height,
i * height + box_size - 2);
mw_gl_hline(draw_info,
1,
box_size - 2,
1 + i * height);
mw_gl_set_fg_colour(MW_HAL_LCD_GREY7);
mw_gl_vline(draw_info,
box_size - 2,
1 + i * height,
i * height + box_size - 2);
mw_gl_hline(draw_info,
1,
box_size - 2,
i * height + box_size - 2);
/* check if this radio_button is selected */
if (i == (int16_t)this_radio_radio_button->selected_radio_button)
{
/* it is so set the box fill colour according to enabled state */
if ((mw_get_control_flags(control_handle) & MW_CONTROL_FLAG_IS_ENABLED) == MW_CONTROL_FLAG_IS_ENABLED)
{
mw_gl_set_solid_fill_colour(MW_HAL_LCD_BLACK);
}
else
{
mw_gl_set_solid_fill_colour(MW_CONTROL_DISABLED_COLOUR);
}
/* draw the fill box */
mw_gl_rectangle(draw_info,
3,
i * height + 3,
box_size - 6,
box_size - 6);
}
}
}
/**
* Control message handler called by the window manager.
*
* @param message The message to be processed
*/
static void radio_button_message_function(const mw_message_t *message)
{
mw_ui_radio_button_data_t *this_radio_radio_button = (mw_ui_radio_button_data_t*)mw_get_control_instance_data(message->recipient_handle);
int16_t height;
uint32_t misra_temp;
MW_ASSERT(message != (void*)0, "Null pointer argument");
/* set size dependent values */
if ((mw_get_control_flags(message->recipient_handle) & MW_CONTROL_FLAG_LARGE_SIZE) == MW_CONTROL_FLAG_LARGE_SIZE)
{
height = MW_UI_RADIO_BUTTON_LARGE_HEIGHT;
}
else
{
height = MW_UI_RADIO_BUTTON_HEIGHT;
}
switch (message->message_id)
{
case MW_CONTROL_CREATED_MESSAGE:
/* initialise the control */
this_radio_radio_button->selected_radio_button = 0U;
break;
case MW_RADIO_BUTTON_SET_SELECTED_MESSAGE:
/* handle a transfer data message, which contains new position */
if (message->message_data < this_radio_radio_button->number_of_items)
{
this_radio_radio_button->selected_radio_button = (uint8_t)message->message_data;
}
break;
case MW_TOUCH_DOWN_MESSAGE:
/* handle a touch down event within this control */
if ((mw_get_control_flags(message->recipient_handle) & MW_CONTROL_FLAG_IS_ENABLED) == MW_CONTROL_FLAG_IS_ENABLED)
{
/* find which button was touched */
misra_temp = (message->message_data & 0xffffU) / (uint32_t)height;
this_radio_radio_button->selected_radio_button = (uint8_t)misra_temp;
/* send control response message */
mw_post_message(MW_RADIO_BUTTON_ITEM_SELECTED_MESSAGE,
message->recipient_handle,
mw_get_control_parent_window_handle(message->recipient_handle),
this_radio_radio_button->selected_radio_button,
NULL,
MW_WINDOW_MESSAGE);
mw_paint_control(message->recipient_handle);
}
break;
default:
/* keep MISRA happy */
break;
}
}
/***********************
*** GLOBAL FUNCTIONS ***
***********************/
mw_handle_t mw_ui_radio_button_add_new(int16_t x,
int16_t y,
int16_t width,
mw_handle_t parent_handle,
uint16_t flags,
mw_ui_radio_button_data_t *radio_button_instance_data)
{
mw_util_rect_t r;
uint8_t i;
/* check for null parameters */
if (radio_button_instance_data == NULL ||
radio_button_instance_data->radio_button_labels == NULL)
{
MW_ASSERT((bool)false, "Null pointer argument");
return (MW_INVALID_HANDLE);
}
/* check for 0 entries */
if (radio_button_instance_data->number_of_items == 0U)
{
MW_ASSERT((bool)false, "Zero argument");
return (MW_INVALID_HANDLE);
}
/* check for null pointers in entry text */
for (i = 0U; i < radio_button_instance_data->number_of_items; i++)
{
if (radio_button_instance_data->radio_button_labels[i] == NULL)
{
MW_ASSERT((bool)false, "Null pointer value in array");
return (MW_INVALID_HANDLE);
}
}
if ((flags & MW_CONTROL_FLAG_LARGE_SIZE) == MW_CONTROL_FLAG_LARGE_SIZE)
{
if (width < MW_UI_RADIO_BUTTON_LARGE_HEIGHT)
{
return (MW_INVALID_HANDLE);
}
mw_util_set_rect(&r, x, y, width, MW_UI_RADIO_BUTTON_LARGE_HEIGHT * (int16_t)radio_button_instance_data->number_of_items);
}
else
{
if (width < MW_UI_RADIO_BUTTON_HEIGHT)
{
return (MW_INVALID_HANDLE);
}
mw_util_set_rect(&r, x, y, width, MW_UI_RADIO_BUTTON_HEIGHT * (int16_t)radio_button_instance_data->number_of_items);
}
return (mw_add_control(&r,
parent_handle,
radio_button_paint_function,
radio_button_message_function,
flags,
radio_button_instance_data));
}
|
octree-nn/ocnn-pytorch
|
ocnn/modules/modules.py
|
<reponame>octree-nn/ocnn-pytorch
import torch
import torch.utils.checkpoint
from typing import List
import ocnn
from ocnn.nn import OctreeConv, OctreeDeconv
from ocnn.octree import Octree
bn_momentum, bn_eps = 0.01, 0.001 # the default value of Tensorflow 1.x
# bn_momentum, bn_eps = 0.1, 1e-05 # the default value of pytorch
def ckpt_conv_wrapper(conv_op, data, octree):
# The dummy tensor is a workaround when the checkpoint is used for the first conv layer:
# https://discuss.pytorch.org/t/checkpoint-with-no-grad-requiring-inputs-problem/19117/11
dummy = torch.ones(1, dtype=torch.float32, requires_grad=True)
def conv_wrapper(data, octree, dummy_tensor):
return conv_op(data, octree)
return torch.utils.checkpoint.checkpoint(conv_wrapper, data, octree, dummy)
class OctreeConvBn(torch.nn.Module):
r''' A sequence of :class:`OctreeConv` and :obj:`BatchNorm`.
Please refer to :class:`ocnn.nn.OctreeConv` for details on the parameters.
'''
def __init__(self, in_channels: int, out_channels: int,
kernel_size: List[int] = [3], stride: int = 1,
nempty: bool = False):
super().__init__()
self.conv = OctreeConv(
in_channels, out_channels, kernel_size, stride, nempty)
self.bn = torch.nn.BatchNorm1d(out_channels, bn_eps, bn_momentum)
def forward(self, data: torch.Tensor, octree: Octree, depth: int):
r''''''
out = self.conv(data, octree, depth)
out = self.bn(out)
return out
class OctreeConvBnRelu(torch.nn.Module):
r''' A sequence of :class:`OctreeConv`, :obj:`BatchNorm`, and :obj:`Relu`.
Please refer to :class:`ocnn.nn.OctreeConv` for details on the parameters.
'''
def __init__(self, in_channels: int, out_channels: int,
kernel_size: List[int] = [3], stride: int = 1,
nempty: bool = False):
super().__init__()
self.conv = OctreeConv(
in_channels, out_channels, kernel_size, stride, nempty)
self.bn = torch.nn.BatchNorm1d(out_channels, bn_eps, bn_momentum)
self.relu = torch.nn.ReLU(inplace=True)
def forward(self, data: torch.Tensor, octree: Octree, depth: int):
r''''''
out = self.conv(data, octree, depth)
out = self.bn(out)
out = self.relu(out)
return out
class OctreeDeconvBnRelu(torch.nn.Module):
r''' A sequence of :class:`OctreeDeconv`, :obj:`BatchNorm`, and :obj:`Relu`.
Please refer to :class:`ocnn.nn.OctreeDeconv` for details on the parameters.
'''
def __init__(self, in_channels: int, out_channels: int,
kernel_size: List[int] = [3], stride: int = 1,
nempty: bool = False):
super().__init__()
self.deconv = OctreeDeconv(
in_channels, out_channels, kernel_size, stride, nempty)
self.bn = torch.nn.BatchNorm1d(out_channels, bn_eps, bn_momentum)
self.relu = torch.nn.ReLU(inplace=True)
def forward(self, data: torch.Tensor, octree: Octree, depth: int):
r''''''
out = self.deconv(data, octree, depth)
out = self.bn(out)
out = self.relu(out)
return out
class Conv1x1(torch.nn.Module):
r''' Performs a convolution with kernel :obj:`(1,1,1)`.
The shape of octree features is :obj:`(N, C)`, where :obj:`N` is the node
number and :obj:`C` is the feature channel. Therefore, :class:`Conv1x1` can be
implemented with :class:`torch.nn.Linear`.
'''
def __init__(self, in_channels: int, out_channels: int, use_bias: bool = False):
super().__init__()
self.linear = torch.nn.Linear(in_channels, out_channels, use_bias)
def forward(self, data: torch.Tensor):
r''''''
return self.linear(data)
class Conv1x1Bn(torch.nn.Module):
r''' A sequence of :class:`Conv1x1` and :class:`BatchNorm`.
'''
def __init__(self, in_channels: int, out_channels: int):
super().__init__()
self.conv = Conv1x1(in_channels, out_channels, use_bias=False)
self.bn = torch.nn.BatchNorm1d(out_channels, bn_eps, bn_momentum)
def forward(self, data: torch.Tensor):
r''''''
out = self.conv(data)
out = self.bn(out)
return out
class Conv1x1BnRelu(torch.nn.Module):
r''' A sequence of :class:`Conv1x1`, :class:`BatchNorm` and :class:`Relu`.
'''
def __init__(self, in_channels: int, out_channels: int):
super().__init__()
self.conv = Conv1x1(in_channels, out_channels, use_bias=False)
self.bn = torch.nn.BatchNorm1d(out_channels, bn_eps, bn_momentum)
self.relu = torch.nn.ReLU(inplace=True)
def forward(self, data: torch.Tensor):
r''''''
out = self.conv(data)
out = self.bn(out)
out = self.relu(out)
return out
class FcBnRelu(torch.nn.Module):
r''' A sequence of :class:`FC`, :class:`BatchNorm` and :class:`Relu`.
'''
def __init__(self, in_channels: int, out_channels: int):
super().__init__()
self.flatten = torch.nn.Flatten(start_dim=1)
self.fc = torch.nn.Linear(in_channels, out_channels, bias=False)
self.bn = torch.nn.BatchNorm1d(out_channels, bn_eps, bn_momentum)
self.relu = torch.nn.ReLU(inplace=True)
def forward(self, data):
r''''''
out = self.flatten(data)
out = self.fc(out)
out = self.bn(out)
out = self.relu(out)
return out
class InputFeature(torch.nn.Module):
r''' Returns the initial input feature stored in octree.
Args:
feature (str): A string used to indicate which features to extract in octree.
If the character :obj:`N` is in :attr:`feature`, the normal signal is
extracted (3 channels). Similarly, if :obj:`D` is in :attr:`feature`,
the local displacement is extracted (1 channels). If :obj:`L` is in
:attr:`feature`, the local coordinates of the averaged points in each
octree node is extracted (3 channels). If :attr:`P` is in :attr:`feature`,
the global coordinates are extracted (3 channels). If :attr:`F` is in
:attr:`feature`, other features (like colors) are extracted (k channels).
nempty (bool): If false, gets the features of all octree nodes.
'''
def __init__(self, feature: str = 'NDF', nempty: bool = False):
super().__init__()
self.nempty = nempty
self.feature = feature.upper()
def forward(self, octree: Octree):
r''''''
features = list()
depth = octree.depth
if 'N' in self.feature:
features.append(octree.normals[depth])
if 'L' in self.feature or 'D' in self.feature:
local_points = octree.points[depth].frac() - 0.5
if 'D' in self.feature:
dis = torch.sum(local_points * octree.normals[depth], dim=1, keepdim=True)
features.append(dis)
if 'L' in self.feature:
features.append(local_points)
if 'P' in self.feature:
scale = 2 ** (1 - depth) # normalize [0, 2^depth] -> [-1, 1]
global_points = octree.points[depth] * scale - 1.0
features.append(global_points)
if 'F' in self.feature:
features.append(octree.features[depth])
out = torch.cat(features, dim=1)
if not self.nempty:
out = ocnn.nn.octree_pad(out, octree, depth)
return out
|
sudeshana/carbon-governance
|
components/governance/org.wso2.carbon.governance.registry.extensions/src/org/wso2/carbon/governance/registry/extensions/discoveryagents/DiscoveryAgentExecutor.java
|
/*
* Copyright (c) 2015, 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 org.wso2.carbon.governance.registry.extensions.discoveryagents;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.governance.api.exception.GovernanceException;
import org.wso2.carbon.governance.api.generic.GenericArtifactManager;
import org.wso2.carbon.governance.api.generic.dataobjects.DetachedGenericArtifact;
import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact;
import org.wso2.carbon.governance.common.GovernanceConfiguration;
import org.wso2.carbon.governance.registry.extensions.internal.GovernanceRegistryExtensionsDataHolder;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DiscoveryAgentExecutor {
public static final String SERVER_RXT_OVERVIEW_TYPE = "overview_type";
public static final String DISCOVERY_STATUS = "discovery_status";
public static final String DISCOVERY_STATUS_EXISTING = "existing";
public static final String DISCOVERY_STATUS_NEW = "new";
public static final String AGENT_CLASS = "AgentClass";
private final Log log = LogFactory.getLog(DiscoveryAgentExecutor.class);
private static DiscoveryAgentExecutor executor = new DiscoveryAgentExecutor();
private Map<String, DiscoveryAgent> agentMap;
public static DiscoveryAgentExecutor getInstance() {
return executor;
}
public Map<String, List<DetachedGenericArtifact>> executeDiscoveryAgent(GenericArtifact serverArtifact)
throws DiscoveryAgentException {
if (!isAgentMapInitialized()) {
initializeAgentMap();
}
String serverTypeId = getServerTypeId(serverArtifact);
DiscoveryAgent agent = findDiscoveryAgent(serverTypeId);
Map<String, List<DetachedGenericArtifact>> discoveredArtifacts = agent.discoverArtifacts(serverArtifact);
try {
markExistingArtifacts(discoveredArtifacts, getGovRegistry());
} catch (RegistryException e) {
throw new DiscoveryAgentException("Exception occurred accessing Registry", e);
}
return discoveredArtifacts;
}
private void markExistingArtifacts(Map<String, List<DetachedGenericArtifact>> artifacts, Registry registry)
throws RegistryException {
for(Map.Entry<String, List<DetachedGenericArtifact>> entry : artifacts.entrySet()){
String shortName = entry.getKey();
GenericArtifactManager manager = new GenericArtifactManager(registry, shortName);
for(GenericArtifact artifact : entry.getValue()){
if(manager.isExists(artifact)){
artifact.addAttribute(DISCOVERY_STATUS, DISCOVERY_STATUS_EXISTING);
} else {
artifact.addAttribute(DISCOVERY_STATUS, DISCOVERY_STATUS_NEW);
}
}
}
}
private boolean isAgentMapInitialized() {
return agentMap != null;
}
protected void initializeAgentMap() {
agentMap = new HashMap<>();
GovernanceConfiguration configuration = GovernanceRegistryExtensionsDataHolder.getInstance().getGovernanceConfiguration();
for (Map.Entry<String, Map<String, String>> configEntry : configuration.getDiscoveryAgentConfigs().entrySet()) {
String serverType = configEntry.getKey();
Map<String, String> properties = configEntry.getValue();
String agentClass = properties.get(AGENT_CLASS);
DiscoveryAgent thisAgent = loadDiscoveryAgent(agentClass);
if (thisAgent != null) {
thisAgent.init(properties);
agentMap.put(serverType, thisAgent);
}
}
}
private DiscoveryAgent loadDiscoveryAgent(String agentClass) {
try {
Class clazz = getClass().getClassLoader().loadClass(agentClass);
return (DiscoveryAgent) clazz.newInstance();
} catch (ClassNotFoundException e) {
log.error("Can't load DiscoveryAgent class " + agentClass);
} catch (InstantiationException | IllegalAccessException e) {
log.error("Can't Instantiate DiscoveryAgent class " + agentClass);
}
return null;
}
private DiscoveryAgent findDiscoveryAgent(String serverTypeId) throws DiscoveryAgentException {
DiscoveryAgent agent = agentMap.get(serverTypeId);
if (agent == null) {
throw new DiscoveryAgentException("Can't find DiscoveryAgent associated to server type :" + serverTypeId);
}
return agent;
}
private String getServerTypeId(GenericArtifact serverArtifact) throws DiscoveryAgentException {
String serverTypeId;
try {
serverTypeId = serverArtifact.getAttribute(SERVER_RXT_OVERVIEW_TYPE);
if (serverTypeId == null) {
throw new DiscoveryAgentException("ServerTypeId value is null, can't proceed");
}
return serverTypeId;
} catch (GovernanceException e) {
throw new DiscoveryAgentException("ServerTypeId issue", e);
}
}
private Registry getGovRegistry() throws RegistryException {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(CarbonConstants.REGISTRY_SYSTEM_USERNAME);
return GovernanceRegistryExtensionsDataHolder.getInstance().getRegistryService().getGovernanceSystemRegistry();
}
}
|
torped/mystajl
|
SafeAreaView/index.js
|
// @flow
// eslint-disable-next-line import/no-unresolved, import/extensions
export { default } from "./SafeAreaView";
|
jimcox/spring-security-rcp
|
client/src/test/java/jcox/security/rcp/client/service/SupplierConsumerSwingWorkerTest.java
|
/*
Copyright 2016 <NAME> <<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 jcox.security.rcp.client.service;
import static org.junit.Assert.*;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Matchers.anyString;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.swing.SwingUtilities;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(MockitoJUnitRunner.class)
public class SupplierConsumerSwingWorkerTest {
private final static Logger logger = LoggerFactory.getLogger(SupplierConsumerSwingWorkerTest.class);
@Mock Supplier<String> supplier;
@Mock Consumer<String> consumer;
SupplierConsumerSwingWorker<String, Object> worker;
String actual = null;
boolean wasEventDispatchThread = false;
CountDownLatch latch = null;
boolean exceptionHandled = false;
final String production = "OK";
@Before
public void beforeEachTest() {
actual = null;
wasEventDispatchThread = false;
exceptionHandled = false;
latch = new CountDownLatch(1);;
}
/**
* Test that the producer hands off to the consumer
* AND the consumer completes it's work on the event dispatch thread.
*
* @throws Exception
*/
@Test(timeout=5000L)
public void happyPath() throws Exception {
when(supplier.get()).thenReturn(production);
worker = new SupplierConsumerSwingWorker<String, Object>(supplier,
(String in) -> {
actual = in;
wasEventDispatchThread = SwingUtilities.isEventDispatchThread();
latch.countDown();
},
(ExecutionException ee) -> logger.info("Exception in Swing Worker", ee)
);
worker.execute();
latch.await();
assertEquals(production, actual );
assertTrue(wasEventDispatchThread);
}
/**
* Test that the handler processes Supplier Exceptions.
*
* @throws Exception
*/
@Test(timeout=5000L)
public void executionException() throws Exception {
doThrow(new RuntimeException("RuntimeException!")).when(supplier).get();
worker = new SupplierConsumerSwingWorker<String, Object>(supplier,
consumer,
(ExecutionException ee) -> {
logger.info("Exception in Swing Worker", ee);
exceptionHandled = true;
latch.countDown();
}
);
worker.execute();
latch.await();
assertTrue(exceptionHandled);
verify(consumer,never()).accept(anyString());
}
}
|
flaithbheartaigh/mirrlicht
|
source/Irrlicht/COpenGLDriver.h
|
// Copyright (C) 2002-2007 <NAME>
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in Irrlicht.h
#ifndef __C_VIDEO_OPEN_GL_H_INCLUDED__
#define __C_VIDEO_OPEN_GL_H_INCLUDED__
#include "IrrCompileConfig.h"
#include "CNullDriver.h"
#include "IMaterialRendererServices.h"
#ifdef _IRR_COMPILE_WITH_OPENGL_
#if defined(_IRR_WINDOWS_API_)
// include windows headers for HWND
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glext.h"
#ifdef _MSC_VER
#pragma comment(lib, "OpenGL32.lib")
#pragma comment(lib, "GLu32.lib")
#endif
#elif defined(MACOSX)
#define GL_EXT_texture_env_combine 1
#include "CIrrDeviceMacOSX.h"
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <OpenGL/glext.h>
#elif defined(__SYMBIAN32__)
#include <GLES/egl.h>
//#include "glext.h"
#include "gles_ARB_redefine.h"
#elif defined(_IRR_USE_SDL_DEVICE_)
#if defined(_IRR_OPENGL_USE_EXTPOINTER_)
#define GL_GLEXT_LEGACY 1
#define GLX_GLXEXT_LEGACY 1
#else
#define GL_GLEXT_PROTOTYPES 1
#define GLX_GLXEXT_PROTOTYPES 1
#endif
#include <SDL/SDL_opengl.h>
#define NO_SDL_GLEXT
#include "glext.h"
#else
#if defined(_IRR_OPENGL_USE_EXTPOINTER_)
#define GL_GLEXT_LEGACY 1
#define GLX_GLXEXT_LEGACY 1
#else
#define GL_GLEXT_PROTOTYPES 1
#define GLX_GLXEXT_PROTOTYPES 1
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#if defined(_IRR_OPENGL_USE_EXTPOINTER_)
#include "glext.h"
#undef GLX_ARB_get_proc_address // avoid problems with local glxext.h
#include "glxext.h"
#endif
#endif
namespace irr
{
namespace video
{
class COpenGLTexture;
class COpenGLDriver : public CNullDriver, public IMaterialRendererServices
{
public:
#ifdef _IRR_WINDOWS_API_
//! win32 constructor
COpenGLDriver(const core::dimension2d<s32>& screenSize, HWND window, bool fullscreen,
bool stencilBuffer, io::IFileSystem* io, bool antiAlias);
//! inits the windows specific parts of the open gl driver
bool initDriver(const core::dimension2d<s32>& screenSize, HWND window,
u32 bits, bool fullscreen, bool vsync);
#endif
#ifdef _IRR_USE_LINUX_DEVICE_
COpenGLDriver(const core::dimension2d<s32>& screenSize, bool fullscreen,
bool stencilBuffer, io::IFileSystem* io, bool vsync, bool antiAlias);
#endif
#ifdef MACOSX
COpenGLDriver(const core::dimension2d<s32>& screenSize, bool fullscreen,
bool stencilBuffer, CIrrDeviceMacOSX *device,io::IFileSystem* io, bool vsync, bool antiAlias);
#endif
#ifdef __SYMBIAN32__
COpenGLDriver(const core::dimension2d<s32>& screenSize, bool fullscreen,
bool stencilBuffer, EGLSurface window, EGLDisplay display, io::IFileSystem* io, bool vsync, bool antiAlias);
#endif
#ifdef _IRR_USE_SDL_DEVICE_
COpenGLDriver(const core::dimension2d<s32>& screenSize, bool fullscreen,
bool stencilBuffer, io::IFileSystem* io, bool vsync, bool antiAlias);
#endif
//! destructor
virtual ~COpenGLDriver();
//! presents the rendered scene on the screen, returns false if failed
virtual bool endScene( s32 windowId, core::rect<s32>* sourceRect=0 );
//! clears the zbuffer
virtual bool beginScene(bool backBuffer, bool zBuffer, SColor color);
//! sets transformation
virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat);
//! draws a vertex primitive list
void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, const u16* indexList, u32 primitiveCount, E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType);
//! queries the features of the driver, returns true if feature is available
bool queryFeature(E_VIDEO_DRIVER_FEATURE feature);
//! Sets a material. All 3d drawing functions draw geometry now
//! using this material.
//! \param material: Material to be used from now on.
virtual void setMaterial(const SMaterial& material);
//! draws an 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
virtual void draw2DImage(video::ITexture* texture, const core::position2d<s32>& destPos,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false);
//! draws a set of 2d images, using a color and the alpha
/** channel of the texture if desired. The images are drawn
beginning at pos and concatenated in one line. All drawings
are clipped against clipRect (if != 0).
The subtextures are defined by the array of sourceRects
and are chosen by the indices given.
\param texture: Texture to be drawn.
\param pos: Upper left 2d destination position where the image will be drawn.
\param sourceRects: Source rectangles of the image.
\param indices: List of indices which choose the actual rectangle used each time.
\param clipRect: Pointer to rectangle on the screen where the image is clipped to.
This pointer can be 0. Then the image is not clipped.
\param color: Color with which the image is colored.
Note that the alpha component is used: If alpha is other than 255, the image will be transparent.
\param useAlphaChannelOfTexture: If true, the alpha channel of the texture is
used to draw the image. */
virtual void draw2DImage(video::ITexture* texture,
const core::position2d<s32>& pos,
const core::array<core::rect<s32> >& sourceRects,
const core::array<s32>& indices,
const core::rect<s32>* clipRect=0,
SColor color=SColor(255,255,255,255),
bool useAlphaChannelOfTexture=false);
//! Draws a part of the texture into the rectangle.
virtual void draw2DImage(video::ITexture* texture, const core::rect<s32>& destRect,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
video::SColor* colors=0, bool useAlphaChannelOfTexture=false);
//! draw an 2d rectangle
virtual void draw2DRectangle(SColor color, const core::rect<s32>& pos,
const core::rect<s32>* clip = 0);
//!Draws an 2d rectangle with a gradient.
virtual void draw2DRectangle(const core::rect<s32>& pos,
SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
const core::rect<s32>* clip = 0);
//! Draws a 2d line.
virtual void draw2DLine(const core::position2d<s32>& start,
const core::position2d<s32>& end,
SColor color=SColor(255,255,255,255));
//! Draws a 3d line.
virtual void draw3DLine(const core::vector3df& start,
const core::vector3df& end,
SColor color = SColor(255,255,255,255));
//! \return Returns the name of the video driver. Example: In case of the Direct3D8
//! driver, it would return "Direct3D8.1".
virtual const wchar_t* getName();
//! deletes all dynamic lights there are
virtual void deleteAllDynamicLights();
//! adds a dynamic light
virtual void addDynamicLight(const SLight& light);
//! returns the maximal amount of dynamic lights the device can handle
virtual u32 getMaximalDynamicLightAmount();
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
virtual void setAmbientLight(const SColorf& color);
//! Draws a shadow volume into the stencil buffer. To draw a stencil shadow, do
//! this: First, draw all geometry. Then use this method, to draw the shadow
//! volume. Then, use IVideoDriver::drawStencilShadow() to visualize the shadow.
virtual void drawStencilShadowVolume(const core::vector3df* triangles, s32 count, bool zfail);
//! Fills the stencil shadow with color. After the shadow volume has been drawn
//! into the stencil buffer using IVideoDriver::drawStencilShadowVolume(), use this
//! to draw the color of the shadow.
virtual void drawStencilShadow(bool clearStencilBuffer=false,
video::SColor leftUpEdge = video::SColor(0,0,0,0),
video::SColor rightUpEdge = video::SColor(0,0,0,0),
video::SColor leftDownEdge = video::SColor(0,0,0,0),
video::SColor rightDownEdge = video::SColor(0,0,0,0));
//! sets a viewport
virtual void setViewPort(const core::rect<s32>& area);
//! Sets the fog mode.
virtual void setFog(SColor color, bool linearFog, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog);
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
virtual void OnResize(const core::dimension2d<s32>& size);
//! Returns type of video driver
virtual E_DRIVER_TYPE getDriverType();
//! Returns the transformation set by setTransform
virtual const core::matrix4& getTransform(E_TRANSFORMATION_STATE state);
// public access to the (loaded) extensions.
void extGlActiveTextureARB(GLenum texture);
void extGlClientActiveTextureARB(GLenum texture);
void extGlGenProgramsARB(GLsizei n, GLuint *programs);
void extGlBindProgramARB(GLenum target, GLuint program);
void extGlProgramStringARB(GLenum target, GLenum format, GLsizei len, const GLvoid *string);
void extGlDeleteProgramsARB(GLsizei n, const GLuint *programs);
void extGlProgramLocalParameter4fvARB(GLenum, GLuint, const GLfloat *);
GLhandleARB extGlCreateShaderObjectARB(GLenum shaderType);
void extGlShaderSourceARB(GLhandleARB shader, int numOfStrings, const char **strings, int *lenOfStrings);
void extGlCompileShaderARB(GLhandleARB shader);
GLhandleARB extGlCreateProgramObjectARB(void);
void extGlAttachObjectARB(GLhandleARB program, GLhandleARB shader);
void extGlLinkProgramARB(GLhandleARB program);
void extGlUseProgramObjectARB(GLhandleARB prog);
void extGlDeleteObjectARB(GLhandleARB object);
void extGlGetInfoLogARB(GLhandleARB object, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
void extGlGetObjectParameterivARB(GLhandleARB object, GLenum type, int *param);
GLint extGlGetUniformLocationARB(GLhandleARB program, const char *name);
void extGlUniform4fvARB(GLint location, GLsizei count, const GLfloat *v);
void extGlUniform1ivARB (GLint loc, GLsizei count, const GLint *v);
void extGlUniform1fvARB (GLint loc, GLsizei count, const GLfloat *v);
void extGlUniform2fvARB (GLint loc, GLsizei count, const GLfloat *v);
void extGlUniform3fvARB (GLint loc, GLsizei count, const GLfloat *v);
void extGlUniformMatrix2fvARB (GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
void extGlUniformMatrix3fvARB (GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
void extGlUniformMatrix4fvARB (GLint loc, GLsizei count, GLboolean transpose, const GLfloat *v);
void extGlGetActiveUniformARB (GLhandleARB program, GLuint index, GLsizei maxlength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
void extGlPointParameterfARB (GLint loc, GLfloat f);
void extGlPointParameterfvARB (GLint loc, const GLfloat *v);
void extGlStencilFuncSeparate (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
void extGlStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
void extGlCompressedTexImage2D(GLenum target, GLint level,
GLenum internalformat, GLsizei width, GLsizei height,
GLint border, GLsizei imageSize, const void* data);
void extGlBindFramebufferEXT (GLenum target, GLuint framebuffer);
void extGlDeleteFramebuffersEXT (GLsizei n, const GLuint *framebuffers);
void extGlGenFramebuffersEXT (GLsizei n, GLuint *framebuffers);
GLenum extGlCheckFramebufferStatusEXT (GLenum target);
void extGlFramebufferTexture2DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
void extGlBindRenderbufferEXT (GLenum target, GLuint renderbuffer);
void extGlDeleteRenderbuffersEXT (GLsizei n, const GLuint *renderbuffers);
void extGlGenRenderbuffersEXT (GLsizei n, GLuint *renderbuffers);
void extGlRenderbufferStorageEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
void extGlFramebufferRenderbufferEXT (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
//! Can be called by an IMaterialRenderer to make its work easier.
void setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial,
bool resetAllRenderstates);
//! Sets a vertex shader constant.
virtual void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a pixel shader constant.
virtual void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1);
//! Sets a constant for the vertex shader based on a name.
virtual bool setVertexShaderConstant(const c8* name, const f32* floats, int count);
//! Sets a constant for the pixel shader based on a name.
virtual bool setPixelShaderConstant(const c8* name, const f32* floats, int count);
//! sets the current Texture
//! Returns whether setting was a success or not.
bool setTexture(s32 stage, video::ITexture* texture);
//! disables all textures beginning with the optional fromStage parameter. Otherwise all texture stages are disabled.
//! Returns whether disabling was successful or not.
bool disableTextures(s32 fromStage=0);
//! Adds a new material renderer to the VideoDriver, using extGLGetObjectParameterivARB(shaderHandle, GL_OBJECT_COMPILE_STATUS_ARB, &status) pixel and/or
//! vertex shaders to render geometry.
s32 addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram,
IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData);
//! Adds a new material renderer to the VideoDriver, using GLSL to render geometry.
s32 addHighLevelShaderMaterial(const c8* vertexShaderProgram, const c8* vertexShaderEntryPointName,
E_VERTEX_SHADER_TYPE vsCompileTarget, const c8* pixelShaderProgram, const c8* pixelShaderEntryPointName,
E_PIXEL_SHADER_TYPE psCompileTarget, IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial,
s32 userData);
//! Returns pointer to the IGPUProgrammingServices interface.
IGPUProgrammingServices* getGPUProgrammingServices();
//! Returns a pointer to the IVideoDriver interface. (Implementation for
//! IMaterialRendererServices)
virtual IVideoDriver* getVideoDriver();
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
virtual u32 getMaximalPrimitiveCount();
ITexture* createRenderTargetTexture(const core::dimension2d<s32>& size);
bool setRenderTarget(video::ITexture* texture, bool clearBackBuffer,
bool clearZBuffer, SColor color);
//! Clears the ZBuffer.
virtual void clearZBuffer();
//! Returns an image created from the last rendered frame.
virtual IImage* createScreenShot();
//! checks if an OpenGL error has happend and prints it
//! for performance reasons only available in debug mode
bool testGLError();
private:
//! inits the parts of the open gl driver used on all platforms
bool genericDriverInit(const core::dimension2d<s32>& screenSize);
//! returns a device dependent texture from a software surface (IImage)
virtual video::ITexture* createDeviceDependentTexture(IImage* surface, const char* name);
//! creates a transposed matrix in supplied GLfloat array to pass to OpenGL
void createGLMatrix(GLfloat gl_matrix[16], const core::matrix4& m);
void createGLTextureMatrix(GLfloat gl_matrix[16], const core::matrix4& m);
//! sets the needed renderstates
void setRenderStates3DMode();
//! sets the needed renderstates
void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel);
// returns the current size of the screen or rendertarget
core::dimension2d<s32> getCurrentRenderTargetSize();
void loadExtensions();
void createMaterialRenderers();
core::stringw Name;
core::matrix4 Matrices[ETS_COUNT];
core::array<u8> ColorBuffer;
// enumeration for rendering modes such as 2d and 3d for minizing the switching of renderStates.
enum E_RENDER_MODE
{
ERM_NONE = 0, // no render state has been set yet.
ERM_2D, // 2d drawing rendermode
ERM_3D // 3d rendering mode
};
E_RENDER_MODE CurrentRenderMode;
bool ResetRenderStates; // bool to make all renderstates be reseted if set.
bool Transformation3DChanged;
bool StencilBuffer;
bool AntiAlias;
bool MultiTextureExtension;
bool MultiSamplingExtension;
bool AnisotropyExtension;
bool ARBVertexProgramExtension; //GL_ARB_vertex_program
bool ARBFragmentProgramExtension; //GL_ARB_fragment_program
bool ARBShadingLanguage100Extension;
bool SeparateStencilExtension;
bool GenerateMipmapExtension;
bool TextureCompressionExtension;
bool TextureNPOTExtension;
bool FramebufferObjectExtension;
bool EXTPackedDepthStencil;
bool EXTSeparateSpecularColor;
SMaterial Material, LastMaterial;
COpenGLTexture* RenderTargetTexture;
ITexture* CurrentTexture[MATERIAL_MAX_TEXTURES];
s32 LastSetLight;
f32 MaxAnisotropy;
GLint MaxTextureUnits;
GLint MaxLights;
GLint MaxIndices;
core::dimension2d<s32> CurrentRendertargetSize;
#if defined(_IRR_OPENGL_USE_EXTPOINTER_)
PFNGLACTIVETEXTUREARBPROC pGlActiveTextureARB;
PFNGLCLIENTACTIVETEXTUREARBPROC pGlClientActiveTextureARB;
PFNGLGENPROGRAMSARBPROC pGlGenProgramsARB;
PFNGLBINDPROGRAMARBPROC pGlBindProgramARB;
PFNGLPROGRAMSTRINGARBPROC pGlProgramStringARB;
PFNGLDELETEPROGRAMSNVPROC pGlDeleteProgramsARB;
PFNGLPROGRAMLOCALPARAMETER4FVARBPROC pGlProgramLocalParameter4fvARB;
PFNGLCREATESHADEROBJECTARBPROC pGlCreateShaderObjectARB;
PFNGLSHADERSOURCEARBPROC pGlShaderSourceARB;
PFNGLCOMPILESHADERARBPROC pGlCompileShaderARB;
PFNGLCREATEPROGRAMOBJECTARBPROC pGlCreateProgramObjectARB;
PFNGLATTACHOBJECTARBPROC pGlAttachObjectARB;
PFNGLLINKPROGRAMARBPROC pGlLinkProgramARB;
PFNGLUSEPROGRAMOBJECTARBPROC pGlUseProgramObjectARB;
PFNGLDELETEOBJECTARBPROC pGlDeleteObjectARB;
PFNGLGETINFOLOGARBPROC pGlGetInfoLogARB;
PFNGLGETOBJECTPARAMETERIVARBPROC pGlGetObjectParameterivARB;
PFNGLGETUNIFORMLOCATIONARBPROC pGlGetUniformLocationARB;
PFNGLUNIFORM1IVARBPROC pGlUniform1ivARB;
PFNGLUNIFORM1FVARBPROC pGlUniform1fvARB;
PFNGLUNIFORM2FVARBPROC pGlUniform2fvARB;
PFNGLUNIFORM3FVARBPROC pGlUniform3fvARB;
PFNGLUNIFORM4FVARBPROC pGlUniform4fvARB;
PFNGLUNIFORMMATRIX2FVARBPROC pGlUniformMatrix2fvARB;
PFNGLUNIFORMMATRIX3FVARBPROC pGlUniformMatrix3fvARB;
PFNGLUNIFORMMATRIX4FVARBPROC pGlUniformMatrix4fvARB;
PFNGLGETACTIVEUNIFORMARBPROC pGlGetActiveUniformARB;
PFNGLPOINTPARAMETERFARBPROC pGlPointParameterfARB;
PFNGLPOINTPARAMETERFVARBPROC pGlPointParameterfvARB;
#ifdef GL_ATI_separate_stencil
PFNGLSTENCILFUNCSEPARATEPROC pGlStencilFuncSeparate;
PFNGLSTENCILOPSEPARATEPROC pGlStencilOpSeparate;
PFNGLSTENCILFUNCSEPARATEATIPROC pGlStencilFuncSeparateATI;
PFNGLSTENCILOPSEPARATEATIPROC pGlStencilOpSeparateATI;
#endif
#ifdef PFNGLCOMPRESSEDTEXIMAGE2DPROC
PFNGLCOMPRESSEDTEXIMAGE2DPROC pGlCompressedTexImage2D;
#endif // PFNGLCOMPRESSEDTEXIMAGE2DPROC
#ifdef _IRR_WINDOWS_API_
typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALFARPROC)(int);
PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT;
#elif defined(_IRR_LINUX_PLATFORM_) && defined(GLX_SGI_swap_control)
PFNGLXSWAPINTERVALSGIPROC glxSwapIntervalSGI;
#endif
PFNGLBINDFRAMEBUFFEREXTPROC pGlBindFramebufferEXT;
PFNGLDELETEFRAMEBUFFERSEXTPROC pGlDeleteFramebuffersEXT;
PFNGLGENFRAMEBUFFERSEXTPROC pGlGenFramebuffersEXT;
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC pGlCheckFramebufferStatusEXT;
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC pGlFramebufferTexture2DEXT;
PFNGLBINDRENDERBUFFEREXTPROC pGlBindRenderbufferEXT;
PFNGLDELETERENDERBUFFERSEXTPROC pGlDeleteRenderbuffersEXT;
PFNGLGENRENDERBUFFERSEXTPROC pGlGenRenderbuffersEXT;
PFNGLRENDERBUFFERSTORAGEEXTPROC pGlRenderbufferStorageEXT;
PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC pGlFramebufferRenderbufferEXT;
#endif
#ifdef _IRR_WINDOWS_API_
HDC HDc; // Private GDI Device Context
HWND Window;
HGLRC HRc; // Permanent Rendering Context
#elif defined(_IRR_USE_LINUX_DEVICE_)
GLXDrawable XWindow;
Display* XDisplay;
#elif defined(MACOSX)
CIrrDeviceMacOSX *_device;
#endif
#if defined(__SYMBIAN32__)
EGLSurface eglWindowSurface;
EGLDisplay eglDisplay;
#endif
};
} // end namespace video
} // end namespace irr
#endif // _IRR_COMPILE_WITH_OPENGL_
#endif
|
nistefan/cmssw
|
FWCore/Catalog/interface/FileLocator.h
|
#ifndef FWCore_Catalog_FileLocator_h
#define FWCore_Catalog_FileLocator_h
#include <string>
#include <list>
#include <map>
#include <utility>
#include <regex>
#include <xercesc/dom/DOM.hpp>
namespace edm {
class FileLocator {
public:
explicit FileLocator(std::string const& catUrl, bool fallback);
~FileLocator();
std::string pfn(std::string const& ilfn) const;
std::string lfn(std::string const& ipfn) const;
private:
/** For the time being the only allowed configuration item is a
* prefix to be added to the GUID/LFN.
*/
static int s_numberOfInstances;
struct Rule {
std::regex pathMatch;
std::regex destinationMatch;
std::string result;
std::string chain;
};
typedef std::vector<Rule> Rules;
typedef std::map<std::string, Rules> ProtocolRules;
void init(std::string const& catUrl, bool fallback);
void parseRule(xercesc::DOMNode* ruleNode,
ProtocolRules& rules);
std::string applyRules(ProtocolRules const& protocolRules,
std::string const& protocol,
std::string const& destination,
bool direct,
std::string name) const;
std::string convert(std::string const& input, ProtocolRules const& rules, bool direct) const;
/** Direct rules are used to do the mapping from LFN to PFN.*/
ProtocolRules m_directRules;
/** Inverse rules are used to do the mapping from PFN to LFN*/
ProtocolRules m_inverseRules;
std::string m_fileType;
std::string m_filename;
std::vector<std::string> m_protocols;
std::string m_destination;
};
}
#endif // FWCore_Catalog_FileLocator_h
|
carpawell/neo-go
|
pkg/network/capability/type.go
|
<filename>pkg/network/capability/type.go
package capability
// Type represents node capability type.
type Type byte
const (
// TCPServer represents TCP node capability type.
TCPServer Type = 0x01
// WSServer represents WebSocket node capability type.
WSServer Type = 0x02
// FullNode represents full node capability type.
FullNode Type = 0x10
)
|
fuldaros/paperplane_kernel_wileyfox-spark
|
sources/drivers/clk/mmp/clk.h
|
<reponame>fuldaros/paperplane_kernel_wileyfox-spark<filename>sources/drivers/clk/mmp/clk.h<gh_stars>10-100
#ifndef __MACH_MMP_CLK_H
#define __MACH_MMP_CLK_H
#include <linux/clk-provider.h>
#include <linux/clkdev.h>
#define APBC_NO_BUS_CTRL BIT(0)
#define APBC_POWER_CTRL BIT(1)
struct clk_factor_masks {
unsigned int factor;
unsigned int num_mask;
unsigned int den_mask;
unsigned int num_shift;
unsigned int den_shift;
};
struct clk_factor_tbl {
unsigned int num;
unsigned int den;
};
extern struct clk *mmp_clk_register_pll2(const char *name,
const char *parent_name, unsigned long flags);
extern struct clk *mmp_clk_register_apbc(const char *name,
const char *parent_name, void __iomem *base,
unsigned int delay, unsigned int apbc_flags, spinlock_t *lock);
extern struct clk *mmp_clk_register_apmu(const char *name,
const char *parent_name, void __iomem *base, u32 enable_mask,
spinlock_t *lock);
extern struct clk *mmp_clk_register_factor(const char *name,
const char *parent_name, unsigned long flags,
void __iomem *base, struct clk_factor_masks *masks,
struct clk_factor_tbl *ftbl, unsigned int ftbl_cnt);
#endif
|
ceekay1991/AliPayForDebug
|
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/aluAppInfo.h
|
<filename>AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/aluAppInfo.h<gh_stars>1-10
//
// 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 NSString;
@interface aluAppInfo : NSObject
{
NSString *_productId;
NSString *_productName;
NSString *_productVersion;
NSString *_channel;
NSString *_clientType;
NSString *_appType;
NSString *_userAgent;
NSString *_appKey;
NSString *_appID;
}
@property(retain, nonatomic) NSString *appID; // @synthesize appID=_appID;
@property(retain, nonatomic) NSString *appKey; // @synthesize appKey=_appKey;
@property(retain, nonatomic) NSString *userAgent; // @synthesize userAgent=_userAgent;
@property(retain, nonatomic) NSString *appType; // @synthesize appType=_appType;
@property(retain, nonatomic) NSString *clientType; // @synthesize clientType=_clientType;
@property(retain, nonatomic) NSString *channel; // @synthesize channel=_channel;
@property(retain, nonatomic) NSString *productVersion; // @synthesize productVersion=_productVersion;
@property(retain, nonatomic) NSString *productName; // @synthesize productName=_productName;
@property(retain, nonatomic) NSString *productId; // @synthesize productId=_productId;
- (void).cxx_destruct;
@end
|
alexfmsu/pyquantum
|
plot_M3D.py
|
from PyQuantum.Tools.PlotBuilder3D import *
plot_builder = PlotBuilder3D({
'title': 'title',
'x_title': 'x_title',
'y_title': 'y_title',
'width': 100,
'height': 100,
'online': True
})
plot_builder.prepare({
'x_csv': 'Bipartite/out/10_5/x.csv',
'y_csv': 'test_y.csv',
'z_csv': 'test_z.csv',
})
|
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
|
src/StockIT-v1-release_source_from_JADX/sources/com/google/zxing/client/result/BizcardResultParser.java
|
package com.google.zxing.client.result;
import com.google.zxing.Result;
import java.util.ArrayList;
public final class BizcardResultParser extends AbstractDoCoMoResultParser {
public AddressBookParsedResult parse(Result result) {
String massagedText = getMassagedText(result);
if (!massagedText.startsWith("BIZCARD:")) {
return null;
}
String buildName = buildName(matchSingleDoCoMoPrefixedField("N:", massagedText, true), matchSingleDoCoMoPrefixedField("X:", massagedText, true));
String matchSingleDoCoMoPrefixedField = matchSingleDoCoMoPrefixedField("T:", massagedText, true);
String matchSingleDoCoMoPrefixedField2 = matchSingleDoCoMoPrefixedField("C:", massagedText, true);
return new AddressBookParsedResult(maybeWrap(buildName), (String[]) null, (String) null, buildPhoneNumbers(matchSingleDoCoMoPrefixedField("B:", massagedText, true), matchSingleDoCoMoPrefixedField("M:", massagedText, true), matchSingleDoCoMoPrefixedField("F:", massagedText, true)), (String[]) null, maybeWrap(matchSingleDoCoMoPrefixedField("E:", massagedText, true)), (String[]) null, (String) null, (String) null, matchDoCoMoPrefixedField("A:", massagedText, true), (String[]) null, matchSingleDoCoMoPrefixedField2, (String) null, matchSingleDoCoMoPrefixedField, (String[]) null, (String[]) null);
}
private static String[] buildPhoneNumbers(String str, String str2, String str3) {
ArrayList arrayList = new ArrayList(3);
if (str != null) {
arrayList.add(str);
}
if (str2 != null) {
arrayList.add(str2);
}
if (str3 != null) {
arrayList.add(str3);
}
int size = arrayList.size();
if (size == 0) {
return null;
}
return (String[]) arrayList.toArray(new String[size]);
}
private static String buildName(String str, String str2) {
if (str == null) {
return str2;
}
if (str2 == null) {
return str;
}
return str + ' ' + str2;
}
}
|
lstyles/nsgflowlogsbeat
|
vendor/github.com/elastic/beats/vendor/github.com/Azure/azure-event-hubs-go/v3/tracing.go
|
package eventhub
import (
"context"
"net/http"
"os"
"strconv"
"github.com/devigned/tab"
)
func (h *Hub) startSpanFromContext(ctx context.Context, operationName string) (tab.Spanner, context.Context) {
ctx, span := tab.StartSpan(ctx, operationName)
ApplyComponentInfo(span)
return span, ctx
}
func (ns *namespace) startSpanFromContext(ctx context.Context, operationName string) (tab.Spanner, context.Context) {
ctx, span := tab.StartSpan(ctx, operationName)
ApplyComponentInfo(span)
return span, ctx
}
func (s *sender) startProducerSpanFromContext(ctx context.Context, operationName string) (tab.Spanner, context.Context) {
ctx, span := tab.StartSpan(ctx, operationName)
ApplyComponentInfo(span)
span.AddAttributes(
tab.StringAttribute("span.kind", "producer"),
tab.StringAttribute("message_bus.destination", s.getFullIdentifier()),
)
return span, ctx
}
func (r *receiver) startConsumerSpanFromContext(ctx context.Context, operationName string) (tab.Spanner, context.Context) {
ctx, span := tab.StartSpan(ctx, operationName)
ApplyComponentInfo(span)
span.AddAttributes(
tab.StringAttribute("span.kind", "consumer"),
tab.StringAttribute("message_bus.destination", r.getFullIdentifier()),
)
return span, ctx
}
func (em *entityManager) startSpanFromContext(ctx context.Context, operationName string) (tab.Spanner, context.Context) {
ctx, span := tab.StartSpan(ctx, operationName)
ApplyComponentInfo(span)
span.AddAttributes(tab.StringAttribute("span.kind", "client"))
return span, ctx
}
// ApplyComponentInfo applies eventhub library and network info to the span
func ApplyComponentInfo(span tab.Spanner) {
span.AddAttributes(
tab.StringAttribute("component", "github.com/Azure/azure-event-hubs-go"),
tab.StringAttribute("version", Version))
applyNetworkInfo(span)
}
func applyNetworkInfo(span tab.Spanner) {
hostname, err := os.Hostname()
if err == nil {
span.AddAttributes(tab.StringAttribute("peer.hostname", hostname))
}
}
func applyRequestInfo(span tab.Spanner, req *http.Request) {
span.AddAttributes(
tab.StringAttribute("http.url", req.URL.String()),
tab.StringAttribute("http.method", req.Method),
)
}
func applyResponseInfo(span tab.Spanner, res *http.Response) {
if res != nil {
span.AddAttributes(tab.StringAttribute("http.status_code", strconv.Itoa(res.StatusCode)))
}
}
|
sango-tech/echarts
|
lib/component/axis/AxisView.js
|
<reponame>sango-tech/echarts
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* AUTO-GENERATED FILE. DO NOT MODIFY.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { __extends } from "tslib";
import * as axisPointerModelHelper from '../axisPointer/modelHelper.js';
import ComponentView from '../../view/Component.js';
var axisPointerClazz = {};
/**
* Base class of AxisView.
*/
var AxisView =
/** @class */
function (_super) {
__extends(AxisView, _super);
function AxisView() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = AxisView.type;
return _this;
}
/**
* @override
*/
AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
// FIXME
// This process should proformed after coordinate systems updated
// (axis scale updated), and should be performed each time update.
// So put it here temporarily, although it is not appropriate to
// put a model-writing procedure in `view`.
this.axisPointerClass && axisPointerModelHelper.fixValue(axisModel);
_super.prototype.render.apply(this, arguments);
this._doUpdateAxisPointerClass(axisModel, api, true);
};
/**
* Action handler.
*/
AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
this._doUpdateAxisPointerClass(axisModel, api, false);
};
/**
* @override
*/
AxisView.prototype.remove = function (ecModel, api) {
var axisPointer = this._axisPointer;
axisPointer && axisPointer.remove(api);
};
/**
* @override
*/
AxisView.prototype.dispose = function (ecModel, api) {
this._disposeAxisPointer(api);
_super.prototype.dispose.apply(this, arguments);
};
AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
if (!Clazz) {
return;
}
var axisPointerModel = axisPointerModelHelper.getAxisPointerModel(axisModel);
axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
};
AxisView.prototype._disposeAxisPointer = function (api) {
this._axisPointer && this._axisPointer.dispose(api);
this._axisPointer = null;
};
AxisView.registerAxisPointerClass = function (type, clazz) {
if (process.env.NODE_ENV !== 'production') {
if (axisPointerClazz[type]) {
throw new Error('axisPointer ' + type + ' exists');
}
}
axisPointerClazz[type] = clazz;
};
;
AxisView.getAxisPointerClass = function (type) {
return type && axisPointerClazz[type];
};
;
AxisView.type = 'axis';
return AxisView;
}(ComponentView);
export default AxisView;
|
enfoTek/tomato.linksys.e2000.nvram-mod
|
release/src/linux/linux/arch/mips/vr41xx/zao-capcella/ide-capcella.c
|
<gh_stars>10-100
/*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* IDE routines for typical pc-like standard configurations
* for the ZAO Networks Capcella.
*
* Copyright (C) 1998, 1999, 2001 by <NAME>
*/
/*
* Changes:
* <NAME> <<EMAIL>> Sun, 24 Feb 2002
* - Added ZAO Networks Capcella support.
*/
#include <linux/sched.h>
#include <linux/ide.h>
#include <linux/ioport.h>
#include <linux/hdreg.h>
#include <asm/ptrace.h>
#include <asm/hdreg.h>
static int capcella_ide_default_irq(ide_ioreg_t base)
{
switch (base) {
case 0x8300: return 42;
}
return 0;
}
static ide_ioreg_t capcella_ide_default_io_base(int index)
{
switch (index) {
case 0: return 0x8300;
}
return 0;
}
static void capcella_ide_init_hwif_ports(hw_regs_t *hw, ide_ioreg_t data_port,
ide_ioreg_t ctrl_port, int *irq)
{
ide_ioreg_t reg = data_port;
int i;
for (i = IDE_DATA_OFFSET; i <= IDE_STATUS_OFFSET; i++) {
hw->io_ports[i] = reg;
reg += 1;
}
if (ctrl_port) {
hw->io_ports[IDE_CONTROL_OFFSET] = ctrl_port;
} else {
hw->io_ports[IDE_CONTROL_OFFSET] = hw->io_ports[IDE_DATA_OFFSET] + 0x206;
}
if (irq != NULL)
*irq = 0;
hw->io_ports[IDE_IRQ_OFFSET] = 0;
}
static int capcella_ide_request_irq(unsigned int irq,
void (*handler)(int,void *, struct pt_regs *),
unsigned long flags, const char *device,
void *dev_id)
{
return request_irq(irq, handler, flags, device, dev_id);
}
static void capcella_ide_free_irq(unsigned int irq, void *dev_id)
{
free_irq(irq, dev_id);
}
static int capcella_ide_check_region(ide_ioreg_t from, unsigned int extent)
{
return check_region(from, extent);
}
static void capcella_ide_request_region(ide_ioreg_t from, unsigned int extent,
const char *name)
{
request_region(from, extent, name);
}
static void capcella_ide_release_region(ide_ioreg_t from, unsigned int extent)
{
release_region(from, extent);
}
struct ide_ops capcella_ide_ops = {
&capcella_ide_default_irq,
&capcella_ide_default_io_base,
&capcella_ide_init_hwif_ports,
&capcella_ide_request_irq,
&capcella_ide_free_irq,
&capcella_ide_check_region,
&capcella_ide_request_region,
&capcella_ide_release_region
};
|
tmdmaker/tmdmaker
|
bundles/org.tmdmaker.ui/src/org/tmdmaker/ui/editor/gef3/editparts/node/SubsetTypeEditPart.java
|
/*
* Copyright 2009-2019 TMD-Maker Project <https://www.tmdmaker.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tmdmaker.ui.editor.gef3.editparts.node;
import java.beans.PropertyChangeEvent;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.jface.dialogs.Dialog;
import org.tmdmaker.core.model.AbstractEntityModel;
import org.tmdmaker.core.model.SubsetType;
import org.tmdmaker.ui.dialogs.SubsetCreateDialog;
import org.tmdmaker.ui.editor.draw2d.figure.node.SubsetTypeFigure;
/**
* サブセット種類のコントローラ.
*
* @author nakaG
*
*/
public class SubsetTypeEditPart extends AbstractSubsetTypeEditPart<SubsetType> {
/**
* コンストラクタ.
*/
public SubsetTypeEditPart(SubsetType type) {
super();
setModel(type);
}
/**
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractSubsetTypeEditPart#propertyChange(java.beans.PropertyChangeEvent)
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(SubsetType.PROPERTY_TYPE)) {
refreshVisuals();
} else if (evt.getPropertyName().equals(SubsetType.PROPERTY_PARTITION)) {
refreshVisuals();
} else {
super.propertyChange(evt);
}
}
/**
*
* {@inheritDoc}
*
* @see org.tmdmaker.ui.editor.gef3.editparts.node.AbstractModelEditPart#updateFigure(org.eclipse.draw2d.IFigure)
*/
@Override
protected void updateFigure(IFigure figure) {
SubsetTypeFigure sf = (SubsetTypeFigure) figure;
SubsetType model = getModel();
sf.setVertical(model.isVertical());
sf.setSameType(model.isSameType());
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.gef.editparts.AbstractEditPart#getCommand(org.eclipse.gef.Request)
*/
@Override
public Command getCommand(Request request) {
if (REQ_OPEN.equals(request.getType())) {
logger.debug("{}#getCommand(req)", getClass());
SubsetType subsetType = getModel();
AbstractEntityModel model = subsetType.getSuperset();
SubsetCreateDialog dialog = new SubsetCreateDialog(getViewer().getControl().getShell(),
model);
if (dialog.open() == Dialog.OK) {
return dialog.getCcommand();
}
}
return super.getCommand(request);
}
}
|
kmdkuk/AndroidTraining
|
Eclipse/assignments/fundamentals/6th/ListViewAssignment/src/jp/mixi/assignment/listview/beg/BookActivity.java
|
<filename>Eclipse/assignments/fundamentals/6th/ListViewAssignment/src/jp/mixi/assignment/listview/beg/BookActivity.java
package jp.mixi.assignment.listview.beg;
import android.app.Activity;
import android.os.Bundle;
public class BookActivity extends Activity {
@SuppressWarnings("unused")
private static final String TAG = BookActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
// TODO:MainActiviyから送られてきたtitleを表示してください。
}
}
|
mauricioszabo/relational-scala
|
src/main/scala/relational/comparissions/None.scala
|
<reponame>mauricioszabo/relational-scala
package relational.comparissions
import relational.comparissions.Equality.{Comparission => EComp}
import relational.PartialStatement
object None extends Comparission {
lazy val partial = PartialStatement { a => "" -> Nil }
override protected def newEquality(k: EComp, a: Any): Comparission = None
override def in(s: Seq[Any]) = None
override def isNull = None
override def ||(other: Comparission) = other
override def &&(other: Comparission) = other
override def unary_! = None
}
|
lobbyra/minishell
|
srcs/execution/builtins/export_utils.c
|
<filename>srcs/execution/builtins/export_utils.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* export_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jecaudal <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/06/26 14:55:00 by jecaudal #+# #+# */
/* Updated: 2020/07/24 16:10:53 by jecaudal ### ########.fr */
/* */
/* ************************************************************************** */
/*
** This is additionnal functions for export minishell builtin.
*/
#include "minishell.h"
void print_envp_export(char **envp, int fd)
{
char *temp;
char **dup;
char **save_dup;
dup = ft_strarrdup(envp);
save_dup = dup;
ft_sort_strs(dup);
while (*dup)
{
if (**dup != '_')
{
temp = *dup;
write(fd, "declare -x ", 11);
write(fd, temp, ft_strlen_c(temp, '=') + 1);
ft_skip_until(&temp, '=');
temp++;
write(fd, "\"", 1);
write(fd, temp, ft_strlen(temp));
write(fd, "\"", 1);
write(fd, "\n", 1);
}
dup++;
}
ft_freestrs(save_dup);
}
t_bool is_var_exist(char **envp, char *arg)
{
while (*envp)
{
if (ft_strncmp(*envp, arg, ft_strlen_c(*envp, '=')) == 0)
return (TRUE);
envp++;
}
return (FALSE);
}
/*
** static function for var_replacement.
*/
static char **var_finder(char **envp, char *arg)
{
int len_name;
len_name = 0;
while (arg[len_name] != '=')
len_name++;
while (*envp)
{
if (ft_strncmp(*envp, arg, len_name + 1) == 0)
return (envp);
envp++;
}
return (NULL);
}
/*
** This function will replace the value of a variable in envp.
** Return ERR_MALLOC or 0 if success.
*/
int var_replacement(char **envp, char *arg)
{
char **to_replace;
to_replace = var_finder(envp, arg);
free(*to_replace);
if (!(*to_replace = ft_strdup(arg)))
return (ERR_MALLOC);
return (0);
}
|
Clariones/event-driven-generation
|
projects/project_moyi/cla/edg/project/moyi/gen/graphquery/WithdrawConfiguration.java
|
<reponame>Clariones/event-driven-generation<gh_stars>1-10
package cla.edg.project.moyi.gen.graphquery;
import java.util.Map;
import cla.edg.modelbean.*;
public class WithdrawConfiguration extends BaseModelBean {
public String getFullClassName() {
return "com.terapico.moyi.withdrawconfiguration.WithdrawConfiguration";
}
// 枚举对象
// 引用的对象
public Moyi moyi() {
Moyi member = new Moyi();
member.setModelTypeName("moyi");
member.setName("moyi");
member.setMemberName("moyi");
member.setReferDirection(true);
member.setRelationName("moyi");
append(member);
return member;
}
// 被引用的对象
// 普通属性
public StringAttribute id() {
StringAttribute member = new StringAttribute();
member.setModelTypeName("string");
// member.setName("id");
member.setName("id");
useMember(member);
return member;
}
public StringAttribute defaultPaymentMethod() {
StringAttribute member = new StringAttribute();
member.setModelTypeName("string");
// member.setName("defaultPaymentMethod");
member.setName("default_payment_method");
useMember(member);
return member;
}
public StringAttribute payingAccount() {
StringAttribute member = new StringAttribute();
member.setModelTypeName("string");
// member.setName("payingAccount");
member.setName("paying_account");
useMember(member);
return member;
}
public NumberAttribute singleTradeUpperLimit() {
NumberAttribute member = new NumberAttribute();
member.setModelTypeName("double");
// member.setName("singleTradeUpperLimit");
member.setName("single_trade_upper_limit");
useMember(member);
return member;
}
public NumberAttribute singleTradeLowerLimit() {
NumberAttribute member = new NumberAttribute();
member.setModelTypeName("double");
// member.setName("singleTradeLowerLimit");
member.setName("single_trade_lower_limit");
useMember(member);
return member;
}
public NumberAttribute version() {
NumberAttribute member = new NumberAttribute();
member.setModelTypeName("int");
// member.setName("version");
member.setName("version");
useMember(member);
return member;
}
}
|
TinaXie/MTToolsLib
|
MTToolsLib/Classes/CustomView/UIView+MT.h
|
//
// UIView+MT.h
// TToolsHelper
//
// Created by xiejc on 2017/7/31.
// Copyright © 2017年 Xiejc. All rights reserved.
//
#import <UIKit/UIKit.h>
#define UI_IS_IPHONE4 ([[UIScreen mainScreen] bounds].size.height < 568.0)
#define UI_IS_IPHONE5 ([[UIScreen mainScreen] bounds].size.height == 568.0)
#define UI_IS_IPHONE6 ([[UIScreen mainScreen] bounds].size.height == 667.0)
#define UI_IS_IPHONE6PLUS ([[UIScreen mainScreen] bounds].size.height == 736.0 || [[UIScreen mainScreen] bounds].size.width == 736.0)
#define UI_IS_IPHONEX (Screen_Height == 812.0 || Screen_Height == 896.0)
#define Screen_Width [UIScreen mainScreen].bounds.size.width
#define Screen_Height [UIScreen mainScreen].bounds.size.height
#define ViewByNib(nibName) [UIView viewByNib:nibName]
#define ViewByNibWithClass(class) [UIView viewByNib:NSStringFromClass(class)]
@interface UIView (MT)
/**
* 获取当前App的view window
*
* @return 当前View的窗口
*/
+ (UIWindow *)getCurrentWindow;
/**
从nib创建view
@param nibName nibname
@return view
*/
+ (id)viewByNib:(NSString *)nibName;
/**
* 获取view的显示 ViewController
*
* @return 显示ViewController
*/
- (UIViewController *)viewControllerOwnner;
/**
* 清除view的所有子View
*/
- (void)clearAllSubViews;
/**
* 截图视图
*
* @return 截图图片
*/
- (UIImage *)captureImage;
#pragma mark - corner
/**
* 圆角化页面
*
* @param cornerR 圆角半径
* @param borderColor 边线颜色
*/
- (void)cornerWithRadius:(float)cornerR borderColor:(UIColor *)borderColor;
- (void)cornerWithRadius:(float)cornerR borderColor:(UIColor *)borderColor borderWidth:(CGFloat)borderWidth;
/**
半圆角化
@param borderColor 边线颜色
*/
- (void)cornerHalfWithBorderColor:(UIColor *)borderColor;
/**
* 顶部圆角化页面
*
* @param cornerR 圆角半径
* @param borderColor 边线颜色
*/
- (void)cornerTopWithRadius:(float)cornerR borderColor:(UIColor *)borderColor;
/**
添加四边阴影颜色
@param color color
*/
- (void)shadowWithColor:(UIColor *)color;
/**
添加四边阴影效果
@param offset 偏移量
@param cornerR 阴影半径
@param theColor 阴影颜色
@param shadowOpacity 阴影透明度
*/
- (void)shadowWithOffset:(float)offset raduis:(float)cornerR color:(UIColor *)color opacity:(float)opacity;
#pragma mark - frame
- (CGFloat)x;
- (CGFloat)y;
- (CGFloat)width;
- (CGFloat)height;
- (void)resetXFrame:(float)x;
- (void)resetYFrame:(float)y;
- (void)resetWidthFrame:(float)w;
- (void)resetHeightFrame:(float)h;
@end
|
adelbennaceur/carla
|
Util/OSM2ODR/src/utils/iodevices/PlainXMLFormatter.h
|
/****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2012-2020 German Aerospace Center (DLR) and others.
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0/
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License 2.0 are satisfied: GNU General Public License, version 2
// or later which is available at
// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
/****************************************************************************/
/// @file PlainXMLFormatter.h
/// @author <NAME>
/// @author <NAME>
/// @date 2012
///
// Output formatter for plain XML output
/****************************************************************************/
#pragma once
#include <config.h>
#include "OutputFormatter.h"
// ===========================================================================
// class definitions
// ===========================================================================
/**
* @class PlainXMLFormatter
* @brief Output formatter for plain XML output
*
* PlainXMLFormatter format XML like output into the output stream.
*/
class PlainXMLFormatter : public OutputFormatter {
public:
/// @brief Constructor
PlainXMLFormatter(const int defaultIndentation = 0);
/// @brief Destructor
virtual ~PlainXMLFormatter() { }
/** @brief Writes an XML header with optional configuration
*
* If something has been written (myXMLStack is not empty), nothing
* is written and false returned.
*
* @param[in] into The output stream to use
* @param[in] rootElement The root element to use
* @param[in] attrs Additional attributes to save within the rootElement
* @todo Describe what is saved
*/
bool writeXMLHeader(std::ostream& into, const std::string& rootElement,
const std::map<SumoXMLAttr, std::string>& attrs);
/** @brief Writes an XML header with optional configuration
*
* If something has been written (myXMLStack is not empty), nothing
* is written and false returned.
*
* @param[in] into The output stream to use
* @param[in] rootElement The root element to use
*/
bool writeHeader(std::ostream& into, const SumoXMLTag& rootElement);
/** @brief Opens an XML tag
*
* An indentation, depending on the current xml-element-stack size, is written followed
* by the given xml element ("<" + xmlElement)
* The xml element is added to the stack, then.
*
* @param[in] into The output stream to use
* @param[in] xmlElement Name of element to open
* @return The OutputDevice for further processing
*/
void openTag(std::ostream& into, const std::string& xmlElement);
/** @brief Opens an XML tag
*
* Helper method which finds the correct string before calling openTag.
*
* @param[in] into The output stream to use
* @param[in] xmlElement Id of the element to open
*/
void openTag(std::ostream& into, const SumoXMLTag& xmlElement);
/** @brief Closes the most recently opened tag
*
* @param[in] into The output stream to use
* @return Whether a further element existed in the stack and could be closed
* @todo it is not verified that the topmost element was closed
*/
bool closeTag(std::ostream& into, const std::string& comment = "");
/** @brief writes a preformatted tag to the device but ensures that any
* pending tags are closed
* @param[in] into The output stream to use
* @param[in] val The preformatted data
*/
void writePreformattedTag(std::ostream& into, const std::string& val);
/** @brief writes arbitrary padding
*/
void writePadding(std::ostream& into, const std::string& val);
/** @brief writes an arbitrary attribute
*
* @param[in] into The output stream to use
* @param[in] attr The attribute (name)
* @param[in] val The attribute value
*/
template <class T>
static void writeAttr(std::ostream& into, const std::string& attr, const T& val) {
into << " " << attr << "=\"" << toString(val, into.precision()) << "\"";
}
/** @brief writes a named attribute
*
* @param[in] into The output stream to use
* @param[in] attr The attribute (name)
* @param[in] val The attribute value
*/
template <class T>
static void writeAttr(std::ostream& into, const SumoXMLAttr attr, const T& val) {
into << " " << toString(attr) << "=\"" << toString(val, into.precision()) << "\"";
}
private:
/// @brief The stack of begun xml elements
std::vector<std::string> myXMLStack;
/// @brief The initial indentation level
int myDefaultIndentation;
/// @brief whether a closing ">" might be missing
bool myHavePendingOpener;
};
|
moe123/macadam
|
macadam/details/numa/mc_mulax3x3.h
|
<reponame>moe123/macadam
//
// # -*- coding: utf-8, tab-width: 3 -*-
// mc_mulax3x3.h
//
// Copyright (C) 2019-2021 Moe123. All rights reserved.
//
#include <macadam/details/numa/mc_addmulax3x3.h>
#ifndef MC_MULAX3X3_H
#define MC_MULAX3X3_H
#pragma mark - mc_mulax3x3 -
MC_TARGET_FUNC void mc_mulax3x3f(float * b, const float a[9], const float x[3])
{
//!# Requires b[3 x 1], a[3 * 3] and x[3 x 1].
//!# b=a*x
const float x0 = x[0];
const float x1 = x[1];
const float x2 = x[2];
b[0] = a[0] * x0;
b[0] = b[0] + (a[1] * x1);
b[0] = b[0] + (a[2] * x2);
b[1] = a[3] * x0;
b[1] = b[1] + (a[4] * x1);
b[1] = b[1] + (a[5] * x2);
b[2] = a[6] * x0;
b[2] = b[2] + (a[7] * x1);
b[2] = b[2] + (a[8] * x2);
}
MC_TARGET_FUNC void mc_mulax3x3ff(double * b, const float a[9], const float x[3])
{
//!# Requires b[3 x 1], a[3 * 3] and x[3 x 1].
//!# b=a*x
b[0] = 0.0; b[1] = 0.0; b[2] = 0.0;
mc_addmulax3x3ff(b, a, x);
}
MC_TARGET_FUNC void mc_mulax3x3(double * b, const double a[9], const double x[3])
{
//!# Requires b[3 x 1], a[3 * 3] and x[3 x 1].
//!# b=a*x
const double x0 = x[0];
const double x1 = x[1];
const double x2 = x[2];
b[0] = a[0] * x0;
b[0] = b[0] + (a[1] * x1);
b[0] = b[0] + (a[2] * x2);
b[1] = a[3] * x0;
b[1] = b[1] + (a[4] * x1);
b[1] = b[1] + (a[5] * x2);
b[2] = a[6] * x0;
b[2] = b[2] + (a[7] * x1);
b[2] = b[2] + (a[8] * x2);
}
MC_TARGET_FUNC void mc_mulax3x3l(long double * b, const long double a[9], const long double x[3])
{
//!# Requires b[3 x 1], a[3 * 3] and x[3 x 1].
//!# b=a*x
const long double x0 = x[0];
const long double x1 = x[1];
const long double x2 = x[2];
b[0] = a[0] * x0;
b[0] = b[0] + (a[1] * x1);
b[0] = b[0] + (a[2] * x2);
b[1] = a[3] * x0;
b[1] = b[1] + (a[4] * x1);
b[1] = b[1] + (a[5] * x2);
b[2] = a[6] * x0;
b[2] = b[2] + (a[7] * x1);
b[2] = b[2] + (a[8] * x2);
}
#endif /* !MC_MULAX3X3_H */
/* EOF */
|
panxudong/pxd-base
|
algorithms-tree/src/main/java/com/pxd/base/algorithms/tree/binary/TreeIsComplete.java
|
<filename>algorithms-tree/src/main/java/com/pxd/base/algorithms/tree/binary/TreeIsComplete.java
package com.pxd.base.algorithms.tree.binary;
import com.pxd.base.algorithms.commons.tree.binary.BinaryTreeBuilder;
import com.pxd.base.algorithms.commons.tree.binary.BinaryTreeNode;
import com.pxd.base.algorithms.commons.tree.binary.BinaryTreePrinter;
import lombok.Builder;
import org.apache.commons.collections4.CollectionUtils;
import java.util.Arrays;
import java.util.LinkedList;
/**
* Created by panxudong on 2019/11/24.
* Description: 判断二叉树是不是完全二叉树
* Reference: 完全二叉树定义为若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树
*/
@Builder
public class TreeIsComplete {
public static void main(String[] args) {
BinaryTreeNode root_1 = BinaryTreeBuilder.newInstance().appendNodes(Arrays.asList(1, 2, 3, 4, 5, 6, 7)).build();
BinaryTreeNode root_2 = BinaryTreeBuilder.newInstance().appendNodes(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).build();
BinaryTreeBuilder root_3_builder = BinaryTreeBuilder.newInstance().appendNodes(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
root_3_builder.appendNode(-1, true);
root_3_builder.appendNode(-1, true);
root_3_builder.appendNode(-1, true);
root_3_builder.appendNode(-1, true);
root_3_builder.appendNode(-1, true);
root_3_builder.appendNode(-1, true);
root_3_builder.appendNode(10, false);
BinaryTreeNode root_3 = root_3_builder.build();
TreeIsComplete treeIsComplete = TreeIsComplete.builder().build();
System.out.print("root_1:");
BinaryTreePrinter.print(root_1);
System.out.println("root_1 is complete:" + treeIsComplete.isComplete(root_1));
System.out.println("root_1 is complete by recursion:" + treeIsComplete.isCompleteByRecursion(root_1));
System.out.println("root_1 is full:" + treeIsComplete.isFull(root_1));
System.out.print("root_2:");
BinaryTreePrinter.print(root_2);
System.out.println("root_2 is complete:" + treeIsComplete.isComplete(root_2));
System.out.println("root_2 is complete by recursion:" + treeIsComplete.isCompleteByRecursion(root_2));
System.out.println("root_2 is full:" + treeIsComplete.isFull(root_2));
System.out.print("root_3:");
BinaryTreePrinter.print(root_3);
System.out.println("root_3 is complete:" + treeIsComplete.isComplete(root_3));
System.out.println("root_3 is complete by recursion:" + treeIsComplete.isCompleteByRecursion(root_3));
System.out.println("root_3 is full:" + treeIsComplete.isFull(root_3));
}
/**
* 迭代解法
* 思路:
* 逐层遍历二叉树结点,一旦遍历到空结点,那么不在往队列里加入结点了,遍历队列里的已有元素,若有一个不是空结点,那么就不是完全二叉树,若全是空结点那么就是完全二叉树
*
* @param root
* @return
*/
public boolean isComplete(BinaryTreeNode root) {
if (root == null || root.getNode() == null || root.getNode().isNull()) {
return false;
}
LinkedList<BinaryTreeNode> queue = new LinkedList<>();
queue.addFirst(root);
boolean isNoChild = false;
while (CollectionUtils.isNotEmpty(queue)) {
BinaryTreeNode node = queue.removeLast();
if (isNoChild) {
if ((node.getLeft() == null || node.getLeft().getNode() == null || node.getLeft().getNode().isNull()) &&
(node.getRight() == null || node.getRight().getNode() == null || node.getRight().getNode().isNull())) {
continue;
} else {
return false;
}
}
if (node.getLeft() != null && node.getRight() != null
&& node.getLeft().getNode() != null && node.getRight().getNode() != null
&& !node.getLeft().getNode().isNull() && !node.getRight().getNode().isNull()) {
queue.addFirst(node.getLeft());
queue.addFirst(node.getRight());
}
if ((node.getLeft() != null && node.getLeft().getNode() != null && !node.getLeft().getNode().isNull())
&& (node.getRight() == null || node.getRight().getNode() == null || node.getRight().getNode().isNull())) {
queue.addFirst(node.getLeft());
isNoChild = true;
}
if ((node.getLeft() == null || node.getLeft().getNode() == null || node.getLeft().getNode().isNull())
&& (node.getRight() != null && node.getRight().getNode() != null && !node.getRight().getNode().isNull())) {
return false;
}
if ((node.getLeft() == null || node.getLeft().getNode() == null || node.getLeft().getNode().isNull())
&& (node.getRight() == null || node.getRight().getNode() == null || node.getRight().getNode().isNull())) {
isNoChild = true;
}
}
return true;
}
/**
* 递归解法
* 思路:
* 完全二叉树的定义决定(左子树深度 - 右子树深度)只有两种取值0、1;
* <p>如果等于0,说明左子树是一棵满二叉树,判断左子树的结点个数是否为 2^n - 1,如果不是,返回false,如果是,递归判断右子树是否是完全二叉树
* <p>如果等于1,说明右子树是一棵满二叉树,判断右子树的结点个数是否为 2^n - 1,如果不是,返回false,如果是,递归判断左子树是否是完全二叉树
* <p>如果不等于0、1,说明不是一棵完全二叉树
*
* @param root
* @return
*/
public boolean isCompleteByRecursion(BinaryTreeNode root) {
if (root == null || root.getNode() == null || root.getNode().isNull()) {
return true;
}
TreeDepth treeDepth = TreeDepth.builder().build();
int leftDepth = treeDepth.getTreeDepth(root.getLeft());
int rightDepth = treeDepth.getTreeDepth(root.getRight());
TreeCount treeCount = TreeCount.builder().build();
int diff = leftDepth - rightDepth;
int count;
switch (diff) {
case 0:
count = treeCount.getTreeNumber(root.getLeft());
if (count != Double.valueOf(Math.pow(2, leftDepth)).intValue() - 1) {
return false;
} else {
return this.isCompleteByRecursion(root.getRight());
}
case 1:
count = treeCount.getTreeNumber(root.getRight());
if (count != Double.valueOf(Math.pow(2, rightDepth)).intValue() - 1) {
return false;
} else {
return this.isCompleteByRecursion(root.getLeft());
}
default:
return false;
}
}
/**
* 判断是否是满二叉树
* 满二叉树定义:一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是满二叉树。也就是说,如果一个二叉树的层数为K,且结点总数是(2^k) -1 ,则它就是满二叉树
* 思路:
* 1.计算树的深度depth,结点个数count
* 2.判断 count == 2^depth - 1 并返回
*
* @param root
* @return
*/
public boolean isFull(BinaryTreeNode root) {
if (root == null || root.getNode() == null || root.getNode().isNull()) {
return true;
}
TreeDepth treeDepth = TreeDepth.builder().build();
TreeCount treeCount = TreeCount.builder().build();
int depth = treeDepth.getTreeDepth(root);
int count = treeCount.getTreeNumber(root);
return count == Double.valueOf(Math.pow(2, depth)).intValue() - 1;
}
}
|
AK-21/ElBandido
|
src/main/java/org/elbandido/application/ui/ToolButtonDelete.java
|
<reponame>AK-21/ElBandido
package org.elbandido.application.ui;
import org.elbandido.application.data.FileSystem;
import org.elbandido.dialog.ToolButton;
import javax.swing.*;
import java.io.File;
class ToolButtonDelete extends ToolButton
{
private static final ImageIcon ICON_DELETE = new ImageIcon(FileSystem.PATH_ICONS + File.separator + "delete.png");
ToolButtonDelete()
{
super(ICON_DELETE);
}
}
|
bytemaster-0xff/DroneTek
|
NiVek/Micro/Firmware/MultiWii_Picopter/def.h
|
#ifndef DEF_H
#define DEF_H
#define DRONE_NAME_LENGTH 32
#define I2C_PULLUPS_ENABLE PORTD |= 1<<0; PORTD |= 1<<1; // PIN A4&A5 (SDA&SCL)
#define I2C_PULLUPS_DISABLE PORTD &= ~(1<<0); PORTD &= ~(1<<1);
#define ISR_UART ISR(USART0_UDRE_vect)
#define ISR_TWI ISR(TWI_vect_num);
#define ACC_ORIENTATION(X, Y, Z) {imu.accADC[ROLL] = -Y; imu.accADC[PITCH] = X; imu.accADC[YAW] = Z;}
#define GYRO_ORIENTATION(X, Y, Z) {imu.gyroADC[ROLL] = -Y; imu.gyroADC[PITCH] = X; imu.gyroADC[YAW] = Z;}
#define GYRO_CALIBRATION_SAMPLES 400
#define ACC_CALIBRATION_SAMPLES 400
#define null 0
#define ACC 1
#define MAG 1
#define GYRO 1
#define BARO 1
#define GPSPRESENT 0
#define ROLL 0
#define PITCH 1
#define YAW 2
#define THROTTLE 3
#define AUX1 4
#define AUX2 5
#define CAMPITCH 6
#define CAMROLL 7
#define PIDALT 3
#define PIDLEVEL 4
#define MULTITYPE 3
enum LEDTypes{
LEDComms = 0,
LEDOnline = 1,
LEDFailure = 2,
LEDArmed = 3,
};
#define NUMBERLEDS LEDArmed + 1
enum LEDStates{
LEDOn,
LEDOff,
LEDFastBlick,
LEDSlowBlink,
};
#define LEDPort PORTF
#define LEDPINComms 2
#define LEDPINArmed 3
#define LEDPINFail 4
#define LEDPINOnline 5
typedef struct {
int32_t X, Y, Z;
} t_int32_t_vector_def;
typedef struct {
uint16_t XL; int16_t X;
uint16_t YL; int16_t Y;
uint16_t ZL; int16_t Z;
} t_int16_t_vector_def;
typedef union {
int32_t A32[3];
t_int32_t_vector_def V32;
int16_t A16[6];
t_int16_t_vector_def V16;
} t_int32_t_vector;
#endif
|
sbyount/learning_python_2016
|
class6ex1.py
|
# multiplication function
def multiply(x, y, z=1):
num_sum = x*y*z
print num_sum
multiply(2,5,10)
print '\n'
multiply(y=5, x=2, z=10)
print '\n'
multiply(2,5, z=10)
print '\n'
multiply(2,5)
|
fangjinuo/langx-java
|
langx-java/src/main/java/com/jn/langx/event/remote/RemoteEventPublisher.java
|
package com.jn.langx.event.remote;
import com.jn.langx.event.DomainEvent;
import com.jn.langx.event.EventListener;
import com.jn.langx.event.EventPublisher;
public interface RemoteEventPublisher<EVENT extends DomainEvent> extends EventPublisher<EVENT> {
@Override
void publish(EVENT event);
@Override
void addEventListener(String eventDomain, EventListener listener);
@Override
void addFirst(String eventDomain, EventListener listener);
}
|
tuobaye0711/codewars
|
solution/Does my number look big in this.js
|
<reponame>tuobaye0711/codewars
const narcissistic = value => {
let arr = value.toString().split('').map(s => parseInt(s));
let sum = 0;
for (let i = 0; sum < value; i++) {
sum = 0;
arr.forEach(n => sum += Math.pow(n, i))
if (sum === value) {
return true
}
}
return false
}
|
metalels/rundock
|
spec/integration/recipes/file_hook_spec.rb
|
<reponame>metalels/rundock<filename>spec/integration/recipes/file_hook_spec.rb
require 'spec_helper'
describe file('/var/tmp/hello_rundock_from_file_hook_inner_one_scenario') do
it { should be_file }
its(:content) { should match(/hookname:file_hook_one /) }
its(:content) { should match(/DEBUG/) }
end
describe file('/var/tmp/hello_rundock_from_file_hook_inner_two_scenario') do
it { should be_file }
its(:content) { should match(/hookname:file_hook_two /) }
its(:content) { should match(/DEBUG/) }
end
|
turesnake/leetPractice
|
src/_leetcode/leet_945.cpp
|
/*
* ====================== leet_945.cpp ==========================
* -- tpr --
* CREATE -- 2020.04.14
* MODIFY --
* ----------------------------------------------------------
* 945. 使数组唯一的最小增量
*/
#include "innLeet.h"
namespace leet_945 {//~
int minIncrementForUnique( std::vector<int>& A ) {
if( A.size()<2 ){ return 0; }
std::sort( A.begin(), A.end() );
auto slow = A.begin();
auto fast = slow;
int num {0};
int sum {0};
int curVal {0};
int nextVal {0}; // next elem or INT_MAX
for( ; slow!=A.end(); slow=fast ){
// search next elem or end
if( (slow+1)==A.end() ){ // slow is last elem
fast = A.end();
nextVal = INT_MAX;
}else{
fast = slow+1;
while( true ){
if( fast == A.end() ){
nextVal = INT_MAX;
break;
}
if( *fast == *slow ){
num++;
sum -= *fast; // 负数形式存储 base
}else{
nextVal = *fast;
break;
}
fast++;
}
}
// 处理元素
curVal = *slow;
for( ; (num>0) && (nextVal>curVal+1) ; num-- ){
curVal++;
sum += curVal; // 正数形式存储 targetVal
}
}
return sum;
}
int minIncrementForUnique_2( std::vector<int>& A ) {
if( A.size()<2 ){ return 0; }
std::sort( A.begin(), A.end() );
int sum {0};
for( auto it = A.begin()+1; it!=A.end(); it++ ){
if( *it <= *(it-1) ){
int newVal = *(it-1) + 1;
sum += newVal - *it;
*it = newVal;
}
}
return sum;
}
// 返回找到的 位置
int findPos( int pos_, std::vector<int> &poses_ ){
int curVal = poses_.at(pos_);
if( curVal == -1 ){ // slot empty
poses_.at(pos_) = pos_;
return pos_;
}else{
int ret = findPos( curVal+1, poses_ );
poses_.at(pos_) = ret;
return ret;
}
}
int minIncrementForUnique_3( std::vector<int>& A ) {
if( A.size()<2 ){ return 0; }
std::vector<int> poses ( 8000, -1 );
int sum {0};
for( const auto i : A ){
int ret = findPos( i, poses );
sum += ret - i;
}
return sum;
}
//=========================================================//
void main_(){
std::vector<int> v {
2,2,2,1
};
auto ret = minIncrementForUnique_3( v );
cout << "ret = " << ret << endl;
debug::log( "\n~~~~ leet: 945 :end ~~~~\n" );
}
}//~
|
hsadler/zentype2
|
app/server/api/web/user_api.py
|
<reponame>hsadler/zentype2
# User API
from flask import Blueprint, jsonify, request
from flask_jwt_simple import (
jwt_required,
get_jwt_identity
)
from service.user import User
user_api = Blueprint('user_api', __name__)
@user_api.route('/get-data', methods=['GET'])
@jwt_required
def get_data():
"""
Get api formatted user data.
"""
user_data = get_jwt_identity()
api_formatted_user_data = {}
allowed_keys = ['email']
for key in allowed_keys:
api_formatted_user_data[key] = user_data[key]
res = {
'success': True,
'result': { 'user_data': api_formatted_user_data }
}
return jsonify(res)
|
strawsyz/straw
|
my_cv/famous_netorks/VAE_pytorch/utils.py
|
<filename>my_cv/famous_netorks/VAE_pytorch/utils.py
import torch
def save_params(net, file_name):
# 只保存网络中的参数 (速度快, 占内存少)
torch.save(net.state_dict(), file_name + ".pkl")
def load_params(target_net, path):
# 将保存的参数复制到 target_net
target_net.load_state_dict(torch.load(path))
return target_net
|
549654033/RDHelp
|
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/ace/Monitor_T.h
|
<reponame>549654033/RDHelp
/*********************************************************************
** Copyright (C) 2003 Terabit Pty Ltd. All rights reserved.
**
** This file is part of the POSIX-Proactor module.
**
**
**
**
**
**
** @author <NAME> <<EMAIL>>
**
**********************************************************************/
#ifndef TERABIT_MONITOR_T_H
#define TERABIT_MONITOR_T_H
#include /**/ "ace/pre.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "ace/OS_NS_sys_time.h"
#include "ace/Time_Value.h"
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
// **********************************************************
//
//
// **********************************************************
template <typename MTX, typename COND>
class Monitor_T
{
public:
typedef MTX Mutex;
typedef COND Condition;
typedef Monitor_T<MTX, COND> Monitor;
Monitor_T (): mtx_ (), cond_(mtx_) {}
~Monitor_T () {}
int acquire () { return mtx_.acquire();}
int release () { return mtx_.release();}
int signal () { return cond_.signal();}
int broadcast() { return cond_.broadcast();}
int wait () { return cond_.wait(); }
int wait (ACE_Time_Value * tv, bool flgAbsTime) ;
private:
// copy operations are prohibited
Monitor_T (const Monitor_T<MTX,COND> & other);
Monitor_T& operator=(const Monitor_T<MTX,COND> & other);
Mutex mtx_;
Condition cond_;
};
template <typename MTX, typename COND>
inline int
Monitor_T<MTX,COND>::wait (ACE_Time_Value * tv, bool flgAbsTime)
{
if (!tv)
return cond_.wait();
if (flgAbsTime)
return cond_.wait(tv);
ACE_Time_Value abs_time = ACE_OS::gettimeofday ();
abs_time += (*tv);
return cond_.wait (&abs_time);
}
// **********************************************************
//
//
// **********************************************************
template <typename MON>
class Guard_Monitor_T
{
public:
typedef typename MON::Mutex Mutex;
typedef typename MON::Condition Condition;
typedef typename MON::Monitor Monitor;
typedef Guard_Monitor_T < MON > Guard_Monitor;
Guard_Monitor_T (MON & monitor, bool flgLock = true);
~Guard_Monitor_T ();
bool locked () const { return locked_; }
void acquire ();
void release ();
void signal ();
void broadcast ();
int wait ();
int wait (ACE_Time_Value * tv, bool flgAbsTime);
template <class FUNC>
void waitFor (FUNC f);
class Save_Guard
{
public:
enum Action{ ACQUIRE, RELEASE };
Save_Guard (Guard_Monitor_T <MON> & guard, Action action);
~Save_Guard();
private:
// copy operations are prohibited
Save_Guard (const Save_Guard & other);
Save_Guard& operator=(const Save_Guard & other);
Guard_Monitor_T<MON> & guard_;
bool state_;
};
private:
// copy operations are prohibited
Guard_Monitor_T (const Guard_Monitor_T<MON> & other);
Guard_Monitor_T& operator= (const Guard_Monitor_T<MON> & other);
Monitor & monitor_;
bool locked_;
};
//================================================================
//
//================================================================
template <typename MON>
inline
Guard_Monitor_T<MON>::Save_Guard::Save_Guard(Guard_Monitor_T<MON> & guard,
Action action)
: guard_ (guard)
, state_ (guard.locked())
{
if (action == ACQUIRE)
guard_.acquire ();
else
guard_.release ();
}
template <typename MON>
inline
Guard_Monitor_T<MON>::Save_Guard::~Save_Guard()
{
if (state_ == guard_.locked())
return;
if (state_)
guard_.acquire ();
else
guard_.release ();
}
//================================================================
//
//================================================================
template <typename MON>
inline
Guard_Monitor_T<MON>::Guard_Monitor_T (MON & monitor, bool flgLock)
: monitor_(monitor)
, locked_ (false)
{
if (flgLock)
this->acquire ();
}
template <typename MON>
inline
Guard_Monitor_T<MON>::~Guard_Monitor_T ()
{
this->release();
}
template <typename MON>
inline void
Guard_Monitor_T<MON>::acquire()
{
if (!this->locked_)
{
monitor_.acquire();
this->locked_ = true;
}
}
template <typename MON>
inline void
Guard_Monitor_T<MON>::release()
{
if (this->locked_)
{
monitor_.release();
this->locked_ = false;
}
}
template <typename MON>
inline void
Guard_Monitor_T<MON>::signal()
{
monitor_.signal ();
}
template <typename MON>
inline void
Guard_Monitor_T<MON>::broadcast()
{
monitor_.broadcast ();
}
template <typename MON>
inline int
Guard_Monitor_T<MON>::wait()
{
ACE_ASSERT (this->locked_);
return monitor_.wait ();
}
template <typename MON>
inline int
Guard_Monitor_T<MON>::wait(ACE_Time_Value * tv, bool flgAbsTime)
{
ACE_ASSERT (this->locked_);
return monitor_.wait (tv, flgAbsTime);
}
template <typename MON>
template <typename FUNC>
inline void
Guard_Monitor_T<MON>::waitFor (FUNC f)
{
Save_Guard saver(*this, Save_Guard::ACQUIRE);
while (! f())
{
monitor_.wait ();
}
}
ACE_END_VERSIONED_NAMESPACE_DECL
#include /**/ "ace/post.h"
#endif /* TERABIT_MONITOR_T_H */
|
AngularJS-Angular2-Angular4/angular2-project
|
wsdl/SFALeadService/com/sforce/soap/schemas/_class/ws_acq_leads/LogType.java
|
package com.sforce.soap.schemas._class.ws_acq_leads;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LogType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="LogType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="None"/>
* <enumeration value="Debugonly"/>
* <enumeration value="Db"/>
* <enumeration value="Profiling"/>
* <enumeration value="Callout"/>
* <enumeration value="Detail"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "LogType")
@XmlEnum
public enum LogType {
@XmlEnumValue("None")
NONE("None"),
@XmlEnumValue("Debugonly")
DEBUGONLY("Debugonly"),
@XmlEnumValue("Db")
DB("Db"),
@XmlEnumValue("Profiling")
PROFILING("Profiling"),
@XmlEnumValue("Callout")
CALLOUT("Callout"),
@XmlEnumValue("Detail")
DETAIL("Detail");
private final String value;
LogType(String v) {
value = v;
}
public String value() {
return value;
}
public static LogType fromValue(String v) {
for (LogType c: LogType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
trannguyenhan01092000/WorkspaceAlgorithm
|
KTLT/lab2/Bai2_3.cpp
|
<reponame>trannguyenhan01092000/WorkspaceAlgorithm
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
//# Viết hàm get_value
/****************
Ho va ten : <NAME>
MSSV : 20183554
*/
int get_value(int x, int a=2, int b=1, int c=0){
int S = a*x*x + b*x + c;
return S;
}
/*****************/
int main(){
printf("Ho Va Ten: <NAME>\n");
printf("MSSV: 20183554\n\n");
int x;
scanf("%d", &x);
int a = 2; //# giá trị mặc định của a
int b = 1; //# giá trị mặc định của b
int c = 0; //# giá trị mặc định của c
//# Nhập 3 số nguyên a, b, c từ bàn phím
/*****************/
cin >> a >> b >> c;
/*****************/
printf("a=2, b=1, c=0: %d\n", get_value(x));
printf("a=%d, b=1, c=0: %d\n", a, get_value(x, a));
printf("a=%d, b=%d, c=0: %d\n", a, b, get_value(x, a, b));
printf("a=%d, b=%d, c=%d: %d\n", a, b, c, get_value(x, a, b, c));
return 0;
}
|
chudichen/spring-source-code
|
spring-chu-beans/src/main/java/com/chu/beans/factory/config/ConfigurableBeanFactory.java
|
package com.chu.beans.factory.config;
import com.chu.beans.factory.HierarchicalBeanFactory;
import com.chu.core.convert.ConversionService;
import com.chu.util.StringValueResolver;
/**
* @author chudichen
* @date 2021-04-01
*/
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
/**
* 添加bean的后置处理器
*
* @param beanPostProcessor 后置处理器
*/
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
/**
* 销毁bean
*/
void destroySingletons();
void addEmbeddedValueResolver(StringValueResolver valueResolver);
String resolveEmbeddedValue(String value);
void setConversionService(ConversionService conversionService);
ConversionService getConversionService();
}
|
AngelKitty/angular.js
|
benchmarks/orderby-bp/jquery-noop.js
|
<filename>benchmarks/orderby-bp/jquery-noop.js
// Override me with ?jquery=/node_modules/jquery/dist/jquery.js
|
ElementAI/bytesteady
|
bytesteady/digram_codec.hpp
|
<gh_stars>1-10
/*
* Copyright 2021 ServiceNow
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BYTESTEADY_DIGRAM_CODEC_HPP_
#define BYTESTEADY_DIGRAM_CODEC_HPP_
#include <functional>
#include <queue>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "bytesteady/integer.hpp"
#include "thunder/serializer.hpp"
namespace bytesteady {
class DigramCodec {
public:
typedef ::std::vector< uint8_t > byte_array;
typedef typename byte_array::size_type size_type;
typedef ::std::vector< size_type > size_array;
typedef ::std::vector< ::std::string > string_array;
typedef ::std::unordered_map< ::std::string, size_type > size_table;
typedef ::std::unordered_map< ::std::string, ::std::string > string_table;
typedef ::std::unordered_set< ::std::string > string_set;
typedef ::std::pair< ::std::string, ::std::string > replace_pair;
typedef ::std::vector< replace_pair > replace_array;
typedef ::std::function< bool (byte_array *input) > data_callback;
// Node type for priority queue
struct Node {
::std::string target;
::std::string source;
size_type value;
bool operator<(const Node &b) const;
};
typedef Node node_type;
// This is a max heap for Node
typedef ::std::priority_queue<
Node, ::std::vector< Node >, ::std::less< Node > > node_queue;
// Construct the codec
DigramCodec(const size_array &g = {});
// Build the codec from a callback
void build(const data_callback &callback);
// Encode the data
void encode(const byte_array &input, byte_array *output) const;
// Decode the data
void decode(const byte_array &input, byte_array *output) const;
// Internal Logic
void buildCountFromData(
const data_callback &callback, size_table *count) const;
void buildBaseGramSetFromCount(
size_table *count, string_set *base_gram_set) const;
void buildGramTextFromCount(
size_table *count, string_set *base_gram_set,
string_table *gram_text) const;
void buildReplaceFromGramText(
const string_table &gram_text, replace_array *replace) const;
// Utility functions
uint8_t increase(byte_array *key) const;
void replaceString(
const ::std::string &source, const ::std::string &target,
::std::string *output) const;
size_type dict_size() const;
void set_dict_size(size_type d);
size_type gram_size() const;
void set_gram_size(size_type g);
size_type count_size() const;
void set_count_size(size_type c);
size_type count_threshold() const;
void set_count_threshold(size_type t);
const replace_array &replace() const;
void set_replace(const replace_array &r);
const size_table &count() const;
const string_set &base_gram_set() const;
const string_table &gram_text() const;
private:
// Size of the dictionary entry
size_type dict_size_;
// Maximum gram length to store in count table
size_type gram_size_;
// Maximum size of count table. If reached, will remove the count entry
size_type count_size_;
// Remove count whose size is less than this threshold
size_type count_threshold_;
// Store the count table
size_table count_;
// Store the set of base grams
string_set base_gram_set_;
// Store the gram and text correspondence
string_table gram_text_;
// Store the replace pairs for encoding and decoding
replace_array replace_;
};
} // namespace bytesteady
namespace thunder {
namespace serializer {
template < typename S >
void save (S *s, const ::bytesteady::DigramCodec &c);
template < typename S >
void load (S *s, ::bytesteady::DigramCodec *c);
} // namespace serializer
} // namespace thunder
namespace thunder {
namespace serializer {
// Pre-compiled template serializer instantiation
extern template void save(
StringBinarySerializer *s, const ::bytesteady::DigramCodec &c);
extern template void StringBinarySerializer::save(
const ::bytesteady::DigramCodec &c);
extern template void load(
StringBinarySerializer *s, ::bytesteady::DigramCodec *c);
extern template void StringBinarySerializer::load(
::bytesteady::DigramCodec *c);
extern template void save(
FileBinarySerializer *s, const ::bytesteady::DigramCodec &c);
extern template void FileBinarySerializer::save(
const ::bytesteady::DigramCodec &c);
extern template void load(
FileBinarySerializer *s, ::bytesteady::DigramCodec *c);
extern template void FileBinarySerializer::load(
::bytesteady::DigramCodec *c);
extern template void save(
StringTextSerializer *s, const ::bytesteady::DigramCodec &c);
extern template void StringTextSerializer::save(
const ::bytesteady::DigramCodec &c);
extern template void load(
StringTextSerializer *s, ::bytesteady::DigramCodec *c);
extern template void StringTextSerializer::load(
::bytesteady::DigramCodec *c);
extern template void save(
FileTextSerializer *s, const ::bytesteady::DigramCodec &c);
extern template void FileTextSerializer::save(
const ::bytesteady::DigramCodec &c);
extern template void load(
FileTextSerializer *s, ::bytesteady::DigramCodec *c);
extern template void FileTextSerializer::load(
::bytesteady::DigramCodec *c);
} // namespace thunder
} // namespace serializer
#endif // BYTESTEADY_DIGRAM_CODEC_HPP_
|
jameskoch/nteract
|
applications/commuter/pages/index.js
|
<filename>applications/commuter/pages/index.js
// @flow
import * as React from "react";
import Link from "next/link";
class IndexPage extends React.Component<*> {
static async getInitialProps(ctx: Object) {
if (ctx.res) {
// Server side, do a redirect using the HTTP response object
ctx.res.writeHead(302, { Location: "/view/" });
ctx.res.end();
} else {
// Client side redirect
document.location.pathname = "/view/";
}
return {};
}
render() {
return (
<React.Fragment>
Redirecting to{" "}
<Link href="/view">
<a>/view</a>
</Link>
</React.Fragment>
);
}
}
export default IndexPage;
|
momo-i/Mekanism
|
src/main/java/mekanism/common/content/miner/MinerItemStackFilter.java
|
<filename>src/main/java/mekanism/common/content/miner/MinerItemStackFilter.java
package mekanism.common.content.miner;
import javax.annotation.Nonnull;
import mekanism.common.content.filter.FilterType;
import mekanism.common.content.filter.IItemStackFilter;
import mekanism.common.tags.MekanismTags;
import net.minecraft.block.BlockState;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
public class MinerItemStackFilter extends MinerFilter<MinerItemStackFilter> implements IItemStackFilter<MinerItemStackFilter> {
private ItemStack itemType = ItemStack.EMPTY;
public MinerItemStackFilter(ItemStack item) {
itemType = item;
}
public MinerItemStackFilter() {
}
public MinerItemStackFilter(MinerItemStackFilter filter) {
super(filter);
itemType = filter.itemType.copy();
}
@Override
public boolean canFilter(BlockState state) {
ItemStack itemStack = new ItemStack(state.getBlock());
if (itemStack.isEmpty()) {
return false;
}
return itemType.sameItem(itemStack);
}
@Override
public boolean hasBlacklistedElement() {
return !itemType.isEmpty() && itemType.getItem() instanceof BlockItem && MekanismTags.Blocks.MINER_BLACKLIST.contains(((BlockItem) itemType.getItem()).getBlock());
}
@Override
public CompoundNBT write(CompoundNBT nbtTags) {
super.write(nbtTags);
itemType.save(nbtTags);
return nbtTags;
}
@Override
public void read(CompoundNBT nbtTags) {
super.read(nbtTags);
itemType = ItemStack.of(nbtTags);
}
@Override
public void write(PacketBuffer buffer) {
super.write(buffer);
buffer.writeItem(itemType);
}
@Override
public void read(PacketBuffer dataStream) {
super.read(dataStream);
itemType = dataStream.readItem();
}
@Override
public int hashCode() {
int code = super.hashCode();
code = 31 * code + itemType.hashCode();
return code;
}
@Override
public boolean equals(Object filter) {
return super.equals(filter) && filter instanceof MinerItemStackFilter && ((MinerItemStackFilter) filter).itemType.sameItem(itemType);
}
@Override
public MinerItemStackFilter clone() {
return new MinerItemStackFilter(this);
}
@Override
public FilterType getFilterType() {
return FilterType.MINER_ITEMSTACK_FILTER;
}
@Nonnull
@Override
public ItemStack getItemStack() {
return itemType;
}
@Override
public void setItemStack(@Nonnull ItemStack stack) {
itemType = stack;
}
}
|
DmitryBorisenko33/MySensorsNode
|
.pio/libdeps/nrf52_dk/MySensors/drivers/SPIFlash/SPIFlash.cpp
|
<gh_stars>0
// Copyright (c) 2013-2015 by <NAME>, LowPowerLab.com
// SPI Flash memory library for arduino/moteino.
// This works with 256byte/page SPI flash memory
// For instance a 4MBit (512Kbyte) flash chip will have 2048 pages: 256*2048 = 524288 bytes (512Kbytes)
// Minimal modifications should allow chips that have different page size but modifications
// DEPENDS ON: Arduino SPI library
// > Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment.
// > Updated Feb. 26, 2015 TomWS1, added support for SPI Transactions (Arduino 1.5.8 and above)
// > Selective merge by Felix after testing in IDE 1.0.6, 1.6.4
// > Updated May 19, 2016 D-H-R, added support for SST25/Microchip Flash which does not support Page programming with OPCode 0x02,
// > use define MY_SPIFLASH_SST25TYPE for SST25 Type Flash Memory
// > Updated Sep 07, 2018 tekka, sync with https://github.com/LowPowerLab/SPIFlash
// **********************************************************************************
// License
// **********************************************************************************
// This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU General
// Public License as published by the Free Software
// Foundation; either version 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 General Public
// License for more details.
//
// You should have received a copy of the GNU General
// Public License along with this program.
// If not, see <http://www.gnu.org/licenses/>.
//
// Licence can be viewed at
// http://www.gnu.org/licenses/gpl-3.0.txt
//
// Please maintain this license information along with authorship
// and copyright notices in any redistribution of this code
#include "SPIFlash.h"
uint8_t SPIFlash::UNIQUEID[8];
/// IMPORTANT: NAND FLASH memory requires erase before write, because
/// it can only transition from 1s to 0s and only the erase command can reset all 0s to 1s
/// See http://en.wikipedia.org/wiki/Flash_memory
/// The smallest range that can be erased is a sector (4K, 32K, 64K); there is also a chip erase command
/// Constructor. JedecID is optional but recommended, since this will ensure that the device is present and has a valid response
/// get this from the datasheet of your flash chip
/// Example for Atmel-Adesto 4Mbit AT25DF041A: 0x1F44 (page 27: http://www.adestotech.com/sites/default/files/datasheets/doc3668.pdf)
/// Example for Winbond 4Mbit W25X40CL: 0xEF30 (page 14: http://www.winbond.com/NR/rdonlyres/6E25084C-0BFE-4B25-903D-AE10221A0929/0/W25X40CL.pdf)
// Suppress uninitialized member variable in constructor because some memory can be saved with
// on-demand initialization of these members
// cppcheck-suppress uninitMemberVar
SPIFlash::SPIFlash(uint8_t slaveSelectPin, uint16_t jedecID)
{
_slaveSelectPin = slaveSelectPin;
_jedecID = jedecID;
}
/// Select the flash chip
void SPIFlash::select()
{
//save current SPI settings
#ifndef SPI_HAS_TRANSACTION
noInterrupts();
#endif
#if defined(SPCR) && defined(SPSR)
_SPCR = SPCR;
_SPSR = SPSR;
#endif
#ifdef SPI_HAS_TRANSACTION
SPI.beginTransaction(_settings);
#else
// set FLASH SPI settings
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(
SPI_CLOCK_DIV4); //decided to slow down from DIV2 after SPI stalling in some instances, especially visible on mega1284p when RFM69 and FLASH chip both present
#endif
hwDigitalWrite(_slaveSelectPin, LOW);
}
/// UNselect the flash chip
void SPIFlash::unselect()
{
hwDigitalWrite(_slaveSelectPin, HIGH);
//restore SPI settings to what they were before talking to the FLASH chip
#ifdef SPI_HAS_TRANSACTION
SPI.endTransaction();
#else
interrupts();
#endif
#if defined(SPCR) && defined(SPSR)
SPCR = _SPCR;
SPSR = _SPSR;
#endif
}
/// setup SPI, read device ID etc...
bool SPIFlash::initialize()
{
#if defined(SPCR) && defined(SPSR)
_SPCR = SPCR;
_SPSR = SPSR;
#endif
hwPinMode(_slaveSelectPin, OUTPUT);
SPI.begin(); // see https://github.com/LowPowerLab/SPIFlash/issues/20
#ifdef SPI_HAS_TRANSACTION
_settings = SPISettings(4000000, MSBFIRST, SPI_MODE0);
#endif
unselect();
wakeup();
if (_jedecID == 0 || readDeviceId() == _jedecID) {
command(SPIFLASH_STATUSWRITE, true); // Write Status Register
SPI.transfer(0); // Global Unprotect
unselect();
return true;
}
return false;
}
/// Get the manufacturer and device ID bytes (as a short word)
uint16_t SPIFlash::readDeviceId()
{
#if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo
command(SPIFLASH_IDREAD); // Read JEDEC ID
#else
select();
SPI.transfer(SPIFLASH_IDREAD);
#endif
uint16_t jedecid = SPI.transfer(0) << 8;
jedecid |= SPI.transfer(0);
unselect();
return jedecid;
}
/// Get the 64 bit unique identifier, stores it in UNIQUEID[8]. Only needs to be called once, ie after initialize
/// Returns the byte pointer to the UNIQUEID byte array
/// Read UNIQUEID like this:
/// flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(flash.UNIQUEID[i], HEX); Serial.print(' '); }
/// or like this:
/// flash.readUniqueId(); uint8_t* MAC = flash.readUniqueId(); for (uint8_t i=0;i<8;i++) { Serial.print(MAC[i], HEX); Serial.print(' '); }
uint8_t* SPIFlash::readUniqueId()
{
command(SPIFLASH_MACREAD);
SPI.transfer(0);
SPI.transfer(0);
SPI.transfer(0);
SPI.transfer(0);
for (uint8_t i=0; i<8; i++) {
UNIQUEID[i] = SPI.transfer(0);
}
unselect();
return UNIQUEID;
}
/// read 1 byte from flash memory
uint8_t SPIFlash::readByte(uint32_t addr)
{
command(SPIFLASH_ARRAYREADLOWFREQ);
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
uint8_t result = SPI.transfer(0);
unselect();
return result;
}
/// read unlimited # of bytes
void SPIFlash::readBytes(uint32_t addr, void* buf, uint16_t len)
{
command(SPIFLASH_ARRAYREAD);
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
SPI.transfer(0); //"dont care"
for (uint16_t i = 0; i < len; ++i) {
((uint8_t*) buf)[i] = SPI.transfer(0);
}
unselect();
}
/// Send a command to the flash chip, pass TRUE for isWrite when its a write command
void SPIFlash::command(uint8_t cmd, bool isWrite)
{
#if defined(__AVR_ATmega32U4__) // Arduino Leonardo, MoteinoLeo
DDRB |= B00000001; // Make sure the SS pin (PB0 - used by RFM12B on MoteinoLeo R1) is set as output HIGH!
PORTB |= B00000001;
#endif
if (isWrite) {
command(SPIFLASH_WRITEENABLE); // Write Enable
unselect();
}
//wait for any write/erase to complete
// a time limit cannot really be added here without it being a very large safe limit
// that is because some chips can take several seconds to carry out a chip erase or other similar multi block or entire-chip operations
// a recommended alternative to such situations where chip can be or not be present is to add a 10k or similar weak pulldown on the
// open drain MISO input which can read noise/static and hence return a non 0 status byte, causing the while() to hang when a flash chip is not present
if (cmd != SPIFLASH_WAKE) while(busy());
select();
SPI.transfer(cmd);
}
/// check if the chip is busy erasing/writing
bool SPIFlash::busy()
{
/*
select();
SPI.transfer(SPIFLASH_STATUSREAD);
uint8_t status = SPI.transfer(0);
unselect();
return status & 1;
*/
return readStatus() & 1;
}
/// return the STATUS register
uint8_t SPIFlash::readStatus()
{
select();
SPI.transfer(SPIFLASH_STATUSREAD);
uint8_t status = SPI.transfer(0);
unselect();
return status;
}
/// Write 1 byte to flash memory
/// WARNING: you can only write to previously erased memory locations (see datasheet)
/// use the block erase commands to first clear memory (write 0xFFs)
void SPIFlash::writeByte(uint32_t addr, uint8_t byt)
{
command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
SPI.transfer(byt);
unselect();
}
/// write multiple bytes to flash memory (up to 64K)
/// WARNING: you can only write to previously erased memory locations (see datasheet)
/// use the block erase commands to first clear memory (write 0xFFs)
/// This version handles both page alignment and data blocks larger than 256 bytes.
/// See documentation of #MY_SPIFLASH_SST25TYPE define for more information
void SPIFlash::writeBytes(uint32_t addr, const void* buf, uint16_t len)
{
#ifdef MY_SPIFLASH_SST25TYPE
//SST25 Type of Flash does not support Page Programming but AAI Word Programming
uint16_t i=0;
uint8_t oddAdr=0;
command(SPIFLASH_AAIWORDPROGRAM, true); // Byte/Page Program
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
if (addr%2) {
//start address is not even, i.e. first byte of word must be 0xff
SPI.transfer(0xff);
SPI.transfer(((uint8_t*) buf)[0]);
unselect();
oddAdr=1; //following addresses must all be shifted one off
len--;
if (len > 0) {
command(SPIFLASH_AAIWORDPROGRAM); //If for loop will run issue Wordprogram command
}
}
for (i=0; i<(len/2); i++) {
//AAI command must be set before every new word
if (i>0) {
command(SPIFLASH_AAIWORDPROGRAM); //Wordprogram command for first write has been issued before
}
SPI.transfer(((uint8_t*) buf)[i*2+oddAdr]);
SPI.transfer(((uint8_t*) buf)[i*2+1+oddAdr]);
unselect();
}
if (len-i*2 == 1) {
//There is one byte (i.e. half word) left. This happens if len was odd or (len was even and addr odd)
if (i>0) {
command(SPIFLASH_AAIWORDPROGRAM); //if for loop had not run wordprogram command from before is still valid
}
SPI.transfer(((uint8_t*) buf)[i*2+oddAdr]);
SPI.transfer(0xff);
unselect();
}
command(SPIFLASH_WRITEDISABLE); //end AAI programming
unselect();
#else
uint16_t maxBytes = 256-(addr%256); // force the first set of bytes to stay within the first page
uint16_t offset = 0;
while (len>0) {
uint16_t n = (len<=maxBytes) ? len : maxBytes;
command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
for (uint16_t i = 0; i < n; i++) {
SPI.transfer(((uint8_t*) buf)[offset + i]);
}
unselect();
addr+=n; // adjust the addresses and remaining bytes by what we've just transferred.
offset +=n;
len -= n;
maxBytes = 256; // now we can do up to 256 bytes per loop
}
#endif
}
/// erase entire flash memory array
/// may take several seconds depending on size, but is non blocking
/// so you may wait for this to complete using busy() or continue doing
/// other things and later check if the chip is done with busy()
/// note that any command will first wait for chip to become available using busy()
/// so no need to do that twice
void SPIFlash::chipErase()
{
command(SPIFLASH_CHIPERASE, true);
unselect();
}
/// erase a 4Kbyte block
void SPIFlash::blockErase4K(uint32_t addr)
{
command(SPIFLASH_BLOCKERASE_4K, true); // Block Erase
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
unselect();
}
/// erase a 32Kbyte block
void SPIFlash::blockErase32K(uint32_t addr)
{
command(SPIFLASH_BLOCKERASE_32K, true); // Block Erase
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
unselect();
}
/// erase a 64Kbyte block
void SPIFlash::blockErase64K(uint32_t addr)
{
command(SPIFLASH_BLOCKERASE_64K, true); // Block Erase
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
unselect();
}
void SPIFlash::sleep()
{
command(SPIFLASH_SLEEP);
unselect();
}
void SPIFlash::wakeup()
{
command(SPIFLASH_WAKE);
unselect();
}
/// cleanup
void SPIFlash::end()
{
SPI.end();
}
|
shijingsh/pay-spring-boot-starter-parent
|
pay-spring-boot-starter-demo/src/main/java/com/egzosn/pay/spring/boot/demo/config/handlers/WxPayMessageHandler.java
|
package com.egzosn.pay.spring.boot.demo.config.handlers;
import com.egzosn.pay.common.api.PayMessageHandler;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import com.egzosn.pay.wx.bean.WxPayMessage;
import java.util.Map;
/**
* 微信支付回调处理器
* Created by ZaoSheng on 2016/6/1.
*/
public class WxPayMessageHandler implements PayMessageHandler<WxPayMessage, PayService> {
@Override
public PayOutMessage handle(WxPayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
//交易状态
if ("SUCCESS".equals(payMessage.getPayMessage().get("result_code"))){
/////这里进行成功的处理
return payService.getPayOutMessage("SUCCESS", "OK");
}
return payService.getPayOutMessage("FAIL", "失败");
}
}
|
suda-morris/SUDA_3518E
|
uboot/u-boot-2010.06/drivers/mtd/nand/hinfc504/hinfc504_read_retry_micron.c
|
<reponame>suda-morris/SUDA_3518E
/******************************************************************************
* NAND Flash Controller V504 Device Driver
* Copyright (c) 2009-2010 by Hisilicon.
* All rights reserved.
* ***
* Create By Czyong.
*
******************************************************************************/
#include <common.h>
#include <nand.h>
#include <asm/io.h>
#include <asm/errno.h>
#include <malloc.h>
#include <linux/mtd/nand.h>
#include "hinfc504.h"
/*****************************************************************************/
#define MICRON_RR_ADDR 0x89
static int hinfc504_micron_set_rr_reg(struct hinfc_host *host, int rr)
{
#define MICRON_SET_RR 0xEF
hinfc_write(host, 1, HINFC504_DATA_NUM);
writel(rr, host->chip->IO_ADDR_W);
hinfc_write(host, MICRON_RR_ADDR, HINFC504_ADDRL);
hinfc_write(host, MICRON_SET_RR, HINFC504_CMD);
hinfc_write(host, HINFC504_WRITE_1CMD_1ADD_DATA, HINFC504_OP);
WAIT_CONTROLLER_FINISH();
#undef MICRON_SET_RR
return 0;
}
/*****************************************************************************/
#if 0
static int hinfc504_micron_get_rr_param(struct hinfc_host *host)
{
#define MICRON_GET_RR 0xEE
hinfc_write(host, 1, HINFC504_DATA_NUM);
hinfc_write(host, MICRON_RR_ADDR, HINFC504_ADDRL);
hinfc_write(host, MICRON_GET_RR, HINFC504_CMD);
hinfc_write(host, HINFC504_READ_1CMD_1ADD_DATA, HINFC504_OP);
WAIT_CONTROLLER_FINISH();
hinfc_write(host, NAND_CMD_READ0, HINFC504_CMD);
hinfc_write(host, HINFC504_READ_1CMD_0ADD_NODATA, HINFC504_OP);
#undef MICRON_GET_RR
return readl(host->chip->IO_ADDR_R) & 0xff;
}
#endif
#undef MICRON_RR_ADDR
/*****************************************************************************/
static int hinfc504_micron_set_rr_param(struct hinfc_host *host, int rr_option)
{
return hinfc504_micron_set_rr_reg(host, rr_option);
}
/*****************************************************************************/
struct read_retry_t hinfc504_micron_read_retry = {
.type = NAND_RR_MICRON,
.count = 8,
.set_rr_param = hinfc504_micron_set_rr_param,
.get_rr_param = NULL,
.enable_enhanced_slc = NULL,
};
|
TempJ-Team/TenSquare
|
apps/user/serializers.py
|
<gh_stars>0
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from .models import *
from apps.question.serializers import LablesModelSerializer, QuestionsModelSerializer, ReplySerializerForList
from apps.recruit.serializers import RecruitModelSerialier, EnterpriseModelSerializer
from apps.article.models import Article
# 用户注册
class UserModelSerializer(serializers.ModelSerializer):
fans = serializers.PrimaryKeyRelatedField(many=True, read_only=True, allow_null=True)
class Meta:
model = User
fields = '__all__'
# 密码要加密
def validate(self, attrs):
raw_password = attrs.pop('password')
secret_password = make_password(raw_password)
attrs['password'] = <PASSWORD>_password
return attrs
class ArticleDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
# 用户个人中心
class UserInfoSerializer(serializers.ModelSerializer):
'''用户信息'''
username = serializers.CharField(read_only=True)
# TODO:这里可能有些不需要 read_only=True后续再改
# ==> question
questions = QuestionsModelSerializer(many=True, read_only=True)
replies = ReplySerializerForList(many=True, read_only=True)
labels = LablesModelSerializer(many=True, read_only=True)
# ==> artical
collected_articles = ArticleDetailSerializer(many=True, read_only=True)
# ==> recruit
enterpises = EnterpriseModelSerializer(many=True, read_only=True)
recruits = RecruitModelSerialier(many=True, read_only=True)
class Meta:
model = User
fields = [
'id',
'username',
'mobile',
'realname',
'birthday',
'sex',
'avatar',
'website',
'city',
'email',
'address',
'labels',
'questions',
# 'answer_question', # 不存在的字段? 应该是replies?
'replies',
'collected_articles',
'enterpises',
'recruits',
]
# 修改用户标签
class ChangeLabelModelSerializer(serializers.ModelSerializer):
labels = LablesModelSerializer(many=True)
class Meta:
model = User
fields = [
'labels'
]
# 修改用户密码
class ChangePasswordModelSerializer(serializers.ModelSerializer):
username = serializers.CharField(read_only=True)
class Meta:
model = User
fields = [
'username',
'password'
]
def validate(self, attrs):
raw_password = attrs.pop('password')
secret_password = <PASSWORD>_password(raw_password)
attrs['password'] = <PASSWORD>
return attrs
|
EricRemmerswaal/tensorflow
|
tensorflow/lite/delegates/gpu/common/model.h
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_LITE_DELEGATES_GPU_COMMON_MODEL_H_
#define TENSORFLOW_LITE_DELEGATES_GPU_COMMON_MODEL_H_
#include <algorithm>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/types/any.h"
#include "absl/types/optional.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/tensor.h"
namespace tflite {
namespace gpu {
// There is yet another representation of CNN graph. The primary purpose of this
// representation is to simplify graph manipulation.
using ValueId = uint32_t;
using NodeId = uint32_t;
// Used to emulate quantized behavior.
struct QuantizationParams {
float min = 0;
float max = 0;
float scale = 0;
};
// Connects tensor's producer and operation that depends on this tensor.
struct Value {
const ValueId id;
TensorRef<BHWC> tensor;
absl::optional<QuantizationParams> quant_params;
};
struct Operation {
std::string type;
absl::any attributes;
};
struct Node {
const NodeId id;
Operation operation;
};
// A DAG that consists of nodes and values. Each value may have a single
// producer node and multiple consumer nodes. Therefore, each node may have
// multiple input and output values.
//
// Value that does not have a producer is a graph's input. Value that does not
// have a consumer is a graph's output.
//
// It keeps values and nodes referenced by their index in a vector. Therefore,
// nodes and values are never deleted, but rather erased, where corresponding
// index remains.
//
// It is possible to re-use removed indices, but it is not implemented yet.
class GraphFloat32 {
public:
// @return a collection of nodes in this graph.
std::vector<Node*> nodes() const;
// @return a collection of values in this graph.
std::vector<Value*> values() const;
// @return graph inputs, that are values without producers.
std::vector<Value*> inputs() const;
// @return graph outputs, that are values without consumers.
std::vector<Value*> outputs() const;
// @return values updated in place with a previously defined tensor reference.
std::vector<Value*> variable_inputs() const;
// @return inputs into the given node. Returns empty vector for deleted node.
std::vector<Value*> FindInputs(NodeId id) const;
// @return outputs from the given node. Returns empty vector for deleted node.
std::vector<Value*> FindOutputs(NodeId id) const;
bool IsGraphInput(ValueId id) const;
bool IsGraphOutput(ValueId id) const;
// @return producer of the given value. Returns nullptr for deleted value.
Node* FindProducer(ValueId id) const;
// @return consumers of the given value. Returns empty vector for deleted
// value.
std::vector<Node*> FindConsumers(ValueId id) const;
// @return a node or nullptr if node with the given id is not present.
Node* GetNode(NodeId id) const;
// @return a value or nullptr if value with the given id is not present.
Value* GetValue(ValueId id) const;
//////////////////////////////////////////////////////////////////////////////
// Graph manipulation functions are below
//////////////////////////////////////////////////////////////////////////////
// @return new node created in this graph
// NOTE: nodes should be created in the topological order, e.g. node A that
// depends on a value from node B should be created after node B.
Node* NewNode();
// Insert Node after another in the execution plan.
absl::Status InsertNodeAfter(NodeId id, Node** new_node);
// @return new value created in this graph
Value* NewValue();
// Sets a producer for the given value. There could be a single producer
// for a value. If a value had another producer, it will reassign producer
// appropriately. If a value didn't have a producer, it will be removed
// from a graph's input.
absl::Status SetProducer(NodeId producer, ValueId value);
// Removes a producer for the given value. Value becomes producer-less and
// therefore becomes graph's input.
absl::Status RemoveProducer(ValueId value);
// Sets a consumer for the given value. There could be multiple consumers
// for a value.
absl::Status AddConsumer(NodeId consumer, ValueId value);
// Replace input value for given node.
absl::Status ReplaceInput(NodeId node, ValueId old_value, ValueId new_value);
// Removes a consumer for the given value. If value does not have any
// consumers it becomes graph's output.
absl::Status RemoveConsumer(NodeId consumer, ValueId value);
// Removes node from this graph. For all input values this node will be
// removed from consumers and for all output values a producer will be
// removed.
absl::Status DeleteNode(NodeId id);
// Removes value from this graph. It will be removed from inputs for all
// dependent nodes. A node that was a producer of this value will loose its
// output.
absl::Status DeleteValue(ValueId id);
absl::Status MakeExactCopy(GraphFloat32* model) const;
private:
struct NodeDef {
std::vector<Value*> inputs;
std::vector<Value*> outputs;
std::unique_ptr<Node> node;
};
struct ValueDef {
Node* producer = nullptr;
std::vector<Node*> consumers;
std::unique_ptr<Value> value;
};
bool IsInput(NodeId node, ValueId value);
template <typename T>
static void Erase(std::vector<T>* values, T value) {
values->erase(std::find(values->begin(), values->end(), value));
}
// @return non-nullptr NodeDef that has valid Node or an error
absl::Status LookupNode(NodeId id, NodeDef** node_def);
// @return non-nullptr ValueDef that has valid Value or an error
absl::Status LookupValue(ValueId id, ValueDef** value_def);
template <typename Pred>
std::vector<Value*> FilterValues(const Pred& predicate) const {
std::vector<Value*> values;
values.reserve(values_.size());
for (auto& v : values_) {
if (v.value != nullptr && predicate(v)) {
values.push_back(v.value.get());
}
}
return values;
}
template <typename Pred>
std::vector<Node*> FilterNodes(const Pred& predicate) const {
std::vector<Node*> nodes;
nodes.reserve(nodes_.size());
for (const auto id : execution_plan_) {
auto& n = nodes_.at(id);
if (n.node != nullptr && predicate(n)) {
nodes.push_back(n.node.get());
}
}
return nodes;
}
// There are two approaches possible: wrap entire NodeDef and ValueDef into
// unique_ptr and store it in values_ and nodes_ or store it by value.
// We store it by value here to make introspection calls cheaper.
std::vector<ValueDef> values_;
std::map<NodeId, NodeDef> nodes_;
// Node Ids in order of execution.
std::vector<NodeId> execution_plan_;
};
// Removes to_remove node that precedes to_keep node only if to_remove has
// outputs that are consumed only by to_keep. In such case to_keep inherits all
// to_remove inputs.
absl::Status RemovePrecedingNode(GraphFloat32* graph, const Node* to_remove,
const Node* to_keep);
// Removes to_remove node that follows to_keep node only if to_remove has inputs
// that are produced by to_keep. to_keep inherits all to_remove inputs.
absl::Status RemoveFollowingNode(GraphFloat32* graph, const Node* to_remove,
const Node* to_keep);
// Removes simple_node and its output value from the graph. Node is considered
// simple if it has only one input and one output value. Input value is kept.
absl::Status RemoveSimpleNodeKeepInput(GraphFloat32* graph,
const Node* simple_node);
// Removes simple_node and its input value from the graph. Node is considered
// simple if it has only one input and one output value. Output value is kept.
// simple_node should be an exclusive consumer of its input value.
absl::Status RemoveSimpleNodeKeepOutput(GraphFloat32* graph,
const Node* simple_node);
absl::Status AddOutput(GraphFloat32* graph, const Node* from_node,
Value** output);
// Makes a direct connection between from_node and to_node. All input parameters
// except output are expected to be initialized before passing to the function.
// If from_node already has an output value, which is not yet consumed by
// to_node, it may be passed as output parameter.
absl::Status ConnectTwoNodes(GraphFloat32* graph, const Node* from_node,
const Node* to_node, Value** output);
// @return true if all tensors have same batch value or if model has no values.
bool IsBatchMatchesForAllValues(const GraphFloat32& model);
} // namespace gpu
} // namespace tflite
#endif // TENSORFLOW_LITE_DELEGATES_GPU_COMMON_MODEL_H_
|
altalk23/gd.h
|
layers_scenes_transitions_nodes/CCBlockLayer.h
|
#ifndef __CCBLOCKLAYER_H__
#define __CCBLOCKLAYER_H__
#include <gd.h>
class CCBlockLayer : public cocos2d::CCLayerColor {
public:
bool m_bUnknown;
bool m_bUnknown2;
};
#endif
|
zipated/src
|
chrome/services/wifi_util_win/wifi_credentials_getter.cc
|
<filename>chrome/services/wifi_util_win/wifi_credentials_getter.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/services/wifi_util_win/wifi_credentials_getter.h"
#include "components/wifi/wifi_service.h"
WiFiCredentialsGetter::WiFiCredentialsGetter(
std::unique_ptr<service_manager::ServiceContextRef> service_ref)
: service_ref_(std::move(service_ref)) {}
WiFiCredentialsGetter::~WiFiCredentialsGetter() = default;
void WiFiCredentialsGetter::GetWiFiCredentials(
const std::string& ssid,
GetWiFiCredentialsCallback callback) {
if (ssid == kWiFiTestNetwork) {
// test-mode: return the ssid in key_data.
std::move(callback).Run(true, ssid);
return;
}
std::unique_ptr<wifi::WiFiService> wifi_service(wifi::WiFiService::Create());
wifi_service->Initialize(nullptr);
std::string key_data;
std::string error;
wifi_service->GetKeyFromSystem(ssid, &key_data, &error);
const bool success = error.empty();
if (!success)
key_data.clear();
std::move(callback).Run(success, key_data);
}
|
MaksymDryha/ui-eholdings
|
src/components/title/_fields/identifiers/identifiers-fields.js
|
import React, { Component, Fragment } from 'react';
import { Field, FieldArray } from 'redux-form';
import PropTypes from 'prop-types';
import {
RepeatableField,
Select,
TextField
} from '@folio/stripes/components';
import { injectIntl, intlShape } from 'react-intl';
import styles from './identifiers-fields.css';
class IdentifiersFields extends Component {
static propTypes = {
initialValue: PropTypes.array,
intl: intlShape.isRequired
};
static defaultProps = {
initialValue: []
};
renderField = (identifier, index, fields) => {
const { intl } = this.props;
return (
<Fragment>
<div
data-test-eholdings-identifiers-fields-type
className={styles['identifiers-fields-field']}
>
<Field
name={`${identifier}.flattenedType`}
type="text"
component={Select}
autoFocus={Object.keys(fields.get(index)).length === 0}
label={intl.formatMessage({ id: 'ui-eholdings.type' })}
dataOptions={[
{ value: '0', label: intl.formatMessage({ id: 'ui-eholdings.label.identifier.issnOnline' }) },
{ value: '1', label: intl.formatMessage({ id: 'ui-eholdings.label.identifier.issnPrint' }) },
{ value: '2', label: intl.formatMessage({ id: 'ui-eholdings.label.identifier.isbnOnline' }) },
{ value: '3', label: intl.formatMessage({ id: 'ui-eholdings.label.identifier.isbnPrint' }) }
]}
/>
</div>
<div
data-test-eholdings-identifiers-fields-id
className={styles['identifiers-fields-field']}
>
<Field
name={`${identifier}.id`}
type="text"
component={TextField}
label={intl.formatMessage({ id: 'ui-eholdings.id' })}
/>
</div>
</Fragment>
);
}
render() {
const { initialValue, intl } = this.props;
return (
<div data-test-eholdings-identifiers-fields>
<FieldArray
addLabel={intl.formatMessage({ id: 'ui-eholdings.title.identifier.addIdentifier' })}
component={RepeatableField}
emptyMessage={
initialValue.length > 0 && initialValue[0].id ?
intl.formatMessage({ id: 'ui-eholdings.title.identifier.notSet' }) : ''
}
legend={intl.formatMessage({ id: 'ui-eholdings.label.identifiers' })}
name="identifiers"
renderField={this.renderField}
/>
</div>
);
}
}
export function validate(values, { intl }) {
let errors = [];
values.identifiers.forEach((identifier, index) => {
let identifierErrors = {};
if (!identifier.id) {
identifierErrors.id = intl.formatMessage({ id: 'ui-eholdings.validate.errors.identifiers.noBlank' });
}
if (identifier.id && identifier.id.length >= 20) {
identifierErrors.id = intl.formatMessage({ id: 'ui-eholdings.validate.errors.identifiers.exceedsLength' });
}
errors[index] = identifierErrors;
});
return { identifiers: errors };
}
export default injectIntl(IdentifiersFields);
|
knocknote/libhtml5
|
include/native_object.h
|
<reponame>knocknote/libhtml5<filename>include/native_object.h<gh_stars>1-10
#pragma once
#include "html5.h"
NAMESPACE_HTML5_BEGIN;
class NativeObject {
public:
NativeObject();
virtual ~NativeObject();
void autorelease();
void release();
void retain();
unsigned int referenceCount();
bool isAutoRelease();
private:
bool _isAutoRelease;
unsigned int _refCount;
};
NAMESPACE_HTML5_END;
|
zipated/src
|
chrome/browser/interstitials/chrome_metrics_helper.cc
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/interstitials/chrome_metrics_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/buildflags.h"
#include "components/history/core/browser/history_service.h"
#include "content/public/browser/web_contents.h"
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
#include "chrome/browser/ssl/captive_portal_metrics_recorder.h"
#endif
ChromeMetricsHelper::ChromeMetricsHelper(
content::WebContents* web_contents,
const GURL& request_url,
const security_interstitials::MetricsHelper::ReportDetails settings)
: security_interstitials::MetricsHelper(
request_url,
settings,
HistoryServiceFactory::GetForProfile(
Profile::FromBrowserContext(web_contents->GetBrowserContext()),
ServiceAccessType::EXPLICIT_ACCESS)),
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
web_contents_(web_contents),
#endif
request_url_(request_url) {
}
ChromeMetricsHelper::~ChromeMetricsHelper() {}
void ChromeMetricsHelper::StartRecordingCaptivePortalMetrics(bool overridable) {
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
captive_portal_recorder_.reset(
new CaptivePortalMetricsRecorder(web_contents_, overridable));
#endif
}
void ChromeMetricsHelper::RecordExtraShutdownMetrics() {
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
// The captive portal metrics should be recorded when the interstitial is
// closing (or destructing).
if (captive_portal_recorder_)
captive_portal_recorder_->RecordCaptivePortalUMAStatistics();
#endif
}
|
PennController/penncontroller
|
src_until_beta0.2/instructions/timer.js
|
<filename>src_until_beta0.2/instructions/timer.js
// import {_setCtrlr} from "../controller.js";
// Adds a timer
// Done immediately
class TimerInstr extends Instruction {
constructor(id, delay, callback) {
super(id, delay, "timer");
if (delay != Abort){
this.delay = delay;
this.setElement($("<timer>"));
this.step = 10;
this.callback = callback;
this.cleared = false;
}
}
// ========================================
// PRIVATE & INTRINSIC METHODS
// ========================================
run() {
if (super.run() == Abort)
return Abort;
this.left = this.delay;
let ti = this;
/*this.timer = setInterval(function(){
ti.left -= ti.step;
if (ti.left <= 0){
clearInterval(ti.timer);
ti.left = 0;
ti._elapsed();
}
}, this.step);*/
//this.timer = setTimeout(function(){ ti._elapsed(); }, this.delay);
//_setCtrlr("timers", Ctrlr.running.timers.concat([this.timer]));
Ctrlr.running.timers.push(this.timer);
this.done();
}
// Called when timer has elapsed
_elapsed() {
this.origin.cleared = true;
if (this.origin.callback instanceof Function)
this.origin.callback();
else if (this.origin.callback instanceof Instruction) {
this.origin.callback.parentElement = Ctrlr.running.element;
this.origin.callback.run();
}
}
// ========================================
// METHODS RETURNING NEW INSTRUCTIONS
// ========================================
// Returns an instruction to start the timer
// Done immediately
start() {
return this.newMeta(function(){
let origin = this.origin;
origin.timer = setTimeout(function(){ origin._elapsed(); }, origin.delay);
this.done();
});
}
// Returns an instruction that prematurely stops the timer
// Done immediately
stop() {
return this.newMeta(function(){
let origin = this.origin;
clearTimeout(origin.timer);
origin._elapsed();
this.done();
});
}
// Returns an instruction to sait until the timer has elapsed
// Done when the timer has elapsed
wait(what) {
return this.newMeta(function(){
let ti = this;
if (what=="first" && this.origin.cleared)
this.done();
else if (what instanceof Instruction) {
// Test instructions have 'success'
if (what.hasOwnProperty("success")) {
// Done only when success
what.success = what.extend("success", function(arg){ if (!(arg instanceof Instruction)) ti.done(); });
// Test 'what' whenever press on enter until done
ti.origin._elapsed = ti.origin.extend("_elapsed", function(){
if (!ti.isDone) {
// Resets for re-running the test each time
what.hasBeenRun = false;
what.isDone = false;
what.run();
}
});
}
// If no 'success,' then invalid test
else {
console.log("ERROR: invalid test passed to 'wait'");
ti.done();
}
}
// If no test instruction was passed, listen for next 'clicked'
else
this.origin._elapsed = this.origin.extend("_elapsed", function(){ ti.done(); });
});
}
}
// SETTINGS 'instructions'
TimerInstr.prototype.settings = {
callback: function(instructionOrFunction){
return this.newMeta(function(){
let timerCleared = function(){
if (instructionOrFunction instanceof Function)
instructionOrFunction.call();
else if (instructionOrFunction instanceof Instruction && !instructionOrFunction.hasBeenRun)
instructionOrFunction.run();
};
if (this.origin.cleared)
timerCleared();
else
this.origin._elapsed = this.origin.extend("_elapsed", timerCleared);
this.done();
});
}
,
// Returns an instruction to set the timer's step
step: function(value) {
return this.newMeta(function(){
// (Re)set the step
this.origin.step = value;
this.done();
});
}
}
// TEST 'instructions'
TimerInstr.prototype.test = {
// Tests whether the timer has ended
ended: function () {
let o = this.origin, arg = arguments;
let istr = this.newMeta(function(){
if (o.timer.cleared)
return this.success();
else
return this.failure();
});
// What happens if success
istr.success = function(successInstruction){
if (successInstruction instanceof Instruction){
istr._then = successInstruction;
successInstruction.done = successInstruction.extend("done", function(){ istr.done() });
}
else if (istr._then instanceof Instruction)
istr._then.run();
else
istr.done();
return istr;
};
// What happens if failure
istr.failure = function(failureInstruction){
if (failureInstruction instanceof Instruction){
istr._fail = failureInstruction;
failureInstruction.done = failureInstruction.extend("done", function(){ istr.done() });
}
else if (istr._fail instanceof Instruction)
istr._fail.run();
else
istr.done();
return istr;
};
return istr;
}
}
TimerInstr._setDefaultsName("timer");
PennController.instruction.newTimer = function(id, delay, callback){
return TimerInstr._newDefault(new TimerInstr(id, delay, callback));
};
PennController.instruction.getTimer = function(id){ return PennController.instruction(id); };
|
xaxiong/CityScope
|
Processing/libraries/WordCram/src/wordcram/WordShaper.java
|
package wordcram;
/*
Copyright 2010 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.awt.Font;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import processing.core.PFont;
public class WordShaper {
private FontRenderContext frc = new FontRenderContext(null, true, true);
public Shape getShapeFor(String word, PFont font, float fontSize, float angle, int minShapeSize) {
Shape shape = makeShape(word, font, fontSize);
if (isTooSmall(shape, minShapeSize)) {
return null;
}
return moveToOrigin(rotate(shape, angle));
}
private Shape makeShape(String word, PFont pFont, float fontSize) {
Font font = pFont.getFont().deriveFont(fontSize);
char[] chars = word.toCharArray();
// TODO hmm: this doesn't render newlines. Hrm. If your word text is "foo\nbar", you get "foobar".
GlyphVector gv = font.layoutGlyphVector(frc, chars, 0, chars.length,
Font.LAYOUT_LEFT_TO_RIGHT);
return gv.getOutline();
}
private boolean isTooSmall(Shape shape, int minShapeSize) {
Rectangle2D r = shape.getBounds2D();
// Most words will be wider than tall, so this basically boils down to height.
// For the odd word like "I", we check width, too.
return r.getHeight() < minShapeSize || r.getWidth() < minShapeSize;
}
private Shape rotate(Shape shape, float rotation) {
if (rotation == 0) {
return shape;
}
return AffineTransform.getRotateInstance(rotation).createTransformedShape(shape);
}
private Shape moveToOrigin(Shape shape) {
Rectangle2D rect = shape.getBounds2D();
if (rect.getX() == 0 && rect.getY() == 0) {
return shape;
}
return AffineTransform.getTranslateInstance(-rect.getX(), -rect.getY()).createTransformedShape(shape);
}
}
|
rezigned/omise-java
|
src/test/java/co/omise/requests/ForexRequestTest.java
|
package co.omise.requests;
import co.omise.models.Forex;
import co.omise.models.OmiseException;
import org.junit.Test;
import java.io.IOException;
public class ForexRequestTest extends RequestTest {
@Test
public void testGet() throws IOException, OmiseException {
Request<Forex> request = new Forex.GetRequestBuilder("usd")
.build();
Forex forex = getTestRequester().sendRequest(request);
assertRequested("GET", "/forex/usd", 200);
assertEquals("USD", forex.getBase());
assertEquals("THB", forex.getQuote());
}
}
|
pkosiec/capact
|
pkg/argo-actions/actions.go
|
package argoactions
import "context"
type Action interface {
Do(context.Context) error
}
|
flashvoid/core
|
common/client/store.go
|
// Copyright (c) 2016-2017 <NAME>
// All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package client
import (
"bytes"
"encoding/json"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/docker/libkv"
libkvStore "github.com/docker/libkv/store"
libkvEtcd "github.com/docker/libkv/store/etcd"
"github.com/romana/core/common"
"github.com/romana/core/common/log/trace"
log "github.com/romana/rlog"
)
// Store is a structure storing information specific to KV-based
// implementation of Store.
type Store struct {
prefix string
libkvStore.Store
// etcdCli *clientv3.Client
}
func NewStore(etcdEndpoints []string, prefix string) (*Store, error) {
var err error
myStore := &Store{prefix: prefix}
myStore.Store, err = libkv.NewStore(
libkvStore.ETCD,
etcdEndpoints,
&libkvStore.Config{},
)
if err != nil {
return nil, err
}
// BEGIN EXPERIMENT...
// myStore.etcdCli, err := clientv3.New(clientv3.Config{
// Endpoints: etcdEndpoints,
// })
// if err != nil {
// return nil, err
// }
// END EXPERIMENT
// Test connection
_, err = myStore.Exists("test")
if err != nil {
return nil, err
}
return myStore, nil
}
func normalize(key string) string {
key2 := strings.TrimSpace(key)
elts := strings.Split(key2, "/")
normalizedElts := make([]string, 0)
for _, elt := range elts {
elt = strings.TrimSpace(elt)
if elt == "" {
continue
}
normalizedElts = append(normalizedElts, elt)
}
normalizedKey := strings.Join(normalizedElts, "/")
normalizedKey = "/" + normalizedKey
// log.Tracef(trace.Inside, "Normalized key %s to %s", key, normalizedKey)
return normalizedKey
}
// s.getKey normalizes key and prepends prefix to it
func (s *Store) getKey(key string) string {
// See https://github.com/docker/libkv/blob/master/store/helpers.go#L15
normalizedKey := normalize(s.prefix + "/" + key)
return normalizedKey
}
// BEGIN WRAPPER METHODS
// For now, the wrapper methods (below) just ensure the specified
// prefix is added to all keys (and this is mostly so that tests can
// run concurrently). Perhaps other things can be added later.
func (s *Store) Exists(key string) (bool, error) {
return s.Store.Exists(s.getKey(key))
}
func (s *Store) PutObject(key string, value []byte) error {
key = s.getKey(key)
log.Tracef(trace.Inside, "Saving object under key %s: %s", key, string(value))
return s.Store.Put(key, value, nil)
}
// Atomizable defines an interface on which it is possible to execute
// Atomic operations from the point of view of KVStore.
type Atomizable interface {
GetPrevKVPair() *libkvStore.KVPair
SetPrevKVPair(*libkvStore.KVPair)
}
func (s *Store) AtomicPut(key string, value Atomizable) error {
key = s.getKey(key)
b, err := json.Marshal(value)
if err != nil {
return err
}
prevVal := value.GetPrevKVPair()
ok, kvp, err := s.Store.AtomicPut(key, b, prevVal, nil)
if err != nil {
return err
}
if !ok {
return common.NewError("Could not store value under %s", key)
}
value.SetPrevKVPair(kvp)
prevIdx := uint64(0)
if prevVal != nil {
prevIdx = prevVal.LastIndex
}
log.Tracef(trace.Inside, "%d: AtomicPut(): At key %s, went from %d to %d", getGID(), key, prevIdx, kvp.LastIndex)
return nil
}
func (s *Store) Get(key string) (*libkvStore.KVPair, error) {
return s.Store.Get(s.getKey(key))
}
func (s *Store) GetBool(key string, defaultValue bool) (bool, error) {
kvp, err := s.Store.Get(s.getKey(key))
if err != nil {
if err == libkvStore.ErrKeyNotFound {
return defaultValue, nil
}
return false, err
}
return common.ToBool(string(kvp.Value))
}
func (s *Store) ListObjects(key string) ([]*libkvStore.KVPair, error) {
kvps, err := s.Store.List(s.getKey(key))
if err != nil {
return nil, err
}
return kvps, nil
}
func (s *Store) GetObject(key string) (*libkvStore.KVPair, error) {
kvp, err := s.Store.Get(s.getKey(key))
if err != nil {
if err == libkvStore.ErrKeyNotFound {
return nil, nil
}
return nil, err
}
return kvp, nil
}
func (s *Store) GetString(key string, defaultValue string) (string, error) {
kvp, err := s.Store.Get(s.getKey(key))
if err != nil {
if err == libkvStore.ErrKeyNotFound {
return defaultValue, nil
}
return "", err
}
return string(kvp.Value), nil
}
func (s *Store) GetInt(key string, defaultValue int) (int, error) {
kvp, err := s.Store.Get(s.getKey(key))
if err != nil {
if err == libkvStore.ErrKeyNotFound {
return defaultValue, nil
}
return 0, err
}
str := string(kvp.Value)
val, err := strconv.ParseInt(str, 32, 10)
return int(val), err
}
// Delete wrapes Delete operation, returning:
// - true if deletion succeede
// - false and no error if deletion failed because key was not found
// - false and error if another error occurred
func (s *Store) Delete(key string) (bool, error) {
err := s.Store.Delete(s.getKey(key))
if err == nil {
return true, nil
}
if err == libkvStore.ErrKeyNotFound {
return false, nil
}
return false, err
}
// END WRAPPER METHODS
// ReconnectingWatch wraps libkv Watch method, but attempts to re-establish
// the watch if it drop.
func (s *Store) ReconnectingWatch(key string, stopCh <-chan struct{}) (<-chan *libkvStore.KVPair, error) {
outCh := make(chan *libkvStore.KVPair)
inCh, err := s.Watch(s.getKey(key), stopCh)
if err != nil {
return nil, err
}
go s.reconnectingWatcher(key, stopCh, inCh, outCh)
return outCh, nil
}
func (s *Store) reconnectingWatcher(key string, stopCh <-chan struct{}, inCh <-chan *libkvStore.KVPair, outCh chan *libkvStore.KVPair) {
var err error
log.Tracef(trace.Private, "Entering ReconnectingWatch goroutine: %d", getGID())
channelClosed := false
retryDelay := 1 * time.Millisecond
for {
select {
case <-stopCh:
log.Info("Stop message received for WatchHosts")
return
case kv, ok := <-inCh:
if ok {
channelClosed = false
outCh <- kv
break
}
// Not ok - channel continues to be closed
if channelClosed {
// We got here because we attempted to re-create
// a watch but it came back with a closed channel again.
// So we should increase the retry
retryDelay *= 2
} else {
channelClosed = true
retryDelay = 1 * time.Millisecond
}
log.Infof("ReconnectingWatch: Lost watch on %s, trying to re-establish...", key)
for {
inCh, err = s.Watch(s.getKey(key), stopCh)
if err == nil {
break
} else {
log.Errorf("ReconnectingWatch: Error reconnecting: %v (%T)", err, err)
retryDelay *= 2
}
}
}
}
}
// Locker implements an interface for locking and unlocking.
// sync.Locker was not good for our purpose it does not allow
// for returning an error on lock. libkv's Locker is too libkv-specific
// and we do not need a stop channel really; and since the use case
// is to defer Unlock(), no need for it to return an error
type Locker interface {
Lock() (<-chan struct{}, error)
Unlock()
GetOwner() uint64
}
// storeLocker implements Locker interface using the
// lock form the backend store.
type storeLocker struct {
key string
owner uint64
libkvStore.Locker
}
// See https://blog.sgmansfield.com/2015/12/goroutine-ids/
func getGID() uint64 {
b := make([]byte, 64)
b = b[:runtime.Stack(b, false)]
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, _ := strconv.ParseUint(string(b), 10, 64)
return n
}
func (sl *storeLocker) GetOwner() uint64 {
return sl.owner
}
// Lock implements Lock method of Locker interface.
func (sl *storeLocker) Lock() (<-chan struct{}, error) {
stopChan := make(chan struct{})
ch, err := sl.Locker.Lock(stopChan)
if err == nil {
sl.owner = getGID()
} else {
log.Tracef(trace.Inside, "%d: Error getting lock for %s: %s", getGID(), sl.key, err)
}
return ch, err
}
// Unlock implements Unlock method of Locker interface.
func (sl *storeLocker) Unlock() {
prevOwner := sl.owner
sl.owner = 0
err := sl.Locker.Unlock()
if err != nil {
sl.owner = prevOwner
// switch err := err.(type) {
// case etcd.Error:
// if err.Code == etcd.ErrorCodeKeyNotFound {
// // If key is not found, then we did not hold the lock to begin with,
// // and unlock was called by a defer...
// }
// default:
// log.Errorf("%d: Error unlocking %s: %s (%T)", sl.key, err, err)
// }
log.Errorf("%d: Error unlocking %s: %s (%T)", getGID(), sl.key, err, err)
}
}
func (store *Store) NewLocker(name string) (Locker, error) {
key := store.getKey("/lock/" + name)
l, err := store.Store.NewLock(key, nil)
if err != nil {
return nil, err
}
return &storeLocker{key: key, Locker: l}, nil
}
// mutexLocker implements Locker interface with a sync.Mutex
type mutexLocker struct {
mutex *sync.Mutex
owner uint64
}
func (ml *mutexLocker) GetOwner() uint64 {
return ml.owner
}
// Lock implements Lock method of Locker interface.
func (ml *mutexLocker) Lock() (<-chan struct{}, error) {
ch := make(<-chan struct{})
if ml.mutex == nil {
ml.mutex = &sync.Mutex{}
}
ml.mutex.Lock()
ml.owner = getGID()
return ch, nil
}
// Unlock implements Unlock method of Locker interface.
func (ml *mutexLocker) Unlock() {
ml.owner = 0
ml.mutex.Unlock()
}
func newMutexLocker() *mutexLocker {
return &mutexLocker{mutex: &sync.Mutex{}}
}
func init() {
// Register etcd store to libkv
libkvEtcd.Register()
}
|
roboterclubaachen/xpcc-doc
|
docs/api/classxpcc_1_1_zero_m_q_connector.js
|
var classxpcc_1_1_zero_m_q_connector =
[
[ "ZeroMQConnector", "classxpcc_1_1_zero_m_q_connector.html#ad5234fe1fee59e5fb75e3f1e611b327d", null ],
[ "~ZeroMQConnector", "classxpcc_1_1_zero_m_q_connector.html#ad8342473c74376c8df9deb65c6f26ee8", null ],
[ "sendPacket", "classxpcc_1_1_zero_m_q_connector.html#a9dd08bd8a48e537bea471862fc1c811f", null ],
[ "isPacketAvailable", "classxpcc_1_1_zero_m_q_connector.html#a7353598b7a2ec64beae5125cfaa4e122", null ],
[ "getPacketHeader", "classxpcc_1_1_zero_m_q_connector.html#a69b6998df64c439730439e90eb6e373f", null ],
[ "getPacketPayload", "classxpcc_1_1_zero_m_q_connector.html#ab5c0cf01d64e35ed3f0d8cf4e08a01c6", null ],
[ "dropPacket", "classxpcc_1_1_zero_m_q_connector.html#aa5731d201c5611e1333e8aa289dd3793", null ],
[ "update", "classxpcc_1_1_zero_m_q_connector.html#a4956a3c202012af87365cf028abf9fde", null ],
[ "context", "classxpcc_1_1_zero_m_q_connector.html#a93f7e85aef9340361f3c9cda8fd3977d", null ],
[ "socketIn", "classxpcc_1_1_zero_m_q_connector.html#a937b3218e2a8ffa8e6c748d2b84d131c", null ],
[ "socketOut", "classxpcc_1_1_zero_m_q_connector.html#a8677e124ff8fbeeeb74d995b226527d4", null ],
[ "reader", "classxpcc_1_1_zero_m_q_connector.html#a967551aa0f8d845f111cb42473563c62", null ]
];
|
TheWhiteEagle/Dryad
|
DryadVertex/VertexHost/system/common/include/dryaderror.h
|
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
// This file must contain *only* DEFINE_DRYAD_ERROR directives!
//
//
// It is included multiple times with different macro definitions.
// Dummy error
DEFINE_DRYAD_ERROR (DryadError_BadMetaData, DRYAD_ERROR (0x0001), "Bad MetaData XML")
DEFINE_DRYAD_ERROR (DryadError_InvalidCommand, DRYAD_ERROR (0x0002), "Invalid Command")
DEFINE_DRYAD_ERROR (DryadError_VertexReceivedTermination, DRYAD_ERROR (0x0003), "Vertex Received Termination")
DEFINE_DRYAD_ERROR (DryadError_InvalidChannelURI, DRYAD_ERROR (0x0004), "Invalid Channel URI syntax")
DEFINE_DRYAD_ERROR (DryadError_ChannelOpenError, DRYAD_ERROR (0x0005), "Channel Open Error")
DEFINE_DRYAD_ERROR (DryadError_ChannelRestartError, DRYAD_ERROR (0x0006), "Channel Restart Error")
DEFINE_DRYAD_ERROR (DryadError_ChannelWriteError, DRYAD_ERROR (0x0007), "Channel Write Error")
DEFINE_DRYAD_ERROR (DryadError_ChannelReadError, DRYAD_ERROR (0x0008), "Channel Read Error")
DEFINE_DRYAD_ERROR (DryadError_ItemParseError, DRYAD_ERROR (0x0009), "Item Parse Error")
DEFINE_DRYAD_ERROR (DryadError_ItemMarshalError, DRYAD_ERROR (0x0010), "Item Marshal Error")
DEFINE_DRYAD_ERROR (DryadError_BufferHole, DRYAD_ERROR (0x0011), "Buffer Hole")
DEFINE_DRYAD_ERROR (DryadError_ItemHole, DRYAD_ERROR (0x0012), "Item Hole")
DEFINE_DRYAD_ERROR (DryadError_ChannelRestart, DRYAD_ERROR (0x0013), "Channel Sent Restart")
DEFINE_DRYAD_ERROR (DryadError_ChannelAbort, DRYAD_ERROR (0x0014), "Channel Sent Abort")
DEFINE_DRYAD_ERROR (DryadError_VertexRunning, DRYAD_ERROR (0x0015), "Vertex Is Running")
DEFINE_DRYAD_ERROR (DryadError_VertexCompleted, DRYAD_ERROR (0x0016), "Vertex Has Completed")
DEFINE_DRYAD_ERROR (DryadError_VertexError, DRYAD_ERROR (0x0017), "Vertex Had Errors")
DEFINE_DRYAD_ERROR (DryadError_ProcessingError, DRYAD_ERROR (0x0018), "Error While Processing")
DEFINE_DRYAD_ERROR (DryadError_VertexInitialization, DRYAD_ERROR (0x0019), "Vertex Could Not Initialize")
DEFINE_DRYAD_ERROR (DryadError_ProcessingInterrupted, DRYAD_ERROR (0x001a), "Processing was interrupted before completion")
DEFINE_DRYAD_ERROR (DryadError_VertexChannelClose, DRYAD_ERROR (0x001b), "Errors during channel close")
DEFINE_DRYAD_ERROR (DryadError_AssertFailure, DRYAD_ERROR (0x001c), "Assertion Failure")
DEFINE_DRYAD_ERROR (DryadError_ExternalChannel, DRYAD_ERROR (0x001d), "External Channel")
DEFINE_DRYAD_ERROR (DryadError_AlreadyInitialized, DRYAD_ERROR (0x001e), "Dryad Already Initialized")
DEFINE_DRYAD_ERROR (DryadError_DuplicateVertices, DRYAD_ERROR (0x001f), "Duplicate Vertices")
DEFINE_DRYAD_ERROR (DryadError_ComposeRHSNeedsInput, DRYAD_ERROR (0x0020), "RHS of composition must have at least one input")
DEFINE_DRYAD_ERROR (DryadError_ComposeLHSNeedsOutput, DRYAD_ERROR (0x0021), "LHS of composition must have at least one output")
DEFINE_DRYAD_ERROR (DryadError_ComposeStagesMustBeDifferent, DRYAD_ERROR (0x0022), "Stages for composition must be different")
DEFINE_DRYAD_ERROR (DryadError_ComposeStageEmpty, DRYAD_ERROR (0x0023), "Stage for composition is empty")
DEFINE_DRYAD_ERROR (DryadError_VertexNotInGraph, DRYAD_ERROR (0x0024), "Vertex not in graph")
DEFINE_DRYAD_ERROR (DryadError_HardConstraintCannotBeMet, DRYAD_ERROR (0x0025), "Hard constraint cannot be met")
DEFINE_DRYAD_ERROR (DryadError_MustRequeue, DRYAD_ERROR (0x0026), "Must requeue process")
|
seahrh/cses-problem-set
|
cses/graphalgorithms/1667_MessageRoute.cpp
|
/*
Syrjälä's network has n computers and m connections.
Your task is to find out if Uolevi can send a message to Maija,
and if it is possible, what is the minimum number of computers on such a route.
Input
The first input line has two integers n and m: the number of computers and connections.
The computers are numbered 1,2,…,n. Uolevi's computer is 1 and Maija's computer is n.
Then, there are m lines describing the connections.
Each line has two integers a and b: there is a connection between those computers.
Every connection is between two different computers, and there is at most one connection between any two computers.
Output
If it is possible to send a message,
first print k: the minimum number of computers on a valid route.
After this, print an example of such a route. You can print any valid solution.
If there are no routes, print "IMPOSSIBLE".
Constraints
2≤n≤10^5
1≤m≤2⋅10^5
1≤a,b≤n
Example
Input:
5 5
1 2
1 3
1 4
2 3
5 4
Output:
3
1 4 5
SOLUTION
BFS to find shortest path.
Time O(N + M)
Space O(N + M)
*/
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll max_size = 1e5 + 1;
vector<bool> vis(max_size);
vector<vector<ll>> adj(max_size);
vector<ll> parent(max_size);
void bfs(ll s)
{
vis[s] = 1;
deque<ll> q;
q.push_back(s);
while (!q.empty())
{
ll curr = q.front();
q.pop_front();
for (auto i : adj[curr])
{
if (vis[i])
continue;
vis[i] = 1;
parent[i] = curr;
q.push_back(i);
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n, m;
cin >> n >> m;
while (m--)
{
ll a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
bfs(1);
if (!vis[n])
{
cout << "IMPOSSIBLE";
return 0;
}
deque<ll> path;
ll i = n;
while (i != 1)
{
path.push_front(i);
i = parent[i];
}
path.push_front(1);
cout << path.size() << endl;
for (auto p : path)
cout << p << " ";
return 0;
}
|
Pandinosaurus/gpu.js
|
test/features/to-string/precision/unsigned/arguments/input.js
|
const { assert, skip, test, module: describe, only } = require('qunit');
const { GPU, input } = require('../../../../../../dist/gpu.js');
describe('feature: to-string unsigned precision arguments Input');
function testArgument(mode, context, canvas) {
const gpu = new GPU({ mode });
const originalKernel = gpu.createKernel(function(a) {
let sum = 0;
for (let y = 0; y < 2; y++) {
for (let x = 0; x < 2; x++) {
sum += a[y][x];
}
}
return sum;
}, {
canvas,
context,
output: [1],
precision: 'unsigned',
});
const arg1 = input([1,2,3,4],[2,2]);
const arg2 = input([5,6,7,8],[2,2]);
assert.deepEqual(originalKernel(arg1)[0], 10);
assert.deepEqual(originalKernel(arg2)[0], 26);
const kernelString = originalKernel.toString(arg1);
const newKernel = new Function('return ' + kernelString)()({ context });
assert.deepEqual(newKernel(arg1)[0], 10);
assert.deepEqual(newKernel(arg2)[0], 26);
gpu.destroy();
}
(GPU.isWebGLSupported ? test : skip)('webgl', () => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('webgl');
testArgument('webgl', context, canvas);
});
(GPU.isWebGL2Supported ? test : skip)('webgl2', () => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('webgl2');
testArgument('webgl2', context, canvas);
});
(GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => {
testArgument('headlessgl', require('gl')(1, 1), null);
});
test('cpu', () => {
testArgument('cpu');
});
|
saltaf07/Public-Scripts
|
common/utils/get-focusable-elements.js
|
// @flow
// https://gomakethings.com/how-to-get-the-first-and-last-focusable-elements-in-the-dom/
const getFocusableElements = (el: HTMLElement): HTMLElement[] => {
return [
...el.querySelectorAll(
'button, [href]:not([tabindex="-1"]), input, select, textarea, [tabindex]:not([tabindex="-1"])'
),
];
};
export default getFocusableElements;
|
zamorajavi/google-input-tools
|
client/imm/context_manager.h
|
/*
Copyright 2014 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef GOOPY_IMM_CONTEXT_MANAGER_H__
#define GOOPY_IMM_CONTEXT_MANAGER_H__
#include <atlbase.h>
#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "common/debug.h"
#include "common/framework_interface.h"
#include "imm/context.h"
#include "imm/candidate_info.h"
#include "imm/composition_string.h"
#include "imm/context_locker.h"
#include "imm/debug.h"
#include "imm/immdev.h"
namespace ime_goopy {
namespace imm {
template <class ContextType>
class ContextManagerT {
public:
~ContextManagerT() {
DestroyAll();
}
// Create a context in the pool. The caller should call Destroy to delete the
// context if user is switching to another input method.
bool Add(HIMC himc, ContextType* context) {
assert(himc);
if (!context) return false;
CComCritSecLock<CComAutoCriticalSection> lock(critical_section_);
ContextMap::const_iterator iter = context_map_.find(himc);
if (iter != context_map_.end()) return iter->second;
context_map_[himc] = context;
return true;
}
ContextType* Get(HIMC himc) {
if (!himc) return NULL;
CComCritSecLock<CComAutoCriticalSection> lock(critical_section_);
ContextMap::const_iterator iter = context_map_.find(himc);
if (iter == context_map_.end()) return NULL;
return iter->second;
}
// Save the mapping of context <-> ui_manager
bool AssociateUIManager(ContextInterface* context,
UIManagerInterface* ui_manager) {
if (!context || !ui_manager) return false;
CComCritSecLock<CComAutoCriticalSection> lock(critical_section_);
active_ui_manager_map_[context] = ui_manager;
return true;
}
UIManagerInterface* DisassociateUIManager(ContextInterface* context) {
if (!context) return NULL;
CComCritSecLock<CComAutoCriticalSection> lock(critical_section_);
ContextUIManagerMap::iterator iter =
active_ui_manager_map_.find(context);
if (iter == active_ui_manager_map_.end()) return NULL;
UIManagerInterface* ui_manager = iter->second;
active_ui_manager_map_.erase(iter);
return ui_manager;
}
ContextType* GetFromWindow(HWND hwnd) {
assert(hwnd);
// There is a bug in the type definition of GetWindowLongPtr, which cause
// the warning 4312. So we disable this warning just for the following
// line. More information at
// http://kernelmustard.com/2006/09/16/when-you-cant-follow-the-api/
// ImmGetContext can't be used here, because when the focus changed to an
// empty context, ImmGetContext() still get the old context handler, not the
// expected NULL value.
#pragma warning(suppress:4312)
HIMC himc = reinterpret_cast<HIMC>(GetWindowLongPtr(hwnd, IMMGWLP_IMC));
return Get(himc);
}
bool Destroy(HIMC himc) {
assert(himc);
CComCritSecLock<CComAutoCriticalSection> lock(critical_section_);
ContextMap::iterator iter = context_map_.find(himc);
if (iter == context_map_.end()) return false;
delete iter->second;
context_map_.erase(iter);
return true;
}
void DestroyAll() {
DVLOG(1) << __FUNCTION__;
CComCritSecLock<CComAutoCriticalSection> lock(critical_section_);
for (ContextMap::const_iterator iter = context_map_.begin();
iter != context_map_.end();
iter++) {
delete iter->second;
}
context_map_.clear();
}
static ContextManagerT& Instance() {
static ContextManagerT manager;
return manager;
}
private:
typedef map<HIMC, ContextType*> ContextMap;
typedef map<ContextInterface*, UIManagerInterface*> ContextUIManagerMap;
ContextManagerT() {}
ContextMap context_map_;
CComAutoCriticalSection critical_section_;
// Bug fix for 4505900(IME v2.4 crash in explorer.exe process under WindowsXP)
// There will be mutiple UIWindow objects and UIManager objects in
// explorer.exe process at the same time. The mapping from context to
// active ui_manager should be saved. So that, while a context is switched
// out, the according ui_manager can be deactivated.
ContextUIManagerMap active_ui_manager_map_;
DISALLOW_EVIL_CONSTRUCTORS(ContextManagerT);
};
typedef ContextManagerT<Context> ContextManager;
} // namespace imm
} // namespace ime_goopy
#endif // GOOPY_IMM_CONTEXT_MANAGER_H__
|
ulisesten/xalanc
|
src/xalanc/XPath/XToken.cpp
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Class header file.
#include "XToken.hpp"
#include <xalanc/PlatformSupport/DoubleSupport.hpp>
#include "XObjectTypeCallback.hpp"
namespace XALAN_CPP_NAMESPACE {
static const XalanDOMString s_emptyString(XalanMemMgrs::getDummyMemMgr());
XToken::XToken(MemoryManager& theMemoryManager) :
XObject(eTypeString, theMemoryManager),
m_stringValue(&s_emptyString),
m_numberValue(DoubleSupport::getNaN()),
m_isString(true)
{
}
XToken::XToken(
const XalanDOMString& theString,
double theNumber,
MemoryManager& theMemoryManager) :
XObject(eTypeString, theMemoryManager),
m_stringValue(&theString),
m_numberValue(theNumber),
m_isString(true)
{
}
XToken::XToken(
double theNumber,
const XalanDOMString& theString,
MemoryManager& theMemoryManager) :
XObject(eTypeString, theMemoryManager),
m_stringValue(&theString),
m_numberValue(theNumber),
m_isString(false)
{
}
XToken::XToken(
const XToken& theSource,
MemoryManager& theMemoryManager) :
XObject(theSource, theMemoryManager),
m_stringValue(theSource.m_stringValue),
m_numberValue(theSource.m_numberValue),
m_isString(theSource.m_isString)
{
assert(m_stringValue != 0);
}
XToken::XToken(const XToken& theSource) :
XObject(theSource),
m_stringValue(theSource.m_stringValue),
m_numberValue(theSource.m_numberValue),
m_isString(theSource.m_isString)
{
assert(m_stringValue != 0);
}
XToken::~XToken()
{
assert(m_stringValue != 0);
}
const XalanDOMString&
XToken::getTypeString() const
{
assert(m_stringValue != 0);
return s_stringString;
}
double
XToken::num(XPathExecutionContext& /* executionContext */) const
{
assert(m_stringValue != 0);
return m_numberValue;
}
bool
XToken::boolean(XPathExecutionContext& /* executionContext */) const
{
assert(m_stringValue != 0);
return m_isString == true ? XObject::boolean(*m_stringValue) : XObject::boolean(m_numberValue);
}
const XalanDOMString&
XToken::str(XPathExecutionContext& /* executionContext */) const
{
return *m_stringValue;
}
const XalanDOMString&
XToken::str() const
{
return *m_stringValue;
}
void
XToken::str(
XPathExecutionContext& /* executionContext */,
FormatterListener& formatterListener,
MemberFunctionPtr function) const
{
assert(m_stringValue != 0);
string(*m_stringValue, formatterListener, function);
}
void
XToken::str(
FormatterListener& formatterListener,
MemberFunctionPtr function) const
{
assert(m_stringValue != 0);
string(*m_stringValue, formatterListener, function);
}
void
XToken::str(XalanDOMString& theBuffer) const
{
assert(m_stringValue != 0);
theBuffer.append(*m_stringValue);
}
void
XToken::str(
XPathExecutionContext& /* executionContext */,
XalanDOMString& theBuffer) const
{
assert(m_stringValue != 0);
theBuffer.append(*m_stringValue);
}
double
XToken::stringLength(XPathExecutionContext& /* executionContext */) const
{
assert(m_stringValue != 0);
return static_cast<double>(m_stringValue->length());
}
void
XToken::ProcessXObjectTypeCallback(XObjectTypeCallback& theCallbackObject)
{
assert(m_stringValue != 0);
if (m_isString == true)
{
theCallbackObject.String(*this, *m_stringValue);
}
else
{
theCallbackObject.Number(*this, m_numberValue);
}
}
void
XToken::ProcessXObjectTypeCallback(XObjectTypeCallback& theCallbackObject) const
{
assert(m_stringValue != 0);
if (m_isString == true)
{
theCallbackObject.String(*this, *m_stringValue);
}
else
{
theCallbackObject.Number(*this, m_numberValue);
}
}
void
XToken::set(
const XalanDOMString& theString,
double theNumber)
{
m_stringValue = &theString;
m_numberValue = theNumber;
m_isString = true;
}
void
XToken::set(
double theNumber,
const XalanDOMString& theString)
{
m_numberValue = theNumber;
m_stringValue = &theString;
m_isString = false;
}
void
XToken::referenced()
{
}
void
XToken::dereferenced()
{
}
}
|
ls1110924/Aria
|
FtpComponent/src/main/java/com/arialyy/aria/ftp/download/FtpDGInfoTask.java
|
/*
* Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria)
*
* 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.arialyy.aria.ftp.download;
import android.net.Uri;
import android.text.TextUtils;
import aria.apache.commons.net.ftp.FTPClient;
import aria.apache.commons.net.ftp.FTPFile;
import aria.apache.commons.net.ftp.FTPReply;
import com.arialyy.aria.core.FtpUrlEntity;
import com.arialyy.aria.core.common.CompleteInfo;
import com.arialyy.aria.core.download.DGTaskWrapper;
import com.arialyy.aria.core.download.DTaskWrapper;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadGroupEntity;
import com.arialyy.aria.core.wrapper.AbsTaskWrapper;
import com.arialyy.aria.ftp.AbsFtpInfoTask;
import com.arialyy.aria.ftp.FtpTaskOption;
import com.arialyy.aria.orm.DbEntity;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.DeleteDGRecord;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
/**
* Created by Aria.Lao on 2017/7/25. 获取ftp文件夹信息
*/
final class FtpDGInfoTask extends AbsFtpInfoTask<DownloadGroupEntity, DGTaskWrapper> {
FtpDGInfoTask(DGTaskWrapper wrapper) {
super(wrapper);
}
@Override public void run() {
if (mTaskWrapper.getEntity().getFileSize() > 1 && checkSubOption()) {
onSucceed(new CompleteInfo(200, mTaskWrapper));
} else {
super.run();
}
}
@Override
protected void handelFileInfo(FTPClient client, FTPFile[] files, String convertedRemotePath)
throws IOException {
boolean isExist = files.length != 0;
if (!isExist) {
int i = convertedRemotePath.lastIndexOf(File.separator);
FTPFile[] files1;
if (i == -1) {
files1 = client.listFiles();
} else {
files1 = client.listFiles(convertedRemotePath.substring(0, i + 1));
}
if (files1.length > 0) {
ALog.i(TAG,
String.format("路径【%s】下的文件列表 ===================================", getRemotePath()));
for (FTPFile file : files1) {
ALog.d(TAG, file.toString());
}
ALog.i(TAG,
"================================= --end-- ===================================");
} else {
ALog.w(TAG, String.format("获取文件列表失败,msg:%s", client.getReplyString()));
}
closeClient(client);
handleFail(client,
String.format("文件不存在,url: %s, remotePath:%s", mTaskOption.getUrlEntity().url,
getRemotePath()), null, false);
return;
}
// 处理拦截功能
if (!onInterceptor(client, files)) {
closeClient(client);
ALog.d(TAG, "拦截器处理完成任务");
return;
}
//为了防止编码错乱,需要使用原始字符串
mSize = getFileSize(files, client, getRemotePath());
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
closeClient(client);
handleFail(client, "获取文件信息错误,url: " + mTaskOption.getUrlEntity().url, null, true);
return;
}
mTaskWrapper.setCode(reply);
if (mSize != 0) {
mEntity.setFileSize(mSize);
}
onPreComplete(reply);
mEntity.update();
}
/**
* 检查子任务的任务设置
*
* @return true 子任务任务设置成功,false 子任务任务设置失败
*/
private boolean checkSubOption() {
for (DTaskWrapper wrapper : mTaskWrapper.getSubTaskWrapper()) {
if (wrapper.getTaskOption() == null) {
return false;
}
}
return true;
}
@Override protected String getRemotePath() {
return mTaskOption.getUrlEntity().remotePath;
}
@Override protected void handleFile(FTPClient client, String remotePath, FTPFile ftpFile) {
super.handleFile(client, remotePath, ftpFile);
addEntity(remotePath, ftpFile);
}
@Override protected void onPreComplete(int code) {
super.onPreComplete(code);
mEntity.setFileSize(mSize);
for (DTaskWrapper wrapper : mTaskWrapper.getSubTaskWrapper()) {
cloneInfo(wrapper);
}
onSucceed(new CompleteInfo(code, mTaskWrapper));
}
private void cloneInfo(DTaskWrapper subWrapper) {
FtpTaskOption option = (FtpTaskOption) mTaskWrapper.getTaskOption();
FtpUrlEntity urlEntity = option.getUrlEntity().clone();
Uri uri = Uri.parse(subWrapper.getEntity().getUrl());
String remotePath = uri.getPath();
urlEntity.remotePath = TextUtils.isEmpty(remotePath) ? "/" : remotePath;
FtpTaskOption subOption = new FtpTaskOption();
subOption.setUrlEntity(urlEntity);
subOption.setCharSet(option.getCharSet());
subOption.setProxy(option.getProxy());
subOption.setClientConfig(option.getClientConfig());
subOption.setNewFileName(option.getNewFileName());
subOption.setProxy(option.getProxy());
subOption.setUploadInterceptor(option.getUploadInterceptor());
subWrapper.setTaskOption(subOption);
}
/**
* FTP文件夹的子任务实体 在这生成
*/
private void addEntity(String remotePath, FTPFile ftpFile) {
final FtpUrlEntity urlEntity = mTaskOption.getUrlEntity().clone();
String url =
urlEntity.scheme + "://" + urlEntity.hostName + ":" + urlEntity.port + "/" + remotePath;
if (checkEntityExist(url)) {
ALog.w(TAG, "子任务已存在,取消子任务的添加,url = " + url);
return;
}
DownloadEntity entity = new DownloadEntity();
entity.setUrl(url);
entity.setFilePath(mEntity.getDirPath() + "/" + remotePath);
int lastIndex = remotePath.lastIndexOf("/");
String fileName = lastIndex < 0 ? CommonUtil.keyToHashKey(remotePath)
: remotePath.substring(lastIndex + 1);
entity.setFileName(
new String(fileName.getBytes(), Charset.forName(mTaskOption.getCharSet())));
entity.setGroupHash(mEntity.getGroupHash());
entity.setGroupChild(true);
entity.setConvertFileSize(CommonUtil.formatFileSize(ftpFile.getSize()));
entity.setFileSize(ftpFile.getSize());
if (DbEntity.checkDataExist(DownloadEntity.class, "downloadPath=?", entity.getFilePath())) {
DbEntity.deleteData(DownloadEntity.class, "downloadPath=?", entity.getFilePath());
}
entity.insert();
DTaskWrapper subWrapper = new DTaskWrapper(entity);
subWrapper.setGroupTask(true);
subWrapper.setGroupHash(mEntity.getGroupHash());
subWrapper.setRequestType(AbsTaskWrapper.D_FTP);
urlEntity.url = entity.getUrl();
urlEntity.remotePath = remotePath;
cloneInfo(subWrapper, urlEntity);
if (mEntity.getUrls() == null) {
mEntity.setUrls(new ArrayList<String>());
}
mEntity.getSubEntities().add(entity);
mTaskWrapper.getSubTaskWrapper().add(subWrapper);
}
private void cloneInfo(DTaskWrapper subWrapper, FtpUrlEntity urlEntity) {
FtpTaskOption subOption = new FtpTaskOption();
subOption.setUrlEntity(urlEntity);
subOption.setCharSet(mTaskOption.getCharSet());
subOption.setProxy(mTaskOption.getProxy());
subOption.setClientConfig(mTaskOption.getClientConfig());
subOption.setNewFileName(mTaskOption.getNewFileName());
subOption.setProxy(mTaskOption.getProxy());
subOption.setUploadInterceptor(mTaskOption.getUploadInterceptor());
subWrapper.setTaskOption(subOption);
}
/**
* 检查子任务是否已经存在,如果子任务存在,取消添加操作
*
* @param key url
* @return true 子任务已存在,false 子任务不存在
*/
private boolean checkEntityExist(String key) {
for (DTaskWrapper wrapper : mTaskWrapper.getSubTaskWrapper()) {
if (wrapper.getKey().equals(key)) {
return true;
}
}
return false;
}
@Override
protected void handleFail(FTPClient client, String msg, Exception e, boolean needRetry) {
super.handleFail(client, msg, e, needRetry);
DeleteDGRecord.getInstance().deleteRecord(mTaskWrapper.getEntity(), true, true);
}
}
|
ckamtsikis/cmssw
|
FWCore/Integration/python/restricted_cff.py
|
import FWCore.ParameterSet.Config as cms
cms.checkImportPermission(allowedPatterns = ['allowed'])
|
ph4m/constrained-rl
|
ceres/tools/io/h5_helper.py
|
<filename>ceres/tools/io/h5_helper.py
# Copyright (c) IBM Corp. 2018. All Rights Reserved.
# Project name: Constrained Exploration and Recovery from Experience Shaping
# This project is licensed under the MIT License, see LICENSE
import os
import h5py
'''
Helper functions for writing and loading data in the HDF5 format
'''
def save_dict_as_h5(d, path_save, confirm_overwrite=True, verbose=False):
assert type(d) == dict, 'Invalid dictionary argument: {0}'.format(d)
assert type(path_save) == str, 'Invalid path argument: {0}'.format(path_save)
assert os.path.isdir(os.path.dirname(path_save)), 'Directory for save path does not exist: {0}'.format(path_save)
if os.path.isfile(path_save):
if confirm_overwrite:
if input('File exists: {0}\nOverwrite?[y/N]\n'.format(path_save)).lower() != 'y':
print('Cancel write')
return False
os.remove(path_save)
# Check that no nested dictionary
with h5py.File(path_save, 'w') as h5f:
write_dict(h5f, d)
if verbose:
print('Wrote backup: {0}'.format(path_save))
return True
def write_dict(h5f, d):
for _k, _v in d.items():
if type(_v) == dict:
grp = h5f.create_group(_k)
write_dict(grp, _v)
else:
h5f.create_dataset(_k, data=_v)
def load_dict_from_h5(path_save, verbose=False):
d = {}
with h5py.File(path_save, 'r') as h5f:
read_dict(h5f, d)
if verbose:
print('Loaded {0} from backup: {0}'.format(','.join(d.keys())))
return d
def read_dict(h5f, d):
for _k, _v in h5f.items():
if isinstance(_v, h5py.Dataset):
d[_k] = _v[()]
else:
assert isinstance(_v, h5py.Group)
d[_k] = {}
read_dict(_v, d[_k])
|
Bobinette/papernet
|
papernet/services/paper.go
|
package services
import (
"fmt"
"github.com/bobinette/papernet/errors"
"github.com/bobinette/papernet/papernet"
"github.com/bobinette/papernet/users"
)
func errPaperNotFound(id int) error {
return errors.New(fmt.Sprintf("paper %d not found", id), errors.NotFound())
}
type UserService interface {
CreatePaper(userID, paperID int) error
}
type PaperService struct {
repository papernet.PaperRepository
index papernet.PaperIndex
userService UserService
tagService *TagService
}
func NewPaperService(
repo papernet.PaperRepository,
index papernet.PaperIndex,
us UserService,
ts *TagService,
) *PaperService {
return &PaperService{
repository: repo,
index: index,
userService: us,
tagService: ts,
}
}
func (s *PaperService) Get(user users.User, id int) (papernet.Paper, error) {
if err := aclCanSee(user, id); err != nil {
return papernet.Paper{}, err
}
papers, err := s.repository.Get(id)
if err != nil {
return papernet.Paper{}, err
} else if len(papers) != 1 {
return papernet.Paper{}, errPaperNotFound(id)
}
return papers[0], nil
}
type SearchResults struct {
Papers []papernet.Paper `json:"papers"`
Facets papernet.Facets `json:"facets"`
Pagination papernet.Pagination `json:"pagination"`
}
func (s *PaperService) Search(user users.User, q string, tags []string, bookmarked bool, offset, limit int) (SearchResults, error) {
sp := papernet.SearchParams{
IDs: user.CanSee,
Q: q,
Tags: tags,
Offset: uint64(offset),
Limit: uint64(limit),
}
if bookmarked {
sp.IDs = user.Bookmarks
}
if sp.Limit <= 0 {
sp.Limit = 20
}
res, err := s.index.Search(sp)
if err != nil {
return SearchResults{}, err
}
papers, err := s.repository.Get(res.IDs...)
if err != nil {
return SearchResults{}, err
}
return SearchResults{
Papers: papers,
Facets: res.Facets,
Pagination: res.Pagination,
}, nil
}
func (s *PaperService) Create(callerID int, paper papernet.Paper) (papernet.Paper, error) {
if paper.ID != 0 {
return papernet.Paper{}, errors.New("id already set", errors.BadRequest())
}
err := s.repository.Upsert(&paper)
if err != nil {
return papernet.Paper{}, err
}
err = s.userService.CreatePaper(callerID, paper.ID)
if err != nil {
return papernet.Paper{}, err
}
err = s.index.Index(&paper)
if err != nil {
return papernet.Paper{}, err
}
return paper, nil
}
func (s *PaperService) Update(user users.User, paper papernet.Paper) (papernet.Paper, error) {
if paper.ID == 0 {
return papernet.Paper{}, errors.New("id already set", errors.BadRequest())
}
err := aclCanEdit(user, paper.ID)
if err != nil {
return papernet.Paper{}, err
}
err = s.repository.Upsert(&paper)
if err != nil {
return papernet.Paper{}, err
}
err = s.index.Index(&paper)
if err != nil {
return papernet.Paper{}, err
}
return paper, nil
}
func (s *PaperService) Delete(user users.User, paperID int) error {
err := aclCanDelete(user, paperID)
if err != nil {
return err
}
err = s.repository.Delete(paperID)
if err != nil {
return err
}
err = s.index.Delete(paperID)
if err != nil {
return err
}
return nil
}
func aclCanSee(user users.User, paperID int) error {
if !contains(paperID, user.CanSee) {
return errPaperNotFound(paperID)
}
return nil
}
func aclCanEdit(user users.User, paperID int) error {
// CanEdit < CanSee
err := aclCanSee(user, paperID)
if err != nil {
return err
}
if !contains(paperID, user.CanEdit) {
return errors.New("you do not have edit permission", errors.Forbidden())
}
return nil
}
func aclCanDelete(user users.User, paperID int) error {
// Owns < CanSee
err := aclCanSee(user, paperID)
if err != nil {
return err
}
if !contains(paperID, user.Owns) {
return errors.New("only the owner can delete a paper", errors.Forbidden())
}
return nil
}
func contains(v int, a []int) bool {
for _, i := range a {
if i == v {
return true
}
}
return false
}
|
applitools/eyes.selenium.python
|
applitools/core/geometry.py
|
<reponame>applitools/eyes.selenium.python
from __future__ import absolute_import
import math
import typing as tp
from collections import OrderedDict
from .errors import EyesError
if tp.TYPE_CHECKING:
from ..utils.custom_types import ViewPort
__all__ = ('Point', 'Region',)
class Point(object):
"""
A point with the coordinates (x,y).
"""
__slots__ = ('x', 'y')
def __init__(self, x=0, y=0):
# type: (float, float) -> None
self.x = int(round(x))
self.y = int(round(y))
def __getstate__(self):
return OrderedDict([("x", self.x),
("y", self.y)])
def __setstate__(self, state):
self.x = state['x']
self.y = state['y']
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
return Point(self.x * scalar, self.y * scalar)
def __div__(self, scalar):
return Point(self.x / scalar, self.y / scalar)
def __repr__(self):
return "({0}, {1})".format(self.x, self.y)
def __bool__(self):
return self.x and self.y
def __getitem__(self, item):
if item not in ('x', 'y'):
raise KeyError
return getattr(self, item)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
@classmethod
def create_top_left(cls):
return cls(0, 0)
def length(self):
# type: () -> float
"""
Returns the distance from (0, 0).
"""
return math.sqrt(self.x ** 2 + self.y ** 2)
def distance_to(self, p):
# type: (Point) -> float
"""
Calculate the distance between two points.
:return: The distance to p.
"""
return (self - p).length()
def as_tuple(self):
# type: () -> tuple
"""
Return the point as a tuple.
:return: Point as tuple.
"""
return self.x, self.y
def clone(self):
# type: () -> Point
"""
Return a full copy of this point.
:return: Cloned point.
"""
return Point(self.x, self.y)
def move_to(self, x, y):
# type: (int, int) -> None
"""
Moves the point to new x, y.
:param x: Coordinate x.
:param y: Coordinate y.
"""
self.x = x
self.y = y
def offset(self, dx, dy):
# type: (int, int) -> Point
"""
Move to new (x+dx,y+dy).
:param dx: Offset to move coordinate x.
:param dy: Offset to move coordinate y.
"""
self.x = self.x + dx
self.y = self.y + dy
return self
def offset_by_location(self, location):
# type: (Point) -> Point
self.offset(location.x, location.y)
return self
def offset_negative(self, dx, dy):
# type: (int, int) -> Point
self.x -= dx
self.y -= dy
return self
def rotate(self, rad):
# type: (int) -> Point
"""
Rotate counter-clockwise around the origin by rad radians.
Positive y goes *up,* as in traditional mathematics.
Interestingly, you can use this in y-down computer graphics, if
you just remember that it turns clockwise, rather than
counter-clockwise.
:param rad: The radians to rotate the point.
:return: The new position is returned as a new Point.
"""
s, c = [f(rad) for f in (math.sin, math.cos)]
x, y = (c * self.x - s * self.y, s * self.x + c * self.y)
return Point(x, y)
def rotate_about(self, p, theta):
# type: (Point, int) -> Point
"""
Rotate counter-clockwise around a point, by theta degrees.
Positive y goes *up,* as in traditional mathematics.
The new position is returned as a new Point.
:param p: A point to rotate around.
:param theta: Theta degrees to rotate around.
:return: The result of the rotation.
"""
result = self.clone()
result.offset(-p.x, -p.y)
result.rotate(theta)
result.offset(p.x, p.y)
return result
def scale(self, scale_ratio):
return Point(int(math.ceil(self.x * scale_ratio)),
int(math.ceil(self.y * scale_ratio)))
class Region(object):
"""
A rectangle identified by left,top, width, height.
"""
__slots__ = ('left', 'top', 'width', 'height')
def __init__(self, left=0, top=0, width=0, height=0):
# type: (float, float, float, float) -> None
self.left = int(round(left))
self.top = int(round(top))
self.width = int(round(width))
self.height = int(round(height))
def __getstate__(self):
return OrderedDict([("top", self.top), ("left", self.left), ("width", self.width),
("height", self.height)])
# Required is required in order for jsonpickle to work on this object.
# noinspection PyMethodMayBeStatic
def __setstate__(self, state):
raise EyesError('Cannot create Region instance from dict!')
@classmethod
def create_empty_region(cls):
return cls(0, 0, 0, 0)
@classmethod
def from_location_size(cls, location, size):
return cls(location.x, location.y, size.width, size.height)
@property
def x(self):
return self.left
@property
def y(self):
return self.top
@property
def right(self):
# type: () -> int
return self.left + self.width
@property
def bottom(self):
# type: () -> int
return self.top + self.height
@property
def location(self):
# type: () -> Point
"""Return the top-left corner as a Point."""
return Point(self.left, self.top)
@location.setter
def location(self, p):
# type: (Point) -> None
"""Sets the top left corner of the region"""
self.left, self.top = p.x, p.y
@property
def bottom_right(self):
# type: () -> Point
"""Return the bottom-right corner as a Point."""
return Point(self.right, self.bottom)
@property
def size(self):
# type: () -> ViewPort
"""
:return: The size of the region.
"""
return dict(width=self.width, height=self.height)
def clone(self):
# type: () -> Region
"""
Clone the rectangle.
:return: The new rectangle object.
"""
return Region(self.left, self.top, self.width, self.height)
def is_same(self, other):
# type: (Region) -> bool
"""
Checks whether the other rectangle has the same coordinates.
:param other: The other rectangle to check with.
:return: Whether or not the rectangles have same coordinates.
:rtype: bool
"""
return (self.left == other.left and self.top == other.top and self.width == other.width
and self.height == other.height)
def is_same_size(self, other):
# type: (Region) -> bool
"""
Checks whether the other rectangle is the same size.
:param other: The other rectangle to check with.
:return: Whether or not the rectangles are the same size.
"""
return self.width == other.width and self.height == other.height
def make_empty(self):
"""
Sets the current instance as an empty instance
"""
self.left = self.top = self.width = self.height = 0
def clip_negative_location(self):
"""
Sets the left/top values to 0 if the value is negative
"""
self.left = max(self.left, 0)
self.top = max(self.top, 0)
def is_size_empty(self):
# type: () -> bool
"""
:return: true if the region's size is 0, false otherwise.
"""
return self.width <= 0 or self.height <= 0
def is_empty(self):
# type: () -> bool
"""
Checks whether the rectangle is empty.
:return: True if the rectangle is empty. Otherwise False.
"""
return self.left == self.top == self.width == self.height == 0
def contains(self, pt):
# type: (Point) -> bool
"""
Return true if a point is inside the rectangle.
:return: True if the point is inside the rectangle. Otherwise False.
"""
x, y = pt.as_tuple()
return (self.left <= x <= self.right and # noqa
self.top <= y <= self.bottom)
def overlaps(self, other):
# type: (Region) -> bool
"""
Return true if a rectangle overlaps this rectangle.
"""
return ((self.left <= other.left <= self.right or other.left <= self.left <= other.right)
and (self.top <= other.top <= self.bottom or other.top <= self.top <= other.bottom))
def intersect(self, other):
# type: (Region) -> None
# If the regions don't overlap, the intersection is empty
if not self.overlaps(other):
self.make_empty()
return
intersection_left = self.left if self.left >= other.left else other.left
intersection_top = self.top if self.top >= other.top else other.top
intersection_right = self.right if self.right <= other.right else other.right
intersection_bottom = self.bottom if self.bottom <= other.bottom else other.bottom
self.left, self.top = intersection_left, intersection_top
self.width = intersection_right - intersection_left
self.height = intersection_bottom - intersection_top
def get_sub_regions(self, max_sub_region_size):
# type: (tp.Dict) -> tp.List[Region]
"""
Returns a list of Region objects which compose the current region.
"""
sub_regions = []
current_top = self.top
while current_top < self.height:
current_bottom = current_top + max_sub_region_size["height"]
if current_bottom > self.height:
current_bottom = self.height
current_left = self.left
while current_left < self.width:
current_right = current_left + max_sub_region_size["width"]
if current_right > self.width:
current_right = self.width
current_height = current_bottom - current_top
current_width = current_right - current_left
sub_regions.append(Region(current_left, current_top, current_width,
current_height))
current_left += max_sub_region_size["width"]
current_top += max_sub_region_size["height"]
return sub_regions
@property
def middle_offset(self):
# type: () -> Point
return Point(int(round(self.width / 2)), int(round(self.height / 2)))
def offset(self, dx, dy):
location = self.location.offset(dx, dy)
return Region(left=location.x, top=location.y,
width=self.size['width'],
height=self.size['height'])
def scale(self, scale_ratio):
return Region(
left=int(math.ceil(self.left * scale_ratio)),
top=int(math.ceil(self.top * scale_ratio)),
width=int(math.ceil(self.width * scale_ratio)),
height=int(math.ceil(self.height * scale_ratio))
)
def __repr__(self):
return "(%s, %s) %s x %s" % (self.left, self.top, self.width, self.height)
|
gepeng66666/frist_try
|
app/src/main/java/com/geekghost/gp/geekghost/frag/interfaces/ICommentView.java
|
package com.geekghost.gp.geekghost.frag.interfaces;
import com.geekghost.gp.geekghost.entity.CommentListBean;
import java.util.List;
/**
* 作者:戈鹏
* on 2018/1/2 21:49
*/
public interface ICommentView {
void onCommentSuccess(List<CommentListBean> commentList);
void onCommentFailed(Exception e);
}
|
ioio-creative/web-canvas
|
Example/threejs/threejs-demos/js/autumn-scene.js
|
<reponame>ioio-creative/web-canvas<gh_stars>0
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? undefined : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Demo wrapper
var AutumnScene = function( ) {
// CONSTANTS
var CAMERA_NEAR = .1
, CAMERA_FAR = 5000
, DPR = window.devicePixelRatio || 1
, SCENE_FILE = 'autumn-scene-prep3.dae'
, BACKGROUND_COLOR = 0x85ada6
, ROTATION_RATE = 10;
// PRIVATE PROPERTIES
var self = this;
// PUBLIC PROPERTIES
this.camera;
this.composer;
this.container;
this.controls;
this.renderer;
this.scene;
this.tick = 0;
// private variables
var clock = new THREE.Clock(true);
// PRIVATE METHODS
// initialization function, runs on instantiation
function setup() {
// create a container element
self.container = document.createElement( 'div' );
self.container.id = "threejs";
document.body.appendChild( self.container );
// create a Three.js scene
self.scene = new THREE.Scene();
// create and add a camera to our scene
self.camera = new THREE.PerspectiveCamera( 28, window.innerWidth / window.innerHeight, CAMERA_NEAR, CAMERA_FAR );
self.camera.position.z = 10;
self.camera.position.y = -30;
self.scene.add(self.camera);
// create a renderer and set up for retina
self.renderer = new THREE.WebGLRenderer({
devicePixelRatio: DPR
});
self.renderer.setClearColor( BACKGROUND_COLOR );
self.scene.fog = new THREE.FogExp2(BACKGROUND_COLOR, .0125);
// Probably deprecated
if(typeof(self.renderer.setPixelRatio) !== "undefined") {
self.renderer.setPixelRatio( DPR );
}
self.renderer.setSize( window.innerWidth, window.innerHeight );
// add our renderer element to our container
self.container.appendChild( self.renderer.domElement );
// setup THREE trackball controls
self.controls = new THREE.TrackballControls( self.camera, self.container );
self.controls.rotateSpeed = 1.0;
self.controls.zoomSpeed = 2.2;
self.controls.panSpeed = .3;
self.controls.dynamicDampingFactor = 0.3;
}
function init() {
// setup a boilerplate threejs scene
setup();
var loader = new THREE.ColladaLoader();
loader.load( './models/' + SCENE_FILE, function ( collada ) {
for(var i = 0; i < collada.scene.children.length; i++) {
var child = collada.scene.children[i];
if( child.name === "Ground" ) {
child.children[0].material = new THREE.MeshBasicMaterial( { side: THREE.DoubleSide, map: THREE.ImageUtils.loadTexture("./models/autumn-scene.jpg") })
self.tree = child;
self.scene.add(child);
}
}
requestAnimationFrame( update );
} );
}
// runs once per frame
var update = function() {
// get the elapsed time for the project
var delta = 0;
delta = clock.getDelta();
self.tick += delta;
if( delta > 0 ) {
}
self.tree.rotation.z += (ROTATION_RATE * delta) * Math.PI / 180;
var zoom = ( 1. - ( self.camera.position.z / 80. ) ) * 5.;
zoom = Math.max( 0.15, Math.min( 5., zoom ) );
// update controls
self.controls.update();
// rinse and repeat
self.renderer.render( self.scene, self.camera );
requestAnimationFrame(update);
}
// INIT
// initialize on load
init();
}
var demo = new AutumnScene();
|
Light-Wizzard/QtLingo
|
doc/html/build-QtLingoTest-Desktop-Debug_2moc__MainWindow_8cpp.js
|
var build_QtLingoTest_Desktop_Debug_2moc__MainWindow_8cpp =
[
[ "qt_meta_stringdata_MainWindow_t", "structqt__meta__stringdata__MainWindow__t.html", "structqt__meta__stringdata__MainWindow__t" ],
[ "QT_MOC_LITERAL", "build-QtLingoTest-Desktop-Debug_2moc__MainWindow_8cpp.html#a75bb9482d242cde0a06c9dbdc6b83abe", null ]
];
|
lucmoreau/OpenProvenanceModel
|
opm/src/main/java/org/openprovenance/model/Normalise.java
|
package org.openprovenance.model;
import java.util.List;
import java.util.LinkedList;
import java.util.Collection;
import java.util.Collections;
import javax.xml.bind.JAXBElement;
import java.util.Comparator;
public class Normalise {
OPMFactory oFactory;
public Normalise(OPMFactory oFactory) {
this.oFactory=oFactory;
}
public void sortGraph(OPMGraph graph) {
graph.setAnnotations(oFactory.getObjectFactory().createAnnotations());
sortById((List)graph.getAccounts().getAccount());
if (graph.getProcesses()!=null && graph.getProcesses().getProcess()!=null) {
sortById((List)graph.getProcesses().getProcess());
for (Process p: graph.getProcesses().getProcess()) {
sortAnnotations(p.getAnnotation());
sortByRef(p.getAccount());
}
}
if (graph.getArtifacts()!=null && graph.getArtifacts().getArtifact()!=null) {
sortById((List)graph.getArtifacts().getArtifact());
for (Artifact a: graph.getArtifacts().getArtifact()) {
sortAnnotations(a.getAnnotation());
sortByRef(a.getAccount());
}
}
if (graph.getAgents()!=null && graph.getAgents().getAgent()!=null) {
sortById((List)graph.getAgents().getAgent());
for (Agent a: graph.getAgents().getAgent()) {
sortAnnotations(a.getAnnotation());
sortByRef(a.getAccount());
}
}
for (Object e: graph.getDependencies().getUsedOrWasGeneratedByOrWasTriggeredBy()) {
sortAnnotations(((Edge)e).getAnnotation());
sortByRef(((Edge)e).getAccount());
}
sortEdges(graph.getDependencies().getUsedOrWasGeneratedByOrWasTriggeredBy());
}
public void updateFromRdfGraph(OPMGraph graph) {
IndexedOPMGraph igraph=new IndexedOPMGraph(oFactory,graph);
List<Account> accs=graph.getAccounts().getAccount();
for (Account acc: accs) {
if (acc.getId().equals("_null")) {
accs.remove(acc);
break;
}
}
Collection<Account> green=Collections.singleton(igraph.getAccount("green"));
Collection<Account> orange=Collections.singleton(igraph.getAccount("orange"));
List<Account> green_orange=new LinkedList();
green_orange.addAll(green);
green_orange.addAll(orange);
Overlaps ov1=oFactory.newOverlaps(green_orange);
graph.getAccounts().getOverlaps().add(ov1);
}
public void noAnnotation(OPMGraph graph) {
graph.setAnnotations(null);
destroy(graph.getAnnotation());
if (graph.getProcesses()!=null && graph.getProcesses().getProcess()!=null) {
for (Process p: graph.getProcesses().getProcess()) {
destroy(p.getAnnotation());
}
}
if (graph.getArtifacts()!=null && graph.getArtifacts().getArtifact()!=null) {
for (Artifact a: graph.getArtifacts().getArtifact()) {
destroy(a.getAnnotation());
}
}
if (graph.getAgents()!=null && graph.getAgents().getAgent()!=null) {
for (Agent a: graph.getAgents().getAgent()) {
destroy(a.getAnnotation());
}
}
for (Object e: graph.getDependencies().getUsedOrWasGeneratedByOrWasTriggeredBy()) {
destroy(((Edge)e).getAnnotation());
}
}
public void embedExternalAnnotations(OPMGraph graph) {
IndexedOPMGraph igraph=new IndexedOPMGraph(oFactory,graph);
// embed external annotations
if (graph.getAnnotations()!=null) {
List<Annotation> anns=graph.getAnnotations().getAnnotation();
for (Annotation ann: anns) {
String id=(((Identifiable)ann.getLocalSubject()).getId());
EmbeddedAnnotation embedded=oFactory.newEmbeddedAnnotation(ann.getId(),
ann.getProperty(),
ann.getAccount(),
null);
Process p=igraph.getProcess(id);
if (p!=null) {
p.getAnnotation().add(oFactory.compactAnnotation(embedded));
} else {
Artifact a=igraph.getArtifact(id);
if (a!=null) {
a.getAnnotation().add(oFactory.compactAnnotation(embedded));
} else {
Agent ag=igraph.getAgent(id);
if (ag!=null) {
ag.getAnnotation().add(oFactory.compactAnnotation(embedded));
}
}
}
}
graph.setAnnotations(null);
}
}
public void updateOriginalGraph(OPMGraph graph) {
embedExternalAnnotations(graph);
if (graph.getProcesses()!=null && graph.getProcesses().getProcess()!=null) {
for (Process p: graph.getProcesses().getProcess()) {
List<AccountRef> accRefs=p.getAccount();
destroy(accRefs); //rdf does not have accounts in nodes
}
}
if (graph.getArtifacts()!=null && graph.getArtifacts().getArtifact()!=null) {
for (Artifact a: graph.getArtifacts().getArtifact()) {
List<AccountRef> accRefs=a.getAccount();
destroy(accRefs); //rdf does not have accounts in nodes
}
}
if (graph.getAgents()!=null && graph.getAgents().getAgent()!=null) {
for (Agent a: graph.getAgents().getAgent()) {
List<AccountRef> accRefs=a.getAccount();
destroy(accRefs); //rdf does not have accounts in nodes
}
}
for (Object e: graph.getDependencies().getUsedOrWasGeneratedByOrWasTriggeredBy()) {
((Identifiable)e).setId(null); // tupelo rdf does not allow ids in edges
// my translation does not support annotations on roles
if (e instanceof WasGeneratedBy) {
WasGeneratedBy wgb=(WasGeneratedBy) e;
wgb.getRole().setId(null);
}
if (e instanceof Used) {
Used u=(Used) e;
u.getRole().setId(null);
}
if (e instanceof WasControlledBy) {
WasControlledBy wcb=(WasControlledBy) e;
wcb.getRole().setId(null);
}
}
}
public void sortById(List ll) {
Collections.sort(ll,
new Comparator() {
public int compare(Object o1, Object o2) {
Identifiable i1=(Identifiable) o1;
Identifiable i2=(Identifiable) o2;
return i1.getId().compareTo(i2.getId());
}
public boolean equals_IGNORE(Object o1, Object o2) {
Identifiable i1=(Identifiable) o1;
Identifiable i2=(Identifiable) o2;
return (i1.getId().equals(i2.getId()));
}
});
}
public void sortByRef(List ll) {
Collections.sort(ll,
new Comparator() {
public int compare(Object o1, Object o2) {
Identifiable i1=(Identifiable) ((Ref) o1).getRef();
Identifiable i2=(Identifiable) ((Ref) o2).getRef();
return i1.getId().compareTo(i2.getId());
}
});
}
public void sortEdges(List ll) {
Collections.sort(ll,
new Comparator() {
public int compare(Object o1, Object o2) {
Edge e1=(Edge) o1;
Edge e2=(Edge) o2;
String id1_1=((Identifiable)(e1.getCause().getRef())).getId();
String id1_2=((Identifiable)(e1.getEffect().getRef())).getId();
String s1=id1_1+id1_2;
String id2_1=((Identifiable)(e2.getCause().getRef())).getId();
String id2_2=((Identifiable)(e2.getEffect().getRef())).getId();
String s2=id2_1+id2_2;
return s1.compareTo(s2);
}
});
}
public void sortAnnotations(List<JAXBElement<? extends EmbeddedAnnotation>> ll) {
Collections.sort(ll,
new Comparator() {
public int compare(Object o1, Object o2) {
JAXBElement j1=(JAXBElement) o1;
JAXBElement j2=(JAXBElement) o2;
EmbeddedAnnotation a1=(EmbeddedAnnotation) j1.getValue();
EmbeddedAnnotation a2=(EmbeddedAnnotation) j2.getValue();
if (a1.getId()==null) {
if (a2.getId()==null) {
return a1.getClass().getName().compareTo(a2.getClass().getName());
} else {
return -1;
}
} else {
if (a2.getId()==null) {
return +1;
} else {
return a1.getId().compareTo(a2.getId());
}
}
}});
for (JAXBElement je: ll) {
EmbeddedAnnotation a=(EmbeddedAnnotation) je.getValue();
sortProperties(a.getProperty());
sortByRef(a.getAccount());
}
}
public void sortProperties(List<Property> ll) {
// TODO: when keys are identical, i should sort by values too
Collections.sort(ll,
new Comparator() {
public int compare(Object o1, Object o2) {
Property p1=(Property) o1;
Property p2=(Property) o2;
return p1.getKey().compareTo(p2.getKey());
}});
}
public void sortAccounts(List<Account> ll) {
// TODO: when keys are identical, i should sort by values too
Collections.sort(ll,
new Comparator() {
public int compare(Object o1, Object o2) {
Account acc1=(Account) o1;
Account acc2=(Account) o2;
return acc1.getId().compareTo(acc2.getId());
}});
}
public void destroy(List ll) {
for (int i=ll.size()-1; i>=0; i--) {
ll.remove(ll.get(i));
}
}
public void sortAnnotationsIGNORE(List<EmbeddedAnnotation> ll) {
Collections.sort(ll,
new Comparator() {
public int compare(Object o1, Object o2) {
EmbeddedAnnotation a1=(EmbeddedAnnotation) o1;
EmbeddedAnnotation a2=(EmbeddedAnnotation) o2;
if (a1.getId()==null) {
if (a2.getId()==null) {
return a1.getClass().getName().compareTo(a2.getClass().getName());
} else {
return -1;
}
} else {
if (a2.getId()==null) {
return +1;
} else {
return a1.getId().compareTo(a2.getId());
}
}
}});
}
}
|
sentinelweb/microserver
|
microserver-java/src/main/java/uk/co/sentinelweb/microserver/server/MultiCastListener.java
|
<reponame>sentinelweb/microserver
package uk.co.sentinelweb.microserver.server;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.HashMap;
public class MultiCastListener extends Thread {
String ip = C.MULTICAST_IP_DEF;
int port = C.MULTICAST_PORT_DEF;
String _localIp = null;
boolean _keepGoing = true;
MulticastSocket _theSocket = null;
int _webPort = C.SERVERPORT_DEF;
InetAddress _broadcastAddress;
OnAsyncListener _recieveListener;
Gson gson;
public MultiCastListener(final String multiCastIp, final String localIp, final int port, final int webPort) {
super("MultiCastListener");
this.ip = multiCastIp;
this.port = port;
_localIp = localIp;
this._webPort = webPort;
final GsonBuilder gsonb = new GsonBuilder();
gson = gsonb.create();
}
@Override
public void run() {
try {
_broadcastAddress = InetAddress.getByName(ip);
_theSocket = new MulticastSocket(port);
_theSocket.joinGroup(_broadcastAddress);
sendBroadcast();
final byte[] buffer = new byte[10 * 1024];
final DatagramPacket data1 = new DatagramPacket(buffer, buffer.length);
System.out.println("multi start: addr:" + _broadcastAddress);
while (_keepGoing) {
_theSocket.receive(data1);
final String msg = new String(buffer, 0, data1.getLength(), "utf-8");
System.out.println("multi Received: " + msg);
if (_recieveListener != null) {
_recieveListener.onAsync(msg);
}
}
} catch (final IOException e) {
System.err.println(e.toString());
e.printStackTrace(System.err);
}
System.err.println(this.getClass().getCanonicalName() + " :: exit");
}
public void sendBroadcast() {
if (_theSocket != null && !_theSocket.isClosed()) {
try {
final HashMap<String, String> closeMsg = new HashMap<>();
closeMsg.put("join", _localIp + ":" + _webPort);
final String closeMsgStr = gson.toJson(closeMsg);
final DatagramPacket data = new DatagramPacket(closeMsgStr.getBytes(), closeMsgStr.length(), _broadcastAddress, port);
_theSocket.send(data);
System.out.println("sendBroadcast .. done");
} catch (final Exception e) {
System.err.println(this.getClass().getCanonicalName() + "sendBroadcast err");
e.printStackTrace(System.err);
}
}
}
public OnAsyncListener getRecieveListener() {
return _recieveListener;
}
public void setRecieveListener(final OnAsyncListener _recieveListener) {
this._recieveListener = _recieveListener;
}
public interface OnAsyncListener {
public void onAsync(String s);
}
public boolean isKeepGoing() {
return _keepGoing;
}
public void setKeepGoing(final boolean keepGoing) {
this._keepGoing = keepGoing;
}
public void close() {
this._keepGoing = false;
if (_theSocket != null && !_theSocket.isClosed()) {
// TODO note we might need to send a local exit message to stop blocking ...
new Thread("MultiCastClose") {
@Override
public void run() {
try {
final InetAddress group = InetAddress.getByName(ip);
// send exit message
final HashMap<String, String> closeMsg = new HashMap<>();
closeMsg.put("close", _localIp);
final String closeMsgStr = gson.toJson(closeMsg);
final DatagramPacket data = new DatagramPacket(closeMsgStr.getBytes(), closeMsgStr.length(), group, port);
_theSocket.send(data);
System.out.println(this.getClass().getCanonicalName() + "multi closing: send lastcall");
final InetAddress local = InetAddress.getByName("localhost");
final DatagramPacket data1 = new DatagramPacket("".getBytes(), 0, local, port);
_theSocket.send(data1);
System.out.println(this.getClass().getCanonicalName() + "multi closing: ");
_theSocket.close();
} catch (final Exception e) {
System.err.println(this.getClass().getCanonicalName() + "multi close ex: ");
e.printStackTrace(System.err);
}
}
}.start();
}
}
}
|
lpxz/grail-derby104
|
java/storeless/org/apache/derby/impl/storeless/NoOpTransaction.java
|
/*
Derby - Class org.apache.impl.storeless.NoOpTransaction
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.impl.storeless;
import java.io.Serializable;
import java.util.Properties;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.services.io.FormatableBitSet;
import org.apache.derby.iapi.services.io.Storable;
import org.apache.derby.iapi.services.locks.CompatibilitySpace;
import org.apache.derby.iapi.store.access.AccessFactory;
import org.apache.derby.iapi.store.access.BackingStoreHashtable;
import org.apache.derby.iapi.store.access.ColumnOrdering;
import org.apache.derby.iapi.store.access.ConglomerateController;
import org.apache.derby.iapi.store.access.DatabaseInstant;
import org.apache.derby.iapi.store.access.DynamicCompiledOpenConglomInfo;
import org.apache.derby.iapi.store.access.FileResource;
import org.apache.derby.iapi.store.access.GroupFetchScanController;
import org.apache.derby.iapi.store.access.Qualifier;
import org.apache.derby.iapi.store.access.RowLocationRetRowSource;
import org.apache.derby.iapi.store.access.ScanController;
import org.apache.derby.iapi.store.access.SortController;
import org.apache.derby.iapi.store.access.SortCostController;
import org.apache.derby.iapi.store.access.SortObserver;
import org.apache.derby.iapi.store.access.StaticCompiledOpenConglomInfo;
import org.apache.derby.iapi.store.access.StoreCostController;
import org.apache.derby.iapi.store.access.TransactionController;
import org.apache.derby.iapi.store.raw.Loggable;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.iapi.types.DataValueFactory;
/**
* A TransactionController that does nothing.
* This allows the existing transaction aware language
* code to remain unchanged while not supporting transactions
* for the storeless engine.
*/
class NoOpTransaction implements TransactionController {
public AccessFactory getAccessManager() {
// TODO Auto-generated method stub
return null;
}
public boolean conglomerateExists(long conglomId) throws StandardException {
// TODO Auto-generated method stub
return false;
}
public long createConglomerate(String implementation,
DataValueDescriptor[] template, ColumnOrdering[] columnOrder,
int[] collation_ids,
Properties properties, int temporaryFlag) throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public long createAndLoadConglomerate(String implementation,
DataValueDescriptor[] template, ColumnOrdering[] columnOrder,
int[] collation_ids,
Properties properties, int temporaryFlag,
RowLocationRetRowSource rowSource, long[] rowCount)
throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public long recreateAndLoadConglomerate(String implementation,
boolean recreate_ifempty, DataValueDescriptor[] template,
ColumnOrdering[] columnOrder,
int[] collation_ids,
Properties properties,
int temporaryFlag, long orig_conglomId,
RowLocationRetRowSource rowSource, long[] rowCount)
throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public void addColumnToConglomerate(long conglomId, int column_id,
Storable template_column, int collation_id) throws StandardException {
// TODO Auto-generated method stub
}
public void dropConglomerate(long conglomId) throws StandardException {
// TODO Auto-generated method stub
}
public long findConglomid(long containerid) throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public long findContainerid(long conglomid) throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public TransactionController startNestedUserTransaction(boolean readOnly)
throws StandardException {
return this;
}
public Properties getUserCreateConglomPropList() {
// TODO Auto-generated method stub
return null;
}
public ConglomerateController openConglomerate(long conglomId,
boolean hold, int open_mode, int lock_level, int isolation_level)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public ConglomerateController openCompiledConglomerate(boolean hold,
int open_mode, int lock_level, int isolation_level,
StaticCompiledOpenConglomInfo static_info,
DynamicCompiledOpenConglomInfo dynamic_info)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public BackingStoreHashtable createBackingStoreHashtableFromScan(
long conglomId, int open_mode, int lock_level, int isolation_level,
FormatableBitSet scanColumnList,
DataValueDescriptor[] startKeyValue, int startSearchOperator,
Qualifier[][] qualifier, DataValueDescriptor[] stopKeyValue,
int stopSearchOperator, long max_rowcnt, int[] key_column_numbers,
boolean remove_duplicates, long estimated_rowcnt,
long max_inmemory_rowcnt, int initialCapacity, float loadFactor,
boolean collect_runtimestats, boolean skipNullKeyColumns,
boolean keepAfterCommit)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public ScanController openScan(long conglomId, boolean hold, int open_mode,
int lock_level, int isolation_level,
FormatableBitSet scanColumnList,
DataValueDescriptor[] startKeyValue, int startSearchOperator,
Qualifier[][] qualifier, DataValueDescriptor[] stopKeyValue,
int stopSearchOperator) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public ScanController openCompiledScan(boolean hold, int open_mode,
int lock_level, int isolation_level,
FormatableBitSet scanColumnList,
DataValueDescriptor[] startKeyValue, int startSearchOperator,
Qualifier[][] qualifier, DataValueDescriptor[] stopKeyValue,
int stopSearchOperator, StaticCompiledOpenConglomInfo static_info,
DynamicCompiledOpenConglomInfo dynamic_info)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public GroupFetchScanController openGroupFetchScan(long conglomId,
boolean hold, int open_mode, int lock_level, int isolation_level,
FormatableBitSet scanColumnList,
DataValueDescriptor[] startKeyValue, int startSearchOperator,
Qualifier[][] qualifier, DataValueDescriptor[] stopKeyValue,
int stopSearchOperator) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public GroupFetchScanController defragmentConglomerate(long conglomId,
boolean online, boolean hold, int open_mode, int lock_level,
int isolation_level) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public void purgeConglomerate(long conglomId) throws StandardException {
// TODO Auto-generated method stub
}
public void compressConglomerate(long conglomId) throws StandardException {
// TODO Auto-generated method stub
}
public boolean fetchMaxOnBtree(long conglomId, int open_mode,
int lock_level, int isolation_level,
FormatableBitSet scanColumnList, DataValueDescriptor[] fetchRow)
throws StandardException {
// TODO Auto-generated method stub
return false;
}
public StoreCostController openStoreCost(long conglomId)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public int countOpens(int which_to_count) throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public String debugOpened() throws StandardException {
// TODO Auto-generated method stub
return null;
}
public FileResource getFileHandler() {
// TODO Auto-generated method stub
return null;
}
public CompatibilitySpace getLockSpace() {
// TODO Auto-generated method stub
return null;
}
public StaticCompiledOpenConglomInfo getStaticCompiledConglomInfo(
long conglomId) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public DynamicCompiledOpenConglomInfo getDynamicCompiledConglomInfo(
long conglomId) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public long[] getCacheStats(String cacheName) {
// TODO Auto-generated method stub
return null;
}
public void resetCacheStats(String cacheName) {
// TODO Auto-generated method stub
}
public void logAndDo(Loggable operation) throws StandardException {
// TODO Auto-generated method stub
}
public long createSort(Properties implParameters,
DataValueDescriptor[] template, ColumnOrdering[] columnOrdering,
SortObserver sortObserver, boolean alreadyInOrder,
long estimatedRows, int estimatedRowSize) throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public void dropSort(long sortid) throws StandardException {
// TODO Auto-generated method stub
}
public SortController openSort(long id) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public SortCostController openSortCostController(Properties implParameters)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public RowLocationRetRowSource openSortRowSource(long id)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public ScanController openSortScan(long id, boolean hold)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public boolean anyoneBlocked() {
// TODO Auto-generated method stub
return false;
}
public void abort() throws StandardException {
// TODO Auto-generated method stub
}
public void commit() throws StandardException {
// TODO Auto-generated method stub
}
public DatabaseInstant commitNoSync(int commitflag)
throws StandardException {
// TODO Auto-generated method stub
return null;
}
public void destroy() {
// TODO Auto-generated method stub
}
public ContextManager getContextManager() {
// TODO Auto-generated method stub
return null;
}
public String getTransactionIdString() {
// TODO Auto-generated method stub
return null;
}
public String getActiveStateTxIdString() {
// TODO Auto-generated method stub
return null;
}
public boolean isIdle() {
// TODO Auto-generated method stub
return false;
}
public boolean isGlobal() {
// TODO Auto-generated method stub
return false;
}
public boolean isPristine() {
// TODO Auto-generated method stub
return false;
}
public int releaseSavePoint(String name, Object kindOfSavepoint)
throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public int rollbackToSavePoint(String name, boolean close_controllers,
Object kindOfSavepoint) throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public int setSavePoint(String name, Object kindOfSavepoint)
throws StandardException {
// TODO Auto-generated method stub
return 0;
}
public Object createXATransactionFromLocalTransaction(int format_id,
byte[] global_id, byte[] branch_id) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public Serializable getProperty(String key) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public Serializable getPropertyDefault(String key) throws StandardException {
// TODO Auto-generated method stub
return null;
}
public boolean propertyDefaultIsVisible(String key)
throws StandardException {
// TODO Auto-generated method stub
return false;
}
public void setProperty(String key, Serializable value,
boolean dbOnlyProperty) throws StandardException {
// TODO Auto-generated method stub
}
public void setPropertyDefault(String key, Serializable value)
throws StandardException {
// TODO Auto-generated method stub
}
public Properties getProperties() throws StandardException {
// TODO Auto-generated method stub
return null;
}
public DataValueFactory getDataValueFactory() throws StandardException {
// TODO Auto-generated method stub
return(null);
}
public void setNoLockWait(boolean noWait) {
// TODO Auto-generated method stub
}
}
|
seanrowens/ACCAST
|
AirSim/Machinetta/CostMaps/TiledCostMap.java
|
/*******************************************************************************
* Copyright (C) 2017, <NAME>, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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.
******************************************************************************/
/*
* TiledCostMap.java
*
* Created on April 26, 2006, 5:01 PM
*
*/
package AirSim.Machinetta.CostMaps;
import java.awt.Rectangle;
import java.io.Serializable;
import java.util.ArrayList;
/**
*
* @author pscerri
*/
public class TiledCostMap implements CostMap, Serializable {
private ArrayList<Rectangle> best = new ArrayList<Rectangle>(), worst = new ArrayList<Rectangle>();
private int noBest = 10, noWorst = 10;
private int dx, dy;
private double [][] costs = null;
/** Creates a new instance of TiledCostMap */
public TiledCostMap(int width, int height, int dx, int dy) {
this.dx = dx;
this.dy = dy;
costs = new double[(int)Math.ceil(width/dx)][(int)Math.ceil(height/dy)];
}
/**
* Sets the value of the tile containing the point (x,y)
*/
public void setValue(int x, int y, double val) {
costs[(int)Math.floor(x/dx)][(int)Math.floor(y/dy)] = val;
}
/**
* Not implemented yet.
*/
public ArrayList<Rectangle> getBadAreas(long t) {
return worst;
}
/**
* Not implemented yet.
*/
public ArrayList<Rectangle> getGoodAreas(long t) {
return best;
}
public double getCost(double x1, double y1, double z1, long t1, double x2, double y2, double z2, long t2) {
double cost = 0.0;
if (x1 > x2) {
double temp = x2;
x2 = x1;
x1 = temp;
}
if (y1 > y2) {
double temp = y2;
y2 = y1;
y1 = temp;
}
double steps = 10;
double ldx = (x2-x1)/steps;
double ldy = (y2-y1)/steps;
int px = -1;
int py = -1;
for (int i = 0; i < steps; i++) {
x1 += ldx; y1 += ldy;
int x = (int)Math.floor(x1/dx);
int y = (int)Math.floor(y1/dy);
if (!(x == px && y == py)) {
cost += costs[x][y];
}
px = x; py = y;
}
return cost;
}
public double getCost(double x1, double y1, long t1, double x2, double y2, long t2) {
return getCost(x1, y1, 0, t1, x2, y2, 0, t2);
}
public void timeElapsed(long t) {
// this is static, do nothing
}
}
|
Piterski72/git_test
|
chapter_001/src/main/java/ru/nivanov/DuplicMass.java
|
package ru.nivanov;
/**
* Programm finds duplicates in massive and creates new one with no copies.
* @author nivanov.
*/
class DuplicMass {
/**
*/
private final String[] symbols;
public DuplicMass(String[] psymbols) {
this.symbols = psymbols;
}
/**
* copyRemover.
* @return String[] result
*/
public String[] copyRemover() {
int max = symbols.length;
int count = 0;
// finding copies and converting to nulls
for (int i = 0; i < max - 1; i++) {
if (symbols[i].equals("")) {
count++;
}
for (int j = i + 1; j < max; j++) {
if (symbols[i].equals(symbols[j])) {
symbols[j] = "";
}
}
}
//moving nulls to the end of massive
String tmp = "";
for (int i = max - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (!symbols[max - j - 1].equals("") && symbols[max - j - 2].equals("")) {
tmp = symbols[max - j - 2];
symbols[max - j - 2] = symbols[max - j - 1];
symbols[max - j - 1] = tmp;
}
}
}
// creating new massive, cutting copies
String[] result = new String[symbols.length - count];
for (int i = 0; i < result.length; i++) {
result[i] = symbols[i];
}
return result;
}
}
|
Petkr/PPreflection
|
PPreflection/types/types.hpp
|
<reponame>Petkr/PPreflection
#pragma once
#include "types.h"
#include "arithmetic_type.hpp"
#include "arithmetic_type_strong.hpp"
#include "array_type.hpp"
#include "class_type.hpp"
#include "cv_type.hpp"
#include "enum_type.hpp"
#include "function_type.hpp"
#include "known_bound_array_type.hpp"
#include "non_array_object_type.hpp"
#include "non_user_defined_type.hpp"
#include "pointer_to_member_type.hpp"
#include "pointer_type.hpp"
#include "reference_type.hpp"
#include "type.hpp"
#include "unknown_bound_array_type.hpp"
|
JFixby/Rana
|
rana-loader-api/src/com/jfixby/rana/api/loader/PackageInfo.java
|
<reponame>JFixby/Rana<gh_stars>0
package com.jfixby.rana.api.loader;
import com.jfixby.rana.api.format.PackageFormat;
import com.jfixby.scarabei.api.assets.ID;
import com.jfixby.scarabei.api.collections.Collection;
public class PackageInfo {
public String packageName;
public PackageFormat packageFormat;
public Collection<ID> packedAssets;
public Collection<ID> dependencies;
}
|
twsearle/atlas
|
src/atlas/mesh/actions/ExtendNodesGlobal.cc
|
/*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#include "atlas/mesh/actions/ExtendNodesGlobal.h"
#include "atlas/array.h"
#include "atlas/field/Field.h"
#include "atlas/grid/Grid.h"
#include "atlas/grid/Iterator.h"
#include "atlas/mesh/Mesh.h"
#include "atlas/mesh/Nodes.h"
#include "atlas/runtime/Exception.h"
#include "atlas/util/CoordinateEnums.h"
#include "atlas/util/Earth.h"
namespace atlas {
namespace mesh {
namespace actions {
ExtendNodesGlobal::ExtendNodesGlobal(const std::string& gridname): gridname_(gridname) {}
void ExtendNodesGlobal::operator()(const Grid& grid, Mesh& mesh) const {
if (grid.domain().global()) {
return; // don't add virtual points to global domains
}
Grid O16("O16");
// virtual points
std::vector<PointXY> extended_pts;
extended_pts.reserve(grid.size());
// loop over the point and keep the ones that *don't* fall in the domain
for (const PointLonLat& lonlat : O16.lonlat()) {
PointXY xy = grid.projection().xy(lonlat);
if (not grid.domain().contains(xy)) {
extended_pts.push_back(xy);
}
}
mesh::Nodes& nodes = mesh.nodes();
const idx_t nb_real_pts = nodes.size();
const idx_t nb_extension_pts = extended_pts.size();
idx_t new_size = nodes.size() + extended_pts.size();
nodes.resize(new_size); // resizes the fields
const idx_t nb_total_pts = nodes.size();
ATLAS_ASSERT(nb_total_pts == nb_real_pts + nb_extension_pts);
nodes.metadata().set<idx_t>("NbRealPts", nb_real_pts);
nodes.metadata().set<idx_t>("NbVirtualPts", nb_extension_pts);
array::ArrayView<double, 2> xyz = array::make_view<double, 2>(nodes.field("xyz"));
array::ArrayView<double, 2> xy = array::make_view<double, 2>(nodes.xy());
array::ArrayView<double, 2> lonlat = array::make_view<double, 2>(nodes.lonlat());
array::ArrayView<gidx_t, 1> gidx = array::make_view<gidx_t, 1>(nodes.global_index());
for (idx_t i = 0; i < nb_extension_pts; ++i) {
const idx_t n = nb_real_pts + i;
const PointLonLat pLL = grid.projection().lonlat(extended_pts[i]);
PointXYZ pXYZ;
util::Earth::convertSphericalToCartesian(pLL, pXYZ);
xyz(n, XX) = pXYZ.x();
xyz(n, YY) = pXYZ.y();
xyz(n, ZZ) = pXYZ.z();
xy(n, XX) = extended_pts[i].x();
xy(n, YY) = extended_pts[i].y();
lonlat(n, LON) = pLL.lon();
lonlat(n, LAT) = pLL.lat();
gidx(n) = n + 1;
}
}
} // namespace actions
} // namespace mesh
} // namespace atlas
|
ChineseTony/javaDataStruct
|
src/main/java/com/tom/array/MakeConnected.java
|
<filename>src/main/java/com/tom/array/MakeConnected.java
package com.tom.array;
import com.tom.unionfind.UnionFind;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author tom
*/
public class MakeConnected {
public static int makeConnected(int n, int[][] connections) {
if (connections.length < n -1){
return -1;
}
UF uf = new UF(n);
for (int i = 0; i < connections.length; i++) {
uf.unionElement(connections[i][0],connections[i][1]);
}
return uf.getSize()-1;
}
public static void main(String[] args) {
int n = 6;
int[][] nums = new int[][]{
{0,1},{0,2},{0,3},{1,2},{2,4}};
System.out.println(makeConnected(n,nums));
}
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) {
return new ArrayList<>();
}
Map<String,List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char[] c = strs[i].toCharArray();
Arrays.sort(c);
String key =new String(c);
if (map.containsKey(key)) {
map.get(key).add(strs[i]);
}else {
List<String> tmp = new ArrayList<>();
tmp.add(strs[i]);
map.put(key,tmp);
}
}
List<List<String>> result = new ArrayList<>();
for(Map.Entry<String,List<String>> entry:map.entrySet()){
result.add(entry.getValue());
}
return result;
}
private String getKey(String s){
if (s == null || s.length() <= 0){
return s;
}
char[] chars = new char[26];
for (char c:s.toCharArray()){
chars[c -'a']++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 26; i++) {
sb.append(chars[i]);
}
return sb.toString();
}
static class UF implements UnionFind{
private int[] parent;
private int len;
public UF(int len) {
this.len = len;
parent = new int[len];
for (int i = 0; i < len; i++) {
//每一个元素 的根节点指向自己
parent[i] = i;
}
}
@Override
public int getSize() {
return len;
}
@Override
public boolean isConnect(int p, int q) {
int pParent = getParent(p);
int qParent = getParent(q);
return pParent == qParent;
}
@Override
public void unionElement(int p, int q) {
int pParent = getParent(p);
int qParent = getParent(q);
if (pParent == qParent){
return;
}
parent[pParent] = qParent;
len--;
}
private int getParent(int p){
if (p < 0 || p >= parent.length){
throw new RuntimeException("p index error");
}
while (parent[p] != p){
p = parent[p];
}
return p;
}
}
}
|
markusstraub/java-playground
|
src/main/java/com/github/mstraub/performance/PerformanceTester.java
|
package com.github.mstraub.performance;
//package performance;
//
//import java.io.File;
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.ResultSet;
//import java.sql.SQLException;
//import java.sql.Statement;
//import java.util.Vector;
//
//public class PerformanceTester {
//
// private void runTests(Vector<TestCase> testCases, int iterations) {
// long start, duration;
// for(TestCase tc : testCases) {
// System.out.println("========================");
// System.out.println(tc.getClass().getName() + ": START");
// start = System.currentTimeMillis();
// tc.prepareTest();
// duration = System.currentTimeMillis() - start;
// System.out.println(tc.getClass().getName()
// + ": preparation finished in " + duration + "ms");
//
// start = System.currentTimeMillis();
// tc.conductTest(iterations);
// duration = System.currentTimeMillis() - start;
// System.out.println(tc.getClass().getName() + ": " + iterations
// + " iterations of Test 1 finished in " + duration + "ms");
//
// start = System.currentTimeMillis();
// tc.conductTest2(iterations);
// duration = System.currentTimeMillis() - start;
// System.out.println(tc.getClass().getName() + ": " + iterations
// + " iterations of Test 2 finished in " + duration + "ms");
//
// start = System.currentTimeMillis();
// tc.conductTest3(iterations);
// duration = System.currentTimeMillis() - start;
// System.out.println(tc.getClass().getName() + ": " + iterations
// + " iterations of Test 3 finished in " + duration + "ms");
//
// start = System.currentTimeMillis();
// tc.conductTest4(iterations);
// duration = System.currentTimeMillis() - start;
// System.out.println(tc.getClass().getName() + ": " + iterations
// + " iterations of Test 4 finished in " + duration + "ms");
// }
// }
//
// private String[] getTrafficStates(File sqliteFile) {
// Vector<String> trafficSits = new Vector<String>();
//
// try {
// Class.forName("org.sqlite.JDBC");
//
//
// Connection conn = DriverManager.getConnection("jdbc:sqlite:"+sqliteFile.getAbsolutePath());
// Statement stmt = conn.createStatement();
// ResultSet rs = null;
//
// // copy data
// String trafficSitQuery = "SELECT DISTINCT(TrafficSit) FROM emissions";
// rs = stmt.executeQuery(trafficSitQuery);
//
// while(rs.next())
// trafficSits.add(rs.getString(1));
//
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException e) {
// e.printStackTrace();
// }
//
// return trafficSits.toArray(new String[1]);
// }
//
//
// public static void main(String[] args) {
// PerformanceTester pt = new PerformanceTester();
//
// String path = "/home/mstraub/projects/ilos/svn/trunk/java/indicator2/resources/emissions/";
//
// String[] trafficStates = pt.getTrafficStates(new File(path + "emissions.sqlite"));
//
// EmissionDataSqliteTestCase sql =
// new EmissionDataSqliteTestCase(path + "emissions.sqlite", trafficStates);
// EmissionDataSqliteInMemoryTestCase sqlInMemory =
// new EmissionDataSqliteInMemoryTestCase(path + "emissions.sqlite", trafficStates);
// EmissionDataCSVTestCase csvHashmap =
// new EmissionDataCSVTestCase(path + "emissions.csv", true);
// EmissionDataCSVTestCase csv =
// new EmissionDataCSVTestCase(path + "emissions.csv", false);
//
// Vector<TestCase> testCases = new Vector<TestCase>();
// testCases.add(sql); // db must be indexed on trafficSit, subsegment (otherwise it's superslow)
//// testCases.add(sqlInMemory);
//// testCases.add(csv);
//// testCases.add(csvHashmap);
// pt.runTests(testCases, 50);
// }
//}
|
AiLovesAi/Nimble-Engine
|
docs/NimbleLibrary/html/search/all_1.js
|
var searchData=
[
['argc_5',['argc',['../_nimble_engine_8h.html#a3337a5ceb7d556a05c8ee774ce054d5e',1,'NimbleEngine.h']]]
];
|
vsobolmaven/tavutil
|
tavutil/test_paypalx.py
|
<reponame>vsobolmaven/tavutil<gh_stars>0
# Public Domain (-) 2010-2011 The Tavutil Authors.
# See the Tavutil UNLICENSE file for details.
from __future__ import absolute_import
from tavutil.paypalx import AdaptivePayment, PayRequest
from config import (
PPX_API_USERNAME, PPX_API_PASSWORD,
PPX_API_SIGNATURE, PPX_APP_ID
)
api_credentials = {'api_username': PPX_API_USERNAME,
'api_password': <PASSWORD>,
'api_signature': PPX_API_SIGNATURE,
'app_id': PPX_APP_ID}
adaptpay = AdaptivePayment(**api_credentials)
pay_request_kwargs = {
'receiver_email': '<EMAIL>',
'receiver_amount': 20.00, 'currency_code': 'GBP',
'cancel_url': 'http://www.ebay.com',
'return_url': 'http://www.sandbox.paypal.com'
}
payreq = PayRequest(**pay_request_kwargs)
payreqmsg = payreq.get_message()
#pp_response = adaptpay.call("PAY", payreqmsg)
|
jlprieur/jlplib
|
jlp_gsegraf/jlp_gsegraf_axes/jlp_GsegAxes_Setup.cpp
|
/******************************************************************************
* jlp_Gsegraf_Setup.cpp
* JLP_GsegAxes class
*
* JLP
* Version 01/04/2017
******************************************************************************/
#include <stdlib.h> // exit()
#include <math.h>
#include <time.h>
#include "jlp_gseg_axes.h"
/***************************************************************************
* Check axis type
*
***************************************************************************/
int JLP_GsegAxes::CheckAxesParameters()
{
int status = 0;
char error_str0[80], *pchar;
/* Check axis_type parameter */
if ( strcmp(p_plot_param->axis_type, "linear") != 0 &&
strcmp(p_plot_param->axis_type, "semilogx") != 0 &&
strcmp(p_plot_param->axis_type, "semilogy") != 0 &&
strcmp(p_plot_param->axis_type, "loglog") != 0 &&
strcmp(p_plot_param->axis_type, "polar") != 0 &&
strcmp(p_plot_param->axis_type, "3d") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid or missing axis_type parameter: axis_type=%s",
p_plot_param->axis_type);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check axis_scale parameter */
if ( strcmp(p_plot_param->axis_scale, "auto") != 0 &&
strcmp(p_plot_param->axis_scale, "equal") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid axis_scale parameter: axis_scale=%s",
p_plot_param->axis_scale);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check grid parameters */
if ( strcmp(p_plot_param->grid, "on1") != 0 &&
strcmp(p_plot_param->grid, "on2") != 0 &&
strcmp(p_plot_param->grid, "off") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid grid parameter: grid=%s",
p_plot_param->grid);
JLP_ErrorDialog(error_str0);
status = -1;
}
// Decodes grid color using color_string (i.e., "kaswrylqbfmogtnpx")
if ( strcmp(p_plot_param->grid, "on1") == 0 )
{
if ( (gridchar1 != 'l' && gridchar1 != 'd' && gridchar1 != '.') ||
(pchar = strchr(color_string, gridchar2)) == NULL )
{
sprintf(error_str0, "CheckAxesParameters/Invalid grid parameter: grid=%s and gridchar1,2 = (%c + %c)",
p_plot_param->grid, gridchar1, gridchar2);
JLP_ErrorDialog(error_str0);
status = -1;
}
}
else if ( strcmp(p_plot_param->grid, "on2") == 0 )
{
if ( gridchar1 != 'l' && gridchar1 != 'd' )
{
sprintf(error_str0, "CheckAxesParameters/Invalid grid parameter: grid=%s and gridchar1 = %c",
p_plot_param->grid, gridchar1);
JLP_ErrorDialog(error_str0);
status = -1;
}
}
/* Check view-direction angles for 3d plots */
if ( strcmp(p_plot_param->axis_type, "3d") == 0 )
if ( p_plot_param_3d->theta < 0.0 ||
p_plot_param_3d->theta > 90.0 )
{
sprintf(error_str0, "CheckAxesParameters/View-direction elevation angle out of range: theta=%f",
p_plot_param_3d->theta);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check plot_box parameter */
if ( strcmp(p_plot_param->plot_box, "on") != 0 &&
strcmp(p_plot_param->plot_box, "off") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid plot_box parameter: plotbox=%s",
p_plot_param->plot_box);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check x_tick_marks parameter */
if ( strcmp(p_plot_param->x_tick_marks, "on") != 0 &&
strcmp(p_plot_param->x_tick_marks, "off") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid x_tick_marks parameter: x_tick_marks = %s",
p_plot_param->x_tick_marks);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check y_tick_marks parameter */
if ( strcmp(p_plot_param->y_tick_marks, "on") != 0 &&
strcmp(p_plot_param->y_tick_marks, "off") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid y_tick_marks parameter: y_tick_marks = %s",
p_plot_param->y_tick_marks);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check z_tick_marks parameter */
if ( strcmp(p_plot_param->z_tick_marks, "on") != 0 &&
strcmp(p_plot_param->z_tick_marks, "off") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid z_tick_marks parameter: z_tick_marks = %s",
p_plot_param->z_tick_marks);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check x_tick_labels parameter */
if ( strcmp(p_plot_param->x_tick_labels, "on") != 0 &&
strcmp(p_plot_param->x_tick_labels, "off") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid x_tick_labels parameter: x_tick_labels = %s",
p_plot_param->x_tick_labels);
JLP_ErrorDialog(error_str0);
exit(1);
}
/* Check y_tick_labels parameter */
if ( strcmp(p_plot_param->y_tick_labels, "on") != 0 &&
strcmp(p_plot_param->y_tick_labels, "off") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid y_tick_labels parameter: y_tick_labels = %s",
p_plot_param->y_tick_labels);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check z_tick_labels parameter */
if ( strcmp(p_plot_param->z_tick_labels, "on") != 0 &&
strcmp(p_plot_param->z_tick_labels, "off") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid z_tick_labels parameter: z_tick_labels = %s",
p_plot_param->z_tick_labels);
JLP_ErrorDialog(error_str0);
status = -1;
}
/* Check date_time parameter */
if ( strcmp(p_plot_param->date_time_anchor, "off") != 0 &&
strcmp(p_plot_param->date_time_anchor, "north") != 0 &&
strcmp(p_plot_param->date_time_anchor, "northeast") != 0 &&
strcmp(p_plot_param->date_time_anchor, "southeast") != 0 &&
strcmp(p_plot_param->date_time_anchor, "south") != 0 &&
strcmp(p_plot_param->date_time_anchor, "southwest") != 0 &&
strcmp(p_plot_param->date_time_anchor, "northwest") != 0 )
{
sprintf(error_str0, "CheckAxesParameters/Invalid date_time parameter: anchor=%s",
p_plot_param->date_time_anchor);
JLP_ErrorDialog(error_str0);
status = -1;
}
if(status == -1) exit(1);
return(status);
}
/***************************************************************************
* Set axis_type flags
*
***************************************************************************/
void JLP_GsegAxes::SetAxisTypeFlags(char *axis_type0)
{
strcpy(p_plot_param->axis_type, axis_type0);
flag_linear_1 = 0;
flag_logx_1 = 0;
flag_logy_1 = 0;
flag_loglog_1 = 0;
flag_polar_1 = 0;
flag_3d_1 = 0;
flag_2d_1 = 0;
flag_2d_rect_1 = 0;
if ( strcmp(axis_type0, "linear") == 0 )
flag_linear_1 = 1;
else if ( strcmp(axis_type0, "semilogx") == 0 )
flag_logx_1 = 1;
else if ( strcmp(axis_type0, "semilogy") == 0 )
flag_logy_1 = 1;
else if ( strcmp(axis_type0, "loglog") == 0 )
flag_loglog_1 = 1;
else if ( strcmp(axis_type0, "polar") == 0 )
flag_polar_1 = 1;
else if ( strcmp(axis_type0, "3d") == 0 )
flag_3d_1 = 1;
if ( flag_linear_1 == 1 ||
flag_logx_1 == 1 ||
flag_logy_1 == 1 ||
flag_loglog_1 == 1 ||
flag_polar_1 == 1 )
flag_2d_1 = 1;
if ( flag_linear_1 == 1 ||
flag_logx_1 == 1 ||
flag_logy_1 == 1 ||
flag_loglog_1 == 1 )
flag_2d_rect_1 = 1;
return;
}
/*****************************************************************************
* Set the axis limits in the same way as if it was read from the parameter file
*
*****************************************************************************/
void JLP_GsegAxes::SetPlotParamAxisLimits(double *axis_limits_0,
const int nlimits)
{
int i, set_axis_limits0[6];
if(nlimits != 6) {
fprintf(stderr, "SetAxisLimits/Error: nlimits should be equal to 6 !\n");
exit(-1);
}
// Will force to set those values by setting the following flags to one:
for(i = 0; i < 6; i++) {
set_axis_limits0[i] = 1;
}
// Update axis limits:
UpdateAxisLimitsAndReversedAxis(axis_limits_0, set_axis_limits0);
return;
}
/*****************************************************************************
* Turn local axis limits on/off
* if set_axis_limits=0, axis limits is turned off
* if set_axis_limits=1, axis limits is turned on
*****************************************************************************/
void JLP_GsegAxes::SetAxisLimitsOnOff(int *set_axis_limits_0,
const int nlimits)
{
int i;
if(nlimits != 6) {
fprintf(stderr, "SetAxisLimitsOnOff/Error: nlimits should be equal to 6 !\n");
exit(-1);
}
for(i = 0; i < 6; i++) set_axis_limits1[i] = set_axis_limits_0[i];
return;
}
/*****************************************************************************
* Get axis limits on/off flags
*****************************************************************************/
void JLP_GsegAxes::GetAxisLimitsOnOff(int *set_axis_limits_0,
const int nlimits)
{
int i;
if(nlimits != 6) {
fprintf(stderr, "SetAxisLimitsOnOff/Error: nlimits should be equal to 6 !\n");
exit(-1);
}
for(i = 0; i < 6; i++) set_axis_limits_0[i] = set_axis_limits1[i];
return;
}
/*****************************************************************************
*
*****************************************************************************/
void JLP_GsegAxes::SetTickOffsetLabels(const double xoffset1_0,
const double xoffset2_0,
const double yoffset1_0,
const double yoffset2_0,
const double zoffset1_0,
const double zoffset2_0)
{
p_ticklabels->xoffset1 = xoffset1_0;
p_ticklabels->xoffset2 = xoffset2_0;
p_ticklabels->yoffset1 = yoffset1_0;
p_ticklabels->yoffset2 = yoffset2_0;
p_ticklabels->zoffset1 = zoffset1_0;
p_ticklabels->zoffset2 = zoffset2_0;
return;
}
/*****************************************************************************
* Set plot settings back to their original values (stored as "refrence" values)
*
*****************************************************************************/
void JLP_GsegAxes::SetPlotSettingsToRefValues()
{
int i, nx, ny, nz;
if ( strcmp(p_plot_param->axis_type, "linear") == 0 ||
strcmp(p_plot_param->axis_type, "semilogx") == 0 ||
strcmp(p_plot_param->axis_type, "semilogy") == 0 ||
strcmp(p_plot_param->axis_type, "loglog") == 0 )
{
/* Get tick-mark reference values */
nx = p_ticklabels->nxvalues_ref;
ny = p_ticklabels->nyvalues_ref;
nz = p_ticklabels->nzvalues_ref;
p_ticklabels->nxvalues = nx;
p_ticklabels->nyvalues = ny;
p_ticklabels->nzvalues = nz;
for ( i=1; i<=nx; i++ )
p_ticklabels->xvalues[i-1] = p_ticklabels->xvalues_ref[i-1];
for ( i=1; i<=ny; i++ )
p_ticklabels->yvalues[i-1] = p_ticklabels->yvalues_ref[i-1];
for ( i=1; i<=nz; i++ )
p_ticklabels->zvalues[i-1] = p_ticklabels->zvalues_ref[i-1];
p_ticklabels->xoffset1 = p_ticklabels->xoffset1_ref;
p_ticklabels->xoffset2 = p_ticklabels->xoffset2_ref;
p_ticklabels->yoffset1 = p_ticklabels->yoffset1_ref;
p_ticklabels->yoffset2 = p_ticklabels->yoffset2_ref;
p_ticklabels->zoffset1 = p_ticklabels->zoffset1_ref;
p_ticklabels->zoffset2 = p_ticklabels->zoffset2_ref;
}
else if ( strcmp(p_plot_param->axis_type, "polar") == 0 )
{
/* Get tick-mark reference values */
ny = p_ticklabels->nyvalues_ref;
p_ticklabels->nyvalues = ny;
for ( i=1; i<=ny; i++ )
p_ticklabels->yvalues[i-1] = p_ticklabels->yvalues_ref[i-1];
p_ticklabels->yoffset1 = p_ticklabels->yoffset1_ref;
p_ticklabels->yoffset2 = p_ticklabels->yoffset2_ref;
}
else if ( strcmp(p_plot_param->axis_type, "3d") == 0 )
{
/* Get tick-mark reference values */
nx = p_ticklabels->nxvalues_ref;
ny = p_ticklabels->nyvalues_ref;
nz = p_ticklabels->nzvalues_ref;
p_ticklabels->nxvalues = nx;
p_ticklabels->nyvalues = ny;
p_ticklabels->nzvalues = nz;
for ( i=1; i<=nx; i++ )
p_ticklabels->xvalues[i-1] = p_ticklabels->xvalues_ref[i-1];
for ( i=1; i<=ny; i++ )
p_ticklabels->yvalues[i-1] = p_ticklabels->yvalues_ref[i-1];
for ( i=1; i<=nz; i++ )
p_ticklabels->zvalues[i-1] = p_ticklabels->zvalues_ref[i-1];
p_ticklabels->xoffset1 = p_ticklabels->xoffset1_ref;
p_ticklabels->xoffset2 = p_ticklabels->xoffset2_ref;
p_ticklabels->yoffset1 = p_ticklabels->yoffset1_ref;
p_ticklabels->yoffset2 = p_ticklabels->yoffset2_ref;
p_ticklabels->zoffset1 = p_ticklabels->zoffset1_ref;
p_ticklabels->zoffset2 = p_ticklabels->zoffset2_ref;
/* Get view-angle reference values */
p_plot_param_3d->phi = p_plot_param_3d->phi_ref;
p_plot_param_3d->theta = p_plot_param_3d->theta_ref;
}
return;
}
/*****************************************************************************
*
*****************************************************************************/
void JLP_GsegAxes::Set3DParams(const double phi_0, const double theta_0)
{
p_plot_param_3d->phi = phi_0;
p_plot_param_3d->theta = theta_0;
return;
}
/*****************************************************************************
* Compute plot-box device coordinates from current window size,
* and set them to the coordinates of the plot box four corners
*
* INPUT:
* p_plot_param : number of plots, etc
* plot_types : "color", "contour", etc
*
* OUTPUT:
* p_plot_box_data : xmin, xmax, ymin, ymax
*****************************************************************************/
void JLP_GsegAxes::SetPlotBoxDataLimitsFromWindowSize(void)
{
/* Declare variables */
int iplot, nplots0, flag, gseg_plot_type0;
int x0, y0, window_width0, window_height0;
// Size of window (from Gnome interface for instance)
jlp_gseg1->GSEG_GetWindowLimits(&x0, &window_width0, &y0, &window_height0);
/* Specify plot box screen coordinates */
jlp_gsegraf1->GSEG_get_nplots(&nplots0);
flag = 0;
if ( strcmp(p_plot_param->axis_type, "linear") == 0 )
for ( iplot = 1; iplot <= nplots0; iplot++ ) {
/* gseg_plot_type:
* 1="points"
* 2="histogram"
* 3="contour"
* 4="color"
* 5="mesh"
*************************/
jlp_gsegraf1->GSEG_get_plot_type(iplot, &gseg_plot_type0);
// 3="contour" or 4="color"
if((gseg_plot_type0 == 3) || (gseg_plot_type0 == 4)) {
flag = 1;
}
}
// flag = 0 (plot types: points or histogram)
if ( flag == 0 )
{
p_plot_box_data->xmin = 0.15625 * window_width0;
p_plot_box_data->xmax = 0.90625 * window_width0;
p_plot_box_data->ymin = 0.09375 * window_height0;
p_plot_box_data->ymax = 0.84375 * window_height0;
}
// flag == 1 (plot types: contour or color)
else
{
p_plot_box_data->xmin = 0.18750 * window_width0;
p_plot_box_data->xmax = 0.75000 * window_width0;
p_plot_box_data->ymin = 0.09375 * window_height0;
p_plot_box_data->ymax = 0.84375 * window_height0;
}
return;
}
/*****************************************************************************
* Set the device coordinates of the plot box four corners
*
*****************************************************************************/
void JLP_GsegAxes::SetPlotBoxDataLimits(const double dev_x1_box,
const double dev_x2_box,
const double dev_y1_box,
const double dev_y2_box)
{
p_plot_box_data->xmin = dev_x1_box;
p_plot_box_data->xmax = dev_x2_box;
p_plot_box_data->ymin = dev_y1_box;
p_plot_box_data->ymax = dev_y2_box;
}
/*****************************************************************************
* Set pixbufs for xlabel, ylabel, zlabel, and title
*****************************************************************************/
void JLP_GsegAxes::SetAxisLabelPixbufs(char *xlabel0, char *ylabel0,
char *zlabel0, char *title0,
double font_size_axis_labels0,
double font_size_title0,
const UINT32 color0)
{
strcpy(pixbuf_xlabel.text, xlabel0);
strcpy(pixbuf_xlabel.font_name, "font_axis_labels");
pixbuf_xlabel.font_size = font_size_axis_labels0;
pixbuf_xlabel.color = color0;
strcpy(pixbuf_ylabel.text, ylabel0);
strcpy(pixbuf_ylabel.font_name, "font_axis_labels");
pixbuf_ylabel.font_size = font_size_axis_labels0;
pixbuf_ylabel.color = color0;
strcpy(pixbuf_zlabel.text, zlabel0);
strcpy(pixbuf_zlabel.font_name, "font_axis_labels");
pixbuf_zlabel.font_size = font_size_axis_labels0;
pixbuf_zlabel.color = color0;
strcpy(pixbuf_title.text, title0);
strcpy(pixbuf_title.font_name, "font_axis_title");
pixbuf_title.font_size = font_size_title0;
pixbuf_title.color = color0;
return;
}
/*****************************************************************************
*
*****************************************************************************/
void JLP_GsegAxes::GetFontParams(char *font_name0, double *font_size_title0,
double *font_size_axis_labels0,
double *font_size_tick_labels0,
double *font_size_text0,
double *font_size_legend0,
double *font_size_date_time0)
{
// Get values from private variables:
strcpy(font_name0, font_name1);
*font_size_title0 = font_size_title1;
*font_size_axis_labels0 = font_size_axis_labels1;
*font_size_tick_labels0 = font_size_tick_labels1;
*font_size_text0 = font_size_text1;
*font_size_legend0 = font_size_legend1;
*font_size_date_time0 = font_size_date_time1;
return;
}
/*****************************************************************************
*
*****************************************************************************/
void JLP_GsegAxes::SetFontParams(char *font_name0, double font_size_title0,
double font_size_axis_labels0,
double font_size_tick_labels0,
double font_size_text0,
double font_size_legend0,
double font_size_date_time0)
{
// Save values to private variables:
strcpy(font_name1, font_name0);
font_size_title1 = font_size_title0;
font_size_axis_labels1 = font_size_axis_labels0;
font_size_tick_labels1 = font_size_tick_labels0;
font_size_text1 = font_size_text0;
font_size_legend1 = font_size_legend0;
font_size_date_time1 = font_size_date_time0;
return;
}
|
DICL/cassandra-driver
|
driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java
|
<reponame>DICL/cassandra-driver
/*
* Copyright (C) 2012-2015 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.driver.core.querybuilder;
import com.datastax.driver.core.CCMBridge;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.utils.CassandraVersion;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collection;
import static com.datastax.driver.core.Assertions.assertThat;
import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
@CassandraVersion(major = 2.1)
public class QueryBuilder21ExecutionTest extends CCMBridge.PerClassSingleNodeCluster {
@Override
protected Collection<String> getTableDefinitions() {
// Taken from http://www.datastax.com/dev/blog/cql-in-2-1
return Arrays.asList(
"CREATE TABLE products (id int PRIMARY KEY, description text, price int, categories set<text>, buyers list<int>, features_keys map<text, text>, features_values map<text, text>)",
"CREATE INDEX cat_index ON products(categories)",
"CREATE INDEX buyers_index ON products(buyers)",
"CREATE INDEX feat_index ON products(features_values)",
"CREATE INDEX feat_key_index ON products(KEYS(features_keys))",
"INSERT INTO products(id, description, price, categories, buyers, features_keys, features_values) " +
"VALUES (34134, '120-inch 1080p 3D plasma TV', 9999, {'tv', '3D', 'hdtv'}, [1], {'screen' : '120-inch', 'refresh-rate' : '400hz', 'techno' : 'plasma'}, {'screen' : '120-inch', 'refresh-rate' : '400hz', 'techno' : 'plasma'})",
"INSERT INTO products(id, description, price, categories, buyers, features_keys, features_values) " +
"VALUES (29412, '32-inch LED HDTV (black)', 929, {'tv', 'hdtv'}, [1,2,3], {'screen' : '32-inch', 'techno' : 'LED'}, {'screen' : '32-inch', 'techno' : 'LED'})",
"INSERT INTO products(id, description, price, categories, buyers, features_keys, features_values) " +
"VALUES (38471, '32-inch LCD TV', 110, {'tv', 'used'}, [2,4], {'screen' : '32-inch', 'techno' : 'LCD'}, {'screen' : '32-inch', 'techno' : 'LCD'})"
);
}
@Test(groups = "short")
public void should_handle_contains_on_set_with_index() {
PreparedStatement byCategory = session.prepare(select("id", "description", "categories")
.from("products")
.where(contains("categories", bindMarker("category"))));
ResultSet results = session.execute(byCategory.bind().setString("category", "hdtv"));
assertThat(results.getAvailableWithoutFetching()).isEqualTo(2);
for (Row row : results) {
assertThat(row.getSet("categories", String.class)).contains("hdtv");
}
}
@Test(groups = "short")
public void should_handle_contains_on_list_with_index() {
PreparedStatement byBuyer = session.prepare(select("id", "description", "buyers")
.from("products")
.where(contains("buyers", bindMarker("buyer"))));
ResultSet results = session.execute(byBuyer.bind().setInt("buyer", 4));
Row row = results.one();
assertThat(row).isNotNull();
assertThat(row.getInt("id")).isEqualTo(38471);
assertThat(row.getList("buyers", Integer.class)).contains(4);
}
@Test(groups = "short")
public void should_handle_contains_on_map_with_index() {
PreparedStatement byFeatures = session.prepare(select("id", "description", "features_values")
.from("products")
.where(contains("features_values", bindMarker("feature"))));
ResultSet results = session.execute(byFeatures.bind().setString("feature", "LED"));
Row row = results.one();
assertThat(row).isNotNull();
assertThat(row.getInt("id")).isEqualTo(29412);
assertThat(row.getMap("features_values", String.class, String.class)).containsEntry("techno", "LED");
}
@Test(groups = "short")
public void should_handle_contains_key_on_map_with_index() {
PreparedStatement byFeatures = session.prepare(select("id", "description", "features_keys")
.from("products")
.where(containsKey("features_keys", bindMarker("feature"))));
ResultSet results = session.execute(byFeatures.bind().setString("feature", "refresh-rate"));
Row row = results.one();
assertThat(row).isNotNull();
assertThat(row.getInt("id")).isEqualTo(34134);
assertThat(row.getMap("features_keys", String.class, String.class)).containsEntry("refresh-rate", "400hz");
}
}
|
carlosturnerbenites/rememberHelp
|
public/js/activities.js
|
<reponame>carlosturnerbenites/rememberHelp<filename>public/js/activities.js
var text = new Text(),
detailActivityActive = null,
voice = new Voice( response ),
buttonCaptureVoice = document.querySelector( '#buttonCaptureVoice' )
if ( buttonCaptureVoice ){
buttonCaptureVoice.addEventListener( 'mousedown', event => {
voice.listen()
this.addEventListener( 'mouseup', voice.listen )
} )
}
var answersAffirmation = [ 'si', 'sí', 'ya', 'efectivamente', 'evidentemente', 'sin duda' ],
answersNegation = [ 'no', 'nones', 'nanai', 'naranjas', 'quia', 'ca' ],
answers = answersAffirmation.concat( answersNegation )
function response ( resultText ){
if ( resultText ) {
if ( answers.indexOf( resultText ) < 0 ) {
text.toVoice( 'No respondiste la pregunta.' )
}else{
if ( answersAffirmation.indexOf( resultText ) >= 0 ) {
$.ajax( {
'type' : 'POST',
'url' : '/activities/valid-activity',
'contentType' : 'application/json',
'success' : ( response ) => {
if( response.err ) return text.toVoice( response.err )
var selector = '[data-id = "' + response.id +'"]',
reminder = $( selector ).find( '.reminder' )
reminder.attr( 'data-statereminder', response.classcss )
text.toVoice( response.message )
$( '#confirmActivityWindow' ).modal( 'hide' )
},
'data' : JSON.stringify( detailActivityActive )
} )
}else{
text.toVoice( 'No olvides hacerlo.' )
$( '#confirmActivityWindow' ).modal( 'hide' )
}
}
}else text.toVoice( 'No te entendi.' )
}
function RangeTolerance ( options ){
var developed = options.developed | false
var currentTime = new Date(),
date = options.date
date.setDate( currentTime.getDate() )
date.setFullYear( currentTime.getFullYear() )
date.setMonth( currentTime.getMonth() )
var lowerLimit = new Date( currentTime.setMinutes( currentTime.getMinutes() - options.tolerance ) ),
upperLimit = new Date( currentTime.setMinutes( currentTime.getMinutes() + options.tolerance*2 ) )
if ( !developed ){
if( date < lowerLimit ) return options.onBefore()
else if( date > upperLimit ) return options.onAfter()
else if ( date >= lowerLimit && date <= upperLimit ) return options.onDuring()
}else{
return options.onDuring()
}
}
$( '.activity' ).toArray().forEach( ( activity ) => {
var date = new Date( $( activity ).data( 'time' ) ),
dataDate = date.getHours() > 6 && date.getHours() < 18 ? { 'classcss' : 'morning' } : { 'classcss' : 'nigth' }
$( activity ).find( '[rol=time]' ).html( date.toHour12() )
$( activity ).find( '.date' ).addClass( dataDate.classcss )
$( activity ).click( confirmActivity )
} )
function confirmActivity () {
var reminder = this.querySelector( '[data-statereminder]' )
if ( reminder.dataset.statereminder != 'inprocess' ) return text.toVoice( 'Ya has completado esta actiidad.' )
RangeTolerance( {
'developed' : false,
'date' : new Date( this.dataset.date ),
'tolerance' : parseInt( this.dataset.tolerance ),
'onBefore' : () => {
text.toVoice( 'Vas un poco tarde.' )
registerActivity.bind( this )()
},
'onDuring' : registerActivity.bind( this ),
'onAfter' : () => text.toVoice( 'Aun no es hora de realizar esta actividad.' )
} )
}
function registerActivity (){
detailActivityActive = this.dataset
text.toVoice( this.dataset.speech )
$( '#confirmActivityWindow' ).modal( 'show' )
}
|
618lf/swak
|
swak-vertx/src/main/java/com/swak/vertx/security/handler/AdviceHandler.java
|
<filename>swak-vertx/src/main/java/com/swak/vertx/security/handler/AdviceHandler.java<gh_stars>1-10
package com.swak.vertx.security.handler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import com.swak.security.Subject;
import com.swak.vertx.security.Context;
/**
* 访问控制器
*
* @author: lifeng
* @date: 2020/3/29 20:35
*/
public abstract class AdviceHandler implements Handler {
/**
* 执行处理
*/
@Override
public CompletionStage<Boolean> handle(Context context, Subject subject, HandlerChain chain) {
return this.isAccessDenied(context, subject).thenCompose(allowed -> {
if (!allowed) {
return this.onAccessDenied(context, subject);
}
return CompletableFuture.completedFuture(true);
}).thenCompose(allowed -> {
if (allowed) {
return chain.doHandler(context, subject);
}
return CompletableFuture.completedFuture(false);
});
}
/**
* 是否继续执行
*
* @param context 请求上下文
* @param subject 用户主体
* @return 异步结果
*/
public CompletionStage<Boolean> isAccessDenied(Context context, Subject subject) {
return CompletableFuture.completedFuture(true);
}
/**
* 如果不继续执行则怎么处理
*
* @param context 请求上下文
* @param subject 用户主体
* @return 异步结果
*/
public CompletionStage<Boolean> onAccessDenied(Context context, Subject subject) {
return CompletableFuture.completedFuture(true);
}
}
|
danielflanigan/kid_readout
|
apps/data_analysis_scripts/custom_fix_atten_2015_06_hpd_pickle_sweep_noise_measurements.py
|
# Automatically associate sweeps with timestreams
import os
import time
import numpy as np
from kid_readout.measurement.io.readoutnc import ReadoutNetCDF
from kid_readout.analysis.noise_measurement import SweepNoiseMeasurement, save_noise_pkl
import cPickle
from kid_readout.roach.tools import ntone_power_correction
cryostats=dict(detectors='HPD',readout='StarCryo')
atten_map = {#"/data/detectors/2015-06-26_135847_dark.nc": [],
#"/data/detectors/2015-06-26_142600_dark.nc": [],
"/data/detectors/2015-06-26_151943_dark.nc": [40,30,20,10,0],
"/data/detectors/2015-06-26_154035_dark.nc": [40,30,20,10,0],
"/data/detectors/2015-06-26_171018_dark.nc": [40,30,20,10,0],
"/data/detectors/2015-06-26_173844_dark.nc": [40,30,20,10,0],
"/data/detectors/2015-06-26_180144_dark.nc": [40,30,20,10,0],
"/data/detectors/2015-06-26_182443_dark.nc": [40,30,20,10,0],
"/data/detectors/2015-06-26_222304_dark.nc": [40,30,20,10,0],
# "/data/detectors/2015-06-27_015155_dark.nc": [],
# "/data/detectors/2015-06-27_053941_dark.nc": [],
}
def find_closest_sweep(ts,sweeps):
start_epoch = ts.epoch.min()
# print "ts",time.ctime(start_epoch)
best_index = 0
for sweep_index in range(len(sweeps)):
# print sweep_index,time.ctime(sweeps[sweep_index].end_epoch)
if sweeps[sweep_index].end_epoch < start_epoch:
best_index = sweep_index
# print "found",best_index
return best_index
def extract_and_pickle(nc_filename):
basedir = os.path.split(nc_filename)[0] # should make this more robust, currently assumes all nc files are in top
# level of /data/<machine>/*.nc
machine = os.path.split(basedir)[1]
cryostat = cryostats[machine]
try:
print("Processing {}".format(nc_filename))
snms = []
rnc = ReadoutNetCDF(nc_filename)
for timestream_index,timestream in enumerate(rnc.timestreams):
if timestream.epoch.shape[0] == 0:
print "no timestreams in", nc_filename
return
start_epoch = timestream.epoch.min()
sweep_index = find_closest_sweep(timestream,rnc.sweeps)
sweep = rnc.sweeps[sweep_index]
sweep_epoch = sweep.end_epoch
resonator_indexes = np.array(list(set(sweep.index)))
resonator_indexes.sort()
print "%s: timestream[%d] at %s, associated sweep[%d] at %s, %d resonators" % (nc_filename,timestream_index,
time.ctime(start_epoch),
sweep_index,
time.ctime(sweep_epoch),
len(resonator_indexes))
for resonator_index in resonator_indexes:
snm = SweepNoiseMeasurement(rnc, sweep_group_index=sweep_index,
timestream_group_index=timestream_index,
resonator_index=resonator_index, cryostat=cryostat)
if nc_filename in atten_map:
atten = atten_map[nc_filename][timestream_index]
ntone_correction = ntone_power_correction(16)
print "overriding attenuation",atten
snm.atten = atten
snm.total_dac_atten = atten +ntone_correction
snm.power_dbm = snm.dac_chain_gain - snm.total_dac_atten
try:
snm.zbd_voltage = timestream.zbd_voltage[0]
except AttributeError:
pass
pkld = cPickle.dumps(snm,cPickle.HIGHEST_PROTOCOL)
del snm
snm = cPickle.loads(pkld)
snms.append(snm)
rnc.close()
pkl_filename = os.path.join(basedir,'pkl', os.path.splitext(os.path.split(nc_filename)[1])[0] + '.pkl')
save_noise_pkl(pkl_filename, snms)
print("Saved {}".format(pkl_filename))
except KeyboardInterrupt:
pass
except Exception as e:
print "failed on",nc_filename,e
if __name__ == '__main__':
import sys
from glob import glob
try:
threads = int(sys.argv[1])
filenames = atten_map.keys()
filenames.sort()
for arg in sys.argv[2:]:
filenames.extend(glob(arg))
except IndexError:
print("python pickle_sweep_noise_measurements.py <threads> <file patterns>")
sys.exit()
if threads == 1:
for filename in filenames:
extract_and_pickle(filename)
else:
import multiprocessing
pool = multiprocessing.Pool(threads)
pool.map(extract_and_pickle, filenames)
|
hispindia/BIHAR-2.7
|
dhis-2/dhis-services/dhis-service-importexport/src/main/java/org/hisp/dhis/importexport/dhis14/util/Dhis14ObjectMappingUtil.java
|
package org.hisp.dhis.importexport.dhis14.util;
/*
* Copyright (c) 2004-2012, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.HashMap;
import java.util.Map;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.period.DailyPeriodType;
import org.hisp.dhis.period.MonthlyPeriodType;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.period.QuarterlyPeriodType;
import org.hisp.dhis.period.SixMonthlyPeriodType;
import org.hisp.dhis.period.TwoYearlyPeriodType;
import org.hisp.dhis.period.WeeklyPeriodType;
import org.hisp.dhis.period.YearlyPeriodType;
/**
* @author <NAME>
* @version $Id: Dhis14ObjectMappingUtil.java 4699 2008-03-11 14:56:56Z larshelg $
*/
public class Dhis14ObjectMappingUtil
{
private static Map<Integer, PeriodType> periodTypeMap;
private static Map<Integer, String> dataElementTypeMap;
static
{
periodTypeMap = new HashMap<Integer, PeriodType>();
periodTypeMap.put( 1, new MonthlyPeriodType() );
periodTypeMap.put( 2, new QuarterlyPeriodType() );
periodTypeMap.put( 3, new YearlyPeriodType() );
periodTypeMap.put( 4, new MonthlyPeriodType() ); // Should be OnChange, which is un-supported
periodTypeMap.put( 5, new DailyPeriodType() ); // Should be Survey, which is un-supported
periodTypeMap.put( 6, new DailyPeriodType() );
periodTypeMap.put( 7, new WeeklyPeriodType() );
periodTypeMap.put( 8, new SixMonthlyPeriodType() );
periodTypeMap.put( 9, new TwoYearlyPeriodType() );
}
static
{
dataElementTypeMap = new HashMap<Integer, String>();
dataElementTypeMap.put( 1, DataElement.VALUE_TYPE_STRING ); // Should be Date
dataElementTypeMap.put( 2, DataElement.VALUE_TYPE_STRING );
dataElementTypeMap.put( 3, DataElement.VALUE_TYPE_INT );
dataElementTypeMap.put( 4, DataElement.VALUE_TYPE_STRING );
dataElementTypeMap.put( 5, DataElement.VALUE_TYPE_BOOL );
dataElementTypeMap.put( 6, DataElement.VALUE_TYPE_STRING ); // Should be Object
}
public static Map<Integer, PeriodType> getPeriodTypeMap()
{
return periodTypeMap;
}
public static Map<Integer, String> getDataElementTypeMap()
{
return dataElementTypeMap;
}
}
|
tabordasolutions/nics-common
|
entities/src/main/java/edu/mit/ll/nics/common/entity/IncidentIncidentType.java
|
<reponame>tabordasolutions/nics-common<filename>entities/src/main/java/edu/mit/ll/nics/common/entity/IncidentIncidentType.java
/**
* Copyright (c) 2008-2018, Massachusetts Institute of Technology (MIT)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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 edu.mit.ll.nics.common.entity;
// Generated Sep 30, 2011 1:24:44 PM by Hibernate Tools 3.4.0.CR1
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Proxy;
import org.json.JSONException;
import org.json.JSONObject;
/**
* IncidentIncidenttype generated by hbm2java
*/
@Entity
@Proxy(lazy=false)
@Table(name = "incident_incidenttype")
public class IncidentIncidentType extends SADisplayMessageEntity implements SADisplayPersistedEntity {
private int incidentIncidenttypeid;
private Incident incident;
private IncidentType incidentType;
private int incidenttypeid;
private int incidentid;
public IncidentIncidentType() {
}
public IncidentIncidentType(int incidentIncidenttypeid, Incident incident) {
this.incidentIncidenttypeid = incidentIncidenttypeid;
this.incident = incident;
}
public IncidentIncidentType(int incidentIncidenttypeid, Incident incident,
IncidentType incidenttype) {
this.incidentIncidenttypeid = incidentIncidenttypeid;
this.incident = incident;
this.incidentType = incidenttype;
}
@Id @GeneratedValue
@Column(name = "incident_incidenttypeid", unique = true, nullable = false)
public int getIncidentIncidenttypeid() {
return this.incidentIncidenttypeid;
}
public void setIncidentIncidenttypeid(int incidentIncidenttypeid) {
this.incidentIncidenttypeid = incidentIncidenttypeid;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "incidentid", nullable = false, insertable = false, updatable = false)
public Incident getIncident() {
return this.incident;
}
public void setIncident(Incident incident) {
this.incident = incident;
}
@Column(name = "incidentid", nullable = false)
public int getIncidentid() {
return this.incidentid;
}
public void setIncidentid(int incidentid) {
this.incidentid = incidentid;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "incidenttypeid", insertable = false, updatable = false)
public IncidentType getIncidentType() {
return this.incidentType;
}
public void setIncidentType(IncidentType incidenttype) {
this.incidentType = incidenttype;
}
@Column(name = "incidenttypeid")
public int getIncidenttypeid() {
return this.incidenttypeid;
}
public void setIncidenttypeid(int incidenttypeid) {
this.incidenttypeid = incidenttypeid;
}
//@Override // LDDRS-648 - Removing to get to compile
public JSONObject toJSONObject()
{
JSONObject json = new JSONObject();
try
{
json.put("incidentTypeId", this.incidenttypeid);
if(this.incidentType != null){
json.put("incidentTypeName", this.incidentType.getIncidentTypeName());
}
} catch (JSONException je)
{
Logger.getLogger(Incident.class.getSimpleName()).log(Level.SEVERE, null, je);
}
return json;
}
}
|
mateimicu/cloudbase-init-ci
|
argus/tests/cloud/smoke.py
|
# Copyright 2015 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import binascii
import operator
import os
import time
import unittest
# pylint: disable=import-error
from six.moves import urllib
from argus import config as argus_config
from argus import log as argus_log
from argus.tests import base
from argus.tests.cloud import util as test_util
from argus import util
DNSMASQ_NEUTRON = '/etc/neutron/dnsmasq-neutron.conf'
CONFIG = argus_config.CONFIG
LOG = argus_log.LOG
def _get_dhcp_value(key):
"""Get the value of an override from the dnsmasq-config file.
An override will be have the format 'dhcp-option-force=key,value'.
"""
lookup = "dhcp-option-force={}".format(key)
with open(DNSMASQ_NEUTRON) as stream:
for line in stream:
if not line.startswith(lookup):
continue
_, _, option_value = line.strip().partition("=")
_, _, value = option_value.partition(",")
return value.strip()
def _parse_ssh_public_keys(file_content):
"""Parses ssh-keys, so that the returned output has the right format."""
file_content = file_content.replace("\r\n", "")
ssh_keys = file_content.replace("ssh-rsa", "\nssh-rsa").strip()
return ssh_keys.splitlines()
class BaseTestPassword(base.BaseTestCase):
"""Base test class for testing that passwords were set properly."""
def _run_remote_command(self, cmd, password):
# Test that the proper password was set.
remote_client = self._backend.get_remote_client(
CONFIG.cloudbaseinit.created_user, password)
stdout = remote_client.run_command_verbose(
cmd, command_type=util.CMD)
return stdout
def is_password_set(self, password):
stdout = self._run_remote_command("echo 1", password)
self.assertEqual('1', stdout.strip())
class TestPasswordMetadataSmoke(BaseTestPassword):
"""Password test with a provided metadata password.
This should be used when the underlying metadata service does
not support password posting.
"""
def test_password_set_from_metadata(self):
metadata = self._backend.metadata
if metadata and metadata.get('admin_pass'):
password = metadata['admin_<PASSWORD>']
self.is_password_set(password)
else:
raise unittest.SkipTest("No metadata password")
class TestPasswordPostedSmoke(BaseTestPassword,
test_util.InstancePasswordMixin):
"""Test that the password was set and posted to the metadata service
This will attempt a WinRM login on the instance, which will use the
password which was correctly set by the underlying cloud
initialization software.
"""
@test_util.requires_service('http')
def test_password_set_posted(self):
self.is_password_set(password=self.password)
class TestPasswordPostedRescueSmoke(TestPasswordPostedSmoke):
"""Test that the password can be used in case of rescued instances."""
@test_util.requires_service('http')
def test_password_set_on_rescue(self):
password = self.password
stdout = self._run_remote_command("echo 1", password=password)
self.assertEqual('1', stdout.strip())
self._backend.rescue_server()
self._recipe.prepare()
self._backend.save_instance_output(suffix='rescue-1')
stdout = self._run_remote_command("echo 2", password=password)
self.assertEqual('2', stdout.strip())
self._backend.unrescue_server()
stdout = self._run_remote_command("echo 3", password=password)
self.assertEqual('3', stdout.strip())
class TestCloudstackUpdatePasswordSmoke(base.BaseTestCase):
"""Tests that the service can update passwords.
Test that the cloud initialization service can update passwords when
using the Cloudstack metadata service.
"""
@property
def service_url(self):
port = CONFIG.cloudstack_mock.password_server_port
return "http://%(host)s:%(port)s/" % {"host": "0.0.0.0",
"port": port}
@property
def password(self):
generated = binascii.hexlify(os.urandom(14)).decode()
return generated + "!*"
def _update_password(self, password):
url = urllib.parse.urljoin(self.service_url, 'password')
if password:
params = {'password': password}
else:
params = {}
data = urllib.parse.urlencode(params)
request = urllib.request.Request(url, data=data)
try:
response = urllib.request.urlopen(request)
except urllib.error.HTTPError as exc:
return exc.code
return response.getcode()
def _wait_for_service_status(self, status, retry_count=3,
retry_interval=1):
while retry_count:
response_status = None
retry_count -= 1
try:
response = urllib.request.urlopen(self.service_url)
response_status = response.getcode()
except urllib.error.HTTPError as error:
response_status = error.code
except urllib.error.URLError:
pass
if response_status == status:
return True
time.sleep(retry_interval)
return False
def _wait_for_completion(self, password):
remote_client = self._backend.get_remote_client(
CONFIG.cloudbaseinit.created_user, password)
remote_client.manager.wait_cbinit_service()
def _test_password(self, password, expected):
# Set the password in the Password Server.
response = self._update_password(password)
self.assertEqual(200, response)
# Reboot the instance.
self._backend.reboot_instance()
# Check if the password was set properly.
self._wait_for_completion(expected)
def test_update_password(self):
# Get the password from the metadata.
password = self._backend.metadata['admin_pass']
# Wait until the web service starts serving requests.
self.assertTrue(self._wait_for_service_status(status=400))
# Set a new password in Password Server and test if the
# plugin updates the password.
new_password = <PASSWORD>
self._test_password(password=<PASSWORD>, expected=new_password)
self._backend.save_instance_output(suffix="password-1")
# Remove the password from Password Server in order to check
# if the plugin keeps the last password.
self._test_password(password=<PASSWORD>, expected=new_password)
self._backend.save_instance_output(suffix="password-2")
# Change the password again and check if the plugin updates it.
self._test_password(password=password, expected=password)
self._backend.save_instance_output(suffix="password-3")
class TestCreatedUser(base.BaseTestCase):
"""Test that the user was created.
Test that the user created by the cloud initialization service
was actually created.
"""
def test_username_created(self):
# Verify that the expected created user exists.
exists = self._introspection.username_exists(
CONFIG.cloudbaseinit.created_user)
self.assertTrue(exists)
class TestSetTimezone(base.BaseTestCase):
"""Test that the expected timezone was set in the instance."""
def test_set_timezone(self):
# Verify that the instance timezone matches what we are
# expecting from it.
timezone = self._introspection.get_timezone()
self.assertEqual("Georgian Standard Time", timezone.strip())
class TestSetHostname(base.BaseTestCase):
"""Test that the expected hostname was set in the instance."""
def test_set_hostname(self):
# Verify that the instance hostname matches what we are
# expecting from it.
hostname = self._introspection.get_instance_hostname()
self.assertEqual("newhostname", hostname.strip())
class TestLongHostname(base.BaseTestCase):
def test_hostname_compatibility(self):
# Verify that the hostname is set accordingly
# when the netbios option is set to False
hostname = self._introspection.get_instance_hostname()
self.assertEqual("someverylonghostnametosetonthemachine-00", hostname)
class TestSwapEnabled(base.BaseTestCase):
"""Tests whether the instance has swap enabled."""
def test_swap_enabled(self):
"""Tests the swap status on the underlying instance."""
expected = r'?:\pagefile.sys'
swap_status = self._introspection.get_swap_status()
self.assertEqual(swap_status, expected)
class TestNoError(base.BaseTestCase):
"""Test class which verifies that no traceback occurs."""
def test_any_exception_occurred(self):
# Verify that any exception occurred in the instance
# for Cloudbase-Init.
instance_traceback = self._introspection.get_cloudbaseinit_traceback()
self.assertEqual('', instance_traceback)
class TestPowershellMultipartX86TxtExists(base.BaseTestCase):
"""Tests that the file powershell_multipart_x86.txt exists on 'C:'."""
def test_file_exists(self):
names = self._introspection.list_location("C:\\")
expected_files = ["powershell_multipart_x86.txt"]
for file_exists in expected_files:
self.assertIn(file_exists, names)
class TestUserdataFileExists(base.BaseTestCase):
"""Tests that the file userdatafile exists on 'C:'."""
@util.skip_on_os([util.WINDOWS_NANO], "OS Version not supported")
def test_userdatafile_exists(self):
names = self._introspection.list_location("C:\\")
expected_files = ["userdatafile"]
for file_exists in expected_files:
self.assertIn(file_exists, names)
# pylint: disable=abstract-method
class TestsBaseSmoke(TestCreatedUser,
TestPasswordPostedSmoke,
TestPasswordMetadataSmoke,
TestNoError,
base.BaseTestCase):
"""Various smoke tests for testing Cloudbase-Init."""
def test_disk_expanded(self):
# Test the disk expanded properly.
image = self._backend.get_image_by_ref()
if isinstance(image, dict) and 'image' in image:
image = image['image']
datastore_size = image['OS-EXT-IMG-SIZE:size']
disk_size = self._introspection.get_disk_size()
self.assertGreater(disk_size, datastore_size)
def test_hostname_set(self):
# Test that the hostname was properly set.
instance_hostname = self._introspection.get_instance_hostname()
server = self._backend.instance_server()
self.assertEqual(instance_hostname,
str(server['name'][:15]).lower())
@test_util.skip_unless_dnsmasq_configured
def test_ntp_properly_configured(self):
# Verify that the expected NTP peers are active.
peers = self._introspection.get_instance_ntp_peers()
expected_peers = _get_dhcp_value('42').split(",")
if expected_peers is None:
self.fail('DHCP NTP option was not configured.')
self.assertEqual(expected_peers, peers)
def test_sshpublickeys_set(self):
# Verify that we set the expected ssh keys.
authorized_keys = self._introspection.get_instance_keys_path()
public_keys = self._introspection.get_instance_file_content(
authorized_keys)
metadata_provider = self._recipe.metadata_provider
posted_pubkeys = metadata_provider.get_ssh_pubkeys().values()
self.assertEqual(set(posted_pubkeys),
set(_parse_ssh_public_keys(public_keys)))
def test_mtu(self):
# Verify that we have the expected MTU in the instance.
mtu = self._introspection.get_instance_mtu().mtu
expected_mtu = str(self._backend.get_mtu())
self.assertEqual(expected_mtu, mtu)
def test_user_belongs_to_group(self):
# Check that the created user belongs to the specified local groups
members = self._introspection.get_group_members(
CONFIG.cloudbaseinit.group)
self.assertIn(CONFIG.cloudbaseinit.created_user, members)
# pylint: disable=protected-access
def _is_serial_port_set(self):
"""Check if the option for serial port is set.
We look in both config objects to see if `logging_serial_port_settings`
is set.
:rtype: bool
"""
args = ("DEFAULT", "logging_serial_port_settings")
return (self._recipe._cbinit_conf.conf.has_option(*args) or
self._recipe._cbinit_unattend_conf.conf.has_option(*args))
def test_get_console_output(self):
# Verify that the product emits messages to the console output.
if not self._is_serial_port_set():
raise unittest.SkipTest(
"No `logging_serial_port_settings` was set for this Recipe.")
output = self._backend.instance_output()
self.assertTrue(output, "Console output was empty.")
class TestStaticNetwork(base.BaseTestCase):
"""Test that the static network was configured properly in instance."""
def test_static_network(self):
"""Check if the attached NICs were properly configured."""
# Get network adapter details within the guest compute node.
guest_nics = self._backend.get_network_interfaces()
# Get network adapter details within the instance.
instance_nics = self._introspection.get_network_interfaces()
guest_nics = [nic for nic in guest_nics if not nic["dhcp"]]
instance_nics = [nic for nic in instance_nics if not nic["dhcp"]]
# Sort by hardware address and compare results.
guest_nics.sort(key=operator.itemgetter('mac'))
instance_nics.sort(key=operator.itemgetter('mac'))
# Do not take into account v6 DNSes, because
# they aren't retrieved even when they are set.
for nics in (guest_nics, instance_nics):
for nic in nics:
nic["dns6"] = None
# If OS version < 6.2 then IPv6 configuration is not available
# so we need to remove all IPv6 related keys from the dictionaries
version = self._introspection.get_instance_os_version()
if version < (6, 2):
for nic in guest_nics:
for key in list(nic.keys()):
if key.endswith('6'):
del nic[key]
for nic in instance_nics:
for key in list(nic.keys()):
if key.endswith('6'):
del nic[key]
self.assertEqual(guest_nics, instance_nics)
class TestPublicKeys(base.BaseTestCase):
def test_public_keys(self):
# Check multiple ssh keys case.
authorized_keys = self._introspection.get_instance_keys_path()
public_keys = self._introspection.get_instance_file_content(
authorized_keys)
metadata_provider = self._recipe.metadata_provider
metadata_public_keys = metadata_provider.get_ssh_pubkeys().values()
self.assertEqual(set(metadata_public_keys),
set(_parse_ssh_public_keys(public_keys)))
|
zhoutao0712/rtn11pb1
|
release/src/router/iptables-1.4.x/include/linux/netfilter/xt_TCPOPTSTRIP.h
|
#ifndef _XT_TCPOPTSTRIP_H
#define _XT_TCPOPTSTRIP_H
#define tcpoptstrip_set_bit(bmap, idx) \
(bmap[(idx) >> 5] |= 1U << (idx & 31))
#define tcpoptstrip_test_bit(bmap, idx) \
(((1U << (idx & 31)) & bmap[(idx) >> 5]) != 0)
struct xt_tcpoptstrip_target_info {
__u32 strip_bmap[8];
};
#endif /* _XT_TCPOPTSTRIP_H */
|
somkiet073/ci-demos-dashbord
|
assets/DevExtreme/Demos/WidgetsGallery/Demos/Scheduler/WebAPIService/React/App.js
|
import React from 'react';
import Scheduler from 'devextreme-react/scheduler';
import * as AspNetData from 'devextreme-aspnet-data-nojquery';
const url = 'https://js.devexpress.com/Demos/Mvc/api/SchedulerData';
const dataSource = AspNetData.createStore({
key: 'AppointmentId',
loadUrl: `${url }/Get`,
insertUrl: `${url }/Post`,
updateUrl: `${url }/Put`,
deleteUrl: `${url }/Delete`,
onBeforeSend(_, ajaxOptions) {
ajaxOptions.xhrFields = { withCredentials: true };
}
});
const currentDate = new Date(2017, 4, 23);
const views = ['day', 'workWeek', 'month'];
class App extends React.Component {
render() {
return (
<Scheduler
dataSource={dataSource}
views={views}
defaultCurrentView="day"
defaultCurrentDate={currentDate}
height={600}
startDayHour={9}
endDayHour={19}
textExpr= "Text"
startDateExpr="StartDate"
endDateExpr="EndDate"
allDayExpr="AllDay" />
);
}
}
export default App;
|
bottomless-archive-project/library-of-alexandria
|
loa-application/loa-downloader-application/src/main/java/com/github/bottomlessarchive/loa/downloader/service/source/queue/DownloadQueueListener.java
|
package com.github.bottomlessarchive.loa.downloader.service.source.queue;
import com.github.bottomlessarchive.loa.downloader.service.document.DocumentLocationEvaluator;
import com.github.bottomlessarchive.loa.queue.service.QueueManipulator;
import com.github.bottomlessarchive.loa.queue.service.domain.Queue;
import com.github.bottomlessarchive.loa.downloader.service.document.DocumentLocationProcessor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(value = "loa.downloader.source", havingValue = "queue", matchIfMissing = true)
public class DownloadQueueListener implements CommandLineRunner {
private final QueueManipulator queueManipulator;
private final DocumentLocationProcessor documentLocationProcessor;
private final DownloaderQueueConsumer downloaderQueueConsumer;
private final DocumentLocationEvaluator documentLocationEvaluator;
@Override
public void run(final String... args) {
queueManipulator.silentlyInitializeQueue(Queue.DOCUMENT_LOCATION_QUEUE);
if (log.isInfoEnabled()) {
log.info("Initialized queue processing! There are {} messages available in the location queue!",
queueManipulator.getMessageCount(Queue.DOCUMENT_LOCATION_QUEUE));
}
queueManipulator.silentlyInitializeQueue(Queue.DOCUMENT_ARCHIVING_QUEUE);
if (log.isInfoEnabled()) {
log.info("Initialized queue processing! There are {} messages available in the archiving queue!",
queueManipulator.getMessageCount(Queue.DOCUMENT_ARCHIVING_QUEUE));
}
Flux.generate(downloaderQueueConsumer)
.publishOn(Schedulers.boundedElastic())
.flatMap(documentLocationEvaluator::evaluateDocumentLocation)
.flatMap(documentLocationProcessor::processDocumentLocation)
.subscribe();
}
}
|
ndlib/hydramaton
|
hydramata-core/spec/dummy/config/routes.rb
|
<reponame>ndlib/hydramaton
Rails.application.routes.draw do
mount Hydramata::Core::Engine => "/Core"
end
|
samuelbaizg/ssguan
|
ssguan/data/investors.py
|
<gh_stars>1-10
# -*- coding: utf-8 -*-
import datetime
import re
import time
import traceback
from ssguan import config
from ssguan.ignitor.web import webcli
from ssguan.ignitor.orm import properti
from ssguan.ignitor.utility import type, money
from ssguan.ignitor.orm.model import Model
class MoneyManStat(Model):
@classmethod
def meta_domain(cls):
return config.MODULE_MONEY
"""
统计周期
"""
start_time = properti.DateTimeProperty("startTime", required=True) # 统计开始时间
end_time = properti.DateTimeProperty("endTime", required=True, validator=[properti.UniqueValidator('end_time', scope=['start_time'])]) # 统计结束时间
"""
新增投资者数量
"""
mm_add_qty = properti.IntegerProperty("mmAddQty", required=True) # 新增投资者数量
np_add_qty = properti.IntegerProperty("npAddQty", required=True) # 新增自然人数量
nonp_add_qty = properti.IntegerProperty("NoNpAddQty", required=True) # 新增非自然人数量
"""
期末投资者数量
"""
mm_tmend_qty = properti.IntegerProperty("mmTmEndQty", required=True) # 期末投资者数量
np_tmend_qty = properti.IntegerProperty("npTmEndQty", required=True) # 期末自然人数量
np_tmend_a_qty = properti.IntegerProperty("npTmEndAQty", required=True) # 期末自然人数量(已开A股)
np_tmend_b_qty = properti.IntegerProperty("npTmEndQty", required=True) # 期末自然人数量(已开B股)
nonp_tmend_qty = properti.IntegerProperty("noNpTmEndQty", required=True) # 期末非自然人数量
nonp_tmend_a_qty = properti.IntegerProperty("noNpTmEndAQty", required=True) # 期末非自然人数量(已开A股)
nonp_tmend_b_qty = properti.IntegerProperty("noNpTmEndQty", required=True) # 期末非自然人数量(已开B股)
"""
期末持仓投资者数量
"""
mm_tmend_hold_qty = properti.IntegerProperty("mmTmEndHoldQty", required=True) # 期末持仓投资者数量
mm_tmend_hold_a_qty = properti.IntegerProperty("mmTmEndHoldAQty", required=True) # 期末持仓投资者数量(持有A股的投资者)
mm_tmend_hold_b_qty = properti.IntegerProperty("mmTmEndHoldBQty", required=True) # 期末持仓投资者数量(持有B股的投资者)
"""
期间参与交易的投资者数量
"""
mm_term_trade_qty = properti.IntegerProperty("mmTermTradeQty", required=True) # 期间参与交易的投资者数量
mm_term_trade_a_qty = properti.IntegerProperty("mmTermTradeAQty", required=True) # 期间参与交易的投资者数量(A股交易投资者)
mm_term_trade_b_qty = properti.IntegerProperty("mmTermTradeBQty", required=True) # 期间参与交易的投资者数量(B股交易投资者)
def new_mms(date):
mms = MoneyManStat()
def fetch_one(date):
datestr = type.datetime_to_str(date, fmt='%Y.%m.%d')
options = {}
options['method'] = 'POST'
options['data'] = {'dateType':'',
'dateStr':datestr,
'channelIdStr':'6ac54ce22db4474abc234d6edbe53ae7'}
response = webcli.http_fetch("http://www.chinaclear.cn/cms-search/view.action?action=china", options=options)
return response
def set_period(bs, mms):
h2 = bs.find('h2', attrs={'class':'fl'})
pat = re.compile(r"[\.]*([0-9.]*)-([0-9.]*)")
xx = pat.search(h2.string).groups()
st = type.str_to_datetime(xx[0], fmt='%Y.%m.%d')
et = type.str_to_datetime(xx[1], fmt='%Y.%m.%d')
mms.start_time = st
mms.end_time = et
return (st, et)
def set_qty(bs, mms):
row_delta = 0
table = bs.find('table', attrs={"style":"WIDTH: 100%; BORDER-COLLAPSE: collapse"})
if table is None:
table = bs.find('table', attrs={"style":"OVERFLOW-X: hidden; WORD-BREAK: break-all; WIDTH: 432pt"})
if table is None:
table = bs.find('table', attrs={"style":"width: 577px; border-collapse: collapse;"})
if table is None:
table = bs.find('table', attrs={"style":"width:100.0%;border-collapse:collapse;"})
if table is None:
table = bs.find('table', attrs={"style":"width: 100%; border-collapse: collapse;"})
if table is None:
table = bs.find('table', attrs={"style":"width: 432pt; word-break: break-all; overflow-x: hidden;"})
if table is None:
table = bs.find('table', attrs={"style":"width: 432pt; -ms-word-break: break-all; -ms-overflow-x: hidden;"})
if table is None:
table = bs.find('table', attrs={"style":"width: 599px; border-collapse: collapse;"})
trs = table.find_all('tr')
if trs[1 + row_delta].find_all('span')[-1].string == '投资者数(万)':
row_delta += 1
mms.mm_add_qty = money.kilostr_to_int(trs[1 + row_delta].find_all('span')[-1].string, times=10000)
# mms.np_add_qty = moneyutils.kilostr_to_int(trs[2+row_delta].find_all('span')[-1].string, times=10000)
# mms.nonp_add_qty = moneyutils.kilostr_to_int(trs[3+row_delta].find_all('span')[-1].string, times=10000)
# mms.mm_tmend_qty = moneyutils.kilostr_to_int(trs[4+row_delta].find_all('span')[-1].string, times=10000)
# mms.np_tmend_qty = moneyutils.kilostr_to_int(trs[5+row_delta].find_all('span')[-1].string, times=10000)
# mms.np_tmend_a_qty = moneyutils.kilostr_to_int(trs[7+row_delta].find_all('span')[-1].string, times=10000)
# mms.np_tmend_b_qty = moneyutils.kilostr_to_int(trs[8+row_delta].find_all('span')[-1].string, times=10000)
# mms.nonp_tmend_qty = moneyutils.kilostr_to_int(trs[9+row_delta].find_all('span')[-1].string, times=10000)
# mms.nonp_tmend_a_qty = moneyutils.kilostr_to_int(trs[11+row_delta].find_all('span')[-1].string, times=10000)
# mms.nonp_tmend_b_qty = moneyutils.kilostr_to_int(trs[12+row_delta].find_all('span')[-1].string, times=10000)
# if len(trs) >= 13+row_delta-1:
# mms.mm_tmend_hold_qty = moneyutils.kilostr_to_int(trs[13+row_delta].find_all('span')[-1].string, times=10000)
# mms.mm_tmend_hold_a_qty = moneyutils.kilostr_to_int(trs[15+row_delta].find_all('span')[-1].string, times=10000)
# mms.mm_tmend_hold_b_qty = moneyutils.kilostr_to_int(trs[16+row_delta].find_all('span')[-1].string, times=10000)
# mms.mm_term_trade_qty = moneyutils.kilostr_to_int(trs[17+row_delta].find_all('span')[-1].string, times=10000)
# mms.mm_term_trade_a_qty = moneyutils.kilostr_to_int(trs[19+row_delta].find_all('span')[-1].string, times=10000)
# mms.mm_term_trade_b_qty = moneyutils.kilostr_to_int(trs[20+row_delta].find_all('span')[-1].string, times=10000)
response = fetch_one(date)
bs = response.to_unibs()
set_period(bs, mms)
set_qty(bs, mms)
return mms
def fetch_all():
start_date = type.str_to_datetime('2015.01.06' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2015.09.21' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2017.02.06' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2017.05.08' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2016.04.25' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2016.07.04' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2016.08.15' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2016.10.10' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2016.10.24' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2017.01.23' , fmt='%Y.%m.%d')
# start_date = type.str_to_datetime('2016.12.09' , fmt='%Y.%m.%d')
start_date = type.str_to_datetime('2017.09.11' , fmt='%Y.%m.%d')
end_date = type.str_to_datetime('2017.10.01' , fmt='%Y.%m.%d')
mmses = []
while start_date <= end_date:
try:
time.sleep(0.2)
mms = new_mms(start_date)
mmses.append(mms)
start_date += datetime.timedelta(days=7)
except:
print (start_date)
traceback.print_exc()
start_date += datetime.timedelta(days=7)
print (len(mmses))
return mmses
mmses = fetch_all()
with open("d:/moneymans_original.csv", "w") as f:
f.writelines('start_date,end_date,moneymans\n')
for mms in mmses:
f.writelines("%s,%s,%i\n" % (type.datetime_to_str(mms.start_time, fmt='%Y-%m-%d'), type.datetime_to_str(mms.end_time, fmt='%Y-%m-%d'), mms.mm_add_qty))
f.close()
with open("d:/moneymans_dealed.csv", "w") as f:
f.writelines('start_date,moneymans\n')
for mms in mmses:
t = mms.end_time - mms.start_time + datetime.timedelta(days=1)
tmp = mms.start_time
while tmp <= mms.end_time:
avg = mms.mm_add_qty / t.days
f.writelines("%s,%.2f\n" % (type.datetime_to_str(tmp, fmt='%Y-%m-%d'), avg))
tmp += datetime.timedelta(days=1)
f.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.