text stringlengths 2 1.04M | meta dict |
|---|---|
using System;
namespace Qwack.Dates
{
public class TimePeriod
{
public TimeSpan Start { get; set; }
public TimeSpan End { get; set; }
}
}
| {
"content_hash": "57430ddf679c7789df2262ef032c5ec7",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 43,
"avg_line_length": 16.7,
"alnum_prop": 0.592814371257485,
"repo_name": "cetusfinance/qwack",
"id": "69c3d59a5c998c8ad39511cfd327b974f1007ac2",
"size": "167",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Qwack.Dates/TimePeriod.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "800"
},
{
"name": "C#",
"bytes": "3310132"
},
{
"name": "HTML",
"bytes": "6755"
},
{
"name": "Scilab",
"bytes": "3564"
},
{
"name": "Shell",
"bytes": "124"
},
{
"name": "TypeScript",
"bytes": "17933"
}
],
"symlink_target": ""
} |
import shutil
import locm, routem, mapm, dropboxm, gmaps, tools, bokehm
import logging.config, os, yaml, inspect
import time, math, random, sys, copy
import numpy as np
import anneal_optimizer
import haversine
# haversine((45.7597, 4.8422),(48.8567, 2.3508),miles = True)243.71209416020253
logger = logging.getLogger(__name__)
class ThreadOptimizer(anneal_optimizer.AnnealOptimizer):
"""ThreadOptimizer class provides
splitter
based on AnnealOptimizer."""
def __init__(self, start = None, finish = None, **kwarg):
super(ThreadOptimizer, self).__init__()
self.start = start
self.finish = finish
# self.set = None
# self.new_set = None
self.threads_scores = None
self.score = None
self.new_score = None
self.n_threads = None
self.node4threading_dtype = [(name,self.node_dtype[name]) for name in self.node_dtype.names] + [('potential', np.float64, 1),('proximity', np.float64, 1)]
def get_score(self,a_set_):
logger.debug(tools.get_string_caller_objclass_method(self,inspect.stack()))
full_score = 0.
# threads_scores = []
logger.debug("self.set\n%s" % (self.set,))
for thread_number,thread_idxs in enumerate(self.set):
logger.debug("thread_idxs\n%s" % (thread_idxs,))
a = anneal_optimizer.AnnealOptimizer()
a.nodes = np.take(self.nodes,thread_idxs)
a.start = self.start
a.finish = self.finish
a.set = list(np.arange(a.nodes.shape[0]))
a.SORT_ON = True
a.set = a.sort(a.set)
logger.debug("after sort a.nodes[a.set]['name']\n%s" % (a.nodes[a.set]['name'],))
a.update_stats()
# a.plot_route_from_stats()
# threads_scores.append(a.score)
full_score += a.score
return full_score
def create_threads(self):
logger.debug(tools.get_string_caller_objclass_method(self,inspect.stack()))
# node4threading_dtype = [(name,self.node_dtype[name]) for name in self.node_dtype.names] + [('potential', np.float64, 1),('proximity', np.float64, 1)]
nodes4threading = np.zeros(self.nodes.shape[0],dtype = self.node4threading_dtype)
for node,n4s in zip(self.nodes,nodes4threading):
n4s['name'] = node['name']
n4s['lat'] = node['lat']
n4s['lng'] = node['lng']
n4s['potential'] = tools.r([self.start['lat'],self.start['lng']],[node['lat'],node['lng']]) + \
tools.r([self.finish['lat'],self.finish['lng']],[node['lat'],node['lng']])
nodes4threading = np.sort(nodes4threading,order=('potential'))
logger.debug("nodes4threading\n%s" % (nodes4threading,))
sorted_indices = []
for node_name in nodes4threading['name']:
sorted_indices.append(np.where(self.nodes['name'] == node_name)[0][0])
sorted_indices = np.array(sorted_indices)
# logger.debug("sorted_indices\n%s" % (sorted_indices,))
n_per_route = self.nodes.shape[0]//self.n_threads
logger.debug("n_per_route\n%s" % (n_per_route,))
if self.nodes.shape[0] % self.n_threads != 0.:
logger.error("nodes left behind by threading - remainder of division is not 0")
splitted_sorted_indices = np.split(sorted_indices,n_per_route)
logger.debug("splitted_sorted_indices\n%s" % (splitted_sorted_indices,))
thr_idxs = np.zeros((self.n_threads,n_per_route),dtype = np.int32)
for part_num, split_part_indices in enumerate(splitted_sorted_indices):
part_nodes = np.take(nodes4threading,split_part_indices)
for thread_n in range(self.n_threads):
if part_num==0:
thr_idxs[thread_n][part_num] = split_part_indices[thread_n]# первый узел в нитке проставляем просто по порядку узлов в списке эквипотенциальных с наименьшим потенциалом
else:
prev_nodes_idxs = thr_idxs[thread_n][0:part_num]
prev_nodes = np.take(nodes4threading,split_part_indices)
prev_nodes_coords = [ [node['lat'],node['lng']] for node in prev_nodes]
part_nodes_coords = [ [node['lat'],node['lng']] for node in part_nodes if node['name']!='']
proximity_matrix = tools.get_proximity_matrix(prev_nodes_coords,part_nodes_coords)
_ ,equi_nodes_min_idx = np.unravel_index(np.argmin(proximity_matrix), proximity_matrix.shape)
next_node_in_thread_name = part_nodes[equi_nodes_min_idx]['name']
thr_idxs[thread_n][part_num] = \
np.where(nodes4threading['name']==next_node_in_thread_name)[0][0]
logger.debug("node added to route :\n%s" % nodes4threading[thr_idxs[thread_n][part_num]])
part_nodes = np.delete(part_nodes, equi_nodes_min_idx)
logger.debug("part_nodes after delete\n%s" % str(part_nodes))
logger.debug("thr_idxs\n%s" % (thr_idxs,))
self.set = thr_idxs
self.threads_scores = np.zeros((self.n_threads),dtype = np.float64)
def calc_scores(self):
logger.debug(tools.get_string_caller_objclass_method(self,inspect.stack()))
self.score = 0.
logger.debug("self.set\n%s" % (self.set,))
for thread_number,thread_idxs in enumerate(self.set):
logger.debug("thread_idxs\n%s" % (thread_idxs,))
a = anneal_optimizer.AnnealOptimizer()
a.nodes = np.take(self.nodes,thread_idxs)
a.start = self.start
a.finish = self.finish
a.set = list(np.arange(a.nodes.shape[0]))
a.SORT_ON = True
a.set = a.sort(a.set)
logger.debug("after sort a.nodes[a.set]['name']\n%s" % (a.nodes[a.set]['name'],))
a.update_stats()
# a.plot_route_from_stats()
self.threads_scores[thread_number] = a.score
self.score += a.score
def get_worst_thread_and_bad_node(self):
logger.debug(tools.get_string_caller_objclass_method(self,inspect.stack()))
max_score = max(self.threads_scores)
longest_thread_index = [i for i,j in enumerate(self.threads_scores) if j == max_score][0]
thread_nodes = np.take(self.nodes,self.set[longest_thread_index])
nodes4sorting = np.zeros(thread_nodes.shape[0],dtype = self.node4threading_dtype)
for node,n4s in zip(thread_nodes,nodes4sorting):
n4s['name'] = node['name']
n4s['lat'] = node['lat']
n4s['lng'] = node['lng']
n4s['potential'] = tools.r([self.start['lat'],self.start['lng']],[node['lat'],node['lng']]) + \
tools.r([self.finish['lat'],self.finish['lng']],[node['lat'],node['lng']])
nodes4sorting = np.sort(nodes4sorting,order=('potential'))[::-1]
logger.debug("nodes4sorting\n%s" % (nodes4sorting,))
return longest_thread_index, nodes4sorting[0]
def get_nearest_node(self, indices_to_choose_from, node_name):
logger.debug(tools.get_string_caller_objclass_method(self,inspect.stack()))
part_nodes = np.take(self.nodes, indices_to_choose_from)
logger.debug("part_nodes\n%s" % (part_nodes,))
node = np.take(self.nodes, np.where(self.nodes['name'] == node_name)[0][0])
logger.debug("node\n%s" % (node,))
part_nodes_coords = [ [node['lat'],node['lng']] for node in part_nodes if node['name']!=node_name]
proximity_matrix = tools.get_proximity_matrix(part_nodes_coords,[[node['lat'],node['lng']]])
_ ,part_nodes_min_idx = np.unravel_index(np.argmin(proximity_matrix), proximity_matrix.shape)
nearest_node = np.take(part_nodes, part_nodes_min_idx)
return nearest_node
def swap_indices_in_threads(self,i,j):
position_of_index_i = np.where( self.set == i )
logger.debug("position_of_index_i\n%s" % (position_of_index_i,))
position_of_index_j = np.where( self.set == j )
logger.debug("position_of_index_j\n%s" % (position_of_index_j,))
self.set[position_of_index_i] = j
self.set[position_of_index_j] = i
def update_stats(self):
logger.debug(tools.get_string_caller_objclass_method(self,inspect.stack()))
if self.stats == None and self.score != None: # and self.set != None:
new_entry = [self.score, self.set]
self.stats = [copy.deepcopy(new_entry)]
else:
new_entry = [self.score, self.set]
self.stats.append(copy.deepcopy(new_entry))
self.stats[-1].append(self.current_temp)
def loop(self):
self.new_set = self.set[:]
longest_thread_number, bad_node = self.get_worst_thread_and_bad_node()
logger.debug("bad_node\n%s" % (bad_node,))
other_threads_idxs = self.set[:]
other_threads_idxs = np.delete(other_threads_idxs, longest_thread_number,axis=0)
logger.debug("other_threads_idxs\n%s" % (other_threads_idxs,))
flattend_indices_to_choose_from = [idx for sublist in other_threads_idxs for idx in sublist]
nearest = self.get_nearest_node(flattend_indices_to_choose_from,bad_node['name'])
logger.debug("nearest\n%s" % (nearest,))
idx_of_bad_node = np.where(self.nodes['name'] == bad_node['name'])[0][0]
idx_of_nearest = np.where(self.nodes['name'] == nearest['name'])[0][0]
logger.debug("idx_of_bad_node\n%s" % (idx_of_bad_node,))
logger.debug("idx_of_nearest\n%s" % (idx_of_nearest,))
logger.debug("before swap self.set\n%s" % (self.set,))
self.swap_indices_in_threads(idx_of_bad_node,idx_of_nearest)
logger.debug("after swap self.set\n%s" % (self.set,))
self.calc_scores()
logger.debug("self.score\n%s" % (self.score,))
if self.choose():
logger.debug("New set chosen over old one")
self.set = self.new_set[:]
new_set_chosen = True
else:
logger.debug("Old set remains current one")
new_set_chosen = False
logger.debug("new_set_chosen\n%s" % (new_set_chosen,))
self.update_stats()
return new_set_chosen
def plot_threads(nodes_data,threads_indices):
start = tools.tver_coords
finish = tools.ryazan_coords
moscow = locm.Location(address='Moscow')
plot = bokehm.Figure(output_fname='threads.html',center_coords=moscow.coords,use_gmap=True,)
colors_list = ['darkgreen','magenta','blue','orange','brown']*(len(threads_indices)//5+1)
for i,thread_idxs in enumerate(threads_indices):
plot.add_line(nodes_data[thread_idxs], circle_size=10,circles_color=colors_list[i],alpha= 1.,no_line = True)
plot.add_line([start], circle_size=10,circles_color='green',alpha= 1.,no_line = True)
plot.add_line([finish], circle_size=10,circles_color='red',alpha= 1.,no_line = True)
plot.save2html()
# for i,part in enumerate(annealed_index_sets):
# logger.debug("len(part)\n%s" % (len(part),))
# logger.debug("part\n%s" % (part,))
# plot.add_line(all_nodes_list[part], circle_size=5,circles_color=colors_list[i],alpha= 0.5,no_line = False)
# if knots_indices[i]!=None:
# plot.add_line([s.start,all_nodes_list[knots_indices[i]]], circle_size=10,circles_color='red',alpha= 1.,no_line = False)
def init_thread_optimizer(n_cities=100, max_loops = 100, max_temp = 50, stop_temp = 0.1):
t = ThreadOptimizer()
nodes_data = tools.get_nodes_data(nodes_num = n_cities, recreate_nodes_data=False)
t.nodes = nodes_data
tver_coords = {u'lat':56.8583600,u'lng':35.9005700}
ryazan_coords = {u'lat':54.6269000,u'lng':39.6916000}
t.start = np.array(('Tver',tver_coords['lat'],tver_coords['lng']),dtype = t.node_dtype)
t.finish = np.array(('Ryazan',ryazan_coords['lat'],ryazan_coords['lng']),dtype = t.node_dtype)
logging.disable(logging.DEBUG)
t.set = [range(t.nodes.shape[0])]
logging.disable(logging.NOTSET)
logger.debug("t.set\n%s" % (t.set,))
alpha = (1 - 1./max_loops)
logger.debug("alpha\n%s" % (alpha,))
# alpha = 1-(1/max_temp)/2.
t.SWAP_NEAREST = False
t.SWAP_ORDER = True
t.SWAP_ONLY_NEIGHBOUR = False
# инициализация генератора температур в оптимизаторе
t.init_linear_cooling_schedule(max_temp,max_loops,stop_temp = stop_temp)
return t
def main():
number_of_cities_from_file = 100
max_threads_anneal_loops = 10
# max_temp = max_loops/1e1
max_threads_anneal_temp = 500
stop_threads_anneal_temperature = 0.1
t = init_thread_optimizer(n_cities=number_of_cities_from_file,
max_loops = max_threads_anneal_loops,
max_temp = max_threads_anneal_temp,
stop_temp = stop_threads_anneal_temperature)
t.n_threads = 5
logging.disable(logging.DEBUG)
t.create_threads()
t.calc_scores()
logging.disable(logging.NOTSET)
logger.debug("t.score\n%s" % (t.score,))
logger.debug("t.threads_scores\n%s" % (t.threads_scores,))
t.update_stats()
logging.disable(logging.DEBUG)
for i in range(max_threads_anneal_loops):
new_set_chosen = t.loop()
logger.debug("new_set_chosen\n%s" % (new_set_chosen,))
logger.debug("t.current_temp\n%s" % (t.current_temp,))
propability = t.get_transition_probability()
logger.debug("propability\n%.3f" % (propability,))
if i%5==0:
logger.info("threads anneal: %d from %d" % (i,max_threads_anneal_loops))
logger.info("t.current_temp %s" % (t.current_temp,))
logger.info("t.score %s" % (t.score,))
logging.disable(logging.NOTSET)
logger.debug("t.stats[-1]\n%s" % (t.stats[-1],))
t.plot_stats()
# plot routes after thread anneal
# for thread_number,thread_idxs in enumerate(t.set):
# # logger.debug("thread_idxs\n%s" % (thread_idxs,))
# a = anneal_optimizer.AnnealOptimizer()
# a.nodes = np.take(t.nodes,thread_idxs)
# a.start = t.start
# a.finish = t.finish
# a.set = list(np.arange(a.nodes.shape[0]))
# a.SORT_ON = True
# a.set = a.sort(a.set)
# # logger.debug("after sort a.nodes[a.set]['name']\n%s" % (a.nodes[a.set]['name'],))
# a.update_stats()
# a.plot_route_from_stats()
if __name__ == "__main__":
tools.setup_logging()
logger.info("thread optimizer script run directly")
main()
logger.info("thread optimizer script finished running") | {
"content_hash": "595096e2aefe7f8ad70f27fb2da78bb6",
"timestamp": "",
"source": "github",
"line_count": 300,
"max_line_length": 188,
"avg_line_length": 49.093333333333334,
"alnum_prop": 0.599877783813145,
"repo_name": "sergeimoiseev/othodi_code",
"id": "b20e568b2f7a3e2681a7e71103a82c45ab55bbdf",
"size": "14891",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "thread_optimizer.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "206"
},
{
"name": "HTML",
"bytes": "81386159"
},
{
"name": "Matlab",
"bytes": "2323"
},
{
"name": "Python",
"bytes": "456803"
},
{
"name": "Shell",
"bytes": "253"
}
],
"symlink_target": ""
} |
package org.jf.dexlib2;
import com.google.common.collect.Maps;
import javax.annotation.Nullable;
import java.util.HashMap;
public class Opcodes {
private final Opcode[] opcodesByValue;
private final HashMap<String, Opcode> opcodesByName;
public Opcodes(int api, boolean experimental) {
opcodesByValue = new Opcode[256];
opcodesByName = Maps.newHashMap();
for (Opcode opcode: Opcode.values()) {
if (!opcode.format.isPayloadFormat) {
if (api <= opcode.getMaxApi() && api >= opcode.getMinApi() &&
(experimental || !opcode.isExperimental())) {
opcodesByValue[opcode.value] = opcode;
opcodesByName.put(opcode.name.toLowerCase(), opcode);
}
}
}
}
@Nullable
public Opcode getOpcodeByName(String opcodeName) {
return opcodesByName.get(opcodeName.toLowerCase());
}
@Nullable
public Opcode getOpcodeByValue(int opcodeValue) {
switch (opcodeValue) {
case 0x100:
return Opcode.PACKED_SWITCH_PAYLOAD;
case 0x200:
return Opcode.SPARSE_SWITCH_PAYLOAD;
case 0x300:
return Opcode.ARRAY_PAYLOAD;
default:
if (opcodeValue >= 0 && opcodeValue < opcodesByValue.length) {
return opcodesByValue[opcodeValue];
}
return null;
}
}
}
| {
"content_hash": "5b5b415a870c3ca072515c6147fd8f8f",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 78,
"avg_line_length": 30,
"alnum_prop": 0.5686666666666667,
"repo_name": "Sukelluskello/VectorAttackScanner",
"id": "fb4838d97e1c8e8343ff227ca62398349e60d026",
"size": "3062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Android/DependenciesVectorAttackScanner/src/org/jf/dexlib2/Opcodes.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "44562"
},
{
"name": "Java",
"bytes": "12017578"
}
],
"symlink_target": ""
} |
#include "ixgbe.h"
#include "ixgbe_sriov.h"
#ifdef CONFIG_IXGBE_DCB
/**
* ixgbe_cache_ring_dcb_sriov - Descriptor ring to register mapping for SR-IOV
* @adapter: board private structure to initialize
*
* Cache the descriptor ring offsets for SR-IOV to the assigned rings. It
* will also try to cache the proper offsets if RSS/FCoE are enabled along
* with VMDq.
*
**/
static bool ixgbe_cache_ring_dcb_sriov(struct ixgbe_adapter *adapter)
{
#ifdef IXGBE_FCOE
struct ixgbe_ring_feature *fcoe = &adapter->ring_feature[RING_F_FCOE];
#endif /* IXGBE_FCOE */
struct ixgbe_ring_feature *vmdq = &adapter->ring_feature[RING_F_VMDQ];
int i;
u16 reg_idx;
u8 tcs = netdev_get_num_tc(adapter->netdev);
/* verify we have DCB queueing enabled before proceeding */
if (tcs <= 1)
return false;
/* verify we have VMDq enabled before proceeding */
if (!(adapter->flags & IXGBE_FLAG_SRIOV_ENABLED))
return false;
/* start at VMDq register offset for SR-IOV enabled setups */
reg_idx = vmdq->offset * __ALIGN_MASK(1, ~vmdq->mask);
for (i = 0; i < adapter->num_rx_queues; i++, reg_idx++) {
/* If we are greater than indices move to next pool */
if ((reg_idx & ~vmdq->mask) >= tcs)
reg_idx = __ALIGN_MASK(reg_idx, ~vmdq->mask);
adapter->rx_ring[i]->reg_idx = reg_idx;
}
reg_idx = vmdq->offset * __ALIGN_MASK(1, ~vmdq->mask);
for (i = 0; i < adapter->num_tx_queues; i++, reg_idx++) {
/* If we are greater than indices move to next pool */
if ((reg_idx & ~vmdq->mask) >= tcs)
reg_idx = __ALIGN_MASK(reg_idx, ~vmdq->mask);
adapter->tx_ring[i]->reg_idx = reg_idx;
}
#ifdef IXGBE_FCOE
/* nothing to do if FCoE is disabled */
if (!(adapter->flags & IXGBE_FLAG_FCOE_ENABLED))
return true;
/* The work is already done if the FCoE ring is shared */
if (fcoe->offset < tcs)
return true;
/* The FCoE rings exist separately, we need to move their reg_idx */
if (fcoe->indices) {
u16 queues_per_pool = __ALIGN_MASK(1, ~vmdq->mask);
u8 fcoe_tc = ixgbe_fcoe_get_tc(adapter);
reg_idx = (vmdq->offset + vmdq->indices) * queues_per_pool;
for (i = fcoe->offset; i < adapter->num_rx_queues; i++) {
reg_idx = __ALIGN_MASK(reg_idx, ~vmdq->mask) + fcoe_tc;
adapter->rx_ring[i]->reg_idx = reg_idx;
reg_idx++;
}
reg_idx = (vmdq->offset + vmdq->indices) * queues_per_pool;
for (i = fcoe->offset; i < adapter->num_tx_queues; i++) {
reg_idx = __ALIGN_MASK(reg_idx, ~vmdq->mask) + fcoe_tc;
adapter->tx_ring[i]->reg_idx = reg_idx;
reg_idx++;
}
}
#endif /* IXGBE_FCOE */
return true;
}
/* ixgbe_get_first_reg_idx - Return first register index associated with ring */
static void ixgbe_get_first_reg_idx(struct ixgbe_adapter *adapter, u8 tc,
unsigned int *tx, unsigned int *rx)
{
struct net_device *dev = adapter->netdev;
struct ixgbe_hw *hw = &adapter->hw;
u8 num_tcs = netdev_get_num_tc(dev);
*tx = 0;
*rx = 0;
switch (hw->mac.type) {
case ixgbe_mac_82598EB:
/* TxQs/TC: 4 RxQs/TC: 8 */
*tx = tc << 2; /* 0, 4, 8, 12, 16, 20, 24, 28 */
*rx = tc << 3; /* 0, 8, 16, 24, 32, 40, 48, 56 */
break;
case ixgbe_mac_82599EB:
case ixgbe_mac_X540:
case ixgbe_mac_X550:
case ixgbe_mac_X550EM_x:
case ixgbe_mac_x550em_a:
if (num_tcs > 4) {
/*
* TCs : TC0/1 TC2/3 TC4-7
* TxQs/TC: 32 16 8
* RxQs/TC: 16 16 16
*/
*rx = tc << 4;
if (tc < 3)
*tx = tc << 5; /* 0, 32, 64 */
else if (tc < 5)
*tx = (tc + 2) << 4; /* 80, 96 */
else
*tx = (tc + 8) << 3; /* 104, 112, 120 */
} else {
/*
* TCs : TC0 TC1 TC2/3
* TxQs/TC: 64 32 16
* RxQs/TC: 32 32 32
*/
*rx = tc << 5;
if (tc < 2)
*tx = tc << 6; /* 0, 64 */
else
*tx = (tc + 4) << 4; /* 96, 112 */
}
default:
break;
}
}
/**
* ixgbe_cache_ring_dcb - Descriptor ring to register mapping for DCB
* @adapter: board private structure to initialize
*
* Cache the descriptor ring offsets for DCB to the assigned rings.
*
**/
static bool ixgbe_cache_ring_dcb(struct ixgbe_adapter *adapter)
{
struct net_device *dev = adapter->netdev;
unsigned int tx_idx, rx_idx;
int tc, offset, rss_i, i;
u8 num_tcs = netdev_get_num_tc(dev);
/* verify we have DCB queueing enabled before proceeding */
if (num_tcs <= 1)
return false;
rss_i = adapter->ring_feature[RING_F_RSS].indices;
for (tc = 0, offset = 0; tc < num_tcs; tc++, offset += rss_i) {
ixgbe_get_first_reg_idx(adapter, tc, &tx_idx, &rx_idx);
for (i = 0; i < rss_i; i++, tx_idx++, rx_idx++) {
adapter->tx_ring[offset + i]->reg_idx = tx_idx;
adapter->rx_ring[offset + i]->reg_idx = rx_idx;
adapter->tx_ring[offset + i]->dcb_tc = tc;
adapter->rx_ring[offset + i]->dcb_tc = tc;
}
}
return true;
}
#endif
/**
* ixgbe_cache_ring_sriov - Descriptor ring to register mapping for sriov
* @adapter: board private structure to initialize
*
* SR-IOV doesn't use any descriptor rings but changes the default if
* no other mapping is used.
*
*/
static bool ixgbe_cache_ring_sriov(struct ixgbe_adapter *adapter)
{
#ifdef IXGBE_FCOE
struct ixgbe_ring_feature *fcoe = &adapter->ring_feature[RING_F_FCOE];
#endif /* IXGBE_FCOE */
struct ixgbe_ring_feature *vmdq = &adapter->ring_feature[RING_F_VMDQ];
struct ixgbe_ring_feature *rss = &adapter->ring_feature[RING_F_RSS];
int i;
u16 reg_idx;
/* only proceed if VMDq is enabled */
if (!(adapter->flags & IXGBE_FLAG_VMDQ_ENABLED))
return false;
/* start at VMDq register offset for SR-IOV enabled setups */
reg_idx = vmdq->offset * __ALIGN_MASK(1, ~vmdq->mask);
for (i = 0; i < adapter->num_rx_queues; i++, reg_idx++) {
#ifdef IXGBE_FCOE
/* Allow first FCoE queue to be mapped as RSS */
if (fcoe->offset && (i > fcoe->offset))
break;
#endif
/* If we are greater than indices move to next pool */
if ((reg_idx & ~vmdq->mask) >= rss->indices)
reg_idx = __ALIGN_MASK(reg_idx, ~vmdq->mask);
adapter->rx_ring[i]->reg_idx = reg_idx;
}
#ifdef IXGBE_FCOE
/* FCoE uses a linear block of queues so just assigning 1:1 */
for (; i < adapter->num_rx_queues; i++, reg_idx++)
adapter->rx_ring[i]->reg_idx = reg_idx;
#endif
reg_idx = vmdq->offset * __ALIGN_MASK(1, ~vmdq->mask);
for (i = 0; i < adapter->num_tx_queues; i++, reg_idx++) {
#ifdef IXGBE_FCOE
/* Allow first FCoE queue to be mapped as RSS */
if (fcoe->offset && (i > fcoe->offset))
break;
#endif
/* If we are greater than indices move to next pool */
if ((reg_idx & rss->mask) >= rss->indices)
reg_idx = __ALIGN_MASK(reg_idx, ~vmdq->mask);
adapter->tx_ring[i]->reg_idx = reg_idx;
}
#ifdef IXGBE_FCOE
/* FCoE uses a linear block of queues so just assigning 1:1 */
for (; i < adapter->num_tx_queues; i++, reg_idx++)
adapter->tx_ring[i]->reg_idx = reg_idx;
#endif
return true;
}
/**
* ixgbe_cache_ring_rss - Descriptor ring to register mapping for RSS
* @adapter: board private structure to initialize
*
* Cache the descriptor ring offsets for RSS to the assigned rings.
*
**/
static bool ixgbe_cache_ring_rss(struct ixgbe_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
adapter->rx_ring[i]->reg_idx = i;
for (i = 0; i < adapter->num_tx_queues; i++)
adapter->tx_ring[i]->reg_idx = i;
return true;
}
/**
* ixgbe_cache_ring_register - Descriptor ring to register mapping
* @adapter: board private structure to initialize
*
* Once we know the feature-set enabled for the device, we'll cache
* the register offset the descriptor ring is assigned to.
*
* Note, the order the various feature calls is important. It must start with
* the "most" features enabled at the same time, then trickle down to the
* least amount of features turned on at once.
**/
static void ixgbe_cache_ring_register(struct ixgbe_adapter *adapter)
{
/* start with default case */
adapter->rx_ring[0]->reg_idx = 0;
adapter->tx_ring[0]->reg_idx = 0;
#ifdef CONFIG_IXGBE_DCB
if (ixgbe_cache_ring_dcb_sriov(adapter))
return;
if (ixgbe_cache_ring_dcb(adapter))
return;
#endif
if (ixgbe_cache_ring_sriov(adapter))
return;
ixgbe_cache_ring_rss(adapter);
}
#define IXGBE_RSS_16Q_MASK 0xF
#define IXGBE_RSS_8Q_MASK 0x7
#define IXGBE_RSS_4Q_MASK 0x3
#define IXGBE_RSS_2Q_MASK 0x1
#define IXGBE_RSS_DISABLED_MASK 0x0
#ifdef CONFIG_IXGBE_DCB
/**
* ixgbe_set_dcb_sriov_queues: Allocate queues for SR-IOV devices w/ DCB
* @adapter: board private structure to initialize
*
* When SR-IOV (Single Root IO Virtualiztion) is enabled, allocate queues
* and VM pools where appropriate. Also assign queues based on DCB
* priorities and map accordingly..
*
**/
static bool ixgbe_set_dcb_sriov_queues(struct ixgbe_adapter *adapter)
{
int i;
u16 vmdq_i = adapter->ring_feature[RING_F_VMDQ].limit;
u16 vmdq_m = 0;
#ifdef IXGBE_FCOE
u16 fcoe_i = 0;
#endif
u8 tcs = netdev_get_num_tc(adapter->netdev);
/* verify we have DCB queueing enabled before proceeding */
if (tcs <= 1)
return false;
/* verify we have VMDq enabled before proceeding */
if (!(adapter->flags & IXGBE_FLAG_SRIOV_ENABLED))
return false;
/* Add starting offset to total pool count */
vmdq_i += adapter->ring_feature[RING_F_VMDQ].offset;
/* 16 pools w/ 8 TC per pool */
if (tcs > 4) {
vmdq_i = min_t(u16, vmdq_i, 16);
vmdq_m = IXGBE_82599_VMDQ_8Q_MASK;
/* 32 pools w/ 4 TC per pool */
} else {
vmdq_i = min_t(u16, vmdq_i, 32);
vmdq_m = IXGBE_82599_VMDQ_4Q_MASK;
}
#ifdef IXGBE_FCOE
/* queues in the remaining pools are available for FCoE */
fcoe_i = (128 / __ALIGN_MASK(1, ~vmdq_m)) - vmdq_i;
#endif
/* remove the starting offset from the pool count */
vmdq_i -= adapter->ring_feature[RING_F_VMDQ].offset;
/* save features for later use */
adapter->ring_feature[RING_F_VMDQ].indices = vmdq_i;
adapter->ring_feature[RING_F_VMDQ].mask = vmdq_m;
/*
* We do not support DCB, VMDq, and RSS all simultaneously
* so we will disable RSS since it is the lowest priority
*/
adapter->ring_feature[RING_F_RSS].indices = 1;
adapter->ring_feature[RING_F_RSS].mask = IXGBE_RSS_DISABLED_MASK;
/* disable ATR as it is not supported when VMDq is enabled */
adapter->flags &= ~IXGBE_FLAG_FDIR_HASH_CAPABLE;
adapter->num_rx_pools = vmdq_i;
adapter->num_rx_queues_per_pool = tcs;
adapter->num_tx_queues = vmdq_i * tcs;
adapter->num_rx_queues = vmdq_i * tcs;
#ifdef IXGBE_FCOE
if (adapter->flags & IXGBE_FLAG_FCOE_ENABLED) {
struct ixgbe_ring_feature *fcoe;
fcoe = &adapter->ring_feature[RING_F_FCOE];
/* limit ourselves based on feature limits */
fcoe_i = min_t(u16, fcoe_i, fcoe->limit);
if (fcoe_i) {
/* alloc queues for FCoE separately */
fcoe->indices = fcoe_i;
fcoe->offset = vmdq_i * tcs;
/* add queues to adapter */
adapter->num_tx_queues += fcoe_i;
adapter->num_rx_queues += fcoe_i;
} else if (tcs > 1) {
/* use queue belonging to FcoE TC */
fcoe->indices = 1;
fcoe->offset = ixgbe_fcoe_get_tc(adapter);
} else {
adapter->flags &= ~IXGBE_FLAG_FCOE_ENABLED;
fcoe->indices = 0;
fcoe->offset = 0;
}
}
#endif /* IXGBE_FCOE */
/* configure TC to queue mapping */
for (i = 0; i < tcs; i++)
netdev_set_tc_queue(adapter->netdev, i, 1, i);
return true;
}
static bool ixgbe_set_dcb_queues(struct ixgbe_adapter *adapter)
{
struct net_device *dev = adapter->netdev;
struct ixgbe_ring_feature *f;
int rss_i, rss_m, i;
int tcs;
/* Map queue offset and counts onto allocated tx queues */
tcs = netdev_get_num_tc(dev);
/* verify we have DCB queueing enabled before proceeding */
if (tcs <= 1)
return false;
/* determine the upper limit for our current DCB mode */
rss_i = dev->num_tx_queues / tcs;
if (adapter->hw.mac.type == ixgbe_mac_82598EB) {
/* 8 TC w/ 4 queues per TC */
rss_i = min_t(u16, rss_i, 4);
rss_m = IXGBE_RSS_4Q_MASK;
} else if (tcs > 4) {
/* 8 TC w/ 8 queues per TC */
rss_i = min_t(u16, rss_i, 8);
rss_m = IXGBE_RSS_8Q_MASK;
} else {
/* 4 TC w/ 16 queues per TC */
rss_i = min_t(u16, rss_i, 16);
rss_m = IXGBE_RSS_16Q_MASK;
}
/* set RSS mask and indices */
f = &adapter->ring_feature[RING_F_RSS];
rss_i = min_t(int, rss_i, f->limit);
f->indices = rss_i;
f->mask = rss_m;
/* disable ATR as it is not supported when multiple TCs are enabled */
adapter->flags &= ~IXGBE_FLAG_FDIR_HASH_CAPABLE;
#ifdef IXGBE_FCOE
/* FCoE enabled queues require special configuration indexed
* by feature specific indices and offset. Here we map FCoE
* indices onto the DCB queue pairs allowing FCoE to own
* configuration later.
*/
if (adapter->flags & IXGBE_FLAG_FCOE_ENABLED) {
u8 tc = ixgbe_fcoe_get_tc(adapter);
f = &adapter->ring_feature[RING_F_FCOE];
f->indices = min_t(u16, rss_i, f->limit);
f->offset = rss_i * tc;
}
#endif /* IXGBE_FCOE */
for (i = 0; i < tcs; i++)
netdev_set_tc_queue(dev, i, rss_i, rss_i * i);
adapter->num_tx_queues = rss_i * tcs;
adapter->num_rx_queues = rss_i * tcs;
return true;
}
#endif
/**
* ixgbe_set_sriov_queues - Allocate queues for SR-IOV devices
* @adapter: board private structure to initialize
*
* When SR-IOV (Single Root IO Virtualiztion) is enabled, allocate queues
* and VM pools where appropriate. If RSS is available, then also try and
* enable RSS and map accordingly.
*
**/
static bool ixgbe_set_sriov_queues(struct ixgbe_adapter *adapter)
{
u16 vmdq_i = adapter->ring_feature[RING_F_VMDQ].limit;
u16 vmdq_m = 0;
u16 rss_i = adapter->ring_feature[RING_F_RSS].limit;
u16 rss_m = IXGBE_RSS_DISABLED_MASK;
#ifdef IXGBE_FCOE
u16 fcoe_i = 0;
#endif
bool pools = (find_first_zero_bit(&adapter->fwd_bitmask, 32) > 1);
/* only proceed if SR-IOV is enabled */
if (!(adapter->flags & IXGBE_FLAG_SRIOV_ENABLED))
return false;
/* Add starting offset to total pool count */
vmdq_i += adapter->ring_feature[RING_F_VMDQ].offset;
/* double check we are limited to maximum pools */
vmdq_i = min_t(u16, IXGBE_MAX_VMDQ_INDICES, vmdq_i);
/* 64 pool mode with 2 queues per pool */
if ((vmdq_i > 32) || (rss_i < 4) || (vmdq_i > 16 && pools)) {
vmdq_m = IXGBE_82599_VMDQ_2Q_MASK;
rss_m = IXGBE_RSS_2Q_MASK;
rss_i = min_t(u16, rss_i, 2);
/* 32 pool mode with 4 queues per pool */
} else {
vmdq_m = IXGBE_82599_VMDQ_4Q_MASK;
rss_m = IXGBE_RSS_4Q_MASK;
rss_i = 4;
}
#ifdef IXGBE_FCOE
/* queues in the remaining pools are available for FCoE */
fcoe_i = 128 - (vmdq_i * __ALIGN_MASK(1, ~vmdq_m));
#endif
/* remove the starting offset from the pool count */
vmdq_i -= adapter->ring_feature[RING_F_VMDQ].offset;
/* save features for later use */
adapter->ring_feature[RING_F_VMDQ].indices = vmdq_i;
adapter->ring_feature[RING_F_VMDQ].mask = vmdq_m;
/* limit RSS based on user input and save for later use */
adapter->ring_feature[RING_F_RSS].indices = rss_i;
adapter->ring_feature[RING_F_RSS].mask = rss_m;
adapter->num_rx_pools = vmdq_i;
adapter->num_rx_queues_per_pool = rss_i;
adapter->num_rx_queues = vmdq_i * rss_i;
adapter->num_tx_queues = vmdq_i * rss_i;
/* disable ATR as it is not supported when VMDq is enabled */
adapter->flags &= ~IXGBE_FLAG_FDIR_HASH_CAPABLE;
#ifdef IXGBE_FCOE
/*
* FCoE can use rings from adjacent buffers to allow RSS
* like behavior. To account for this we need to add the
* FCoE indices to the total ring count.
*/
if (adapter->flags & IXGBE_FLAG_FCOE_ENABLED) {
struct ixgbe_ring_feature *fcoe;
fcoe = &adapter->ring_feature[RING_F_FCOE];
/* limit ourselves based on feature limits */
fcoe_i = min_t(u16, fcoe_i, fcoe->limit);
if (vmdq_i > 1 && fcoe_i) {
/* alloc queues for FCoE separately */
fcoe->indices = fcoe_i;
fcoe->offset = vmdq_i * rss_i;
} else {
/* merge FCoE queues with RSS queues */
fcoe_i = min_t(u16, fcoe_i + rss_i, num_online_cpus());
/* limit indices to rss_i if MSI-X is disabled */
if (!(adapter->flags & IXGBE_FLAG_MSIX_ENABLED))
fcoe_i = rss_i;
/* attempt to reserve some queues for just FCoE */
fcoe->indices = min_t(u16, fcoe_i, fcoe->limit);
fcoe->offset = fcoe_i - fcoe->indices;
fcoe_i -= rss_i;
}
/* add queues to adapter */
adapter->num_tx_queues += fcoe_i;
adapter->num_rx_queues += fcoe_i;
}
#endif
return true;
}
/**
* ixgbe_set_rss_queues - Allocate queues for RSS
* @adapter: board private structure to initialize
*
* This is our "base" multiqueue mode. RSS (Receive Side Scaling) will try
* to allocate one Rx queue per CPU, and if available, one Tx queue per CPU.
*
**/
static bool ixgbe_set_rss_queues(struct ixgbe_adapter *adapter)
{
struct ixgbe_ring_feature *f;
u16 rss_i;
/* set mask for 16 queue limit of RSS */
f = &adapter->ring_feature[RING_F_RSS];
rss_i = f->limit;
f->indices = rss_i;
f->mask = IXGBE_RSS_16Q_MASK;
/* disable ATR by default, it will be configured below */
adapter->flags &= ~IXGBE_FLAG_FDIR_HASH_CAPABLE;
/*
* Use Flow Director in addition to RSS to ensure the best
* distribution of flows across cores, even when an FDIR flow
* isn't matched.
*/
if (rss_i > 1 && adapter->atr_sample_rate) {
f = &adapter->ring_feature[RING_F_FDIR];
rss_i = f->indices = f->limit;
if (!(adapter->flags & IXGBE_FLAG_FDIR_PERFECT_CAPABLE))
adapter->flags |= IXGBE_FLAG_FDIR_HASH_CAPABLE;
}
#ifdef IXGBE_FCOE
/*
* FCoE can exist on the same rings as standard network traffic
* however it is preferred to avoid that if possible. In order
* to get the best performance we allocate as many FCoE queues
* as we can and we place them at the end of the ring array to
* avoid sharing queues with standard RSS on systems with 24 or
* more CPUs.
*/
if (adapter->flags & IXGBE_FLAG_FCOE_ENABLED) {
struct net_device *dev = adapter->netdev;
u16 fcoe_i;
f = &adapter->ring_feature[RING_F_FCOE];
/* merge FCoE queues with RSS queues */
fcoe_i = min_t(u16, f->limit + rss_i, num_online_cpus());
fcoe_i = min_t(u16, fcoe_i, dev->num_tx_queues);
/* limit indices to rss_i if MSI-X is disabled */
if (!(adapter->flags & IXGBE_FLAG_MSIX_ENABLED))
fcoe_i = rss_i;
/* attempt to reserve some queues for just FCoE */
f->indices = min_t(u16, fcoe_i, f->limit);
f->offset = fcoe_i - f->indices;
rss_i = max_t(u16, fcoe_i, rss_i);
}
#endif /* IXGBE_FCOE */
adapter->num_rx_queues = rss_i;
adapter->num_tx_queues = rss_i;
return true;
}
/**
* ixgbe_set_num_queues - Allocate queues for device, feature dependent
* @adapter: board private structure to initialize
*
* This is the top level queue allocation routine. The order here is very
* important, starting with the "most" number of features turned on at once,
* and ending with the smallest set of features. This way large combinations
* can be allocated if they're turned on, and smaller combinations are the
* fallthrough conditions.
*
**/
static void ixgbe_set_num_queues(struct ixgbe_adapter *adapter)
{
/* Start with base case */
adapter->num_rx_queues = 1;
adapter->num_tx_queues = 1;
adapter->num_rx_pools = adapter->num_rx_queues;
adapter->num_rx_queues_per_pool = 1;
#ifdef CONFIG_IXGBE_DCB
if (ixgbe_set_dcb_sriov_queues(adapter))
return;
if (ixgbe_set_dcb_queues(adapter))
return;
#endif
if (ixgbe_set_sriov_queues(adapter))
return;
ixgbe_set_rss_queues(adapter);
}
/**
* ixgbe_acquire_msix_vectors - acquire MSI-X vectors
* @adapter: board private structure
*
* Attempts to acquire a suitable range of MSI-X vector interrupts. Will
* return a negative error code if unable to acquire MSI-X vectors for any
* reason.
*/
static int ixgbe_acquire_msix_vectors(struct ixgbe_adapter *adapter)
{
struct ixgbe_hw *hw = &adapter->hw;
int i, vectors, vector_threshold;
/* We start by asking for one vector per queue pair */
vectors = max(adapter->num_rx_queues, adapter->num_tx_queues);
/* It is easy to be greedy for MSI-X vectors. However, it really
* doesn't do much good if we have a lot more vectors than CPUs. We'll
* be somewhat conservative and only ask for (roughly) the same number
* of vectors as there are CPUs.
*/
vectors = min_t(int, vectors, num_online_cpus());
/* Some vectors are necessary for non-queue interrupts */
vectors += NON_Q_VECTORS;
/* Hardware can only support a maximum of hw.mac->max_msix_vectors.
* With features such as RSS and VMDq, we can easily surpass the
* number of Rx and Tx descriptor queues supported by our device.
* Thus, we cap the maximum in the rare cases where the CPU count also
* exceeds our vector limit
*/
vectors = min_t(int, vectors, hw->mac.max_msix_vectors);
/* We want a minimum of two MSI-X vectors for (1) a TxQ[0] + RxQ[0]
* handler, and (2) an Other (Link Status Change, etc.) handler.
*/
vector_threshold = MIN_MSIX_COUNT;
adapter->msix_entries = kcalloc(vectors,
sizeof(struct msix_entry),
GFP_KERNEL);
if (!adapter->msix_entries)
return -ENOMEM;
for (i = 0; i < vectors; i++)
adapter->msix_entries[i].entry = i;
vectors = pci_enable_msix_range(adapter->pdev, adapter->msix_entries,
vector_threshold, vectors);
if (vectors < 0) {
/* A negative count of allocated vectors indicates an error in
* acquiring within the specified range of MSI-X vectors
*/
e_dev_warn("Failed to allocate MSI-X interrupts. Err: %d\n",
vectors);
adapter->flags &= ~IXGBE_FLAG_MSIX_ENABLED;
kfree(adapter->msix_entries);
adapter->msix_entries = NULL;
return vectors;
}
/* we successfully allocated some number of vectors within our
* requested range.
*/
adapter->flags |= IXGBE_FLAG_MSIX_ENABLED;
/* Adjust for only the vectors we'll use, which is minimum
* of max_q_vectors, or the number of vectors we were allocated.
*/
vectors -= NON_Q_VECTORS;
adapter->num_q_vectors = min_t(int, vectors, adapter->max_q_vectors);
return 0;
}
static void ixgbe_add_ring(struct ixgbe_ring *ring,
struct ixgbe_ring_container *head)
{
ring->next = head->ring;
head->ring = ring;
head->count++;
}
/**
* ixgbe_alloc_q_vector - Allocate memory for a single interrupt vector
* @adapter: board private structure to initialize
* @v_count: q_vectors allocated on adapter, used for ring interleaving
* @v_idx: index of vector in adapter struct
* @txr_count: total number of Tx rings to allocate
* @txr_idx: index of first Tx ring to allocate
* @rxr_count: total number of Rx rings to allocate
* @rxr_idx: index of first Rx ring to allocate
*
* We allocate one q_vector. If allocation fails we return -ENOMEM.
**/
static int ixgbe_alloc_q_vector(struct ixgbe_adapter *adapter,
int v_count, int v_idx,
int txr_count, int txr_idx,
int rxr_count, int rxr_idx)
{
struct ixgbe_q_vector *q_vector;
struct ixgbe_ring *ring;
int node = NUMA_NO_NODE;
int cpu = -1;
int ring_count, size;
u8 tcs = netdev_get_num_tc(adapter->netdev);
ring_count = txr_count + rxr_count;
size = sizeof(struct ixgbe_q_vector) +
(sizeof(struct ixgbe_ring) * ring_count);
/* customize cpu for Flow Director mapping */
if ((tcs <= 1) && !(adapter->flags & IXGBE_FLAG_SRIOV_ENABLED)) {
u16 rss_i = adapter->ring_feature[RING_F_RSS].indices;
if (rss_i > 1 && adapter->atr_sample_rate) {
if (cpu_online(v_idx)) {
cpu = v_idx;
node = cpu_to_node(cpu);
}
}
}
/* allocate q_vector and rings */
q_vector = kzalloc_node(size, GFP_KERNEL, node);
if (!q_vector)
q_vector = kzalloc(size, GFP_KERNEL);
if (!q_vector)
return -ENOMEM;
/* setup affinity mask and node */
if (cpu != -1)
cpumask_set_cpu(cpu, &q_vector->affinity_mask);
q_vector->numa_node = node;
#ifdef CONFIG_IXGBE_DCA
/* initialize CPU for DCA */
q_vector->cpu = -1;
#endif
/* initialize NAPI */
netif_napi_add(adapter->netdev, &q_vector->napi,
ixgbe_poll, 64);
#ifdef CONFIG_NET_RX_BUSY_POLL
/* initialize busy poll */
atomic_set(&q_vector->state, IXGBE_QV_STATE_DISABLE);
#endif
/* tie q_vector and adapter together */
adapter->q_vector[v_idx] = q_vector;
q_vector->adapter = adapter;
q_vector->v_idx = v_idx;
/* initialize work limits */
q_vector->tx.work_limit = adapter->tx_work_limit;
/* initialize pointer to rings */
ring = q_vector->ring;
/* intialize ITR */
if (txr_count && !rxr_count) {
/* tx only vector */
if (adapter->tx_itr_setting == 1)
q_vector->itr = IXGBE_12K_ITR;
else
q_vector->itr = adapter->tx_itr_setting;
} else {
/* rx or rx/tx vector */
if (adapter->rx_itr_setting == 1)
q_vector->itr = IXGBE_20K_ITR;
else
q_vector->itr = adapter->rx_itr_setting;
}
while (txr_count) {
/* assign generic ring traits */
ring->dev = &adapter->pdev->dev;
ring->netdev = adapter->netdev;
/* configure backlink on ring */
ring->q_vector = q_vector;
/* update q_vector Tx values */
ixgbe_add_ring(ring, &q_vector->tx);
/* apply Tx specific ring traits */
ring->count = adapter->tx_ring_count;
if (adapter->num_rx_pools > 1)
ring->queue_index =
txr_idx % adapter->num_rx_queues_per_pool;
else
ring->queue_index = txr_idx;
/* assign ring to adapter */
adapter->tx_ring[txr_idx] = ring;
/* update count and index */
txr_count--;
txr_idx += v_count;
/* push pointer to next ring */
ring++;
}
while (rxr_count) {
/* assign generic ring traits */
ring->dev = &adapter->pdev->dev;
ring->netdev = adapter->netdev;
/* configure backlink on ring */
ring->q_vector = q_vector;
/* update q_vector Rx values */
ixgbe_add_ring(ring, &q_vector->rx);
/*
* 82599 errata, UDP frames with a 0 checksum
* can be marked as checksum errors.
*/
if (adapter->hw.mac.type == ixgbe_mac_82599EB)
set_bit(__IXGBE_RX_CSUM_UDP_ZERO_ERR, &ring->state);
#ifdef IXGBE_FCOE
if (adapter->netdev->features & NETIF_F_FCOE_MTU) {
struct ixgbe_ring_feature *f;
f = &adapter->ring_feature[RING_F_FCOE];
if ((rxr_idx >= f->offset) &&
(rxr_idx < f->offset + f->indices))
set_bit(__IXGBE_RX_FCOE, &ring->state);
}
#endif /* IXGBE_FCOE */
/* apply Rx specific ring traits */
ring->count = adapter->rx_ring_count;
if (adapter->num_rx_pools > 1)
ring->queue_index =
rxr_idx % adapter->num_rx_queues_per_pool;
else
ring->queue_index = rxr_idx;
/* assign ring to adapter */
adapter->rx_ring[rxr_idx] = ring;
/* update count and index */
rxr_count--;
rxr_idx += v_count;
/* push pointer to next ring */
ring++;
}
return 0;
}
/**
* ixgbe_free_q_vector - Free memory allocated for specific interrupt vector
* @adapter: board private structure to initialize
* @v_idx: Index of vector to be freed
*
* This function frees the memory allocated to the q_vector. In addition if
* NAPI is enabled it will delete any references to the NAPI struct prior
* to freeing the q_vector.
**/
static void ixgbe_free_q_vector(struct ixgbe_adapter *adapter, int v_idx)
{
struct ixgbe_q_vector *q_vector = adapter->q_vector[v_idx];
struct ixgbe_ring *ring;
ixgbe_for_each_ring(ring, q_vector->tx)
adapter->tx_ring[ring->queue_index] = NULL;
ixgbe_for_each_ring(ring, q_vector->rx)
adapter->rx_ring[ring->queue_index] = NULL;
adapter->q_vector[v_idx] = NULL;
napi_hash_del(&q_vector->napi);
netif_napi_del(&q_vector->napi);
/*
* ixgbe_get_stats64() might access the rings on this vector,
* we must wait a grace period before freeing it.
*/
kfree_rcu(q_vector, rcu);
}
/**
* ixgbe_alloc_q_vectors - Allocate memory for interrupt vectors
* @adapter: board private structure to initialize
*
* We allocate one q_vector per queue interrupt. If allocation fails we
* return -ENOMEM.
**/
static int ixgbe_alloc_q_vectors(struct ixgbe_adapter *adapter)
{
int q_vectors = adapter->num_q_vectors;
int rxr_remaining = adapter->num_rx_queues;
int txr_remaining = adapter->num_tx_queues;
int rxr_idx = 0, txr_idx = 0, v_idx = 0;
int err;
/* only one q_vector if MSI-X is disabled. */
if (!(adapter->flags & IXGBE_FLAG_MSIX_ENABLED))
q_vectors = 1;
if (q_vectors >= (rxr_remaining + txr_remaining)) {
for (; rxr_remaining; v_idx++) {
err = ixgbe_alloc_q_vector(adapter, q_vectors, v_idx,
0, 0, 1, rxr_idx);
if (err)
goto err_out;
/* update counts and index */
rxr_remaining--;
rxr_idx++;
}
}
for (; v_idx < q_vectors; v_idx++) {
int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx);
int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx);
err = ixgbe_alloc_q_vector(adapter, q_vectors, v_idx,
tqpv, txr_idx,
rqpv, rxr_idx);
if (err)
goto err_out;
/* update counts and index */
rxr_remaining -= rqpv;
txr_remaining -= tqpv;
rxr_idx++;
txr_idx++;
}
return 0;
err_out:
adapter->num_tx_queues = 0;
adapter->num_rx_queues = 0;
adapter->num_q_vectors = 0;
while (v_idx--)
ixgbe_free_q_vector(adapter, v_idx);
return -ENOMEM;
}
/**
* ixgbe_free_q_vectors - Free memory allocated for interrupt vectors
* @adapter: board private structure to initialize
*
* This function frees the memory allocated to the q_vectors. In addition if
* NAPI is enabled it will delete any references to the NAPI struct prior
* to freeing the q_vector.
**/
static void ixgbe_free_q_vectors(struct ixgbe_adapter *adapter)
{
int v_idx = adapter->num_q_vectors;
adapter->num_tx_queues = 0;
adapter->num_rx_queues = 0;
adapter->num_q_vectors = 0;
while (v_idx--)
ixgbe_free_q_vector(adapter, v_idx);
}
static void ixgbe_reset_interrupt_capability(struct ixgbe_adapter *adapter)
{
if (adapter->flags & IXGBE_FLAG_MSIX_ENABLED) {
adapter->flags &= ~IXGBE_FLAG_MSIX_ENABLED;
pci_disable_msix(adapter->pdev);
kfree(adapter->msix_entries);
adapter->msix_entries = NULL;
} else if (adapter->flags & IXGBE_FLAG_MSI_ENABLED) {
adapter->flags &= ~IXGBE_FLAG_MSI_ENABLED;
pci_disable_msi(adapter->pdev);
}
}
/**
* ixgbe_set_interrupt_capability - set MSI-X or MSI if supported
* @adapter: board private structure to initialize
*
* Attempt to configure the interrupts using the best available
* capabilities of the hardware and the kernel.
**/
static void ixgbe_set_interrupt_capability(struct ixgbe_adapter *adapter)
{
int err;
/* We will try to get MSI-X interrupts first */
if (!ixgbe_acquire_msix_vectors(adapter))
return;
/* At this point, we do not have MSI-X capabilities. We need to
* reconfigure or disable various features which require MSI-X
* capability.
*/
/* Disable DCB unless we only have a single traffic class */
if (netdev_get_num_tc(adapter->netdev) > 1) {
e_dev_warn("Number of DCB TCs exceeds number of available queues. Disabling DCB support.\n");
netdev_reset_tc(adapter->netdev);
if (adapter->hw.mac.type == ixgbe_mac_82598EB)
adapter->hw.fc.requested_mode = adapter->last_lfc_mode;
adapter->flags &= ~IXGBE_FLAG_DCB_ENABLED;
adapter->temp_dcb_cfg.pfc_mode_enable = false;
adapter->dcb_cfg.pfc_mode_enable = false;
}
adapter->dcb_cfg.num_tcs.pg_tcs = 1;
adapter->dcb_cfg.num_tcs.pfc_tcs = 1;
/* Disable SR-IOV support */
e_dev_warn("Disabling SR-IOV support\n");
ixgbe_disable_sriov(adapter);
/* Disable RSS */
e_dev_warn("Disabling RSS support\n");
adapter->ring_feature[RING_F_RSS].limit = 1;
/* recalculate number of queues now that many features have been
* changed or disabled.
*/
ixgbe_set_num_queues(adapter);
adapter->num_q_vectors = 1;
err = pci_enable_msi(adapter->pdev);
if (err)
e_dev_warn("Failed to allocate MSI interrupt, falling back to legacy. Error: %d\n",
err);
else
adapter->flags |= IXGBE_FLAG_MSI_ENABLED;
}
/**
* ixgbe_init_interrupt_scheme - Determine proper interrupt scheme
* @adapter: board private structure to initialize
*
* We determine which interrupt scheme to use based on...
* - Kernel support (MSI, MSI-X)
* - which can be user-defined (via MODULE_PARAM)
* - Hardware queue count (num_*_queues)
* - defined by miscellaneous hardware support/features (RSS, etc.)
**/
int ixgbe_init_interrupt_scheme(struct ixgbe_adapter *adapter)
{
int err;
/* Number of supported queues */
ixgbe_set_num_queues(adapter);
/* Set interrupt mode */
ixgbe_set_interrupt_capability(adapter);
err = ixgbe_alloc_q_vectors(adapter);
if (err) {
e_dev_err("Unable to allocate memory for queue vectors\n");
goto err_alloc_q_vectors;
}
ixgbe_cache_ring_register(adapter);
e_dev_info("Multiqueue %s: Rx Queue count = %u, Tx Queue count = %u\n",
(adapter->num_rx_queues > 1) ? "Enabled" : "Disabled",
adapter->num_rx_queues, adapter->num_tx_queues);
set_bit(__IXGBE_DOWN, &adapter->state);
return 0;
err_alloc_q_vectors:
ixgbe_reset_interrupt_capability(adapter);
return err;
}
/**
* ixgbe_clear_interrupt_scheme - Clear the current interrupt scheme settings
* @adapter: board private structure to clear interrupt scheme on
*
* We go through and clear interrupt specific resources and reset the structure
* to pre-load conditions
**/
void ixgbe_clear_interrupt_scheme(struct ixgbe_adapter *adapter)
{
adapter->num_tx_queues = 0;
adapter->num_rx_queues = 0;
ixgbe_free_q_vectors(adapter);
ixgbe_reset_interrupt_capability(adapter);
}
void ixgbe_tx_ctxtdesc(struct ixgbe_ring *tx_ring, u32 vlan_macip_lens,
u32 fcoe_sof_eof, u32 type_tucmd, u32 mss_l4len_idx)
{
struct ixgbe_adv_tx_context_desc *context_desc;
u16 i = tx_ring->next_to_use;
context_desc = IXGBE_TX_CTXTDESC(tx_ring, i);
i++;
tx_ring->next_to_use = (i < tx_ring->count) ? i : 0;
/* set bits to identify this as an advanced context descriptor */
type_tucmd |= IXGBE_TXD_CMD_DEXT | IXGBE_ADVTXD_DTYP_CTXT;
context_desc->vlan_macip_lens = cpu_to_le32(vlan_macip_lens);
context_desc->seqnum_seed = cpu_to_le32(fcoe_sof_eof);
context_desc->type_tucmd_mlhl = cpu_to_le32(type_tucmd);
context_desc->mss_l4len_idx = cpu_to_le32(mss_l4len_idx);
}
| {
"content_hash": "de0b8dc091ab4155ccecd872a700568a",
"timestamp": "",
"source": "github",
"line_count": 1195,
"max_line_length": 95,
"avg_line_length": 28.0744769874477,
"alnum_prop": 0.6613609943664491,
"repo_name": "AlbandeCrevoisier/ldd-athens",
"id": "bcdc88444cebeb2762f8634210556ce87a8c9961",
"size": "34753",
"binary": false,
"copies": "95",
"ref": "refs/heads/master",
"path": "linux-socfpga/drivers/net/ethernet/intel/ixgbe/ixgbe_lib.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "10184236"
},
{
"name": "Awk",
"bytes": "40418"
},
{
"name": "Batchfile",
"bytes": "81753"
},
{
"name": "C",
"bytes": "566858455"
},
{
"name": "C++",
"bytes": "21399133"
},
{
"name": "Clojure",
"bytes": "971"
},
{
"name": "Cucumber",
"bytes": "5998"
},
{
"name": "FORTRAN",
"bytes": "11832"
},
{
"name": "GDB",
"bytes": "18113"
},
{
"name": "Groff",
"bytes": "2686457"
},
{
"name": "HTML",
"bytes": "34688334"
},
{
"name": "Lex",
"bytes": "56961"
},
{
"name": "Logos",
"bytes": "133810"
},
{
"name": "M4",
"bytes": "3325"
},
{
"name": "Makefile",
"bytes": "1685015"
},
{
"name": "Objective-C",
"bytes": "920162"
},
{
"name": "Perl",
"bytes": "752477"
},
{
"name": "Perl6",
"bytes": "3783"
},
{
"name": "Python",
"bytes": "533352"
},
{
"name": "Shell",
"bytes": "468244"
},
{
"name": "SourcePawn",
"bytes": "2711"
},
{
"name": "UnrealScript",
"bytes": "12824"
},
{
"name": "XC",
"bytes": "33970"
},
{
"name": "XS",
"bytes": "34909"
},
{
"name": "Yacc",
"bytes": "113516"
}
],
"symlink_target": ""
} |
import $ from 'jquery';
import { clearStyles } from '../util';
export default function () {
let jews = {};
jews.title = $('#articleWrap h2').text() || $('#articleWrap h1').text() || undefined;
jews.subtitle = $('.article .stit strong b').text() || undefined;
jews.content = (function () {
var content = $('.article')[0].cloneNode(true);
$('.stit, .banner-0-wrap, .article_ban, .adrs', content).remove();
return clearStyles(content).innerHTML;
})();
jews.timestamp = {
created: new Date($('.article .adrs .pblsh').text().replace(/\s*송고/, '')),
lastModified: undefined
};
jews.reporters = [];
return jews;
}
| {
"content_hash": "cfa55fde57a00eacbae5426c9ba4c642",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 89,
"avg_line_length": 35.94736842105263,
"alnum_prop": 0.5710102489019033,
"repo_name": "teslamint/jews",
"id": "40453f2b4d580066bb15dab03d3bb60f2ba99717",
"size": "687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/impl/연합뉴스.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "99181"
}
],
"symlink_target": ""
} |
package com.google.drive.samples.dredit.model;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;
import com.google.api.services.drive.model.File.Labels;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.Reader;
import java.util.List;
/**
* An object representing a File and its content, for use while interacting
* with a DrEdit JavaScript client. Can be serialized and deserialized using
* Gson.
*
* @author vicfryzel@google.com (Vic Fryzel)
* @author nivco@google.com (Nicolas Garnier)
*/
public class ClientFile {
/**
* ID of file.
*/
public String resource_id;
/**
* Title of file.
*/
public String title;
/**
* Description of file.
*/
public String description;
/**
* MIME type of file.
*/
public String mimeType;
/**
* Content body of file.
*/
public String content;
/**
* Is the file editable.
*/
public boolean editable;
/**
* Labels.
*/
public Labels labels;
/**
* parents.
*/
public List<ParentReference> parents;
/**
* Empty constructor required by Gson.
*/
public ClientFile() {}
/**
* Creates a new ClientFile based on the given File and content.
*/
public ClientFile(File file, String content) {
this.resource_id = file.getId();
this.title = file.getTitle();
this.description = file.getDescription();
this.mimeType = file.getMimeType();
this.content = content;
this.labels = file.getLabels();
this.editable = file.getEditable();
this.parents = file.getParents();
}
/**
* Construct a new ClientFile from its JSON representation.
*
* @param in Reader of JSON string to parse.
*/
public ClientFile(Reader in) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
ClientFile other = gson.fromJson(in, ClientFile.class);
this.resource_id = other.resource_id;
this.title = other.title;
this.description = other.description;
this.mimeType = other.mimeType;
this.content = other.content;
this.labels = other.labels;
this.editable = other.editable;
this.parents = other.parents;
}
/**
* @return Representation of this ClientFile as a Drive file.
*/
public File toFile() {
File file = new File();
file.setId(resource_id);
file.setTitle(title);
file.setDescription(description);
file.setMimeType(mimeType);
file.setLabels(labels);
file.setEditable(editable);
file.setParents(parents);
return file;
}
}
| {
"content_hash": "12e450814ca129f74f7eaa146321c222",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 76,
"avg_line_length": 22.434782608695652,
"alnum_prop": 0.6647286821705426,
"repo_name": "googlearchive/drive-dredit",
"id": "a35165f0294602c2d3c8be7e10e1bf33ae418c02",
"size": "3168",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "java/src/com/google/drive/samples/dredit/model/ClientFile.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "98"
},
{
"name": "ApacheConf",
"bytes": "100"
},
{
"name": "C",
"bytes": "4073"
},
{
"name": "C#",
"bytes": "39197"
},
{
"name": "C++",
"bytes": "2926"
},
{
"name": "CSS",
"bytes": "792"
},
{
"name": "HTML",
"bytes": "2381"
},
{
"name": "Java",
"bytes": "152225"
},
{
"name": "JavaScript",
"bytes": "7045272"
},
{
"name": "Objective-C",
"bytes": "1358858"
},
{
"name": "PHP",
"bytes": "1546336"
},
{
"name": "Python",
"bytes": "488863"
},
{
"name": "Ruby",
"bytes": "5943"
}
],
"symlink_target": ""
} |
<!--
~ Copyright 2014 Miroslav Jaros
~
~ 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.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- **************************************************************** -->
<!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * -->
<!-- * i.e. only iterate & print data where possible. Thanks, Jez. * -->
<!-- **************************************************************** -->
<html>
<head>
<!-- Generated by groovydoc (2.0.6) on Fri May 09 23:50:49 CEST 2014 -->
<title>Initialize (Groovy Documentation)</title>
<meta name="date" content="2014-05-09">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript">
function windowTitle() {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title = "Initialize (Groovy Documentation)";
}
}
</script>
<noscript>
</noscript>
</head>
<body onload="windowTitle();" bgcolor="white">
<hr>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../overview-summary.html"><FONT
CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="package-summary.html"><FONT
CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>
</TD>
<!--<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
-->
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../deprecated-list.html"><FONT
CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../index-all.html"><FONT
CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"><A HREF="../../help-doc.html"><FONT
CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Groovy Documentation</b>
</EM></TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><!--<FONT SIZE="-2">
<A HREF="../../groovy/lang/ExpandoMetaClass.ExpandoMetaProperty.html" title="class in groovy.lang"><B>PREV CLASS</B></A>
<A HREF="../../groovy/lang/GroovyClassLoader.html" title="class in groovy.lang"><B>NEXT CLASS</B></A></FONT>--></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../index.html?griffon-app/lifecycle/Initialize.html" target="_top"><B>FRAMES</B></A>
<A HREF="Initialize.html" target="_top"><B>NO FRAMES</B></A>
<script type="text/javascript">
<!--
if (window == top) {
document.writeln('<A HREF="../../allclasses-frame.html"><B>All Classes</B></A>');
}
//-->
</script>
<noscript>
<A HREF="../../allclasses-frame.html"><B>All Classes</B></A>
</noscript>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | METHOD</FONT>
</TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | METHOD</FONT></TD>
</TR>
</TABLE>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
griffon-app.lifecycle</FONT>
<BR>
<span CLASS="ClassTitleFont">[Groovy] Class Initialize</span></H2>
<pre>java.lang.Object
<img src='../../inherit.gif'>griffon-app.lifecycle.Initialize
</pre>
<hr>
<PRE>class Initialize
</PRE>
<!-- =========== NESTED CLASS SUMMARY =========== -->
<A NAME="nested_summary"><!-- --></A>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<A NAME="enum_constant_summary"><!-- --></A>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<!-- =========== PROPERTY SUMMARY =========== -->
<A NAME="property_summary"><!-- --></A>
<!-- =========== ELEMENT SUMMARY =========== -->
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#D5D5FF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD>
<CODE><B><a href="#Initialize()">Initialize</a></B>()</CODE>
<BR>
<P></P>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2" CLASS="ClassHeadingFont">
<B>Method Summary</B></FONT></TH>
</TR>
</table>
<table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<tr CLASS="TableSubHeadingColor">
<th ALIGN="left" COLSPAN="2">
<b>Methods inherited from class java.lang.Object</b>
</th>
</tr>
<tr class="TableRowColor">
<td colspan='2'>java.lang.Object#wait(long, int), java.lang.Object#wait(long), java.lang.Object#wait(),
java.lang.Object#equals(java.lang.Object), java.lang.Object#toString(), java.lang.Object#hashCode(),
java.lang.Object#getClass(), java.lang.Object#notify(), java.lang.Object#notifyAll()
</td>
</tr>
</table>
<P>
<!-- ============ ENUM CONSTANT DETAIL ========== -->
<A NAME="enum_constant_detail"><!-- --></A>
<!-- =========== FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<!-- =========== PROPERTY DETAIL =========== -->
<A NAME="prop_detail"><!-- --></A>
<!-- =========== ELEMENT DETAIL =========== -->
<A NAME="element_detail"><!-- --></A>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="Initialize()"><!-- --></A>
<H3>
Initialize</H3>
<PRE><B>Initialize</B>()</PRE>
<DL>
<DD>
</DD>
<P>
</DL>
<HR>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<!-- ========= END OF CLASS DATA ========= -->
<p>Groovy Documentation</p>
<hr>
</body>
</html>
| {
"content_hash": "2abb3dd63b82193cce513fa28280d1c9",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 157,
"avg_line_length": 33.26744186046512,
"alnum_prop": 0.518350227193289,
"repo_name": "xjaros1/AsistantTest",
"id": "a4291fcf731cbff2be56e5c16e7971ab13ac10e0",
"size": "8583",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/griffon-app/lifecycle/Initialize.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1917"
},
{
"name": "Groovy",
"bytes": "48903"
},
{
"name": "Shell",
"bytes": "7365"
}
],
"symlink_target": ""
} |
module OneviewCookbook
module API800
module C7000
# LogicalInterconnect API800 C7000 provider
class LogicalInterconnectProvider < API600::C7000::LogicalInterconnectProvider
end
end
end
end
| {
"content_hash": "a021e0e0061570f137ad873a0ec294f3",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 84,
"avg_line_length": 24.333333333333332,
"alnum_prop": 0.7488584474885844,
"repo_name": "HewlettPackard/oneview-chef",
"id": "f0c06fa7716037ff4fecf75cdd6828a991ab8d7f",
"size": "819",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libraries/resource_providers/api800/c7000/logical_interconnect_provider.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1301"
},
{
"name": "Ruby",
"bytes": "873743"
}
],
"symlink_target": ""
} |
namespace NAlgorithms
{
class CMoveDetectBackgroundSubtractorTest: public CAbstractAlertAlgorighm
{
public:
CMoveDetectBackgroundSubtractorTest(
const CMoveDetectBackgroundSubtractorConfig& config,
size_t bufferId,
bool isColor,
const NVideoInput::CAlgoCoeficients& algoCoef);
virtual bool hasAlert(const QList<std::shared_ptr<CMatWithTimeStamp> >& buff) override;
virtual const std::string getAlgorithmName() const override;
bool test(
const cv::Mat& mat1,
const cv::Mat& mat2);
virtual void reset() override;
private:
CMoveDetectBackgroundSubtractorConfig mConfig;
bool mIsColor;
cv::Mat mAvgMat;
};
}
| {
"content_hash": "5ad811ee2fcdd4f1d8db6a5b3fcd0401",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 91,
"avg_line_length": 23.866666666666667,
"alnum_prop": 0.6941340782122905,
"repo_name": "ymuv/CameraAlerts",
"id": "8811cd353dc38d45a6950556e3587bf2b2c5b04f",
"size": "852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Image/motionAlgorithms/CBackgroundSubtractorTest.hpp",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Arduino",
"bytes": "3506"
},
{
"name": "C++",
"bytes": "395324"
},
{
"name": "CMake",
"bytes": "31780"
},
{
"name": "QMake",
"bytes": "236"
},
{
"name": "Shell",
"bytes": "456"
}
],
"symlink_target": ""
} |
import numpy
import os
import sys
from datetime import datetime
from mock import Mock, patch
from StringIO import StringIO
from race_code import race_code_functions as rcf, race_code_globals, settings
from . import FormulaPiTestCase
class TestRace(FormulaPiTestCase):
def setUp(self):
# Patch standard out to capture the string for testing.
self.original_stdout = sys.stdout
self.out = StringIO()
sys.stdout = self.out
def tearDown(self):
# Reset standard out to the original function.
sys.stdout = self.original_stdout
def test_speed(self):
# Test speed above the maximum.
self.assertEqual(rcf.speed(120.0), 1.0)
# Test speed below the minimum.
self.assertEqual(rcf.speed(-30), 0.0)
# Test within the range
self.assertEqual(rcf.speed(19), 0.19)
# Test top of the range
self.assertEqual(rcf.speed(100), 1.0)
# Test bottom of the range
self.assertEqual(rcf.speed(0), 0.0)
def test_log_user_call(self):
# Test with no parameters provided.
rcf.log_user_call(None, None)
self.assertTrue(self.out.getvalue().endswith('test_log_user_call()\n\n'))
# Test with only format string parameter.
rcf.log_user_call('%d', None)
self.assertTrue(self.out.getvalue().endswith('test_log_user_call(%d)\n\n'))
# Test with only tuple parameter provided with single value "tuple".
rcf.log_user_call(None, 1)
self.assertTrue(self.out.getvalue().endswith('test_log_user_call()\n\n'))
# Test with only tuple parameter provided.
rcf.log_user_call(None, (1, 2))
self.assertTrue(self.out.getvalue().endswith('test_log_user_call()\n\n'))
# Test all parameters provided provided with single value "tuple".
rcf.log_user_call('%d', 1)
self.assertTrue(self.out.getvalue().endswith('test_log_user_call(1)\n\n'))
# Test all parameters provided provided.
rcf.log_user_call('%d %d', (1, 2))
self.assertTrue(self.out.getvalue().endswith('test_log_user_call(1 2)\n\n'))
# Test with parameter tuple not matching format.
with self.assertRaises(TypeError) as err:
rcf.log_user_call('%d', 'a')
self.assertEqual(err.exception.message, '%d format: a number is required, not str')
# Test with parameter tuple having an extra element.
with self.assertRaises(TypeError) as err:
rcf.log_user_call('%d', (1, 'a'))
self.assertEqual(
err.exception.message,
'not all arguments converted during string formatting'
)
# Start the log file.
rcf.start_user_log()
rcf.log_user_call(None, None)
self.assertTrue(self.out.getvalue().endswith('test_log_user_call()\n\n'))
file_name = race_code_globals.user_log_file.name
# End the user log so it flushes it to the file.
rcf.end_user_log()
# Open the file manually to check results then delete it,
log_file = open(file_name, 'r')
lines = log_file.readlines()
# The first and third (last) line are opening and closing log comments.
self.assertEqual(len(lines), 3)
self.assertTrue(lines[1].endswith('test_log_user_call()\n'))
log_file.close()
os.remove(file_name)
def test_aim_for_lane(self):
self.assertNotEqual(race_code_globals.user_target_lane, 4)
rcf.aim_for_lane(4)
self.assertEqual(race_code_globals.user_target_lane, 4)
def test_wait_for_waypoint(self):
race_code_globals.running = False
self.assertIsNone(rcf.wait_for_waypoint(2))
self.assertTrue(self.out.getvalue().endswith('wait_for_waypoint(2)\n\n'))
race_code_globals.running = True
self.assertIsNone(rcf.wait_for_waypoint(0))
self.assertTrue(self.out.getvalue().endswith('wait_for_waypoint(0)\n\n'))
race_code_globals.running = True
more_than_settings = len(settings.distance_between_waypoints) + 1
self.assertIsNone(rcf.wait_for_waypoint(more_than_settings))
self.assertTrue(
self.out.getvalue().endswith('wait_for_waypoint(%d)\n\n' % more_than_settings)
)
self.assertIsNone(rcf.wait_for_waypoint(1))
self.assertTrue('wait_for_waypoint(1)\n\n' in self.out.getvalue())
patch_1 = patch('race_code.race_code_functions.wait_for_distance')
patch_1.start()
self.assertIsNone(rcf.wait_for_waypoint(3))
self.assertTrue('wait_for_waypoint(3)\n\n' in self.out.getvalue())
patch_1.stop()
def test_wait_for_distance(self):
race_code_globals.running = False
self.assertIsNone(rcf.wait_for_distance(2))
self.assertTrue(self.out.getvalue().endswith('wait_for_distance(2.000)\n\n'))
race_code_globals.running = True
patch_1 = patch('race_code.race_code_functions.get_distance', new=lambda: 1)
patch_1.start()
self.assertIsNone(rcf.wait_for_distance(1))
self.assertTrue('wait_for_distance(1.000)\n\n' in self.out.getvalue())
patch_1.stop()
patch_1 = patch('race_code.race_code_functions.get_distance', new=lambda: 10)
patch_1.start()
patch_2 = patch('race_code.race_code_functions.lap_count', side_effect=[0, 1])
patch_2.start()
self.assertIsNone(rcf.wait_for_distance(4))
self.assertTrue('wait_for_distance(4.000)\n\n' in self.out.getvalue())
patch_2.stop()
patch_2 = patch('race_code.race_code_functions.lap_count', side_effect=[0, 0, 1])
patch_2.start()
self.assertIsNone(rcf.wait_for_distance(4))
self.assertTrue('wait_for_distance(4.000)\n\n' in self.out.getvalue())
patch_2.stop()
patch_2 = patch('race_code.race_code_functions.lap_count', side_effect=[0, 0, 1])
patch_2.start()
patch_1.stop()
patch_1 = patch('race_code.race_code_functions.get_distance', new=lambda: 9)
patch_1.start()
wait_for_next_lap_after = settings.wait_for_next_lap_after
settings.wait_for_next_lap_after = 10000
self.assertIsNone(rcf.wait_for_distance(10))
self.assertTrue('wait_for_distance(10.000)\n\n' in self.out.getvalue())
settings.wait_for_next_lap_after = wait_for_next_lap_after
patch_2.stop()
patch_1.stop()
def test_lap_count(self):
race_code_globals.running = False
self.assertEqual(rcf.lap_count(), 99999)
self.assertTrue('lap_count()\n\n' in self.out.getvalue())
race_code_globals.running = True
self.assertEqual(rcf.lap_count(), race_code_globals.lap_count)
self.assertTrue('lap_count()\n\n' in self.out.getvalue())
def test_get_distance(self):
race_code_globals.running = False
self.assertEqual(rcf.get_distance(), 99999.9)
self.assertTrue('get_distance()\n\n' in self.out.getvalue())
race_code_globals.running = True
self.assertEqual(rcf.get_distance(), race_code_globals.lap_travelled)
self.assertTrue('get_distance()\n\n' in self.out.getvalue())
def test_track_found(self):
initial_track_found = race_code_globals.track_found
race_code_globals.track_found = False
self.assertEqual(rcf.track_found(), False)
self.assertTrue('track_found()\n\n' in self.out.getvalue())
race_code_globals.track_found = True
self.assertEqual(rcf.track_found(), True)
self.assertTrue('track_found()\n\n' in self.out.getvalue())
race_code_globals.track_found = initial_track_found
def test_current_track_position(self):
self.assertEqual(rcf.current_track_position(), None)
self.assertTrue('track_position()\n\n' in self.out.getvalue())
initial_controller = race_code_globals.controller
m2 = Mock()
m = Mock()
m.last_d0 = m2
race_code_globals.controller = m
self.assertEqual(rcf.current_track_position(), m2)
race_code_globals.controller = initial_controller
def test_end_user_log(self):
self.assertIsNone(race_code_globals.user_log_file)
self.assertIsNone(rcf.end_user_log())
patch_1 = patch('race_code.image_processor.full_time_stamp', new=lambda: 'test')
patch_1.start()
rcf.start_user_log()
self.assertIsNotNone(race_code_globals.user_log_file)
file_path = './logs/User test.txt'
self.assertTrue(os.path.isfile(file_path))
# As the file wont have been closed and flushed we can test if there is any information
# in the actually file itself to determine if it is still open or if it has been closed.
open_file = open(file_path)
self.assertFalse(open_file.readlines())
self.assertIsNone(rcf.end_user_log())
self.assertIsNone(race_code_globals.user_log_file)
self.assertTrue(os.path.isfile(file_path))
# Reset file to the beginning and check there is now data.
open_file.seek(0)
self.assertTrue(open_file.readlines())
os.remove(file_path)
patch_1.stop()
def test_finish_race(self):
initial_running = race_code_globals.running
race_code_globals.running = True
self.assertIsNone(rcf.finish_race())
self.assertTrue('finish_race()\n\n' in self.out.getvalue())
self.assertFalse(race_code_globals.running)
race_code_globals.running = initial_running
def test_get_latest_image(self):
self.assertIsNone(rcf.get_latest_image())
self.assertTrue('get_latest_image()\n\n' in self.out.getvalue())
race_code_globals.last_raw_frame = 'test'
self.assertEqual(rcf.get_latest_image(), 'test')
race_code_globals.last_raw_frame = None
def test_save_image(self):
if os.path.isdir('./logs'):
os.removedirs('./logs')
self.assertFalse(os.path.isdir('./logs'))
self.assertIsNone(rcf.save_image(numpy.array([]), 'test'))
self.assertTrue(os.path.isdir('./logs'))
self.assertTrue(os.path.isfile('./logs/test.jpg'))
self.assertIsNone(rcf.save_image(numpy.array([]), 'test2'))
self.assertTrue(os.path.isfile('./logs/test2.jpg'))
os.remove('./logs/test.jpg')
os.remove('./logs/test2.jpg')
os.removedirs('./logs')
def test_start_user_log(self):
# Test opens a log file when one is not present
self.assertIsNone(race_code_globals.user_log_file)
patch_1 = patch('race_code.image_processor.full_time_stamp', new=lambda: 'test')
patch_1.start()
self.assertIsNone(rcf.start_user_log())
self.assertIsNotNone(race_code_globals.user_log_file)
self.assertTrue(os.path.isfile('./logs/User test.txt'))
self.assertTrue('start_user_log()\n\n' in self.out.getvalue())
patch_1.stop()
# Test that it closes an open log file and opens it again
self.assertIsNotNone(race_code_globals.user_log_file)
patch_1 = patch('race_code.image_processor.full_time_stamp', new=lambda: 'test2')
patch_1.start()
self.assertIsNone(rcf.start_user_log())
self.assertIsNotNone(race_code_globals.user_log_file)
self.assertTrue(os.path.isfile('./logs/User test.txt'))
self.assertTrue(os.path.isfile('./logs/User test2.txt'))
patch_1.stop()
rcf.end_user_log()
# Test when `logs` directory is not present
os.remove('./logs/User test.txt')
os.remove('./logs/User test2.txt')
os.removedirs('./logs')
self.assertIsNone(race_code_globals.user_log_file)
patch_1 = patch('race_code.image_processor.full_time_stamp', new=lambda: 'test')
patch_1.start()
self.assertIsNone(rcf.start_user_log())
self.assertIsNotNone(race_code_globals.user_log_file)
self.assertTrue(os.path.isfile('./logs/User test.txt'))
patch_1.stop()
rcf.end_user_log()
# Test when the file cannot be opened / created
os.remove('./logs/User test.txt')
os.removedirs('./logs')
def raise_err(x):
raise IOError
patch_1 = patch('os.mkdir', new=raise_err)
patch_1.start()
self.assertIsNone(rcf.start_user_log())
self.assertIsNone(race_code_globals.user_log_file)
self.assertFalse(os.path.isdir('./logs'))
self.assertTrue('Failed to start user logging!\n\n' in self.out.getvalue())
patch_1.stop()
def test_wait_for_go(self):
initial_running = race_code_globals.running
# Race is not running so do nothing!
race_code_globals.running = False
self.assertIsNone(rcf.wait_for_go())
self.assertTrue('wait_for_go()\n\n' in self.out.getvalue())
race_code_globals.running = True
def turn_off_running(x):
race_code_globals.running = False
with patch('time.sleep', new=turn_off_running):
self.assertIsNone(rcf.wait_for_go())
self.assertTrue('wait_for_go()\n\n' in self.out.getvalue())
self.assertEqual(race_code_globals.image_mode, 2)
race_code_globals.running = initial_running
def test_wait_for_seconds(self):
start_time = datetime.now()
self.assertIsNone(rcf.wait_for_seconds(2))
end_time = datetime.now()
self.assertTrue((end_time - start_time).total_seconds() > 2)
self.assertTrue('wait_for_seconds(2.000)\n\n' in self.out.getvalue())
| {
"content_hash": "f90d9d99572e60986959540dfb79c383",
"timestamp": "",
"source": "github",
"line_count": 331,
"max_line_length": 96,
"avg_line_length": 40.96978851963746,
"alnum_prop": 0.6319592950372391,
"repo_name": "amorphic/sparkcc-formulapi",
"id": "d767622de8d7d474c32b2dd51fb0ae663af8fa32",
"size": "13561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_race_code_functions.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "135775"
},
{
"name": "Shell",
"bytes": "439"
}
],
"symlink_target": ""
} |
#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
#include "hdbc-sqlite3-helper.h"
int sqlite3_bind_text2(sqlite3_stmt* a, int b, const char *c, int d) {
return sqlite3_bind_text(a, b, c, d, SQLITE_TRANSIENT);
}
/* Sqlite things can't finalize more than once.
We'd like to let people call them from the app to get the error, if any.
Yet we'd also like to be able to have a ForeignPtr finalize them.
So, here's a little wrapper for things. */
int sqlite3_open2(const char *filename, finalizeonce **ppo) {
sqlite3 *ppDb;
finalizeonce *newobj;
int res;
res = sqlite3_open(filename, &ppDb);
newobj = malloc(sizeof(finalizeonce));
if (newobj == NULL) {
fprintf(stderr, "\nhdbc sqlite internal error: couldn't malloc memory for newobj\n");
return -999;
}
newobj->encapobj = (void *) ppDb;
newobj->isfinalized = 0;
newobj->refcount = 1;
newobj->parent = NULL;
*ppo = newobj;
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nAllocated db at %p %p\n", newobj, newobj->encapobj);
#endif
return res;
}
int sqlite3_close_app(finalizeonce *ppdb) {
int res;
if (ppdb->isfinalized) {
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nclose_app on already finalized %p\n", ppdb);
#endif
return SQLITE_OK;
}
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nclose_app on non-finalized %p\n", ppdb);
#endif
res = sqlite3_close((sqlite3 *) (ppdb->encapobj));
ppdb->isfinalized = 1;
return res;
}
void sqlite3_close_finalizer(finalizeonce *ppdb) {
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nclose_finalizer on %p: %d\n", ppdb, ppdb->isfinalized);
#endif
(ppdb->refcount)--;
sqlite3_conditional_finalizer(ppdb);
}
void sqlite3_conditional_finalizer(finalizeonce *ppdb) {
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\ncond finalizer on %p: refcount %d\n", ppdb, ppdb->refcount);
#endif
if (ppdb->refcount < 1) {
sqlite3_close_app(ppdb);
free(ppdb);
}
}
void sqlite3_busy_timeout2(finalizeonce *ppdb, int ms) {
sqlite3 *db;
db = (sqlite3 *) ppdb->encapobj;
sqlite3_busy_timeout(db, ms);
}
int sqlite3_prepare2(finalizeonce *fdb, const char *zSql,
int nBytes, finalizeonce **ppo,
const char **pzTail) {
sqlite3_stmt *ppst;
sqlite3 *db;
finalizeonce *newobj;
int res;
db = (sqlite3 *) fdb->encapobj;
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nCalling prepare on %p", db);
#endif
#if SQLITE_VERSION_NUMBER > 3003011
res = sqlite3_prepare_v2(db, zSql, nBytes, &ppst,
pzTail);
#else
res = sqlite3_prepare(db, zSql, nBytes, &ppst,
pzTail);
#endif
/* We don't try to deallocate this in Haskell if there
was an error. */
if (res != SQLITE_OK) {
if (ppst != NULL) {
sqlite3_finalize(ppst);
}
return res;
}
newobj = malloc(sizeof(finalizeonce));
if (newobj == NULL) {
fprintf(stderr, "\nhdbc sqlite3 internal error: couldn't malloc memory for newobj\n");
return -999;
}
newobj->encapobj = (void *) ppst;
newobj->isfinalized = 0;
newobj->parent = fdb;
newobj->refcount = 1;
(fdb->refcount)++;
*ppo = newobj;
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nAllocated stmt at %p %p\n", newobj, newobj->encapobj);
#endif
return res;
}
int sqlite3_finalize_app(finalizeonce *ppst) {
int res;
if (ppst->isfinalized) {
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nfinalize_app on already finalized %p\n", ppst);
#endif
return SQLITE_OK;
}
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nfinalize_app on non-finalized %p\n", ppst);
#endif
res = sqlite3_finalize((sqlite3_stmt *) (ppst->encapobj));
ppst->isfinalized = 1;
return res;
}
void sqlite3_finalize_finalizer(finalizeonce *ppst) {
#ifdef DEBUG_HDBC_SQLITE3
fprintf(stderr, "\nfinalize_finalizer on %p: %d\n", ppst, ppst->isfinalized);
#endif
sqlite3_finalize_app(ppst);
(ppst->refcount)--; /* Not really important since no children use
us */
/* Now decrement the refcount for the parent */
(ppst->parent->refcount)--;
sqlite3_conditional_finalizer(ppst->parent);
free(ppst);
}
| {
"content_hash": "0a4a6e9892538e6c0bddf3450d5d872c",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 90,
"avg_line_length": 26.634615384615383,
"alnum_prop": 0.6553549939831528,
"repo_name": "hdbc/hdbc-sqlite3",
"id": "502185a04b7f8e1594d5f38ad323d00a5b38cd77",
"size": "4155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hdbc-sqlite3-helper.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5123"
},
{
"name": "Haskell",
"bytes": "54573"
},
{
"name": "Makefile",
"bytes": "957"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Ui\Test\Unit\Component\Filters\Type;
use Magento\Framework\View\Element\UiComponent\ContextInterface as UiContext;
use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Filters\Type\Range;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
/**
* Class RangeTest
*/
class RangeTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ContextInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $contextMock;
/**
* @var UiComponentFactory|\PHPUnit_Framework_MockObject_MockObject
*/
protected $uiComponentFactory;
/**
* @var \Magento\Framework\Api\FilterBuilder|\PHPUnit_Framework_MockObject_MockObject
*/
protected $filterBuilderMock;
/**
* @var \Magento\Ui\Component\Filters\FilterModifier|\PHPUnit_Framework_MockObject_MockObject
*/
protected $filterModifierMock;
/**
* Set up
*/
protected function setUp()
{
$this->contextMock = $this->getMockForAbstractClass(
'Magento\Framework\View\Element\UiComponent\ContextInterface',
[],
'',
false
);
$processor = $this->getMockBuilder('Magento\Framework\View\Element\UiComponent\Processor')
->disableOriginalConstructor()
->getMock();
$this->contextMock->expects($this->any())->method('getProcessor')->willReturn($processor);
$this->uiComponentFactory = $this->getMock(
'Magento\Framework\View\Element\UiComponentFactory',
[],
[],
'',
false
);
$this->filterBuilderMock = $this->getMock(
'Magento\Framework\Api\FilterBuilder',
[],
[],
'',
false
);
$this->filterModifierMock = $this->getMock(
'Magento\Ui\Component\Filters\FilterModifier',
['applyFilterModifier'],
[],
'',
false
);
}
/**
* Run test getComponentName method
*
* @return void
*/
public function testGetComponentName()
{
$range = new Range(
$this->contextMock,
$this->uiComponentFactory,
$this->filterBuilderMock,
$this->filterModifierMock,
[]
);
$this->assertTrue($range->getComponentName() === Range::NAME);
}
/**
* Run test prepare method
*
* @param string $name
* @param array $filterData
* @param array|null $expectedCondition
* @dataProvider getPrepareDataProvider
* @return void
*/
public function testPrepare($name, $filterData, $expectedCondition)
{
$this->contextMock->expects($this->any())
->method('getNamespace')
->willReturn(Range::NAME);
$this->contextMock->expects($this->any())
->method('addComponentDefinition')
->with(Range::NAME, ['extends' => Range::NAME]);
$this->contextMock->expects($this->any())
->method('getRequestParam')
->with(UiContext::FILTER_VAR)
->willReturn($filterData);
/** @var DataProviderInterface $dataProvider */
$dataProvider = $this->getMockForAbstractClass(
'Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface',
[],
'',
false
);
$this->contextMock->expects($this->any())
->method('getDataProvider')
->willReturn($dataProvider);
if ($expectedCondition !== null) {
$dataProvider->expects($this->any())
->method('addFilter')
->with($expectedCondition, $name);
}
$range = new Range(
$this->contextMock,
$this->uiComponentFactory,
$this->filterBuilderMock,
$this->filterModifierMock,
[],
['name' => $name]
);
$range->prepare();
}
/**
* @return array
*/
public function getPrepareDataProvider()
{
return [
[
'test_date',
['test_date' => ['from' => 0, 'to' => 1]],
['from' => null, 'orig_from' => 0, 'to' => 1],
],
[
'test_date',
['test_date' => ['from' => '', 'to' => 2]],
['from' => null, 'orig_from' => '', 'to' => 2],
],
[
'test_date',
['test_date' => ['from' => 1, 'to' => '']],
['from' => 1, 'orig_to' => '', 'to' => null],
],
[
'test_date',
['test_date' => ['from' => 1, 'to' => 0]],
['from' => 1, 'orig_to' => 0, 'to' => null],
],
[
'test_date',
['test_date' => ['from' => 1, 'to' => 2]],
['from' => 1, 'to' => 2],
],
[
'test_date',
['test_date' => ['from' => '', 'to' => '']],
null,
],
[
'test_date',
['test_date' => []],
null,
],
];
}
}
| {
"content_hash": "561cc9ce909484e00e6b9c0efd6acb7d",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 98,
"avg_line_length": 29.530054644808743,
"alnum_prop": 0.4933382679496669,
"repo_name": "enettolima/magento-training",
"id": "02c1092313c4ff38eebdb07ec81ef74eca51a558",
"size": "5502",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "magento2ce/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/RangeTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "22648"
},
{
"name": "CSS",
"bytes": "3382928"
},
{
"name": "HTML",
"bytes": "8749335"
},
{
"name": "JavaScript",
"bytes": "7355635"
},
{
"name": "PHP",
"bytes": "58607662"
},
{
"name": "Perl",
"bytes": "10258"
},
{
"name": "Shell",
"bytes": "41887"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
package com.taxisurfr.server.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.taxisurfr.server.entity.Agent;
import com.taxisurfr.server.entity.Booking;
import com.taxisurfr.server.entity.Contractor;
import com.taxisurfr.server.entity.Route;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.google.common.io.Files;
import com.taxisurfr.shared.model.AgentInfo;
import com.taxisurfr.shared.model.BookingInfo;
import com.taxisurfr.shared.model.ContractorInfo;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
public class PdfUtil
{
public final static String FORMDATE = "FormDate";
public final static String ORDERNO = "OrderNo";
public final static String NAME = "Name";
public final static String EMAIL = "Email";
public final static String PAX = "Passengers";
public final static String SURFBOARDS = "Surfboards";
public final static String DATE = "Date";
public final static String FLIGHTNO = "FlightNo";
public final static String LANDINGTIME = "LandingTime";
public final static String PAID = "Paid";
public final static String OTHER1 = "Other1";
public final static String OTHER2 = "Other2";
public final static String OTHER3 = "Other3";
public final static String ARRIVAL = "Arrival";
public final static String FLIGHT_HOTEL = "Flight_Hotel";
static final DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy");
static final DateTimeFormatter fmtFormDate = DateTimeFormat.forPattern("dd MMM yyyy");
static final float TABLE_WIDTH = 452;
static final float TABLE_Y = 400;
static final float INSET = 72;
static final String CUSTOMER_FEEDBACK = "BTW. You will receive a link for feedback shortly after your trip. Taking a few minutes to answer this will help us greatly. Thank you in advance.";
@Deprecated
public byte[] generateTaxiOrder(String path, BookingInfo bookingInfo, AgentInfo agentInfo, ContractorInfo contractorInfo)
{
PdfReader reader;
final FileInputStream fis;
try
{
fis = new FileInputStream(path);
reader = new PdfReader(IOUtils.toByteArray(fis));
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, out);
PdfContentByte canvas = stamper.getOverContent(1);
PdfPTable table = createBookingTable(bookingInfo);
table.writeSelectedRows(0, 2, 0, 11, INSET, TABLE_Y, canvas);
Font helvetica20 = new Font(FontFamily.HELVETICA, 20);
Font helvetica14 = new Font(FontFamily.HELVETICA, 14);
BaseFont bf_helv = helvetica20.getCalculatedBaseFont(false);
// route
int addressY = 430;
Chunk chunk = new Chunk(bookingInfo.getRouteInfo().getKey(""), helvetica20);
ColumnText.showTextAligned(canvas,
Element.ALIGN_LEFT, new Phrase(chunk), INSET, addressY, 0);
addressY = 564;
// agent
chunk = new Chunk(agentInfo.getEmail(), helvetica14);
ColumnText.showTextAligned(canvas,
Element.ALIGN_LEFT, new Phrase(chunk), INSET + 120, addressY, 0);
String address = "";
for (String contractorAddress : contractorInfo.getAddress())
{
address += contractorAddress + " ";
}
addressY -= 42;
chunk = new Chunk(address, helvetica14);
ColumnText.showTextAligned(canvas,
Element.ALIGN_LEFT, new Phrase(chunk), INSET, addressY, 0);
stamper.close();
reader.close();
fis.close();
return out.toByteArray();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public byte[] generateTaxiOrder(String path, Booking booking, Route route, Agent agent, Contractor contractor)
{
PdfReader reader;
final FileInputStream fis;
try
{
fis = new FileInputStream(path);
reader = new PdfReader(IOUtils.toByteArray(fis));
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, out);
PdfContentByte canvas = stamper.getOverContent(1);
PdfPTable table = createBookingTable(booking,route);
table.writeSelectedRows(0, 2, 0, 11, INSET, TABLE_Y, canvas);
Font helvetica20 = new Font(FontFamily.HELVETICA, 20);
Font helvetica14 = new Font(FontFamily.HELVETICA, 14);
BaseFont bf_helv = helvetica20.getCalculatedBaseFont(false);
// route
int addressY = 430;
Chunk chunk = new Chunk(route.getStart()+" to "+route.getEnd(), helvetica20);
ColumnText.showTextAligned(canvas,
Element.ALIGN_LEFT, new Phrase(chunk), INSET, addressY, 0);
addressY = 564;
// agent
if (agent.getEmail() != null) {
chunk = new Chunk(agent.getEmail(), helvetica14);
ColumnText.showTextAligned(canvas,
Element.ALIGN_LEFT, new Phrase(chunk), INSET + 120, addressY, 0);
}
if (contractor.getAddress() != null) {
String address = "";
for (String contractorAddress : contractor.getAddress()) {
address += contractorAddress + " ";
}
addressY -= 42;
chunk = new Chunk(address, helvetica14);
ColumnText.showTextAligned(canvas,
Element.ALIGN_LEFT, new Phrase(chunk), INSET, addressY, 0);
}
stamper.close();
reader.close();
fis.close();
return out.toByteArray();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static byte[] get()
{
File f = new File("template/test.pdf");
try
{
return Files.toByteArray(f);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Deprecated
public PdfPTable createBookingTable(BookingInfo bookingInfo)
{
PdfPTable table = new PdfPTable(2);
table.setTotalWidth(TABLE_WIDTH);
table.setWidthPercentage(TABLE_WIDTH / 3f);
try
{
table.setWidths(new int[] { 1, 2 });
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// the cell object
PdfPCell cell;
table.addCell(ORDERNO);
table.addCell(bookingInfo.getOrderRef());
table.addCell(NAME);
table.addCell(bookingInfo.getName());
table.addCell(EMAIL);
table.addCell(bookingInfo.getEmail());
table.addCell(PAX);
table.addCell("" + bookingInfo.getPax());
table.addCell(SURFBOARDS);
table.addCell("" + bookingInfo.getSurfboards());
table.addCell(DATE);
table.addCell(fmt.print(new DateTime((bookingInfo.getDate()))));
table.addCell(bookingInfo.getRouteInfo().getPickupType().getLocationType());
table.addCell(bookingInfo.getFlightNo());
table.addCell(bookingInfo.getRouteInfo().getPickupType().getTimeType());
table.addCell(bookingInfo.getLandingTime());
table.addCell(PAID);
table.addCell(bookingInfo.getCurrency().symbol + " " + bookingInfo.getPaidPrice());
table.addCell("Other requirements");
table.addCell(bookingInfo.getRequirements());
return table;
}
public PdfPTable createBookingTable(Booking booking, Route route)
{
PdfPTable table = new PdfPTable(2);
table.setTotalWidth(TABLE_WIDTH);
table.setWidthPercentage(TABLE_WIDTH / 3f);
try
{
table.setWidths(new int[] { 1, 2 });
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// the cell object
PdfPCell cell;
table.addCell(ORDERNO);
table.addCell(booking.getRef());
table.addCell(NAME);
table.addCell(booking.getName());
table.addCell(EMAIL);
table.addCell(booking.getEmail());
table.addCell(PAX);
table.addCell("" + booking.getPax());
table.addCell(SURFBOARDS);
table.addCell("" + booking.getSurfboards());
table.addCell(DATE);
table.addCell(booking.getDateText());
table.addCell(route.getPickupType().getLocationType());
table.addCell(booking.getFlightNo());
table.addCell(route.getPickupType().getTimeType());
table.addCell(booking.getLandingTime());
table.addCell(PAID);
table.addCell(booking.getCurrency().symbol + " " + booking.getPaidPrice());
table.addCell("Other requirements");
table.addCell(booking.getRequirements());
return table;
}
}
| {
"content_hash": "e5d5dca3f05b2d9644577e5d814df5ed",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 193,
"avg_line_length": 35.1986301369863,
"alnum_prop": 0.6164623467600701,
"repo_name": "peterredmondhall/taxisurfr",
"id": "2a93fd77baa99d59b26ac9bcba1ba0a65e6bedcf",
"size": "10278",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/taxisurfr/server/util/PdfUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "806"
},
{
"name": "CSS",
"bytes": "11932"
},
{
"name": "HTML",
"bytes": "194124"
},
{
"name": "Java",
"bytes": "409959"
},
{
"name": "JavaScript",
"bytes": "673"
}
],
"symlink_target": ""
} |
package org.kwstudios.play.ragemode.signs;
import java.io.File;
import java.io.IOException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.kwstudios.play.ragemode.loader.PluginLoader;
public class SignConfiguration {
private static boolean inited = false;
private static File yamlSignsFile;
private static FileConfiguration signConfiguration;
public static void initSignConfiguration() {
if (inited)
return;
else
inited = true;
File file = new File(PluginLoader.getInstance().getDataFolder(), "signs.yml");
YamlConfiguration config = null;
yamlSignsFile = file;
if (!file.exists()) {
file.getParentFile().mkdirs();
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
config = new YamlConfiguration();
config.createSection("data");
try {
config.save(file);
} catch (IOException e2) {
e2.printStackTrace();
}
} else {
config = YamlConfiguration.loadConfiguration(file);
}
signConfiguration = config;
try {
config.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
public static File getYamlSignsFile() {
return yamlSignsFile;
}
public static FileConfiguration getSignConfiguration() {
return signConfiguration;
}
}
| {
"content_hash": "676ee4234fbb821edac7843527a5204d",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 80,
"avg_line_length": 21.22222222222222,
"alnum_prop": 0.7180254300673149,
"repo_name": "KWStudios/RageMode",
"id": "afad6d807ca2288069652e06b3c628dfcd3d0488",
"size": "1337",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/kwstudios/play/ragemode/signs/SignConfiguration.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "291779"
},
{
"name": "Shell",
"bytes": "1120"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Sales\Model\Order\Creditmemo\Total;
use Magento\Framework\Pricing\PriceCurrencyInterface;
/**
* Order creditmemo shipping total calculation model
*/
class Shipping extends AbstractTotal
{
/**
* @var PriceCurrencyInterface
*/
protected $priceCurrency;
/**
* @param PriceCurrencyInterface $priceCurrency
* @param array $data
*/
public function __construct(
PriceCurrencyInterface $priceCurrency,
array $data = []
) {
parent::__construct($data);
$this->priceCurrency = $priceCurrency;
}
/**
* @param \Magento\Sales\Model\Order\Creditmemo $creditmemo
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function collect(\Magento\Sales\Model\Order\Creditmemo $creditmemo)
{
$order = $creditmemo->getOrder();
$allowedAmount = $order->getShippingAmount() - $order->getShippingRefunded();
$baseAllowedAmount = $order->getBaseShippingAmount() - $order->getBaseShippingRefunded();
$orderShippingAmount = $order->getShippingAmount();
$orderBaseShippingAmount = $order->getBaseShippingAmount();
$orderShippingInclTax = $order->getShippingInclTax();
$orderBaseShippingInclTax = $order->getBaseShippingInclTax();
$shippingAmount = $baseShippingAmount = $shippingInclTax = $baseShippingInclTax = 0;
/**
* Check if shipping amount was specified (from invoice or another source).
* Using has magic method to allow setting 0 as shipping amount.
*/
if ($creditmemo->hasBaseShippingAmount()) {
$baseShippingAmount = $this->priceCurrency->round($creditmemo->getBaseShippingAmount());
/*
* Rounded allowed shipping refund amount is the highest acceptable shipping refund amount.
* Shipping refund amount shouldn't cause errors, if it doesn't exceed that limit.
* Note: ($x < $y + 0.0001) means ($x <= $y) for floats
*/
if ($baseShippingAmount < $this->priceCurrency->round($baseAllowedAmount) + 0.0001) {
$ratio = 0;
if ($orderBaseShippingAmount > 0) {
$ratio = $baseShippingAmount / $orderBaseShippingAmount;
}
/*
* Shipping refund amount should be equated to allowed refund amount,
* if it exceeds that limit.
* Note: ($x > $y - 0.0001) means ($x >= $y) for floats
*/
if ($baseShippingAmount > $baseAllowedAmount - 0.0001) {
$shippingAmount = $allowedAmount;
$baseShippingAmount = $baseAllowedAmount;
} else {
$shippingAmount = $this->priceCurrency->round($orderShippingAmount * $ratio);
}
$shippingInclTax = $this->priceCurrency->round($orderShippingInclTax * $ratio);
$baseShippingInclTax = $this->priceCurrency->round($orderBaseShippingInclTax * $ratio);
} else {
$baseAllowedAmount = $order->getBaseCurrency()->format($baseAllowedAmount, null, false);
throw new \Magento\Framework\Exception\LocalizedException(
__('Maximum shipping amount allowed to refund is: %1', $baseAllowedAmount)
);
}
} else {
$shippingAmount = $allowedAmount;
$baseShippingAmount = $baseAllowedAmount;
$allowedTaxAmount = $order->getShippingTaxAmount() - $order->getShippingTaxRefunded();
$baseAllowedTaxAmount = $order->getBaseShippingTaxAmount() - $order->getBaseShippingTaxRefunded();
$shippingInclTax = $this->priceCurrency->round($allowedAmount + $allowedTaxAmount);
$baseShippingInclTax = $this->priceCurrency->round(
$baseAllowedAmount + $baseAllowedTaxAmount
);
}
$creditmemo->setShippingAmount($shippingAmount);
$creditmemo->setBaseShippingAmount($baseShippingAmount);
$creditmemo->setShippingInclTax($shippingInclTax);
$creditmemo->setBaseShippingInclTax($baseShippingInclTax);
$creditmemo->setGrandTotal($creditmemo->getGrandTotal() + $shippingAmount);
$creditmemo->setBaseGrandTotal($creditmemo->getBaseGrandTotal() + $baseShippingAmount);
return $this;
}
}
| {
"content_hash": "72721bf4f7d2e2874f3c738dc7c1e291",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 110,
"avg_line_length": 42.94230769230769,
"alnum_prop": 0.6164352888490819,
"repo_name": "tarikgwa/test",
"id": "a5cbd3431b33765263d3fd6e5b9bee27ea9b42ea",
"size": "4564",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "html/app/code/Magento/Sales/Model/Order/Creditmemo/Total/Shipping.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "26588"
},
{
"name": "CSS",
"bytes": "4874492"
},
{
"name": "HTML",
"bytes": "8635167"
},
{
"name": "JavaScript",
"bytes": "6810903"
},
{
"name": "PHP",
"bytes": "55645559"
},
{
"name": "Perl",
"bytes": "7938"
},
{
"name": "Shell",
"bytes": "4505"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
name "rubygems"
license "MIT"
license_file "https://raw.githubusercontent.com/rubygems/rubygems/master/LICENSE.txt"
skip_transitive_dependency_licensing true
dependency "ruby"
if version && !source
known_tarballs = {
"2.4.1" => "7e39c31806bbf9268296d03bd97ce718",
"2.4.4" => "440a89ad6a3b1b7a69b034233cc4658e",
"2.4.5" => "5918319a439c33ac75fbbad7fd60749d",
"2.4.8" => "dc77b51449dffe5b31776bff826bf559",
"2.6.7" => "9cd4c5bdc70b525dfacd96e471a64605",
"2.6.8" => "40b3250f28c1d0d5cb9ff5ab2b17df6e",
}
known_tarballs.each do |vsn, md5|
version vsn do
source md5: md5, url: "http://production.cf.rubygems.org/rubygems/rubygems-#{vsn}.tgz"
relative_path "rubygems-#{vsn}"
end
end
end
# If we still don't have a source (if it's a tarball) grab from ruby ...
if version && !source
# If the version is a gem version, we"ll just be using rubygems.
# If it's a branch or SHA (i.e. v1.2.3) we use github.
begin
Gem::Version.new(version)
rescue ArgumentError
source git: "https://github.com/rubygems/rubygems.git"
end
end
# git repo is always expanded to "rubygems"
if source && source.include?(:git)
relative_path "rubygems"
end
build do
env = with_standard_compiler_flags(with_embedded_path)
if source
# Building from source:
command "git submodule init", env: env
command "git submodule update", env: env
ruby "setup.rb --no-document", env: env
else
# Installing direct from rubygems:
# If there is no version, this will get latest.
gem "update --no-document --system #{version}", env: env
gem "uninstall rubygems-update -ax"
end
end
| {
"content_hash": "cde7ebced5cab0fae252b7ef6415e8d4",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 92,
"avg_line_length": 29.410714285714285,
"alnum_prop": 0.689738919247116,
"repo_name": "higanworks/omnibus-software",
"id": "7a52f2cd5b1a13c6ca49cb37b15ef11714c1e1f6",
"size": "2240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/software/rubygems.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "829"
},
{
"name": "C++",
"bytes": "1257"
},
{
"name": "Ruby",
"bytes": "189540"
},
{
"name": "Shell",
"bytes": "1241"
}
],
"symlink_target": ""
} |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.ondemandscanning.v1.model;
/**
* The category to which the update belongs.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the On-Demand Scanning API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Category extends com.google.api.client.json.GenericJson {
/**
* The identifier of the category.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String categoryId;
/**
* The localized name of the category.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The identifier of the category.
* @return value or {@code null} for none
*/
public java.lang.String getCategoryId() {
return categoryId;
}
/**
* The identifier of the category.
* @param categoryId categoryId or {@code null} for none
*/
public Category setCategoryId(java.lang.String categoryId) {
this.categoryId = categoryId;
return this;
}
/**
* The localized name of the category.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The localized name of the category.
* @param name name or {@code null} for none
*/
public Category setName(java.lang.String name) {
this.name = name;
return this;
}
@Override
public Category set(String fieldName, Object value) {
return (Category) super.set(fieldName, value);
}
@Override
public Category clone() {
return (Category) super.clone();
}
}
| {
"content_hash": "62d53cc6fdc76e32990ea3e971dfede1",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 182,
"avg_line_length": 28.53846153846154,
"alnum_prop": 0.6958028494416635,
"repo_name": "googleapis/google-api-java-client-services",
"id": "c0e2746fc745c2117c7962ec8573da4f31db777d",
"size": "2597",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "clients/google-api-services-ondemandscanning/v1/2.0.0/com/google/api/services/ondemandscanning/v1/model/Category.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package eu.toolchain.serializer;
import eu.toolchain.serializer.collection.ImmutableListSerializer;
import eu.toolchain.serializer.collection.ImmutableMapSerializer;
import eu.toolchain.serializer.collection.ImmutableNavigableMapSerializer;
import eu.toolchain.serializer.collection.ImmutableNavigableSetSerializer;
import eu.toolchain.serializer.collection.ImmutableSetSerializer;
import eu.toolchain.serializer.collection.ImmutableSortedMapSerializer;
import eu.toolchain.serializer.collection.ImmutableSortedSetSerializer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
public class ImmutableCollectionsProvider implements CollectionsProvider {
private final Serializer<Integer> size;
public ImmutableCollectionsProvider(final Serializer<Integer> size) {
this.size = size;
}
static final String[] collections = new String[]{
"ImmutableList", "ImmutableMap", "ImmutableSortedMap", "ImmutableNavigableMap", "ImmutableSet",
"ImmutableSortedSet", "ImmutableNavigableSet"
};
public static void verifyGuavaAvailable() {
final List<String> missing = new ArrayList<>();
for (final String collection : collections) {
if (!check(String.format("com.google.common.collect.%s", collection))) {
missing.add(collection);
}
}
if (!missing.isEmpty()) {
throw new IllegalStateException(
String.format("Missing guava collections (%s), is guava available in your classpath?",
missing));
}
}
static boolean check(String className) {
try {
Class.forName(className, true, ImmutableCollectionsProvider.class.getClassLoader());
} catch (ClassNotFoundException e) {
return false;
}
return true;
}
@Override
public <T> Serializer<List<T>> list(Serializer<T> value) {
return new ImmutableListSerializer<T>(size, value);
}
@Override
public <K, V> Serializer<Map<K, V>> map(Serializer<K> key, Serializer<V> value) {
return new ImmutableMapSerializer<K, V>(size, key, value);
}
@Override
public <K extends Comparable<?>, V> Serializer<SortedMap<K, V>> sortedMap(
Serializer<K> key, Serializer<V> value
) {
return new ImmutableSortedMapSerializer<K, V>(size, key, value);
}
@Override
public <K extends Comparable<?>, V> Serializer<NavigableMap<K, V>> navigableMap(
Serializer<K> key, Serializer<V> value
) {
return new ImmutableNavigableMapSerializer<K, V>(size, key, value);
}
@Override
public <T> Serializer<Set<T>> set(Serializer<T> value) {
return new ImmutableSetSerializer<T>(size, value);
}
@Override
public <T extends Comparable<?>> Serializer<SortedSet<T>> sortedSet(Serializer<T> value) {
return new ImmutableSortedSetSerializer<T>(size, value);
}
@Override
public <T extends Comparable<?>> Serializer<NavigableSet<T>> navigableSet(Serializer<T> value) {
return new ImmutableNavigableSetSerializer<T>(size, value);
}
}
| {
"content_hash": "a8f124a160f4eda0050ce96eed429eee",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 99,
"avg_line_length": 32.48421052631579,
"alnum_prop": 0.7346079066753078,
"repo_name": "udoprog/tiny-serializer-java",
"id": "bf1d1bbd79dea58e8a076a2d1e66bf5b97002712",
"size": "3086",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tiny-serializer-core/src/main/java/eu/toolchain/serializer/ImmutableCollectionsProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "315111"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace PostmarkDotNet.Model
{
public class PostmarkTaggedTriggerList
{
public int TotalCount { get; set; }
public IEnumerable<PostmarkTaggedTriggerInfo> Tags { get; set; }
}
}
| {
"content_hash": "137a2e37d64ce837c35380b2f48bf54f",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 72,
"avg_line_length": 22.181818181818183,
"alnum_prop": 0.6967213114754098,
"repo_name": "gov-ithub/auth-sso",
"id": "3278211585585a676c02f7f09c079361c02ee71e",
"size": "246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/external/GovITHub.External.Postmark.NetCore/Model/PostmarkTaggedTriggerList.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "402701"
},
{
"name": "CSS",
"bytes": "358476"
},
{
"name": "HTML",
"bytes": "40057"
},
{
"name": "JavaScript",
"bytes": "2003412"
},
{
"name": "Nginx",
"bytes": "570"
}
],
"symlink_target": ""
} |
from launcher.utils.imports import import_submodules
import_submodules(globals(),__name__,__path__)
| {
"content_hash": "98fc37a8c738d77d960c00ebd3e3f477",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 52,
"avg_line_length": 33.666666666666664,
"alnum_prop": 0.7623762376237624,
"repo_name": "hikelee/launcher",
"id": "fc6dbafe5363f53ff034eb185ddde96cb81aa7c8",
"size": "101",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "launcher/views/mixins/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "58461"
},
{
"name": "JavaScript",
"bytes": "14117"
},
{
"name": "Python",
"bytes": "212230"
}
],
"symlink_target": ""
} |
<!--
Copyright 2022 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/color_primary</item>
<item name="colorPrimaryDark">@color/color_primary_dark</item>
<item name="colorAccent">@color/color_accent</item>
</style>
</resources>
| {
"content_hash": "325287f168980ce31eedefd390396229",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 74,
"avg_line_length": 47.68421052631579,
"alnum_prop": 0.7328918322295805,
"repo_name": "android/android-test",
"id": "802774c3f734b5c2708be46ee1d23779f77fcb08",
"size": "906",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "testapps/foldable_testapp/java/androidx/test/foldable/app/res/values/styles.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AIDL",
"bytes": "10175"
},
{
"name": "Dockerfile",
"bytes": "837"
},
{
"name": "HTML",
"bytes": "29993"
},
{
"name": "Java",
"bytes": "4893629"
},
{
"name": "Kotlin",
"bytes": "176390"
},
{
"name": "Python",
"bytes": "308427"
},
{
"name": "Shell",
"bytes": "3950"
},
{
"name": "Starlark",
"bytes": "354299"
}
],
"symlink_target": ""
} |
using System;
namespace Org.BouncyCastle.Pkix
{
public class PkixNameConstraintValidatorException : Exception
{
public PkixNameConstraintValidatorException(String msg)
: base(msg)
{
}
}
}
| {
"content_hash": "09b0bd7375fc536c57b31152623cbaef",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 65,
"avg_line_length": 19.75,
"alnum_prop": 0.6455696202531646,
"repo_name": "maurobennici/LicenseOn",
"id": "9f01e87659558ef29207754602de8c0875e10e86",
"size": "237",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "crypto/src/pkix/PkixNameConstraintValidatorException.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "14348"
},
{
"name": "C#",
"bytes": "4370330"
},
{
"name": "HTML",
"bytes": "671"
},
{
"name": "Smalltalk",
"bytes": "20844"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@color/colorPrimaryDark"
android:orientation="vertical"
android:padding="@dimen/default_padding">
</LinearLayout>
| {
"content_hash": "a1c870349d8058bf45dfa2d19ec75f76",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 72,
"avg_line_length": 43.875,
"alnum_prop": 0.7378917378917379,
"repo_name": "LukaszPiskadlo/TodoApp",
"id": "915041073777de16e7bf0b574f6ae8a45abcd110",
"size": "351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/nav_header.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "15325"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" type="image/x-icon" href="img/favicon.png">
<title>3D4E at UCLA - Leadership</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Custom styles for this template -->
<link href="css/clean-blog.min.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
<div class="container">
<a class="navbar-brand" href="index.html">3D4E at UCLA</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menu
<i class="fa fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="leadership.html">Leadership</a>
</li>
<li class="nav-item">
<a class="nav-link" href="sponsors.html">Sponsors</a>
</li>
<li class="nav-item">
<a class="nav-link" href="projects.html">Projects</a>
</li>
<li class="nav-item">
<a class="nav-link" href="media.html">Media</a>
</li>
<li class="nav-item">
<a class="nav-link" href="workshops.html">Workshop Archive</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.html">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Header -->
<header class="masthead" style="background-image: url('img/campus.jpg')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading">
<h1><strong>Leadership</strong></h1>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Meet the people who help keep our club running!</h2> </br>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-2"> <img src="img/Ryan.jpg" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>President - Ryan Poon</strong></h4>
<p>Ryan is a third year undergraduate mechanical engineer. He is excited to design and manufacture for 3D4E, as he loves to exploit the versatility of 3D printing to make each organic idea become a reality. Also the ASME President and a volunteer in UCLA’s Biomechatronics Lab, Ryan loves to exercise, shoot arrows with the archery team, and drool over Game of Thrones.</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/Joey.jpg" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Vice President - Joey Meurer</strong></h4>
<p>
As a third year mechanical engineering student, Joey enjoys diving into new endeavours both literally and figuratively. He recently interned at WhiteWave foods, designing standard operating procedures for pneumatic valves as well as systems to improve safety and efficiency in valve handling.
</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/Bhav.png" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Treasurer - Bhav Patel</strong></h4>
<p>
Bhav is a second year aerospace engineering student with an interest in astronautics. His interests, in addition to 3D printing, include rockets, philosophy, running, as well as unholy amounts of binge watching shows. The biggest thing on his bucket list is to backpack in Patagonia and see the Milky Way in the night sky.
</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/China.jpg" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Secretary - China Hagstrom</strong></h4>
<p>
China is a second year undergraduate mechanical engineering major. She has learned how to use Solidworks and Fusion360 in the past 6 months, so she enjoys designing cool projects to 3D print. She is a mentor for UCLA Tech Camp and is involved with ASME Battlebots, but she also loves to rock climb, skateboard, dye her hair multiple colors a year, and figure skate.
</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/Dennis.png" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Social and Recruitment Chair - Dennis Shen</strong></h4>
<p>
Dennis is a second year mechanical engineering student that joined 3D4E to really dive into 3D printing with an emphasis on educating others about the field. He is also the 17-18 Resident Assistant for UCLA’s Design and Innovation community, working with groups such as FuturizeX and StartupUCLA to promote innovation and entrepreneurship on the Hill.
</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/Michael.jpg" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Lab Manager - Michael Cui</strong></h4>
<p>
Michael is a third-year mechanical undergraduate mechanical engineer that joined 3D4E to explore different possibilities of the 3D printing technology. Besides being consumed by school related works, Michael enjoys mixing and creating EDM tracks using Ableton and his Novation launchpad. As a lab manager, his ultimate motto is “You break I fix, you dirty I clean.”
</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/Brooke.JPG" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Advisor - Brooke Zampell</strong></h4>
<p>
Brooke is a 4th year bioengineering student who has been involved in 3D4E for two years. After spending this past summer interning at Dexcom, a San Diego company that makes Continuous Glucose Monitors for diabetes patients, she is planning to go into the biotech industry. In addition to 3D4E, Brooke loves spending her time exploring LA, and cheering on the Bruins in athletics.
</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/James.png" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Head of Technical Instruction - James Chang</strong></h4>
<p>
James took a deep dive into the world of 3D printing when he purchased his first ever DIY printer, the Printrbot Simple 1401, in 2014. Ever since that, he has caught the printing bug, deconstructing, modifying, and learning from various printers. In addition to bouts of sporadic veganism, James is passionate about anything outdoors-related.
</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/Quentin.jpg" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Head of Technical Instruction - Quentin Truong</strong></h4>
<p>
Quentin is a second year undergraduate computer science major from southern California. Focusing on creating parts that move and function together, he works with involute gears, snap fit joints, and arduino. He also has experience in 3D graphics and animation. Outside of school, he loves to explore the night via stickshift cars.
</p>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-2"> <img src="img/David.jpg" class="img-rounded" style="width:180px;height:180px;"> </div>
<div class="col-lg-10">
<h4 class="media-heading"><strong>Webmaster - David Lu</strong></h4>
<p>
David is a third year aerospace engineering student, who joined 3D4E in order to explore the possibilities of additive manufacturing. A lifelong Star Trek fan, he has a strong interest in human spaceflight and is the external vice president of UCLA's AIAA. When not building rockets, he is a big fan of jazz music and enjoys improvising on the piano and clarinet.
</p>
</div>
</div>
</br>
</div>
<hr>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<ul class="list-inline text-center">
<li class="list-inline-item">
<a href="https://www.facebook.com/3D4E.UCLA/">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="copyright text-muted">Copyright © 3D4E at UCLA 2017</p>
</div>
</div>
</div>
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Custom scripts for this template -->
<script src="js/clean-blog.min.js"></script>
</body>
</html>
| {
"content_hash": "037c802d8dc2170f05fc28581c9f7013",
"timestamp": "",
"source": "github",
"line_count": 244,
"max_line_length": 391,
"avg_line_length": 47.02049180327869,
"alnum_prop": 0.5942647956070775,
"repo_name": "Ludav15/Ludav15.github.io",
"id": "4af27f607ae29d08a3dc43a989cd2e89aad23a02",
"size": "11481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "leadership.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "123356"
},
{
"name": "HTML",
"bytes": "14914"
}
],
"symlink_target": ""
} |
The Ur Project is a dynamic new collaboration between the British Museum,
and the Penn Museum. We hope that also the Iraq Museum will become a
partner in the future. The project takes the long-standing and successful
cooperation as exemplified by the Ur excavations into the 21st century, by
digitally reunifying the remarkable finds from the city of Ur in a
state-of-the-art online facility. Every object recovered is being
digitised and researched, the cuneiform tablets are being translated,
whilst the original excavation photographs, the archives, plans, and other
documents, are being scanned and indexed. All this data will be made
freely available in an open neoteric database that will preserve the
complete finds and records in digital formats for posterity. The
unification of this diverse information into a single resource, from
photographs of Agatha Christie, to excavation diaries and the find-spots
of individual artefacts, will enable research that has hitherto been
impossible. Our desired outcomes are to stimulate a new level of interest,
and open new avenues of research by scholars and students from a range of
fields such as archaeology, history, Assyriology, anthropology, art and
architectural history, as well as to engage non-expert audiences in the
astonishing remains of this wonderful site. The second phase of the
project started in July 2013, it is titled *Ur of the Chaldees: A Virtual
Vision of Woolley's excavations*, and it was made possible by $1.28
million in lead support from the Leon Levy Foundation.
## Project goals ##
Our multi-faceted website will present for the first time an authoritative
set of high resolution images of the finds, integrated with all field
notes, catalogs, photos, reports, maps, letters, publications. The
cuneiform inscriptions are being transliterated and translated into
English. Importantly, all data will be recorded in a format that allows it
to be fully extractable and taggable, enabling researchers to create their
own datasets and make comparisons with their own research. A further
significant outcome will be that the reintegrated records will allow us to
re-establish lost object identifications and crucial find-spot information.
We will relate internal references between notes, letters, publications
and catalogs, connect artefacts to their find-spots on maps, and link
wherever possible to other resources with the goal of enabling researchers
to analyse the site in radical new ways. Our understanding of Ur and the
ancient Near East will improve dramatically, fostering an era of
intensified research centred upon Ur, using the unparalleled wealth of
resources that we will make available.
## Architecture ##
The UrOnline Digital Resource is supported by a number of open source technologies,
including Django (web framework), Solr (indexing), MySQL (database backend),
and Haystack (search module for Django). The Django 1.6 base template was forked from
Xenith's original base template repository. This version of the UrOnline Digital Resource
is part of Phase 1 of the website's development schedule. During Phase 2, we hope to
combine aspects of our work with OpenContext v.2 currently being developed by Eric
Kansa to expand our project to include Open Data capabilities. | {
"content_hash": "b8da4d13a7a475617c49bdc2660e7d38",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 89,
"avg_line_length": 62.90384615384615,
"alnum_prop": 0.8162641394069092,
"repo_name": "sashafr/uronline",
"id": "4114e29112ec2ca4ca7abbfdc0da36374443746d",
"size": "3327",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "209581"
},
{
"name": "HTML",
"bytes": "669194"
},
{
"name": "JavaScript",
"bytes": "270371"
},
{
"name": "Nginx",
"bytes": "4758"
},
{
"name": "Python",
"bytes": "627857"
},
{
"name": "Shell",
"bytes": "3570"
}
],
"symlink_target": ""
} |
from unittest import TestCase
from core.tape import Tape
from core.turing_states import State
from file_import.parser import parse_lines
class TestSolutions(TestCase):
def setUp(self):
lines = [
'1 | 6 | 0, 1 | 0, 1, B | B | 5;',
'q0, 0 > q0, B, R',
'q0, 1 > q1, 1, R',
'q0, B > q5, B, N',
'q1, 0 > q3, 0, R',
'q1, 1 > q2, 0, L',
'q2, 0 > q2, 0, L',
'q2, 1 > q2, 0, L',
'q2, B > q0, B, R',
'q3, 0 > q2, 1, L',
'q3, 1 > q4, 0, L',
'q4, 0 > q2, 1, L'
]
self.turing_machine = parse_lines(lines)
self.band_alphabet = self.turing_machine.alphabet
def test_tm_terminates_immediatly_if_type_ist_empty(self):
empty_tape = Tape([], alphabet=self.band_alphabet)
iterations = list(self.turing_machine.as_iterator(empty_tape))
self.assertEqual(1, len(iterations))
def test_0_is_valid_input(self):
tape = Tape(['0'], alphabet=self.band_alphabet)
iterations = list(self.turing_machine.as_iterator(tape))
last_event, last_transition = iterations[-1]
self.assertIsNotNone(last_transition)
def test_turing_machine_terminates_in_state5(self):
tape = Tape(['0'], alphabet=self.band_alphabet)
iterations = list(self.turing_machine.as_iterator(tape))
_, last_transition = iterations[-1]
self.assertEqual(State(index=5, name='q5'), last_transition.new_state)
def test_1_is_invalid_input(self):
tape = Tape(['1'], alphabet=self.band_alphabet)
iterations = list(self.turing_machine.as_iterator(tape))
_, last_transition = iterations[-1]
self.assertIsNone(last_transition)
def test_11_is_valid_input(self):
tape = Tape(['1', '1'], alphabet=self.band_alphabet)
iterations = list(self.turing_machine.as_iterator(tape))
_, last_transition = iterations[-1]
self.assertIsNotNone(last_transition)
def test_1100_is_valid_input(self):
tape = Tape(['1', '1', '0', '0'], alphabet=self.band_alphabet)
iterations = list(self.turing_machine.as_iterator(tape))
_, last_transition = iterations[-1]
self.assertIsNotNone(last_transition)
def test_00111_is_invalid_input(self):
tape = Tape(['0', '0', '1', '1', '1'], alphabet=self.band_alphabet)
iterations = list(self.turing_machine.as_iterator(tape))
_, last_transition = iterations[-1]
self.assertIsNone(last_transition)
| {
"content_hash": "bc5bbcb0cc4aa5a8a1a5700d6f1d26af",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 78,
"avg_line_length": 35.23287671232877,
"alnum_prop": 0.5839813374805599,
"repo_name": "mjutzi/TikzTuringSimulator",
"id": "9865c8e851432b5728d4247629935b4db8331b46",
"size": "2572",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/unit_tests/test_div_by_3.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "52124"
}
],
"symlink_target": ""
} |
require 'test_helper'
require 'redclothcoderay'
class PluginWithCodeTagTest < Test::Unit::TestCase
def test_parsing_inline_code
text = "Hello, this is *textilized*. It also has <code>@inline_code_examples</code>!"
result = RedCloth.new(text).to_html
assert_equal(%Q{<p>Hello, this is <strong>textilized</strong>. It also has <code class="inline_code"><span class="iv">@inline_code_examples</span></code>!</p>}, result)
end
def test_parsing_multiline_code
text = %Q{Hello, this is *textilized*.
<code>
def hello_world
puts "Allright"
end
</code>}
result = RedCloth.new(text).to_html
assert result.include?(%Q{<strong>textilized</strong>})
assert result.include?(%Q{<pre><code class="multiline_code">})
end
def test_one_liner_multiline_code
text = %Q{Hello, this is *textilized*.
<code>
hello_to_you
</code>
}
result = RedCloth.new(text).to_html
assert result.include?(%Q{<strong>textilized</strong>})
assert result.include?(%Q{<pre><code class=\"multiline_code\">hello_to_you</code></pre>})
end
def test_parsing_other_languages
text = %Q{Hello, this is *textilized* with some <code:html><p>HTML code</p></code>!}
result = RedCloth.new(text).to_html
assert result.include?(%Q{<strong>textilized</strong>})
assert result.include?(%Q{<code class="inline_code"><span class="ta"><p></span>HTML code<span class="ta"></p></span></code>})
end
def test_after_a_header
text = %Q{h2. Hello, world.
<code>
hello_world
</code>}
result = RedCloth.new(text).to_html
assert result.include?(%Q{<h2>Hello, world.</h2>})
end
# This case is a real case that caused borks, which lead to 0.3.0.
def test_odd_indents
text = %Q{Let's try, now.
<code>
class Person < ActiveRecord::Base
composed_of :address, :class_name => "Address",
:mapping => [
[:address_street, :street],
[:address_postal_code, :postal_code]]
end
</code>}
result = RedCloth.new(text).to_html
assert result.include?(%{[<span class="sy">:address_street</span>, <span class="sy">:street</span>],})
assert result.include?(%{composed_of <span class="sy">:address</span>, <span class="sy">:class_name</span> => <span class="s"><span class="dl">"</span><span class="k">Address</span><span class="dl">"</span></span>,})
end
end | {
"content_hash": "3c4bdff7e9271ce1845cd5dcbdb8a10d",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 233,
"avg_line_length": 32.527027027027025,
"alnum_prop": 0.6418778562525966,
"repo_name": "matiaskorhonen/redcloth-with-coderay",
"id": "ed3fb896de4731519e0571c5e3607e65e7ca5310",
"size": "2407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/redclothcoderay_code_tag.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "7037"
}
],
"symlink_target": ""
} |
.auratestHybridContainerTestSetRunner.auraPlaceholder.spin{
position:absolute;top:50%;left:50%;
}
| {
"content_hash": "d08cdbb98014d8d74b7184a2981c815e",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 59,
"avg_line_length": 25.25,
"alnum_prop": 0.8118811881188119,
"repo_name": "lhong375/aura",
"id": "cee5e441a327b60fdada48d78d1c9add7fc097a9",
"size": "712",
"binary": false,
"copies": "1",
"ref": "refs/heads/load-test-without-testjar",
"path": "aura/src/test/components/auratest/hybridContainerTestSetRunner/hybridContainerTestSetRunner.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "633422"
},
{
"name": "GAP",
"bytes": "9236"
},
{
"name": "Java",
"bytes": "6205033"
},
{
"name": "JavaScript",
"bytes": "9903940"
},
{
"name": "Python",
"bytes": "7342"
},
{
"name": "Shell",
"bytes": "12892"
},
{
"name": "XSLT",
"bytes": "1140"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>railroad-crossing: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.0~camlp4 / railroad-crossing - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
railroad-crossing
<small>
8.9.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-04 11:54:16 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-04 11:54:16 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp4 4.04+1 Camlp4 is a system for writing extensible parsers for programming languages
conf-findutils 1 Virtual package relying on findutils
coq 8.5.0~camlp4 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.04.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.04.2 Official 4.04.2 release
ocaml-config 1 OCaml Switch Configuration
ocamlbuild 0.14.2 OCamlbuild is a build system with builtin rules to easily build most OCaml projects
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/railroad-crossing"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/RailroadCrossing"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: CTL"
"keyword: TCTL"
"keyword: real time"
"keyword: timed automatas"
"keyword: safety"
"keyword: concurrency properties"
"keyword: invariants"
"keyword: non-Zeno"
"keyword: discrete time"
"category: Computer Science/Concurrent Systems and Protocols/Correctness of specific protocols"
"date: February-March 2000"
]
authors: [
"Carlos Daniel Luna [http://www.fing.edu.uy/~cluna]"
]
bug-reports: "https://github.com/coq-contribs/railroad-crossing/issues"
dev-repo: "git+https://github.com/coq-contribs/railroad-crossing.git"
synopsis: "The Railroad Crossing Example"
description: """
This library present the specification and verification of
one real time system: the Railroad Crossing Problem, which has been
proposed as a benchmark for the comparison of real-time formalisms. We
specify the system using timed automatas (timed graphs) with discrete
time and we prove invariants, the system safety property and the NonZeno
property, using the logics CTL and TCTL."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/railroad-crossing/archive/v8.9.0.tar.gz"
checksum: "md5=98e7fada2a3a76ef365de972182d566b"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-railroad-crossing.8.9.0 coq.8.5.0~camlp4</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0~camlp4).
The following dependencies couldn't be met:
- coq-railroad-crossing -> coq >= 8.9 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-railroad-crossing.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "7940406ebb4c7f74cab120a523250610",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 159,
"avg_line_length": 42.20652173913044,
"alnum_prop": 0.5690187998969869,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "5b8cdd51bc0693e5350fa2d674a87abd6a3b6706",
"size": "7791",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.5.0~camlp4/railroad-crossing/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package iso20022
type RedemptionCompletion1Code string
| {
"content_hash": "68c63c6c5d530f768ab5714328fa8aca",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 37,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.8928571428571429,
"repo_name": "fgrid/iso20022",
"id": "baccd58c757fe450cea8c5825eff8877b52a2b1f",
"size": "56",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RedemptionCompletion1Code.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "21383920"
}
],
"symlink_target": ""
} |
package co.cask.cdap.api.worker;
import co.cask.cdap.api.DatasetConfigurer;
import co.cask.cdap.api.ProgramConfigurer;
import co.cask.cdap.api.Resources;
import co.cask.cdap.api.TxRunnable;
import co.cask.cdap.api.data.DatasetContext;
import co.cask.cdap.api.dataset.Dataset;
import co.cask.cdap.api.plugin.PluginConfigurer;
/**
* Interface for configuring {@link Worker}.
*/
public interface WorkerConfigurer extends DatasetConfigurer, ProgramConfigurer, PluginConfigurer {
/**
* Sets the resources requirements for the the {@link Worker}.
* @param resources the requirements
*/
void setResources(Resources resources);
/**
* Sets the number of instances needed for the {@link Worker}.
* @param instances number of instances, must be > 0
*/
void setInstances(int instances);
/**
* Adds the names of {@link Dataset Datasets} used by the worker.
* @param datasets dataset names
* @deprecated Deprecated as of 2.8.0. Dataset can be requested directly through the method
* {@link DatasetContext#getDataset(String)} at runtime when
* calling {@link WorkerContext#execute(TxRunnable)}.
*/
@Deprecated
void useDatasets(Iterable<String> datasets);
}
| {
"content_hash": "464754dd7377433460026281b1361f57",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 98,
"avg_line_length": 31.41025641025641,
"alnum_prop": 0.7257142857142858,
"repo_name": "chtyim/cdap",
"id": "94503cc343b2915b2c7c4804881adb28fc69fffd",
"size": "1827",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "cdap-api/src/main/java/co/cask/cdap/api/worker/WorkerConfigurer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "13173"
},
{
"name": "CSS",
"bytes": "219754"
},
{
"name": "HTML",
"bytes": "455678"
},
{
"name": "Java",
"bytes": "15847298"
},
{
"name": "JavaScript",
"bytes": "1180404"
},
{
"name": "Python",
"bytes": "102235"
},
{
"name": "Ruby",
"bytes": "3178"
},
{
"name": "Scala",
"bytes": "30340"
},
{
"name": "Shell",
"bytes": "195815"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hive.hbase;
import java.io.IOException;
import java.util.Properties;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.BufferedMutator;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
import org.apache.hadoop.io.Writable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapred.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableOutputCommitter;
import org.apache.hadoop.hbase.mapreduce.TableOutputFormat;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.shims.ShimLoader;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.OutputCommitter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.security.UserGroupInformation;
/**
* HiveHBaseTableOutputFormat implements HiveOutputFormat for HBase tables.
*/
public class HiveHBaseTableOutputFormat extends
TableOutputFormat<ImmutableBytesWritable> implements
HiveOutputFormat<ImmutableBytesWritable, Object> {
static final Logger LOG = LoggerFactory.getLogger(HiveHBaseTableOutputFormat.class);
@Override
public void checkOutputSpecs(FileSystem fs, JobConf jc) throws IOException {
//obtain delegation tokens for the job
if (UserGroupInformation.getCurrentUser().hasKerberosCredentials()) {
TableMapReduceUtil.initCredentials(jc);
}
String hbaseTableName = jc.get(HBaseSerDe.HBASE_TABLE_NAME);
jc.set(TableOutputFormat.OUTPUT_TABLE, hbaseTableName);
Job job = new Job(jc);
JobContext jobContext = ShimLoader.getHadoopShims().newJobContext(job);
try {
checkOutputSpecs(jobContext);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
@Override
public
org.apache.hadoop.mapred.RecordWriter<ImmutableBytesWritable, Object>
getRecordWriter(
FileSystem fileSystem,
JobConf jobConf,
String name,
Progressable progressable) throws IOException {
return getMyRecordWriter(jobConf);
}
@Override
public OutputCommitter getOutputCommitter(TaskAttemptContext context) throws IOException,
InterruptedException {
return new TableOutputCommitter();
}
@Override
public FileSinkOperator.RecordWriter getHiveRecordWriter(
JobConf jobConf, Path finalOutPath, Class<? extends Writable> valueClass, boolean isCompressed,
Properties tableProperties, Progressable progress) throws IOException {
return getMyRecordWriter(jobConf);
}
private MyRecordWriter getMyRecordWriter(JobConf jobConf) throws IOException {
String hbaseTableName = jobConf.get(HBaseSerDe.HBASE_TABLE_NAME);
jobConf.set(TableOutputFormat.OUTPUT_TABLE, hbaseTableName);
final boolean walEnabled = HiveConf.getBoolVar(
jobConf, HiveConf.ConfVars.HIVE_HBASE_WAL_ENABLED);
final Connection conn = ConnectionFactory.createConnection(HBaseConfiguration.create(jobConf));
final BufferedMutator table = conn.getBufferedMutator(TableName.valueOf(hbaseTableName));
return new MyRecordWriter(table, conn, walEnabled);
}
private static class MyRecordWriter
implements org.apache.hadoop.mapred.RecordWriter<ImmutableBytesWritable, Object>,
org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter {
private final BufferedMutator m_table;
private final boolean m_walEnabled;
private final Connection m_connection;
public MyRecordWriter(BufferedMutator table, Connection connection, boolean walEnabled) {
m_table = table;
m_walEnabled = walEnabled;
m_connection = connection;
}
public void close(Reporter reporter) throws IOException {
m_table.close();
}
public void write(ImmutableBytesWritable key,
Object value) throws IOException {
Put put;
if (value instanceof Put){
put = (Put)value;
} else if (value instanceof PutWritable) {
put = new Put(((PutWritable)value).getPut());
} else {
throw new IllegalArgumentException("Illegal Argument " + (value == null ? "null" : value.getClass().getName()));
}
if(m_walEnabled) {
put.setDurability(Durability.SYNC_WAL);
} else {
put.setDurability(Durability.SKIP_WAL);
}
m_table.mutate(put);
}
@Override
protected void finalize() throws Throwable {
try {
m_table.close();
m_connection.close();
} finally {
super.finalize();
}
}
@Override
public void write(Writable w) throws IOException {
write(null, w);
}
@Override
public void close(boolean abort) throws IOException {
close(null);
}
}
}
| {
"content_hash": "7ffbb32971a01e27adac89ed3889cc8c",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 120,
"avg_line_length": 34.23870967741936,
"alnum_prop": 0.7467495760316563,
"repo_name": "b-slim/hive",
"id": "b344e16c13dabc763886c481c32213c397681c86",
"size": "6112",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hbase-handler/src/java/org/apache/hadoop/hive/hbase/HiveHBaseTableOutputFormat.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "54376"
},
{
"name": "Batchfile",
"bytes": "845"
},
{
"name": "C",
"bytes": "28218"
},
{
"name": "C++",
"bytes": "45308"
},
{
"name": "CSS",
"bytes": "5157"
},
{
"name": "GAP",
"bytes": "177410"
},
{
"name": "HTML",
"bytes": "58711"
},
{
"name": "HiveQL",
"bytes": "7122267"
},
{
"name": "Java",
"bytes": "52041555"
},
{
"name": "JavaScript",
"bytes": "43855"
},
{
"name": "M4",
"bytes": "2276"
},
{
"name": "PHP",
"bytes": "148097"
},
{
"name": "PLSQL",
"bytes": "5261"
},
{
"name": "PLpgSQL",
"bytes": "302587"
},
{
"name": "Perl",
"bytes": "319842"
},
{
"name": "PigLatin",
"bytes": "12333"
},
{
"name": "Python",
"bytes": "407540"
},
{
"name": "Roff",
"bytes": "5379"
},
{
"name": "SQLPL",
"bytes": "409"
},
{
"name": "Shell",
"bytes": "299497"
},
{
"name": "TSQL",
"bytes": "2521294"
},
{
"name": "Thrift",
"bytes": "142763"
},
{
"name": "XSLT",
"bytes": "20199"
},
{
"name": "q",
"bytes": "608893"
}
],
"symlink_target": ""
} |
import {Writable} from 'stream';
import chalk from 'chalk';
import CustomConsole from '../CustomConsole';
describe('CustomConsole', () => {
let _console;
let _stdout;
let _stderr;
beforeEach(() => {
_stdout = '';
_stderr = '';
const stdout = new Writable({
write(chunk, encoding, callback) {
_stdout += chunk.toString();
callback();
},
});
const stderr = new Writable({
write(chunk, encoding, callback) {
_stderr += chunk.toString();
callback();
},
});
_console = new CustomConsole(stdout, stderr);
});
describe('log', () => {
test('should print to stdout', () => {
_console.log('Hello world!');
expect(_stdout).toBe('Hello world!\n');
});
});
describe('error', () => {
test('should print to stderr', () => {
_console.error('Found some error!');
expect(_stderr).toBe('Found some error!\n');
});
});
describe('warn', () => {
test('should print to stderr', () => {
_console.warn('Found some warning!');
expect(_stderr).toBe('Found some warning!\n');
});
});
describe('assert', () => {
test('do not log when the assertion is truthy', () => {
_console.assert(true);
expect(_stderr).toMatch('');
});
test('do not log when the assertion is truthy and there is a message', () => {
_console.assert(true, 'ok');
expect(_stderr).toMatch('');
});
test('log the assertion error when the assertion is falsy', () => {
_console.assert(false);
expect(_stderr).toMatch('AssertionError');
expect(_stderr).toMatch(
// The message may differ across Node versions
/(false == true)|(The expression evaluated to a falsy value:)/,
);
});
test('log the assertion error when the assertion is falsy with another message argument', () => {
_console.assert(false, 'this should not happen');
expect(_stderr).toMatch('AssertionError');
expect(_stderr).toMatch('this should not happen');
});
});
describe('count', () => {
test('count using the default counter', () => {
_console.count();
_console.count();
_console.count();
expect(_stdout).toEqual('default: 1\ndefault: 2\ndefault: 3\n');
});
test('count using the a labeled counter', () => {
_console.count('custom');
_console.count('custom');
_console.count('custom');
expect(_stdout).toEqual('custom: 1\ncustom: 2\ncustom: 3\n');
});
test('countReset restarts default counter', () => {
_console.count();
_console.count();
_console.countReset();
_console.count();
expect(_stdout).toEqual('default: 1\ndefault: 2\ndefault: 1\n');
});
test('countReset restarts custom counter', () => {
_console.count('custom');
_console.count('custom');
_console.countReset('custom');
_console.count('custom');
expect(_stdout).toEqual('custom: 1\ncustom: 2\ncustom: 1\n');
});
});
describe('group', () => {
test('group without label', () => {
_console.group();
_console.log('hey');
_console.group();
_console.log('there');
expect(_stdout).toEqual(' hey\n there\n');
});
test('group with label', () => {
_console.group('first');
_console.log('hey');
_console.group('second');
_console.log('there');
expect(_stdout).toEqual(` ${chalk.bold('first')}
hey
${chalk.bold('second')}
there
`);
});
test('groupEnd remove the indentation of the current group', () => {
_console.group();
_console.log('hey');
_console.groupEnd();
_console.log('there');
expect(_stdout).toEqual(' hey\nthere\n');
});
test('groupEnd can not remove the indentation below the starting point', () => {
_console.groupEnd();
_console.groupEnd();
_console.group();
_console.log('hey');
_console.groupEnd();
_console.log('there');
expect(_stdout).toEqual(' hey\nthere\n');
});
});
describe('time', () => {
test('should return the time between time() and timeEnd() on default timer', () => {
_console.time();
_console.timeEnd();
expect(_stdout).toMatch('default: ');
expect(_stdout).toMatch('ms');
});
test('should return the time between time() and timeEnd() on custom timer', () => {
_console.time('custom');
_console.timeEnd('custom');
expect(_stdout).toMatch('custom: ');
expect(_stdout).toMatch('ms');
});
});
});
| {
"content_hash": "d90aac7d198bb1096ee586c64a76a8d9",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 101,
"avg_line_length": 25.016304347826086,
"alnum_prop": 0.5533347816641321,
"repo_name": "bookman25/jest",
"id": "56c6964eab7b55218122e540033b3415ea013179",
"size": "4812",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/jest-console/src/__tests__/CustomConsole.test.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13066"
},
{
"name": "JavaScript",
"bytes": "5513776"
},
{
"name": "Shell",
"bytes": "1629"
},
{
"name": "TypeScript",
"bytes": "1851402"
}
],
"symlink_target": ""
} |
package org.javacs.debug.proto;
/** Arguments for 'modules' request. */
public class ModulesArguments {
/** The index of the first module to return; if omitted modules start at 0. */
public Integer startModule;
/** The number of modules to return. If moduleCount is not specified or 0, all modules are returned. */
public Integer moduleCount;
}
| {
"content_hash": "05d99d1f03896af98ee0d69f6ae62b6f",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 107,
"avg_line_length": 40.22222222222222,
"alnum_prop": 0.7182320441988951,
"repo_name": "georgewfraser/vscode-javac",
"id": "507b80635cf4d7cb702e450cca9ab3e704bbe336",
"size": "362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/javacs/debug/proto/ModulesArguments.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "359138"
},
{
"name": "Shell",
"bytes": "4903"
},
{
"name": "TypeScript",
"bytes": "9471"
}
],
"symlink_target": ""
} |
import Vue from 'vue';
import template from './layout.html';
const LayoutComponent = Vue.component('app-layout', {
template,
data: function(){
return {
thisYear: (new Date()).getFullYear()
};
},
props: {
welcome: {
type: Boolean,
default: () => false
}
}
});
export default LayoutComponent; | {
"content_hash": "e2471d45cdd561323a3a3af4b1d96102",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 53,
"avg_line_length": 17.68421052631579,
"alnum_prop": 0.5952380952380952,
"repo_name": "timplourde/dcidr",
"id": "3928d46a002e42fc95af99cf25230923f50cc709",
"size": "336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/layout.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49761"
},
{
"name": "HTML",
"bytes": "17912"
},
{
"name": "JavaScript",
"bytes": "46532"
}
],
"symlink_target": ""
} |
require 'flapjack/client'
module Flapjack
end
| {
"content_hash": "2eead380afb4b79e0bb68c35f715d9f9",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 25,
"avg_line_length": 11.75,
"alnum_prop": 0.8085106382978723,
"repo_name": "jswoods/flapjack-client",
"id": "2a41fe0b00e20b70ded018ea966593c534db4932",
"size": "47",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/flapjack.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "28002"
}
],
"symlink_target": ""
} |
[](https://github.com/blevesearch/bleve/actions?query=workflow%3ATests+event%3Apush+branch%3Amaster)
[](https://coveralls.io/github/blevesearch/bleve?branch=master)
[](https://godoc.org/github.com/blevesearch/bleve)
[](https://gitter.im/blevesearch/bleve?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[](https://codebeat.co/projects/github-com-blevesearch-bleve)
[](https://goreportcard.com/report/blevesearch/bleve)
[](https://sourcegraph.com/github.com/blevesearch/bleve?badge)
[](https://opensource.org/licenses/Apache-2.0)
modern text indexing in go - [blevesearch.com](http://www.blevesearch.com/)
## Features
* Index any go data structure (including JSON)
* Intelligent defaults backed up by powerful configuration
* Supported field types:
* Text, Numeric, Datetime, Boolean
* Supported query types:
* Term, Phrase, Match, Match Phrase, Prefix, Fuzzy
* Conjunction, Disjunction, Boolean (must/should/must_not)
* Term Range, Numeric Range, Date Range
* [Geo Spatial](https://github.com/blevesearch/bleve/blob/master/geo/README.md)
* Simple [query string syntax](http://www.blevesearch.com/docs/Query-String-Query/) for human entry
* [tf-idf](https://en.wikipedia.org/wiki/Tf-idf) Scoring
* Boosting
* Search result match highlighting
* Aggregations/faceting support:
* Terms Facet
* Numeric Range Facet
* Date Range Facet
## Discussion/Issues
Discuss usage/development of bleve and/or report issues here:
* [Github issues](https://github.com/blevesearch/bleve/issues)
* [Google group](https://groups.google.com/forum/#!forum/bleve)
## Indexing
```go
message := struct{
Id string
From string
Body string
}{
Id: "example",
From: "marty.schoch@gmail.com",
Body: "bleve indexing is easy",
}
mapping := bleve.NewIndexMapping()
index, err := bleve.New("example.bleve", mapping)
if err != nil {
panic(err)
}
index.Index(message.Id, message)
```
## Querying
```go
index, _ := bleve.Open("example.bleve")
query := bleve.NewQueryStringQuery("bleve")
searchRequest := bleve.NewSearchRequest(query)
searchResult, _ := index.Search(searchRequest)
```
## Command Line Interface
To install the CLI for the latest release of bleve, run:
```bash
$ go install github.com/blevesearch/bleve/v2/cmd/bleve@latest
```
```
$ bleve --help
Bleve is a command-line tool to interact with a bleve index.
Usage:
bleve [command]
Available Commands:
bulk bulk loads from newline delimited JSON files
check checks the contents of the index
count counts the number documents in the index
create creates a new index
dictionary prints the term dictionary for the specified field in the index
dump dumps the contents of the index
fields lists the fields in this index
help Help about any command
index adds the files to the index
mapping prints the mapping used for this index
query queries the index
registry registry lists the bleve components compiled into this executable
scorch command-line tool to interact with a scorch index
Flags:
-h, --help help for bleve
Use "bleve [command] --help" for more information about a command.
```
## Text Analysis Wizard
[bleveanalysis.couchbase.com](https://bleveanalysis.couchbase.com)
## License
Apache License Version 2.0
| {
"content_hash": "b97b3b18d2f97eee9735a57b31fafe93",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 210,
"avg_line_length": 36.19090909090909,
"alnum_prop": 0.7370007535795027,
"repo_name": "blevesearch/bleve",
"id": "e10454da70e5523f3690c5be1cc5ec9115218222",
"size": "4015",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "3092797"
},
{
"name": "Shell",
"bytes": "241"
},
{
"name": "Yacc",
"bytes": "7408"
}
],
"symlink_target": ""
} |
<?php
// GENERATED CODE -- DO NOT EDIT!
// Original file comments:
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
//
namespace Google\Cloud\Trace\V2;
/**
* This file describes an API for collecting and viewing traces and spans
* within a trace. A Trace is a collection of spans corresponding to a single
* operation or set of operations for an application. A span is an individual
* timed event which forms a node of the trace tree. A single trace may
* contain span(s) from multiple services.
*/
class TraceServiceGrpcClient extends \Grpc\BaseStub {
/**
* @param string $hostname hostname
* @param array $opts channel options
* @param \Grpc\Channel $channel (optional) re-use channel object
*/
public function __construct($hostname, $opts, $channel = null) {
parent::__construct($hostname, $opts, $channel);
}
/**
* Sends new spans to new or existing traces. You cannot update
* existing spans.
* @param \Google\Cloud\Trace\V2\BatchWriteSpansRequest $argument input argument
* @param array $metadata metadata
* @param array $options call options
* @return \Grpc\UnaryCall
*/
public function BatchWriteSpans(\Google\Cloud\Trace\V2\BatchWriteSpansRequest $argument,
$metadata = [], $options = []) {
return $this->_simpleRequest('/google.devtools.cloudtrace.v2.TraceService/BatchWriteSpans',
$argument,
['\Google\Protobuf\GPBEmpty', 'decode'],
$metadata, $options);
}
/**
* Creates a new span.
* @param \Google\Cloud\Trace\V2\Span $argument input argument
* @param array $metadata metadata
* @param array $options call options
* @return \Grpc\UnaryCall
*/
public function CreateSpan(\Google\Cloud\Trace\V2\Span $argument,
$metadata = [], $options = []) {
return $this->_simpleRequest('/google.devtools.cloudtrace.v2.TraceService/CreateSpan',
$argument,
['\Google\Cloud\Trace\V2\Span', 'decode'],
$metadata, $options);
}
}
| {
"content_hash": "49b0cdff1103b70919d99744c285d354",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 99,
"avg_line_length": 36.82857142857143,
"alnum_prop": 0.6799844840961986,
"repo_name": "chingor13/google-cloud-php",
"id": "ca9ba2e19553ae6002c0b04bad446304cf2b0b0f",
"size": "2578",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Trace/src/V2/TraceServiceGrpcClient.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "670"
},
{
"name": "PHP",
"bytes": "34466701"
},
{
"name": "Python",
"bytes": "321175"
},
{
"name": "Shell",
"bytes": "8827"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.codepipeline.model;
import java.io.Serializable;
/**
* <p>
* Represents information about a job.
* </p>
*/
public class Job implements Serializable, Cloneable {
/**
* <p>
* The unique system-generated ID of the job.
* </p>
*/
private String id;
/**
* <p>
* Additional data about a job.
* </p>
*/
private JobData data;
/**
* <p>
* A system-generated random number that AWS CodePipeline uses to ensure
* that the job is being worked on by only one job worker. This number must
* be returned in the response.
* </p>
*/
private String nonce;
/**
* <p>
* The ID of the AWS account to use when performing the job.
* </p>
*/
private String accountId;
/**
* <p>
* The unique system-generated ID of the job.
* </p>
*
* @param id
* The unique system-generated ID of the job.
*/
public void setId(String id) {
this.id = id;
}
/**
* <p>
* The unique system-generated ID of the job.
* </p>
*
* @return The unique system-generated ID of the job.
*/
public String getId() {
return this.id;
}
/**
* <p>
* The unique system-generated ID of the job.
* </p>
*
* @param id
* The unique system-generated ID of the job.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Job withId(String id) {
setId(id);
return this;
}
/**
* <p>
* Additional data about a job.
* </p>
*
* @param data
* Additional data about a job.
*/
public void setData(JobData data) {
this.data = data;
}
/**
* <p>
* Additional data about a job.
* </p>
*
* @return Additional data about a job.
*/
public JobData getData() {
return this.data;
}
/**
* <p>
* Additional data about a job.
* </p>
*
* @param data
* Additional data about a job.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Job withData(JobData data) {
setData(data);
return this;
}
/**
* <p>
* A system-generated random number that AWS CodePipeline uses to ensure
* that the job is being worked on by only one job worker. This number must
* be returned in the response.
* </p>
*
* @param nonce
* A system-generated random number that AWS CodePipeline uses to
* ensure that the job is being worked on by only one job worker.
* This number must be returned in the response.
*/
public void setNonce(String nonce) {
this.nonce = nonce;
}
/**
* <p>
* A system-generated random number that AWS CodePipeline uses to ensure
* that the job is being worked on by only one job worker. This number must
* be returned in the response.
* </p>
*
* @return A system-generated random number that AWS CodePipeline uses to
* ensure that the job is being worked on by only one job worker.
* This number must be returned in the response.
*/
public String getNonce() {
return this.nonce;
}
/**
* <p>
* A system-generated random number that AWS CodePipeline uses to ensure
* that the job is being worked on by only one job worker. This number must
* be returned in the response.
* </p>
*
* @param nonce
* A system-generated random number that AWS CodePipeline uses to
* ensure that the job is being worked on by only one job worker.
* This number must be returned in the response.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Job withNonce(String nonce) {
setNonce(nonce);
return this;
}
/**
* <p>
* The ID of the AWS account to use when performing the job.
* </p>
*
* @param accountId
* The ID of the AWS account to use when performing the job.
*/
public void setAccountId(String accountId) {
this.accountId = accountId;
}
/**
* <p>
* The ID of the AWS account to use when performing the job.
* </p>
*
* @return The ID of the AWS account to use when performing the job.
*/
public String getAccountId() {
return this.accountId;
}
/**
* <p>
* The ID of the AWS account to use when performing the job.
* </p>
*
* @param accountId
* The ID of the AWS account to use when performing the job.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public Job withAccountId(String accountId) {
setAccountId(accountId);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getId() != null)
sb.append("Id: " + getId() + ",");
if (getData() != null)
sb.append("Data: " + getData() + ",");
if (getNonce() != null)
sb.append("Nonce: " + getNonce() + ",");
if (getAccountId() != null)
sb.append("AccountId: " + getAccountId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Job == false)
return false;
Job other = (Job) obj;
if (other.getId() == null ^ this.getId() == null)
return false;
if (other.getId() != null
&& other.getId().equals(this.getId()) == false)
return false;
if (other.getData() == null ^ this.getData() == null)
return false;
if (other.getData() != null
&& other.getData().equals(this.getData()) == false)
return false;
if (other.getNonce() == null ^ this.getNonce() == null)
return false;
if (other.getNonce() != null
&& other.getNonce().equals(this.getNonce()) == false)
return false;
if (other.getAccountId() == null ^ this.getAccountId() == null)
return false;
if (other.getAccountId() != null
&& other.getAccountId().equals(this.getAccountId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getId() == null) ? 0 : getId().hashCode());
hashCode = prime * hashCode
+ ((getData() == null) ? 0 : getData().hashCode());
hashCode = prime * hashCode
+ ((getNonce() == null) ? 0 : getNonce().hashCode());
hashCode = prime * hashCode
+ ((getAccountId() == null) ? 0 : getAccountId().hashCode());
return hashCode;
}
@Override
public Job clone() {
try {
return (Job) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| {
"content_hash": "646e54c50f6bcfb27678a0eb38777705",
"timestamp": "",
"source": "github",
"line_count": 300,
"max_line_length": 79,
"avg_line_length": 26.45,
"alnum_prop": 0.5338374291115312,
"repo_name": "nterry/aws-sdk-java",
"id": "a2536fc362ecd313b08fb928518f72b34e4b21ef",
"size": "8522",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/Job.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "126417"
},
{
"name": "Java",
"bytes": "113994954"
},
{
"name": "Scilab",
"bytes": "3561"
}
],
"symlink_target": ""
} |
namespace media {
class AudioHardwareConfig;
class AudioRendererMixer;
class AudioRendererMixerInput;
class AudioRendererSink;
}
namespace content {
// Manages sharing of an AudioRendererMixer among AudioRendererMixerInputs based
// on their AudioParameters configuration. Inputs with the same AudioParameters
// configuration will share a mixer while a new AudioRendererMixer will be
// lazily created if one with the exact AudioParameters does not exist.
//
// There should only be one instance of AudioRendererMixerManager per render
// thread.
//
// TODO(dalecurtis): Right now we require AudioParameters to be an exact match
// when we should be able to ignore bits per channel since we're only dealing
// with floats. However, bits per channel is currently used to interleave the
// audio data by AudioOutputDevice::AudioThreadCallback::Process for consumption
// via the shared memory. See http://crbug.com/114700.
class CONTENT_EXPORT AudioRendererMixerManager {
public:
AudioRendererMixerManager();
~AudioRendererMixerManager();
// Creates an AudioRendererMixerInput with the proper callbacks necessary to
// retrieve an AudioRendererMixer instance from AudioRendererMixerManager.
// |source_render_frame_id| refers to the RenderFrame containing the entity
// rendering the audio. Caller must ensure AudioRendererMixerManager outlives
// the returned input. |device_id| and |security_origin| identify the output
// device to use
media::AudioRendererMixerInput* CreateInput(
int source_render_frame_id,
const std::string& device_id,
const url::Origin& security_origin);
// Returns a mixer instance based on AudioParameters; an existing one if one
// with the provided AudioParameters exists or a new one if not.
media::AudioRendererMixer* GetMixer(int source_render_frame_id,
const media::AudioParameters& params,
const std::string& device_id,
const url::Origin& security_origin,
media::OutputDeviceStatus* device_status);
// Remove a mixer instance given a mixer if the only other reference is held
// by AudioRendererMixerManager. Every AudioRendererMixer owner must call
// this method when it's done with a mixer.
void RemoveMixer(int source_render_frame_id,
const media::AudioParameters& params,
const std::string& device_id,
const url::Origin& security_origin);
private:
friend class AudioRendererMixerManagerTest;
// Define a key so that only those AudioRendererMixerInputs from the same
// RenderView, AudioParameters and output device can be mixed together.
struct MixerKey {
MixerKey(int source_render_frame_id,
const media::AudioParameters& params,
const std::string& device_id,
const url::Origin& security_origin);
MixerKey(const MixerKey& other);
int source_render_frame_id;
media::AudioParameters params;
std::string device_id;
url::Origin security_origin;
};
// Custom compare operator for the AudioRendererMixerMap. Allows reuse of
// mixers where only irrelevant keys mismatch; e.g., effects, bits per sample.
struct MixerKeyCompare {
bool operator()(const MixerKey& a, const MixerKey& b) const {
if (a.source_render_frame_id != b.source_render_frame_id)
return a.source_render_frame_id < b.source_render_frame_id;
if (a.params.channels() != b.params.channels())
return a.params.channels() < b.params.channels();
// Ignore effects(), bits_per_sample(), format(), and frames_per_buffer(),
// these parameters do not affect mixer reuse. All AudioRendererMixer
// units disable FIFO, so frames_per_buffer() can be safely ignored.
if (a.params.channel_layout() != b.params.channel_layout())
return a.params.channel_layout() < b.params.channel_layout();
if (a.device_id != b.device_id)
return a.device_id < b.device_id;
return a.security_origin < b.security_origin;
}
};
// Map of MixerKey to <AudioRendererMixer, Count>. Count allows
// AudioRendererMixerManager to keep track explicitly (v.s. RefCounted which
// is implicit) of the number of outstanding AudioRendererMixers.
struct AudioRendererMixerReference {
media::AudioRendererMixer* mixer;
int ref_count;
};
typedef std::map<MixerKey, AudioRendererMixerReference, MixerKeyCompare>
AudioRendererMixerMap;
// Active mixers.
AudioRendererMixerMap mixers_;
base::Lock mixers_lock_;
DISALLOW_COPY_AND_ASSIGN(AudioRendererMixerManager);
};
} // namespace content
#endif // CONTENT_RENDERER_MEDIA_AUDIO_RENDERER_MIXER_MANAGER_H_
| {
"content_hash": "0c4383e1839752c828e7fe0f14309195",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 80,
"avg_line_length": 42.39823008849557,
"alnum_prop": 0.7079941557086203,
"repo_name": "was4444/chromium.src",
"id": "a245a10294bc02df005fb9408804d4cd82944131",
"size": "5358",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw15",
"path": "content/renderer/media/audio_renderer_mixer_manager.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.fincatto.documentofiscal.cte300.classes;
import org.junit.Assert;
import org.junit.Test;
public class CTTipoDirecaoTest {
@Test
public void deveRepresentarOCodigoCorretamente() {
Assert.assertNull(CTTipoDirecao.valueOfCodigo(null));
Assert.assertEquals("N", CTTipoDirecao.NORTE.getCodigo());
Assert.assertEquals("L", CTTipoDirecao.LESTE.getCodigo());
Assert.assertEquals("S", CTTipoDirecao.SUL.getCodigo());
Assert.assertEquals("O", CTTipoDirecao.OESTE.getCodigo());
}
}
| {
"content_hash": "4003e46344426e1a87d6277eecf927d1",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 63,
"avg_line_length": 31.823529411764707,
"alnum_prop": 0.7171903881700554,
"repo_name": "jefperito/nfe",
"id": "d905f2f1be0ef0e6041febbb0b1277a30d49ab69",
"size": "541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/fincatto/documentofiscal/cte300/classes/CTTipoDirecaoTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7951315"
}
],
"symlink_target": ""
} |
from django.core.urlresolvers import reverse
from django.test import RequestFactory
from django.test import TestCase
from voteswap.match import get_friend_matches
from voteswap.tests.test_match import _TestSafeStateMatchBase
from voteswap.tests.test_match import _TestSwingStateMatchBase
from voteswap.tests.test_match import _TestSafeStateFriendsOfFriendsMatchBase
from voteswap.views import match as match_view
HTTP_OK = 200
class Common(object):
class Base(TestCase):
def setUp(self):
super(Common.Base, self).setUp()
self.request = RequestFactory()
def test_has_matches(self):
request = self.request.get(reverse(match_view))
request.user = self.user
response = match_view(request)
self.assertEqual(response.status_code, HTTP_OK)
matches = get_friend_matches(self.user.profile)
for match in matches:
self.assertContains(
response, match.profile.user.get_full_name())
class TestSafeStateMatch(_TestSafeStateMatchBase, Common.Base):
pass
class TestSwingStateMatch(_TestSwingStateMatchBase, Common.Base):
pass
class TestSafeStateFriendsOfFriendsMatch(
_TestSafeStateFriendsOfFriendsMatchBase, Common.Base):
def test_through_friend_shown(self):
request = self.request.get(reverse(match_view))
request.user = self.user
response = match_view(request)
self.assertEqual(response.status_code, HTTP_OK)
matches = get_friend_matches(self.user.profile)
for match in matches:
self.assertContains(
response, match.profile.fb_name)
if not match.is_direct:
self.assertContains(
response, "via %s" % match.through.fb_name)
| {
"content_hash": "6caf512b86e6765e70b8a3ae90cd3528",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 77,
"avg_line_length": 34.92307692307692,
"alnum_prop": 0.6773127753303965,
"repo_name": "sbuss/voteswap",
"id": "ace7708ce93f2686fff5d1fda2e98849c4366637",
"size": "1816",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "voteswap/tests/test_match_view.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "200347"
},
{
"name": "HTML",
"bytes": "159385"
},
{
"name": "JavaScript",
"bytes": "120612"
},
{
"name": "Makefile",
"bytes": "1227"
},
{
"name": "Python",
"bytes": "11135152"
},
{
"name": "Shell",
"bytes": "931"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="com.companyname.Mvx.Geocorder.Sample.Droid">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
| {
"content_hash": "6bf9ef4394aa50111e84b3013eefd786",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 215,
"avg_line_length": 64,
"alnum_prop": 0.7234375,
"repo_name": "SeeD-Seifer/Mvx.Geocoder",
"id": "57a4bc69ae07f579af8d788bcd6819ccd3ab0bff",
"size": "642",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Mvx.Geocorder.Sample.Droid/Properties/AndroidManifest.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "23682"
},
{
"name": "Puppet",
"bytes": "400"
},
{
"name": "Shell",
"bytes": "107"
}
],
"symlink_target": ""
} |
import os
from devilry.devilry_compressionutil.backends import backends_base
class DevilryExaminerZipBackend(backends_base.PythonZipFileBackend):
backend_id = 'devilry_examiner_local'
@classmethod
def delete_archive(cls, full_path):
if not os.path.exists(full_path):
return False
try:
os.remove(full_path)
except OSError:
return False
return True
| {
"content_hash": "181009d54dbe52584ec8b7464c412fdb",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 68,
"avg_line_length": 25.352941176470587,
"alnum_prop": 0.6612529002320185,
"repo_name": "devilry/devilry-django",
"id": "d55377203747dc5c887ae5478d2293c4556cb843",
"size": "431",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "devilry/devilry_examiner/views/assignment/download_files/backends.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "513510"
},
{
"name": "Dockerfile",
"bytes": "211"
},
{
"name": "HTML",
"bytes": "421969"
},
{
"name": "JavaScript",
"bytes": "756713"
},
{
"name": "Less",
"bytes": "166670"
},
{
"name": "PLpgSQL",
"bytes": "397986"
},
{
"name": "Python",
"bytes": "6507968"
},
{
"name": "Shell",
"bytes": "10328"
}
],
"symlink_target": ""
} |
- [Installation](#installation)
- [Local Development Environment](#local-development-environment)
- [Routing](#routing)
- [Creating A View](#creating-a-view)
- [Creating A Migration](#creating-a-migration)
- [Eloquent ORM](#eloquent-orm)
- [Displaying Data](#displaying-data)
- [Deploying Your Application](#deploying-your-application)
<a name="installation"></a>
## Installation
### Via Laravel Installer
First, download the Laravel installer using Composer.
composer global require "laravel/installer=~1.1"
Make sure to place the `~/.composer/vendor/bin` directory in your PATH (or `C:\%HOMEPATH%\AppData\Roaming\Composer\vendor\bin` if working with Windows) so the `laravel` executable is found when you run the `laravel` command in your terminal.
Once installed, the simple `laravel new` command will create a fresh Laravel installation in the directory you specify. For instance, `laravel new blog` would create a directory named `blog` containing a fresh Laravel installation with all dependencies installed. This method of installation is much faster than installing via Composer.
### Via Composer
The Laravel framework utilizes [Composer](http://getcomposer.org) for installation and dependency management. If you haven't already, start by [installing Composer](http://getcomposer.org/doc/00-intro.md).
Now you can install Laravel by issuing the following command from your terminal:
composer create-project laravel/laravel your-project-name 4.2.*
This command will download and install a fresh copy of Laravel in a new `your-project-name` folder within your current directory.
If you prefer, you can alternatively download a copy of the [Laravel repository from GitHub](https://github.com/laravel/docs/archive/4.2.zip) manually. Next run the `composer install` command in the root of your manually created project directory. This command will download and install the framework's dependencies.
### Permissions
After installing Laravel, you may need to grant the web server write permissions to the `app/storage` directories. See the [Installation](/docs/4.2/installation) documentation for more details on configuration.
### Serving Laravel
Typically, you may use a web server such as Apache or Nginx to serve your Laravel applications. If you are on PHP 5.4+ and would like to use PHP's built-in development server, you may use the `serve` Artisan command:
php artisan serve
By default the HTTP-server will listen to port 8000. However if that port is already in use or you wish to serve multiple applications this way, you might want to specify what port to use. Just add the --port argument:
php artisan serve --port=8080
<a name="directories"></a>
### Directory Structure
After installing the framework, take a glance around the project to familiarize yourself with the directory structure. The `app` directory contains folders such as `views`, `controllers`, and `models`. Most of your application's code will reside somewhere in this directory. You may also wish to explore the `app/config` directory and the configuration options that are available to you.
<a name="local-development-environment"></a>
## Local Development Environment
In the past, configuring a local PHP development environment on your machine was a headache. Installing the proper version of PHP, required extensions, and other needed components is time consuming and confusing. Instead, consider using [Laravel Homestead](/docs/4.2/homestead). Homestead is a simple virtual machine designed for Laravel and [Vagrant](http://vagrantup.com). Since the Homestead Vagrant box is pre-packaged with all of the software you need to build robust PHP applications, you can create a virtualized, isolated development environment in seconds. Here is a list of some of the goodies included with Homestead:
- Nginx
- PHP 5.6
- MySQL
- Redis
- Memcached
- Beanstalk
Don't worry, even though "virtualized" sounds complicated, it's painless. VirtualBox and Vagrant, which are Homestead's two dependencies, both include simple, graphical installers for all popular operating systems. Check out the [Homestead documentation](/docs/4.2/homestead) to get started.
<a name="routing"></a>
## Routing
To get started, let's create our first route. In Laravel, the simplest route is a route to a Closure. Pop open the `app/routes.php` file and add the following route to the bottom of the file:
Route::get('users', function()
{
return 'Users!';
});
Now, if you hit the `/users` route in your web browser, you should see `Users!` displayed as the response. Great! You've just created your first route.
Routes can also be attached to controller classes. For example:
Route::get('users', 'UserController@getIndex');
This route informs the framework that requests to the `/users` route should call the `getIndex` method on the `UserController` class. For more information on controller routing, check out the [controller documentation](/docs/4.2/controllers).
<a name="creating-a-view"></a>
## Creating A View
Next, we'll create a simple view to display our user data. Views live in the `app/views` directory and contain the HTML of your application. We're going to place two new views in this directory: `layout.blade.php` and `users.blade.php`. First, let's create our `layout.blade.php` file:
<html>
<body>
<h1>Laravel Quickstart</h1>
@yield('content')
</body>
</html>
Next, we'll create our `users.blade.php` view:
@extends('layout')
@section('content')
Users!
@stop
Some of this syntax probably looks quite strange to you. That's because we're using Laravel's templating system: Blade. Blade is very fast, because it is simply a handful of regular expressions that are run against your templates to compile them to pure PHP. Blade provides powerful functionality like template inheritance, as well as some syntax sugar on typical PHP control structures such as `if` and `for`. Check out the [Blade documentation](/docs/4.2/templates) for more details.
Now that we have our views, let's return it from our `/users` route. Instead of returning `Users!` from the route, return the view instead:
Route::get('users', function()
{
return View::make('users');
});
Wonderful! Now you have setup a simple view that extends a layout. Next, let's start working on our database layer.
<a name="creating-a-migration"></a>
## Creating A Migration
To create a table to hold our data, we'll use the Laravel migration system. Migrations let you expressively define modifications to your database, and easily share them with the rest of your team.
First, let's configure a database connection. You may configure all of your database connections from the `app/config/database.php` file. By default, Laravel is configured to use MySQL, and you will need to supply connection credentials within the database configuration file. If you wish, you may change the `driver` option to `sqlite` and it will use the SQLite database included in the `app/database` directory.
Next, to create the migration, we'll use the [Artisan CLI](/docs/4.2/artisan). From the root of your project, run the following from your terminal:
php artisan migrate:make create_users_table
Next, find the generated migration file in the `app/database/migrations` folder. This file contains a class with two methods: `up` and `down`. In the `up` method, you should make the desired changes to your database tables, and in the `down` method you simply reverse them.
Let's define a migration that looks like this:
public function up()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('email')->unique();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
Next, we can run our migrations from our terminal using the `migrate` command. Simply execute this command from the root of your project:
php artisan migrate
If you wish to rollback a migration, you may issue the `migrate:rollback` command. Now that we have a database table, let's start pulling some data!
<a name="eloquent-orm"></a>
## Eloquent ORM
Laravel ships with a superb ORM: Eloquent. If you have used the Ruby on Rails framework, you will find Eloquent familiar, as it follows the ActiveRecord ORM style of database interaction.
First, let's define a model. An Eloquent model can be used to query an associated database table, as well as represent a given row within that table. Don't worry, it will all make sense soon! Models are typically stored in the `app/models` directory. Let's define a `User.php` model in that directory like so:
class User extends Eloquent {}
Note that we do not have to tell Eloquent which table to use. Eloquent has a variety of conventions, one of which is to use the plural form of the model name as the model's database table. Convenient!
Using your preferred database administration tool, insert a few rows into your `users` table, and we'll use Eloquent to retrieve them and pass them to our view.
Now let's modify our `/users` route to look like this:
Route::get('users', function()
{
$users = User::all();
return View::make('users')->with('users', $users);
});
Let's walk through this route. First, the `all` method on the `User` model will retrieve all of the rows in the `users` table. Next, we're passing these records to the view via the `with` method. The `with` method accepts a key and a value, and is used to make a piece of data available to a view.
Awesome. Now we're ready to display the users in our view!
<a name="displaying-data"></a>
## Displaying Data
Now that we have made the `users` available to our view, we can display them like so:
@extends('layout')
@section('content')
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeach
@stop
You may be wondering where to find our `echo` statements. When using Blade, you may echo data by surrounding it with double curly braces. It's a cinch. Now, you should be able to hit the `/users` route and see the names of your users displayed in the response.
This is just the beginning. In this tutorial, you've seen the very basics of Laravel, but there are so many more exciting things to learn. Keep reading through the documentation and dig deeper into the powerful features available to you in [Eloquent](/docs/4.2/eloquent) and [Blade](/docs/4.2/templates). Or, maybe you're more interested in [Queues](/docs/4.2/queues) and [Unit Testing](/docs/4.2/testing). Then again, maybe you want to flex your architecture muscles with the [IoC Container](/docs/4.2/ioc). The choice is yours!
<a name="deploying-your-application"></a>
## Deploying Your Application
One of Laravel's goals is to make PHP application development enjoyable from download to deploy, and [Laravel Forge](https://forge.laravel.com) provides a simple way to deploy your Laravel applications onto blazing fast servers. Forge can configure and provision servers on DigitalOcean, Linode, Rackspace, and Amazon EC2. Like Homestead, all of the latest goodies are included: Nginx, PHP 5.6, MySQL, Postgres, Redis, Memcached, and more. Forge "Quick Deploy" can even deploy your code for you each time you push changes out to GitHub or Bitbucket!
On top of that, Forge can help you configure queue workers, SSL, Cron jobs, sub-domains, and more. For more information, visit the [Forge website](https://forge.laravel.com).
| {
"content_hash": "6a668637c8573ab470740a4095169f9f",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 628,
"avg_line_length": 56.14778325123153,
"alnum_prop": 0.7617125811545885,
"repo_name": "kelixlabs/docs-1",
"id": "5bbcacb720e1a5ccd409ac6991d52267424bca96",
"size": "11420",
"binary": false,
"copies": "1",
"ref": "refs/heads/4.2",
"path": "quick.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<html>
<head>
<link rel="stylesheet" href="./css/maps.css"/>
</head>
<body>
<div id="wrapper" style="width:714px;margin:auto">
<p>Web Mercator image tiles map using <a href="http://github.com/gagan-bansal/web-mercator-tiles">web-mercator-tiles</a></p>
<div id="map">
</div>
<span> Center (long, lat) </span><input type="text" id="center" value="-71.147, 42.472"/>
<span> Zoom </span> <input type="number" id="zoom" value="12" style="width:50px" />
<input id="zoomTo" type="button" value="Zoom To" />
</div>
<script type="text/javascript" src="./js/build.js"></script>
</body>
</html>
| {
"content_hash": "c738fd84d2d09c2a70e9f0f8e7bb0354",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 130,
"avg_line_length": 37.88235294117647,
"alnum_prop": 0.5993788819875776,
"repo_name": "maps-on-blackboard/web-mercator-tiles-map",
"id": "23447017c2ffd1f7c371ba2bf2161e4adfbcfc66",
"size": "644",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "map1.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "173"
},
{
"name": "HTML",
"bytes": "644"
},
{
"name": "JavaScript",
"bytes": "26112"
}
],
"symlink_target": ""
} |
package com.intellij.xml.index;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.HashMap;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataExternalizer;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
/**
* @author Dmitry Avdeev
*/
public class XmlTagNamesIndex extends XmlIndex<Void> {
public static Collection<VirtualFile> getFilesByTagName(String tagName, final Project project) {
return FileBasedIndex.getInstance().getContainingFiles(NAME, tagName, createFilter(project));
}
public static Collection<String> getAllTagNames(Project project) {
return FileBasedIndex.getInstance().getAllKeys(NAME, project);
}
static void requestRebuild() {
FileBasedIndex.getInstance().requestRebuild(NAME);
}
private static final ID<String,Void> NAME = ID.create("XmlTagNames");
public ID<String, Void> getName() {
return NAME;
}
public DataIndexer<String, Void, FileContent> getIndexer() {
return new DataIndexer<String, Void, FileContent>() {
@NotNull
public Map<String, Void> map(final FileContent inputData) {
final Collection<String> tags = XsdTagNameBuilder.computeTagNames(new ByteArrayInputStream(inputData.getContent()));
if (tags != null && !tags.isEmpty()) {
final HashMap<String, Void> map = new HashMap<String, Void>(tags.size());
for (String tag : tags) {
map.put(tag, null);
}
return map;
} else {
return Collections.emptyMap();
}
}
};
}
public DataExternalizer<Void> getValueExternalizer() {
return ScalarIndexExtension.VOID_DATA_EXTERNALIZER;
}
}
| {
"content_hash": "e0e30f491c351de9244172cd0b518d71",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 124,
"avg_line_length": 30.16393442622951,
"alnum_prop": 0.7092391304347826,
"repo_name": "jexp/idea2",
"id": "f26e3705671a19fc94ea4710c4dedec9e53dbc0f",
"size": "2440",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xml/impl/src/com/intellij/xml/index/XmlTagNamesIndex.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "6350"
},
{
"name": "C#",
"bytes": "103"
},
{
"name": "C++",
"bytes": "30760"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Java",
"bytes": "72888555"
},
{
"name": "JavaScript",
"bytes": "910"
},
{
"name": "PHP",
"bytes": "133"
},
{
"name": "Perl",
"bytes": "6523"
},
{
"name": "Shell",
"bytes": "4068"
}
],
"symlink_target": ""
} |
using System;
using System.Web;
using MyChy.Frame.Common.MvcHelper;
namespace MyChy.Frame.Common.Helper
{
public class CookieHelper
{
public CookieHelper()
{
}
private static readonly string Des3Key = WebConfig.AppSettingsName<string>("CookieHelperKey", "dtvb^*3e");
/// <summary>
/// 设置Cookie
/// </summary>
/// <param name="cookiename"></param>
/// <param name="cookievalue"></param>
/// <param name="domainname">如果为空,则设置当前域名</param>
/// <param name="hour"></param>
/// <param name="minute"></param>
/// <returns></returns>
public static bool SetCookie(string cookiename, string cookievalue, string domainname, int hour, int minute)
{
if (cookievalue == null) return false;
//设定cookie 过期时间.
DateTime dtExpiry = DateTime.Now.AddHours(hour).AddMinutes(minute);
var httpCookie = HttpContext.Current.Response.Cookies[cookiename];
if (httpCookie == null) return false;
HttpCookie sessionCookie = null;
//对 SessionId 进行备份.
if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
{
string sesssionId = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value.ToString();
sessionCookie = new HttpCookie("ASP.NET_SessionId") { Value = sesssionId };
}
httpCookie.Expires = dtExpiry;
//设定cookie 域名.
if (domainname.Length == 0)
{
string domain = string.Empty;
if (HttpContext.Current.Request.Params["HTTP_HOST"] != null)
{
//domain = "www.elong.com";
domain = HttpContext.Current.Request.Params["HTTP_HOST"].ToString();
}
if (domain.IndexOf(".", System.StringComparison.Ordinal) > -1)
{
int index = domain.IndexOf(".", System.StringComparison.Ordinal);
domain = domain.Substring(index + 1);
httpCookie.Domain = domain;
}
}
else
{
httpCookie.Domain = domainname;
}
httpCookie.Value = cookievalue;
//如果cookie总数超过20 个, 重写ASP.NET_SessionId, 以防Session 丢失.
if (HttpContext.Current.Request.Cookies.Count <= 20 || sessionCookie == null) return true;
if (sessionCookie.Value == string.Empty) return true;
HttpContext.Current.Response.Cookies.Remove("ASP.NET_SessionId");
HttpContext.Current.Response.Cookies.Add(sessionCookie);
return true;
}
public static bool SetCookie(string cookiename, string cookievalue, string domainname)
{
if (cookievalue == null) return false;
var httpCookie = HttpContext.Current.Response.Cookies[cookiename];
if (httpCookie != null)
{
if (domainname.Length == 0)
{
string domain = string.Empty;
if (HttpContext.Current.Request.Params["HTTP_HOST"] != null)
{
//domain = "www.elong.com";
domain = HttpContext.Current.Request.Params["HTTP_HOST"].ToString();
}
if (domain.IndexOf(".", System.StringComparison.Ordinal) > -1)
{
int index = domain.IndexOf(".", System.StringComparison.Ordinal);
domain = domain.Substring(index + 1);
httpCookie.Domain = domain;
}
}
else
{
httpCookie.Domain = domainname;
}
httpCookie.Value = cookievalue;
}
return true;
}
/// <summary>
/// 获取Cookie
/// </summary>
/// <param name="cookiekey"></param>
/// <returns></returns>
public static string GetCookie(string cookiekey)
{
string cookyval;
try
{
if (HttpContext.Current.Request.Cookies[cookiekey] == null)
{
return "";
}
cookyval = HttpContext.Current.Request.Cookies[cookiekey].Value;
}
catch
{
return "";
}
return cookyval;
}
/// <summary>
///
/// </summary>
/// <param name="cookiename"></param>
/// <param name="cookievalue"></param>
/// <param name="domainname"></param>
/// <param name="hour"></param>
/// <param name="minute"></param>
/// <returns></returns>
public static bool SetCookie3Des(string cookiename, string cookievalue, string domainname, int hour, int minute)
{
cookievalue = SafeSecurity.EncryptDES(cookievalue, Des3Key);
return SetCookie(cookiename, cookievalue, domainname, hour, minute);
}
/// <summary>
///
/// </summary>
/// <param name="cookiekey"></param>
/// <returns></returns>
public static string GetCookie3Des(string cookiekey)
{
string cookyval = GetCookie(cookiekey);
if (!String.IsNullOrEmpty(cookiekey))
{
cookyval = SafeSecurity.DecryptDES(cookyval, Des3Key);
}
return cookyval;
}
/// <summary>
/// 清除Cookie
/// </summary>
/// <param name="cookiekey"></param>
public static void RemoveCookie(string cookiekey)
{
CookieHelper.SetCookie(cookiekey, "", "", -1, 0);
}
}
}
| {
"content_hash": "432a423408dc698514d8232cbcaedb3a",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 120,
"avg_line_length": 35.97041420118343,
"alnum_prop": 0.49185721335746013,
"repo_name": "chyenc/EF",
"id": "f8e60cbd55186b386b1e4d39a7a73a012a8daae9",
"size": "6173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MyChy.Frame.Common/Helper/CookieHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "172336"
}
],
"symlink_target": ""
} |
package com.kredx.tastysearch.service;
import com.kredx.tastysearch.review.Review;
import com.kredx.tastysearch.review.ReviewCollection;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
* Created by prashkr on 7/4/16.
*/
public class LoadTestingService {
/**
* List of all the words in all the reviews. No duplicates here.
* Todo: Remove stop words such as 'a', 'of', 'the', 'if', etc.
*
*/
public static List<String> words = new ArrayList<>();
/**
* Loads words from all reviews into the above mentioned structure.
*/
public void loadWords() {
Map<String, Boolean> wordMap = new HashMap<>();
for (Review review : ReviewCollection.sampledReviews) {
String reviewText = review.getFilteredText();
StringTokenizer st = new StringTokenizer(reviewText);
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (!wordMap.containsKey(token)) {
//Todo: exclude stop words
wordMap.put(token, true);
}
}
}
words.addAll(wordMap.keySet());
}
/**
* Generates test set and writes it to a file in the following format:
*
* token1 token2 token3...
* token4 token5 token6...
* .
* .
*
* @param testSetFileName Write test set to this file
* @param testSetSize Number of tests to generate
* @param maxTestTokens Maximum possible tokens allowed in a test
* @throws IOException
*/
public static void generateTestSet(String testSetFileName, int testSetSize, int maxTestTokens) throws IOException {
List<String> lines = new ArrayList<>();
for (int i = 0; i < testSetSize; i++) {
int numTokens = RandomNumberService.generateRandomNumberBetween(1, maxTestTokens);
String line = generateTest(numTokens);
lines.add(line);
}
Path file = Paths.get(testSetFileName);
Files.write(file, lines, Charset.forName("UTF-8"));
}
/**
* Generates a line in the following form:
*
* "token1 token2 token3..."
*
* @param numTokens
* @return
*/
private static String generateTest(int numTokens) {
Map<Integer, Boolean> tokenMap = new HashMap<>();
int size = words.size();
String line = "";
for (int i = 0; i < numTokens; i++) {
int wordIndex = RandomNumberService.generateRandomNumberBetween(0, size - 1);
if (!tokenMap.containsKey(wordIndex)) {
line += words.get(wordIndex) + " ";
}
}
return line.trim();
}
}
| {
"content_hash": "3b3f1af302de96dae76293ab1d26d111",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 119,
"avg_line_length": 29.768421052631577,
"alnum_prop": 0.594059405940594,
"repo_name": "prashkr/tasty-search",
"id": "4a7dc95485eff1be8e8085e7c34c5426942d6807",
"size": "2828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/kredx/tastysearch/service/LoadTestingService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "369"
},
{
"name": "HTML",
"bytes": "2983"
},
{
"name": "Java",
"bytes": "33592"
},
{
"name": "JavaScript",
"bytes": "812"
}
],
"symlink_target": ""
} |
package com.hazelcast.internal.nearcache.impl.invalidation;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import static java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater;
import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
/**
* Contains one partitions' invalidation metadata.
*/
public final class MetaDataContainer {
private static final AtomicLongFieldUpdater<MetaDataContainer> SEQUENCE
= newUpdater(MetaDataContainer.class, "sequence");
private static final AtomicLongFieldUpdater<MetaDataContainer> STALE_SEQUENCE
= newUpdater(MetaDataContainer.class, "staleSequence");
private static final AtomicLongFieldUpdater<MetaDataContainer> MISSED_SEQUENCE_COUNT =
newUpdater(MetaDataContainer.class, "missedSequenceCount");
private static final AtomicReferenceFieldUpdater<MetaDataContainer, UUID> UUID =
newUpdater(MetaDataContainer.class, java.util.UUID.class, "uuid");
/**
* Sequence number of last received invalidation event
*/
private volatile long sequence;
/**
* Holds the biggest sequence number that is lost, lower sequences from this sequence are accepted as stale
*
* @see StaleReadDetector
*/
private volatile long staleSequence;
/**
* Number of missed sequence count
*/
private volatile long missedSequenceCount;
/**
* UUID of the source partition that generates invalidation events
*/
private volatile UUID uuid;
public MetaDataContainer() {
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
UUID.set(this, uuid);
}
public boolean casUuid(UUID prevUuid, UUID newUuid) {
return UUID.compareAndSet(this, prevUuid, newUuid);
}
public long getSequence() {
return sequence;
}
public void setSequence(long sequence) {
SEQUENCE.set(this, sequence);
}
public boolean casSequence(long currentSequence, long nextSequence) {
return SEQUENCE.compareAndSet(this, currentSequence, nextSequence);
}
public void resetSequence() {
SEQUENCE.set(this, 0);
}
public long getStaleSequence() {
return STALE_SEQUENCE.get(this);
}
public boolean casStaleSequence(long lastKnownStaleSequence, long lastReceivedSequence) {
return STALE_SEQUENCE.compareAndSet(this, lastKnownStaleSequence, lastReceivedSequence);
}
public void resetStaleSequence() {
STALE_SEQUENCE.set(this, 0);
}
public long addAndGetMissedSequenceCount(long missCount) {
return MISSED_SEQUENCE_COUNT.addAndGet(this, missCount);
}
public long getMissedSequenceCount() {
return missedSequenceCount;
}
}
| {
"content_hash": "a5f88ccfa7fcad846af3bf619f0b9258",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 111,
"avg_line_length": 29.53061224489796,
"alnum_prop": 0.7093987560469938,
"repo_name": "mdogan/hazelcast",
"id": "ebd572c4293ce67c7c7ae3f5405dc82c8420670b",
"size": "3519",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hazelcast/src/main/java/com/hazelcast/internal/nearcache/impl/invalidation/MetaDataContainer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1862"
},
{
"name": "C",
"bytes": "3721"
},
{
"name": "Java",
"bytes": "45797218"
},
{
"name": "Shell",
"bytes": "30002"
}
],
"symlink_target": ""
} |
const path = require('path');
const webpackMerge = require('webpack-merge');
const autoprefixer = require('autoprefixer');
const webpackCommon = require('./common.config');
// webpack plugins
const HtmlWebpackPlugin = require('html-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
module.exports = webpackMerge(webpackCommon, {
bail: true,
devtool: 'source-map',
output: {
path: path.resolve(__dirname, '../dist'),
filename: '[name]-[hash].min.js',
sourceMapFilename: '[name]-[hash].map',
chunkFilename: '[id]-[chunkhash].js'
},
module: {
rules: [
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader?modules&localIdentName=[name]__[local]&minimize&sourceMap&importLoaders=2',
'postcss-loader',
'sass-loader?outputStyle=expanded&sourceMap&sourceMapContents'
]
})
}
]
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: path.resolve(__dirname, '../static/index.html'),
favicon: path.resolve(__dirname, '../static/favicon.ico'),
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
new CleanWebpackPlugin(['dist'], {
root: path.resolve(__dirname, '..'),
exclude: '.gitignore'
}),
new DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new ExtractTextPlugin('[name]-[chunkhash].min.css'),
new UglifyJsPlugin({
compressor: {
screw_ie8: true,
warnings: false
},
mangle: {
screw_ie8: true
},
output: {
comments: false,
screw_ie8: true
},
sourceMap: true
}),
new LoaderOptionsPlugin({
options: {
context: '/',
sassLoader: {
includePaths: [path.resolve(__dirname, '../src')]
},
postcss: function () {
return [autoprefixer];
}
}
})
]
});
| {
"content_hash": "39ec6d8d94cd231054be86c7a25f51dd",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 99,
"avg_line_length": 24.714285714285715,
"alnum_prop": 0.5892100192678227,
"repo_name": "rdf-pipeline/shex-schema-ide",
"id": "7ac50a696361ff0eb45991bda530c1faea20350d",
"size": "2595",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mdan/webpack/prod.config.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11233"
},
{
"name": "HTML",
"bytes": "15423"
},
{
"name": "JavaScript",
"bytes": "12074"
}
],
"symlink_target": ""
} |
<?php declare(strict_types = 1);
namespace Nextras\Orm\Exception;
class LogicException extends \LogicException
{
}
| {
"content_hash": "c954320e231d94786592c2e1768581d7",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 44,
"avg_line_length": 14.75,
"alnum_prop": 0.7627118644067796,
"repo_name": "nextras/orm",
"id": "1a17a215b3adb7757a1532a765af399d799c13ed",
"size": "118",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Exception/LogicException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "641808"
},
{
"name": "PLpgSQL",
"bytes": "5571"
},
{
"name": "Shell",
"bytes": "103"
}
],
"symlink_target": ""
} |
title: "Java Polymorphism And equals()"
categories: articles
date: 2014-01-29
modified: 2014-01-29
tags: [java,core,polymorphism]
image:
feature:
teaser: /assets/images/2014/01/equals.jpg
path: /assets/images/2014/01/equals.jpg
thumb:
excerpt: How should equals() behave in case of polymorphic classes? What are the pitfalls here?
---
Let's start by having a small introduction. The mother of all Java classes -- `Object` -- does define a `equals()` method, which is meant to return true if the passed instance is equal to the current instance. The default implementation is limited to comparing references. So it will only return `true` when the current and the passed object are the same. The `equals()` method is meant to be overridden by extending classes with meaningful logic. The implementation has to obey some requirements (from javadoc on [Object.equals()]):
> The equals() method guarantees that...
>
> * It is reflexive: for any non-null reference value `x`, `x.equals(x)` should return `true`.
* It is symmetric: for any non-null reference values `x` and `y`, `x.equals(y)` should return `true` if and only if `y.equals(x)` returns `true`.
* It is transitive: for any non-null reference values `x`, `y`, and `z`, if `x.equals(y)` returns `true` and `y.equals(z)` returns `true`, then `x.equals(z)` should return `true`.
* It is consistent: for any non-null reference values `x` and `y`, multiple invocations of `x.equals(y)` consistently return `true` or consistently return `false`, provided no information used in equals comparisons on the objects is modified.
* For any non-null reference value `x`, `x.equals(null)` should return `false`.
Quite a bunch. Luckily those requirements are often easy to achieve. Let's create a simple class and equip it with a `equals()` method.
## A Drink
```java
public class Drink {
private final int size;
public Drink(final int size) {
this.size = size;
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Drink)) return false;
return equals((Drink) obj);
}
public boolean equals(final Drink other) {
return this.size == other.size;
}
}
```
This `equals()` implementation obeys all the requirements above. And I added a convenience method with the exact type. Note that `equals(Drink)` does overload `Object.equals(Object)` but it [does not override] it! The difference between those two will be important later.
## A Drink? A Coffee? A Coke?
Now let's introduce [polymorphism]. We add two classes Coffee and Coke which extend the `Drink` class:
```java
public class Coffee extends Drink {
private final int coffeine;
public Coffee(final int size, final int coffeine) {
super(size);
this.coffeine = coffeine;
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Coffee)) return false;
return equals((Coffee) obj);
}
public boolean equals(final Coffee other) {
if (!super.equals(other)) return false;
return coffeine == other.coffeine;
}
}
public class Coke extends Drink {
private final int sugar;
public Coke(final int size, final int sugar) {
super(size);
this.sugar = sugar;
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Coke)) return false;
return equals((Coke) obj);
}
public boolean equals(final Coke other) {
if (!super.equals(other)) return false;
return sugar == other.sugar;
}
}
```
The `equals()` methods are implemented here in a similar way. Everything looks fine, doesn't it? Let's see how the `equals()` methods behave:
```java
final Drink drink = new Drink(15);
final Drink secondDrink = new Drink(15);
System.out.println("drink.equals(secondDrink): " + drink.equals(secondDrink));
System.out.println("secondDrink.equals(drink): " + secondDrink.equals(drink));
final Coffee coffee = new Coffee(15, 3);
final Coke coke = new Coke(15, 42);
System.out.println("coffee.equals(drink): " + coffee.equals(drink);
System.out.println("drink.equals(coffee): " + drink.equals(coffee));
System.out.println("coke.equals(coffee): " + coke.equals(coffee));
```
What’s the output? Your brain might tell you something like this:
~~~
drink.equals(secondDrink): true
secondDrink.equals(drink): true
coffee.equals(drink): false
drink.equals(coffee): false
coke.equals(coffee): false
But what’s the actual output? This:
drink.equals(secondDrink): true
secondDrink.equals(drink): true
coffee.equals(drink): true
drink.equals(coffee): true
coke.equals(coffee): true
~~~
Wow! What's happening? `drink.equals(coffee)` is passed a parameter of type `Coffee`. The best method match for this type is `Drink.equals(Drink)`. This method does only compare the size field. Since it's equal it returns true. `coffee.equals(drink)` is passed a parameter of type `Drink`. The best method match for this type is.... `Drink.equals(Drink)`! Not `Coffee.equals(Object)`! So again only the size field is compared. The same goes for `coke.equals(coffee)`: `Drink.equals(Drink)` is invoked.
**First lesson**: it’s a bad idea to implement convenience public equals() methods with different types than Object. Or in other words: do not overload equals(), override it.
Now let's "fix" this problem by making the overloaded methods private. What will be the output this time? This:
~~~
drink.equals(secondDrink): true
secondDrink.equals(drink): true
coffee.equals(drink): false
drink.equals(coffee): true
coffee.equals(coke): false
~~~
Still not quite the output we're expecting. What's happening now? When `coffee.equals(drink)` is invoked, the `Coffee.equals(Object)` method is executed, `Drink` instance is checked against `instanceof Coffee` and this evaluates to `false`. But when we invoke `drink.equals(coffee)` the `equals()` implementation in `Drink` is executed and the passed instance is checked against `instanceof Drink`. Since `Coffee` is a extension of `Drink`, this evaluates to `true`.
## Not all Drinks are Coffees
So is polymorphism broken in Java? Not quite. It seems like `instanceof` is not the check you should use per default in `equals()`. It's sometimes important, we'll see in a minute, but usually what you'd like to do is to use `Object.getClass()` and compare the class of the passed instance to the class of the current instance:
```java
public class Drink {
...
@Override
public boolean equals(final Object obj) {
if (obj == null) return false;
if (this.getClass() != obj.getClass()) return false;
return equals((Drink) obj);
}
private boolean equals(final Drink other) {
return this.size == other.size;
}
}
// changes in Coffee and Coke similar
```
As specified by [documentation of getClass()], it is guaranteed to return the same `Class` instance for the same class. So it is save to use the `==` operator. Note that `obj.getClass()` is compared against `this.getClass()` and not against `Drink.class`! If we'd compare against the hard coded class `super.equals()` invocations from extending classes would always fail for non `Drink` instances.
**Second lesson**: use `Object.getClass()` in `equals()` if unsure. Only use `instanceof` if you know what you do. ;)
## Instanceof
Now when would one want to use `instanceof` in `equals()` implementations? The semantics of `equals()` implementations are actually up to you (as long you follow the restrictions stated at the beginning). In my example above I wanted to have `Drink!=Coffee!=Coke`. But that's just a definition thing. Sometimes you want to have a set of types behave like one type. The Java class library does this for lists and maps for example. A `TreeMap` and a `HashMap` are considered equal if they contain the same objects. Even though a `TreeMap` has an element order which a `HashMap` does not have. The types achieve this by having a `AbstractMap` class implement a [equals()] method which checks against `instanceof Map` and checks only `Map` properties. All extensions of `AbstractMap` do not override (and do not overload) `equals()`.
## One more thing
Don't forget to implement `hashCode()` if you override `equals()`. Both methods have a tight relationship. Whenever `a.equals(b)` returns true, also `a.hashCode()` has to be equal to `b.hashCode()`!
[Object.equals()]: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals%28java.lang.Object%29
[does not override]: https://stackoverflow.com/questions/10568772/overloaded-and-overridden-in-java
[polymorphism]: https://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29
[documentation of getClass()]: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#getClass%28%29
[equals()]: https://docs.oracle.com/javase/8/docs/api/java/util/AbstractMap.html#equals-java.lang.Object-
| {
"content_hash": "e856f146da4a5805a4b8b791ffbaeb9e",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 829,
"avg_line_length": 48.899441340782126,
"alnum_prop": 0.7336913058379984,
"repo_name": "ewirch/ewirch.github.io",
"id": "a378ab66f816dd59484e0892b5fb77462a719f55",
"size": "8763",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2014-01-29-java-polymorphism-and-equals.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "234"
},
{
"name": "Ruby",
"bytes": "7982"
}
],
"symlink_target": ""
} |
using namespace swift;
using DenseFunctionSet = llvm::DenseSet<SILFunction *>;
using ImmutableFunctionSet = llvm::ImmutableSet<SILFunction *>;
STATISTIC(NumMandatoryInlines,
"Number of function application sites inlined by the mandatory "
"inlining pass");
template<typename...T, typename...U>
static void diagnose(ASTContext &Context, SourceLoc loc, Diag<T...> diag,
U &&...args) {
Context.Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
/// \brief Fixup reference counts after inlining a function call (which is a
/// no-op unless the function is a thick function). Note that this function
/// makes assumptions about the release/retain convention of thick function
/// applications: namely, that an apply of a thick function consumes the callee
/// and that the function implementing the closure consumes its capture
/// arguments.
static void fixupReferenceCounts(
SILBasicBlock::iterator I, SILValue CalleeValue,
SmallVectorImpl<std::pair<SILValue, ParameterConvention>> &CaptureArgs,
bool isCalleeGuaranteed) {
// Add a copy of each non-address type capture argument to lifetime extend the
// captured argument over the inlined function. This deals with the
// possibility of the closure being destroyed by an earlier application and
// thus cause the captured argument to be destroyed.
for (auto &CaptureArg : CaptureArgs) {
if (!CaptureArg.first->getType().isAddress() &&
CaptureArg.second != ParameterConvention::Direct_Guaranteed &&
CaptureArg.second != ParameterConvention::Direct_Unowned) {
createIncrementBefore(CaptureArg.first, &*I);
} else {
// FIXME: What about indirectly owned parameters? The invocation of the
// closure would perform an indirect copy which we should mimick here.
assert(CaptureArg.second != ParameterConvention::Indirect_In &&
"Missing indirect copy");
}
}
// Destroy the callee as the apply would have done.
if (!isCalleeGuaranteed)
createDecrementBefore(CalleeValue, &*I);
}
static SILValue cleanupLoadedCalleeValue(SILValue CalleeValue, LoadInst *LI) {
auto *PBI = cast<ProjectBoxInst>(LI->getOperand());
auto *ABI = cast<AllocBoxInst>(PBI->getOperand());
// The load instruction must have no more uses left to erase it.
if (!LI->use_empty())
return SILValue();
LI->eraseFromParent();
// Look through uses of the alloc box the load is loading from to find up to
// one store and up to one strong release.
StrongReleaseInst *SRI = nullptr;
for (Operand *ABIUse : ABI->getUses()) {
if (SRI == nullptr && isa<StrongReleaseInst>(ABIUse->getUser())) {
SRI = cast<StrongReleaseInst>(ABIUse->getUser());
continue;
}
if (ABIUse->getUser() == PBI)
continue;
return SILValue();
}
StoreInst *SI = nullptr;
for (Operand *PBIUse : PBI->getUses()) {
if (SI == nullptr && isa<StoreInst>(PBIUse->getUser())) {
SI = cast<StoreInst>(PBIUse->getUser());
continue;
}
return SILValue();
}
// If we found a store, record its source and erase it.
if (SI) {
CalleeValue = SI->getSrc();
SI->eraseFromParent();
} else {
CalleeValue = SILValue();
}
// If we found a strong release, replace it with a strong release of the
// source of the store and erase it.
if (SRI) {
if (CalleeValue)
SILBuilderWithScope(SRI).emitStrongReleaseAndFold(SRI->getLoc(),
CalleeValue);
SRI->eraseFromParent();
}
assert(PBI->use_empty());
PBI->eraseFromParent();
assert(ABI->use_empty());
ABI->eraseFromParent();
return CalleeValue;
}
/// \brief Removes instructions that create the callee value if they are no
/// longer necessary after inlining.
static void cleanupCalleeValue(SILValue CalleeValue) {
// Handle the case where the callee of the apply is a load instruction. If we
// fail to optimize, return. Otherwise, see if we can look through other
// abstractions on our callee.
if (auto *LI = dyn_cast<LoadInst>(CalleeValue)) {
CalleeValue = cleanupLoadedCalleeValue(CalleeValue, LI);
if (!CalleeValue) {
return;
}
}
SILValue CalleeSource = CalleeValue;
// Handle partial_apply/thin_to_thick -> convert_function:
// tryDeleteDeadClosure must run before deleting a ConvertFunction that
// uses the PartialApplyInst or ThinToThickFunctionInst. tryDeleteDeadClosure
// will delete any uses of the closure, including a convert_escape_to_noescape
// conversion.
if (auto *CFI = dyn_cast<ConvertFunctionInst>(CalleeValue))
CalleeSource = CFI->getOperand();
else if (auto *Cvt = dyn_cast<ConvertEscapeToNoEscapeInst>(CalleeValue))
CalleeSource = Cvt->getOperand();
if (auto *PAI = dyn_cast<PartialApplyInst>(CalleeSource)) {
SILValue Callee = PAI->getCallee();
if (!tryDeleteDeadClosure(PAI))
return;
CalleeValue = Callee;
} else if (auto *TTTFI = dyn_cast<ThinToThickFunctionInst>(CalleeSource)) {
SILValue Callee = TTTFI->getCallee();
if (!tryDeleteDeadClosure(TTTFI))
return;
CalleeValue = Callee;
}
// Handle function_ref -> convert_function -> partial_apply/thin_to_thick.
if (auto *CFI = dyn_cast<ConvertFunctionInst>(CalleeValue)) {
if (isInstructionTriviallyDead(CFI)) {
recursivelyDeleteTriviallyDeadInstructions(CFI, true);
return;
}
}
if (auto *FRI = dyn_cast<FunctionRefInst>(CalleeValue)) {
if (!FRI->use_empty())
return;
FRI->eraseFromParent();
}
}
namespace {
/// Cleanup dead closures after inlining.
class ClosureCleanup {
using DeadInstSet = SmallBlotSetVector<SILInstruction *, 4>;
/// A helper class to update an instruction iterator if
/// removal of instructions would invalidate it.
///
/// Since this is called by the SILModule callback, the instruction may longer
/// be well-formed. Do not visit its operands. However, it's position in the
/// basic block is still valid.
///
/// FIXME: Using the Module's callback mechanism is undesirable. Instead,
/// cleanupCalleeValue could be easily rewritten to use its own instruction
/// deletion helper and pass a callback to tryDeleteDeadClosure and
/// recursivelyDeleteTriviallyDeadInstructions.
class IteratorUpdateHandler : public DeleteNotificationHandler {
SILModule &Module;
SILBasicBlock::iterator CurrentI;
DeadInstSet &DeadInsts;
public:
IteratorUpdateHandler(SILBasicBlock::iterator I, DeadInstSet &DeadInsts)
: Module(I->getModule()), CurrentI(I), DeadInsts(DeadInsts) {
Module.registerDeleteNotificationHandler(this);
}
~IteratorUpdateHandler() override {
// Unregister the handler.
Module.removeDeleteNotificationHandler(this);
}
SILBasicBlock::iterator getIterator() const { return CurrentI; }
// Handling of instruction removal notifications.
bool needsNotifications() override { return true; }
// Handle notifications about removals of instructions.
void handleDeleteNotification(SILNode *node) override {
auto deletedI = dyn_cast<SILInstruction>(node);
if (!deletedI)
return;
DeadInsts.erase(deletedI);
if (CurrentI == SILBasicBlock::iterator(deletedI))
++CurrentI;
}
};
SmallBlotSetVector<SILInstruction *, 4> deadFunctionVals;
public:
/// This regular instruction deletion callback checks for any function-type
/// values that may be unused after deleting the given instruction.
void recordDeadFunction(SILInstruction *deletedInst) {
// If the deleted instruction was already recorded as a function producer,
// delete it from the map and record its operands instead.
deadFunctionVals.erase(deletedInst);
for (auto &operand : deletedInst->getAllOperands()) {
SILValue operandVal = operand.get();
if (!operandVal->getType().is<SILFunctionType>())
continue;
// Simply record all function-producing instructions used by dead
// code. Checking for a single use would not be precise because
// `deletedInst` could itself use `deadInst` multiple times.
if (auto *deadInst = operandVal->getDefiningInstruction())
deadFunctionVals.insert(deadInst);
}
}
// Note: instructions in the `deadFunctionVals` set may use each other, so the
// set needs to continue to be updated (by this handler) when deleting
// instructions. This assumes that DeadFunctionValSet::erase() is stable.
SILBasicBlock::iterator cleanupDeadClosures(SILBasicBlock::iterator II) {
IteratorUpdateHandler iteratorUpdate(II, deadFunctionVals);
for (Optional<SILInstruction *> I : deadFunctionVals) {
if (!I.hasValue())
continue;
if (auto *SVI = dyn_cast<SingleValueInstruction>(I.getValue()))
cleanupCalleeValue(SVI);
}
return iteratorUpdate.getIterator();
}
};
} // end of namespace
static void collectPartiallyAppliedArguments(
PartialApplyInst *PAI,
SmallVectorImpl<std::pair<SILValue, ParameterConvention>> &CapturedArgs,
SmallVectorImpl<SILValue> &FullArgs) {
ApplySite Site(PAI);
SILFunctionConventions CalleeConv(Site.getSubstCalleeType(),
PAI->getModule());
for (auto &Arg : PAI->getArgumentOperands()) {
unsigned CalleeArgumentIndex = Site.getCalleeArgIndex(Arg);
assert(CalleeArgumentIndex >= CalleeConv.getSILArgIndexOfFirstParam());
auto ParamInfo = CalleeConv.getParamInfoForSILArg(CalleeArgumentIndex);
CapturedArgs.push_back(std::make_pair(Arg.get(), ParamInfo.getConvention()));
FullArgs.push_back(Arg.get());
}
}
/// \brief Returns the callee SILFunction called at a call site, in the case
/// that the call is transparent (as in, both that the call is marked
/// with the transparent flag and that callee function is actually transparently
/// determinable from the SIL) or nullptr otherwise. This assumes that the SIL
/// is already in SSA form.
///
/// In the case that a non-null value is returned, FullArgs contains effective
/// argument operands for the callee function.
static SILFunction *getCalleeFunction(
SILFunction *F, FullApplySite AI, bool &IsThick,
SmallVectorImpl<std::pair<SILValue, ParameterConvention>> &CaptureArgs,
SmallVectorImpl<SILValue> &FullArgs, PartialApplyInst *&PartialApply) {
IsThick = false;
PartialApply = nullptr;
CaptureArgs.clear();
FullArgs.clear();
for (const auto &Arg : AI.getArguments())
FullArgs.push_back(Arg);
SILValue CalleeValue = AI.getCallee();
if (auto *LI = dyn_cast<LoadInst>(CalleeValue)) {
// Conservatively only see through alloc_box; we assume this pass is run
// immediately after SILGen
auto *PBI = dyn_cast<ProjectBoxInst>(LI->getOperand());
if (!PBI)
return nullptr;
auto *ABI = dyn_cast<AllocBoxInst>(PBI->getOperand());
if (!ABI)
return nullptr;
// Ensure there are no other uses of alloc_box than the project_box and
// retains, releases.
for (Operand *ABIUse : ABI->getUses())
if (ABIUse->getUser() != PBI &&
!isa<StrongRetainInst>(ABIUse->getUser()) &&
!isa<StrongReleaseInst>(ABIUse->getUser()))
return nullptr;
// Scan forward from the alloc box to find the first store, which
// (conservatively) must be in the same basic block as the alloc box
StoreInst *SI = nullptr;
for (auto I = SILBasicBlock::iterator(ABI), E = I->getParent()->end();
I != E; ++I) {
// If we find the load instruction first, then the load is loading from
// a non-initialized alloc; this shouldn't really happen but I'm not
// making any assumptions
if (&*I == LI)
return nullptr;
if ((SI = dyn_cast<StoreInst>(I)) && SI->getDest() == PBI) {
// We found a store that we know dominates the load; now ensure there
// are no other uses of the project_box except loads.
for (Operand *PBIUse : PBI->getUses())
if (PBIUse->getUser() != SI && !isa<LoadInst>(PBIUse->getUser()))
return nullptr;
// We can conservatively see through the store
break;
}
}
if (!SI)
return nullptr;
CalleeValue = SI->getSrc();
}
// PartialApply/ThinToThick -> ConvertFunction patterns are generated
// by @noescape closures.
//
// FIXME: We don't currently handle mismatched return types, however, this
// would be a good optimization to handle and would be as simple as inserting
// a cast.
auto skipFuncConvert = [](SILValue CalleeValue) {
// We can also allow a thin @escape to noescape conversion as such:
// %1 = function_ref @thin_closure_impl : $@convention(thin) () -> ()
// %2 = convert_function %1 :
// $@convention(thin) () -> () to $@convention(thin) @noescape () -> ()
// %3 = thin_to_thick_function %2 :
// $@convention(thin) @noescape () -> () to
// $@noescape @callee_guaranteed () -> ()
// %4 = apply %3() : $@noescape @callee_guaranteed () -> ()
if (auto *ThinToNoescapeCast = dyn_cast<ConvertFunctionInst>(CalleeValue)) {
auto FromCalleeTy =
ThinToNoescapeCast->getOperand()->getType().castTo<SILFunctionType>();
if (FromCalleeTy->getExtInfo().hasContext())
return CalleeValue;
auto ToCalleeTy = ThinToNoescapeCast->getType().castTo<SILFunctionType>();
auto EscapingCalleeTy = ToCalleeTy->getWithExtInfo(
ToCalleeTy->getExtInfo().withNoEscape(false));
if (FromCalleeTy != EscapingCalleeTy)
return CalleeValue;
return ThinToNoescapeCast->getOperand();
}
auto *CFI = dyn_cast<ConvertEscapeToNoEscapeInst>(CalleeValue);
if (!CFI)
return CalleeValue;
// TODO: Handle argument conversion. All the code in this file needs to be
// cleaned up and generalized. The argument conversion handling in
// optimizeApplyOfConvertFunctionInst should apply to any combine
// involving an apply, not just a specific pattern.
//
// For now, just handle conversion that doesn't affect argument types,
// return types, or throws. We could trivially handle any other
// representation change, but the only one that doesn't affect the ABI and
// matters here is @noescape, so just check for that.
auto FromCalleeTy = CFI->getOperand()->getType().castTo<SILFunctionType>();
auto ToCalleeTy = CFI->getType().castTo<SILFunctionType>();
auto EscapingCalleeTy =
ToCalleeTy->getWithExtInfo(ToCalleeTy->getExtInfo().withNoEscape(false));
if (FromCalleeTy != EscapingCalleeTy)
return CalleeValue;
return CFI->getOperand();
};
// Look through a escape to @noescape conversion.
CalleeValue = skipFuncConvert(CalleeValue);
// We are allowed to see through exactly one "partial apply" instruction or
// one "thin to thick function" instructions, since those are the patterns
// generated when using auto closures.
if (auto *PAI = dyn_cast<PartialApplyInst>(CalleeValue)) {
// Collect the applied arguments and their convention.
collectPartiallyAppliedArguments(PAI, CaptureArgs, FullArgs);
CalleeValue = PAI->getCallee();
IsThick = true;
PartialApply = PAI;
} else if (auto *TTTFI = dyn_cast<ThinToThickFunctionInst>(CalleeValue)) {
CalleeValue = TTTFI->getOperand();
IsThick = true;
}
CalleeValue = skipFuncConvert(CalleeValue);
auto *FRI = dyn_cast<FunctionRefInst>(CalleeValue);
if (!FRI)
return nullptr;
SILFunction *CalleeFunction = FRI->getReferencedFunction();
switch (CalleeFunction->getRepresentation()) {
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::WitnessMethod:
break;
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::Block:
return nullptr;
}
// If the CalleeFunction is a not-transparent definition, we can not process
// it.
if (CalleeFunction->isTransparent() == IsNotTransparent)
return nullptr;
// If CalleeFunction is a declaration, see if we can load it.
if (CalleeFunction->empty())
AI.getModule().loadFunction(CalleeFunction);
// If we fail to load it, bail.
if (CalleeFunction->empty())
return nullptr;
if (F->isSerialized() &&
!CalleeFunction->hasValidLinkageForFragileInline()) {
if (!CalleeFunction->hasValidLinkageForFragileRef()) {
llvm::errs() << "caller: " << F->getName() << "\n";
llvm::errs() << "callee: " << CalleeFunction->getName() << "\n";
llvm_unreachable("Should never be inlining a resilient function into "
"a fragile function");
}
return nullptr;
}
return CalleeFunction;
}
static std::tuple<FullApplySite, SILBasicBlock::iterator>
tryDevirtualizeApplyHelper(FullApplySite InnerAI, SILBasicBlock::iterator I,
ClassHierarchyAnalysis *CHA) {
auto NewInst = tryDevirtualizeApply(InnerAI, CHA);
if (!NewInst) {
return std::make_tuple(InnerAI, I);
}
deleteDevirtualizedApply(InnerAI);
auto newApplyAI = NewInst.getInstruction();
assert(newApplyAI && "devirtualized but removed apply site?");
return std::make_tuple(FullApplySite::isa(newApplyAI),
newApplyAI->getIterator());
}
/// \brief Inlines all mandatory inlined functions into the body of a function,
/// first recursively inlining all mandatory apply instructions in those
/// functions into their bodies if necessary.
///
/// \param F the function to be processed
/// \param AI nullptr if this is being called from the top level; the relevant
/// ApplyInst requiring the recursive call when non-null
/// \param FullyInlinedSet the set of all functions already known to be fully
/// processed, to avoid processing them over again
/// \param SetFactory an instance of ImmutableFunctionSet::Factory
/// \param CurrentInliningSet the set of functions currently being inlined in
/// the current call stack of recursive calls
///
/// \returns true if successful, false if failed due to circular inlining.
static bool
runOnFunctionRecursively(SILOptFunctionBuilder &FuncBuilder,
SILFunction *F, FullApplySite AI,
DenseFunctionSet &FullyInlinedSet,
ImmutableFunctionSet::Factory &SetFactory,
ImmutableFunctionSet CurrentInliningSet,
ClassHierarchyAnalysis *CHA) {
// Avoid reprocessing functions needlessly.
if (FullyInlinedSet.count(F))
return true;
// Prevent attempt to circularly inline.
if (CurrentInliningSet.contains(F)) {
// This cannot happen on a top-level call, so AI should be non-null.
assert(AI && "Cannot have circular inline without apply");
SILLocation L = AI.getLoc();
assert(L && "Must have location for transparent inline apply");
diagnose(F->getModule().getASTContext(), L.getStartSourceLoc(),
diag::circular_transparent);
return false;
}
// Add to the current inlining set (immutably, so we only affect the set
// during this call and recursive subcalls).
CurrentInliningSet = SetFactory.add(CurrentInliningSet, F);
SmallVector<std::pair<SILValue, ParameterConvention>, 16> CaptureArgs;
SmallVector<SILValue, 32> FullArgs;
for (auto BI = F->begin(), BE = F->end(); BI != BE; ++BI) {
// While iterating over this block, instructions are inserted and deleted.
for (auto II = BI->begin(), nextI = II; II != BI->end(); II = nextI) {
nextI = std::next(II);
FullApplySite InnerAI = FullApplySite::isa(&*II);
if (!InnerAI)
continue;
auto *ApplyBlock = InnerAI.getParent();
// *NOTE* If devirtualization succeeds, sometimes II will not be InnerAI,
// but a casted result of InnerAI or even a block argument due to
// abstraction changes when calling the witness or class method. We still
// know that InnerAI dominates II though.
std::tie(InnerAI, II) = tryDevirtualizeApplyHelper(InnerAI, II, CHA);
if (!InnerAI)
continue;
SILValue CalleeValue = InnerAI.getCallee();
bool IsThick;
PartialApplyInst *PAI;
SILFunction *CalleeFunction = getCalleeFunction(
F, InnerAI, IsThick, CaptureArgs, FullArgs, PAI);
if (!CalleeFunction)
continue;
// Then recursively process it first before trying to inline it.
if (!runOnFunctionRecursively(FuncBuilder, CalleeFunction, InnerAI,
FullyInlinedSet, SetFactory,
CurrentInliningSet, CHA)) {
// If we failed due to circular inlining, then emit some notes to
// trace back the failure if we have more information.
// FIXME: possibly it could be worth recovering and attempting other
// inlines within this same recursive call rather than simply
// propagating the failure.
if (AI) {
SILLocation L = AI.getLoc();
assert(L && "Must have location for transparent inline apply");
diagnose(F->getModule().getASTContext(), L.getStartSourceLoc(),
diag::note_while_inlining);
}
return false;
}
// Get our list of substitutions.
auto Subs = (PAI
? PAI->getSubstitutionMap()
: InnerAI.getSubstitutionMap());
SILOpenedArchetypesTracker OpenedArchetypesTracker(F);
F->getModule().registerDeleteNotificationHandler(
&OpenedArchetypesTracker);
// The callee only needs to know about opened archetypes used in
// the substitution list.
OpenedArchetypesTracker.registerUsedOpenedArchetypes(
InnerAI.getInstruction());
if (PAI) {
OpenedArchetypesTracker.registerUsedOpenedArchetypes(PAI);
}
SILInliner Inliner(FuncBuilder, SILInliner::InlineKind::MandatoryInline,
Subs, OpenedArchetypesTracker);
if (!Inliner.canInlineApplySite(InnerAI)) {
// See comment above about casting when devirtualizing and how this
// sometimes causes II and InnerAI to be different and even in different
// blocks.
II = InnerAI.getInstruction()->getIterator();
continue;
}
// Inline function at I, which also changes I to refer to the first
// instruction inlined in the case that it succeeds. We purposely
// process the inlined body after inlining, because the inlining may
// have exposed new inlining opportunities beyond those present in
// the inlined function when processed independently.
LLVM_DEBUG(llvm::errs() << "Inlining @" << CalleeFunction->getName()
<< " into @" << InnerAI.getFunction()->getName()
<< "\n");
// If we intend to inline a thick function, then we need to balance the
// reference counts for correctness.
if (IsThick) {
bool IsCalleeGuaranteed =
PAI &&
PAI->getType().castTo<SILFunctionType>()->isCalleeGuaranteed();
fixupReferenceCounts(II, CalleeValue, CaptureArgs, IsCalleeGuaranteed);
}
// Register a callback to record potentially unused function values after
// inlining.
ClosureCleanup closureCleanup;
Inliner.setDeletionCallback([&closureCleanup](SILInstruction *I) {
closureCleanup.recordDeadFunction(I);
});
// Inlining deletes the apply, and can introduce multiple new basic
// blocks. After this, CalleeValue and other instructions may be invalid.
nextI = Inliner.inlineFunction(CalleeFunction, InnerAI, FullArgs);
++NumMandatoryInlines;
// The IR is now valid, and trivial dead arguments are removed. However,
// we may be able to remove dead callee computations (e.g. dead
// partial_apply closures).
nextI = closureCleanup.cleanupDeadClosures(nextI);
assert(nextI == ApplyBlock->end()
|| nextI->getParent() == ApplyBlock
&& "Mismatch between the instruction and basic block");
}
}
// Keep track of full inlined functions so we don't waste time recursively
// reprocessing them.
FullyInlinedSet.insert(F);
return true;
}
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
namespace {
class MandatoryInlining : public SILModuleTransform {
/// The entry point to the transformation.
void run() override {
ClassHierarchyAnalysis *CHA = getAnalysis<ClassHierarchyAnalysis>();
SILModule *M = getModule();
bool ShouldCleanup = !getOptions().DebugSerialization;
DenseFunctionSet FullyInlinedSet;
ImmutableFunctionSet::Factory SetFactory;
SILOptFunctionBuilder FuncBuilder(*this);
for (auto &F : *M) {
// Don't inline into thunks, even transparent callees.
if (F.isThunk())
continue;
// Skip deserialized functions.
if (F.wasDeserializedCanonical())
continue;
runOnFunctionRecursively(FuncBuilder, &F,
FullApplySite(), FullyInlinedSet, SetFactory,
SetFactory.getEmptySet(), CHA);
}
if (!ShouldCleanup)
return;
// Now that we've inlined some functions, clean up. If there are any
// transparent functions that are deserialized from another module that are
// now unused, just remove them from the module.
//
// We do this with a simple linear scan, because transparent functions that
// reference each other have already been flattened.
for (auto FI = M->begin(), E = M->end(); FI != E; ) {
SILFunction &F = *FI++;
invalidateAnalysis(&F, SILAnalysis::InvalidationKind::Everything);
if (F.getRefCount() != 0) continue;
// Leave non-transparent functions alone.
if (!F.isTransparent())
continue;
// We discard functions that don't have external linkage,
// e.g. deserialized functions, internal functions, and thunks.
// Being marked transparent controls this.
if (F.isPossiblyUsedExternally()) continue;
// ObjC functions are called through the runtime and are therefore alive
// even if not referenced inside SIL.
if (F.getRepresentation() == SILFunctionTypeRepresentation::ObjCMethod)
continue;
// Okay, just erase the function from the module.
FuncBuilder.eraseFunction(&F);
}
}
};
} // end anonymous namespace
SILTransform *swift::createMandatoryInlining() {
return new MandatoryInlining();
}
| {
"content_hash": "dd90a849950049b009007ae453919923",
"timestamp": "",
"source": "github",
"line_count": 696,
"max_line_length": 81,
"avg_line_length": 38.60919540229885,
"alnum_prop": 0.6743822566239952,
"repo_name": "brentdax/swift",
"id": "9924339b37b65f28694c96989e8641b3d4eafe09",
"size": "28072",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/SILOptimizer/Mandatory/MandatoryInlining.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "34"
},
{
"name": "C",
"bytes": "205124"
},
{
"name": "C++",
"bytes": "30580826"
},
{
"name": "CMake",
"bytes": "468248"
},
{
"name": "D",
"bytes": "1107"
},
{
"name": "DTrace",
"bytes": "2438"
},
{
"name": "Emacs Lisp",
"bytes": "57210"
},
{
"name": "LLVM",
"bytes": "70800"
},
{
"name": "Makefile",
"bytes": "1841"
},
{
"name": "Objective-C",
"bytes": "382820"
},
{
"name": "Objective-C++",
"bytes": "243321"
},
{
"name": "Perl",
"bytes": "2211"
},
{
"name": "Python",
"bytes": "1333445"
},
{
"name": "Ruby",
"bytes": "2091"
},
{
"name": "Shell",
"bytes": "212537"
},
{
"name": "Swift",
"bytes": "25158306"
},
{
"name": "Vim script",
"bytes": "16250"
}
],
"symlink_target": ""
} |
<section id="hero">
<h1 class="animated fadeInUp">Aproveite mais tempo com a sua família,<br> o resto a gente cuida</h1>
<form>
<div>
<i class="fa fa-search"></i>
<input-dropdown
input-placeholder="Qual serviço você deseja?"
selected-item="vm.selectedDropdownItem"
default-dropdown-items="vm.dropdownItems"
item-selected-method="vm.createTask(item)">
</input-dropdown>
</div>
</form>
<div class='category-examples'>
<ul>
<li>Pintura</li>
<li>Mudanças</li>
<li>Reparos</li>
<li>Fixação</li>
</ul>
</div>
</section>
<section id="how-it-works">
<h2>Como Funciona</h2>
<div class="step">
<img alt="Poste uma Tarefa" src="assets/images/pin-post.svg">
<h4>1 - Poste uma tarefa</h4>
<p>Crie uma tarefa detalhando tudo o que você deseja.</p>
</div>
<div class="step">
<img alt="Receba Propostas" src="assets/images/documents.svg">
<h4>2 - Receba propostas</h4>
<p>Receba e avalie diferentes propostas, tenha informações sobre perfil, habilidades e preços de diferentes pessoas.</p>
</div>
<div class="step">
<img alt="Realize Tarefa" src="assets/images/task.svg">
<h4>3 - Realize com o melhor</h4>
<p>Realize a tarefa com o que melhor se adequa a sua necessidade sem medo de errar.</p>
</div>
</section>
<section id="popular-tasks">
<h2>Tarefas Populares</h2>
<div class="task">
<a href="#" ng-click="vm.createTask('Pintura')" analytics-on="click" analytics-event="CreateTask" analytics-category="Task" analytics-label="Pintura">
<div class="img" style="background-image: url('assets/images/Pintor.jpg');"></div>
<h4>Pintura</h4>
<p>Encontre o melhor profissional para sua casa</p>
</a>
</div>
<div class="task">
<a href="#" ng-click="vm.createTask('Webdesign')" analytics-on="click" analytics-event="CreateTask" analytics-category="Task" analytics-label="Webdesign">
<div class="img" style="background-image: url('assets/images/Webdesign.jpg');"></div>
<h4>Webdesign</h4>
<p>Encontre um profissional e se destaque na internet e nas redes sociais</p>
</a>
</div>
<div class="task">
<a href="#" ng-click="vm.createTask('Conserto')" analytics-on="click" analytics-event="CreateTask" analytics-category="Task" analytics-label="Conserto">
<div class="img" style="background-image: url('assets/images/Conserto.jpg');"></div>
<h4>Reparos</h4>
<p>Elétrico, hidráulico ou de qualquer outro tipo, encontre aqui o que você precisa</p>
</a>
</div>
<div class="task">
<a href="#" ng-click="vm.createTask('Montagem')" analytics-on="click" analytics-event="CreateTask" analytics-category="Task" analytics-label="Montagem">
<div class="img" style="background-image: url('assets/images/Montador.jpg');"></div>
<h4>Montagem</h4>
<p>Não quebre a cabeça, encontre uma pessoa para montar o que você precisar</p>
</a>
</div>
<div class="task">
<a href="#" ng-click="vm.createTask('Mudanca')" analytics-on="click" analytics-event="CreateTask" analytics-category="Task" analytics-label="Mudanca">
<div class="img" style="background-image: url('assets/images/Mudanca.jpg');"></div>
<h4>Mudança</h4>
<p>Encontre ajuda para organizar, embalar ou transportar suas coisas</p>
</a>
</div>
<div class="task" ng-click="vm.createTask('Geral')" analytics-on="click" analytics-event="CreateTask" analytics-category="Task" analytics-label="Geral">
<a href="#">
<div class="img" style="background-image: url('assets/images/Ferramentas.jpg');"></div>
<h4>Geral</h4>
<p>Diga o que você precisa fazer</p>
</a>
</div>
</section>
<section id="join-taskers">
<h2>Torne-se um resolvedor</h2>
<div class="form-taskers">
<h4>Conheça já a melhor rede colaborativa de serviços</h4>
<form ng-submit="vm.signup()">
<input ng-model="vm.user.name" type="text" placeholder="Nome">
<input ng-model="vm.user.email" type="email" placeholder="Email">
<input type="submit" value="Cadastre-me">
</form>
</div>
<ul>
<li>+ Clientes</li>
<li>+ Serviços</li>
<li>+ Renda</li>
</ul>
</section>
<section id="partner">
<h4>PARCEIROS</h4>
<img alt="Oxigênio Aceleradora" src="assets/images/brand-oxigenio-aceleradora-color.png">
<img alt="Porto Seguro" src="assets/images/portoseguro_color.png">
</section> | {
"content_hash": "9b4ebcd850137c6fe72eab1847ba1d0a",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 162,
"avg_line_length": 45.54716981132076,
"alnum_prop": 0.597970173985087,
"repo_name": "NandoFarias/BemCombinado",
"id": "4ed3e49593f256be37bf5f027ab45f9bb996749d",
"size": "4851",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/app/main/main.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23857"
},
{
"name": "HTML",
"bytes": "49741"
},
{
"name": "JavaScript",
"bytes": "68017"
}
],
"symlink_target": ""
} |
package com.ctrip.framework.apollo.biz.entity;
import com.google.common.base.MoreObjects;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@Entity
@Table(name = "Instance")
public class Instance {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id")
private long id;
@Column(name = "AppId", nullable = false)
private String appId;
@Column(name = "ClusterName", nullable = false)
private String clusterName;
@Column(name = "DataCenter", nullable = false)
private String dataCenter;
@Column(name = "Ip", nullable = false)
private String ip;
@Column(name = "DataChange_CreatedTime", nullable = false)
private Date dataChangeCreatedTime;
@Column(name = "DataChange_LastTime")
private Date dataChangeLastModifiedTime;
@PrePersist
protected void prePersist() {
if (this.dataChangeCreatedTime == null) {
dataChangeCreatedTime = new Date();
}
if (this.dataChangeLastModifiedTime == null) {
dataChangeLastModifiedTime = dataChangeCreatedTime;
}
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getDataCenter() {
return dataCenter;
}
public void setDataCenter(String dataCenter) {
this.dataCenter = dataCenter;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getDataChangeCreatedTime() {
return dataChangeCreatedTime;
}
public void setDataChangeCreatedTime(Date dataChangeCreatedTime) {
this.dataChangeCreatedTime = dataChangeCreatedTime;
}
public Date getDataChangeLastModifiedTime() {
return dataChangeLastModifiedTime;
}
public void setDataChangeLastModifiedTime(Date dataChangeLastModifiedTime) {
this.dataChangeLastModifiedTime = dataChangeLastModifiedTime;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("id", id)
.add("appId", appId)
.add("clusterName", clusterName)
.add("dataCenter", dataCenter)
.add("ip", ip)
.add("dataChangeCreatedTime", dataChangeCreatedTime)
.add("dataChangeLastModifiedTime", dataChangeLastModifiedTime)
.toString();
}
}
| {
"content_hash": "f5c34d701c6d09deb8d588fdaf0a0e6a",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 78,
"avg_line_length": 22.693548387096776,
"alnum_prop": 0.7032693674484719,
"repo_name": "nobodyiam/apollo",
"id": "d394e6ff12d608dc2883b475a21052c01872dc44",
"size": "3410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Instance.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2286"
},
{
"name": "CSS",
"bytes": "19419"
},
{
"name": "Dockerfile",
"bytes": "7118"
},
{
"name": "HTML",
"bytes": "426967"
},
{
"name": "Java",
"bytes": "3273245"
},
{
"name": "JavaScript",
"bytes": "364801"
},
{
"name": "Shell",
"bytes": "43324"
}
],
"symlink_target": ""
} |
package kr.pe.courage.tech.uss.org.dept.web;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springmodules.validation.commons.DefaultBeanValidator;
import egovframework.rte.ptl.mvc.tags.ui.pagination.CouragePaginationInfo;
import kr.pe.courage.common.utils.BeanUtils;
import kr.pe.courage.common.vo.JxlsParam;
import kr.pe.courage.common.web.helper.ITreeHelper;
import kr.pe.courage.common.web.utils.WebUtils;
import kr.pe.courage.tech.uss.org.dept.service.DeptBatchVO;
import kr.pe.courage.tech.uss.org.dept.service.DeptService;
import kr.pe.courage.tech.uss.org.dept.service.DeptVO;
/**
* <pre>
* kr.pe.courage.tech.uss.org.dept.web
* DeptController.java
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 9. 29.
* @Version : 1.0
* @see
*
* <pre>
* << 개정이력 >>
* 1. 수정일 : 2016. 9. 29., 수정자 : ChangHo Seok, 수정내용 : 최초등록
* </pre>
*/
@Controller("deptController")
@RequestMapping("/uss/org/dept/*")
@SessionAttributes("errorList")
public class DeptController {
private final Logger logger = Logger.getLogger(this.getClass());
@Resource(name = "beanValidator")
protected DefaultBeanValidator beanValidator;
@Resource(name = "deptService")
private DeptService deptService;
@Resource(name = "defaultTreeHelper")
private ITreeHelper treeHelper;
@Value("#{ussView['formDeptView']}")
private String formDeptView;
@Value("#{ussView['deptTabView']}")
private String deptTabView;
@Value("#{ussView['deptListView']}")
private String deptListView;
@Value("#{ussView['deptTreeView']}")
private String deptTreeView;
@Value("#{ussView['deptDetailView']}")
private String deptDetailView;
@Value("#{ussView['deptCreateView']}")
private String deptCreateView;
@Value("#{ussView['deptModifyView']}")
private String deptModifyView;
@Value("#{ussView['formDeptPopupView']}")
private String formDeptPopupView;
@Value("#{ussView['deptPopupView']}")
private String deptPopupView;
@Value("#{ussView['deptCreateBatchPopupView']}")
private String deptCreateBatchPopupView;
@Value("#{ussView['deptBatchErrorListPopupView']}")
private String deptBatchErrorListPopupView;
@Value("#{pageConfig['dept.page.recordCount']}")
private int recordCount;
@Value("#{pageConfig['dept.page.size']}")
private int pageSize;
@Value("#{pageConfig['dept.page.enable']}")
private String pageEnable;
@ModelAttribute("errorList")
private List<DeptVO> errorList() {
return new ArrayList<DeptVO>();
}
/**
* <pre>
* 1. 개요 : 부서관리 메인
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 9. 29.
* @Method Name : formDept
* @return
* @throws Exception
*/
@RequestMapping("formDept.*")
public ModelAndView formDept() throws Exception {
return new ModelAndView(formDeptView);
}
/**
* <pre>
* 1. 개요 : 부서관리 탭 화면 조회
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 11. 24.
* @Method Name : retrieveDeptTabView
* @return
* @throws Exception
*/
@RequestMapping("retrieveDeptTabView.*")
public ModelAndView retrieveDeptTabView() throws Exception {
return new ModelAndView(deptTabView);
}
/**
* <pre>
* 1. 개요 : 부서관리 목록 조회
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 9. 29.
* @Method Name : retrieveDeptList
* @param request
* @param deptVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping("retrieveDeptList.*")
public ModelAndView retrieveDeptList(HttpServletRequest request, DeptVO deptVO, ModelMap model) throws Exception {
CouragePaginationInfo pagination = new CouragePaginationInfo(deptVO, pageEnable, recordCount, pageSize);
deptVO = (DeptVO) pagination.createCustomVo(request);
pagination.setTotalRecordCount(deptService.selectDeptListCount(deptVO));
List<DeptVO> deptList = null;
if (pagination.getTotalRecordCount() > 0) {
deptList = deptService.selectDeptList(deptVO);
}
model.addAttribute("pagination", pagination);
model.addAttribute("deptList", deptList);
return new ModelAndView(deptListView);
}
/**
* <pre>
* 1. 개요 : 부서관리 정보 조회 (트리형식)
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 11. 24.
* @Method Name : retrieveDeptTree
* @return
* @throws Exception
*/
@RequestMapping("retrieveDeptTree.*")
public ModelAndView retrieveDeptTree() throws Exception {
return new ModelAndView(deptTreeView);
}
/**
* <pre>
* 1. 개요 : 부서관리 정보 상세조회
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 4.
* @Method Name : retrieveDeptDetail
* @param request
* @param deptVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping("retrieveDeptDetail.*")
public ModelAndView retrieveDeptDetail(HttpServletRequest request, DeptVO deptVO, ModelMap model) throws Exception {
DeptVO resultVO = deptService.selectDeptDetail(deptVO);
BeanUtils.copyCondProperties(deptVO, resultVO);
model.addAttribute("deptVO", resultVO);
return new ModelAndView(deptDetailView);
}
/**
* <pre>
* 1. 개요 : 부서관리 정보 등록 화면
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 9. 29.
* @Method Name : createDept
* @param deptVO
* @return
* @throws Exception
*/
@RequestMapping("createDept.*")
public ModelAndView createDept(DeptVO deptVO) throws Exception {
deptVO.setMode(DeptVO.MODE_CREATE);
return new ModelAndView(deptCreateView);
}
/**
* <pre>
* 1. 개요 : 부서관리 정보 등록 처리
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 4.
* @Method Name : createDeptProc
* @param request
* @param deptVO
* @param bindingResult
* @param model
* @return
* @throws Exception
*/
@RequestMapping("createDeptProc.*")
public ModelAndView createDeptProc(HttpServletRequest request, DeptVO deptVO, BindingResult bindingResult, ModelMap model) throws Exception {
beanValidator.validate(deptVO, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("validateCheck", "error");
model.addAttribute("deptVO", deptVO);
WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_VALIDATOR_ERROR);
return new ModelAndView(deptCreateView, model);
}
deptService.createDept(deptVO);
String params = "?" + WebUtils.ACTION_STATUS_PARAM + "=" + WebUtils.ACTION_STATUS_SUCCESS;
String returnUrl = "retrieveDeptDetail." + WebUtils.getUrlExtension(request);
if (deptVO.getSaveLaterView().equals(DeptVO.SAVE_LATER_VIEW_DETAIL)) {
params += "&deptCode=" + deptVO.getDeptCode();
} else if (deptVO.getSaveLaterView().equals(DeptVO.SAVE_LATER_VIEW_LIST)) {
returnUrl = "retrieveDeptList." + WebUtils.getUrlExtension(request);
} else if (deptVO.getSaveLaterView().equals(DeptVO.SAVE_LATER_VIEW_CREATE)) {
returnUrl = "createDept." + WebUtils.getUrlExtension(request);
} else {
params += "&deptCode=" + deptVO.getDeptCode();
}
RedirectView redirectView = new RedirectView();
redirectView.setContextRelative(true);
redirectView.setUrl(returnUrl + params);
return new ModelAndView(redirectView);
}
/**
* <pre>
* 1. 개요 : 부서관리 정보 수정 화면
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 4.
* @Method Name : modifyDept
* @param request
* @param deptVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping("modifyDept.*")
public ModelAndView modifyDept(HttpServletRequest request, DeptVO deptVO, ModelMap model) throws Exception {
DeptVO resultVO = deptService.selectDeptDetail(deptVO);
BeanUtils.copyCondProperties(deptVO, resultVO);
resultVO.setMode(DeptVO.MODE_MODIFY);
model.addAttribute("deptVO", resultVO);
return new ModelAndView(deptModifyView);
}
/**
* <pre>
* 1. 개요 : 부서관리 정보 수정 처리
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 4.
* @Method Name : modifyDeptProc
* @param request
* @param deptVO
* @param bindingResult
* @param model
* @return
* @throws Exception
*/
@RequestMapping("modifyDeptProc.*")
public ModelAndView modifyDeptProc(HttpServletRequest request, DeptVO deptVO, BindingResult bindingResult, ModelMap model) throws Exception {
beanValidator.validate(deptVO, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("validateCheck", "error");
model.addAttribute("deptVO", deptVO);
WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_VALIDATOR_ERROR);
return new ModelAndView(deptModifyView, model);
}
deptService.updateDept(deptVO);
String condParams = BeanUtils.getConditionParameter(deptVO);
String params = "?deptCode=" + deptVO.getDeptCode() + (StringUtils.isEmpty(condParams) ? "" : "&" + condParams);
String returnUrl = "retrieveDeptDetail." + WebUtils.getUrlExtension(request);
RedirectView redirectView = new RedirectView();
redirectView.setContextRelative(true);
redirectView.setUrl(returnUrl + params);
return new ModelAndView(redirectView);
}
/**
* <pre>
* 1. 개요 : 부서관리 정보 삭제
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 4.
* @Method Name : deleteDept
* @param request
* @param deptVO
* @return
* @throws Exception
*/
@RequestMapping("deleteDept.*")
public ModelAndView deleteDept(HttpServletRequest request, DeptVO deptVO) throws Exception {
deptService.deleteDept(deptVO);
String params = "?" + WebUtils.ACTION_STATUS_FAILED + "=" + WebUtils.ACTION_STATUS_SUCCESS;
String returnUrl = "retrieveDeptList." + WebUtils.getUrlExtension(request);
RedirectView redirectView = new RedirectView();
redirectView.setContextRelative(true);
redirectView.setUrl(returnUrl + params);
return new ModelAndView(redirectView);
}
/**
* <pre>
* 1. 개요 : 부서코드 존재 유무
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 4.
* @Method Name : isExistDeptCode
* @param deptVO
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping("isExistDeptCode.*")
public Map<String, Object> isExistDeptCode(DeptVO deptVO) throws Exception {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("result", deptService.isExist(deptVO));
return resultMap;
}
/**
* <pre>
* 1. 개요 : 부서관리 엑셀 저장
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 4.
* @Method Name : downloadDeptExcel
* @param deptVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping("downloadDeptExcel.*")
public ModelAndView downloadDeptExcel(DeptVO deptVO, ModelMap model) throws Exception {
deptVO.setPagingEnable(DeptVO.PAGING_ENABLE_OFF);
int totalRecordCount = deptService.selectDeptListCount(deptVO);
List<DeptVO> deptList = null;
if (totalRecordCount > 0) {
deptList = deptService.selectDeptList(deptVO);
}
JxlsParam jxlsParam = new JxlsParam(JxlsParam.EXCEL_EXT_XLS, "deptExcel", "부서코드 목록", "부서코드 목록", totalRecordCount);
model.addAttribute("list", deptList);
model.addAttribute("jxlsParam", jxlsParam);
return new ModelAndView("jxlsView");
}
/**
* <pre>
* 1. 개요 : 부서 조회 팝업 메인
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 5.
* @Method Name : formDeptPopup
* @return
* @throws Exception
*/
@RequestMapping("formDeptPopup.*")
public ModelAndView formDeptPopup() throws Exception {
return new ModelAndView(formDeptPopupView);
}
/**
* <pre>
* 1. 개요 : 부서 조회 팝업
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 5.
* @Method Name : retrieveDeptPopup
* @param deptVO
* @return
*/
@RequestMapping("retrieveDeptPopup.*")
public ModelAndView retrieveDeptPopup(DeptVO deptVO) {
return new ModelAndView(deptPopupView);
}
/**
* <pre>
* 1. 개요 : 부서 트리 데이터 조회
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 5.
* @Method Name : retrieveDeptTreeData
* @param deptVO
* @param model
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping("retrieveDeptTreeData.*")
public List<Map<String, Object>> retrieveDeptTreeData(DeptVO deptVO) throws Exception {
List<DeptVO> deptList = null;
List<Map<String, Object>> treeMapList = null;;
if (deptVO.getCondAtmbUpperDeptCode() == null) {
deptVO.setCondAtmbUpperDeptCode("");
}
deptList = deptService.selectDeptTreeList(deptVO);
treeMapList = new ArrayList<Map<String,Object>>();
for (DeptVO treeVO : deptList) {
Map<String, Object> dataMap = new HashMap<String, Object>();
Map<String, Object> metadataMap = new HashMap<String, Object>();
metadataMap.put("deptCode", treeVO.getDeptCode());
metadataMap.put("VO", treeVO);
dataMap.put("metadata", metadataMap);
dataMap.put("id", treeVO.getDeptCode());
dataMap.put("title", treeVO.getLowestDeptNm());
if (treeVO.getAblSe().equals("1")) {
dataMap.put("class", "abl");
}
if (treeVO.getSubDeptCnt() > 0) {
dataMap.put("state", "closed");
} else {
dataMap.put("state", "leaf");
}
treeMapList.add(dataMap);
}
return treeHelper.process(treeMapList, deptVO.getDeptCode());
}
/**
* <pre>
* 1. 개요 : 부서 일괄등록
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 9.
* @Method Name : createDeptBatchPopup
* @return
* @throws Exception
*/
@RequestMapping("createDeptBatchPopup.*")
public ModelAndView createDeptBatchPopup(DeptBatchVO deptBatchVO) throws Exception {
return new ModelAndView(deptCreateBatchPopupView);
}
/**
* <pre>
* 1. 개요 : 부서 일괄등록 처리
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 9.
* @Method Name : createDeptBatchProcPopup
* @return
* @throws Exception
*/
@RequestMapping("createDeptBatchProcPopup.*")
public ModelAndView createDeptBatchProcPopup(HttpServletRequest request, DeptBatchVO deptBatchVO,
BindingResult bindingResult, SessionStatus sessionStatus, ModelMap model) throws Exception {
beanValidator.validate(deptBatchVO, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("validateCheck", "error");
model.addAttribute("deptBatchVO", deptBatchVO);
WebUtils.setActionStatus(request, WebUtils.ACTION_STATUS_VALIDATOR_ERROR);
return new ModelAndView(deptCreateBatchPopupView, model);
}
deptBatchVO.setJsessionId(WebUtils.getSessionId(request));
List<DeptVO> errorList = deptService.createDeptBatch(deptBatchVO);
sessionStatus.isComplete();
if (errorList.size() <= 0) {
model.addAttribute(WebUtils.ACTION_STATUS_PARAM, WebUtils.ACTION_STATUS_SUCCESS);
return new ModelAndView(deptCreateBatchPopupView);
} else {
model.addAttribute("errorList", errorList);
model.addAttribute(WebUtils.ACTION_STATUS_PARAM, WebUtils.ACTION_STATUS_FAILED);
return new ModelAndView(deptBatchErrorListPopupView);
}
}
/**
* <pre>
* 1. 개요 : 일괄등록 오류 엑셀 저장
* </pre>
*
* @Author : ChangHo Seok
* @Date : 2016. 10. 14.
* @Method Name : downloadDeptBatchErrorExcel
* @param deptVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping("downloadDeptBatchErrorExcel.*")
public ModelAndView downloadDeptBatchErrorExcel(HttpSession session, ModelMap model) throws Exception {
List<DeptVO> errorList = (List<DeptVO>) session.getAttribute("errorList");
JxlsParam jxlsParam = new JxlsParam(JxlsParam.EXCEL_EXT_XLS, "deptBatchErrorExcel", "일괄등록 오류 내역", "일괄등록 오류 내역", errorList.size());
model.addAttribute("list", errorList);
model.addAttribute("jxlsParam", jxlsParam);
return new ModelAndView("jxlsView");
}
}
| {
"content_hash": "e3aa0ad812b5cc9bdd3390f3806ef65b",
"timestamp": "",
"source": "github",
"line_count": 600,
"max_line_length": 142,
"avg_line_length": 26.983333333333334,
"alnum_prop": 0.6996911673872761,
"repo_name": "ChangHoSeok/courageTech",
"id": "20aba1adab830a3e967c91dfba0e07c33d6331b8",
"size": "16666",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/courage-tech/src/main/java/kr/pe/courage/tech/uss/org/dept/web/DeptController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4804"
},
{
"name": "CSS",
"bytes": "274252"
},
{
"name": "FreeMarker",
"bytes": "4279"
},
{
"name": "HTML",
"bytes": "103090"
},
{
"name": "Java",
"bytes": "1918893"
},
{
"name": "JavaScript",
"bytes": "2808459"
},
{
"name": "Shell",
"bytes": "14265"
}
],
"symlink_target": ""
} |
from setuptools import setup, find_packages
setup(name = 'django-emd',
version = '0.1.0',
description = 'Django models for prices from EMD',
author = 'Joshua Blake',
author_email = 'joshbblake@gmail.com',
packages = find_packages(),
scripts = ['bin/load_prices.sh',],
data_files = [('/tmp', ['bin/create_prices.sql'])],
)
| {
"content_hash": "6e5602b1a70aaf1868322986a892d8fb",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 57,
"avg_line_length": 33.18181818181818,
"alnum_prop": 0.6082191780821918,
"repo_name": "joshuablake/django-emd",
"id": "9cca312bcccb822713744f96e047930c3561201c",
"size": "365",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "1115"
},
{
"name": "Shell",
"bytes": "287"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<title>Generator (Apache JMeter API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Generator (Apache JMeter API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6,"i2":6,"i3":6,"i4":6,"i5":6,"i6":6,"i7":6,"i8":6,"i9":6,"i10":6,"i11":6,"i12":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><b>Apache JMeter</b></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Filter.html" title="interface in org.apache.jmeter.protocol.http.util.accesslog"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/LogFilter.html" title="class in org.apache.jmeter.protocol.http.util.accesslog"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/jmeter/protocol/http/util/accesslog/Generator.html" target="_top">Frames</a></li>
<li><a href="Generator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.jmeter.protocol.http.util.accesslog</div>
<h2 title="Interface Generator" class="title">Interface Generator</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/StandardGenerator.html" title="class in org.apache.jmeter.protocol.http.util.accesslog">StandardGenerator</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">Generator</span></pre>
<div class="block">Description:<br>
<br>
Generator is a base interface that defines the minimum methods needed to
implement a concrete generator. The reason for creating this interface is
eventually JMeter could use the logs directly rather than pre- process the
logs into a JMeter .jmx file. In situations where a test plan simulates load
from production logs, it is more efficient for JMeter to use the logs
directly.
<p>
From first hand experience, loading a test plan with 10K or more Requests
requires a lot of memory. It's important to keep in mind this type of testing
is closer to functional and regression testing than the typical stress tests.
Typically, this kind of testing is most useful for search sites that get a
large number of requests per day, but the request parameters vary
dramatically. E-commerce sites typically have limited inventory, therefore it
is better to design test plans that use data from the database.
</p></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#close--">close</a></span>()</code>
<div class="block">close the generator</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#generateRequest--">generateRequest</a></span>()</code>
<div class="block">The method is responsible for calling the necessary methods to generate a
valid request.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#reset--">reset</a></span>()</code>
<div class="block">The purpose of the reset is so Samplers can explicitly call reset to
create a new instance of HTTPSampler.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#save--">save</a></span>()</code>
<div class="block">If the generator is converting the logs to a .jmx file, save should be
called.</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setHost-java.lang.String-">setHost</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> host)</code>
<div class="block">The host is the name of the server.</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setLabel-java.lang.String-">setLabel</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> label)</code>
<div class="block">This is the label for the request, which is used in the logs and results.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setMethod-java.lang.String-">setMethod</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> post_get)</code>
<div class="block">The method is the HTTP request method.</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setParams-org.apache.jmeter.protocol.http.util.accesslog.NVPair:A-">setParams</a></span>(<a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/NVPair.html" title="class in org.apache.jmeter.protocol.http.util.accesslog">NVPair</a>[] params)</code>
<div class="block">Set the request parameters</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setPath-java.lang.String-">setPath</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> path)</code>
<div class="block">The path is the web page you want to test.</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setPort-int-">setPort</a></span>(int port)</code>
<div class="block">The default port for HTTP is 80, but not all servers run on that port.</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setQueryString-java.lang.String-">setQueryString</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> querystring)</code>
<div class="block">Set the querystring for the request if the method is GET.</div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setSourceLogs-java.lang.String-">setSourceLogs</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> sourcefile)</code>
<div class="block">The source logs is the location where the access log resides.</div>
</td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Generator.html#setTarget-java.lang.Object-">setTarget</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> target)</code>
<div class="block">The target can be either a java.io.File or a Sampler.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="close--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>close</h4>
<pre>void close()</pre>
<div class="block">close the generator</div>
</li>
</ul>
<a name="setHost-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setHost</h4>
<pre>void setHost(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> host)</pre>
<div class="block">The host is the name of the server.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>host</code> - name of the server</dd>
</dl>
</li>
</ul>
<a name="setLabel-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setLabel</h4>
<pre>void setLabel(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> label)</pre>
<div class="block">This is the label for the request, which is used in the logs and results.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>label</code> - label of the request</dd>
</dl>
</li>
</ul>
<a name="setMethod-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setMethod</h4>
<pre>void setMethod(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> post_get)</pre>
<div class="block">The method is the HTTP request method. It's normally POST or GET.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>post_get</code> - method of the HTTP request</dd>
</dl>
</li>
</ul>
<a name="setParams-org.apache.jmeter.protocol.http.util.accesslog.NVPair:A-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setParams</h4>
<pre>void setParams(<a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/NVPair.html" title="class in org.apache.jmeter.protocol.http.util.accesslog">NVPair</a>[] params)</pre>
<div class="block">Set the request parameters</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>params</code> - request parameter</dd>
</dl>
</li>
</ul>
<a name="setPath-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPath</h4>
<pre>void setPath(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> path)</pre>
<div class="block">The path is the web page you want to test.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>path</code> - path of the web page</dd>
</dl>
</li>
</ul>
<a name="setPort-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPort</h4>
<pre>void setPort(int port)</pre>
<div class="block">The default port for HTTP is 80, but not all servers run on that port.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>port</code> - -
port number</dd>
</dl>
</li>
</ul>
<a name="setQueryString-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setQueryString</h4>
<pre>void setQueryString(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> querystring)</pre>
<div class="block">Set the querystring for the request if the method is GET.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>querystring</code> - query string of the request</dd>
</dl>
</li>
</ul>
<a name="setSourceLogs-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setSourceLogs</h4>
<pre>void setSourceLogs(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> sourcefile)</pre>
<div class="block">The source logs is the location where the access log resides.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>sourcefile</code> - path to the access log file</dd>
</dl>
</li>
</ul>
<a name="setTarget-java.lang.Object-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setTarget</h4>
<pre>void setTarget(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> target)</pre>
<div class="block">The target can be either a java.io.File or a Sampler. We make it generic,
so that later on we can use these classes directly from a HTTPSampler.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>target</code> - target to generate into</dd>
</dl>
</li>
</ul>
<a name="generateRequest--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>generateRequest</h4>
<pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> generateRequest()</pre>
<div class="block">The method is responsible for calling the necessary methods to generate a
valid request. If the generator is used to pre-process access logs, the
method wouldn't return anything. If the generator is used by a control
element, it should return the correct Sampler class with the required
fields set.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>prefilled sampler</dd>
</dl>
</li>
</ul>
<a name="save--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>save</h4>
<pre>void save()</pre>
<div class="block">If the generator is converting the logs to a .jmx file, save should be
called.</div>
</li>
</ul>
<a name="reset--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>reset</h4>
<pre>void reset()</pre>
<div class="block">The purpose of the reset is so Samplers can explicitly call reset to
create a new instance of HTTPSampler.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><b>Apache JMeter</b></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/Filter.html" title="interface in org.apache.jmeter.protocol.http.util.accesslog"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/apache/jmeter/protocol/http/util/accesslog/LogFilter.html" title="class in org.apache.jmeter.protocol.http.util.accesslog"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/jmeter/protocol/http/util/accesslog/Generator.html" target="_top">Frames</a></li>
<li><a href="Generator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 1998-2017 Apache Software Foundation. All Rights Reserved.</small></p>
</body>
</html>
| {
"content_hash": "5e060a69e540b35c42c75b58a7972974",
"timestamp": "",
"source": "github",
"line_count": 488,
"max_line_length": 422,
"avg_line_length": 44.20286885245902,
"alnum_prop": 0.6511983681795003,
"repo_name": "kangli914/JmeterAutomation",
"id": "4ccb84fd567cd536b525991beaea0ef426181d1d",
"size": "21571",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apache-jmeter-3.2/docs/api/org/apache/jmeter/protocol/http/util/accesslog/Generator.html",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "55121"
},
{
"name": "CSS",
"bytes": "59549"
},
{
"name": "HTML",
"bytes": "51660646"
},
{
"name": "Java",
"bytes": "2362"
},
{
"name": "JavaScript",
"bytes": "100693"
},
{
"name": "Shell",
"bytes": "38950"
},
{
"name": "XSLT",
"bytes": "54758"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="$APPLICATION_HOME_DIR$/gradle/gradle-2.4" />
<option name="gradleJvm" value="1.8" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/ScoutingClient" />
</set>
</option>
<option name="myModules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/ScoutingClient" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project> | {
"content_hash": "7db96186acb5f996db8930671d2d6b3b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 85,
"avg_line_length": 35.4,
"alnum_prop": 0.5706214689265536,
"repo_name": "JackMc/Scouting",
"id": "14821f51cad10fe7a0ff3b7aa5d130b6c8f055c0",
"size": "885",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Client/Android/.idea/gradle.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "125124"
},
{
"name": "JavaScript",
"bytes": "886"
},
{
"name": "Python",
"bytes": "19862"
}
],
"symlink_target": ""
} |
import numpy as np
import pandas as pd
import pytest
from samplics.categorical.comparison import Ttest
auto = pd.read_csv("./tests/categorical/auto2.csv")
y = auto["mpg"]
make = auto["make"]
foreign = auto["foreign"]
y1 = auto["y1"]
y2 = auto["y2"]
one_sample_known_mean = Ttest(samp_type="one-sample")
@pytest.mark.xfail(strict=True, reason="Parameters 'known_mean' or 'group' must be provided!")
def test_one_sample_wrong_specifications1():
one_sample_wrong = Ttest()
one_sample_wrong.compare(y)
@pytest.mark.xfail(strict=True, reason="Parameters 'known_mean' or 'group' must be provided!")
def test_one_sample_wrong_specifications2():
one_sample_wrong = Ttest("one-sample")
one_sample_wrong.compare(y)
@pytest.mark.xfail(
strict=True,
reason="Parameter 'type' must be equal to 'one-sample', 'two-sample' or 'many-sample'!",
)
def test_one_sample_wrong_specifications3():
one_sample_wrong = Ttest("two-sample")
one_sample_wrong.compare(y, known_mean=0, group=make)
## One-sample with known mean for comparison
one_sample_known_mean = Ttest(samp_type="one-sample")
one_sample_known_mean.compare(y, known_mean=20)
def test_one_sample_known_mean_mean():
assert np.isclose(one_sample_known_mean.point_est, 21.2973, atol=1e-4)
def test_one_sample_known_mean_stderror():
assert np.isclose(one_sample_known_mean.stderror, 0.67255, atol=1e-4)
def test_one_sample_known_mean_stddev():
assert np.isclose(one_sample_known_mean.stddev, 5.78550, atol=1e-4)
def test_one_sample_known_mean_ci():
assert np.isclose(one_sample_known_mean.lower_ci, 19.9569, atol=1e-4)
assert np.isclose(one_sample_known_mean.upper_ci, 22.63769, atol=1e-4)
def test_one_sample_known_mean_stats():
stats = one_sample_known_mean.stats
assert np.isclose(stats["number_obs"], 74, atol=1e-4)
assert np.isclose(stats["t"], 1.92889, atol=1e-4)
assert np.isclose(stats["df"], 73, atol=1e-4)
assert np.isclose(stats["known_mean"], 20, atol=1e-4)
assert np.isclose(stats["p_value"]["less_than"], 0.9712, atol=1e-4)
assert np.isclose(stats["p_value"]["greater_than"], 0.0288, atol=1e-4)
assert np.isclose(stats["p_value"]["not_equal"], 0.0576, atol=1e-4)
## One-sample with comparisons between groups
one_sample_two_groups = Ttest(samp_type="one-sample")
one_sample_two_groups.compare(y, group=foreign)
def test_one_sample_two_groups_means():
assert np.isclose(one_sample_two_groups.point_est["Domestic"], 19.82692, 1e-4)
assert np.isclose(one_sample_two_groups.point_est["Foreign"], 24.77273, 1e-4)
def test_one_sample_two_groups_stderror():
assert np.isclose(one_sample_two_groups.stderror["Domestic"], 0.6558681, 1e-4)
assert np.isclose(one_sample_two_groups.stderror["Foreign"], 1.3865031, 1e-4)
def test_one_sample_two_groups_stddev():
assert np.isclose(one_sample_two_groups.stddev["Domestic"], 4.72953, 1e-4)
assert np.isclose(one_sample_two_groups.stddev["Foreign"], 6.50328, 1e-4)
def test_one_sample_two_groups_lower_ci():
assert np.isclose(one_sample_two_groups.lower_ci["Domestic"], 18.51978, 1e-4)
assert np.isclose(one_sample_two_groups.lower_ci["Foreign"], 22.00943, 1e-4)
def test_one_sample_two_groups_upper_ci():
assert np.isclose(one_sample_two_groups.upper_ci["Domestic"], 21.1340663, 1e-4)
assert np.isclose(one_sample_two_groups.upper_ci["Foreign"], 27.5360239, 1e-4)
one_sample_stats = one_sample_two_groups.stats
def test_one_sample_two_groups_number_obs():
assert np.isclose(one_sample_stats["number_obs"]["Domestic"], 52, 1e-4)
assert np.isclose(one_sample_stats["number_obs"]["Foreign"], 22, 1e-4)
def test_one_sample_two_groups_t_eq_variance():
assert np.isclose(one_sample_stats["t_eq_variance"], -3.66326, 1e-4)
assert np.isclose(one_sample_stats["df_eq_variance"], 72, 1e-4)
assert np.isclose(one_sample_stats["p_value_eq_variance"]["less_than"], 0.0002362, 1e-4)
assert np.isclose(one_sample_stats["p_value_eq_variance"]["greater_than"], 0.9997638, 1e-4)
assert np.isclose(one_sample_stats["p_value_eq_variance"]["not_equal"], 0.0004725, 1e-4)
def test_one_sample_two_groups_t_uneq_variance():
assert np.isclose(one_sample_stats["t_uneq_variance"], -3.22454, 1e-4)
assert np.isclose(one_sample_stats["df_uneq_variance"], 30.81429, 1e-4)
assert np.isclose(one_sample_stats["p_value_uneq_variance"]["less_than"], 0.0014909, 1e-4)
assert np.isclose(one_sample_stats["p_value_uneq_variance"]["greater_than"], 0.9985091, 1e-4)
assert np.isclose(one_sample_stats["p_value_uneq_variance"]["not_equal"], 0.0029818, 1e-4)
## Two-sample comparisons - UNPAIRED
two_samples_unpaired = Ttest(samp_type="two-sample")
two_samples_unpaired.compare(y, group=foreign)
def test_two_samples_unpaired_means():
assert np.isclose(two_samples_unpaired.point_est["Domestic"], 19.82692, 1e-4)
assert np.isclose(two_samples_unpaired.point_est["Foreign"], 24.77273, 1e-4)
def test_two_samples_unpaired_stderror():
assert np.isclose(two_samples_unpaired.stderror["Domestic"], 0.6577770, 1e-4)
assert np.isclose(two_samples_unpaired.stderror["Foreign"], 1.4095098, 1e-4)
def test_two_samples_unpaired_stddev():
assert np.isclose(two_samples_unpaired.stddev["Domestic"], 4.7432972, 1e-4)
assert np.isclose(two_samples_unpaired.stddev["Foreign"], 6.6111869, 1e-4)
def test_two_samples_unpaired_lower_ci():
assert np.isclose(two_samples_unpaired.lower_ci["Domestic"], 18.5063807, 1e-4)
assert np.isclose(two_samples_unpaired.lower_ci["Foreign"], 21.8414912, 1e-4)
def test_two_samples_unpaired_upper_ci():
assert np.isclose(two_samples_unpaired.upper_ci["Domestic"], 21.1474655, 1e-4)
assert np.isclose(two_samples_unpaired.upper_ci["Foreign"], 27.7039633, 1e-4)
two_samples_stats = two_samples_unpaired.stats
def test_two_samples_unpaired_number_obs():
assert np.isclose(two_samples_stats["number_obs"]["Domestic"], 52, 1e-4)
assert np.isclose(two_samples_stats["number_obs"]["Foreign"], 22, 1e-4)
def test_two_samples_unpaired_t_eq_variance():
assert np.isclose(two_samples_stats["t_eq_variance"], -3.630848, 1e-4)
assert np.isclose(two_samples_stats["df_eq_variance"], 72, 1e-4)
assert np.isclose(two_samples_stats["p_value_eq_variance"]["less_than"], 0.0002627, 1e-4)
assert np.isclose(two_samples_stats["p_value_eq_variance"]["greater_than"], 0.9997372, 1e-4)
assert np.isclose(two_samples_stats["p_value_eq_variance"]["not_equal"], 0.0005254, 1e-4)
def test_two_samples_unpaired_t_uneq_variance():
assert np.isclose(two_samples_stats["t_uneq_variance"], -3.179685, 1e-4)
assert np.isclose(two_samples_stats["df_uneq_variance"], 30.546278, 1e-4)
assert np.isclose(two_samples_stats["p_value_uneq_variance"]["less_than"], 0.0016850, 1e-4)
assert np.isclose(two_samples_stats["p_value_uneq_variance"]["greater_than"], 0.9983150, 1e-4)
assert np.isclose(two_samples_stats["p_value_uneq_variance"]["not_equal"], 0.0033701, 1e-4)
## two-sample with paired observations
two_samples_paired = Ttest(samp_type="two-sample", paired=True)
two_samples_paired.compare([y1, y2], group=foreign)
def test_two_samples_paired_mean():
assert np.isclose(two_samples_paired.point_est, 0.000000405405, atol=1e-8)
def test_two_samples_paired_stderror():
assert np.isclose(two_samples_paired.stderror, 0.00000046419, atol=1e-8)
def test_two_samples_paired_stddev():
assert np.isclose(two_samples_paired.stddev, 0.0000039932, atol=1e-8)
def test_two_samples_paired_ci():
assert np.isclose(two_samples_paired.lower_ci, -0.00000051974, atol=1e-8)
assert np.isclose(two_samples_paired.upper_ci, 0.0000013305, atol=1e-8)
def test_two_samples_paired_stats():
stats = two_samples_paired.stats
assert np.isclose(stats["number_obs"], 74, atol=1e-4)
assert np.isclose(stats["t"], 0.873349, atol=1e-4)
assert np.isclose(stats["df"], 73, atol=1e-4)
assert np.isclose(stats["known_mean"], 0, atol=1e-4)
assert np.isclose(stats["p_value"]["less_than"], 0.80733168, atol=1e-4)
assert np.isclose(stats["p_value"]["greater_than"], 0.1926683, atol=1e-4)
assert np.isclose(stats["p_value"]["not_equal"], 0.38533664, atol=1e-4)
| {
"content_hash": "f5efe24cfe74a1a1b4a3a7e636824505",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 98,
"avg_line_length": 37.95852534562212,
"alnum_prop": 0.7066893286390676,
"repo_name": "survey-methods/samplics",
"id": "2ff6a7ca74d529ce35c202414520c3316eee62a5",
"size": "8237",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tests/categorical/test_comparison.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "389217"
},
{
"name": "TeX",
"bytes": "2327"
}
],
"symlink_target": ""
} |
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
# C++ apps need to be linked with g++.
#
# Note: flock is used to seralize linking. Linking is a memory-intensive
# process so running parallel links can often lead to thrashing. To disable
# the serialization, override LINK via an envrionment variable as follows:
#
# export LINK=g++
#
# This will allow make to invoke N linker processes as specified in -jN.
LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX)
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
ARFLAGS.target ?= crs
# N.B.: the logic of which commands to run should match the computation done
# in gyp's make.py where ARFLAGS.host etc. is computed.
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= g++
LDFLAGS.host ?=
AR.host ?= ar
ARFLAGS.host := crs
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_objc = CXX($(TOOLSET)) $@
cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
quiet_cmd_objcxx = CXX($(TOOLSET)) $@
cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
# Commands for precompiled header files.
quiet_cmd_pch_c = CXX($(TOOLSET)) $@
cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_pch_m = CXX($(TOOLSET)) $@
cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
# gyp-mac-tool is written next to the root Makefile by gyp.
# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
# already.
quiet_cmd_mac_tool = MACTOOL $(4) $<
cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@"
quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
quiet_cmd_infoplist = INFOPLIST $@
cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
quiet_cmd_alink = LIBTOOL-STATIC $@
cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool -static -o $@ $(filter %.o,$^)
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
# TODO(thakis): Find out and document the difference between shared_library and
# loadable_module on mac.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
# TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass
# -bundle -single_module here (for osmesa.so).
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds, and deletes the output file when done
# if any of the postbuilds failed.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
F=$$?;\
if [ $$F -ne 0 ]; then\
E=$$F;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 2,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD
@$(call do_cmd,objc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD
@$(call do_cmd,objcxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,bufferutil.target.mk)))),)
include bufferutil.target.mk
endif
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,validation.target.mk)))),)
include validation.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = /Users/Ethan/.node-gyp/0.6.18/tools/gyp_addon -fmake --ignore-environment "--toplevel-dir=." -I/Applications/MAMP/htdocs/Populus2/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/build/config.gypi -I/Users/Ethan/.node-gyp/0.6.18/tools/addon.gypi -I/Users/Ethan/.node-gyp/0.6.18/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/Ethan/.node-gyp/0.6.18" "-Dmodule_root_dir=/Applications/MAMP/htdocs/Populus2/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws" binding.gyp
Makefile: $(srcdir)/../../../../../../../../../../../../Users/Ethan/.node-gyp/0.6.18/common.gypi $(srcdir)/../../../../../../../../../../../../Users/Ethan/.node-gyp/0.6.18/tools/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
# Rather than include each individual .d file, concatenate them into a
# single file which make is able to load faster. We split this into
# commands that take 1000 files at a time to avoid overflowing the
# command line.
$(shell cat $(wordlist 1,1000,$(d_files)) > $(depsdir)/all.deps)
ifneq ($(word 1001,$(d_files)),)
$(error Found unprocessed dependency files (gyp didn't generate enough rules!))
endif
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
$(depsdir)/all.deps: ;
include $(depsdir)/all.deps
endif
| {
"content_hash": "de2064169fc4219b0f2408fb4e088f2a",
"timestamp": "",
"source": "github",
"line_count": 368,
"max_line_length": 680,
"avg_line_length": 39.32065217391305,
"alnum_prop": 0.6547339322736697,
"repo_name": "felakuti4life/AlligatorAgitators",
"id": "b72e6101a1564d3f35aad2554053f13578ba2385",
"size": "14800",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/build/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ChucK",
"bytes": "12998"
},
{
"name": "JavaScript",
"bytes": "399224"
},
{
"name": "PHP",
"bytes": "46753"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.4.0</version>
</parent>
<artifactId>thread-pool</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "1e1adf18024a706990b0e359d6c134be",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 149,
"avg_line_length": 34.44444444444444,
"alnum_prop": 0.6774193548387096,
"repo_name": "erichcervantez/java-design-patterns",
"id": "2190d9a72c466573a505064d94ec42bcacf70e05",
"size": "620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "thread-pool/pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "827"
},
{
"name": "Cucumber",
"bytes": "1078"
},
{
"name": "HTML",
"bytes": "6087"
},
{
"name": "Java",
"bytes": "301919"
},
{
"name": "JavaScript",
"bytes": "47"
}
],
"symlink_target": ""
} |
namespace CompeTournament.Backend
{
using CompeTournament.Backend.Data;
using CompeTournament.Backend.Extensions;
using CompeTournament.Backend.Helpers;
using CompeTournament.Backend.Persistence.Contracts;
using CompeTournament.Backend.Persistence.Implementations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddScoped<ICurrentUserFactory, CurrentUserFactory>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddIdentity<ApplicationUser, IdentityRole>(cfg =>
{
cfg.Tokens.AuthenticatorTokenProvider = TokenOptions.DefaultAuthenticatorProvider;
cfg.SignIn.RequireConfirmedEmail = false;
cfg.User.RequireUniqueEmail = true;
cfg.Password.RequireDigit = false;
cfg.Password.RequiredUniqueChars = 0;
cfg.Password.RequireLowercase = false;
cfg.Password.RequireNonAlphanumeric = false;
cfg.Password.RequireUppercase = false;
cfg.Password.RequiredLength = 6;
})
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthentication()
.AddCookie()
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = this.Configuration["Tokens:Issuer"],
ValidAudience = this.Configuration["Tokens:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(this.Configuration["Tokens:Key"]))
};
});
services.AddDbContext<ApplicationDbContext>(cfg =>
{
cfg.UseSqlServer(this.Configuration.GetConnectionString("PsDatabaseCnn"));
});
services.AddTransient<SeedDb>();
services.AddScoped<IUserHelper, UserHelper>();
services.AddScoped<IMailHelper, MailHelper>();
#region RepositoryScopes
services.AddScoped<IGroupRepository, GroupRepository>();
services.AddScoped<ITournamentTypeRepository, TournamentTypeRepository>();
services.AddScoped<ILeagueRepository, LeagueRepository>();
services.AddScoped<ITeamRepository, TeamRepository>();
services.AddScoped<IMatchRepository, MatchRepository>();
#endregion
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Account/NotAuthorized";
options.AccessDeniedPath = "/Account/NotAuthorized";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/error/{0}");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| {
"content_hash": "fdc9da68c5e5fb069a95fccf1b2a6845",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 143,
"avg_line_length": 39.152671755725194,
"alnum_prop": 0.5964125560538116,
"repo_name": "sgermosen/TorneoPredicciones",
"id": "36d84a9da5215ec66bb88958d3a47629975c99c9",
"size": "5131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CompeTournament.Backend/Startup.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "390"
},
{
"name": "C#",
"bytes": "1383561"
},
{
"name": "CSS",
"bytes": "18071"
},
{
"name": "HTML",
"bytes": "493527"
},
{
"name": "JavaScript",
"bytes": "1216080"
},
{
"name": "Less",
"bytes": "8374"
},
{
"name": "TSQL",
"bytes": "23484"
}
],
"symlink_target": ""
} |
<html>
<head>
<script type="text/javascript" src="../../http/tests/inspector-protocol/inspector-protocol-test.js"></script>
<script>
function test()
{
InspectorTest.sendCommand("Runtime.evaluate", { expression: "let a = 42;" }, step2);
function step2(response)
{
failIfError(response);
InspectorTest.log("first \"let a = 1;\" result: wasThrown = " + !!response.result.exceptionDetails);
InspectorTest.sendCommand("Runtime.evaluate", { expression: "let a = 239;" }, step3);
}
function step3(response)
{
failIfError(response);
InspectorTest.log("second \"let a = 1;\" result: wasThrown = " + !!response.result.exceptionDetails);
if (response.result.exceptionDetails)
InspectorTest.log("exception message: " + response.result.exceptionDetails.text + " " + response.result.exceptionDetails.exception.description);
InspectorTest.sendCommand("Runtime.evaluate", { expression: "a" }, step4);
}
function step4(response)
{
failIfError(response);
InspectorTest.log(JSON.stringify(response.result));
checkMethod(null);
}
var methods = [ "$", "$$", "$x", "dir", "dirxml", "keys", "values", "profile", "profileEnd",
"monitorEvents", "unmonitorEvents", "inspect", "copy", "clear", "getEventListeners",
"debug", "undebug", "monitor", "unmonitor", "table" ];
function checkMethod(response)
{
failIfError(response);
if (response)
InspectorTest.log(response.result.result.description);
var method = methods.shift();
if (!method)
InspectorTest.completeTest();
InspectorTest.sendCommand("Runtime.evaluate", { expression: method, includeCommandLineAPI: true }, checkMethod);
}
function failIfError(response)
{
if (response && response.error) {
InspectorTest.log("FAIL: " + JSON.stringify(response.error));
}
}
}
</script>
</head>
<body onload="runTest()">
</body>
</html>
| {
"content_hash": "e5b02a2ee9ec40612562460a3bedb9e0",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 156,
"avg_line_length": 32.22222222222222,
"alnum_prop": 0.6270935960591133,
"repo_name": "Samsung/ChromiumGStreamerBackend",
"id": "69525ed1ee4ef9ae4e4f721d8baefc4121152820",
"size": "2030",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "third_party/WebKit/LayoutTests/inspector-protocol/console/console-let-const-with-api.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "f2b719b7501177f954f58d238fd6fd63",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e9665e82d3ba8d00a7589b6b8099056fc2454a81",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Nepeta/Nepeta suaveolens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<dt-example table-type="html" order="10">
<css lib="datatables tabletools" />
<js lib="jquery datatables tabletools">
<![CDATA[
$(document).ready(function() {
$('#example').DataTable( {
dom: 'T<"clear">lfrtip<"clear spacer">T',
tableTools: {
"aButtons": [ "copy", "print" ]
}
} );
} );
]]>
</js>
<title lib="TableTools">Multiple toolbars</title>
<info><![CDATA[
Like all DataTables control elements, TableTools can have multiple instances specified in the `dt-init dom` parameter of DataTables. This will create two TableTools toolbars next to the table, providing the same functions.
An example of when this might be useful is to show the toolbar both above and below the table - as is done in this example.
]]></info>
</dt-example>
| {
"content_hash": "49a181f053f92b8cea84ca6b4bd4ddc0",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 222,
"avg_line_length": 29.285714285714285,
"alnum_prop": 0.6695121951219513,
"repo_name": "netfox01/Piggy",
"id": "6935f22a2828ec909eac3f4836c7e7b9249a0ce9",
"size": "820",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "client/app/assets/js/datatables/tools/examples/multi_instance.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "16927"
},
{
"name": "CSS",
"bytes": "607759"
},
{
"name": "HTML",
"bytes": "81562"
},
{
"name": "JavaScript",
"bytes": "999312"
},
{
"name": "Shell",
"bytes": "1690"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Jun 10 13:53:02 MST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.elytron.LogicalRoleMapper.LogicalOperation (BOM: * : All 2.7.0.Final API)</title>
<meta name="date" content="2020-06-10">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.elytron.LogicalRoleMapper.LogicalOperation (BOM: * : All 2.7.0.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.7.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/elytron/class-use/LogicalRoleMapper.LogicalOperation.html" target="_top">Frames</a></li>
<li><a href="LogicalRoleMapper.LogicalOperation.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.elytron.LogicalRoleMapper.LogicalOperation" class="title">Uses of Class<br>org.wildfly.swarm.config.elytron.LogicalRoleMapper.LogicalOperation</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">LogicalRoleMapper.LogicalOperation</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.elytron">org.wildfly.swarm.config.elytron</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.elytron">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">LogicalRoleMapper.LogicalOperation</a> in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a> that return <a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">LogicalRoleMapper.LogicalOperation</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">LogicalRoleMapper.LogicalOperation</a></code></td>
<td class="colLast"><span class="typeNameLabel">LogicalRoleMapper.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.html#logicalOperation--">logicalOperation</a></span>()</code>
<div class="block">The logical operation to be performed on the role mapper mappings.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">LogicalRoleMapper.LogicalOperation</a></code></td>
<td class="colLast"><span class="typeNameLabel">LogicalRoleMapper.LogicalOperation.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html#valueOf-java.lang.String-">valueOf</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">LogicalRoleMapper.LogicalOperation</a>[]</code></td>
<td class="colLast"><span class="typeNameLabel">LogicalRoleMapper.LogicalOperation.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">LogicalRoleMapper.LogicalOperation</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.html" title="type parameter in LogicalRoleMapper">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">LogicalRoleMapper.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.html#logicalOperation-org.wildfly.swarm.config.elytron.LogicalRoleMapper.LogicalOperation-">logicalOperation</a></span>(<a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">LogicalRoleMapper.LogicalOperation</a> value)</code>
<div class="block">The logical operation to be performed on the role mapper mappings.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/elytron/LogicalRoleMapper.LogicalOperation.html" title="enum in org.wildfly.swarm.config.elytron">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.7.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/elytron/class-use/LogicalRoleMapper.LogicalOperation.html" target="_top">Frames</a></li>
<li><a href="LogicalRoleMapper.LogicalOperation.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "16d9c533dff6a8ded06fbfb1c0e5ae47",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 513,
"avg_line_length": 53.22727272727273,
"alnum_prop": 0.6741626340259986,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "886af1f3339f17930c36246ccb1c48d7ec31ce4a",
"size": "10539",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.7.0.Final/apidocs/org/wildfly/swarm/config/elytron/class-use/LogicalRoleMapper.LogicalOperation.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef _FS_SPRITE_2D_H_
#define _FS_SPRITE_2D_H_
#include "FsMacros.h"
#include "stage/entity/FsEntity.h"
#include "graphics/FsColor.h"
#include "graphics/material/FsTextureMaterial.h"
#include "graphics/FsProgram.h"
NS_FS_BEGIN
class Sprite2DData;
class Texture2D;
class FsArray;
class FsDict;
class Sprite2DAnimation;
class AnimationCacheData;
class TextureMaterial;
class Program;
class Sprite2D :public Entity
{
public:
enum
{
ANIM_LOOP,
ANIM_START,
ANIM_END,
};
public:
static Sprite2D* create();
static Sprite2D* create(const char* name);
public:
/* material */
void setColor(Color4f c){m_material->setColor(c);}
Color4f getColor(){return m_material->getColor();}
void setOpacity(float opacity){m_material->setOpacity(opacity);}
float getOpacity(){return m_material->getOpacity();}
void setBlend(int eq,int src,int dst){m_material->setBlend(eq,src,dst);}
void setBlend(int src,int dst){m_material->setBlend(src,dst);}
TextureMaterial* getMaterial(){return m_material;}
void setMaterial(TextureMaterial* mat){FS_SAFE_ASSIGN(m_material,mat);}
Program* getShader(){return m_program;}
void setShader(Program* shader){FS_SAFE_ASSIGN(m_program,shader);}
public:
void setResourceUrl(const char* name);
/* animation */
void setAnimation(const char* name);
const char* getAnimation();
void updateAnimation(float dt);
bool hasAnimation(const char* name);
void playAnimation(int mode=ANIM_LOOP);
void startAnimation(int mode=ANIM_LOOP);
void stopAnimation();
bool isAnimationPlaying();
void setAnimationOffset(float x,float y);
void getAnimationOffset(float* x,float* y);
/* frame */
void setCurFrame(int frame);
int getCurFrame();
int getTotalFrame();
/* fps */
int getFps();
void setFps(int fps);
public:
/* inherit Entity */
virtual void update(float dt);
virtual void draw(Render* render,bool update_matrix=true);
/* inherit FsObject */
virtual const char* className();
protected:
bool init();
bool init(const char* name);
void setAnimation(Sprite2DAnimation* anim);
Sprite2D();
~Sprite2D();
private:
int m_curFrame;
float m_elapseTime;
int m_mode;
int m_stop;
int m_curFps;
Sprite2DData* m_data;
Sprite2DAnimation* m_curAnimation;
AnimationCacheData* m_curAnimationCacheData; /* weak reference */
FsArray* m_textures;
FsDict* m_animationCacheData;
/* material */
TextureMaterial* m_material;
Program* m_program;
};
NS_FS_END
#endif /*_FS_SPRITE_2D_H_*/
| {
"content_hash": "d53a05f0643027d776aaf3312d513dd2",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 74,
"avg_line_length": 19.030075187969924,
"alnum_prop": 0.7068352429869617,
"repo_name": "FSource/Faeris",
"id": "9fc634d666c1f7ee3d5aa2ac733ffd86c278ace6",
"size": "2531",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/libfaeris/src/stage/entity/FsSprite2D.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "15332809"
},
{
"name": "C++",
"bytes": "4068637"
},
{
"name": "Java",
"bytes": "111665"
},
{
"name": "JavaScript",
"bytes": "1856"
},
{
"name": "Lua",
"bytes": "8734"
},
{
"name": "Objective-C",
"bytes": "48742"
},
{
"name": "Python",
"bytes": "181959"
},
{
"name": "Smalltalk",
"bytes": "331"
}
],
"symlink_target": ""
} |
<?php
namespace Google\AdsApi\Dfp\v201611;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class SavedQuery
{
/**
* @var int $id
*/
protected $id = null;
/**
* @var string $name
*/
protected $name = null;
/**
* @var \Google\AdsApi\Dfp\v201611\ReportQuery $reportQuery
*/
protected $reportQuery = null;
/**
* @var boolean $isCompatibleWithApiVersion
*/
protected $isCompatibleWithApiVersion = null;
/**
* @param int $id
* @param string $name
* @param \Google\AdsApi\Dfp\v201611\ReportQuery $reportQuery
* @param boolean $isCompatibleWithApiVersion
*/
public function __construct($id = null, $name = null, $reportQuery = null, $isCompatibleWithApiVersion = null)
{
$this->id = $id;
$this->name = $name;
$this->reportQuery = $reportQuery;
$this->isCompatibleWithApiVersion = $isCompatibleWithApiVersion;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int $id
* @return \Google\AdsApi\Dfp\v201611\SavedQuery
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
* @return \Google\AdsApi\Dfp\v201611\SavedQuery
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return \Google\AdsApi\Dfp\v201611\ReportQuery
*/
public function getReportQuery()
{
return $this->reportQuery;
}
/**
* @param \Google\AdsApi\Dfp\v201611\ReportQuery $reportQuery
* @return \Google\AdsApi\Dfp\v201611\SavedQuery
*/
public function setReportQuery($reportQuery)
{
$this->reportQuery = $reportQuery;
return $this;
}
/**
* @return boolean
*/
public function getIsCompatibleWithApiVersion()
{
return $this->isCompatibleWithApiVersion;
}
/**
* @param boolean $isCompatibleWithApiVersion
* @return \Google\AdsApi\Dfp\v201611\SavedQuery
*/
public function setIsCompatibleWithApiVersion($isCompatibleWithApiVersion)
{
$this->isCompatibleWithApiVersion = $isCompatibleWithApiVersion;
return $this;
}
}
| {
"content_hash": "9c1573dc7218bc18e170ae8639514024",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 114,
"avg_line_length": 20.364406779661017,
"alnum_prop": 0.5859342488555972,
"repo_name": "jeraldfeller/jbenterprises",
"id": "d4d7890dbe824dcbc4c57bcd022dfb2f1d52036b",
"size": "2403",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "google-adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201611/SavedQuery.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "137"
},
{
"name": "CSS",
"bytes": "4465774"
},
{
"name": "CoffeeScript",
"bytes": "83631"
},
{
"name": "HTML",
"bytes": "2549782"
},
{
"name": "JavaScript",
"bytes": "17552996"
},
{
"name": "PHP",
"bytes": "3092947"
},
{
"name": "Shell",
"bytes": "444"
}
],
"symlink_target": ""
} |
package org.wso2.carbon.stratos.common.exception;
public class TenantMgtException extends Exception {
private String errorCode = null;
public TenantMgtException(String msg, Exception e) {
super(msg, e);
}
public TenantMgtException(String msg) {
super(msg);
}
public TenantMgtException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public TenantMgtException(String errorCode, String message, Exception e) {
super(message, e);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
| {
"content_hash": "2f0312841136c1de54d89b7e50d393da",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 78,
"avg_line_length": 19.23076923076923,
"alnum_prop": 0.6493333333333333,
"repo_name": "wso2/carbon-commons",
"id": "a2e39f193e9947fc4dea14bedc568419724ba43d",
"size": "1419",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/tenant-mgt-common/org.wso2.carbon.tenant.common/src/main/java/org/wso2/carbon/stratos/common/exception/TenantMgtException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "67587"
},
{
"name": "HTML",
"bytes": "106168"
},
{
"name": "Java",
"bytes": "3346299"
},
{
"name": "JavaScript",
"bytes": "822249"
},
{
"name": "PHP",
"bytes": "15326"
},
{
"name": "XSLT",
"bytes": "335326"
}
],
"symlink_target": ""
} |
package io.prediction.data.api
import io.prediction.data.Utils
import io.prediction.data.storage.AccessKey
import io.prediction.data.storage.AccessKeys
import io.prediction.data.storage.Event
import io.prediction.data.storage.EventJson4sSupport
import io.prediction.data.storage.LEvents
import io.prediction.data.storage.StorageError
import io.prediction.data.storage.Storage
import akka.actor.ActorSystem
import akka.actor.Actor
import akka.actor.Props
import akka.io.IO
import akka.event.Logging
import akka.pattern.ask
import akka.util.Timeout
import org.json4s.DefaultFormats
//import org.json4s.ext.JodaTimeSerializers
import spray.can.Http
import spray.http.HttpCharsets
import spray.http.HttpEntity
import spray.http.HttpResponse
import spray.http.MediaTypes
import spray.http.StatusCodes
import spray.httpx.Json4sSupport
import spray.httpx.unmarshalling.Unmarshaller
import spray.routing._
import spray.routing.authentication.Authentication
import spray.routing.Directives._
import scala.concurrent.Future
import java.util.concurrent.TimeUnit
class EventServiceActor(
val eventClient: LEvents,
val accessKeysClient: AccessKeys) extends HttpServiceActor {
object Json4sProtocol extends Json4sSupport {
implicit def json4sFormats = DefaultFormats +
new EventJson4sSupport.APISerializer
//implicit def json4sFormats: Formats = DefaultFormats.lossless ++
// JodaTimeSerializers.all
}
import Json4sProtocol._
val log = Logging(context.system, this)
// we use the enclosing ActorContext's or ActorSystem's dispatcher for our
// Futures
implicit def executionContext = actorRefFactory.dispatcher
implicit val timeout = Timeout(5, TimeUnit.SECONDS)
// for better message response
val rejectionHandler = RejectionHandler {
case MalformedRequestContentRejection(msg, _) :: _ =>
complete(StatusCodes.BadRequest, Map("message" -> msg))
case MissingQueryParamRejection(msg) :: _ =>
complete(StatusCodes.NotFound,
Map("message" -> s"missing required query parameter ${msg}."))
case AuthenticationFailedRejection(cause, challengeHeaders) :: _ =>
complete(StatusCodes.Unauthorized, challengeHeaders,
Map("message" -> s"Invalid accessKey."))
}
val jsonPath = """(.+)\.json$""".r
/* with accessKey in query, return appId if succeed */
def withAccessKey: RequestContext => Future[Authentication[Int]] = {
ctx: RequestContext =>
val accessKeyOpt = ctx.request.uri.query.get("accessKey")
Future {
accessKeyOpt.map { accessKey =>
val accessKeyOpt = accessKeysClient.get(accessKey)
accessKeyOpt match {
case Some(k) => Right(k.appid)
case None => Left(AuthenticationFailedRejection(
AuthenticationFailedRejection.CredentialsRejected, List()))
}
}.getOrElse { Left(AuthenticationFailedRejection(
AuthenticationFailedRejection.CredentialsMissing, List()))
}
}
}
val route: Route =
pathSingleSlash {
get {
respondWithMediaType(MediaTypes.`application/json`) {
complete(Map("status" -> "alive"))
}
}
} ~
path("events" / jsonPath ) { eventId =>
get {
handleRejections(rejectionHandler) {
authenticate(withAccessKey) { appId =>
respondWithMediaType(MediaTypes.`application/json`) {
complete {
log.debug(s"GET event ${eventId}.")
val data = eventClient.futureGet(eventId, appId).map { r =>
r match {
case Left(StorageError(message)) =>
(StatusCodes.InternalServerError,
Map("message" -> message))
case Right(eventOpt) => {
eventOpt.map( event =>
(StatusCodes.OK, event)
).getOrElse(
(StatusCodes.NotFound, Map("message" -> "Not Found"))
)
}
}
}
data
}
}
}
}
} ~
delete {
handleRejections(rejectionHandler) {
authenticate(withAccessKey) { appId =>
respondWithMediaType(MediaTypes.`application/json`) {
complete {
log.debug(s"DELETE event ${eventId}.")
val data = eventClient.futureDelete(eventId, appId).map { r =>
r match {
case Left(StorageError(message)) =>
(StatusCodes.InternalServerError,
Map("message" -> message))
case Right(found) =>
if (found) {
(StatusCodes.OK, Map("message" -> "Found"))
} else {
(StatusCodes.NotFound, Map("message" -> "Not Found"))
}
}
}
data
}
}
}
}
}
} ~
path("events.json") {
post {
handleRejections(rejectionHandler) {
authenticate(withAccessKey) { appId =>
entity(as[Event]) { event =>
complete {
log.debug(s"POST events")
val data = eventClient.futureInsert(event, appId).map { r =>
r match {
case Left(StorageError(message)) =>
(StatusCodes.InternalServerError,
Map("message" -> message))
case Right(id) =>
(StatusCodes.Created, Map("eventId" -> s"${id}"))
}
}
data
}
}
}
}
} ~
get {
handleRejections(rejectionHandler) {
authenticate(withAccessKey) { appId =>
parameters(
'startTime.as[Option[String]],
'untilTime.as[Option[String]],
'entityType.as[Option[String]],
'entityId.as[Option[String]],
'event.as[Option[String]],
'targetEntityType.as[Option[String]],
'targetEntityId.as[Option[String]],
'limit.as[Option[Int]],
'reversed.as[Option[Boolean]]) {
(startTimeStr, untilTimeStr, entityType, entityId,
eventName, // only support one event name
targetEntityType, targetEntityId,
limit, reversed) =>
respondWithMediaType(MediaTypes.`application/json`) {
complete {
log.debug(
s"GET events of appId=${appId} " +
s"st=${startTimeStr} ut=${untilTimeStr} " +
s"et=${entityType} eid=${entityId} " +
s"li=${limit} rev=${reversed} ")
val parseTime = Future {
val startTime = startTimeStr.map(Utils.stringToDateTime(_))
val untilTime = untilTimeStr.map(Utils.stringToDateTime(_))
(startTime, untilTime)
}
parseTime.flatMap { case (startTime, untilTime) =>
val data = eventClient.futureFind(
appId = appId,
startTime = startTime,
untilTime = untilTime,
entityType = entityType,
entityId = entityId,
eventNames = eventName.map(List(_)),
targetEntityType = targetEntityType.map(Some(_)),
targetEntityId = targetEntityId.map(Some(_)),
limit = limit.orElse(Some(20)),
reversed = reversed)
.map { r =>
r match {
case Left(StorageError(message)) =>
(StatusCodes.InternalServerError,
Map("message" -> message))
case Right(eventIter) =>
if (eventIter.hasNext)
(StatusCodes.OK, eventIter.toArray)
else
(StatusCodes.NotFound,
Map("message" -> "Not Found"))
}
}
data
}.recover {
case e: Exception =>
(StatusCodes.BadRequest, Map("message" -> s"${e}"))
}
}
}
}
}
}
}
}
def receive = runRoute(route)
}
/* message */
case class StartServer(
val host: String,
val port: Int
)
class EventServerActor(
val eventClient: LEvents,
val accessKeysClient: AccessKeys) extends Actor {
val log = Logging(context.system, this)
val child = context.actorOf(
Props(classOf[EventServiceActor], eventClient, accessKeysClient),
"EventServiceActor")
implicit val system = context.system
def receive = {
case StartServer(host, portNum) => {
IO(Http) ! Http.Bind(child, interface = host, port = portNum)
}
case m: Http.Bound => log.info("Bound received. EventServer is ready.")
case m: Http.CommandFailed => log.error("Command failed.")
case _ => log.error("Unknown message.")
}
}
case class EventServerConfig(
ip: String = "localhost",
port: Int = 7070
)
object EventServer {
def createEventServer(config: EventServerConfig) = {
implicit val system = ActorSystem("EventServerSystem")
val eventClient = Storage.getLEvents()
val accessKeysClient = Storage.getMetaDataAccessKeys
val serverActor = system.actorOf(
Props(classOf[EventServerActor], eventClient, accessKeysClient),
"EventServerActor")
serverActor ! StartServer(config.ip, config.port)
system.awaitTermination
}
}
object Run {
def main (args: Array[String]) {
EventServer.createEventServer(EventServerConfig(
ip = "localhost",
port = 7070))
}
}
| {
"content_hash": "9454a9272ac2d94d26ca9ba9bcaabb11",
"timestamp": "",
"source": "github",
"line_count": 305,
"max_line_length": 79,
"avg_line_length": 33.32786885245902,
"alnum_prop": 0.5516969995081161,
"repo_name": "TheDataShed/PredictionIO",
"id": "f4692590e347641686906843108f6d7b5bae5dd5",
"size": "10777",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "data/src/main/scala/api/EventAPI.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "21818"
},
{
"name": "Java",
"bytes": "103753"
},
{
"name": "JavaScript",
"bytes": "2041"
},
{
"name": "Python",
"bytes": "15600"
},
{
"name": "Ruby",
"bytes": "22738"
},
{
"name": "Scala",
"bytes": "762834"
},
{
"name": "Shell",
"bytes": "45502"
}
],
"symlink_target": ""
} |
Nagios drupal plugin to monitor the state of a drupal site and/or drupal multisite for security updates, system updates, core errors, core warnings and missing database migrations.
[](https://travis-ci.org/cytopia/check_drupal)
[](https://packagist.org/packages/cytopia/check_drupal) [](https://packagist.org/packages/cytopia/check_drupal) [](https://packagist.org/packages/cytopia/check_drupal) [](http://opensource.org/licenses/MIT)
[](https://en.wikipedia.org/?title=POSIX)
[](https://en.wikipedia.org/?title=Bourne_shell)
---
| [](https://github.com/cytopia/awesome-nagios-plugins) | Find more plugins at [Awesome Nagios](https://github.com/cytopia/awesome-nagios-plugins) |
|---|---|
| [](https://exchange.icinga.com/cytopia) | **Find more plugins at [Icinga Exchange](https://exchange.icinga.com/cytopia)** |
| [](https://exchange.nagios.org/directory/Owner/cytopia/1) | **Find more plugins at [Nagios Exchange](https://exchange.nagios.org/directory/Owner/cytopia/1)** |
---
**Tested on**
* Drupal 6
* Drupal 7
* Drupal 8
---
**Overview**

**Details**

---
##### NOTE
This check can be used in two ways:
1. Let nagios always trigger `check_drupal` which might take 1-3 seconds and cause some load
2. Let nagios simply parse the logfile (with `check_drupal_log`) created by `check_drupal` via cron on the target machine.
I would recommend the second option as you do not check each drupal site every 5 minutes and also in order to keep the nagios check as fast as possible. For that use cron to trigger the `check_drupal` on the target machine every 6 hours or so.
##### Requirements
| Program | Required | Description |
| ------------- | ------------- | -------- |
| bourne shell (sh) | yes | The whole script is written in pure bourne shell (sh) and is 100% Posix compliant |
| [check_by_ssh](https://www.monitoring-plugins.org/doc/man/check_by_ssh.html) or<br/>[NRPE](https://exchange.nagios.org/directory/Addons/Monitoring-Agents/NRPE--2D-Nagios-Remote-Plugin-Executor/details) | yes | check_by_ssh is used as a wrapper to check on remote hosts. Alternatively you can use NRPE as reported here: [Issue #2](https://github.com/cytopia/check_drupal/issues/2) |
| [drush](http://www.drush.org) | yes | This nagios plugin requires drush to be installed on the target machine |
##### Features
* Multisite support
* Check for Drupal security updates
* Check for Drupal system updates
* Check for Drupal required database migrations
* Check for Drupal core errors
* Check for Drupal core warnings
* Every check can specify its own nagios severity (Error or Warning)
* Custom name for nagios short output
* Be able to don't show updates that are locked via drush
* Detailed information in nagios long output
* Be able to successfully recognize valid Drupal6 or Drupal7 document root
* Basic performance data fow: how many OKs, Errors, Warnings and Unknowns
## 1. Usage
### 1.1 `check_drupal`
With `-l` you will be able to run the `check_drupal` locally on each machine only a few times a day and dump the output to a logfile.
This file can then be checked normaly via nagios by calling `check_drupal_log` instead, which will just read the log and not put any load onto the machine.
Multiple logfiles for multiple drupal site per server will be possible.
```shell
Usage: check_drupal -d <drupal root> [-n <name>] [-s <w|e>] [-u <w|e>] [-e <w|e>] [-w <w|e>] [-m <w|e>] [-i <uri>] [-l <log file>] [-r]
OR check_drupal --check
OR check_drupal --help
OR check_drupal --version
Nagios plugin that will check drupal sites for errors.
Errors include the following: available security updates,
missed database migrations and drupal status errors.
For each check you can specify the nagios severity (error or warning).
-d <drupal root> The full path to the drupal document root (usually
the 'drupal' folder. This parameter is required.
-n <name> [optional] Specify a name for the drupal instance to
appear on the nagios output. The default is 'Drupal'
-s <w|e> [optional] Check for drupal core and module security
updates and return nagios error or warning.
Warning: -s w
Error: -s e
-u <w|e> [optional] Check for drupal core and module updates
in general and return nagios error or warning.
Warning: -u w
Error: -u e
-e <w|e> [optional] Check for drupal status errors and return
nagios error or warning.
Warning: -e w
Error: -e e
-w <w|e> [optional] Check for drupal status warnings and return
nagios error or warning.
Warning: -w w
Error: -w e
-m <w|e> [optional] Check for drupal missed database migrations
and return nagios error or warning. (They can occur
when you update core or modules and forget the db).
Warning: -m w
Error: -m e
-i <uri> [optional] Parse in an url for a drupal multisite instance.
'drush --uri':
In Drupal 7, the value of --uri should always be
the same as when the site is being accessed from a web browser
(e.g. http://mysite.org, although the http:// is optional).
In Drupal 6, the value of --uri should always be the same as the
site's folder name in the 'sites' folder (e.g. default); it is best
if the site folder name matches the URI from the browser, and is consistent
on every instance of the same site
(e.g. also use sites/mysite.org for http://dev.mysite.org).
-l <log file> [optional] Instead of checking all of the above via nagios
every five minutes or so, run this script via cron once a day
(or twice) and write the output into a logfile. This logfile can
then be checked by the nagios plugin 'check_drupal_log' which is
less costy in terms of load/cpu.
See 'check_drupal_log --help' for more info.
Example:
check_drupal -d /var/www -s e -e e -w w -l /var/log/drupal.log
check_drupal_log -l /var/log/drupal.log
-r [optional] Filters all updates that are locked via drush.
For general infos about locking run 'drush pm-updatestatus -h'
--check Check for program requirements.
--help Show this help
--version Show version information.
```
### 1.2 `check_drupal_log`
```bash
Usage: check_drupal_log -f <logfile>
OR check_drupal_log --help
OR check_drupal_log --version
Nagios plugin that will parse the logfile created by 'check_drupal'.
-f <logfile> The full path to logfile created by 'check_drupal'
--help Show this help
--version Show version information.
```
## 2. Examples
The following examples are run directly from the command line. The exit code will always be aggregated, meaning if the program throws a warning and an error, the final exit code will result in an error.
Also to note: The first line until the `|` represents the actual nagios output. Everything in the first line behind the `|` is performance data used to generate the cool charts. Everything from line two onwards is nagios extended status info (when you click on details).
**Check for security updates**
```bash
./check_drupal -d /shared/httpd/sites-drupal/COOL-PROJECT/drupal/ -n COOL-PROJECT -s e
[CRITICAL] COOL-PROJECT has errors: 2 Security updates | 'Security Updates'=2;;;; 'Updates'=0;;;; 'Core Errors'=0;;;; 'Core Warnings'=0;;;; 'Database Migrations'=0;;;; 'OK'=0;;;0;1 'Errors'=1;1;1;0;1 'Warnings'=0;1;;0;1 'Unknown'=0;;;0;1
==== SECURITY UPDATES ====
[CRITICAL] drupal 7.40 -> 7.41
[CRITICAL] jquery_update 7.x-2.6 -> 7.x-2.7
```
**Check for security and normal updates**
```bash
./check_drupal -d /shared/httpd/sites-drupal/COOL-PROJECT/drupal/ -n COOL-PROJECT -s e -u w
[CRITICAL] COOL-PROJECT has errors: 3 Security updates, 3 Updates | 'Security Updates'=3;;;; 'Updates'=3;;;; 'Core Errors'=0;;;; 'Core Warnings'=0;;;; 'Database Migrations'=0;;;; 'OK'=0;;;0;2 'Errors'=1;1;1;0;2 'Warnings'=1;1;;0;2 'Unknown'=0;;;0;2
==== SECURITY UPDATES ====
[CRITICAL] drupal 7.40 -> 7.41
[CRITICAL] block_class 7.x-2.1 -> 7.x-2.3
[CRITICAL] jquery_update 7.x-2.6 -> 7.x-2.7
==== SYSTEM UPDATES ====
[WARNING] field_collection 7.x-1.0-beta9 -> 7.x-1.0-beta10
[WARNING] views 7.x-3.11 -> 7.x-3.13
[WARNING] bootstrap 7.x-3.0 -> 7.x-3.4
```
**Check for all possible stuff**
```bash
./check_drupal -d /shared/httpd/sites-drupal/COOL-PROJECT/drupal/ -n COOL-PROJECT -s e -u w -e e -w w -m e
[CRITICAL] COOL-PROJECT has errors: 3 Security updates, 3 Updates, 5 Core errors, 1 Core warning | 'Security Updates'=3;;;; 'Updates'=3;;;; 'Core Errors'=5;;;; 'Core Warnings'=1;;;; 'Database Migrations'=0;;;; 'OK'=1;;;0;5 'Errors'=2;1;1;0;5 'Warnings'=2;1;;0;5 'Unknown'=0;;;0;5
==== SECURITY UPDATES ====
[CRITICAL] drupal 7.40 -> 7.41
[CRITICAL] block_class 7.x-2.1 -> 7.x-2.3
[CRITICAL] jquery_update 7.x-2.6 -> 7.x-2.7
==== SYSTEM UPDATES ====
[WARNING] field_collection 7.x-1.0-beta9 -> 7.x-1.0-beta10
[WARNING] views 7.x-3.11 -> 7.x-3.13
[WARNING] bootstrap 7.x-3.0 -> 7.x-3.4
==== CORE ERRORS ====
[CRITICAL] CKeditor
[CRITICAL] Cron-Wartungsaufgaben
[CRITICAL] CTools CSS Cache
[CRITICAL] Aktualisierungsstatus von Modulen und Themes
[CRITICAL] Aktualisierungsstatus des Drupal-Kern
==== CORE WARNINGS ====
[WARNING] Token
==== DB UPDATES ====
[OK] No database migrations required
```
**Check for db updates**
```bash
./check_drupal -d /shared/httpd/sites-drupal/COOL-PROJECT/drupal/ -n COOL-PROJECT -m e
[OK] COOL-PROJECT is healty | 'Security Updates'=0;;;; 'Updates'=0;;;; 'Core Errors'=0;;;; 'Core Warnings'=0;;;; 'Database Migrations'=0;;;; 'OK'=1;;;0;1 'Errors'=0;1;1;0;1 'Warnings'=0;1;;0;1 'Unknown'=0;;;0;1
==== DB UPDATES ====
[OK] No database migrations required
```
## 3. Nagios Configuration
### 3.1 check_drupal
#### Command definition
In order to check drupal sites on remote servers you will need to make use of `check_by_ssh`.
```bash
name: check_by_ssh_drupal
command: $USER1$/check_by_ssh -H $HOSTADDRESS$ -t 60 -l "$USER17$" -C "$USER22$/check_drupal -d $ARG1$ -n $ARG2$ $ARG3$"
```
#### Service definition
In the above command definition there are two fixed arguments for the document root and the project name as well as one loose argument place holder that can hold all checks you want to run. The following shows one example service definition for one specific drupal site:
```bash
check command: ssh_drupal_cool-drupal-project
$ARG1$: /var/www/cool-drupal-project/drupal/
$ARG2$: Cool Drupal Project
$ARG3$: -s e -u w -e e -w w -m e
```
The above service definition will check against security updates (with nagios error), against normal updates (with nagios warning), against core errors (with nagios error), against core warnings (with nagios warning) and finally against missed database migrations (with nagios error).
### 3.2 check_drupal_log
#### Command definition
In order to check drupal sites on remote servers you will need to make use of `check_by_ssh`.
```bash
name: check_by_ssh_drupal
command: $USER1$/check_by_ssh -H $HOSTADDRESS$ -t 60 -l "$USER17$" -C "$USER22$/check_drupal_log -f $ARG1$"
```
#### Service definition
In the above command definition there is only one argument. This will point to the logfile created by `check_drupal`:
```bash
check command: ssh_drupal_cool-drupal-project
$ARG1$: /var/log/drupal_cool-project.log
```
#### Cron setup
For this recommended setup to work you need to setup a cronjob on the target machine (where the drupal site is installed) that is run every 6 hours, every day or whatever you want.
Setup multiple cronjobs with multiple logfiles if you have multiple drupal sites on this machine that you want to monitor.
```cron
0 */6 * * * /path/to/check_drupal -d /var/www/cool-drupal-project/drupal/ -n "Cool Project" -s e -u w -e e -w w -m e -l /var/log/drupal_cool-project.log
```
## 4. Icinga2 Configuration
### 4.1 check_drupal
#### Command definition
Because icinga2 should be running on every monitored server, there is no need for `check_by_ssh`.
```bash
object CheckCommand "check_drupal" {
import "plugin-check-command"
command = [ PluginDir + "/check_drupal" ]
arguments = {
"-d" = "$drupal_root$"
"-n" = "$name$"
"-s" = "$s$"
"-u" = "$u$"
"-e" = "$e$"
"-w" = "$w$"
"-m" = "$m$"
}
}
```
#### Service definition
The following shows an example service definition for one specific drupal site:
```bash
apply Service "check_cool-drupal-project" {
import "generic-service"
check_command = "check_drupal"
vars.drupal_root = "/var/www/cool-drupal-project/drupal/"
vars.name = "Cool Drupal Project"
vars.s = "e"
vars.u = "w"
vars.e = "e"
vars.w = "w"
vars.m = "e"
assign where host.name == NodeName
}
```
The above service definition will check against security updates (with nagios error), against normal updates (with nagios warning), against core errors (with nagios error), against core warnings (with nagios warning) and finally against missed database migrations (with nagios error).
### 4.2 check_drupal_log
#### Command definition
```bash
object CheckCommand "check_drupal_log" {
import "plugin-check-command"
command = [ PluginDir + "/check_drupal_log" ]
arguments = {
"-f" = "$logfile$"
}
}
```
#### Service definition
In the above command definition there is only one argument. This will point to the logfile created by `check_drupal`:
```bash
apply Service for (logfile => config in host.vars.logfile) {
import "generic-service"
check_command = "check_drupal_log"
vars += config
}
```
The above service definition will look for multiple "vars.logfile" in your `host.conf`:
```bash
vars.logfile["drupal name1"] = { logfile = "/var/log/check_drupal/name1.log" }
vars.logfile["drupal name2"] = { logfile = "/var/log/check_drupal/name2.log" }
vars.logfile["drupal name3"] = { logfile = "/var/log/check_drupal/name3.log" }
```
#### Cron setup
For this recommended setup to work you need to setup a cronjob on the target machine (where the drupal site is installed) that is run every 6 hours, every day or whatever you want.
Setup multiple cronjobs with multiple logfiles if you have multiple drupal sites on this machine that you want to monitor.
```cron
0 */6 * * * /path/to/check_drupal -d /var/www/cool-drupal-project/drupal/ -n "Cool Project" -s e -u w -e e -w w -m e -l /var/log/drupal_cool-project.log
```
## 5. Performance data
Screenshots taken from an [Icinga](https://www.icinga.org/) setup
### 5.1 Specific data
The following performance data gives detailed information about specific errors/warnings that have occured





### 5.2 General data
The following performance data gives a general overview about how many OK's, Errors, Warnings and Unknowns have happened over time. This way you can also see how quickly the reaction time has been to occured problems.
**Best practise:**
* OK: should always be a high vertical line
* Error: Should only have short peaks
* Warning: Should only have short peaks
* Unknown: Should never happen




## 6. License
[](http://opensource.org/licenses/mit)
## 7. Awesome
Added by the following [](https://github.com/sindresorhus/awesome) lists:
* [awesome-nagios-plugins](https://github.com/cytopia/awesome-nagios-plugins)
* [mrsinguyen/awesome-drupal](https://github.com/mrsinguyen/awesome-drupal)
| {
"content_hash": "ae4c9dfee40cc7a40920fbc91deed6f5",
"timestamp": "",
"source": "github",
"line_count": 392,
"max_line_length": 503,
"avg_line_length": 46.423469387755105,
"alnum_prop": 0.6763930102209034,
"repo_name": "cytopia/check_drupal",
"id": "b48de2d6e76a985a4bd61b8fcbe4fe2dbc186596",
"size": "18213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "36185"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>http://lpantano.github.io/tag/in-situ-hybridization/</title>
<link rel="canonical" href="http://lpantano.github.io/tag/in-situ-hybridization/">
<meta name="robots" content="noindex">
<meta charset="utf-8">
<meta http-equiv="refresh" content="0; url=http://lpantano.github.io/tag/in-situ-hybridization/">
</head>
</html>
| {
"content_hash": "aae1cf91769f70168179ad3cf573fdd2",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 101,
"avg_line_length": 39.4,
"alnum_prop": 0.6725888324873096,
"repo_name": "lpantano/lpantano.github.io",
"id": "91b6e4a95f3f88bc431bd5c5adb8229b5fd4f918",
"size": "394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tag/in-situ-hybridization/page/1/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "42748"
},
{
"name": "HTML",
"bytes": "27181755"
},
{
"name": "JavaScript",
"bytes": "131965"
},
{
"name": "Jupyter Notebook",
"bytes": "169859"
},
{
"name": "Python",
"bytes": "3522"
},
{
"name": "Ruby",
"bytes": "761"
},
{
"name": "SCSS",
"bytes": "64825"
},
{
"name": "TeX",
"bytes": "418855"
}
],
"symlink_target": ""
} |
package com.xruby.runtime.builtin;
import com.xruby.runtime.builtin.ObjectFactory;
import com.xruby.runtime.builtin.RubyArray;
import com.xruby.runtime.lang.RubyConstant;
import junit.framework.TestCase;
public class ArrayPackerTest extends TestCase {
public void test_pack() {
StringBuilder s = ArrayPacker.pack(new RubyArray(ObjectFactory.FIXNUM1), "q");
String expected = new String(new char[]{1, 0, 0, 0, 0, 0, 0, 0});
assertEquals(expected.length(), s.toString().length());
}
public void test_unpack_empty() {
RubyArray a = ArrayPacker.unpack("", "q");
assertEquals(1, a.size());
assertEquals(RubyConstant.QNIL, a.get(0));
}
public void test_unpack() {
String s = new String(new char[]{1, 0, 0, 0, 0, 0, 0, 0});
RubyArray a = ArrayPacker.unpack(s, "q");
assertEquals(1, a.size());
assertEquals(ObjectFactory.FIXNUM1, a.get(0));
}
}
| {
"content_hash": "a27e2b83c7a2c86fddacfbede6b0ac20",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 86,
"avg_line_length": 33.6551724137931,
"alnum_prop": 0.6260245901639344,
"repo_name": "weimingtom/xruby",
"id": "7f587cbb3213f2c6be213b2e9eadd23cb2c6e925",
"size": "1062",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/com/xruby/runtime/builtin/ArrayPackerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "456"
},
{
"name": "GAP",
"bytes": "76350"
},
{
"name": "Java",
"bytes": "1366741"
},
{
"name": "Ruby",
"bytes": "1648208"
},
{
"name": "Shell",
"bytes": "341"
}
],
"symlink_target": ""
} |
/**
* Create with IntelliJ IDEA
* Project name : blur-admin-1.2.0
* Package name :
* Author : Wukunmeng
* User : wukm
* Date : 17-7-20
* Time : 上午11:16
* ---------------------------------
*
*/
(function () {
'use strict';
angular.module("BlurAdmin.pages.trade",["BlurAdmin.pages.trade.current","BlurAdmin.pages.trade.history","BlurAdmin.pages.trade.count","BlurAdmin.pages.trade.coin"]).config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('trade', {
url: '/trade',
template : '<ui-view></ui-view>',
abstract: true,
title: '订单管理',
sidebarMeta: {
icon: 'ion-social-yen',
order: 40,
},
});
}
})(); | {
"content_hash": "cf00e04b655c530657d1530034e0c7e4",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 189,
"avg_line_length": 26.3125,
"alnum_prop": 0.4857482185273159,
"repo_name": "wkmnet/admin-frontend",
"id": "b0c060201d772cc6f0e1326a4afcdb08cbef365d",
"size": "854",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/pages/trade/trade.module.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1100582"
},
{
"name": "HTML",
"bytes": "500159"
},
{
"name": "JavaScript",
"bytes": "3111330"
},
{
"name": "Shell",
"bytes": "238"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<link href="http://gmpg.org/xfn/11" rel="profile">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<title>Ubuntu · Leif Madsen</title>
<link rel="stylesheet" href="http://blog.leifmadsen.com/css/poole.css">
<link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde.css">
<link rel="stylesheet" href="http://blog.leifmadsen.com/css/poole-overrides.css">
<link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde-overrides.css">
<link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde-x.css">
<link rel="stylesheet" href="http://blog.leifmadsen.com/css/highlight/monokai.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://blog.leifmadsen.com/touch-icon-144-precomposed.png">
<link href="http://blog.leifmadsen.com/favicon.png" rel="icon">
<link href="http://blog.leifmadsen.com/tags/ubuntu/index.xml" rel="alternate" type="application/rss+xml" title="Asterisk, and other worldly endeavours · Leif Madsen" />
<meta name="description" content="">
<meta name="keywords" content="">
</head>
<body>
<div class="sidebar">
<div class="container sidebar-sticky">
<div class="sidebar-about">
<h1>Leif Madsen</h1>
<p class="lead">Asterisk, and other worldly endeavours</p>
</div>
<ul class="sidebar-nav">
<li class="sidebar-nav-item"><a href="http://blog.leifmadsen.com/">Blog</a></li>
</ul>
<ul class="sidebar-nav">
<li class="sidebar-nav-item">
<a href="http://github.com/leifmadsen"><i class="fa fa-github-square fa-3x"></i></a>
<a href="http://linkedin.com/in/leifmadsen"><i class="fa fa-linkedin-square fa-3x"></i></a>
<a href="http://twitter.com/leifmadsen"><i class="fa fa-twitter-square fa-3x"></i></a>
<a href="http://blog.leifmadsen.com/index.xml" type="application/rss+xml"><i class="fa fa-rss-square fa-3x"></i></a>
</li>
</ul>
<p>Copyright © 2016 <a href="http://blog.leifmadsen.com/license/">License</a><br/>
Powered by <a href="http://gohugo.io">Hugo</a> and <a href="https://github.com/zyro/hyde-x">Hyde-X</a></p>
</div>
</div>
<div class="content container">
<ul class="posts">
<li><a href="http://blog.leifmadsen.com/blog/2009/11/27/cisco-vpn-client-on-ubuntu-karmic-9.10/">Cisco VPN Client on Ubuntu Karmic 9.10</a>
·
<a class="label" href="http://blog.leifmadsen.com/categories/technology">Technology</a>
</span>
· <time>Nov 27, 2009</time></li>
</ul>
</div>
<script src="http://blog.leifmadsen.com/js/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</body>
</html>
| {
"content_hash": "1867865b2a45e2f63ee3f1618c31a88c",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 177,
"avg_line_length": 35.80681818181818,
"alnum_prop": 0.6540780704538242,
"repo_name": "leifmadsen/blog",
"id": "63e770555cb19db8940b4d8fa461c519823f35b9",
"size": "3151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tags/ubuntu/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "265010"
},
{
"name": "HTML",
"bytes": "4509657"
},
{
"name": "JavaScript",
"bytes": "5064"
},
{
"name": "Roff",
"bytes": "3343"
},
{
"name": "Shell",
"bytes": "629"
}
],
"symlink_target": ""
} |
package org.zaproxy.zap.extension.sse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.db.Database;
import org.parosproxy.paros.db.DatabaseException;
import org.parosproxy.paros.db.DatabaseUnsupportedException;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.extension.SessionChangedListener;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.PersistentConnectionListener;
import org.zaproxy.zap.ZapGetMethod;
import org.zaproxy.zap.extension.help.ExtensionHelp;
import org.zaproxy.zap.extension.httppanel.Message;
import org.zaproxy.zap.extension.httppanel.component.HttpPanelComponentInterface;
import org.zaproxy.zap.extension.httppanel.view.HttpPanelDefaultViewSelector;
import org.zaproxy.zap.extension.httppanel.view.HttpPanelView;
import org.zaproxy.zap.extension.httppanel.view.hex.HttpPanelHexView;
import org.zaproxy.zap.extension.sse.db.EventStreamStorage;
import org.zaproxy.zap.extension.sse.db.TableEventStream;
import org.zaproxy.zap.extension.sse.ui.EventStreamPanel;
import org.zaproxy.zap.extension.sse.ui.httppanel.component.EventStreamComponent;
import org.zaproxy.zap.extension.sse.ui.httppanel.models.ByteEventStreamPanelViewModel;
import org.zaproxy.zap.extension.sse.ui.httppanel.models.StringEventStreamPanelViewModel;
import org.zaproxy.zap.extension.sse.ui.httppanel.views.EventStreamSyntaxHighlightTextView;
import org.zaproxy.zap.extension.sse.ui.httppanel.views.large.EventStreamLargeEventUtil;
import org.zaproxy.zap.extension.sse.ui.httppanel.views.large.EventStreamLargePayloadView;
import org.zaproxy.zap.extension.sse.ui.httppanel.views.large.EventStreamLargetPayloadViewModel;
import org.zaproxy.zap.view.HttpPanelManager;
import org.zaproxy.zap.view.HttpPanelManager.HttpPanelComponentFactory;
import org.zaproxy.zap.view.HttpPanelManager.HttpPanelDefaultViewSelectorFactory;
import org.zaproxy.zap.view.HttpPanelManager.HttpPanelViewFactory;
/**
* The Server-Sent Events (SSE) extension was written in December 2012. This specification defines
* an API for opening an HTTP connection for receiving push notifications from a server in the form
* of DOM events. See: http://www.w3.org/TR/eventsource/.
*
* @author Robert Koch
*/
public class ExtensionServerSentEvents extends ExtensionAdaptor
implements PersistentConnectionListener, SessionChangedListener {
private static final Logger logger = Logger.getLogger(ExtensionServerSentEvents.class);
public static final int HANDSHAKE_LISTENER = 10;
/** Name of this extension. */
public static final String NAME = "ExtensionServerSentEvents";
private Charset charset;
/** Responsible for storing events. */
private EventStreamStorage storage;
/** List of observers added to all event streams. */
private List<EventStreamObserver> observers = new ArrayList<>();
private Map<Integer, EventStreamProxy> sseProxies = new HashMap<>();
private EventStreamPanel panel;
public ExtensionServerSentEvents() {
super(NAME);
charset = Charset.forName("UTF-8");
setOrder(159);
}
@Override
public void init() {
super.init();
}
private void addObserver(EventStreamObserver observer) {
synchronized (observers) {
observers.add(observer);
}
}
@Override
public void hook(ExtensionHook extensionHook) {
super.hook(extensionHook);
extensionHook.addPersistentConnectionListener(this);
extensionHook.addSessionListener(this);
if (getView() != null) {
// setup SSE tab
EventStreamPanel tab = getEventStreamTab();
tab.setDisplayPanel(getView().getRequestPanel(), getView().getResponsePanel());
addObserver(tab);
extensionHook.addSessionListener(tab.getSessionListener());
extensionHook.getHookView().addStatusPanel(tab);
initializeWorkPanel();
ExtensionHelp.enableHelpKey(tab, "sse.tab");
}
}
@Override
public boolean canUnload() {
return true;
}
@Override
public void unload() {
super.unload();
// clear up existing connections
for (Entry<Integer, EventStreamProxy> sseEntry : sseProxies.entrySet()) {
EventStreamProxy sseProxy = sseEntry.getValue();
sseProxy.stop();
}
clearUpWorkPanel();
}
private EventStreamPanel getEventStreamTab() {
if (panel == null) {
panel = new EventStreamPanel(storage.getTable()); // TODO, getBrkManager());
}
return panel;
}
@Override
public void databaseOpen(Database db) throws DatabaseException, DatabaseUnsupportedException {
TableEventStream table = new TableEventStream();
db.addDatabaseListener(table);
try {
table.databaseOpen(db.getDatabaseServer());
if (panel != null) {
panel.setTable(table);
}
if (storage == null) {
storage = new EventStreamStorage(table);
addObserver(storage);
} else {
storage.setTable(table);
}
} catch (DatabaseException e) {
logger.warn(e.getMessage(), e);
}
}
@Override
public String getDescription() {
return Constant.messages.getString("sse.desc");
}
/**
* Add Server-Sent Events stream.
*
* @param msg Contains request & response headers.
* @param remoteReader Content arrives continuously and is forwarded to local client.
* @param localWriter Received content is written here.
*/
public void addEventStream(
HttpMessage msg, final InputStream remoteReader, final OutputStream localWriter) {
BufferedReader reader = new BufferedReader(new InputStreamReader(remoteReader, charset));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(localWriter, charset));
EventStreamProxy proxy = new EventStreamProxy(msg, reader, writer);
synchronized (observers) {
for (EventStreamObserver observer : observers) {
proxy.addObserver(observer);
}
}
proxy.start();
// TODO: save all proxies
}
@Override
public int getArrangeableListenerOrder() {
return HANDSHAKE_LISTENER;
}
@Override
public boolean onHandshakeResponse(
HttpMessage httpMessage, Socket inSocket, ZapGetMethod method) {
boolean keepSocketOpen = false;
if (httpMessage.isEventStream()) {
logger.debug("Got Server-Sent Events stream.");
ZapGetMethod handshakeMethod = (ZapGetMethod) httpMessage.getUserObject();
if (handshakeMethod != null) {
keepSocketOpen = true;
InputStream inputStream;
try {
inputStream = handshakeMethod.getResponseBodyAsStream();
inSocket.setSoTimeout(0);
inSocket.setTcpNoDelay(true);
inSocket.setKeepAlive(true);
addEventStream(httpMessage, inputStream, inSocket.getOutputStream());
} catch (IOException e) {
logger.warn(e.getMessage(), e);
keepSocketOpen = false;
}
} else {
logger.error("Was not able to retrieve input stream.");
}
}
return keepSocketOpen;
}
@Override
public void sessionChanged(final Session session) {}
@Override
public void sessionAboutToChange(Session session) {
if (View.isInitialised()) {
// Prevent the table from being used
// getWebSocketPanel().setTable(null);
storage.setTable(null);
}
// close existing connections
synchronized (sseProxies) {
for (EventStreamProxy sseProxy : sseProxies.values()) {
sseProxy.stop();
}
sseProxies.clear();
}
}
@Override
public void sessionScopeChanged(Session session) {}
@Override
public void sessionModeChanged(Mode mode) {}
public static int compareTo(EventStreamObserver base, EventStreamObserver other) {
int myOrder = base.getServerSentEventObservingOrder();
int otherOrder = other.getServerSentEventObservingOrder();
if (myOrder < otherOrder) {
return -1;
} else if (myOrder > otherOrder) {
return 1;
}
return 0;
}
private void initializeWorkPanel() {
// Add "HttpPanel" components and views.
HttpPanelManager manager = HttpPanelManager.getInstance();
// component factory for outgoing and incoming messages with Text view
HttpPanelComponentFactory componentFactory = new EventStreamComponentFactory();
manager.addResponseComponentFactory(componentFactory);
// use same factory for request & response,
// as Hex payloads are accessed the same way
HttpPanelViewFactory viewFactory = new EventStreamHexViewFactory();
manager.addResponseViewFactory(EventStreamComponent.NAME, viewFactory);
// add the default Hex view for binary-opcode messages
HttpPanelDefaultViewSelectorFactory viewSelectorFactory =
new HexDefaultViewSelectorFactory();
manager.addResponseDefaultViewSelectorFactory(
EventStreamComponent.NAME, viewSelectorFactory);
// replace the normal Text views with the ones that use syntax highlighting
viewFactory = new SyntaxHighlightTextViewFactory();
manager.addResponseViewFactory(EventStreamComponent.NAME, viewFactory);
// support large payloads on incoming and outgoing messages
viewFactory = new EventStreamLargePayloadViewFactory();
manager.addResponseViewFactory(EventStreamComponent.NAME, viewFactory);
viewSelectorFactory = new EventStreamLargeEventDefaultViewSelectorFactory();
manager.addResponseDefaultViewSelectorFactory(
EventStreamComponent.NAME, viewSelectorFactory);
}
private void clearUpWorkPanel() {
HttpPanelManager manager = HttpPanelManager.getInstance();
// component factory for outgoing and incoming messages with Text view
manager.removeRequestComponentFactory(EventStreamComponentFactory.NAME);
manager.removeRequestComponents(EventStreamComponent.NAME);
manager.removeResponseComponentFactory(EventStreamComponentFactory.NAME);
manager.removeResponseComponents(EventStreamComponent.NAME);
// use same factory for request & response,
// as Hex payloads are accessed the same way
manager.removeResponseViewFactory(
EventStreamComponent.NAME, EventStreamHexViewFactory.NAME);
// remove the default Hex view for binary-opcode messages
manager.removeResponseDefaultViewSelectorFactory(
EventStreamComponent.NAME, HexDefaultViewSelectorFactory.NAME);
// replace the normal Text views with the ones that use syntax highlighting
manager.removeResponseViewFactory(
EventStreamComponent.NAME, SyntaxHighlightTextViewFactory.NAME);
// support large payloads on incoming and outgoing messages
manager.removeResponseViewFactory(
EventStreamComponent.NAME, EventStreamLargeEventDefaultViewSelectorFactory.NAME);
manager.removeResponseDefaultViewSelectorFactory(
EventStreamComponent.NAME, EventStreamLargeEventDefaultViewSelectorFactory.NAME);
}
/**
* The component returned by this factory contain the normal text view (without syntax
* highlighting).
*/
private static final class EventStreamComponentFactory implements HttpPanelComponentFactory {
public static final String NAME = "EventStreamComponentFactory";
@Override
public HttpPanelComponentInterface getNewComponent() {
return new EventStreamComponent();
}
@Override
public String getComponentName() {
return EventStreamComponent.NAME;
}
@Override
public String getName() {
return NAME;
}
}
private static final class EventStreamHexViewFactory implements HttpPanelViewFactory {
public static final String NAME = "EventStreamHexViewFactory";
@Override
public HttpPanelView getNewView() {
return new HttpPanelHexView(new ByteEventStreamPanelViewModel(), false);
}
@Override
public Object getOptions() {
return null;
}
@Override
public String getName() {
return NAME;
}
}
private static final class HexDefaultViewSelector implements HttpPanelDefaultViewSelector {
@Override
public String getName() {
return "HexDefaultViewSelector";
}
@Override
public boolean matchToDefaultView(Message aMessage) {
// use hex view only when previously selected
// if (aMessage instanceof WebSocketMessageDTO) {
// WebSocketMessageDTO msg = (WebSocketMessageDTO)aMessage;
//
// return (msg.opcode == WebSocketMessage.OPCODE_BINARY);
// }
return false;
}
@Override
public String getViewName() {
return HttpPanelHexView.NAME;
}
@Override
public int getOrder() {
return 20;
}
}
private static final class HexDefaultViewSelectorFactory
implements HttpPanelDefaultViewSelectorFactory {
public static final String NAME = "HexDefaultViewSelectorFactory";
private static HttpPanelDefaultViewSelector defaultViewSelector = null;
private HttpPanelDefaultViewSelector getDefaultViewSelector() {
if (defaultViewSelector == null) {
createViewSelector();
}
return defaultViewSelector;
}
private synchronized void createViewSelector() {
if (defaultViewSelector == null) {
defaultViewSelector = new HexDefaultViewSelector();
}
}
@Override
public HttpPanelDefaultViewSelector getNewDefaultViewSelector() {
return getDefaultViewSelector();
}
@Override
public Object getOptions() {
return null;
}
@Override
public String getName() {
return NAME;
}
}
private static final class SyntaxHighlightTextViewFactory implements HttpPanelViewFactory {
public static final String NAME = "SyntaxHighlightTextViewFactory";
@Override
public HttpPanelView getNewView() {
return new EventStreamSyntaxHighlightTextView(new StringEventStreamPanelViewModel());
}
@Override
public Object getOptions() {
return null;
}
@Override
public String getName() {
return NAME;
}
}
private static final class EventStreamLargePayloadViewFactory implements HttpPanelViewFactory {
public static final String NAME = "EventStreamLargePayloadViewFactory";
@Override
public HttpPanelView getNewView() {
return new EventStreamLargePayloadView(new EventStreamLargetPayloadViewModel());
}
@Override
public Object getOptions() {
return null;
}
@Override
public String getName() {
return NAME;
}
}
private static final class EventStreamLargeEventDefaultViewSelectorFactory
implements HttpPanelDefaultViewSelectorFactory {
public static final String NAME = "EventStreamLargeEventDefaultViewSelectorFactory";
private static HttpPanelDefaultViewSelector defaultViewSelector = null;
private HttpPanelDefaultViewSelector getDefaultViewSelector() {
if (defaultViewSelector == null) {
createViewSelector();
}
return defaultViewSelector;
}
private synchronized void createViewSelector() {
if (defaultViewSelector == null) {
defaultViewSelector = new EventStreamLargePayloadDefaultViewSelector();
}
}
@Override
public HttpPanelDefaultViewSelector getNewDefaultViewSelector() {
return getDefaultViewSelector();
}
@Override
public Object getOptions() {
return null;
}
@Override
public String getName() {
return NAME;
}
}
private static final class EventStreamLargePayloadDefaultViewSelector
implements HttpPanelDefaultViewSelector {
@Override
public String getName() {
return "EventStreamLargePayloadDefaultViewSelector";
}
@Override
public boolean matchToDefaultView(Message aMessage) {
return EventStreamLargeEventUtil.isLargeEvent(aMessage);
}
@Override
public String getViewName() {
return EventStreamLargePayloadView.NAME;
}
@Override
public int getOrder() {
// has to come before HexDefaultViewSelector
return 15;
}
}
}
| {
"content_hash": "2566b8ca5a83e437a1614aeadf96e57a",
"timestamp": "",
"source": "github",
"line_count": 543,
"max_line_length": 99,
"avg_line_length": 33.63351749539595,
"alnum_prop": 0.6649509938126266,
"repo_name": "zapbot/zap-extensions",
"id": "09012d59fb324bfed541e30632ea390bed42b3bc",
"size": "19001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addOns/sse/src/main/java/org/zaproxy/zap/extension/sse/ExtensionServerSentEvents.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "29979"
},
{
"name": "HTML",
"bytes": "6653830"
},
{
"name": "Haskell",
"bytes": "1533212"
},
{
"name": "Java",
"bytes": "10514059"
},
{
"name": "JavaScript",
"bytes": "160056"
},
{
"name": "Kotlin",
"bytes": "80437"
},
{
"name": "Python",
"bytes": "26411"
},
{
"name": "Ruby",
"bytes": "16551"
},
{
"name": "XSLT",
"bytes": "78761"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cats-in-zfc: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.0 / cats-in-zfc - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
cats-in-zfc
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-19 20:23:50 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-19 20:23:50 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/cats-in-zfc"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/CatsInZFC"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [
"keyword: set theory"
"keyword: ordinal numbers"
"keyword: cardinal numbers"
"keyword: category theory"
"keyword: functors"
"keyword: natural transformation"
"keyword: limit"
"keyword: colimit"
"category: Mathematics/Logic/Set theory"
"category: Mathematics/Category Theory"
"date: 2004-10-10"
]
authors: [ "Carlos Simpson <carlos@math.unice.fr> [http://math.unice.fr/~carlos/]" ]
bug-reports: "https://github.com/coq-contribs/cats-in-zfc/issues"
dev-repo: "git+https://github.com/coq-contribs/cats-in-zfc.git"
synopsis: "Category theory in ZFC"
description: """
In a ZFC-like environment augmented by reference to the
ambient type theory, we develop some basic set theory, ordinals, cardinals
and transfinite induction, and category theory including functors,
natural transformations, limits and colimits, functor categories,
and the theorem that functor_cat a b has (co)limits if b does."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/cats-in-zfc/archive/v8.6.0.tar.gz"
checksum: "md5=38c46a2ccf98a161903a1763c4cf90d3"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-cats-in-zfc.8.6.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.9.0).
The following dependencies couldn't be met:
- coq-cats-in-zfc -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-cats-in-zfc.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "7611b3c151d00875283c4e3176170f53",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 159,
"avg_line_length": 41.340782122905026,
"alnum_prop": 0.5528378378378378,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "dee587d94cfd5968666b8997df1af0a2e78f67c7",
"size": "7425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.9.0/cats-in-zfc/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/* IE 8 CSS Document */
| {
"content_hash": "55558732e89290fc7ba65006b19cacfa",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 23,
"avg_line_length": 12.5,
"alnum_prop": 0.56,
"repo_name": "thomasdintrone/bones-child",
"id": "6711fc4b422d97d0ecc0bb65c307d82d97c0fe58",
"size": "25",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dev-template/css/ie8.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "10260"
},
{
"name": "CSS",
"bytes": "168175"
},
{
"name": "HTML",
"bytes": "25278"
},
{
"name": "JavaScript",
"bytes": "409435"
},
{
"name": "PHP",
"bytes": "670500"
}
],
"symlink_target": ""
} |
using cc::PictureLayer;
namespace cc_blink {
static bool UseCachedPictureRaster() {
static bool use = !base::CommandLine::ForCurrentProcess()->HasSwitch(
cc::switches::kDisableCachedPictureRaster);
return use;
}
static blink::WebContentLayerClient::PaintingControlSetting
PaintingControlToWeb(
cc::ContentLayerClient::PaintingControlSetting painting_control) {
switch (painting_control) {
case cc::ContentLayerClient::PAINTING_BEHAVIOR_NORMAL:
return blink::WebContentLayerClient::PaintDefaultBehavior;
case cc::ContentLayerClient::PAINTING_BEHAVIOR_NORMAL_FOR_TEST:
return blink::WebContentLayerClient::PaintDefaultBehaviorForTest;
case cc::ContentLayerClient::DISPLAY_LIST_CONSTRUCTION_DISABLED:
return blink::WebContentLayerClient::DisplayListConstructionDisabled;
case cc::ContentLayerClient::DISPLAY_LIST_CACHING_DISABLED:
return blink::WebContentLayerClient::DisplayListCachingDisabled;
case cc::ContentLayerClient::DISPLAY_LIST_PAINTING_DISABLED:
return blink::WebContentLayerClient::DisplayListPaintingDisabled;
case cc::ContentLayerClient::SUBSEQUENCE_CACHING_DISABLED:
return blink::WebContentLayerClient::SubsequenceCachingDisabled;
}
NOTREACHED();
return blink::WebContentLayerClient::PaintDefaultBehavior;
}
WebContentLayerImpl::WebContentLayerImpl(blink::WebContentLayerClient* client)
: client_(client) {
layer_ = make_scoped_ptr(new WebLayerImpl(PictureLayer::Create(this)));
layer_->layer()->SetIsDrawable(true);
}
WebContentLayerImpl::~WebContentLayerImpl() {
static_cast<PictureLayer*>(layer_->layer())->ClearClient();
}
blink::WebLayer* WebContentLayerImpl::layer() {
return layer_.get();
}
gfx::Rect WebContentLayerImpl::PaintableRegion() {
return client_->paintableRegion();
}
scoped_refptr<cc::DisplayItemList>
WebContentLayerImpl::PaintContentsToDisplayList(
cc::ContentLayerClient::PaintingControlSetting painting_control) {
cc::DisplayItemListSettings settings;
settings.use_cached_picture = UseCachedPictureRaster();
scoped_refptr<cc::DisplayItemList> display_list =
cc::DisplayItemList::Create(PaintableRegion(), settings);
if (client_) {
WebDisplayItemListImpl list(display_list.get());
client_->paintContents(&list, PaintingControlToWeb(painting_control));
}
display_list->Finalize();
return display_list;
}
bool WebContentLayerImpl::FillsBoundsCompletely() const {
return false;
}
size_t WebContentLayerImpl::GetApproximateUnsharedMemoryUsage() const {
return client_->approximateUnsharedMemoryUsage();
}
} // namespace cc_blink
| {
"content_hash": "06f021a4e3e53d5db9f020f366dee354",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 78,
"avg_line_length": 35.2027027027027,
"alnum_prop": 0.7742802303262956,
"repo_name": "was4444/chromium.src",
"id": "b7a855cd28279f7e24beb1ca9f57d273dbe0c71f",
"size": "3398",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw15",
"path": "cc/blink/web_content_layer_impl.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
module LearnParsers where
import Control.Applicative
import Text.Trifecta
stop :: Parser a
stop = unexpected "stop"
one = char '1'
one' = one >> stop
oneTwo = char '1' >> char '2' <* eof
oneTwo' = oneTwo >> stop
oneTwoThree = string "123" <|> string "12" <|> string "1"
string' :: String -> Parser String
string' = sequence . fmap char
testParse :: Parser Char -> IO ()
testParse p = print $ parseString p mempty "123"
testParse' :: Parser String -> IO ()
testParse' p = print $ parseString p mempty "123"
pNL s = putStrLn ('\n' : s)
main = do
pNL "stop:"
testParse stop
pNL "one:"
testParse one
pNL "one':"
testParse one'
pNL "oneTwo:"
testParse oneTwo
pNL "oneTwo':"
testParse oneTwo'
pNL "oneTwoThree:"
testParse' oneTwoThree
pNL "Unit of Success:"
print $ parseString (integer <* eof) mempty "123"
| {
"content_hash": "4a09e7c35d4c0666b91309504b9dadf5",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 57,
"avg_line_length": 19.558139534883722,
"alnum_prop": 0.6575505350772889,
"repo_name": "taojang/haskell-programming-book-exercise",
"id": "3a581c4a5cbd606828215827ea3b79a801327769",
"size": "841",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ch24/LearnParsers.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "51043"
},
{
"name": "Nix",
"bytes": "164"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "aea48a297252cbb46d77cbb02c10b410",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "0483018b8a1a1cc85bc5822975e2959efc284b3a",
"size": "195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Bulbophyllum/Bulbophyllum aureum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. -->
<title>Canvas test: 2d.fillStyle.parse.hsla-clamp-2</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/html/canvas/resources/canvas-tests.js"></script>
<link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css">
<body class="show_output">
<h1>2d.fillStyle.parse.hsla-clamp-2</h1>
<p class="desc"></p>
<p class="notes">
<p class="output">Actual output:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="2d.fillStyle.parse.hsla-clamp-2.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
var t = async_test("");
_addTest(function(canvas, ctx) {
ctx.fillStyle = '#f00';
ctx.fillStyle = 'hsla(120, -200%, 49.9%, 1)';
ctx.fillRect(0, 0, 100, 50);
_assertPixel(canvas, 50,25, 127,127,127,255, "50,25", "127,127,127,255");
});
</script>
| {
"content_hash": "75173ecc126101109311ec813a9e7f09",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 142,
"avg_line_length": 34.70967741935484,
"alnum_prop": 0.6868029739776952,
"repo_name": "nwjs/chromium.src",
"id": "e83535ed6ff622824ac49aee672bdb5ce48c4978",
"size": "1076",
"binary": false,
"copies": "13",
"ref": "refs/heads/nw70",
"path": "third_party/blink/web_tests/external/wpt/html/canvas/element/fill-and-stroke-styles/2d.fillStyle.parse.hsla-clamp-2.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
require "rails_helper"
feature "admin visits admin dashboard" do
scenario "and updates fantasy player name" do
create_admin
fantasy_player = create(:fantasy_player)
sign_in_with("admin@example.com", "password")
visit_admin_to_edit "Fantasy Players"
fill_in "Name", with: "LA Seahawks"
click_on "Update Fantasy player"
expect(page).to have_css(".flash",
text: "FantasyPlayer was successfully updated.")
end
scenario "and updates sports league trade deadline" do
create_admin
fantasy_player = create(:sports_league)
sign_in_with("admin@example.com", "password")
visit_admin_to_edit "Sports Leagues"
fill_in "Trade deadline", with: "2016-11-22"
click_on "Update Sports league"
expect(page).to have_css(".flash",
text: "SportsLeague was successfully updated.")
end
scenario "and creates final ranking for fantasy player" do
create_admin
fantasy_player = create(:fantasy_player, name: "Seattle Seahawks")
sign_in_with("admin@example.com", "password")
visit admin_final_rankings_path
click_on "New final ranking"
select "Seattle Seahawks", from: "Fantasy player"
fill_in "Year", with: 2016
fill_in "Rank", with: 1
fill_in "Points", with: 8
fill_in "Winnings", with: 25
click_on "Create Final ranking"
expect(page).to have_css(".flash",
text: "FinalRanking was successfully created.")
end
scenario "and creates final ranking from fantasy player page", js: true do
create_admin
create(:fantasy_player, name: "Seattle Seahawks")
sign_in_with("admin@example.com", "password")
visit_admin_to_edit "Fantasy Players"
click_on "Add Final Ranking"
fill_in "Year", with: 2016
fill_in "Rank", with: 1
fill_in "Points", with: 8
fill_in "Winnings", with: 25
click_on "Update Fantasy player"
expect(page).to have_css(".flash",
text: "FantasyPlayer was successfully updated.")
end
scenario "and adds fantasy player to fantasy team" do
create_admin
create(:fantasy_player, name: "Seattle Seahawks")
create(:fantasy_team, name: "Brown")
sign_in_with("admin@example.com", "password")
visit admin_roster_positions_path
click_on "New roster position"
select "Seattle Seahawks", from: "Fantasy player"
select "Brown", from: "Fantasy team"
click_on "Create Roster position"
expect(page).to have_css(".flash",
text: "RosterPosition was successfully created.")
end
scenario "and creates a fantasy league" do
create_admin
sign_in_with("admin@example.com", "password")
visit admin_fantasy_leagues_path
click_on "New fantasy league"
fill_in "Year", with: 2016
fill_in "Division", with: "A"
click_on "Create Fantasy league"
expect(page).to have_css(".flash",
text: "FantasyLeague was successfully created.")
end
scenario "and updates a user to an admin" do
create_admin
user = create(:user)
sign_in_with("admin@example.com", "password")
visit "/admin/users/#{user.id}"
click_on "Edit"
check "Admin"
click_on "Update User"
expect(page).to have_css(".flash", text: "User was successfully updated.")
end
def create_admin
admin = create(:admin, email: "admin@example.com", password: "password")
end
def visit_admin_to_edit(model)
visit root_path
click_on "Admin"
click_on model
click_on "Edit"
end
end
| {
"content_hash": "d05ab88ddcf83c72514ead79e5444f18",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 78,
"avg_line_length": 29.85593220338983,
"alnum_prop": 0.6531365313653137,
"repo_name": "axelclark/the-338-challenge",
"id": "f1eb5fca059768e2f3528e3ebb1e96f15128d7ca",
"size": "3523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/features/admin_visits_admin_dashboard_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9234"
},
{
"name": "HTML",
"bytes": "19370"
},
{
"name": "JavaScript",
"bytes": "1015"
},
{
"name": "Ruby",
"bytes": "121741"
},
{
"name": "Shell",
"bytes": "518"
}
],
"symlink_target": ""
} |
declare function require(string: string): string; // TOASK: What does this?? why is this here
| {
"content_hash": "9ea05420bdfdf8c85f4663610950b519",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 93,
"avg_line_length": 94,
"alnum_prop": 0.7446808510638298,
"repo_name": "npAfterwork/bankerstrust",
"id": "9108efd1d3670ff62fa1ab9a920d30511c7ad3af",
"size": "94",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/declarations.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "108806"
},
{
"name": "HTML",
"bytes": "10776"
},
{
"name": "JavaScript",
"bytes": "3831"
},
{
"name": "TypeScript",
"bytes": "66372"
}
],
"symlink_target": ""
} |
pojo-bean-editor
================
| {
"content_hash": "bdd63d91a1e280b453739f14dbb51e69",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 16,
"avg_line_length": 17,
"alnum_prop": 0.4117647058823529,
"repo_name": "pavanmankala/pojo-bean-editor",
"id": "659fd0086456af88675b7d92a08df9712cfc768a",
"size": "34",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "229"
},
{
"name": "Java",
"bytes": "104108"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4f76530d439063c6fe61bb27650c4077",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "33ec6cc44e363468bf15fadffadccd46e28760d5",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Besleria/Besleria barbensis/ Syn. Besleria barbensis hirsuta/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\Form;
use Symfony\Component\Form\Exception\RuntimeException;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Exception\AlreadySubmittedException;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Exception\LogicException;
use Symfony\Component\Form\Exception\OutOfBoundsException;
use Symfony\Component\Form\Util\FormUtil;
use Symfony\Component\Form\Util\InheritDataAwareIterator;
use Symfony\Component\Form\Util\OrderedHashMap;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PropertyAccess\PropertyPath;
/**
* Form represents a form.
*
* To implement your own form fields, you need to have a thorough understanding
* of the data flow within a form. A form stores its data in three different
* representations:
*
* (1) the "model" format required by the form's object
* (2) the "normalized" format for internal processing
* (3) the "view" format used for display
*
* A date field, for example, may store a date as "Y-m-d" string (1) in the
* object. To facilitate processing in the field, this value is normalized
* to a DateTime object (2). In the HTML representation of your form, a
* localized string (3) is presented to and modified by the user.
*
* In most cases, format (1) and format (2) will be the same. For example,
* a checkbox field uses a Boolean value for both internal processing and
* storage in the object. In these cases you simply need to set a value
* transformer to convert between formats (2) and (3). You can do this by
* calling addViewTransformer().
*
* In some cases though it makes sense to make format (1) configurable. To
* demonstrate this, let's extend our above date field to store the value
* either as "Y-m-d" string or as timestamp. Internally we still want to
* use a DateTime object for processing. To convert the data from string/integer
* to DateTime you can set a normalization transformer by calling
* addNormTransformer(). The normalized data is then converted to the displayed
* data as described before.
*
* The conversions (1) -> (2) -> (3) use the transform methods of the transformers.
* The conversions (3) -> (2) -> (1) use the reverseTransform methods of the transformers.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class Form implements \IteratorAggregate, FormInterface
{
/**
* The form's configuration.
*
* @var FormConfigInterface
*/
private $config;
/**
* The parent of this form.
*
* @var FormInterface
*/
private $parent;
/**
* The children of this form.
*
* @var FormInterface[] A map of FormInterface instances
*/
private $children;
/**
* The errors of this form.
*
* @var FormError[] An array of FormError instances
*/
private $errors = array();
/**
* Whether this form was submitted.
*
* @var bool
*/
private $submitted = false;
/**
* The button that was used to submit the form.
*
* @var Button
*/
private $clickedButton;
/**
* The form data in model format.
*
* @var mixed
*/
private $modelData;
/**
* The form data in normalized format.
*
* @var mixed
*/
private $normData;
/**
* The form data in view format.
*
* @var mixed
*/
private $viewData;
/**
* The submitted values that don't belong to any children.
*
* @var array
*/
private $extraData = array();
/**
* Returns the transformation failure generated during submission, if any.
*
* @var TransformationFailedException|null
*/
private $transformationFailure;
/**
* Whether the form's data has been initialized.
*
* When the data is initialized with its default value, that default value
* is passed through the transformer chain in order to synchronize the
* model, normalized and view format for the first time. This is done
* lazily in order to save performance when {@link setData()} is called
* manually, making the initialization with the configured default value
* superfluous.
*
* @var bool
*/
private $defaultDataSet = false;
/**
* Whether setData() is currently being called.
*
* @var bool
*/
private $lockSetData = false;
/**
* Creates a new form based on the given configuration.
*
* @param FormConfigInterface $config The form configuration
*
* @throws LogicException if a data mapper is not provided for a compound form
*/
public function __construct(FormConfigInterface $config)
{
// Compound forms always need a data mapper, otherwise calls to
// `setData` and `add` will not lead to the correct population of
// the child forms.
if ($config->getCompound() && !$config->getDataMapper()) {
throw new LogicException('Compound forms need a data mapper');
}
// If the form inherits the data from its parent, it is not necessary
// to call setData() with the default data.
if ($config->getInheritData()) {
$this->defaultDataSet = true;
}
$this->config = $config;
$this->children = new OrderedHashMap();
}
public function __clone()
{
$this->children = clone $this->children;
foreach ($this->children as $key => $child) {
$this->children[$key] = clone $child;
}
}
/**
* {@inheritdoc}
*/
public function getConfig()
{
return $this->config;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->config->getName();
}
/**
* {@inheritdoc}
*/
public function getPropertyPath()
{
if (null !== $this->config->getPropertyPath()) {
return $this->config->getPropertyPath();
}
if (null === $this->getName() || '' === $this->getName()) {
return;
}
$parent = $this->parent;
while ($parent && $parent->getConfig()->getInheritData()) {
$parent = $parent->getParent();
}
if ($parent && null === $parent->getConfig()->getDataClass()) {
return new PropertyPath('['.$this->getName().']');
}
return new PropertyPath($this->getName());
}
/**
* {@inheritdoc}
*/
public function isRequired()
{
if (null === $this->parent || $this->parent->isRequired()) {
return $this->config->getRequired();
}
return false;
}
/**
* {@inheritdoc}
*/
public function isDisabled()
{
if (null === $this->parent || !$this->parent->isDisabled()) {
return $this->config->getDisabled();
}
return true;
}
/**
* {@inheritdoc}
*/
public function setParent(FormInterface $parent = null)
{
if ($this->submitted) {
throw new AlreadySubmittedException('You cannot set the parent of a submitted form');
}
if (null !== $parent && '' === $this->config->getName()) {
throw new LogicException('A form with an empty name cannot have a parent form.');
}
$this->parent = $parent;
return $this;
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return $this->parent;
}
/**
* {@inheritdoc}
*/
public function getRoot()
{
return $this->parent ? $this->parent->getRoot() : $this;
}
/**
* {@inheritdoc}
*/
public function isRoot()
{
return null === $this->parent;
}
/**
* {@inheritdoc}
*/
public function setData($modelData)
{
// If the form is submitted while disabled, it is set to submitted, but the data is not
// changed. In such cases (i.e. when the form is not initialized yet) don't
// abort this method.
if ($this->submitted && $this->defaultDataSet) {
throw new AlreadySubmittedException('You cannot change the data of a submitted form.');
}
// If the form inherits its parent's data, disallow data setting to
// prevent merge conflicts
if ($this->config->getInheritData()) {
throw new RuntimeException('You cannot change the data of a form inheriting its parent data.');
}
// Don't allow modifications of the configured data if the data is locked
if ($this->config->getDataLocked() && $modelData !== $this->config->getData()) {
return $this;
}
if (is_object($modelData) && !$this->config->getByReference()) {
$modelData = clone $modelData;
}
if ($this->lockSetData) {
throw new RuntimeException('A cycle was detected. Listeners to the PRE_SET_DATA event must not call setData(). You should call setData() on the FormEvent object instead.');
}
$this->lockSetData = true;
$dispatcher = $this->config->getEventDispatcher();
// Hook to change content of the data
if ($dispatcher->hasListeners(FormEvents::PRE_SET_DATA)) {
$event = new FormEvent($this, $modelData);
$dispatcher->dispatch(FormEvents::PRE_SET_DATA, $event);
$modelData = $event->getData();
}
// Treat data as strings unless a value transformer exists
if (!$this->config->getViewTransformers() && !$this->config->getModelTransformers() && is_scalar($modelData)) {
$modelData = (string) $modelData;
}
// Synchronize representations - must not change the content!
$normData = $this->modelToNorm($modelData);
$viewData = $this->normToView($normData);
// Validate if view data matches data class (unless empty)
if (!FormUtil::isEmpty($viewData)) {
$dataClass = $this->config->getDataClass();
if (null !== $dataClass && !$viewData instanceof $dataClass) {
$actualType = is_object($viewData)
? 'an instance of class '.get_class($viewData)
: 'a(n) '.gettype($viewData);
throw new LogicException(
'The form\'s view data is expected to be an instance of class '.
$dataClass.', but is '.$actualType.'. You can avoid this error '.
'by setting the "data_class" option to null or by adding a view '.
'transformer that transforms '.$actualType.' to an instance of '.
$dataClass.'.'
);
}
}
$this->modelData = $modelData;
$this->normData = $normData;
$this->viewData = $viewData;
$this->defaultDataSet = true;
$this->lockSetData = false;
// It is not necessary to invoke this method if the form doesn't have children,
// even if the form is compound.
if (count($this->children) > 0) {
// Update child forms from the data
$iterator = new InheritDataAwareIterator($this->children);
$iterator = new \RecursiveIteratorIterator($iterator);
$this->config->getDataMapper()->mapDataToForms($viewData, $iterator);
}
if ($dispatcher->hasListeners(FormEvents::POST_SET_DATA)) {
$event = new FormEvent($this, $modelData);
$dispatcher->dispatch(FormEvents::POST_SET_DATA, $event);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function getData()
{
if ($this->config->getInheritData()) {
if (!$this->parent) {
throw new RuntimeException('The form is configured to inherit its parent\'s data, but does not have a parent.');
}
return $this->parent->getData();
}
if (!$this->defaultDataSet) {
$this->setData($this->config->getData());
}
return $this->modelData;
}
/**
* {@inheritdoc}
*/
public function getNormData()
{
if ($this->config->getInheritData()) {
if (!$this->parent) {
throw new RuntimeException('The form is configured to inherit its parent\'s data, but does not have a parent.');
}
return $this->parent->getNormData();
}
if (!$this->defaultDataSet) {
$this->setData($this->config->getData());
}
return $this->normData;
}
/**
* {@inheritdoc}
*/
public function getViewData()
{
if ($this->config->getInheritData()) {
if (!$this->parent) {
throw new RuntimeException('The form is configured to inherit its parent\'s data, but does not have a parent.');
}
return $this->parent->getViewData();
}
if (!$this->defaultDataSet) {
$this->setData($this->config->getData());
}
return $this->viewData;
}
/**
* {@inheritdoc}
*/
public function getExtraData()
{
return $this->extraData;
}
/**
* {@inheritdoc}
*/
public function initialize()
{
if (null !== $this->parent) {
throw new RuntimeException('Only root forms should be initialized.');
}
// Guarantee that the *_SET_DATA events have been triggered once the
// form is initialized. This makes sure that dynamically added or
// removed fields are already visible after initialization.
if (!$this->defaultDataSet) {
$this->setData($this->config->getData());
}
return $this;
}
/**
* {@inheritdoc}
*/
public function handleRequest($request = null)
{
$this->config->getRequestHandler()->handleRequest($this, $request);
return $this;
}
/**
* {@inheritdoc}
*/
public function submit($submittedData, $clearMissing = true)
{
if ($submittedData instanceof Request) {
@trigger_error('Passing a Symfony\Component\HttpFoundation\Request object to the '.__CLASS__.'::bind and '.__METHOD__.' methods is deprecated since 2.3 and will be removed in 3.0. Use the '.__CLASS__.'::handleRequest method instead. If you want to test whether the form was submitted separately, you can use the '.__CLASS__.'::isSubmitted method.', E_USER_DEPRECATED);
}
if ($this->submitted) {
throw new AlreadySubmittedException('A form can only be submitted once');
}
// Initialize errors in the very beginning so that we don't lose any
// errors added during listeners
$this->errors = array();
// Obviously, a disabled form should not change its data upon submission.
if ($this->isDisabled()) {
$this->submitted = true;
return $this;
}
// The data must be initialized if it was not initialized yet.
// This is necessary to guarantee that the *_SET_DATA listeners
// are always invoked before submit() takes place.
if (!$this->defaultDataSet) {
$this->setData($this->config->getData());
}
// Treat false as NULL to support binding false to checkboxes.
// Don't convert NULL to a string here in order to determine later
// whether an empty value has been submitted or whether no value has
// been submitted at all. This is important for processing checkboxes
// and radio buttons with empty values.
if (false === $submittedData) {
$submittedData = null;
} elseif (is_scalar($submittedData)) {
$submittedData = (string) $submittedData;
}
$dispatcher = $this->config->getEventDispatcher();
$modelData = null;
$normData = null;
$viewData = null;
try {
// Hook to change content of the data submitted by the browser
if ($dispatcher->hasListeners(FormEvents::PRE_SUBMIT)) {
$event = new FormEvent($this, $submittedData);
$dispatcher->dispatch(FormEvents::PRE_SUBMIT, $event);
$submittedData = $event->getData();
}
// Check whether the form is compound.
// This check is preferable over checking the number of children,
// since forms without children may also be compound.
// (think of empty collection forms)
if ($this->config->getCompound()) {
if (null === $submittedData) {
$submittedData = array();
}
if (!is_array($submittedData)) {
throw new TransformationFailedException('Compound forms expect an array or NULL on submission.');
}
foreach ($this->children as $name => $child) {
$isSubmitted = array_key_exists($name, $submittedData);
if ($isSubmitted || $clearMissing) {
$child->submit($isSubmitted ? $submittedData[$name] : null, $clearMissing);
unset($submittedData[$name]);
if (null !== $this->clickedButton) {
continue;
}
if ($child instanceof ClickableInterface && $child->isClicked()) {
$this->clickedButton = $child;
continue;
}
if (method_exists($child, 'getClickedButton') && null !== $child->getClickedButton()) {
$this->clickedButton = $child->getClickedButton();
}
}
}
$this->extraData = $submittedData;
}
// Forms that inherit their parents' data also are not processed,
// because then it would be too difficult to merge the changes in
// the child and the parent form. Instead, the parent form also takes
// changes in the grandchildren (i.e. children of the form that inherits
// its parent's data) into account.
// (see InheritDataAwareIterator below)
if (!$this->config->getInheritData()) {
// If the form is compound, the default data in view format
// is reused. The data of the children is merged into this
// default data using the data mapper.
// If the form is not compound, the submitted data is also the data in view format.
$viewData = $this->config->getCompound() ? $this->viewData : $submittedData;
if (FormUtil::isEmpty($viewData)) {
$emptyData = $this->config->getEmptyData();
if ($emptyData instanceof \Closure) {
/* @var \Closure $emptyData */
$emptyData = $emptyData($this, $viewData);
}
$viewData = $emptyData;
}
// Merge form data from children into existing view data
// It is not necessary to invoke this method if the form has no children,
// even if it is compound.
if (count($this->children) > 0) {
// Use InheritDataAwareIterator to process children of
// descendants that inherit this form's data.
// These descendants will not be submitted normally (see the check
// for $this->config->getInheritData() above)
$childrenIterator = new InheritDataAwareIterator($this->children);
$childrenIterator = new \RecursiveIteratorIterator($childrenIterator);
$this->config->getDataMapper()->mapFormsToData($childrenIterator, $viewData);
}
// Normalize data to unified representation
$normData = $this->viewToNorm($viewData);
// Hook to change content of the data in the normalized
// representation
if ($dispatcher->hasListeners(FormEvents::SUBMIT)) {
$event = new FormEvent($this, $normData);
$dispatcher->dispatch(FormEvents::SUBMIT, $event);
$normData = $event->getData();
}
// Synchronize representations - must not change the content!
$modelData = $this->normToModel($normData);
$viewData = $this->normToView($normData);
}
} catch (TransformationFailedException $e) {
$this->transformationFailure = $e;
// If $viewData was not yet set, set it to $submittedData so that
// the erroneous data is accessible on the form.
// Forms that inherit data never set any data, because the getters
// forward to the parent form's getters anyway.
if (null === $viewData && !$this->config->getInheritData()) {
$viewData = $submittedData;
}
}
$this->submitted = true;
$this->modelData = $modelData;
$this->normData = $normData;
$this->viewData = $viewData;
if ($dispatcher->hasListeners(FormEvents::POST_SUBMIT)) {
$event = new FormEvent($this, $viewData);
$dispatcher->dispatch(FormEvents::POST_SUBMIT, $event);
}
return $this;
}
/**
* Alias of {@link submit()}.
*
* @deprecated since version 2.3, to be removed in 3.0.
* Use {@link submit()} instead.
*/
public function bind($submittedData)
{
// This method is deprecated for Request too, but the error is
// triggered in Form::submit() method.
if (!$submittedData instanceof Request) {
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the '.__CLASS__.'::submit method instead.', E_USER_DEPRECATED);
}
return $this->submit($submittedData);
}
/**
* {@inheritdoc}
*/
public function addError(FormError $error)
{
if (null === $error->getOrigin()) {
$error->setOrigin($this);
}
if ($this->parent && $this->config->getErrorBubbling()) {
$this->parent->addError($error);
} else {
$this->errors[] = $error;
}
return $this;
}
/**
* {@inheritdoc}
*/
public function isSubmitted()
{
return $this->submitted;
}
/**
* Alias of {@link isSubmitted()}.
*
* @deprecated since version 2.3, to be removed in 3.0.
* Use {@link isSubmitted()} instead.
*/
public function isBound()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the '.__CLASS__.'::isSubmitted method instead.', E_USER_DEPRECATED);
return $this->submitted;
}
/**
* {@inheritdoc}
*/
public function isSynchronized()
{
return null === $this->transformationFailure;
}
/**
* {@inheritdoc}
*/
public function getTransformationFailure()
{
return $this->transformationFailure;
}
/**
* {@inheritdoc}
*/
public function isEmpty()
{
foreach ($this->children as $child) {
if (!$child->isEmpty()) {
return false;
}
}
return FormUtil::isEmpty($this->modelData) ||
// arrays, countables
((is_array($this->modelData) || $this->modelData instanceof \Countable) && 0 === count($this->modelData)) ||
// traversables that are not countable
($this->modelData instanceof \Traversable && 0 === iterator_count($this->modelData));
}
/**
* {@inheritdoc}
*/
public function isValid()
{
if (!$this->submitted) {
return false;
}
if ($this->isDisabled()) {
return true;
}
return 0 === count($this->getErrors(true));
}
/**
* Returns the button that was used to submit the form.
*
* @return Button|null The clicked button or NULL if the form was not
* submitted
*/
public function getClickedButton()
{
if ($this->clickedButton) {
return $this->clickedButton;
}
if ($this->parent && method_exists($this->parent, 'getClickedButton')) {
return $this->parent->getClickedButton();
}
}
/**
* {@inheritdoc}
*/
public function getErrors($deep = false, $flatten = true)
{
$errors = $this->errors;
// Copy the errors of nested forms to the $errors array
if ($deep) {
foreach ($this as $child) {
/** @var FormInterface $child */
if ($child->isSubmitted() && $child->isValid()) {
continue;
}
$iterator = $child->getErrors(true, $flatten);
if (0 === count($iterator)) {
continue;
}
if ($flatten) {
foreach ($iterator as $error) {
$errors[] = $error;
}
} else {
$errors[] = $iterator;
}
}
}
return new FormErrorIterator($this, $errors);
}
/**
* Returns a string representation of all form errors (including children errors).
*
* This method should only be used to help debug a form.
*
* @param int $level The indentation level (used internally)
*
* @return string A string representation of all errors
*
* @deprecated since version 2.5, to be removed in 3.0.
* Use {@link getErrors()} instead and cast the result to a string.
*/
public function getErrorsAsString($level = 0)
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.5 and will be removed in 3.0. Use (string) Form::getErrors(true, false) instead.', E_USER_DEPRECATED);
return self::indent((string) $this->getErrors(true, false), $level);
}
/**
* {@inheritdoc}
*/
public function all()
{
return iterator_to_array($this->children);
}
/**
* {@inheritdoc}
*/
public function add($child, $type = null, array $options = array())
{
if ($this->submitted) {
throw new AlreadySubmittedException('You cannot add children to a submitted form');
}
if (!$this->config->getCompound()) {
throw new LogicException('You cannot add children to a simple form. Maybe you should set the option "compound" to true?');
}
// Obtain the view data
$viewData = null;
// If setData() is currently being called, there is no need to call
// mapDataToForms() here, as mapDataToForms() is called at the end
// of setData() anyway. Not doing this check leads to an endless
// recursion when initializing the form lazily and an event listener
// (such as ResizeFormListener) adds fields depending on the data:
//
// * setData() is called, the form is not initialized yet
// * add() is called by the listener (setData() is not complete, so
// the form is still not initialized)
// * getViewData() is called
// * setData() is called since the form is not initialized yet
// * ... endless recursion ...
//
// Also skip data mapping if setData() has not been called yet.
// setData() will be called upon form initialization and data mapping
// will take place by then.
if (!$this->lockSetData && $this->defaultDataSet && !$this->config->getInheritData()) {
$viewData = $this->getViewData();
}
if (!$child instanceof FormInterface) {
if (!is_string($child) && !is_int($child)) {
throw new UnexpectedTypeException($child, 'string, integer or Symfony\Component\Form\FormInterface');
}
if (null !== $type && !is_string($type) && !$type instanceof FormTypeInterface) {
throw new UnexpectedTypeException($type, 'string or Symfony\Component\Form\FormTypeInterface');
}
// Never initialize child forms automatically
$options['auto_initialize'] = false;
if (null === $type && null === $this->config->getDataClass()) {
$type = 'text';
}
if (null === $type) {
$child = $this->config->getFormFactory()->createForProperty($this->config->getDataClass(), $child, null, $options);
} else {
$child = $this->config->getFormFactory()->createNamed($child, $type, null, $options);
}
} elseif ($child->getConfig()->getAutoInitialize()) {
throw new RuntimeException(sprintf(
'Automatic initialization is only supported on root forms. You '.
'should set the "auto_initialize" option to false on the field "%s".',
$child->getName()
));
}
$this->children[$child->getName()] = $child;
$child->setParent($this);
if (!$this->lockSetData && $this->defaultDataSet && !$this->config->getInheritData()) {
$iterator = new InheritDataAwareIterator(new \ArrayIterator(array($child->getName() => $child)));
$iterator = new \RecursiveIteratorIterator($iterator);
$this->config->getDataMapper()->mapDataToForms($viewData, $iterator);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function remove($name)
{
if ($this->submitted) {
throw new AlreadySubmittedException('You cannot remove children from a submitted form');
}
if (isset($this->children[$name])) {
if (!$this->children[$name]->isSubmitted()) {
$this->children[$name]->setParent(null);
}
unset($this->children[$name]);
}
return $this;
}
/**
* {@inheritdoc}
*/
public function has($name)
{
return isset($this->children[$name]);
}
/**
* {@inheritdoc}
*/
public function get($name)
{
if (isset($this->children[$name])) {
return $this->children[$name];
}
throw new OutOfBoundsException(sprintf('Child "%s" does not exist.', $name));
}
/**
* Returns whether a child with the given name exists (implements the \ArrayAccess interface).
*
* @param string $name The name of the child
*
* @return bool
*/
public function offsetExists($name)
{
return $this->has($name);
}
/**
* Returns the child with the given name (implements the \ArrayAccess interface).
*
* @param string $name The name of the child
*
* @return FormInterface The child form
*
* @throws \OutOfBoundsException If the named child does not exist.
*/
public function offsetGet($name)
{
return $this->get($name);
}
/**
* Adds a child to the form (implements the \ArrayAccess interface).
*
* @param string $name Ignored. The name of the child is used
* @param FormInterface $child The child to be added
*
* @throws AlreadySubmittedException If the form has already been submitted.
* @throws LogicException When trying to add a child to a non-compound form.
*
* @see self::add()
*/
public function offsetSet($name, $child)
{
$this->add($child);
}
/**
* Removes the child with the given name from the form (implements the \ArrayAccess interface).
*
* @param string $name The name of the child to remove
*
* @throws AlreadySubmittedException If the form has already been submitted.
*/
public function offsetUnset($name)
{
$this->remove($name);
}
/**
* Returns the iterator for this group.
*
* @return \Traversable|FormInterface[]
*/
public function getIterator()
{
return $this->children;
}
/**
* Returns the number of form children (implements the \Countable interface).
*
* @return int The number of embedded form children
*/
public function count()
{
return count($this->children);
}
/**
* {@inheritdoc}
*/
public function createView(FormView $parent = null)
{
if (null === $parent && $this->parent) {
$parent = $this->parent->createView();
}
$type = $this->config->getType();
$options = $this->config->getOptions();
// The methods createView(), buildView() and finishView() are called
// explicitly here in order to be able to override either of them
// in a custom resolved form type.
$view = $type->createView($this, $parent);
$type->buildView($view, $this, $options);
foreach ($this->children as $name => $child) {
$view->children[$name] = $child->createView($view);
}
$type->finishView($view, $this, $options);
return $view;
}
/**
* Normalizes the value if a normalization transformer is set.
*
* @param mixed $value The value to transform
*
* @return mixed
*
* @throws TransformationFailedException If the value cannot be transformed to "normalized" format
*/
private function modelToNorm($value)
{
try {
foreach ($this->config->getModelTransformers() as $transformer) {
$value = $transformer->transform($value);
}
} catch (TransformationFailedException $exception) {
throw new TransformationFailedException(
'Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
}
return $value;
}
/**
* Reverse transforms a value if a normalization transformer is set.
*
* @param string $value The value to reverse transform
*
* @return mixed
*
* @throws TransformationFailedException If the value cannot be transformed to "model" format
*/
private function normToModel($value)
{
try {
$transformers = $this->config->getModelTransformers();
for ($i = count($transformers) - 1; $i >= 0; --$i) {
$value = $transformers[$i]->reverseTransform($value);
}
} catch (TransformationFailedException $exception) {
throw new TransformationFailedException(
'Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
}
return $value;
}
/**
* Transforms the value if a value transformer is set.
*
* @param mixed $value The value to transform
*
* @return mixed
*
* @throws TransformationFailedException If the value cannot be transformed to "view" format
*/
private function normToView($value)
{
// Scalar values should be converted to strings to
// facilitate differentiation between empty ("") and zero (0).
// Only do this for simple forms, as the resulting value in
// compound forms is passed to the data mapper and thus should
// not be converted to a string before.
if (!$this->config->getViewTransformers() && !$this->config->getCompound()) {
return null === $value || is_scalar($value) ? (string) $value : $value;
}
try {
foreach ($this->config->getViewTransformers() as $transformer) {
$value = $transformer->transform($value);
}
} catch (TransformationFailedException $exception) {
throw new TransformationFailedException(
'Unable to transform value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
}
return $value;
}
/**
* Reverse transforms a value if a value transformer is set.
*
* @param string $value The value to reverse transform
*
* @return mixed
*
* @throws TransformationFailedException If the value cannot be transformed to "normalized" format
*/
private function viewToNorm($value)
{
$transformers = $this->config->getViewTransformers();
if (!$transformers) {
return '' === $value ? null : $value;
}
try {
for ($i = count($transformers) - 1; $i >= 0; --$i) {
$value = $transformers[$i]->reverseTransform($value);
}
} catch (TransformationFailedException $exception) {
throw new TransformationFailedException(
'Unable to reverse value for property path "'.$this->getPropertyPath().'": '.$exception->getMessage(),
$exception->getCode(),
$exception
);
}
return $value;
}
/**
* Utility function for indenting multi-line strings.
*
* @param string $string The string
* @param int $level The number of spaces to use for indentation
*
* @return string The indented string
*/
private static function indent($string, $level)
{
$indentation = str_repeat(' ', $level);
return rtrim($indentation.str_replace("\n", "\n".$indentation, $string), ' ');
}
}
| {
"content_hash": "3a18c7ecf014256c99e7205c2b892fd1",
"timestamp": "",
"source": "github",
"line_count": 1198,
"max_line_length": 380,
"avg_line_length": 32.040066777963276,
"alnum_prop": 0.5601552730304293,
"repo_name": "elqueace/TS",
"id": "54b9b39ebd02cff6cd6d88e7f934c2e920995354",
"size": "38613",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/symfony/symfony/src/Symfony/Component/Form/Form.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "517"
},
{
"name": "CSS",
"bytes": "225668"
},
{
"name": "HTML",
"bytes": "55150"
},
{
"name": "JavaScript",
"bytes": "42516"
},
{
"name": "PHP",
"bytes": "64053"
},
{
"name": "Ruby",
"bytes": "1051"
},
{
"name": "Shell",
"bytes": "2477"
}
],
"symlink_target": ""
} |
// Provides class sap.ui.model.odata.ODataTreeBindingFlat
sap.ui.define(['jquery.sap.global', 'sap/ui/model/Filter', 'sap/ui/model/TreeBinding', 'sap/ui/model/odata/v2/ODataTreeBinding', 'sap/ui/model/ChangeReason', 'sap/ui/model/TreeBindingUtils'],
function(jQuery, Filter, TreeBinding, ODataTreeBinding, ChangeReason, TreeBindingUtils) {
"use strict";
/**
* Adapter for TreeBindings to add the ListBinding functionality and use the
* tree structure in list based controls.
*
* @alias sap.ui.model.odata.ODataTreeBindingFlat
* @function
* @public
*/
var ODataTreeBindingFlat = function() {
// ensure only TreeBindings are enhanced which have not been enhanced yet
if (!(this instanceof TreeBinding) || this._bIsAdapted) {
return;
}
// apply the methods of the adapters prototype to the TreeBinding instance
for (var fn in ODataTreeBindingFlat.prototype) {
if (ODataTreeBindingFlat.prototype.hasOwnProperty(fn)) {
this[fn] = ODataTreeBindingFlat.prototype[fn];
}
}
// make sure we have a parameter object
this.mParameters = this.mParameters || {};
// keep track of the page-size for expand request
this._iPageSize = 0;
// flat data structure to store the tree nodes depth-first ordered
this._aNodes = this._aNodes || [];
// the node cache for the last requested nodes (via getContexts)
this._aNodeCache = [];
// the tree states
this._aCollapsed = this._aCollapsed || [];
this._aExpanded = this._aExpanded || [];
this._aRemoved = [];
this._aAdded = [];
this._aNodeChanges = [];
this._aAllChangedNodes = [];
// a map of all subtree handles, which are removed from the tree (and may be re-inserted)
this._mSubtreeHandles = {};
// lowest server-index level, will be kept correct when loading new entries
this._iLowestServerLevel = null;
// selection state
this._aExpandedAfterSelectAll = this._aExpandedAfterSelectAll || [];
this._mSelected = this._mSelected || {};
this._mDeselected = this._mDeselected || {};
this._bSelectAll = false;
// the delta variable for calculating the correct binding-length (used e.g. for sizing the scrollbar)
this._iLengthDelta = 0;
//default value for collapse recursive
if (this.mParameters.collapseRecursive === undefined) {
this.bCollapseRecursive = true;
} else {
this.bCollapseRecursive = !!this.mParameters.collapseRecursive;
}
this._bIsAdapted = true;
this._bReadOnly = true;
this._aPendingRequests = [];
this._aPendingChildrenRequests = [];
};
/**
* Sets the number of expanded levels.
*/
ODataTreeBindingFlat.prototype.setNumberOfExpandedLevels = function(iLevels) {
this.resetData();
ODataTreeBinding.prototype.setNumberOfExpandedLevels.apply(this, arguments);
};
/**
* Retrieves the requested page.
* API used by the controls.
*/
ODataTreeBindingFlat.prototype.getContexts = function (iStartIndex, iLength, iThreshold, bReturnNodes) {
if (this.isInitial()) {
return [];
}
// make sure the input parameters are not undefined
iStartIndex = iStartIndex || 0;
iLength = iLength || this.oModel.iSizeLimit;
iThreshold = iThreshold || 0;
this._iPageSize = iLength;
this._iThreshold = iThreshold;
// shortcut for initial load
if (this._aNodes.length == 0 && !this.isLengthFinal()) {
this._loadData(iStartIndex, iLength, iThreshold);
}
// cut out the requested section from the tree
var aResultContexts = [];
var aNodes = this._retrieveNodeSection(iStartIndex, iLength);
// clear node cache
this._aNodeCache = [];
// calculate $skip and $top values
var iSkip;
var iTop = 0;
var iLastServerIndex = 0;
// potentially missing entries for each parent deeper than the # of expanded levels
var mGaps = {};
for (var i = 0; i < aNodes.length; i++) {
var oNode = aNodes[i];
// cache node for more efficient access on the currently visible nodes in the TreeTable
// only cache nodes which are real contexts
this._aNodeCache[iStartIndex + i] = oNode && oNode.context ? oNode : undefined;
aResultContexts.push(oNode.context);
if (!oNode.context) {
if (oNode.serverIndex != undefined) { // 0 is a valid server-index!
// construct the $skip to $top range for server indexed nodes
if (iSkip == undefined) {
iSkip = oNode.serverIndex;
}
iLastServerIndex = oNode.serverIndex;
} else if (oNode.positionInParent != undefined) { //0 is a valid index here too
// nodes, which don't have a context but a positionInParent property, are manually expanded missing nodes
var oParent = oNode.parent;
mGaps[oParent.key] = mGaps[oParent.key] || [];
mGaps[oParent.key].push(oNode);
}
}
}
// $top needs to be at minimum 1
iTop = 1 + Math.max(iLastServerIndex - (iSkip || 0), 0);
//if something is missing on the server indexed nodes -> request it
if (iSkip != undefined && iTop) {
this._loadData(iSkip, iTop, iThreshold);
}
//check if we are missing some manually expanded nodes
for (var sMissingKey in mGaps) {
var oRequestParameters = this._calculateRequestParameters(mGaps[sMissingKey]);
this._loadChildren(mGaps[sMissingKey][0].parent, oRequestParameters.skip, oRequestParameters.top);
}
// either return nodes or contexts
if (bReturnNodes) {
return aNodes;
} else {
return aResultContexts;
}
};
ODataTreeBindingFlat.prototype._calculateRequestParameters = function (aMissing) {
var oParent = aMissing[0].parent;
var iMissingSkip = aMissing[0].positionInParent;
var iMissingLength = Math.min(iMissingSkip + Math.max(this._iThreshold, aMissing.length), oParent.children.length);
for (var i = iMissingSkip; i < iMissingLength; i++) {
var oChild = oParent.children[i];
if (oChild) {
break;
}
}
return {
skip: iMissingSkip,
top: i - iMissingSkip
};
};
/**
* Cuts out a piece from the tree.
* @private
*/
ODataTreeBindingFlat.prototype._retrieveNodeSection = function (iStartIndex, iLength) {
return this._bReadOnly ? this._indexRetrieveNodeSection(iStartIndex, iLength) : this._mapRetrieveNodeSection(iStartIndex, iLength);
};
ODataTreeBindingFlat.prototype._mapRetrieveNodeSection = function (iStartIndex, iLength) {
var iNodeCounter = -1;
var aNodes = [];
this._map(function (oNode, oRecursionBreaker, sIndexType, iIndex, oParent) {
iNodeCounter++;
if (iNodeCounter >= iStartIndex) {
// if we have a missing node and it is a server-indexed node -> introduce a gap object
if (!oNode) {
if (sIndexType == "serverIndex") {
oNode = {
serverIndex: iIndex
};
} else if (sIndexType == "positionInParent") {
oNode = {
positionInParent: iIndex,
parent: oParent
};
}
}
aNodes.push(oNode);
}
if (aNodes.length >= iLength) {
oRecursionBreaker.broken = true;
}
});
return aNodes;
};
ODataTreeBindingFlat.prototype._indexRetrieveNodeSection = function (iStartIndex, iLength) {
var i, aNodes = [], oNodeInfo, oNode;
for (i = iStartIndex ; i < iStartIndex + iLength ; i++) {
oNodeInfo = this.getNodeInfoByRowIndex(i);
if (oNodeInfo.index !== undefined && oNodeInfo.index < this._aNodes.length) {
oNode = this._aNodes[oNodeInfo.index];
if (!oNode) {
oNode = {
serverIndex: oNodeInfo.index
};
}
} else if (oNodeInfo.parent) {
oNode = oNodeInfo.parent.children[oNodeInfo.childIndex];
if (!oNode) {
oNode = {
parent: oNodeInfo.parent,
positionInParent: oNodeInfo.childIndex
};
}
}
if (oNode) {
aNodes.push(oNode);
oNode = null;
}
}
return aNodes;
};
/**
* Retrieves the requested section of the nodes.
* Also requests the data if necessary.
* @protected
*/
ODataTreeBindingFlat.prototype.getNodes = function (iStartIndex, iLength, iThreshold) {
var vNodes = this.getContexts(iStartIndex, iLength, iThreshold, true);
return vNodes;
};
/**
* Applies the given function to all tree nodes
* @param {function} fnMap the map function which will be called for all nodes.
* @private
*/
ODataTreeBindingFlat.prototype._map = function (fnMap) {
var oRecursionBreaker = {broken: false};
/**
* Helper function to iterate all added subtrees of a node.
*/
var fnCheckNodeForAddedSubtrees = function (oNode) {
// if there are subnodes added to the current node -> traverse them first (added nodes are at the top, before any children)
if (oNode.addedSubtrees.length > 0 && !oNode.nodeState.collapsed) {
// an added subtree can be either a deep or a flat tree (depending on the addContexts) call
for (var j = 0; j < oNode.addedSubtrees.length; j++) {
var oSubtreeHandle = oNode.addedSubtrees[j];
fnTraverseAddedSubtree(oNode, oSubtreeHandle);
if (oRecursionBreaker.broken) {
return;
}
}
}
};
/**
* Traverses a re-inserted or newly added subtree.
* This can be a combination of flat and deep trees.
*
* Decides if the traversal has to branche over to a flat or a deep part of the tree.
*
* @param {object} oNode the parent node
* @param {object} the subtree handle, inside there is either a deep or a flat tree stored
*/
var fnTraverseAddedSubtree = function (oNode, oSubtreeHandle) {
var oSubtree = oSubtreeHandle._getSubtree();
if (oSubtreeHandle) {
// subtree is flat
if (Array.isArray(oSubtree)) {
if (oSubtreeHandle._oSubtreeRoot) {
// jump to a certain position in the flat structure and map the nodes
fnTraverseFlatSubtree(oSubtree, oSubtreeHandle._oSubtreeRoot.serverIndex, oSubtreeHandle._oSubtreeRoot, oSubtreeHandle._oSubtreeRoot.originalLevel || 0, oNode.level + 1);
} else {
// newly added nodes
fnTraverseFlatSubtree(oSubtree, null, null, 0, oNode.level + 1);
}
} else {
// subtree is deep
oSubtreeHandle._oSubtreeRoot.level = oNode.level + 1;
fnTraverseDeepSubtree(oSubtreeHandle._oSubtreeRoot, false, oSubtreeHandle._oNewParentNode, -1, oSubtreeHandle._oSubtreeRoot);
}
}
};
/**
* Recursive Tree Traversal
* @param {object} oNode the current node
* @param {boolean} bIgnore a flag to indicate if the node should be mapped
* @param {object} oParent the parent node of oNode
* @param {int} iPositionInParent the position of oNode in the children-array of oParent
*/
var fnTraverseDeepSubtree = function (oNode, bIgnore, oParent, iPositionInParent, oIgnoreRemoveForNode) {
// ignore node if it was already mapped or is removed (except if it was reinserted, denoted by oIgnoreRemoveForNode)
if (!bIgnore) {
if (!oNode.nodeState.removed || oIgnoreRemoveForNode == oNode) {
fnMap(oNode, oRecursionBreaker, "positionInParent", iPositionInParent, oParent);
if (oRecursionBreaker.broken) {
return;
}
}
}
fnCheckNodeForAddedSubtrees(oNode);
if (oRecursionBreaker.broken) {
return;
}
// if the node also has children AND is expanded, dig deeper
if (oNode && oNode.children && oNode.nodeState.expanded) {
for (var i = 0; i < oNode.children.length; i++) {
var oChildNode = oNode.children[i];
// Make sure that the level of all child nodes are adapted to the parent level,
// this is necessary if the parent node was placed in a different leveled subtree.
// Ignore removed nodes, which are not re-inserted.
// Re-inserted deep nodes will be regarded in fnTraverseAddedSubtree.
if (oChildNode && !oChildNode.nodeState.removed && !oChildNode.nodeState.reinserted) {
oChildNode.level = oNode.level + 1;
}
// only dive deeper if we have a gap (entry which has to be loaded) or a defined node is NOT removed
if (oChildNode && !oChildNode.nodeState.removed) {
fnTraverseDeepSubtree(oChildNode, false, oNode, i, oIgnoreRemoveForNode);
} else if (!oChildNode) {
fnMap(oChildNode, oRecursionBreaker, "positionInParent", i, oNode);
}
if (oRecursionBreaker.broken) {
return;
}
}
}
};
/**
* Traverses a flat portion of the tree (or rather the given array).
*/
var fnTraverseFlatSubtree = function (aFlatTree, iServerIndexOffset, oIgnoreRemoveForNode, iSubtreeBaseLevel, iNewParentBaseLevel) {
//count the nodes until we find the correct index
for (var i = 0; i < aFlatTree.length; i++) {
var oNode = aFlatTree[i];
// If the node is removed -> ignore it
// BEWARE:
// If a removed range is reinserted again, we will deliver it instead of jumping over it.
// This is denoted by the "oIgnoreRemoveForNode", this is a node which will be served but only if it was traversed by fnTraverseAddedSubtree
if (oNode && oNode.nodeState && oNode.nodeState.removed && oNode != oIgnoreRemoveForNode) {
// only jump over the magnitude range if the node was not initially collapsed/server-expanded
if (!oNode.initiallyCollapsed) {
i += oNode.magnitude;
}
continue;
}
// calculate level shift if necessary (added subtrees are differently indented than before removal)
if (oNode && iSubtreeBaseLevel >= 0 && iNewParentBaseLevel >= 0) {
oNode.level = oNode.originalLevel || 0;
var iLevelDifNormalized = (oNode.level - iSubtreeBaseLevel) || 0;
oNode.level = iNewParentBaseLevel + iLevelDifNormalized || 0;
}
if (iServerIndexOffset === null) {
fnMap(oNode, oRecursionBreaker, "newNode");
} else {
// call map for the node itself, before traversing to any children/siblings
// the server-index position is used to calculate the $skip/$top values for loading the missing entries
fnMap(oNode, oRecursionBreaker, "serverIndex", iServerIndexOffset + i);
}
if (oRecursionBreaker.broken) {
return;
}
// if we have a node, lets see if we have to dig deeper or jump over some entries
if (oNode && oNode.nodeState) {
// jump over collapsed nodes by the enclosing magnitude
if (!oNode.initiallyCollapsed && oNode.nodeState.collapsed) {
i += oNode.magnitude;
} else {
// look into expanded nodes deeper than the initial expand level
if (oNode.initiallyCollapsed && oNode.nodeState.expanded) {
// the node itself will be ignored, since its fnMap was already called
fnTraverseDeepSubtree(oNode, true);
if (oRecursionBreaker.broken) {
return;
}
} else if (!oNode.initiallyCollapsed && oNode.nodeState.expanded) {
// before going to the next flat node (children|sibling), we look at the added subtrees in between
// this is only necessary for expanded server-indexed nodes
fnCheckNodeForAddedSubtrees(oNode);
}
}
}
// break recursion after fnMap or traversal function calls
if (oRecursionBreaker.broken) {
return;
}
}
};
//kickstart the traversal from the original flat nodes array (no server-index offset -> 0)
fnTraverseFlatSubtree(this._aNodes, 0, null);
};
/**
* Loads the server-index nodes within the range [iSkip, iSkip + iTop + iThreshold) and merges the nodes into
* the inner structure.
*
* @param {int} iSkip The start index of the loading
* @param {int} iTop The number of nodes to be loaded
* @param {int} iThreshold The size of the buffer
*/
ODataTreeBindingFlat.prototype._loadData = function (iSkip, iTop, iThreshold) {
var that = this;
this.fireDataRequested();
this._requestServerIndexNodes(iSkip, iTop, iThreshold).then(function(oResponseData) {
that._addServerIndexNodes(oResponseData.oData, oResponseData.iSkip);
that._fireChange({reason: ChangeReason.Change});
that.fireDataReceived({data: oResponseData.oData});
}, function(oError) {
var bAborted = oError.statusCode === 0;
if (!bAborted) {
// reset data and trigger update
that._aNodes = [];
that._bLengthFinal = true;
that._fireChange({reason: ChangeReason.Change});
}
that.fireDataReceived();
});
};
/**
* Reloads the server-index nodes within the range [iSkip, iSkip + iTop) and merges them into the inner structure.
*
* @param {int} iSkip The start index of the loading
* @param {int} iTop The number of nodes to be loaded
* @param {boolean} bInlineCount Whether the inline count for all pages is requested
* @return {Promise} The promise resolves if the reload finishes successfully, otherwise it's rejected. The promise
* resolves with an object which has the calculated iSkip, iTop and the loaded content under
* property oData. It rejects with the error object which is returned from the server.
*/
ODataTreeBindingFlat.prototype._restoreServerIndexNodes = function (iSkip, iTop, bInlineCount) {
var that = this;
return this._requestServerIndexNodes(iSkip, iTop, 0, bInlineCount).then(function(oResponseData) {
that._addServerIndexNodes(oResponseData.oData, oResponseData.iSkip);
return oResponseData;
});
};
/**
* Merges the nodes in parameter oData into the inner structure
*
* @param {object} oData The content which contains the nodes from the backend
* @param {int} iSkip The start index for the merging into inner structure
*/
ODataTreeBindingFlat.prototype._addServerIndexNodes = function (oData, iSkip) {
var oEntry, sKey, iIndex, i,
// the function is used to test whether one of its ascendant is expanded after the selectAll
fnTest = function(oNode, index) {
if (!oNode.isDeepOne && !oNode.initiallyCollapsed && oNode.serverIndex < iIndex && oNode.serverIndex + oNode.magnitude >= iIndex) {
return true;
}
};
// $inlinecount is in oData.__count, the $count is just oData
if (!this._bLengthFinal) {
var iCount = oData.__count ? parseInt(oData.__count, 10) : 0;
this._aNodes[iCount - 1] = undefined;
this._bLengthFinal = true;
}
//merge data into flat array structure
if (oData.results && oData.results.length > 0) {
for (i = 0; i < oData.results.length; i++) {
oEntry = oData.results[i];
sKey = this.oModel.getKey(oEntry);
iIndex = iSkip + i;
var iMagnitude = oEntry[this.oTreeProperties["hierarchy-node-descendant-count-for"]];
// check the magnitude attribute whether it's greater or equal than 0
if (iMagnitude < 0) {
iMagnitude = 0;
jQuery.sap.log.error("The entry data with key '" + sKey + "' under binding path '" + this.getPath() + "' has a negative 'hierarchy-node-descendant-count-for' which isn't allowed.");
}
var oNode = this._aNodes[iIndex] = this._aNodes[iIndex] || {
key: sKey,
context: this.oModel.getContext("/" + sKey),
magnitude: iMagnitude,
level: oEntry[this.oTreeProperties["hierarchy-level-for"]],
originalLevel: oEntry[this.oTreeProperties["hierarchy-level-for"]],
initiallyCollapsed: oEntry[this.oTreeProperties["hierarchy-drill-state-for"]] === "collapsed",
nodeState: {
isLeaf: oEntry[this.oTreeProperties["hierarchy-drill-state-for"]] === "leaf",
expanded: oEntry[this.oTreeProperties["hierarchy-drill-state-for"]] === "expanded",
collapsed: oEntry[this.oTreeProperties["hierarchy-drill-state-for"]] === "collapsed",
selected: this._mSelected[sKey] ? this._mSelected[sKey].nodeState.selected : false
},
children: [],
// an array containing all added subtrees, may be new context nodes or nodes which were removed previously
addedSubtrees: [],
serverIndex: iIndex,
// a server indexed node is not attributed with a parent, in contrast to the manually expanded nodes
parent: null,
isDeepOne: false
};
// track the lowest server-index level --> used to find out if a node is on the top level
if (this._iLowestServerLevel === null) {
this._iLowestServerLevel = oNode.level;
} else {
this._iLowestServerLevel = Math.min(this._iLowestServerLevel, oNode.level);
}
// slection update if we are in select-all mode
if (this._bSelectAll) {
if (!this._aExpandedAfterSelectAll.some(fnTest)) {
this.setNodeSelection(oNode, true);
}
}
}
}
};
/**
* Loads the server-index nodes based on the given range and the initial expand level.
*
* @param {int} iSkip The start index of the loading
* @param {int} iTop The number of nodes to be loaded
* @param {int} iThreshold The size of the buffer
* @param {boolean} bInlineCount Whether the inline count for all pages is requested
* @return {Promise} The promise resolves if the reload finishes successfully, otherwise it's rejected. The promise
* resolves with an object which has the calculated iSkip, iTop and the loaded content under
* property oData. It rejects with the error object which is returned from the server.
*/
ODataTreeBindingFlat.prototype._requestServerIndexNodes = function (iSkip, iTop, iThreshold, bInlineCount) {
return new Promise(function(resolve, reject) {
var oRequest = {
iSkip: iSkip,
iTop: iTop + (iThreshold || 0), // Top also contains threshold if applicable
iThreshold: iThreshold
// oRequestHandle: <will be set later>
};
// Order pending requests by index
this._aPendingRequests.sort(function(a, b) {
return a.iSkip - b.iSkip;
});
// Check pending requests:
// - adjust new request if pending requests already cover parts of it (delta determination)
// - ignore(/abort) new request if pending requests already cover it in full
// - cancel pending requests if the new request covers them in full plus additional data.
// handles will be aborted on filter/sort calls.
for (var i = 0; i < this._aPendingRequests.length; i++) {
if (TreeBindingUtils._determineRequestDelta(oRequest, this._aPendingRequests[i]) === false) {
return; // ignore this request
}
}
// Convenience
iSkip = oRequest.iSkip;
iTop = oRequest.iTop;
function _handleSuccess (oData) {
// Remove request from array
var idx = this._aPendingRequests.indexOf(oRequest);
this._aPendingRequests.splice(idx, 1);
resolve({
oData: oData,
iSkip: iSkip,
iTop: iTop
});
}
function _handleError (oError) {
// Remove request from array
var idx = this._aPendingRequests.indexOf(oRequest);
this._aPendingRequests.splice(idx, 1);
reject(oError);
}
var aUrlParameters = ["$skip=" + iSkip, "$top=" + iTop];
// request inlinecount only once
if (!this._bLengthFinal || bInlineCount) {
aUrlParameters.push("$inlinecount=allpages");
}
// add custom parameters (including $selects)
if (this.sCustomParams) {
aUrlParameters.push(this.sCustomParams);
}
// construct multi-filter for level filter and application filters
var oLevelFilter = new Filter(this.oTreeProperties["hierarchy-level-for"], "LE", this.getNumberOfExpandedLevels());
var aFilters = [oLevelFilter];
if (this.aApplicationFilters) {
aFilters = aFilters.concat(this.aApplicationFilters);
}
// TODO: Add additional filters to the read call, as soon as back-end implementations support it
// Something like this: aFilters = [new sap.ui.model.Filter([hierarchyFilters].concat(this.aFilters))];
oRequest.oRequestHandle = this.oModel.read(this.getPath(), {
context: this.oContext,
urlParameters: aUrlParameters,
filters: [new Filter({
filters: aFilters,
and: true
})],
sorters: this.aSorters || [],
success: _handleSuccess.bind(this),
error: _handleError.bind(this),
groupId: this.sRefreshGroupId ? this.sRefreshGroupId : this.sGroupId
});
this._aPendingRequests.push(oRequest);
}.bind(this));
};
ODataTreeBindingFlat.prototype._propagateMagnitudeChange = function(oParent, iDelta) {
// propagate the magnitude along the parent chain, up to the top parent which is a
// server indexed node (checked by oParent.parent == null)
// first magnitude starting point is the no. of direct children/the childCount
while (oParent != null && (oParent.initiallyCollapsed || oParent.isDeepOne)) {
oParent.magnitude += iDelta;
//up one level, ends at parent == null
oParent = oParent.parent;
}
};
// Calculates the magnitude of a server index node after the initial loading
ODataTreeBindingFlat.prototype._getInitialMagnitude = function(oNode) {
var iDelta = 0,
oChild;
if (oNode.isDeepOne) { // Use original value (not "new")
return 0;
}
if (oNode.children) {
for (var i = 0; i < oNode.children.length; i++) {
oChild = oNode.children[i];
iDelta += oChild.magnitude + 1;
}
}
return oNode.magnitude - iDelta;
};
/**
* Loads the direct children of the <code>oParentNode</code> within the range [iSkip, iSkip + iTop) and merge the
* new nodes into the <code>children</code> array under the parent node.
*
* @param {object} oParentNode The parent node under which the children are loaded
* @param {int} iSkip The start index of the loading
* @param {int} iTop The number of nodes which will be loaded
*/
ODataTreeBindingFlat.prototype._loadChildren = function(oParentNode, iSkip, iTop) {
var that = this;
this.fireDataRequested();
this._requestChildren(oParentNode, iSkip, iTop).then(function(oResponseData) {
that._addChildNodes(oResponseData.oData, oParentNode, oResponseData.iSkip);
that._fireChange({reason: ChangeReason.Change});
that.fireDataReceived({data: oResponseData.oData});
}, function(oError) {
var bAborted = oError.statusCode === 0;
if (!bAborted) {
// reset data and trigger update
if (oParentNode.childCount === undefined) {
oParentNode.children = [];
oParentNode.childCount = 0;
that._fireChange({reason: ChangeReason.Change});
}
}
that.fireDataReceived();
});
};
/**
* Reloads the child nodes of the <code>oParentNode</code> within the range [iSkip, iSkip + iTop) and merges them into the inner structure.
*
* After the child nodes are loaded, the parent node is expanded again.
*
* @param {object} oParentNode The parent node under which the children are reloaded
* @param {int} iSkip The start index of the loading
* @param {int} iTop The number of nodes to be loaded
* @return {Promise} The promise resolves if the reload finishes successfully, otherwise it's rejected. The promise
* resolves with an object which has the calculated iSkip, iTop and the loaded content under
* property oData. It rejects with the error object which is returned from the server.
*/
ODataTreeBindingFlat.prototype._restoreChildren = function(oParentNode, iSkip, iTop) {
var that = this,
// get the updated key from the context in case of insert
sParentKey = this.oModel.getKey(oParentNode.context);
return this._requestChildren(oParentNode, iSkip, iTop, true/*request inline count*/).then(function(oResponseData) {
var oNewParentNode;
that._map(function(oNode, oRecursionBreaker) {
if (oNode && oNode.key === sParentKey) {
oNewParentNode = oNode;
oRecursionBreaker.broken = true;
}
});
if (oNewParentNode) {
that._addChildNodes(oResponseData.oData, oNewParentNode, oResponseData.iSkip);
that.expand(oNewParentNode, true);
}
return oResponseData;
});
};
/**
* Merges the nodes in <code>oData</code> into the <code>children</code> property under <code>oParentNode</code>.
*
* @param {object} oData The content which contains the nodes from the backed
* @param {object} oParentNode The parent node where the child nodes are saved
* @param {int} iSkip The start index for the merging into inner structure
*/
ODataTreeBindingFlat.prototype._addChildNodes = function(oData, oParentNode, iSkip) {
// $inlinecount is in oData.__count
// $count is just the 'oData' argument
if (oParentNode.childCount == undefined && oData && oData.__count) {
var iCount = oData.__count ? parseInt(oData.__count, 10) : 0;
oParentNode.childCount = iCount;
oParentNode.children[iCount - 1] = undefined;
if (oParentNode.nodeState.expanded) {
// propagate the magnitude along the parent chain
this._propagateMagnitudeChange(oParentNode, iCount);
} else {
// If parent node is not expanded, do not propagate magnitude change up to its parents
oParentNode.magnitude = iCount;
}
// once when we reload data and know the direct-child count,
// we have to keep track of the expanded state for the newly loaded nodes, so the length delta can be calculated
this._cleanTreeStateMaps();
}
//merge data into flat array structure
if (oData.results && oData.results.length > 0) {
for (var i = 0; i < oData.results.length; i++) {
var oEntry = oData.results[i];
var sKey = this.oModel.getKey(oEntry);
var oNode = oParentNode.children[iSkip + i] = oParentNode.children[iSkip + i] || {
key: sKey,
context: this.oModel.getContext("/" + sKey),
//sub-child nodes have a magnitude of 0 at their first loading time
magnitude: 0,
//level is either given by the back-end or simply 1 level deeper than the parent
level: oParentNode.level + 1,
originalLevel: oParentNode.level + 1,
initiallyCollapsed: oEntry[this.oTreeProperties["hierarchy-drill-state-for"]] === "collapsed",
//node state is also given by the back-end
nodeState: {
isLeaf: oEntry[this.oTreeProperties["hierarchy-drill-state-for"]] === "leaf",
expanded: oEntry[this.oTreeProperties["hierarchy-drill-state-for"]] === "expanded",
collapsed: oEntry[this.oTreeProperties["hierarchy-drill-state-for"]] === "collapsed",
selected: this._mSelected[sKey] ? this._mSelected[sKey].nodeState.selected : false
},
positionInParent: iSkip + i,
children: [],
// an array containing all added subtrees, may be new context nodes or nodes which were removed previously
addedSubtrees: [],
// a reference on the parent node, will only be set for manually expanded nodes, server-indexed node have a parent of null
parent: oParentNode,
// a reference on the original parent node, this property should not be changed by any algorithms, its used later to construct correct delete requests
originalParent: oParentNode,
// marks a node as a manually expanded one
isDeepOne: true,
// the deep child nodes have the same containing server index as the parent node
// the parent node is either a server-index node or another deep node which already has a containing-server-index
containingServerIndex: oParentNode.containingServerIndex || oParentNode.serverIndex
};
if (this._bSelectAll && this._aExpandedAfterSelectAll.indexOf(oParentNode) === -1) {
this.setNodeSelection(oNode, true);
}
}
}
};
/**
* Loads the child nodes based on the given range and <code>oParentNode</code>
*
* @param {object} oParentNode The node under which the children are loaded
* @param {int} iSkip The start index of the loading
* @param {int} iTop The number of nodes to be loaded
* @param {boolean} bInlineCount Whether the inline count should be requested from the backend
* @return {Promise} The promise resolves if the reload finishes successfully, otherwise it's rejected. The promise
* resolves with an object which has the calculated iSkip, iTop and the loaded content under
* property oData. It rejects with the error object which is returned from the server.
*/
ODataTreeBindingFlat.prototype._requestChildren = function (oParentNode, iSkip, iTop, bInlineCount) {
return new Promise(function(resolve, reject) {
var oRequest = {
sParent: oParentNode.key,
iSkip: iSkip,
iTop: iTop
// oRequestHandle: <will be set later>
};
// Order pending requests by index
this._aPendingChildrenRequests.sort(function(a, b) {
return a.iSkip - b.iSkip;
});
// Check pending requests:
// - adjust new request and remove parts that are already covered by pending requests
// - ignore (abort) a new request if it is already covered by pending requests
// - cancel pending requests if it is covered by the new request and additional data is added
// handles will be aborted on filter/sort calls
for (var i = 0; i < this._aPendingChildrenRequests.length; i++) {
var oPendingRequest = this._aPendingChildrenRequests[i];
if (oPendingRequest.sParent === oRequest.sParent) { // Parent key must match
if (TreeBindingUtils._determineRequestDelta(oRequest, oPendingRequest) === false) {
return; // ignore this request
}
}
}
// Convenience
iSkip = oRequest.iSkip;
iTop = oRequest.iTop;
function _handleSuccess (oData) {
// Remove request from array
var idx = this._aPendingChildrenRequests.indexOf(oRequest);
this._aPendingChildrenRequests.splice(idx, 1);
resolve({
oData: oData,
iSkip: iSkip,
iTop: iTop
});
}
function _handleError (oError) {
// Remove request from array
var idx = this._aPendingChildrenRequests.indexOf(oRequest);
this._aPendingChildrenRequests.splice(idx, 1);
reject(oError);
}
var aUrlParameters = ["$skip=" + iSkip, "$top=" + iTop];
// request inlinecount only once or inline count is needed explicitly
if (oParentNode.childCount == undefined || bInlineCount) {
aUrlParameters.push("$inlinecount=allpages");
}
// add custom parameters (including $selects)
if (this.sCustomParams) {
aUrlParameters.push(this.sCustomParams);
}
// construct multi-filter for level filter and application filters
var oLevelFilter = new Filter(this.oTreeProperties["hierarchy-parent-node-for"], "EQ", oParentNode.context.getProperty(this.oTreeProperties["hierarchy-node-for"]));
var aFilters = [oLevelFilter];
if (this.aApplicationFilters) {
aFilters = aFilters.concat(this.aApplicationFilters);
}
// TODO: Add additional filters to the read call, as soon as back-end implementations support it
// Something like this: aFilters = [new sap.ui.model.Filter([hierarchyFilters].concat(this.aFilters))];
oRequest.oRequestHandle = this.oModel.read(this.getPath(), {
context: this.oContext,
urlParameters: aUrlParameters,
filters: [new Filter({
filters: aFilters,
and: true
})],
sorters: this.aSorters || [],
success: _handleSuccess.bind(this),
error: _handleError.bind(this),
groupId: this.sRefreshGroupId ? this.sRefreshGroupId : this.sGroupId
});
this._aPendingChildrenRequests.push(oRequest);
}.bind(this));
};
/**
* Finds the node object sitting at iRowIndex.
* Does not directly correlate to the nodes position in its containing array.
*/
ODataTreeBindingFlat.prototype.findNode = function (iRowIndex) {
return this._bReadOnly ? this._indexFindNode(iRowIndex) : this._mapFindNode(iRowIndex);
};
/**
* The findNode implementation using the _map algorithm in a WRITE scenario.
*/
ODataTreeBindingFlat.prototype._mapFindNode = function (iRowIndex) {
if (this.isInitial()) {
return;
}
// first make a cache lookup
var oFoundNode = this._aNodeCache[iRowIndex];
if (oFoundNode) {
return oFoundNode;
}
// find the node for the given index
var iNodeCounter = -1;
this._map(function (oNode, oRecursionBreaker, sIndexType, iIndex, oParent) {
iNodeCounter++;
if (iNodeCounter === iRowIndex) {
oFoundNode = oNode;
oRecursionBreaker.broken = true;
}
});
return oFoundNode;
};
/**
* The findNode implementation using the index-calculation algorithm in a READ scenario.
*/
ODataTreeBindingFlat.prototype._indexFindNode = function (iRowIndex) {
if (this.isInitial()) {
return;
}
// first make a cache lookup
var oNode = this._aNodeCache[iRowIndex];
if (oNode) {
return oNode;
}
var oNodeInfo = this.getNodeInfoByRowIndex(iRowIndex),
oNode;
if (oNodeInfo.parent) {
oNode = oNodeInfo.parent.children[oNodeInfo.childIndex];
} else {
oNode = this._aNodes[oNodeInfo.index];
}
this._aNodeCache[iRowIndex] = oNode;
return oNode;
};
/**
* Toggles a row index between expanded and collapsed.
*/
ODataTreeBindingFlat.prototype.toggleIndex = function(iRowIndex) {
var oToggledNode = this.findNode(iRowIndex);
jQuery.sap.assert(oToggledNode != undefined, "toggleIndex(" + iRowIndex + "): Node not found!");
if (oToggledNode) {
if (oToggledNode.nodeState.expanded) {
this.collapse(oToggledNode);
} else {
this.expand(oToggledNode);
}
}
};
/**
* Expands a node or index.
* @param vRowIndex either an index or a node instance
* @param {boolean} bSuppressChange if set to true, no change event will be fired
*/
ODataTreeBindingFlat.prototype.expand = function (vRowIndex, bSuppressChange) {
var oToggledNode = vRowIndex;
if (typeof vRowIndex !== "object") {
oToggledNode = this.findNode(vRowIndex);
jQuery.sap.assert(oToggledNode != undefined, "expand(" + vRowIndex + "): Node not found!");
}
if (oToggledNode.nodeState.expanded) {
return; // Nothing to do here
}
//expand
oToggledNode.nodeState.expanded = true;
oToggledNode.nodeState.collapsed = false;
// remove old tree state from the collapsed array if necessary
// they are mutual exclusive
var iTreeStateFound = this._aCollapsed.indexOf(oToggledNode);
if (iTreeStateFound != -1) {
this._aCollapsed.splice(iTreeStateFound, 1);
}
this._aExpanded.push(oToggledNode);
this._sortNodes(this._aExpanded);
// keep track of server-indexed node changes
if (oToggledNode.serverIndex !== undefined) {
this._aNodeChanges[oToggledNode.serverIndex] = true;
}
if (this._bSelectAll) {
this._aExpandedAfterSelectAll.push(oToggledNode);
}
//trigger loading of the node if it is deeper than our initial level expansion
if (oToggledNode.initiallyCollapsed && oToggledNode.childCount == undefined) {
this._loadChildren(oToggledNode, 0, this._iPageSize);
} else {
this._propagateMagnitudeChange(oToggledNode.parent, oToggledNode.magnitude);
}
// clean the tree state
// this is necessary to make sure that previously collapsed-nodes which are now not contained anymore
// will be regarded for length delta calculation.
this._cleanTreeStateMaps();
//clear cache since, otherwise subsequent getContextByIndex calls will look up a wrong entry
this._aNodeCache = [];
if (!bSuppressChange) {
this._fireChange({reason: ChangeReason.Expand});
}
};
/**
* Sets the number of expanded levels to the given level.
* @param {int} iLevel the number of expanded levels
*/
ODataTreeBindingFlat.prototype.expandToLevel = function (iLevel) {
if (iLevel > this.getNumberOfExpandedLevels()) {
this.setNumberOfExpandedLevels(iLevel);
}
};
/**
* Collapses the given node or index.
* @param vRowIndex either an index or a node instance
* @param {boolean} bSuppressChange if set to true, there will be no change event fired
*/
ODataTreeBindingFlat.prototype.collapse = function (vRowIndex, bSuppressChange) {
var oToggledNode = vRowIndex;
if (typeof vRowIndex !== "object") {
oToggledNode = this.findNode(vRowIndex);
jQuery.sap.assert(oToggledNode != undefined, "expand(" + vRowIndex + "): Node not found!");
}
if (oToggledNode.nodeState.collapsed) {
return; // Nothing to do here
}
//collapse
oToggledNode.nodeState.expanded = false;
oToggledNode.nodeState.collapsed = true;
// remove old tree state
var iTreeStateFound = this._aExpanded.indexOf(oToggledNode);
if (iTreeStateFound != -1) {
this._aExpanded.splice(iTreeStateFound, 1);
}
// remove it from the select all expanded array
if (this._bSelectAll) {
iTreeStateFound = this._aExpandedAfterSelectAll.indexOf(oToggledNode);
if (iTreeStateFound !== -1) {
this._aExpandedAfterSelectAll.splice(iTreeStateFound, 1);
}
}
this._aCollapsed.push(oToggledNode);
this._sortNodes(this._aCollapsed);
if (oToggledNode.isDeepOne) {
this._propagateMagnitudeChange(oToggledNode.parent, oToggledNode.magnitude * -1);
}
// keep track of server-indexed node changes
if (oToggledNode.serverIndex !== undefined) {
this._aNodeChanges[oToggledNode.serverIndex] = true;
}
//remove selection if the nodes are collapsed recursively
this._cleanUpSelection();
// clean the tree state
// this is necessary to make sure that previously collapsed-nodes which are now not contained anymore
// will be regarded for length delta calculation.
this._cleanTreeStateMaps();
//clear cache since, otherwise subsequent getContextByIndex calls will look up a wrong entry
this._aNodeCache = [];
if (!bSuppressChange) {
this._fireChange({reason: ChangeReason.Collapse});
}
};
/**
* Sets the number of expanded levels to the given level.
* Makes sure to adapt the selection accordingly.
* @param {int} iLevel the number of expanded levels
*/
ODataTreeBindingFlat.prototype.collapseToLevel = function (iLevel) {
if (iLevel < this.getNumberOfExpandedLevels()) {
if (this.bCollapseRecursive) {
// first remove selection up to the given level
for (var sKey in this._mSelected) {
var oSelectedNode = this._mSelected[sKey];
if (oSelectedNode.level > iLevel) {
this.setNodeSelection(oSelectedNode, false);
}
}
}
this.setNumberOfExpandedLevels(iLevel);
}
};
/**
* Removes the selection for nodes which are contained in a removed OR collapsed subtree.
* @private
*/
ODataTreeBindingFlat.prototype._getInvisibleSelectedNodes = function () {
var aAffectedNodes = [];
var bIsVisible = true;
var fnCheckVisible = function(oNode, oBreaker) {
if (oNode.nodeState.collapsed || (oNode.nodeState.removed && !oNode.nodeState.reinserted)) {
bIsVisible = false;
oBreaker.broken = true;
}
};
for (var sKey in this._mSelected) {
var oSelectedNode = this._mSelected[sKey];
bIsVisible = true;
this._up(oSelectedNode, fnCheckVisible, false /*current/new parent*/);
if (!bIsVisible) {
aAffectedNodes.push(oSelectedNode);
}
}
return aAffectedNodes;
};
/**
* Removes the selection on all nodes inside invisible subtrees (removed OR collapsed).
* @private
*/
ODataTreeBindingFlat.prototype._cleanUpSelection = function (bForceDeselect) {
var aInvisibleNodes = this._getInvisibleSelectedNodes();
aInvisibleNodes.forEach(function (oSelectedNode) {
if (oSelectedNode.key == this._sLeadSelectionKey) {
this._sLeadSelectionKey = null;
}
if (this.bCollapseRecursive || bForceDeselect) {
this.setNodeSelection(oSelectedNode, false);
}
}.bind(this));
};
/**
* Checks if the oChild node is inside the subtree with root oAncestor.
*/
ODataTreeBindingFlat.prototype._isInSubtree = function (oAncestor, oChild) {
var bIsInSubtree = false;
var fnCheckAncestor = function (oNode, oBreaker) {
if (oNode == oAncestor) {
oBreaker.broken = true;
bIsInSubtree = true;
}
};
this._up(oChild, fnCheckAncestor, false /* new parent */);
return bIsInSubtree;
};
/**
* Backtracking up the tree hierarchy.
* fnUp is called for all nodes.
* @param oNode the start node of the upwards traversal
* @param {function} fnUp callback for the backtracking
* @param {boolean} bOldParent a flag to specify if the new or old/original parent should be used for traversal
* @private
*/
ODataTreeBindingFlat.prototype._up = function(oNode, fnUp, bOldParent) {
var oRecursionBreaker = {broken: false};
var oParent = this._getParent(oNode, bOldParent);
if (oParent) {
this._structuralUp(oParent, fnUp, oRecursionBreaker, bOldParent);
} else {
this._flatUp(oNode, fnUp, oRecursionBreaker, true /*initial call*/);
}
};
/**
* Backtrack in a deep part of the tree.
* @param oNode
* @param {function} fnUp
* @param oBreaker
* @param {boolean} bOldParent
* @private
*/
ODataTreeBindingFlat.prototype._structuralUp = function(oNode, fnUp, oBreaker, bOldParent) {
var oParent = oNode;
do {
fnUp(oParent, oBreaker);
if (oBreaker.broken) {
return;
}
oNode = oParent;
oParent = this._getParent(oParent);
} while (oParent);
this._flatUp(oNode, fnUp, oBreaker);
};
/**
* Backtrack in a flat part of the tree
* @param oNode
* @param {function} fnUp
* @param oBreaker
* @param {boolean} bInitial
* @private
*/
ODataTreeBindingFlat.prototype._flatUp = function(oNode, fnUp, oBreaker, bInitial) {
var iServerIndex = oNode.serverIndex,
i = bInitial ? iServerIndex - 1 : iServerIndex,
oChangedNode, oParent;
for (; i >= 0 ; i--) {
if (this._aNodeChanges[i]) {
oChangedNode = this._aNodes[i];
if (oChangedNode.initiallyCollapsed) {
// Initially collapsed node isn't relevant for the containment range check
continue;
}
if (oChangedNode.serverIndex + oChangedNode.magnitude >= iServerIndex) {
fnUp(oChangedNode, oBreaker);
if (oBreaker.broken) {
return;
}
oParent = this._getParent(oChangedNode);
if (oParent) {
this._structuralUp(oParent, fnUp, oBreaker);
return;
}
} else {
// the changed node is either a sibling or a node in a different sub-tree
// we have to continue upwards to see if another (higher-up) subtree contains oNode
continue;
}
}
}
};
/**
* Retrieves the parent node of a node.
* Either the current parent or the original one set by initial the back-end request.
* @param {object} oNode
* @param {boolean} [bOldParent=false] if set to true, the original parent will be returned.
* @returns {object} Parent node of the given node.
*/
ODataTreeBindingFlat.prototype._getParent = function(oNode, bOldParent) {
return bOldParent ? oNode.originalParent : oNode.parent;
};
/**
* Makes sure that the collapsed and expanded maps/arrays are correctly sanitized,
* by sorting them accordingly.
*/
ODataTreeBindingFlat.prototype._cleanTreeStateMaps = function () {
this._iLengthDelta = this._bReadOnly ? this._indexCleanTreeStateMaps() : this._mapCleanTreeStateMaps();
};
/**
* Calculates the Length-Delta for the index-calculation algorithm.
*/
ODataTreeBindingFlat.prototype._indexCleanTreeStateMaps = function () {
return this._calcIndexDelta(this._aNodes.length);
};
/**
* Calculates the Length-Delta for the _map algorithm.
*/
ODataTreeBindingFlat.prototype._mapCleanTreeStateMaps = function () {
var aAllChangedNodes = this._aCollapsed.concat(this._aRemoved).concat(this._aExpanded).concat(this._aAdded),
// a flag to indicate if the currently processed node is visible
// initially true for each node, but might be set to false via side-effect through fnCheckVisible.
bVisible = true,
bVisibleNewParent,
iDelta = 0,
fnCheckVisible = function(oNode, oBreaker) {
if (oNode.nodeState.collapsed || (oNode.nodeState.removed && !oNode.nodeState.reinserted)) {
bVisible = false;
oBreaker.broken = true;
}
},
mSeenNodes = {};
/**
* Visibility Check Matrix:
* VO = Visible in Old Parent
* VN = Visible in New Parent
* Delta-Sign, the sign which is used to determine if the magnitude should be added, substracted OR ignored.
*
* VO | VN | Delta-Sign
* ----|----|-----------
* 1 | 1 | 0
* 1 | 0 | -1
* 0 | 1 | +1
* 0 | 0 | 0
*/
var aCheckMatrix = [[0, 1], [-1, 0]];
aAllChangedNodes.forEach(function(oNode) {
// ignore duplicate entries, e.g. collapsed and removed/re-inserted
if (mSeenNodes[oNode.key]) {
return;
} else {
mSeenNodes[oNode.key] = true;
}
// if the node is newly added and still has a parent node
if (oNode.nodeState.added) {
if (!oNode.nodeState.removed || oNode.nodeState.reinserted) {
// first assume the newly added node is visible
bVisible = true;
// check whether it's visible under the current parent
// even when it's moved to a new parent, only the new parent needs to be considered because the newly added node doesn't
// have any contribution to the magnitude of the old parent.
this._up(oNode, fnCheckVisible, false /*current/new parent*/);
if (bVisible) {
iDelta++;
}
}
} else {
if (oNode.nodeState.collapsed || oNode.nodeState.expanded || oNode.nodeState.removed) {
// first assume the node is visible
bVisible = true;
this._up(oNode, fnCheckVisible, false /* current/new parent */);
// if the node isn't hidden by one of its current ancestors
if (bVisible) {
// if the node is removed and not reinserted, its children and itself should be substracted
if (oNode.nodeState.removed && !oNode.nodeState.reinserted) {
// deep or initiallyCollapsed nodes only substract themselves.
if (oNode.isDeepOne || oNode.initiallyCollapsed) {
iDelta -= 1;
} else {
// server indexed nodes always subtract their magnitude
iDelta -= (oNode.magnitude + 1);
}
} else {
// if the node which is expanded after the initial loading is collapsed, its magnitude needs to be substracted.
if (oNode.nodeState.collapsed && oNode.serverIndex !== undefined && !oNode.initiallyCollapsed) {
iDelta -= oNode.magnitude;
}
// if the node which is manually expanded after the initial loading, its direct children length (not magnitude) needs to be added
if (oNode.nodeState.expanded && (oNode.isDeepOne || oNode.initiallyCollapsed)) {
iDelta += oNode.children.length;
}
}
}
if (oNode.nodeState.reinserted) {
// if it's reinserted, check it's visibility between the new and old parent. Then decide how it influences the delta.
bVisibleNewParent = bVisible;
bVisible = true;
this._up(oNode, fnCheckVisible, true /*old parent*/);
var iVisibilityFactor = (aCheckMatrix[bVisible | 0][bVisibleNewParent | 0]);
// iVisibilityFactor is either 0, 1 or -1.
// 1 and -1 are the relevant factors here, otherwise the node is not visible
if (!!iVisibilityFactor) {
if (oNode.isDeepOne) {
iDelta += iVisibilityFactor * 1;
} else {
// re-inserted visible nodes, which are initially collapsed only contribute to the length +1
// they only count themselves, their children have already been added (if they were visible)
if (oNode.initiallyCollapsed) {
iDelta += iVisibilityFactor;
} else {
iDelta += iVisibilityFactor * (1 + oNode.magnitude);
}
}
}
}
}
}
}.bind(this));
return iDelta;
};
/**
* Returns if the count was received already and we know how many entries there will be in total.
*/
ODataTreeBindingFlat.prototype.isLengthFinal = function () {
return this._bLengthFinal;
};
/**
* The length of the binding regards the expanded state of the tree.
* So the length is the direct length of the tables scrollbar.
*/
ODataTreeBindingFlat.prototype.getLength = function () {
return this._aNodes.length + this._iLengthDelta;
};
/**
* Retrieves the context for a given index.
*/
ODataTreeBindingFlat.prototype.getContextByIndex = function (iRowIndex) {
if (this.isInitial()) {
return;
}
var oNode = this.findNode(iRowIndex);
return oNode && oNode.context;
};
/**
* Retrieves the context for a given index.
*/
ODataTreeBindingFlat.prototype.getNodeByIndex = function (iRowIndex) {
if (this.isInitial()) {
return;
}
var oNode = this.findNode(iRowIndex);
return oNode;
};
/**
* Checks if an index is expanded
*/
ODataTreeBindingFlat.prototype.isExpanded = function(iRowIndex) {
var oNode = this.findNode(iRowIndex);
return oNode && oNode.nodeState.expanded;
};
/**
* Returns if a node has children.
* This does not mean, the children have to be loaded or the node has to be expanded.
* If the node is a leaf it has not children, otherwise the function returns true.
* @param {object} oContext the context to check
* @returns {boolean} node has children or not
* @protected
*/
ODataTreeBindingFlat.prototype.hasChildren = function(oContext) {
if (!oContext) {
return false;
}
// check if the node for the context is a leaf, if not it has children
var oNodeInfo = this._findNodeByContext(oContext);
var oNode = oNodeInfo && oNodeInfo.node;
return !(oNode && oNode.nodeState.isLeaf);
};
/**
* Checks if a node has children.
* API function for TreeTable.
* @param oNode the node to check
* @returns {boolean} node has children or not
* @protected
*/
ODataTreeBindingFlat.prototype.nodeHasChildren = function (oNode) {
return !(oNode && oNode.nodeState.isLeaf);
};
//*************************************************
//* Selection-Handling *
//************************************************/
/**
* Sets the selection state of the given node.
* @param {object} oNodeState the node state for which the selection should be changed
* @param {boolean} bIsSelected the selection state for the given node
*/
ODataTreeBindingFlat.prototype.setNodeSelection = function (oNode, bIsSelected) {
jQuery.sap.assert(oNode, "Node must be defined!");
oNode.nodeState.selected = bIsSelected;
// toggles the selection state based on bIsSelected
if (bIsSelected) {
delete this._mDeselected[oNode.key];
this._mSelected[oNode.key] = oNode;
} else {
delete this._mSelected[oNode.key];
this._mDeselected[oNode.key] = oNode;
if (oNode.key === this._sLeadSelectionKey) {
// if the lead selection node is deselected, clear the _sLeadSelectionKey
this._sLeadSelectionKey = null;
}
}
};
/**
* Returns the selection state for the node at the given index.
* @param {int} iRowIndex the row index to check for selection state
*/
ODataTreeBindingFlat.prototype.isIndexSelected = function (iRowIndex) {
var oNode = this.findNode(iRowIndex);
return oNode && oNode.nodeState ? oNode.nodeState.selected : false;
};
/**
* Returns if the node at the given index is selectable.
* Always true for TreeTable controls, except the node is not defined.
* @param {int} iRowIndex the row index which should be checked for "selectability"
*/
ODataTreeBindingFlat.prototype.isIndexSelectable = function (iRowIndex) {
var oNode = this.findNode(iRowIndex);
return !!oNode;
};
/**
* Removes the selection from all nodes
* @private
*/
ODataTreeBindingFlat.prototype._clearSelection = function () {
return this._bReadOnly ? this._indexClearSelection() : this._mapClearSelection();
};
ODataTreeBindingFlat.prototype._indexClearSelection = function () {
var iOldLeadIndex = -1,
aChangedIndices = [],
sSelectedKey, oNode, iRowIndex;
this._bSelectAll = false;
this._aExpandedAfterSelectAll = [];
for (sSelectedKey in this._mSelected) {
oNode = this._mSelected[sSelectedKey];
this.setNodeSelection(oNode, false);
iRowIndex = this.getRowIndexByNode(oNode);
aChangedIndices.push(iRowIndex);
// find old lead selection index
if (this._sLeadSelectionKey == sSelectedKey) {
iOldLeadIndex = iRowIndex;
}
}
return {
rowIndices: aChangedIndices,
oldIndex: iOldLeadIndex,
leadIndex: -1
};
};
ODataTreeBindingFlat.prototype._mapClearSelection = function () {
var iNodeCounter = -1;
var iOldLeadIndex = -1;
var iMaxNumberOfSelectedNodes = 0;
var aChangedIndices = [];
this._bSelectAll = false;
this._aExpandedAfterSelectAll = [];
// Optimisation: find out how many nodes we have to check for deselection
for (var sKey in this._mSelected) {
if (sKey) {
iMaxNumberOfSelectedNodes++;
}
}
// collect all selected nodes and switch them to deselected
this._map(function (oNode, oRecursionBreaker, sIndexType, iIndex, oParent) {
iNodeCounter++;
if (oNode && oNode.nodeState.selected) {
this.setNodeSelection(oNode, false);
aChangedIndices.push(iNodeCounter);
//find old lead selection index
if (this._sLeadSelectionKey == oNode.key) {
iOldLeadIndex = iNodeCounter;
}
if (aChangedIndices.length == iMaxNumberOfSelectedNodes) {
oRecursionBreaker.broken = true;
}
}
}.bind(this));
return {
rowIndices: aChangedIndices,
oldIndex: iOldLeadIndex,
leadIndex: -1
};
};
/**
* Marks a single TreeTable node sitting on iRowIndex as selected.
* Also sets the lead selection index to this node.
* @param {int} iRowIndex the absolute row index which should be selected
*/
ODataTreeBindingFlat.prototype.setSelectedIndex = function (iRowIndex) {
var oNode = this.findNode(iRowIndex);
if (oNode) {
// clear and fetch the changes on the selection
var oChanges = this._clearSelection();
// if the selected row index was already selected before -> remove it from the changed Indices from the clearSection() call
var iChangedIndex = oChanges.rowIndices.indexOf(iRowIndex);
if (iChangedIndex >= 0) {
oChanges.rowIndices.splice(iChangedIndex, 1);
} else {
// the newly selcted index is missing and also has to be propagated via the event params
oChanges.rowIndices.push(iRowIndex);
}
//set the new lead index
oChanges.leadKey = oNode.key;
oChanges.leadIndex = iRowIndex;
this.setNodeSelection(oNode, true);
this._publishSelectionChanges(oChanges);
} else {
jQuery.sap.log.warning("ODataTreeBindingFlat: The selection of index '" + iRowIndex + "' was ignored. Please make sure to only select rows, for which data has been fetched to the client.");
}
};
/**
* Retrieves the "Lead-Selection-Index"
* Normally this is the last selected node/table row.
* @return {int} returns the lead selection index or -1 if none is set
*/
ODataTreeBindingFlat.prototype.getSelectedIndex = function () {
return this._bReadOnly ? this._indexGetSelectedIndex() : this._mapGetSelectedIndex();
};
ODataTreeBindingFlat.prototype._indexGetSelectedIndex = function () {
//if we have no nodes selected, the lead selection index is -1
if (!this._sLeadSelectionKey || jQuery.isEmptyObject(this._mSelected)) {
return -1;
}
var oSelectedNode = this._mSelected[this._sLeadSelectionKey];
if (oSelectedNode) {
return this.getRowIndexByNode(oSelectedNode);
} else {
return -1;
}
};
ODataTreeBindingFlat.prototype._mapGetSelectedIndex = function () {
//if we have no nodes selected, the lead selection index is -1
if (!this._sLeadSelectionKey || jQuery.isEmptyObject(this._mSelected)) {
return -1;
}
// find the index of the current lead-selection node
var iNodeCounter = -1;
this._map(function (oNode, oRecursionBreaker) {
iNodeCounter++;
if (oNode) {
if (oNode.key === this._sLeadSelectionKey) {
oRecursionBreaker.broken = true;
}
}
}.bind(this));
return iNodeCounter;
};
/**
* Returns an array with all selected row indices.
* Only absolute row indices for nodes known to the client will can be retrieved this way
* @return {int[]} an array with all selected indices
*/
ODataTreeBindingFlat.prototype.getSelectedIndices = function () {
return this._bReadOnly ? this._indexGetSelectedIndices() : this._mapGetSelectedIndices();
};
ODataTreeBindingFlat.prototype._indexGetSelectedIndices = function () {
var aNodesInfo = this._getSelectedNodesInfo();
return aNodesInfo.map(function(oNodeInfo) {
return oNodeInfo.rowIndex;
});
};
ODataTreeBindingFlat.prototype._mapGetSelectedIndices = function () {
var aResultIndices = [];
//if we have no nodes selected, the selection indices are empty
if (jQuery.isEmptyObject(this._mSelected)) {
return aResultIndices;
}
// collect the indices of all selected nodes
var iNodeCounter = -1;
this._map(function (oNode) {
iNodeCounter++;
if (oNode) {
if (oNode.nodeState && oNode.nodeState.selected) {
aResultIndices.push(iNodeCounter);
}
}
});
return aResultIndices;
};
/**
* Returns the number of selected nodes.
* @private
* @returns {int} number of selected nodes.
*/
ODataTreeBindingFlat.prototype.getSelectedNodesCount = function () {
var iSelectedNodes;
if (this._bSelectAll) {
if (this._bReadOnly) {
// Read only
var aRelevantExpandedAfterSelectAllNodes = [],
iNumberOfVisibleDeselectedNodes = 0,
sKey;
this._aExpandedAfterSelectAll.sort(function (a, b) {
var iA = this._getRelatedServerIndex(a);
var iB = this._getRelatedServerIndex(b);
jQuery.sap.assert(iA != undefined, "getSelectedNodesCount: (containing) Server-Index not found for node 'a'");
jQuery.sap.assert(iB != undefined, "getSelectedNodesCount: (containing) Server-Index not found node 'b'");
// deep nodes are inside the same containing server-index --> sort them by their level
// this way we can make sure, that deeper nodes are sorted after higher-leveled ones
if (iA == iB && a.isDeepOne && b.isDeepOne) {
return a.originalLevel - b.originalLevel;
}
return iA - iB; // ascending
}.bind(this));
var iLastExpandedIndex = -1, oNode, iNodeIdx, i;
for (i = 0; i < this._aExpandedAfterSelectAll.length; i++) {
oNode = this._aExpandedAfterSelectAll[i];
iNodeIdx = this._getRelatedServerIndex(oNode);
if (iNodeIdx <= iLastExpandedIndex && !oNode.initiallyCollapsed) {
// Node got already covered by a previous loop through its parent
// AND node is not initially collapsed.
// Deep nodes are initially collapsed and have to be processed, even though
// their related server-index is in another node's magnitude range.
continue;
}
if (oNode.initiallyCollapsed) {
iLastExpandedIndex = iNodeIdx;
} else {
iLastExpandedIndex = iNodeIdx + oNode.magnitude;
}
aRelevantExpandedAfterSelectAllNodes.push(oNode);
iNumberOfVisibleDeselectedNodes += oNode.magnitude;
}
var checkContainedInExpandedNode = function(oNode, oBreaker) {
if (aRelevantExpandedAfterSelectAllNodes.indexOf(oNode) !== -1) {
iNumberOfVisibleDeselectedNodes--;
oBreaker.broken = true;
}
};
for (sKey in this._mSelected) {
this._up(this._mSelected[sKey], checkContainedInExpandedNode, true /*old/original*/);
}
var bIsVisible;
var checkVisibleDeselectedAndNotAlreadyCountedNode = function(oNode, oBreaker) {
if (oNode.nodeState.collapsed || (oNode.nodeState.removed && !oNode.nodeState.reinserted) ||
aRelevantExpandedAfterSelectAllNodes.indexOf(oNode) !== -1) {
bIsVisible = false;
oBreaker.broken = true;
}
};
for (sKey in this._mDeselected) {
bIsVisible = true;
this._up(this._mDeselected[sKey], checkVisibleDeselectedAndNotAlreadyCountedNode, true /*old/original*/);
if (bIsVisible) {
iNumberOfVisibleDeselectedNodes++;
}
}
iSelectedNodes = this.getLength() - iNumberOfVisibleDeselectedNodes;
} else {
// Write => go through all visible nodes in the tree
iSelectedNodes = 0;
this._map(function (oNode, oRecursionBreaker, sIndexType, iIndex, oParent) {
var oParentNode;
if (oNode) {
if (oNode.nodeState.selected) {
iSelectedNodes++;
}
} else if (oNode === undefined && sIndexType === "serverIndex") {
// Not yet loaded node => parent is unknown
var bIsSelected = true;
for (var i = iIndex - 1; i >= 0; i--) {
if (this._aNodeChanges[i]) {
oParentNode = this._aNodes[i];
if (oParentNode.serverIndex + oParentNode.magnitude >= iIndex &&
this._aExpandedAfterSelectAll.indexOf(oParentNode) !== -1) {
bIsSelected = false;
break;
}
}
}
if (bIsSelected) {
iSelectedNodes++;
}
}
}.bind(this));
}
} else {
var aInvisibleNodes = this._getInvisibleSelectedNodes();
iSelectedNodes = Math.max(Object.keys(this._mSelected).length - aInvisibleNodes.length, 0);
}
return iSelectedNodes;
};
/**
* Returns an array containing all selected contexts, ordered by their appearance in the tree.
* @return {sap.ui.model.Context[]} an array containing the binding contexts for all selected nodes
*/
ODataTreeBindingFlat.prototype.getSelectedContexts = function () {
return this._bReadOnly ? this._indexGetSelectedContexts() : this._mapGetSelectedContexts();
};
ODataTreeBindingFlat.prototype._indexGetSelectedContexts = function () {
var aNodesInfo = this._getSelectedNodesInfo();
return aNodesInfo.map(function(oNodeInfo) {
return oNodeInfo.node.context;
});
};
/**
* Returns an array containing all selected contexts, ordered by their appearance in the tree.
* @return {sap.ui.model.Context[]} an array containing the binding contexts for all selected nodes
*/
ODataTreeBindingFlat.prototype._mapGetSelectedContexts = function () {
var aResultContexts = [];
//if we have no nodes selected, the selection indices are empty
if (jQuery.isEmptyObject(this._mSelected)) {
return aResultContexts;
}
// collect the indices of all selected nodes
var fnMatchFunction = function (oNode) {
if (oNode) {
if (oNode.nodeState.selected && !oNode.isArtificial) {
aResultContexts.push(oNode.context);
}
}
};
this._map(fnMatchFunction);
return aResultContexts;
};
/**
* Sets the selection to the range from iFromIndex to iToIndex (including boundaries).
* e.g. setSelectionInterval(1,3) marks the rows 1,2 and 3.
* All currently selected rows will be deselected in the process.
* A selectionChanged event is fired
*/
ODataTreeBindingFlat.prototype.setSelectionInterval = function (iFromIndex, iToIndex) {
// clears the selection but suppresses the selection change event
var mClearParams = this._clearSelection();
// the addSelectionInterval function takes care of the selection change event
var mSetParams = this._setSelectionInterval(iFromIndex, iToIndex, true);
var mIndicesFound = {};
var aRowIndices = [];
var iIndex;
// flag all cleared indices as changed
for (var i = 0; i < mClearParams.rowIndices.length; i++) {
iIndex = mClearParams.rowIndices[i];
mIndicesFound[iIndex] = true;
}
// now merge the changed indices after clearing with the newly selected
// duplicate indices mean, that the index was previously selected and is now still selected -> remove it from the changes
for (i = 0; i < mSetParams.rowIndices.length; i++) {
iIndex = mSetParams.rowIndices[i];
if (mIndicesFound[iIndex]) {
delete mIndicesFound[iIndex];
} else {
mIndicesFound[iIndex] = true;
}
}
// transform the changed index MAP into a real array of indices
for (iIndex in mIndicesFound) {
if (mIndicesFound[iIndex]) {
aRowIndices.push(parseInt(iIndex, 10));
}
}
//and fire the event
this._publishSelectionChanges({
rowIndices: aRowIndices,
oldIndex: mClearParams.oldIndex,
leadIndex: mSetParams.leadIndex,
leadKey: mSetParams.leadKey
});
};
/**
* Sets the value inside the given range to the value given with 'bSelectionValue'
* @private
* @param {int} iFromIndex the starting index of the selection range
* @param {int} iToIndex the end index of the selection range
* @param {boolean} bSelectionValue the selection state which should be applied to all indices between 'from' and 'to' index
*/
ODataTreeBindingFlat.prototype._setSelectionInterval = function (iFromIndex, iToIndex, bSelectionValue) {
return this._bReadOnly ? this._indexSetSelectionInterval(iFromIndex, iToIndex, bSelectionValue) : this._mapSetSelectionInterval(iFromIndex, iToIndex, bSelectionValue);
};
ODataTreeBindingFlat.prototype._indexSetSelectionInterval = function (iFromIndex, iToIndex, bSelectionValue) {
//make sure the "From" Index is always lower than the "To" Index
var iNewFromIndex = Math.min(iFromIndex, iToIndex),
iNewToIndex = Math.max(iFromIndex, iToIndex),
aNewlySelectedNodes = [],
aChangedIndices = [],
// the old lead index, might be undefined -> publishSelectionChanges() will set it to -1
iOldLeadIndex,
oNode, i, mParams;
bSelectionValue = !!bSelectionValue;
for (i = iNewFromIndex ; i <= iNewToIndex ; i++) {
oNode = this.findNode(i);
if (oNode) {
// fetch the node index if its selection state changes
if (oNode.nodeState.selected !== bSelectionValue) {
aChangedIndices.push(i);
}
// remember the old lead selection index if we encounter it
// (might not happen if the lead selection is outside the newly set range)
if (oNode.key === this._sLeadSelectionKey) {
iOldLeadIndex = i;
}
// select/deselect node, but suppress the selection change event
this.setNodeSelection(oNode, bSelectionValue);
aNewlySelectedNodes.push(oNode);
}
}
mParams = {
rowIndices: aChangedIndices,
oldIndex: iOldLeadIndex,
// if we found a lead index during tree traversal and we deselected it -> the new lead selection index is -1
leadIndex: iOldLeadIndex && !bSelectionValue ? -1 : undefined
};
// set new lead selection node if necessary
if (aNewlySelectedNodes.length > 0 && bSelectionValue) {
mParams.leadKey = aNewlySelectedNodes[aNewlySelectedNodes.length - 1].key;
mParams.leadIndex = iNewToIndex;
}
return mParams;
};
ODataTreeBindingFlat.prototype._mapSetSelectionInterval = function (iFromIndex, iToIndex, bSelectionValue) {
//make sure the "From" Index is always lower than the "To" Index
var iNewFromIndex = Math.min(iFromIndex, iToIndex);
var iNewToIndex = Math.max(iFromIndex, iToIndex);
//find out how many nodes should be selected, this is a termination condition for the match function
var aNewlySelectedNodes = [];
var aChangedIndices = [];
var iNumberOfNodesToSelect = Math.abs(iNewToIndex - iNewFromIndex) + 1; //+1 because the boundary indices are included
// the old lead index, might be undefined -> publishSelectionChanges() will set it to -1
var iOldLeadIndex;
// loop through all nodes and select them if necessary
var iNodeCounter = -1;
var fnMapFunction = function (oNode, oRecursionBreaker, sIndexType, iIndex, oParent) {
iNodeCounter++;
if (oNode) {
//if the node is inside the range -> select it
if (iNodeCounter >= iNewFromIndex && iNodeCounter <= iNewToIndex) {
// fetch the node index if its selection state changes
if (oNode.nodeState.selected !== !!bSelectionValue) {
aChangedIndices.push(iNodeCounter);
}
// remember the old lead selection index if we encounter it
// (might not happen if the lead selection is outside the newly set range)
if (oNode.key === this._sLeadSelectionKey) {
iOldLeadIndex = iNodeCounter;
}
// select/deselect node, but suppress the selection change event
this.setNodeSelection(oNode, !!bSelectionValue);
aNewlySelectedNodes.push(oNode);
if (aNewlySelectedNodes.length === iNumberOfNodesToSelect) {
oRecursionBreaker.broken = true;
}
}
}
}.bind(this);
this._map(fnMapFunction);
var mParams = {
rowIndices: aChangedIndices,
oldIndex: iOldLeadIndex,
//if we found a lead index during tree traversal and we deselected it -> the new lead selection index is -1
leadIndex: iOldLeadIndex && !bSelectionValue ? -1 : undefined
};
// set new lead selection node if necessary
if (aNewlySelectedNodes.length > 0 && bSelectionValue){
var oLeadSelectionNode = aNewlySelectedNodes[aNewlySelectedNodes.length - 1];
mParams.leadKey = oLeadSelectionNode.key;
mParams.leadIndex = iNewToIndex;
}
return mParams;
};
/**
* Marks a range of tree nodes as selected/deselected, starting with iFromIndex going to iToIndex.
* The TreeNodes are referenced via their absolute row index.
* Please be aware, that the absolute row index only applies to the tree which is visualized by the TreeTable.
* Invisible nodes (collapsed child nodes) will not be regarded.
*/
ODataTreeBindingFlat.prototype.addSelectionInterval = function (iFromIndex, iToIndex) {
var mParams = this._setSelectionInterval(iFromIndex, iToIndex, true);
this._publishSelectionChanges(mParams);
};
/**
* Removes the selections inside the given range (including boundaries)
*/
ODataTreeBindingFlat.prototype.removeSelectionInterval = function (iFromIndex, iToIndex) {
var mParams = this._setSelectionInterval(iFromIndex, iToIndex, false);
this._publishSelectionChanges(mParams);
};
/**
* Selects all avaliable nodes
*/
ODataTreeBindingFlat.prototype.selectAll = function () {
this._bReadOnly ? this._indexSelectAll() : this._mapSelectAll();
};
ODataTreeBindingFlat.prototype._indexSelectAll = function () {
// mark the tree as in selectAll mode
this._bSelectAll = true;
this._aExpandedAfterSelectAll = [];
var mParams = {
rowIndices: [],
oldIndex: -1,
selectAll: true
};
var iLength = this.getLength(),
i, oNode;
for (i = 0 ; i < iLength; i++) {
oNode = this.findNode(i);
if (oNode && !oNode.isArtificial) {
//if we find the old lead selection index -> keep it, safes some performance later on
if (oNode.key === this._sLeadSelectionKey) {
mParams.oldIndex = i;
}
//if a node is NOT selected (and is not our artificial root node...)
if (!oNode.nodeState.selected) {
mParams.rowIndices.push(i);
}
this.setNodeSelection(oNode, true);
// keep track of the last selected node -> this will be the new lead index
mParams.leadKey = oNode.key;
mParams.leadIndex = i;
}
}
this._publishSelectionChanges(mParams);
};
ODataTreeBindingFlat.prototype._mapSelectAll = function () {
// mark the tree as in selectAll mode
this._bSelectAll = true;
this._aExpandedAfterSelectAll = [];
var mParams = {
rowIndices: [],
oldIndex: -1,
selectAll: true
};
// recursion variables
var iNodeCounter = -1;
this._map(function (oNode) {
if (!oNode || !oNode.isArtificial) {
iNodeCounter++;
}
if (oNode) {
//if we find the old lead selection index -> keep it, safes some performance later on
if (oNode.key === this._sLeadSelectionKey) {
mParams.oldIndex = iNodeCounter;
}
if (oNode) {
//if a node is NOT selected (and is not our artificial root node...)
if (!oNode.isArtificial && !oNode.nodeState.selected) {
mParams.rowIndices.push(iNodeCounter);
}
this.setNodeSelection(oNode, true);
// keep track of the last selected node -> this will be the new lead index
mParams.leadKey = oNode.key;
mParams.leadIndex = iNodeCounter;
}
}
}.bind(this));
this._publishSelectionChanges(mParams);
};
/**
* Removes the complete selection.
* @param {boolean} bSuppressSelectionChangeEvent if this is set to true, no selectionChange event will be fired
*/
ODataTreeBindingFlat.prototype.clearSelection = function (bSuppresSelectionChangeEvent) {
var oChanges = this._clearSelection();
// check if the selection change event should be suppressed
if (!bSuppresSelectionChangeEvent) {
this._publishSelectionChanges(oChanges);
}
};
/**
* Fires a "selectionChanged" event with the given parameters.
* Also performs a sanity check on the parameters.
*/
ODataTreeBindingFlat.prototype._publishSelectionChanges = function (mParams) {
// retrieve the current (old) lead selection and add it to the changed row indices if necessary
mParams.oldIndex = mParams.oldIndex || this.getSelectedIndex();
//sort row indices ascending
mParams.rowIndices.sort(function(a, b) {
return a - b;
});
//set the lead selection index
if (mParams.leadIndex >= 0 && mParams.leadKey) {
//keep track of a newly set lead index
this._sLeadSelectionKey = mParams.leadKey;
} else if (mParams.leadIndex === -1){
// explicitly remove the lead index
this._sLeadSelectionKey = undefined;
} else {
//nothing changed, lead and old index are the same
mParams.leadIndex = mParams.oldIndex;
}
//only fire event if the selection actually changed somehow
if (mParams.rowIndices.length > 0 || (mParams.leadIndex != undefined && mParams.leadIndex !== -1)) {
this.fireSelectionChanged(mParams);
}
};
/**
* Sets the node hierarchy to collapse recursive. When set to true, all child nodes will get collapsed as well.
* @param {boolean} bCollapseRecursive
*/
ODataTreeBindingFlat.prototype.setCollapseRecursive = function (bCollapseRecursive) {
this.bCollapseRecursive = !!bCollapseRecursive;
};
/**
* Reset the bindings internal data structures.
*/
ODataTreeBindingFlat.prototype.resetData = function () {
ODataTreeBinding.prototype.resetData.apply(this, arguments);
this._aNodes = [];
this._aNodeCache = [];
this._aCollapsed = [];
this._aExpanded = [];
this._aExpandedAfterSelectAll = [];
this._mSelected = {};
this._mDeselected = {};
this._aAdded = [];
this._aRemoved = [];
this._aNodeChanges = [];
this._aAllChangedNodes = [];
this._bLengthFinal = false;
this._iLowestServerLevel = null;
this._bSelectAll = false;
// the delta variable for calculating the correct binding-length (used e.g. for sizing the scrollbar)
this._iLengthDelta = 0;
};
/**
* Finds a node for the given context object.
* First makes a cache search before traversing the tree
*/
ODataTreeBindingFlat.prototype._findNodeByContext = function (oContext) {
// First try to find the node in the cache.
// The cache has a near constant size, yet depending on the number of rows in the TreeTable.
// Worst case: The TreeTable has about ~30 +/- rows in a fullscreen browser window on a Full-HD display with zoom-factor 100%.
// Its more efficient to search here first than search the tree.
for (var sIndex in this._aNodeCache) {
if (this._aNodeCache[sIndex] && this._aNodeCache[sIndex].context == oContext) {
// found it
return {
node: this._aNodeCache[sIndex],
index: parseInt(sIndex, 10)
};
}
}
// node is not in cache, try to find to find it in the tree
var iNodeCounter = -1;
var oNodeForContext;
this._map(function (oNode, oRecursionBreaker, sIndexType, iIndex, oParent) {
iNodeCounter++;
if (oNode) {
if (oNode.context === oContext) {
oNodeForContext = oNode;
oRecursionBreaker.broken = true;
}
}
});
return {
node: oNodeForContext,
index: iNodeCounter
};
};
/**
* Resolves the correct change group for the given key/path.
* @private
*/
ODataTreeBindingFlat.prototype._getCorrectChangeGroup = function (sKey) {
if (!sKey) {
sKey = this.oModel.resolve(this.getPath(), this.getContext());
}
return this.oModel._resolveGroup(sKey).groupId;
};
/**
* Creates a new entry, which can be added to this binding instance via addContexts(...).
*/
ODataTreeBindingFlat.prototype.createEntry = function (mParameters) {
var sAbsolutePath = this.oModel.resolve(this.getPath(), this.getContext());
var oNewEntry;
if (sAbsolutePath) {
mParameters = mParameters || {};
mParameters.groupId = this._getCorrectChangeGroup(sAbsolutePath);
mParameters.refreshAfterChange = false;
oNewEntry = this.oModel.createEntry(sAbsolutePath, mParameters);
} else {
jQuery.sap.log.warning("ODataTreeBindingFlat: createEntry failed, as the binding path could not be resolved.");
}
return oNewEntry;
};
/**
* Submits the queued changes regarding this binding instance.
*/
ODataTreeBindingFlat.prototype.submitChanges = function (mParameters) {
mParameters = mParameters || {};
// group id
var sAbsolutePath = this.oModel.resolve(this.getPath(), this.getContext()),
oOptimizedChanges = this._optimizeChanges();
if (!sAbsolutePath) {
jQuery.sap.log.warning("ODataTreeBindingFlat: submitChanges failed, because the binding-path could not be resolved.");
return;
}
mParameters.groupId = this._getCorrectChangeGroup(sAbsolutePath);
// make sure not to lose the original success/error handlers
var fnOrgSuccess = mParameters.success || jQuery.noop;
var fnOrgError = mParameters.error || jQuery.noop;
var bRestoreRequestFailed = false;
// handlers used by the binding itself
mParameters.success = function (oData) {
// call original success handler
fnOrgSuccess(oData);
var bSomethingFailed = false;
// check the change responses for errors
if (oData.__batchResponses && oData.__batchResponses[0] &&
oData.__batchResponses[0].__changeResponses && oData.__batchResponses[0].__changeResponses.length > 0) {
var aChangeResponses = oData.__batchResponses[0].__changeResponses;
for (var i = 0; i < aChangeResponses.length; i++) {
var oResponse = aChangeResponses[i];
var iStatusCode = parseInt(oResponse.statusCode, 10);
if (iStatusCode < 200 || iStatusCode > 299) {
bSomethingFailed = true;
break;
}
}
if (bSomethingFailed) {
// Just like ODataModel.submitChanges, if a request fails we don't do anything.
// Example from other bindings: ODataPropertyBinding still keeps a value that could not be successfully submitted.
// It is up to the application to handle such errors.
// A tree state restoration won't happen. The tree state will stay the same as no data is getting reset.
} else if (this._bRestoreTreeStateAfterChange && !bRestoreRequestFailed && (!this.aApplicationFilters || this.aApplicationFilters.length === 0)) {
// This is an temporary flag on the binding to turn off the restore feature by default.
// This flag defines whether the tree state before submitChanges should be restored afterwards.
// If this is true, a batch request is sent after the save action is finished to load the nodes
// which were available before in order to properly restore the tree state.
// Application filters are currently not supported for tree state restoration
// this is due to the SiblingsPosition being requested via GET Entity (not filterable) instead of GET Entity Set (filterable)
this._restoreTreeState(oOptimizedChanges).catch(function (err) {
jQuery.sap.log.error("ODataTreeBindingFlat - " + err.message, err.stack);
this._refresh(true);
}.bind(this));
} else {
// Trigger a refresh to reload the newly updated hierarchy
// This is the happy path, and only here a refresh has to be triggered.
this._refresh(true);
}
} else {
// batch response does not contain change responses: error case
jQuery.sap.log.warning("ODataTreeBindingFlat.submitChanges - success: Batch-request response does not contain change response.");
}
}.bind(this);
mParameters.error = function (oEvent) {
// TODO: How to handle errors?
// What kind of errors? Timeout? Authentication failed? General 50x error?
// call original error handler
fnOrgError(oEvent);
};
// built the actual requests for the change-set
this._generateSubmitData(oOptimizedChanges, function(err) {
jQuery.sap.log.error("ODataTreeBindingFlat - Tree state restoration request failed. " + err.message, err.stack);
bRestoreRequestFailed = true;
});
// relay submit call to the model
this.oModel.submitChanges(mParameters);
};
/**
* Generates the request data for a submit request.
* Generates a minimal set of UPDATE & DELETE requests, in the correct order.
*/
ODataTreeBindingFlat.prototype._generateSubmitData = function (oOptimizedChanges, restoreRequestErrorHandler) {
var aRemoved = oOptimizedChanges.removed,
aCreationCancelled = oOptimizedChanges.creationCancelled,
aAdded = oOptimizedChanges.added,
aMoved = oOptimizedChanges.moved,
that = this;
function setParent(oNode) {
jQuery.sap.assert(oNode.context, "Node does not have a context.");
var sParentNodeID = oNode.parent.context.getProperty(that.oTreeProperties["hierarchy-node-for"]);
that.oModel.setProperty(that.oTreeProperties["hierarchy-parent-node-for"], sParentNodeID, oNode.context);
}
var mRestoreRequestParameters = {
groupId: this._getCorrectChangeGroup(),
error: restoreRequestErrorHandler
};
aAdded.forEach(setParent); // No extra requests for add. Everything we need should be in the POST response
aMoved.forEach(function(oNode) {
setParent(oNode);
if (this._bRestoreTreeStateAfterChange && (!this.aApplicationFilters || this.aApplicationFilters.length === 0)) {
// Application filters are currently not supported for tree state restoration
// this is due to the SiblingsPosition being requested via GET Entity (not filterable) instead of GET Entity Set (filterable
this._generatePreorderPositionRequest(oNode, mRestoreRequestParameters);
this._generateSiblingsPositionRequest(oNode, mRestoreRequestParameters);
}
}.bind(this));
aRemoved.forEach(function(oNode) {
this._generateDeleteRequest(oNode);
jQuery.sap.log.debug("ODataTreeBindingFlat: DELETE " + oNode.key);
}.bind(this));
aCreationCancelled.forEach(function(oNode) {
this._generateDeleteRequest(oNode);
}.bind(this));
};
ODataTreeBindingFlat.prototype._generatePreorderPositionRequest = function(oNode, mParameters) {
var sGroupId, sKeyProperty, sKeySelect, mUrlParameters,
successHandler, errorHandler,
aFilters = [],
aSorters = this.aSorters || [],
i;
if (mParameters) {
sGroupId = mParameters.groupId || this.sGroupId;
successHandler = mParameters.success;
errorHandler = mParameters.error;
}
if (this.aApplicationFilters) {
aFilters = aFilters.concat(this.aApplicationFilters);
}
for (i = this._aTreeKeyProperties.length - 1; i >= 0; i--) {
sKeyProperty = this._aTreeKeyProperties[i];
if (!sKeySelect) {
sKeySelect = sKeyProperty;
} else {
sKeySelect += "," + sKeyProperty;
}
aFilters.push(new Filter(
sKeyProperty, "EQ", oNode.context.getProperty(sKeyProperty)
));
}
aFilters.push(new Filter(
this.oTreeProperties["hierarchy-level-for"], "LE", this.getNumberOfExpandedLevels()
));
mUrlParameters = jQuery.extend({}, this.mParameters);
mUrlParameters.select = sKeySelect +
"," + this.oTreeProperties["hierarchy-node-for"] +
"," + this.oTreeProperties["hierarchy-node-descendant-count-for"] +
"," + this.oTreeProperties["hierarchy-drill-state-for"] +
"," + this.oTreeProperties["hierarchy-preorder-rank-for"];
// request the magnitude and preorder
this.oModel.read(this.getPath(), {
context: this.oContext,
urlParameters: this.oModel.createCustomParams(mUrlParameters),
filters: [new Filter({
filters: aFilters,
and: true
})],
sorters: aSorters,
groupId: sGroupId,
success: successHandler,
error: errorHandler
});
};
ODataTreeBindingFlat.prototype._generateSiblingsPositionRequest = function(oNode, mParameters) {
var sGroupId, mUrlParameters, successHandler, errorHandler;
// aFilters = [], aSorters = this.aSorters || [];
if (mParameters) {
sGroupId = mParameters.groupId || this.sGroupId;
successHandler = mParameters.success;
errorHandler = mParameters.error;
}
/* Filtering not possible as long as we request SiblingsPosition via GET Entity instead of GET Entity Set (like Preorder Position)
if (this.aApplicationFilters) {
aFilters = aFilters.concat(this.aApplicationFilters);
}
aFilters.push(new Filter(
this.oTreeProperties["hierarchy-node-for"], "EQ", oNode.context.getProperty(this.oTreeProperties["hierarchy-node-for"])
));
*/
mUrlParameters = jQuery.extend({}, this.mParameters);
mUrlParameters.select = this.oTreeProperties["hierarchy-sibling-rank-for"];
// request the siblings position for moved nodes only as siblings position are already available for added nodes
this.oModel.read(oNode.context.getPath(), {
urlParameters: this.oModel.createCustomParams(mUrlParameters),
// filters: [new Filter({
// filters: aFilters,
// and: true
// })],
// sorters: aSorters,
groupId: sGroupId,
success: successHandler,
error: errorHandler
});
};
/**
* Checks if a node is on the top level of the hierarchy.
*/
ODataTreeBindingFlat.prototype._nodeIsOnTopLevel = function (oNode) {
if (oNode && oNode.serverIndex >= 0) {
var bParentIsNull = oNode.parent == null;
if (bParentIsNull) {
if (oNode.originalLevel == this._iLowestServerLevel) {
return true;
} else {
return false;
}
}
} else {
jQuery.sap.log.warning("ODataTreeBindingFlat.nodeIsOnTopLevel: Node is not defined or not a server-indexed node.");
}
};
/**
* Deletes a node. Two cases which have to be checked:
* 1. Created node: it will NOT be created anymore.
* 2. Existing server-node: it will be deleted.
*/
ODataTreeBindingFlat.prototype._generateDeleteRequest = function (oNode) {
var oContext = oNode.context;
if (oNode.nodeState.added) {
this.oModel.deleteCreatedEntry(oContext);
} else {
var oDeleteRequestHandle = this.oModel.remove(oContext.getPath(), {
groupId: this._getCorrectChangeGroup(),
refreshAfterChange: false
});
return oDeleteRequestHandle;
}
};
ODataTreeBindingFlat.prototype._filterChangeForServerSections = function(oOptimizedChanges) {
var oChanges = {};
oChanges.removed = oOptimizedChanges.removed.filter(function(oRemovedNode) {
return !oRemovedNode.isDeepOne;
});
oChanges.added = oOptimizedChanges.added.filter(function(oAddedNode) {
return !oAddedNode.isDeepOne;
});
oOptimizedChanges.moved.forEach(function(oMovedNode) {
if (!oMovedNode.newIsDeepOne) {
oChanges.added.push(oMovedNode);
}
if (!oMovedNode.isDeepOne) { // "Original" is the state at the time of removal
oChanges.removed.push(oMovedNode);
}
});
return oChanges;
};
ODataTreeBindingFlat.prototype._filterChangesForDeepSections = function(oOptimizedChanges) {
var mChanges = {};
oOptimizedChanges.removed.forEach(function(oRemovedNode) {
var oParent;
if (oRemovedNode.isDeepOne) {
oParent = oRemovedNode.parent;
if (!mChanges[oParent.key]) {
mChanges[oParent.key] = {
added: [],
removed: []
};
}
mChanges[oParent.key].removed.push(oRemovedNode);
}
});
oOptimizedChanges.added.forEach(function(oAddedNode) {
var oParent;
if (oAddedNode.isDeepOne) {
oParent = oAddedNode.parent;
if (!mChanges[oParent.key]) {
mChanges[oParent.key] = {
added: [],
removed: []
};
}
mChanges[oParent.key].added.push(oAddedNode);
}
});
oOptimizedChanges.moved.forEach(function(oMovedNode) {
var oParent;
if (oMovedNode.newIsDeepOne) {
oParent = oMovedNode.parent;
if (!mChanges[oParent.key]) {
mChanges[oParent.key] = {
added: [],
removed: []
};
}
mChanges[oParent.key].added.push(oMovedNode);
}
if (oMovedNode.isDeepOne) { // "Original" is the state at the time of removal
oParent = oMovedNode.originalParent;
if (!mChanges[oParent.key]) {
mChanges[oParent.key] = {
added: [],
removed: []
};
}
mChanges[oParent.key].removed.push(oMovedNode);
}
});
return mChanges;
};
ODataTreeBindingFlat.prototype._optimizeOptimizedChanges = function(oOptimizedChanges) {
var aAddedNodes,
that = this;
// TODO: Add unit test for this function
aAddedNodes = oOptimizedChanges.added.slice();
aAddedNodes.sort(function(a, b) {
var aIsDeep = a.newIsDeepOne !== undefined ? a.newIsDeepOne : a.isDeepOne,
bIsDeep = b.newIsDeepOne !== undefined ? b.newIsDeepOne : b.isDeepOne;
if (aIsDeep && bIsDeep) {
return 0;
}
if (aIsDeep) {
return 1; // move deep nodes to the end
}
if (bIsDeep) {
return -1;
}
return a.context.getProperty(that.oTreeProperties["hierarchy-preorder-rank-for"]) - b.context.getProperty(that.oTreeProperties["hierarchy-preorder-rank-for"]);
});
var iContainingIndex = -1;
aAddedNodes = aAddedNodes.filter(function(oNode, idx) {
if (oNode.newIsDeepOne !== undefined ? oNode.newIsDeepOne : oNode.isDeepOne) {
return true; // Always keep the deep nodes
}
if (idx <= iContainingIndex) {
return false; // Node is part of one of the preceding nodes magnitude range
}
var iMagnitude = oNode.context.getProperty(that.oTreeProperties["hierarchy-node-descendant-count-for"]);
if (iMagnitude) {
iContainingIndex = idx + iMagnitude;
}
return true;
});
return {
added: aAddedNodes,
removed: oOptimizedChanges.removed,
moved: oOptimizedChanges.moved
};
};
ODataTreeBindingFlat.prototype._updateNodeInfoAfterSave = function(oNode) {
// TODO: check whether the binding updates the property if the server returns 404 for this sub request
var bIsDeepOne = oNode.context.getProperty(this.oTreeProperties["hierarchy-preorder-rank-for"]) === undefined;
if (oNode.isDeepOne === undefined) {
// Added node
oNode.isDeepOne = bIsDeepOne;
} else {
// Moved node
oNode.newIsDeepOne = bIsDeepOne;
}
var bInitiallyCollapsed = oNode.context.getProperty(this.oTreeProperties["hierarchy-drill-state-for"]) === "collapsed";
if (oNode.initiallyCollapsed === undefined) {
// Added node
oNode.initiallyCollapsed = bInitiallyCollapsed;
} else {
// Moved node
oNode.newInitiallyCollapsed = bInitiallyCollapsed;
}
};
ODataTreeBindingFlat.prototype._requestExtraInfoForAddedNodes = function(aAdded) {
var aPromises = [],
that = this;
// Request the preorder position for each added node to determine whether the added node
// is a server-index or a deep node and whether it's initially collapsed
// The requests are wrapped into one batch using the default group id and the
aAdded.forEach(function(oNode) {
var p = new Promise(function (resolve, reject) {
that._generatePreorderPositionRequest(oNode, {
success: resolve,
error: reject
});
});
aPromises.push(p);
});
// process all sub requests no matter it succeeds or fails
aPromises = aPromises.map(function(pPromise) {
return pPromise.then(function(aResponseData) {
return {
responseData: aResponseData
};
}, function(oError) {
return {
error: oError
};
});
});
return Promise.all(aPromises).then(function(aData) {
var iAborted = 0;
aData.forEach(function(oData) {
if (oData.error) { // Error occured
// The request is aborted if statusCode is set with 0
if (oData.error.statusCode === 0) {
iAborted++;
} else {
throw new Error("Tree state restoration request failed. Complete or partial tree state might get lost. Error: " +
(oData.error.message.value || oData.error.message));
}
}
});
return iAborted === 0;
});
};
ODataTreeBindingFlat.prototype._restoreTreeState = function(oOptimizedChanges) {
var that = this;
oOptimizedChanges = oOptimizedChanges || {
creationCancelled: [],
added: [],
removed: [],
moved: []
};
this.fireDataRequested();
// Restore tree state is done in the following steps:
// 1. Request preorder position for added nodes (if there's added node) _requestExtraInfoForAddedNodes
// 2. Reload the loaded sections before save action (server index and deep) and set the collapse state _executeRestoreTreeState
return this._requestExtraInfoForAddedNodes(oOptimizedChanges.added).then(function(bNoAbort) {
if (bNoAbort) {
return that._executeRestoreTreeState(oOptimizedChanges).then(function(aData) {
if (aData) {
that._fireRefresh({reason: ChangeReason.Refresh});
that.fireDataReceived({data: aData});
return aData;
}
});
}
});
};
/**
* First collects all of the loaded server-index node and deep node sections. It then reloads all of them and merges
* them into the inner structure. It also takes care of expansion state and restore it after a node is reloaded.
*
* @return {Promise} The promise resolves if all reload requests succeed, otherwise it's rejected.
* The resolved and rejected parameter share the same structure. Both of them are an array of elements.
* Each of the element is an object which has either the responseData or the error property set. If the
* corresponding request succeeds, the responseData property is set with an object which has the
* calculated iSkip, iTop and the loaded content under property oData. Otherwise the error property is
* set with the error object which is returned from the server.
*/
ODataTreeBindingFlat.prototype._executeRestoreTreeState = function (oOptimizedChanges) {
var iCollapsedNodesCount,
oSection, aSections, oDeepNodeSection, oChildSection,
mCollapsedKeys,
aPromises,
i, j, k, l,
oChanges,
mDeepChanges,
that = this;
oOptimizedChanges.added.forEach(this._updateNodeInfoAfterSave.bind(this));
oOptimizedChanges.moved.forEach(this._updateNodeInfoAfterSave.bind(this));
aPromises = [];
// Collect server-index sections
aSections = this._collectServerSections(this._aNodes);
oOptimizedChanges = this._optimizeOptimizedChanges(oOptimizedChanges);
oChanges = this._filterChangeForServerSections(oOptimizedChanges);
this._adaptSections(aSections, oChanges);
// Request server-index nodes
// (for all loaded server-index sections)
for (i = 0; i < aSections.length; i++) {
oSection = aSections[i];
aPromises.push(this._restoreServerIndexNodes(oSection.iSkip, oSection.iTop, i === 0 /* request inline count */));
}
// Request children
// (for expanded nodes on intial-expand-level and expanded deep nodes)
var aDeepNodeSections = this._collectDeepNodes();
mDeepChanges = this._filterChangesForDeepSections(oOptimizedChanges);
for (j = 0; j < aDeepNodeSections.length; j++) {
oDeepNodeSection = aDeepNodeSections[j];
if (mDeepChanges) {
oChanges = mDeepChanges[oDeepNodeSection.oParentNode.key];
if (oChanges) {
this._adaptSections(oDeepNodeSection.aChildSections, oChanges, {
indexName: "positionInParent",
ignoreMagnitude: true
});
}
}
for (k = 0; k < oDeepNodeSection.aChildSections.length; k++) {
oChildSection = oDeepNodeSection.aChildSections[k];
aPromises.push(this._restoreChildren(oDeepNodeSection.oParentNode, oChildSection.iSkip, oChildSection.iTop));
}
}
mCollapsedKeys = {};
for (l = 0; l < this._aCollapsed.length; l++) {
mCollapsedKeys[this._aCollapsed[l].key] = true;
}
iCollapsedNodesCount = this._aCollapsed.length;
// Dump all data
this.resetData();
function restoreCollapseState() {
if (iCollapsedNodesCount > 0) {
that._map(function (oNode, oRecursionBreaker) {
if (oNode && mCollapsedKeys[oNode.key]) {
that.collapse(oNode, true);
iCollapsedNodesCount--;
if (iCollapsedNodesCount === 0) {
oRecursionBreaker.broken = true;
}
}
});
}
}
// process all sub requests no matter it succeeds or fails
aPromises = aPromises.map(function(pPromise) {
return pPromise.then(function(aResponseData) {
return {
responseData: aResponseData
};
}, function(oError) {
return {
error: oError
};
});
});
return Promise.all(aPromises).then(function(aData) {
var iAborted = 0;
aData.forEach(function(oData) {
if (oData.error) { // Error occured
// The request is aborted if statusCode is set with 0
if (oData.error.statusCode === 0) {
iAborted++;
} else {
throw new Error("Tree state restoration request failed. Complete or partial tree state might get lost. Error: " +
(oData.error.message.value || oData.error.message));
}
}
});
// If all requests are aborted, the 'dataReceived' event shouldn't be fired
if (iAborted < aData.length) {
// Restore collapse state
restoreCollapseState();
return aData;
}
});
};
/**
* Collects the loaded server-index node sections. If an element in the <code>aNodes</code>
* isn't undefined, it's counted as loaded and is collected in one loaded section.
* Otherwise the element is treated as unloaded node.
*
* @param {array} The nodes array where loaded sections are collected
* @return {array} The loaded sections. Each section is represented as an element in this array.
* The element has the following two properties: iSkip and iTop.
*/
ODataTreeBindingFlat.prototype._collectServerSections = function (aNodes) {
var aSections = [];
var oSection;
for (var i = 0; i < aNodes.length; i++) {
if (aNodes[i] !== undefined) {
if (!oSection) {
oSection = {
iSkip: i,
iTop: 1
};
aSections.push(oSection);
} else {
oSection.iTop++;
}
} else {
oSection = null;
}
}
return aSections;
};
ODataTreeBindingFlat.prototype._adaptSections = function (aSections, oChanges, oConfig) {
var aRemoved = oChanges.removed || [],
aAdded = oChanges.added || [],
sIndexName = (oConfig && oConfig.indexName) || "serverIndex",
oNode, oSection, oAdded,
iRestLength, iRemovedLength, iRemovedNodeCount = 0, iMagnitude, iPosition, iPendingRemoveEnd, iNextPendingRemoveEnd, iPendingRemoveLength,
iAddedLength,
iNextDelta, iCurrentDelta = 0, iTopDelta, sPositionAnnot,
aAddedIndices = [];
// collect the position of the added nodes
for (var l = aAdded.length - 1; l >= 0; l--) {
oNode = aAdded[l];
if (oNode.newIsDeepOne !== undefined ? oNode.newIsDeepOne : oNode.isDeepOne) { // Only moved nodes have a "newIsDeepNode" attribute
// Deep node
sPositionAnnot = this.oTreeProperties["hierarchy-sibling-rank-for"];
} else {
// Server index node
sPositionAnnot = this.oTreeProperties["hierarchy-preorder-rank-for"];
if (oNode.newInitiallyCollapsed !== undefined ? !oNode.newInitiallyCollapsed : !oNode.initiallyCollapsed) {
iMagnitude = oNode.context.getProperty(this.oTreeProperties["hierarchy-node-descendant-count-for"]);
}
}
iPosition = oNode.context.getProperty(sPositionAnnot);
if (iPosition === undefined) {
// TODO: Throw error or compensate?
jQuery.sap.log.warning("ODataTreeBindingFlat", "Missing " + sPositionAnnot + " value for node " + oNode.key);
break;
}
aAddedIndices.push({
position: iPosition,
magnitude: iMagnitude || 0,
assignedToSection: false
});
}
for (var i = 0; i < aSections.length; i++) {
oSection = aSections[i];
iNextDelta = iCurrentDelta;
iPendingRemoveEnd = iNextPendingRemoveEnd;
iNextPendingRemoveEnd = 0;
iTopDelta = 0;
for (var j = aRemoved.length - 1; j >= 0; j--) {
oNode = aRemoved[j];
iPosition = oNode[sIndexName];
if (iPosition >= oSection.iSkip && iPosition <= oSection.iSkip + oSection.iTop) { // Check if node is in section
if (sIndexName === "serverIndex") {
// Special handling for generated server index nodes.
// Service generates leaf nodes in case a nodes last child is getting removed.
// Not relevant for deep nodes. No restore action necessary if all child nodes got removed.
// To handle potentially generated server index nodes replacing removed nodes, we enhance all server index
// sections by the amount of removed nodes (ignoring their child nodes, i.e. their magnitude).
iRemovedNodeCount++;
}
iMagnitude = (oConfig && oConfig.ignoreMagnitude) ? 0 : this._getInitialMagnitude(oNode);
iRemovedLength = (1 + iMagnitude);
// o---------> the node o is removed, the -------> means the children of node o
// ----------------------------- oSection
// |--------| the length of this range is the iRestLenth
// The amount of nodes within the oSection which appear after the oRemovedNode and are still left after the removal of the oRemoveNode
iRestLength = (oSection.iSkip + oSection.iTop) - iPosition - iRemovedLength;
if (iRestLength > 0) {
// if there are still nodes left after the remove, the front part and the back part
// slide together with the same iSkip
// The iTop is calculated by adding the length of the two parts together
iTopDelta -= iRemovedLength;
} else {
// if there's no nodes left after the remove, the front part is reserved when it's length is greater than 0
iTopDelta -= (oSection.iSkip + oSection.iTop) - iPosition;
if (iRestLength < 0) { // Must happen never or exactly once per section
iNextPendingRemoveEnd = iPosition + iRemovedLength;
}
}
iNextDelta -= iRemovedLength;
}
}
if (oSection.iSkip <= iPendingRemoveEnd) {
iPendingRemoveLength = oSection.iSkip - iPendingRemoveEnd;
iTopDelta += iPendingRemoveLength;
if (oSection.iTop + iTopDelta < 0) {
iNextPendingRemoveEnd = iPendingRemoveEnd;
}
}
oSection.iSkip += iCurrentDelta;
oSection.iTop += iTopDelta;
if (oSection.iTop > 0) { // Process added nodes with updated section range (should equal server indices now)
iCurrentDelta = 0;
iTopDelta = 0;
// calculate the influence on the sections from the added nodes
for (var k = 0; k < aAddedIndices.length; k++) {
oAdded = aAddedIndices[k];
iPosition = oAdded.position;
iAddedLength = (oConfig && oConfig.ignoreMagnitude) ? 1 : oAdded.magnitude + 1;
if (iPosition >= oSection.iSkip && iPosition <= oSection.iSkip + oSection.iTop) {
iTopDelta += iAddedLength;
aAddedIndices[k].assignedToSection = true;
} else if (iPosition < oSection.iSkip) {
iCurrentDelta += iAddedLength;
}
}
oSection.iSkip += iCurrentDelta;
oSection.iTop += iTopDelta;
oSection.iTop += iRemovedNodeCount; // Enhance section by amount of so far removed nodes. Every removed node might get replaced with a generated leaf node by the service
}
if (oSection.iTop <= 0) {
aSections.splice(i, 1);
i--;
}
iCurrentDelta = iNextDelta;
}
// collect the indices of the added nodes which aren't included in any of aSections
// and insert a new section which contains the node into aSections
for (var m = 0; m < aAddedIndices.length; m++) {
oAdded = aAddedIndices[m];
iAddedLength = (oConfig && oConfig.ignoreMagnitude) ? 1 : oAdded.magnitude + 1;
if (!oAdded.assignedToSection) {
aSections.push({
iSkip: oAdded.position,
iTop: iAddedLength
});
}
}
aSections.sort(function(a, b) {
return a.iSkip - b.iSkip;
});
// merge the adjacent sections in aSection
for (var n = 0; n < aSections.length; n++) {
if (n + 1 < aSections.length) {
oSection = aSections[n];
var oNextSection = aSections[n + 1];
if (oSection.iSkip + oSection.iTop === oNextSection.iSkip) {
oSection.iTop += oNextSection.iTop;
aSections.splice(n + 1, 1);
n--;
}
}
}
};
ODataTreeBindingFlat.prototype._optimizeChanges = function () {
var aRemoved = [],
aCreationCancelled = [],
aAdded = [],
aMoved = [];
// removal check function for the parent-chain of a node
var bIsRemovedInParent = false;
var fnCheckRemoved = function(oNode, oBreaker) {
if (oNode.nodeState.removed && !oNode.nodeState.reinserted) {
bIsRemovedInParent = true;
oBreaker.broken = true;
}
};
// Step (1)
// --------------------------------------------------------------------
// Iterate all changed nodes and check their current/new parent chain.
// Keep track of all nodes which are candidates for a DELETE requests.
// New (and wrongly) created UI-only nodes are removed directly, if
// one of their current parent nodes is also removed.
var aPotentiallyRemovedNodes = [];
var fnTrackRemovedNodes = function (oNode) {
// server indexed nodes and deep nodes
if ((oNode.isDeepOne || oNode.serverIndex >= 0) && aPotentiallyRemovedNodes.indexOf(oNode) == -1) {
aPotentiallyRemovedNodes.push(oNode);
}
// cancel create requests for removed new nodes
if (oNode.nodeState.added) {
aCreationCancelled.push(oNode);
}
};
this._aAllChangedNodes.forEach(function (oNode) {
bIsRemovedInParent = false;
this._up(oNode, fnCheckRemoved, false /* current/new parent */);
// at least one of the parents of the node is removed
if (bIsRemovedInParent) {
fnTrackRemovedNodes(oNode);
} else {
// if none of the parents are removed, but the node itself is removed,
// we probably have reached the top-level, in this case the node of course shall also be removed
if (oNode.nodeState.removed && !oNode.nodeState.reinserted) {
// Node is removed)
fnTrackRemovedNodes(oNode);
} else if (oNode.nodeState.added) {
// Node got added. Parent annotation still needs to be set
aAdded.push(oNode);
} else {
// Node is moved
// so we have to change the parent annotation value
aMoved.push(oNode);
}
}
}.bind(this));
// Step (2): Sort nodes based on their related server-index.
aPotentiallyRemovedNodes.sort(function (a, b) {
var iA = this._getRelatedServerIndex(a);
var iB = this._getRelatedServerIndex(b);
jQuery.sap.assert(iA != undefined, "_generateSubmitData: (containing) Server-Index not found for node 'a'");
jQuery.sap.assert(iB != undefined, "_generateSubmitData: (containing) Server-Index not found node 'b'");
// deep nodes are inside the same containing server-index --> sort them first by their level. If they are under
// the same parent, sort them using their position in the parent
// this way we can make sure, that deeper nodes are sorted after higher-leveled ones
if (iA == iB && a.isDeepOne && b.isDeepOne) {
if (a.parent === b.parent) {
return a.positionInParent - b.positionInParent;
} else {
return a.originalLevel - b.originalLevel;
}
}
return iA - iB; // ascending
}.bind(this));
// Step (3): Create actual DELETE requests from a list of candidates.
// ----------------------------------------------------------------------
// Check if a node is deleted inside its old (server-side) parent chain.
// A node is deleted in its old parent chain, if at least one of its
// parent nodes was removed but not reinserted.
// The _up() function ends under two conditions:
// 1. if a node is not deleted at all
// 2. once the first deleted parent node is found
// Only nodes which are not deleted implicitly via their parent, need a DELETE request.
var fnNodeIsDeletedInOldParent = function (oDeletedNode) {
var bIsDeleted = false;
this._up(oDeletedNode, function (oParentNode, oBreak) {
if (oParentNode.nodeState.removed && !oParentNode.nodeState.reinserted) {
bIsDeleted = true;
oBreak.broken = true;
}
}, true /* original/old parent */);
return bIsDeleted;
}.bind(this);
// process all potentially deleted nodes
for (var i = 0; i < aPotentiallyRemovedNodes.length; i++) {
var oDeletedNode = aPotentiallyRemovedNodes[i];
// deep nodes can be deleted depending on their original parent
if (!fnNodeIsDeletedInOldParent(oDeletedNode)) {
aRemoved.push(oDeletedNode);
}
}
return {
removed: aRemoved,
creationCancelled: aCreationCancelled,
added: aAdded,
moved: aMoved
};
};
/**
* Collects the loaded deep nodes in the whole tree.
*
* @return {array} Each element in the array represents all loaded children under a node.
* The element has the following two properties: oParentNode and aChildSections.
* oParentNode is the node where the deep nodes are collected and aChildSections
* represents the loaded deep node sections under the oParentNode. Each element
* in the aChildSections has these two properties: iSkip and iTop
*/
ODataTreeBindingFlat.prototype._collectDeepNodes = function () {
var aDeepNodes = [], that = this;
this._map(function(oNode) {
if (oNode && oNode.nodeState.expanded && (
oNode.initiallyCollapsed || // server index nodes on the initial expansion level
oNode.isDeepOne // deep nodes
)) {
aDeepNodes.push({
oParentNode: oNode,
aChildSections: that._collectServerSections(oNode.children)
});
}
});
return aDeepNodes;
};
/**
* Makes sure that the changed node is only tracked once.
*/
ODataTreeBindingFlat.prototype._trackChangedNode = function (oNode) {
if (this._aAllChangedNodes.indexOf(oNode) == -1) {
this._aAllChangedNodes.push(oNode);
}
};
/**
* @see sap.ui.model.odata.v2.ODataTreebinding#addContexts
*/
ODataTreeBindingFlat.prototype.addContexts = function (oParentContext, vContextHandles) {
var oNodeInfo = this._findNodeByContext(oParentContext),
oNewParentNode = oNodeInfo.node,
oModel = this.getModel(),
oNewHandle,
oContext;
jQuery.sap.assert(oParentContext && vContextHandles, "ODataTreeBinding.addContexts() was called with incomplete arguments!");
// we can only add nodes if we have a valid parent node
if (oNewParentNode) {
this._bReadOnly = false;
// if a node is marked as a leaf, the node should be marked as collapsed after getting a child.
if (oNewParentNode.nodeState && oNewParentNode.nodeState.isLeaf) {
oNewParentNode.nodeState.isLeaf = false;
oNewParentNode.nodeState.collapsed = true;
}
// check if we have a single context or an array of contexts
if (!jQuery.isArray(vContextHandles)) {
if (vContextHandles instanceof sap.ui.model.Context) {
vContextHandles = [vContextHandles];
} else {
jQuery.sap.log.warning("ODataTreeBinding.addContexts(): The child node argument is not of type sap.ui.model.Context.");
}
}
// returns a getSubtree function for the new subtree handles
// used as a closure around a given node, cannot be inside the for-loop below
var fnBuildGetSubtree = function (oFreshNode) {
return function () {
return [oFreshNode];
};
};
// IMPORTANT:
// We need to reverse the order of the input child vContextHandles array.
// The reason is, that we later always "unshift" the subtree-handles to the addedSubtree list of the parent node.
// This is done so the newly added nodes are added to the top of the subtree.
// At this positon they are the most likely to be visible in the TreeTable.
vContextHandles = vContextHandles.slice();
vContextHandles.reverse();
// seperate existing nodes/subtress from the newly created ones
for (var j = 0; j < vContextHandles.length; j++) {
var oContext = vContextHandles[j];
if (!oContext || !(oContext instanceof sap.ui.model.Context)) {
jQuery.sap.log.warning("ODataTreeBindingFlat.addContexts(): no valid child context given!");
return;
}
// look up the context for a cut out subtree handle
var oNewHandle = this._mSubtreeHandles[oContext.getPath()];
// set unique node ID if the context was created and we did not assign an ID yet
this._ensureHierarchyNodeIDForContext(oContext);
// We have a subtree handle for the given context.
// This means we have a cut out subtree and can re-insert it directly
if (oNewHandle && oNewHandle._isRemovedSubtree) {
jQuery.sap.log.info("ODataTreeBindingFlat.addContexts(): Existing context added '" + oContext.getPath() + "'");
// set the parent node for the newly inserted sub-tree to match the new parent
oNewHandle._oNewParentNode = oNewParentNode;
// mark the node as reinserted
oNewHandle._oSubtreeRoot.nodeState.reinserted = true;
// keep track of the new and the original parent of a reinserted node (used for index-, selection- and submit-request-calculations)
oNewHandle._oSubtreeRoot.originalParent = oNewHandle._oSubtreeRoot.originalParent || oNewHandle._oSubtreeRoot.parent;
oNewHandle._oSubtreeRoot.parent = oNewParentNode;
// cyclic reference from the subtreeRoot to the subtreeHandle
// --> used for removing the subtreeHandle from the addedSubtree collection of the new parent node (in #removeContexts())
oNewHandle._oSubtreeRoot.containingSubtreeHandle = oNewHandle;
// update parent property
oContext = oNewHandle.getContext();
// track root node as changed
this._trackChangedNode(oNewHandle._oSubtreeRoot);
// clean cut out subtree handles, if the context is later removed from the binding again,
// we simply re-add it with updated subtree data
this._mSubtreeHandles[oContext.getPath()];
} else {
// Context is unknown to the binding --> new context
// TODO: What to do with contexts, which are not created by this binding?
jQuery.sap.log.info("ODataTreeBindingFlat.addContexts(): Newly created context added.");
this._ensureHierarchyNodeIDForContext(oContext);
var oFreshNode = {
context: oContext,
key: oModel.getKey(oContext),
parent: oNewParentNode,
nodeState: {
isLeaf: true, // by default a newly created context is a leaf
collapsed: false,
expanded: false,
selected: false,
added: true // mark the node as newly added
},
addedSubtrees: [],
children: [],
magnitude: 0
// no level? --> the level information will be maintained during the tree traversal (via _map)
};
// track root node as changed
this._trackChangedNode(oFreshNode);
// separately track the node as added
this._aAdded.push(oFreshNode);
// push the newly added subtree to the parent node
oNewHandle = {
_getSubtree: fnBuildGetSubtree(oFreshNode),
_oSubtreeRoot: null, // no subtree root if the contexts are newly inserted
_oNewParentNode: oNewParentNode
};
}
// update containing-server index for the newly added subtree
// TODO: Check if this information can be used productively, right now it's only used for debugging
oNewHandle._iContainingServerIndex = oNewParentNode.serverIndex || oNewParentNode.containingServerIndex;
// finally add the new subtree handle to the existing parent node's addedSubtree list
oNewParentNode.addedSubtrees.unshift(oNewHandle);
// keep track of server-indexed node changes (used e.g. for index- and selection-calculation
if (oNewParentNode.serverIndex !== undefined) {
this._aNodeChanges[oNewParentNode.serverIndex] = true;
}
}
// clear cache to make sure findNode etc. don't deliver wrong nodes (index is shifted due to adding)
this._aNodeCache = [];
this._cleanTreeStateMaps();
this._fireChange({reason: ChangeReason.Add});
} else {
jQuery.sap.log.warning("The given parent context could not be found in the tree. No new sub-nodes were added!");
}
};
/**
* Makes sure a newly created node gets a newly generated Hierarchy-Node ID.
* This will only happen once per newly created node/context.
*/
ODataTreeBindingFlat.prototype._ensureHierarchyNodeIDForContext = function (oContext) {
if (oContext) {
// set unique node ID if the context was created and we did not assign an ID yet
var sNewlyGeneratedID = oContext.getProperty(this.oTreeProperties["hierarchy-node-for"]);
if (oContext.bCreated && !sNewlyGeneratedID) {
this.oModel.setProperty(this.oTreeProperties["hierarchy-node-for"], jQuery.sap.uid(), oContext);
}
}
};
/**
* @see sap.ui.model.odata.v2.ODataTreebinding#removeContext
*/
ODataTreeBindingFlat.prototype.removeContext = function (oContext) {
var that = this;
var oNodeInfo = this._findNodeByContext(oContext);
var oNodeForContext = oNodeInfo.node;
var iIndex = oNodeInfo.index;
if (oNodeForContext) {
this._bReadOnly = false;
// mark the node as removed so the _map function will not regard it anymore
oNodeForContext.nodeState.removed = true;
this._aRemoved.push(oNodeForContext);
this._trackChangedNode(oNodeForContext);
// keep track of server-indexed node changes
if (oNodeForContext.serverIndex !== undefined) {
this._aNodeChanges[oNodeForContext.serverIndex] = true;
}
// node is the root of a removed/re-inserted subtree (handle)
// remove node from its new parent's addSubtrees collection (otherwise the node will still be rendered)
if (oNodeForContext.containingSubtreeHandle && oNodeForContext.parent != null) {
var iNewParentIndex = oNodeForContext.parent.addedSubtrees.indexOf(oNodeForContext.containingSubtreeHandle);
if (iNewParentIndex != -1) {
oNodeForContext.parent.addedSubtrees.splice(iNewParentIndex, 1);
oNodeForContext.nodeState.reinserted = false;
//TODO: Is reseting the parent a correct way to remove the node/subtree from the whole tree?
oNodeForContext.parent = null;
}
}
// clear cache to make sure findNode etc. don't deliver wrong nodes (index is shifted due to adding)
this._aNodeCache = [];
// remove selection for removed context
this.setNodeSelection(oNodeForContext, false);
this._cleanUpSelection(true);
this._cleanTreeStateMaps();
this._fireChange({reason: ChangeReason.Remove});
// Internal Subtree Handle API
// TODO: Use HierarchyNode ID instead of path? oContext.getProperty(this.oTreeProperties["hierarchy-node-for"])
this._mSubtreeHandles[oContext.getPath()] = {
_removedFromVisualIndex: iIndex,
_isRemovedSubtree: true,
_oSubtreeRoot: oNodeForContext,
_getSubtree: function () {
if (oNodeForContext.serverIndex != undefined && !oNodeForContext.initiallyCollapsed) {
//returns the nodes flat starting from the parent to the last one inside the magnitude range
return that._aNodes.slice(oNodeForContext.serverIndex, oNodeForContext.serverIndex + oNodeForContext.magnitude + 1);
} else {
// the node was initially collapsed or has no server-index (the deep ones)
return oNodeForContext;
}
},
getContext: function () {
return oContext;
},
// TODO: Maybe remove this
_restore: function () {
oNodeForContext.nodeState.removed = false;
var iNodeStateFound = that._aRemoved.indexOf(oNodeForContext);
if (iNodeStateFound != -1) {
that._aRemoved.splice(iNodeStateFound, 1);
}
// clear cache to make sure findNode etc. don't deliver wrong nodes (index is shifted due to adding)
this._aNodeCache = [];
that._cleanTreeStateMaps();
that._fireChange({reason: ChangeReason.Add});
}
};
return oContext;
} else {
jQuery.sap.log.warning("ODataTreeBinding.removeContexts(): The given context is not part of the tree. Was it removed already?");
}
};
//*********************************************
// Functions for index calculation *
//*********************************************
/**
* Gets the related server-index for the given node.
* Either the index of a server-indexed node or the server-index of a containing node (for deep noodes).
*/
ODataTreeBindingFlat.prototype._getRelatedServerIndex = function(oNode) {
if (oNode.serverIndex === undefined) {
return oNode.containingServerIndex;
} else {
return oNode.serverIndex;
}
};
/**
* Gets the node info for the given row-index.
* @param {int} iRowIndex
* @returns {{index:int}} node info for the given row-index
*/
ODataTreeBindingFlat.prototype.getNodeInfoByRowIndex = function(iRowIndex) {
var iCPointer = 0, iEPointer = 0, oNode, bTypeCollapse, iValidCollapseIndex = -1;
while (iCPointer < this._aCollapsed.length || iEPointer < this._aExpanded.length) {
if (this._aCollapsed[iCPointer] && this._aExpanded[iEPointer]) {
if (this._getRelatedServerIndex(this._aCollapsed[iCPointer]) > this._getRelatedServerIndex(this._aExpanded[iEPointer])) {
oNode = this._aExpanded[iEPointer];
iEPointer++;
bTypeCollapse = false;
} else {
oNode = this._aCollapsed[iCPointer];
iCPointer++;
bTypeCollapse = true;
}
} else if (this._aCollapsed[iCPointer]) {
oNode = this._aCollapsed[iCPointer];
iCPointer++;
bTypeCollapse = true;
} else {
oNode = this._aExpanded[iEPointer];
iEPointer++;
bTypeCollapse = false;
}
if (iRowIndex <= this._getRelatedServerIndex(oNode)) {
// the following collapsed and expanded nodes don't affect the node info
break;
}
if (bTypeCollapse) {
// collapse
if (!oNode.isDeepOne && !oNode.initiallyCollapsed && oNode.serverIndex > iValidCollapseIndex) {
iRowIndex += oNode.magnitude;
iValidCollapseIndex = oNode.serverIndex + oNode.magnitude;
}
} else {
// expand
if (oNode.serverIndex > iValidCollapseIndex) {
// only the expanded node on the defined expand level matters the index
if (!oNode.isDeepOne && oNode.initiallyCollapsed) {
iRowIndex -= oNode.magnitude;
}
if (iRowIndex <= oNode.serverIndex) {
// the searched node is under the current node
return this._calcDirectIndex(oNode, iRowIndex + oNode.magnitude - oNode.serverIndex - 1);
}
}
}
}
return {
index: iRowIndex
};
};
/**
* This method calculates the DIRECT parent and the child index of a node's nth descendant.
*/
ODataTreeBindingFlat.prototype._calcDirectIndex = function (oNode, index) {
var i, iMagnitude, oChild;
for (i = 0 ; i < oNode.children.length ; i++) {
oChild = oNode.children[i];
if (index === 0) {
return {
parent: oNode,
childIndex: i
};
}
iMagnitude = oChild ? oChild.magnitude : 0;
index--;
if (!oChild || oChild.nodeState.collapsed) {
continue;
}
if (index < iMagnitude) {
return this._calcDirectIndex(oChild, index);
} else {
index -= iMagnitude;
}
}
};
/**
* Retrieves the Row-Index for the given node.
* @param {Object} oNode
* @returns {int} Row-Index for the given node
*/
ODataTreeBindingFlat.prototype.getRowIndexByNode = function (oNode) {
var iDelta = 0;
var oChildNode;
var i;
if (oNode.isDeepOne) {
// traverse up through the parent chain to the last server indexed node
while (oNode.parent) {
// count the number of nodes which appear before the current one
iDelta += oNode.positionInParent + 1;
for (i = 0; i < oNode.positionInParent; i++) {
oChildNode = oNode.parent.children[i];
// if the deep node is expanded, the number of its children should also be counted
if (oChildNode && oChildNode.nodeState.expanded) {
iDelta += oChildNode.magnitude;
}
}
oNode = oNode.parent;
}
}
return this._calcIndexDelta(oNode.serverIndex) + oNode.serverIndex + iDelta;
};
/**
* Gets an array of node-infos for all selected nodes.
* A node info contains the node itself and a the current row-index for said node.
* @returns {Array}
*/
ODataTreeBindingFlat.prototype._getSelectedNodesInfo = function () {
var aNodesInfo = [];
//if we have no nodes selected, the selection info are empty
if (jQuery.isEmptyObject(this._mSelected)) {
return aNodesInfo;
}
var bIsVisible = true;
var fnCheckVisible = function(oNode, oBreaker) {
if (oNode.nodeState.collapsed || (oNode.nodeState.removed && !oNode.nodeState.reinserted)) {
bIsVisible = false;
oBreaker.broken = true;
}
};
for (var sKey in this._mSelected) {
var oSelectedNode = this._mSelected[sKey];
bIsVisible = true;
this._up(oSelectedNode, fnCheckVisible, false /*current/new parent*/);
// only find indices for visible nodes
if (bIsVisible) {
aNodesInfo.push({
node: oSelectedNode,
rowIndex: this.getRowIndexByNode(oSelectedNode)
});
}
}
aNodesInfo.sort(function(oNodeInfo1, oNodeInfo2) {
return oNodeInfo1.rowIndex - oNodeInfo2.rowIndex;
});
return aNodesInfo;
};
/**
* Calculate the index delta till a given server-index.
* Expanded nodes results in positive delta and collapsed note results in negative one.
*
* A collapsed node contributes to the delta when it meets the following conditions:
* 1. it's not a manually expanded node.
* 2. it's not contained in the range of another collapsed node
*
* An expanded node contributes to the delta when it meets the following conditions:
* 1. it's not expanded with the initial call which means it's either initially collapsed or manually loaded
* 2. none of its ancestor it's collapsed.
*/
ODataTreeBindingFlat.prototype._calcIndexDelta = function (iEndServerIndex) {
// collect all collapsed server indices and magnitude as a look-up table
// serverIndex + magnitude form a range for which we can check if there is a containment situation
var mCollapsedServerIndices = {};
this._aCollapsed.forEach(function (oNode) {
// only regard nodes with a server-index and not initially collapsed
if (oNode.serverIndex >= 0 && oNode.serverIndex < iEndServerIndex && !oNode.isDeepOne && !oNode.initiallyCollapsed) {
mCollapsedServerIndices[oNode.serverIndex] = oNode.magnitude;
}
});
// collapsed delta
var iLastCollapsedIndex = 0;
var iCollapsedDelta = 0;
for (var i = 0; i < this._aCollapsed.length; i++) {
var oCollapsedNode = this._aCollapsed[i];
if (this._getRelatedServerIndex(oCollapsedNode) >= iEndServerIndex) {
break;
}
if (!oCollapsedNode.isDeepOne) {
// if the collapsed node is not inside the last collapsed magnitude range, collapse it also
if (oCollapsedNode.serverIndex >= iLastCollapsedIndex && !oCollapsedNode.initiallyCollapsed) {
iCollapsedDelta -= oCollapsedNode.magnitude;
iLastCollapsedIndex = oCollapsedNode.serverIndex + oCollapsedNode.magnitude;
} else {
//ignore the node since it is contained in another one
}
} else {
// collapsed manually expanded nodes are ignored for collapse delta, since it is only applicable to the server provided magnitude
}
}
// expanded delta
var iExpandedDelta = 0;
var fnInCollapsedRange = function (oNode) {
var bIgnore = false;
var iContainingIndexToCheck = oNode.serverIndex || oNode.containingServerIndex;
for (var j in mCollapsedServerIndices) {
// if the expanded node is inside a collapsed range -> ignore it
if (iContainingIndexToCheck > j && iContainingIndexToCheck < j + mCollapsedServerIndices[j]) {
bIgnore = true;
break;
}
}
return bIgnore;
};
for (i = 0; i < this._aExpanded.length; i++) {
var oExpandedNode = this._aExpanded[i];
if (this._getRelatedServerIndex(oExpandedNode) >= iEndServerIndex) {
break;
}
// regard the real deep ones for the expanded delta
if (oExpandedNode.isDeepOne) {
// simply check if one of its parents is collapsed :)
var oParent = oExpandedNode.parent;
var bYep = false;
while (oParent) {
if (oParent.nodeState.collapsed) {
bYep = true;
break;
}
oParent = oParent.parent;
}
var bIgnore = fnInCollapsedRange(oExpandedNode);
// if not then regard the children for the expanded delta
if (!bYep && !bIgnore) {
iExpandedDelta += oExpandedNode.children.length;
}
} else if (oExpandedNode.initiallyCollapsed) {
// see if the node on the last auto-expand level is contained in a sub-tree of a collapsed server-indexed node
var bIgnore = fnInCollapsedRange(oExpandedNode);
if (!bIgnore) {
// still we have to check for a
iExpandedDelta += oExpandedNode.children.length;
}
}
}
return iExpandedDelta + iCollapsedDelta;
};
/**
* Sorts the given nodes array based on the server-index or a containing server-index.
*/
ODataTreeBindingFlat.prototype._sortNodes = function(aNodes) {
var fnSort = function (a, b) {
var iA = this._getRelatedServerIndex(a);
var iB = this._getRelatedServerIndex(b);
return iA - iB;
}.bind(this);
aNodes.sort(fnSort);
};
//*********************************************
// Events *
//*********************************************
/**
* Attach event-handler <code>fnFunction</code> to the 'selectionChanged' event of this <code>sap.ui.model.SelectionModel</code>.<br/>
* Event is fired if the selection of tree nodes is changed in any way.
*
* @param {object}
* [oData] The object, that should be passed along with the event-object when firing the event.
* @param {function}
* fnFunction The function to call, when the event occurs. This function will be called on the
* oListener-instance (if present) or in a 'static way'.
* @param {object}
* [oListener] Object on which to call the given function. If empty, this binding adapter is used.
*
* @return {sap.ui.model.SelectionModel} <code>this</code> to allow method chaining
* @protected
*/
ODataTreeBindingFlat.prototype.attachSelectionChanged = function(oData, fnFunction, oListener) {
this.attachEvent("selectionChanged", oData, fnFunction, oListener);
return this;
};
/**
* Detach event-handler <code>fnFunction</code> from the 'selectionChanged' event of this <code>sap.ui.model.SelectionModel</code>.<br/>
*
* The passed function and listener object must match the ones previously used for event registration.
*
* @param {function}
* fnFunction The function to call, when the event occurs.
* @param {object}
* oListener Object on which the given function had to be called.
* @return {sap.ui.model.SelectionModel} <code>this</code> to allow method chaining
* @protected
*/
ODataTreeBindingFlat.prototype.detachSelectionChanged = function(fnFunction, oListener) {
this.detachEvent("selectionChanged", fnFunction, oListener);
return this;
};
/**
* Fire event 'selectionChanged' to attached listeners.
*
* Expects following event parameters:
* <ul>
* <li>'leadIndex' of type <code>int</code> Lead selection index.</li>
* <li>'rowIndices' of type <code>int[]</code> Other selected indices (if available)</li>
* </ul>
*
* @param {object} mArguments the arguments to pass along with the event.
* @param {int} mArguments.leadIndex Lead selection index
* @param {int[]} [mArguments.rowIndices] Other selected indices (if available)
* @return {sap.ui.model.SelectionModel} <code>this</code> to allow method chaining
* @protected
*/
ODataTreeBindingFlat.prototype.fireSelectionChanged = function(mArguments) {
this.fireEvent("selectionChanged", mArguments);
return this;
};
/**
* Stub for the TreeBinding API -> not used for Auto-Expand paging in the TreeTable.
* Implementation see ODataTreeBinding (v2).
*/
ODataTreeBindingFlat.prototype.getRootContexts = function () {};
ODataTreeBindingFlat.prototype.getNodeContexts = function () {};
return ODataTreeBindingFlat;
}, /* bExport= */ true);
| {
"content_hash": "af2f7b48b728b7411032381ac1779e7b",
"timestamp": "",
"source": "github",
"line_count": 3949,
"max_line_length": 192,
"avg_line_length": 34.00278551532033,
"alnum_prop": 0.6896415618460346,
"repo_name": "cschuff/openui5",
"id": "4e3f7a83c74bcc9c44f3e7dc5bd0276609f4f255",
"size": "134300",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sap.ui.core/src/sap/ui/model/odata/ODataTreeBindingFlat.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2918722"
},
{
"name": "Gherkin",
"bytes": "17198"
},
{
"name": "HTML",
"bytes": "18167339"
},
{
"name": "Java",
"bytes": "84288"
},
{
"name": "JavaScript",
"bytes": "49673115"
}
],
"symlink_target": ""
} |
CREATE TABLE employees (
store_id INT NOT NULL
)
PARTITION BY RANGE (store_id + 100) (
PARTITION p0 VALUES LESS THAN (105),
PARTITION p1 VALUES LESS THAN (200),
PARTITION p3 VALUES LESS THAN MAXVALUE
);
insert into employees values(1);
insert into employees values(105);
insert into employees values(106);
select count(*) from employees;
select * from employees order by 1;
$integer,$105;
select * from employees where store_id = ? order by 1;
$integer,$1000005;
select * from employees where store_id < ? order by 1;
create class x ( id int);
insert into x values(10);
select * from x order by 1;
drop employees;
drop x;
commit;
--+ holdcas off;
| {
"content_hash": "759c54f9229fd5e5d02740df56a62b43",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 54,
"avg_line_length": 20.59375,
"alnum_prop": 0.7223065250379362,
"repo_name": "CUBRID/cubrid-testcases",
"id": "d0ab8caf7cd2d8f5f1583e13b564e9c954530378",
"size": "676",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "sql/_08_javasp/cases/5-1.sql",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PLSQL",
"bytes": "682246"
},
{
"name": "Roff",
"bytes": "23262735"
},
{
"name": "TSQL",
"bytes": "5619"
},
{
"name": "eC",
"bytes": "710"
}
],
"symlink_target": ""
} |
<bill session="115" type="h" number="2387" updated="2017-06-19T22:15:24Z">
<state datetime="2017-05-04">REFERRED</state>
<status>
<introduced datetime="2017-05-04"/>
</status>
<introduced datetime="2017-05-04"/>
<titles>
<title type="short" as="introduced">Worker Ownership, Readiness, and Knowledge Act</title>
<title type="short" as="introduced">Worker Ownership, Readiness, and Knowledge Act</title>
<title type="official" as="introduced">To establish an Employee Ownership and Participation Initiative, and for other purposes.</title>
<title type="display">Worker Ownership, Readiness, and Knowledge Act</title>
</titles>
<sponsor bioguide_id="P000598"/>
<cosponsors>
<cosponsor bioguide_id="D000620" joined="2017-05-04"/>
<cosponsor bioguide_id="P000034" joined="2017-06-08"/>
<cosponsor bioguide_id="P000607" joined="2017-05-04"/>
</cosponsors>
<actions>
<action datetime="2017-05-04">
<text>Introduced in House</text>
</action>
<action datetime="2017-05-04" state="REFERRED">
<text>Referred to the House Committee on Education and the Workforce.</text>
</action>
</actions>
<committees>
<committee subcommittee="" code="HSED" name="House Education and the Workforce" activity="Referral"/>
</committees>
<relatedbills>
<bill type="s" session="115" relation="unknown" number="1081"/>
</relatedbills>
<subjects>
<term name="Labor and employment"/>
</subjects>
<amendments/>
<committee-reports/>
</bill>
| {
"content_hash": "c72e001435dcb354f395e77eabab2cf0",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 139,
"avg_line_length": 39.921052631578945,
"alnum_prop": 0.6868820039551747,
"repo_name": "peter765/power-polls",
"id": "a392adc8d1a61f211cbd0a007b7d21ccb63afbef",
"size": "1517",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/bills/hr/hr2387/data.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "58567"
},
{
"name": "JavaScript",
"bytes": "7370"
},
{
"name": "Python",
"bytes": "22988"
}
],
"symlink_target": ""
} |
#include "basicparallel.hpp"
#include "map.hpp"
#include "common.hpp"
#include "streamingstat.tcc"
#include <map>
extern Clock *system_clock;
basic_parallel::basic_parallel( Map &map,
Allocate &alloc,
Schedule &sched,
volatile bool &exit_para )
: source_kernels( map.source_kernels ),
all_kernels( map.all_kernels ),
alloc( alloc ),
sched( sched ),
exit_para( exit_para )
{
/** nothing to do here, move along **/
}
void
basic_parallel::start()
{
using hash_t = std::uintptr_t;
std::map< hash_t, stats > hashmap;
//FIXME, need to add the code that'll limit this without a count
auto count( 0 );
while( ! exit_para )
{
auto &kernels( source_kernels.acquire() );
/**
* since we have to have a lock on the ports
* for both BFS and duplication, we'll mark
* the kernels inside of BFS and duplicate
* outside of it.
*/
std::vector< raft::kernel* > dup_list;
GraphTools::BFS( kernels,
[&]( raft::kernel *kernel,
void *data )
{
if( kernel->dup_enabled )
{
/** start checking stats **/
auto hash(
reinterpret_cast< std::uintptr_t >( kernel ) );
/** input stats **/
raft::streamingstat< float > in;
raft::streamingstat< float > out;
if( kernel->input.hasPorts() )
{
auto &input( kernel->input.getPortInfo() );
auto *fifo( input.getFIFO() );
in.update( fifo->size() / fifo->capacity() );
}
if( kernel->output.hasPorts() )
{
auto &output( kernel->output.getPortInfo() );
auto *fifo( output.getFIFO() );
out.update( fifo->size() / fifo->capacity() );
}
/** apply criteria **/
if( ( kernel->input.count() == 0 or
in.mean< float >() > .5 ) and
( out.mean< float >() < .5 or
kernel->output.count() == 0 ) )
{
hashmap[ hash ].occ_in++;
}
if( hashmap[ hash ].occ_in > 3 && count < 2 )
{
count++;
dup_list.emplace_back( kernel );
hashmap[ hash ].occ_in = 0;
}
}
},
nullptr );
source_kernels.release();
for( auto * kernel : dup_list )
{
/**
* FIXME, logic below only works for
* single input, single output..intended
* to get it working
*/
/** clone **/
auto *ptr( kernel->clone() );
/** attach ports **/
if( kernel->input.count() != 0 )
{
auto &old_port_in( kernel->input.getPortInfo() );
old_port_in.other_kernel->lock();
const auto portid(
old_port_in.other_kernel->addPort() );
auto &new_other_outport(
old_port_in.other_kernel->output.getPortInfoFor(
std::to_string( portid )
)
);
auto &new_port_in( ptr->input.getPortInfo() );
/**
* connecting a.y -> b.x
* new_other_outprt == port y on a
* new_port_in == port x on b
*/
alloc.allocate( new_other_outport,
new_port_in,
nullptr );
old_port_in.other_kernel->unlock();
}
if( kernel->output.count() != 0 )
{
auto &old_port_out( kernel->output.getPortInfo() );
old_port_out.other_kernel->lock();
const auto portid(
old_port_out.other_kernel->addPort() );
auto &new_other_inport(
old_port_out.other_kernel->input.getPortInfoFor(
std::to_string( portid ) ) );
auto &newoutport( ptr->output.getPortInfo() );
/**
* connecting b.y -> c.x
* newoutport == port y on b
* new_other_inport == port x on c
*/
alloc.allocate( newoutport,
new_other_inport,
nullptr );
old_port_out.other_kernel->unlock();
}
/** schedule new kernel **/
sched.scheduleKernel( ptr );
}
dup_list.clear();
std::chrono::microseconds dura( 100 );
std::this_thread::sleep_for( dura );
}
return;
}
| {
"content_hash": "4f59b22e6f8dfb4ca3c68354203574b0",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 80,
"avg_line_length": 36.59731543624161,
"alnum_prop": 0.3898771318540253,
"repo_name": "adishavit/RaftLib",
"id": "1063fb1f058ad30d716e7542c809be4cd70a32d5",
"size": "6144",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "basicparallel.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "52280"
},
{
"name": "C++",
"bytes": "527832"
},
{
"name": "Makefile",
"bytes": "5086"
},
{
"name": "Perl",
"bytes": "653"
}
],
"symlink_target": ""
} |
package com.gwidgets.api.leaflet.options;
import static jsinterop.annotations.JsPackage.GLOBAL;
import com.gwidgets.api.leaflet.Point;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
/**
* The Class DivIconOptions.
*
* @author <a href="mailto:zakaria.amine88@gmail.com">Zakaria Amine</a>
* @version $Id: $Id
*/
@JsType(isNative=true, namespace=GLOBAL, name="Object")
public class DivIconOptions {
/**
* Instantiates a new div icon options.
*/
private DivIconOptions() {
}
@JsProperty
private Point iconSize;
@JsProperty
private Point iconAnchor;
@JsProperty
private Point popUpAnchor;
@JsProperty
private String className;
@JsProperty
private String html;
/*****************************************
********************************************/
@JsProperty
private Point bgPos;
/**********************************************
*********************************************/
/*****************************************
********************************************/
@JsProperty
private String iconUrl;
/**********************************************
*********************************************/
@JsProperty
private String iconRetinaUrl;
/*****************************************
********************************************/
@JsProperty
private String shadowUrl;
/**********************************************
*********************************************/
@JsProperty
private String shadowRetinaUrl;
/**********************************************
*********************************************/
@JsProperty
private Point shadowSize;
/**********************************************
*********************************************/
@JsProperty
private Point shadowAnchor;
/**********************************************
*********************************************/
@JsProperty
private String pane;
/**********************************************
*********************************************/
@JsProperty
private String attribution;
/**********************************************
*********************************************/
/**
* Gets the size of the icon in pixels. Can be also set through CSS.
*
* @return the icon size
*/
@JsOverlay public final Point getIconSize() {
return this.iconSize;
}
/**
* Gets The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins.
*
* @return the icon anchor
*/
@JsOverlay public final Point getIconAnchor() {
return this.iconAnchor;
}
/**
* Gets The coordinates of the point from which popups will "open", relative to the icon anchor.
*
* @return the pop up anchor
*/
@JsOverlay public final Point getPopUpAnchor() {
return this.popUpAnchor;
}
/**
* Gets the custom class name assigned to the icon. 'leaflet-div-icon' by default.
*
* @return the class name
*/
@JsOverlay public final String getClassName() {
return this.className;
}
/**
* Gets the custom HTML code put inside the div element, empty by default.
*
* @return the html
*/
@JsOverlay public final String getHtml() {
return this.html;
}
/**
* <p>Getter for the field <code>bgPos</code>.</p>
*
* @return a {@link com.gwidgets.api.leaflet.Point} object
*/
@JsOverlay public final Point getBgPos() {
return this.bgPos;
}
/**
* <p>Getter for the field <code>iconUrl</code>.</p>
*
* @return a {@link java.lang.String} object
*/
@JsOverlay public final String getIconUrl() {
return this.iconUrl;
}
/**
* <p>Getter for the field <code>iconRetinaUrl</code>.</p>
*
* @return a {@link java.lang.String} object
*/
@JsOverlay public final String getIconRetinaUrl() {
return this.iconRetinaUrl;
}
/**
* <p>Getter for the field <code>shadowUrl</code>.</p>
*
* @return a {@link java.lang.String} object
*/
@JsOverlay public final String getShadowUrl() {
return this.shadowUrl;
}
/**
* <p>Getter for the field <code>shadowRetinaUrl</code>.</p>
*
* @return a {@link java.lang.String} object
*/
@JsOverlay public final String getShadowRetinaUrl() {
return this.shadowRetinaUrl;
}
/**
* <p>Getter for the field <code>shadowSize</code>.</p>
*
* @return a {@link com.gwidgets.api.leaflet.Point} object
*/
@JsOverlay public final Point getShadowSize() {
return this.shadowSize;
}
/**
* <p>Getter for the field <code>shadowAnchor</code>.</p>
*
* @return a {@link com.gwidgets.api.leaflet.Point} object
*/
@JsOverlay public final Point getShadowAnchor() {
return this.shadowAnchor;
}
/**
* <p>Getter for the field <code>pane</code>.</p>
*
* @return a {@link java.lang.String} object
*/
@JsOverlay public final String getPane() {
return this.pane;
}
/**
* <p>Getter for the field <code>attribution</code>.</p>
*
* @return a {@link java.lang.String} object
*/
@JsOverlay public final String getAttribution() {
return this.attribution;
}
/**
* The Class Builder.
*/
public static class Builder {
private Point iconSize;
private Point iconAnchor;
private Point popUpAnchor;
private String className;
private String html;
private Point bgPos;
private String iconUrl;
private String iconRetinaUrl;
private String shadowUrl;
private String shadowRetinaUrl;
private Point shadowSize;
private Point shadowAnchor;
private String pane;
private String attribution;
/**
* Instantiates a new builder. Takes the icon url as a required paramater.
*
* @param iconUrl the icon url
*/
public Builder(String iconUrl) {
this.iconUrl = iconUrl;
}
/**
* Size of the icon in pixels. Can be also set through CSS.
*
* @param iconSize the icon size
* @return the builder
*/
public Builder iconSize(Point iconSize){this.iconSize = iconSize; return this;}
/**
* The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins.
*
* @param iconAnchor the icon anchor
* @return the builder
*/
public Builder iconAnchor(Point iconAnchor){this.iconAnchor = iconAnchor; return this;}
/**
* The coordinates of the point from which popups will "open", relative to the icon anchor.
*
* @param popUpAnchor the pop up anchor
* @return the builder
*/
public Builder popUpAnchor(Point popUpAnchor){this.popUpAnchor = popUpAnchor; return this;}
/**
* A custom class name to assign to the icon. 'leaflet-div-icon' by default.
*
* @param className the class name
* @return the builder
*/
public Builder className(String className){this.className = className; return this;}
/**
* A custom HTML code to put inside the div element, empty by default.
*
* @param html the html
* @return the builder
*/
public Builder html(String html){this.html = html; return this;}
public Builder bgPos(Point bgPos){this.bgPos = bgPos; return this;}
public Builder iconRetinaUrl(String iconRetinaUrl){this.iconRetinaUrl = iconRetinaUrl; return this;}
public Builder shadowUrl(String shadowUrl){this.shadowUrl = shadowUrl; return this;}
public Builder shadowRetinaUrl(String shadowRetinaUrl){this.shadowRetinaUrl = shadowRetinaUrl; return this;}
public Builder shadowSize(Point shadowSize){this.shadowSize = shadowSize; return this;}
public Builder shadowAnchor(Point shadowAnchor){this.shadowAnchor = shadowAnchor; return this;}
public Builder pane(String pane){this.pane = pane; return this;}
public Builder attribution(String attribution){this.attribution = attribution; return this;}
/**
* Builds th DivIconOptions new instance
*
* @return the div icon options
*/
public DivIconOptions build(){
DivIconOptions options = new DivIconOptions();
if(this.iconSize != null)
options.iconSize = this.iconSize;
if(this.iconAnchor != null)
options.iconAnchor = this.iconAnchor;
if(this.popUpAnchor != null)
options.popUpAnchor = this.popUpAnchor;
if(this.className != null)
options.className = this.className;
if(this.html != null)
options.html = this.html;
if(this.iconUrl != null)
options.iconUrl = this.iconUrl;
if(this.bgPos != null)
options.bgPos = this.bgPos;
if(this.iconRetinaUrl != null)
options.iconRetinaUrl = this.iconRetinaUrl;
if(this.shadowUrl != null)
options.shadowUrl = this.shadowUrl;
if(this.shadowRetinaUrl != null)
options.shadowRetinaUrl = this.shadowRetinaUrl;
if(this.shadowSize != null)
options.shadowSize = this.shadowSize;
if(this.shadowAnchor != null)
options.shadowAnchor = this.shadowAnchor;
if(this.pane != null)
options.pane = this.pane;
if(this.attribution != null)
options.attribution = this.attribution;
return options;
}
}
}
| {
"content_hash": "e99fe2b09ed716875b9f2118b6fc5a0f",
"timestamp": "",
"source": "github",
"line_count": 381,
"max_line_length": 258,
"avg_line_length": 24.6246719160105,
"alnum_prop": 0.6012577275634193,
"repo_name": "gwidgets/gwty-leaflet",
"id": "f273e7a2f84cd0c0f8cc4608510ddb4727dd3b08",
"size": "9977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/gwidgets/api/leaflet/options/DivIconOptions.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13056"
},
{
"name": "Java",
"bytes": "439247"
},
{
"name": "JavaScript",
"bytes": "365294"
}
],
"symlink_target": ""
} |
import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { logout } from '../actions/authActions';
class NavigationBar extends React.Component {
logout(e) {
e.preventDefault();
this.props.logout();
}
render() {
const { isAuthenticated } = this.props.auth;
const username = localStorage.getItem('username');
// Navigation links if the user is authenticated and logged in
const userLinks = (
<ul className="nav navbar-nav navbar-right">
<li><Link to="/new-event">Add Event</Link></li>
<li><Link to="/scrape">Video Scrapes</Link></li>
<li><Link to="/dashboard">Dashboard</Link></li>
<li><Link to="/midi-archives">Midi Archives</Link></li>
<li><Link to="/">Hello, { this.props.user.username }</Link></li>
<li><a href="#" onClick={this.logout.bind(this)}>Logout</a></li>
</ul>
);
// Navigation links if the user is not logged in
const guestLinks = (
<ul className="nav navbar-nav navbar-right">
<li><Link to="/new-event">Add Event</Link></li>
<li><Link to="/scrape">Video Scrapes</Link></li>
<li><Link to="/dashboard">Dashboard</Link></li>
<li><Link to="/midi-archives">Midi Archives</Link></li>
<li><Link to="/signup">Sign up</Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
);
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<Link to="/" className="navbar-brand">InstaMuzik</Link>
</div>
<div className="collapse navbar-collapse">
{ isAuthenticated ? userLinks : guestLinks }
</div>
</div>
</nav>
);
}
}
NavigationBar.propTypes = {
auth: React.PropTypes.object.isRequired,
logout: React.PropTypes.func.isRequired,
user: React.PropTypes.object.isRequired
}
function mapStateToProps(state) {
return {
auth: state.auth,
user: state.auth.user
};
}
export default connect(mapStateToProps, { logout })(NavigationBar);
| {
"content_hash": "e4b07473ab5c53519f47736d6fea36fe",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 72,
"avg_line_length": 31.352941176470587,
"alnum_prop": 0.6064727954971857,
"repo_name": "bsubedi26/Project-Revised",
"id": "d942ae160c73024b2bf248b5faa1ddd3eb5ffec7",
"size": "2132",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/components/NavigationBar.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3634"
},
{
"name": "HTML",
"bytes": "1362"
},
{
"name": "JavaScript",
"bytes": "62895"
}
],
"symlink_target": ""
} |
'use strict';
angular.module('nlptabApp')
.directive('potentialCui',
/**
* potential-cui element directive. Links to the UMLS Metathesarus browser if a cui matches a
*
* @returns {{template: string, restrict: string, scope: {value: string}, controller: potentialCui.controller}}
*/
function () {
/**
* Pattern for a UMLS CUI.
*
* @type {RegExp}
*/
var cui = /C[0-9]{7}/;
return {
template: '<span ng-if="!isCui">{{value}}</span><a ng-if="isCui" href="https://uts.nlm.nih.gov/metathesaurus.html;#{{value}};0;1;CUI;2015AA;EXACT_MATCH;*;" target="_blank">{{value}}</a>',
restrict: 'E',
scope: {
value: '='
},
/**
* Linking function for the is-cui directive.
*
* @param {$rootScope.Scope} scope angular scope
*/
link: function (scope) {
/**
* Scope property, true if the value is a cui, false otherwise.
*
* @type {boolean}
*/
scope.isCui = cui.test(scope.value);
}
};
});
| {
"content_hash": "83a48779f4460996ce0f0e84f4c7e3c7",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 195,
"avg_line_length": 29.55263157894737,
"alnum_prop": 0.5120213713268033,
"repo_name": "NLPIE/NLP-TAB-webapp",
"id": "f2837684ca4670bfd22bddcf23cae9e0fb5f5906",
"size": "1123",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/common/directives/potential-cui.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6594"
},
{
"name": "HTML",
"bytes": "65961"
},
{
"name": "JavaScript",
"bytes": "104956"
}
],
"symlink_target": ""
} |
package org.elasticsearch.search.aggregations.pipeline;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Order;
import org.elasticsearch.search.aggregations.bucket.terms.support.IncludeExclude;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStats.Bounds;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucket;
import org.elasticsearch.test.ESIntegTestCase;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram;
import static org.elasticsearch.search.aggregations.AggregationBuilders.sum;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders.extendedStatsBucket;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.core.IsNull.notNullValue;
@ESIntegTestCase.SuiteScopeTestCase
public class ExtendedStatsBucketIT extends ESIntegTestCase {
private static final String SINGLE_VALUED_FIELD_NAME = "l_value";
static int numDocs;
static int interval;
static int minRandomValue;
static int maxRandomValue;
static int numValueBuckets;
static long[] valueCounts;
@Override
public void setupSuiteScopeCluster() throws Exception {
assertAcked(client().admin().indices().prepareCreate("idx")
.addMapping("type", "tag", "type=keyword").get());
createIndex("idx_unmapped", "idx_gappy");
numDocs = randomIntBetween(6, 20);
interval = randomIntBetween(2, 5);
minRandomValue = 0;
maxRandomValue = 20;
numValueBuckets = ((maxRandomValue - minRandomValue) / interval) + 1;
valueCounts = new long[numValueBuckets];
List<IndexRequestBuilder> builders = new ArrayList<>();
for (int i = 0; i < numDocs; i++) {
int fieldValue = randomIntBetween(minRandomValue, maxRandomValue);
builders.add(client().prepareIndex("idx", "type").setSource(
jsonBuilder().startObject().field(SINGLE_VALUED_FIELD_NAME, fieldValue).field("tag", "tag" + (i % interval))
.endObject()));
final int bucket = (fieldValue / interval); // + (fieldValue < 0 ? -1 : 0) - (minRandomValue / interval - 1);
valueCounts[bucket]++;
}
for (int i = 0; i < 6; i++) {
// creates 6 documents where the value of the field is 0, 1, 2, 3,
// 3, 5
builders.add(client().prepareIndex("idx_gappy", "type", "" + i).setSource(
jsonBuilder().startObject().field(SINGLE_VALUED_FIELD_NAME, i == 4 ? 3 : i).endObject()));
}
assertAcked(prepareCreate("empty_bucket_idx").addMapping("type", SINGLE_VALUED_FIELD_NAME, "type=integer"));
for (int i = 0; i < 2; i++) {
builders.add(client().prepareIndex("empty_bucket_idx", "type", "" + i).setSource(
jsonBuilder().startObject().field(SINGLE_VALUED_FIELD_NAME, i * 2).endObject()));
}
indexRandom(true, builders);
ensureSearchable();
}
/**
* Test for https://github.com/elastic/elasticsearch/issues/17701
*/
public void testGappyIndexWithSigma() {
double sigma = randomDoubleBetween(1.0, 6.0, true);
SearchResponse response = client().prepareSearch("idx_gappy")
.addAggregation(histogram("histo").field(SINGLE_VALUED_FIELD_NAME).interval(1L))
.addAggregation(extendedStatsBucket("extended_stats_bucket", "histo>_count").sigma(sigma)).execute().actionGet();
assertSearchResponse(response);
Histogram histo = response.getAggregations().get("histo");
assertThat(histo, notNullValue());
assertThat(histo.getName(), equalTo("histo"));
List<? extends Bucket> buckets = histo.getBuckets();
assertThat(buckets.size(), equalTo(6));
for (int i = 0; i < 6; ++i) {
long expectedDocCount;
if (i == 3) {
expectedDocCount = 2;
} else if (i == 4) {
expectedDocCount = 0;
} else {
expectedDocCount = 1;
}
Histogram.Bucket bucket = buckets.get(i);
assertThat("i: " + i, bucket, notNullValue());
assertThat("i: " + i, ((Number) bucket.getKey()).longValue(), equalTo((long) i));
assertThat("i: " + i, bucket.getDocCount(), equalTo(expectedDocCount));
}
ExtendedStatsBucket extendedStatsBucketValue = response.getAggregations().get("extended_stats_bucket");
long count = 6L;
double sum = 1.0 + 1.0 + 1.0 + 2.0 + 0.0 + 1.0;
double sumOfSqrs = 1.0 + 1.0 + 1.0 + 4.0 + 0.0 + 1.0;
double avg = sum / count;
double var = (sumOfSqrs - ((sum * sum) / count)) / count;
double stdDev = Math.sqrt(var);
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("extended_stats_bucket"));
assertThat(extendedStatsBucketValue.getMin(), equalTo(0.0));
assertThat(extendedStatsBucketValue.getMax(), equalTo(2.0));
assertThat(extendedStatsBucketValue.getCount(), equalTo(count));
assertThat(extendedStatsBucketValue.getSum(), equalTo(sum));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(avg));
assertThat(extendedStatsBucketValue.getSumOfSquares(), equalTo(sumOfSqrs));
assertThat(extendedStatsBucketValue.getVariance(), equalTo(var));
assertThat(extendedStatsBucketValue.getStdDeviation(), equalTo(stdDev));
assertThat(extendedStatsBucketValue.getStdDeviationBound(Bounds.LOWER), equalTo(avg - (sigma * stdDev)));
assertThat(extendedStatsBucketValue.getStdDeviationBound(Bounds.UPPER), equalTo(avg + (sigma * stdDev)));
}
public void testDocCountTopLevel() throws Exception {
SearchResponse response = client().prepareSearch("idx")
.addAggregation(histogram("histo").field(SINGLE_VALUED_FIELD_NAME).interval(interval)
.extendedBounds(minRandomValue, maxRandomValue))
.addAggregation(extendedStatsBucket("extended_stats_bucket", "histo>_count")).execute().actionGet();
assertSearchResponse(response);
Histogram histo = response.getAggregations().get("histo");
assertThat(histo, notNullValue());
assertThat(histo.getName(), equalTo("histo"));
List<? extends Bucket> buckets = histo.getBuckets();
assertThat(buckets.size(), equalTo(numValueBuckets));
double sum = 0;
int count = 0;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
double sumOfSquares = 0;
for (int i = 0; i < numValueBuckets; ++i) {
Histogram.Bucket bucket = buckets.get(i);
assertThat(bucket, notNullValue());
assertThat(((Number) bucket.getKey()).longValue(), equalTo((long) i * interval));
assertThat(bucket.getDocCount(), equalTo(valueCounts[i]));
count++;
sum += bucket.getDocCount();
min = Math.min(min, bucket.getDocCount());
max = Math.max(max, bucket.getDocCount());
sumOfSquares += bucket.getDocCount() * bucket.getDocCount();
}
double avgValue = count == 0 ? Double.NaN : (sum / count);
ExtendedStatsBucket extendedStatsBucketValue = response.getAggregations().get("extended_stats_bucket");
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("extended_stats_bucket"));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(avgValue));
assertThat(extendedStatsBucketValue.getMin(), equalTo(min));
assertThat(extendedStatsBucketValue.getMax(), equalTo(max));
assertThat(extendedStatsBucketValue.getSumOfSquares(), equalTo(sumOfSquares));
}
public void testDocCountAsSubAgg() throws Exception {
SearchResponse response = client()
.prepareSearch("idx")
.addAggregation(
terms("terms")
.field("tag")
.order(Order.term(true))
.subAggregation(
histogram("histo").field(SINGLE_VALUED_FIELD_NAME).interval(interval)
.extendedBounds(minRandomValue, maxRandomValue))
.subAggregation(extendedStatsBucket("extended_stats_bucket", "histo>_count"))).execute().actionGet();
assertSearchResponse(response);
Terms terms = response.getAggregations().get("terms");
assertThat(terms, notNullValue());
assertThat(terms.getName(), equalTo("terms"));
List<? extends Terms.Bucket> termsBuckets = terms.getBuckets();
assertThat(termsBuckets.size(), equalTo(interval));
for (int i = 0; i < interval; ++i) {
Terms.Bucket termsBucket = termsBuckets.get(i);
assertThat(termsBucket, notNullValue());
assertThat((String) termsBucket.getKey(), equalTo("tag" + (i % interval)));
Histogram histo = termsBucket.getAggregations().get("histo");
assertThat(histo, notNullValue());
assertThat(histo.getName(), equalTo("histo"));
List<? extends Bucket> buckets = histo.getBuckets();
double sum = 0;
int count = 0;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
double sumOfSquares = 0;
for (int j = 0; j < numValueBuckets; ++j) {
Histogram.Bucket bucket = buckets.get(j);
assertThat(bucket, notNullValue());
assertThat(((Number) bucket.getKey()).longValue(), equalTo((long) j * interval));
count++;
sum += bucket.getDocCount();
min = Math.min(min, bucket.getDocCount());
max = Math.max(max, bucket.getDocCount());
sumOfSquares += bucket.getDocCount() * bucket.getDocCount();
}
double avgValue = count == 0 ? Double.NaN : (sum / count);
ExtendedStatsBucket extendedStatsBucketValue = termsBucket.getAggregations().get("extended_stats_bucket");
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("extended_stats_bucket"));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(avgValue));
assertThat(extendedStatsBucketValue.getMin(), equalTo(min));
assertThat(extendedStatsBucketValue.getMax(), equalTo(max));
assertThat(extendedStatsBucketValue.getSumOfSquares(), equalTo(sumOfSquares));
}
}
public void testMetricTopLevel() throws Exception {
SearchResponse response = client()
.prepareSearch("idx")
.addAggregation(terms("terms").field("tag").subAggregation(sum("sum").field(SINGLE_VALUED_FIELD_NAME)))
.addAggregation(extendedStatsBucket("extended_stats_bucket", "terms>sum")).execute().actionGet();
assertSearchResponse(response);
Terms terms = response.getAggregations().get("terms");
assertThat(terms, notNullValue());
assertThat(terms.getName(), equalTo("terms"));
List<? extends Terms.Bucket> buckets = terms.getBuckets();
assertThat(buckets.size(), equalTo(interval));
double bucketSum = 0;
int count = 0;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
double sumOfSquares = 0;
for (int i = 0; i < interval; ++i) {
Terms.Bucket bucket = buckets.get(i);
assertThat(bucket, notNullValue());
assertThat((String) bucket.getKey(), equalTo("tag" + (i % interval)));
assertThat(bucket.getDocCount(), greaterThan(0L));
Sum sum = bucket.getAggregations().get("sum");
assertThat(sum, notNullValue());
count++;
bucketSum += sum.value();
min = Math.min(min, sum.value());
max = Math.max(max, sum.value());
sumOfSquares += sum.value() * sum.value();
}
double avgValue = count == 0 ? Double.NaN : (bucketSum / count);
ExtendedStatsBucket extendedStatsBucketValue = response.getAggregations().get("extended_stats_bucket");
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("extended_stats_bucket"));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(avgValue));
assertThat(extendedStatsBucketValue.getMin(), equalTo(min));
assertThat(extendedStatsBucketValue.getMax(), equalTo(max));
assertThat(extendedStatsBucketValue.getSumOfSquares(), equalTo(sumOfSquares));
}
public void testMetricAsSubAgg() throws Exception {
SearchResponse response = client()
.prepareSearch("idx")
.addAggregation(
terms("terms")
.field("tag")
.order(Order.term(true))
.subAggregation(
histogram("histo").field(SINGLE_VALUED_FIELD_NAME).interval(interval)
.extendedBounds(minRandomValue, maxRandomValue)
.subAggregation(sum("sum").field(SINGLE_VALUED_FIELD_NAME)))
.subAggregation(extendedStatsBucket("extended_stats_bucket", "histo>sum"))).execute().actionGet();
assertSearchResponse(response);
Terms terms = response.getAggregations().get("terms");
assertThat(terms, notNullValue());
assertThat(terms.getName(), equalTo("terms"));
List<? extends Terms.Bucket> termsBuckets = terms.getBuckets();
assertThat(termsBuckets.size(), equalTo(interval));
for (int i = 0; i < interval; ++i) {
Terms.Bucket termsBucket = termsBuckets.get(i);
assertThat(termsBucket, notNullValue());
assertThat((String) termsBucket.getKey(), equalTo("tag" + (i % interval)));
Histogram histo = termsBucket.getAggregations().get("histo");
assertThat(histo, notNullValue());
assertThat(histo.getName(), equalTo("histo"));
List<? extends Bucket> buckets = histo.getBuckets();
double bucketSum = 0;
int count = 0;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
double sumOfSquares = 0;
for (int j = 0; j < numValueBuckets; ++j) {
Histogram.Bucket bucket = buckets.get(j);
assertThat(bucket, notNullValue());
assertThat(((Number) bucket.getKey()).longValue(), equalTo((long) j * interval));
if (bucket.getDocCount() != 0) {
Sum sum = bucket.getAggregations().get("sum");
assertThat(sum, notNullValue());
count++;
bucketSum += sum.value();
min = Math.min(min, sum.value());
max = Math.max(max, sum.value());
sumOfSquares += sum.value() * sum.value();
}
}
double avgValue = count == 0 ? Double.NaN : (bucketSum / count);
ExtendedStatsBucket extendedStatsBucketValue = termsBucket.getAggregations().get("extended_stats_bucket");
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("extended_stats_bucket"));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(avgValue));
assertThat(extendedStatsBucketValue.getMin(), equalTo(min));
assertThat(extendedStatsBucketValue.getMax(), equalTo(max));
assertThat(extendedStatsBucketValue.getSumOfSquares(), equalTo(sumOfSquares));
}
}
public void testMetricAsSubAggWithInsertZeros() throws Exception {
SearchResponse response = client()
.prepareSearch("idx")
.addAggregation(
terms("terms")
.field("tag")
.order(Order.term(true))
.subAggregation(
histogram("histo").field(SINGLE_VALUED_FIELD_NAME).interval(interval)
.extendedBounds(minRandomValue, maxRandomValue)
.subAggregation(sum("sum").field(SINGLE_VALUED_FIELD_NAME)))
.subAggregation(extendedStatsBucket("extended_stats_bucket", "histo>sum").gapPolicy(GapPolicy.INSERT_ZEROS)))
.execute().actionGet();
assertSearchResponse(response);
Terms terms = response.getAggregations().get("terms");
assertThat(terms, notNullValue());
assertThat(terms.getName(), equalTo("terms"));
List<? extends Terms.Bucket> termsBuckets = terms.getBuckets();
assertThat(termsBuckets.size(), equalTo(interval));
for (int i = 0; i < interval; ++i) {
Terms.Bucket termsBucket = termsBuckets.get(i);
assertThat(termsBucket, notNullValue());
assertThat((String) termsBucket.getKey(), equalTo("tag" + (i % interval)));
Histogram histo = termsBucket.getAggregations().get("histo");
assertThat(histo, notNullValue());
assertThat(histo.getName(), equalTo("histo"));
List<? extends Bucket> buckets = histo.getBuckets();
double bucketSum = 0;
int count = 0;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
double sumOfSquares = 0;
for (int j = 0; j < numValueBuckets; ++j) {
Histogram.Bucket bucket = buckets.get(j);
assertThat(bucket, notNullValue());
assertThat(((Number) bucket.getKey()).longValue(), equalTo((long) j * interval));
Sum sum = bucket.getAggregations().get("sum");
assertThat(sum, notNullValue());
count++;
bucketSum += sum.value();
min = Math.min(min, sum.value());
max = Math.max(max, sum.value());
sumOfSquares += sum.value() * sum.value();
}
double avgValue = count == 0 ? Double.NaN : (bucketSum / count);
ExtendedStatsBucket extendedStatsBucketValue = termsBucket.getAggregations().get("extended_stats_bucket");
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("extended_stats_bucket"));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(avgValue));
assertThat(extendedStatsBucketValue.getMin(), equalTo(min));
assertThat(extendedStatsBucketValue.getMax(), equalTo(max));
assertThat(extendedStatsBucketValue.getSumOfSquares(), equalTo(sumOfSquares));
}
}
public void testNoBuckets() throws Exception {
SearchResponse response = client().prepareSearch("idx")
.addAggregation(terms("terms").field("tag").includeExclude(new IncludeExclude(null, "tag.*"))
.subAggregation(sum("sum").field(SINGLE_VALUED_FIELD_NAME)))
.addAggregation(extendedStatsBucket("extended_stats_bucket", "terms>sum")).execute().actionGet();
assertSearchResponse(response);
Terms terms = response.getAggregations().get("terms");
assertThat(terms, notNullValue());
assertThat(terms.getName(), equalTo("terms"));
List<? extends Terms.Bucket> buckets = terms.getBuckets();
assertThat(buckets.size(), equalTo(0));
ExtendedStatsBucket extendedStatsBucketValue = response.getAggregations().get("extended_stats_bucket");
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("extended_stats_bucket"));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(Double.NaN));
}
public void testBadSigmaAsSubAgg() throws Exception {
try {
SearchResponse response = client()
.prepareSearch("idx")
.addAggregation(
terms("terms")
.field("tag")
.order(Order.term(true))
.subAggregation(
histogram("histo").field(SINGLE_VALUED_FIELD_NAME).interval(interval)
.extendedBounds(minRandomValue, maxRandomValue)
.subAggregation(sum("sum").field(SINGLE_VALUED_FIELD_NAME)))
.subAggregation(extendedStatsBucket("extended_stats_bucket", "histo>sum")
.sigma(-1.0))).execute().actionGet();
fail("Illegal sigma was provided but no exception was thrown.");
} catch (Exception e) {
Throwable cause = ExceptionsHelper.unwrapCause(e);
if (cause == null) {
throw e;
} else if (cause instanceof SearchPhaseExecutionException) {
SearchPhaseExecutionException spee = (SearchPhaseExecutionException) e;
Throwable rootCause = spee.getRootCause();
if (!(rootCause instanceof IllegalArgumentException)) {
throw e;
}
} else if (!(cause instanceof IllegalArgumentException)) {
throw e;
}
}
}
public void testNested() throws Exception {
SearchResponse response = client()
.prepareSearch("idx")
.addAggregation(
terms("terms")
.field("tag")
.order(Order.term(true))
.subAggregation(
histogram("histo").field(SINGLE_VALUED_FIELD_NAME).interval(interval)
.extendedBounds(minRandomValue, maxRandomValue))
.subAggregation(extendedStatsBucket("avg_histo_bucket", "histo>_count")))
.addAggregation(extendedStatsBucket("avg_terms_bucket", "terms>avg_histo_bucket.avg")).execute().actionGet();
assertSearchResponse(response);
Terms terms = response.getAggregations().get("terms");
assertThat(terms, notNullValue());
assertThat(terms.getName(), equalTo("terms"));
List<? extends Terms.Bucket> termsBuckets = terms.getBuckets();
assertThat(termsBuckets.size(), equalTo(interval));
double aggTermsSum = 0;
int aggTermsCount = 0;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
double sumOfSquares = 0;
for (int i = 0; i < interval; ++i) {
Terms.Bucket termsBucket = termsBuckets.get(i);
assertThat(termsBucket, notNullValue());
assertThat((String) termsBucket.getKey(), equalTo("tag" + (i % interval)));
Histogram histo = termsBucket.getAggregations().get("histo");
assertThat(histo, notNullValue());
assertThat(histo.getName(), equalTo("histo"));
List<? extends Bucket> buckets = histo.getBuckets();
double aggHistoSum = 0;
int aggHistoCount = 0;
for (int j = 0; j < numValueBuckets; ++j) {
Histogram.Bucket bucket = buckets.get(j);
assertThat(bucket, notNullValue());
assertThat(((Number) bucket.getKey()).longValue(), equalTo((long) j * interval));
aggHistoCount++;
aggHistoSum += bucket.getDocCount();
}
double avgHistoValue = aggHistoCount == 0 ? Double.NaN : (aggHistoSum / aggHistoCount);
ExtendedStatsBucket extendedStatsBucketValue = termsBucket.getAggregations().get("avg_histo_bucket");
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("avg_histo_bucket"));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(avgHistoValue));
aggTermsCount++;
aggTermsSum += avgHistoValue;
min = Math.min(min, avgHistoValue);
max = Math.max(max, avgHistoValue);
sumOfSquares += avgHistoValue * avgHistoValue;
}
double avgTermsValue = aggTermsCount == 0 ? Double.NaN : (aggTermsSum / aggTermsCount);
ExtendedStatsBucket extendedStatsBucketValue = response.getAggregations().get("avg_terms_bucket");
assertThat(extendedStatsBucketValue, notNullValue());
assertThat(extendedStatsBucketValue.getName(), equalTo("avg_terms_bucket"));
assertThat(extendedStatsBucketValue.getAvg(), equalTo(avgTermsValue));
assertThat(extendedStatsBucketValue.getMin(), equalTo(min));
assertThat(extendedStatsBucketValue.getMax(), equalTo(max));
assertThat(extendedStatsBucketValue.getSumOfSquares(), equalTo(sumOfSquares));
}
}
| {
"content_hash": "5d2e83a76edeee29c11bba228a593f27",
"timestamp": "",
"source": "github",
"line_count": 525,
"max_line_length": 141,
"avg_line_length": 51.08952380952381,
"alnum_prop": 0.6069271493550071,
"repo_name": "strapdata/elassandra5-rc",
"id": "607124ecb159df5e77ce2bc7a4d8dd27a6677ef0",
"size": "27610",
"binary": false,
"copies": "1",
"ref": "refs/heads/v5.5.0-strapdata",
"path": "core/src/test/java/org/elasticsearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "42785"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "323716"
},
{
"name": "HTML",
"bytes": "5519"
},
{
"name": "Java",
"bytes": "41904615"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "PowerShell",
"bytes": "40357"
},
{
"name": "Python",
"bytes": "565445"
},
{
"name": "Shell",
"bytes": "188743"
}
],
"symlink_target": ""
} |
////////////////////////////////////////////////////////////////////////////////////
// CameraFilterPack v2.0 - by VETASOFT 2015 //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[AddComponentMenu ("Camera Filter Pack/Distortion/BigFace")]
public class CameraFilterPack_Distortion_BigFace : MonoBehaviour {
#region Variables
public Shader SCShader;
private float TimeX = 6.5f;
private Vector4 ScreenResolution;
private Material SCMaterial;
public float _Size = 5.0f;
[Range(2.0f, 10.0f)] public float Distortion = 2.5f;
public static float ChangeSize;
public static float ChangeDistortion;
#endregion
#region Properties
Material material
{
get
{
if(SCMaterial == null)
{
SCMaterial = new Material(SCShader);
SCMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return SCMaterial;
}
}
#endregion
void Start ()
{
ChangeSize = _Size;
ChangeDistortion = Distortion;
SCShader = Shader.Find("CameraFilterPack/Distortion_BigFace");
if(!SystemInfo.supportsImageEffects)
{
enabled = false;
return;
}
}
void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture)
{
if(SCShader != null)
{
TimeX+=Time.deltaTime;
if (TimeX>100) TimeX=0;
material.SetFloat("_TimeX", TimeX);
material.SetFloat("_Distortion", Distortion);
material.SetFloat("_Size", _Size);
material.SetVector("_ScreenResolution",new Vector4(sourceTexture.width,sourceTexture.height,0.0f,0.0f));
Graphics.Blit(sourceTexture, destTexture, material);
}
else
{
Graphics.Blit(sourceTexture, destTexture);
}
}
void OnValidate()
{
ChangeSize=_Size;
ChangeDistortion=Distortion;
}
// Update is called once per frame
void Update ()
{
if (Application.isPlaying)
{
_Size = ChangeSize ;
Distortion = ChangeDistortion;
}
#if UNITY_EDITOR
if (Application.isPlaying!=true)
{
SCShader = Shader.Find("CameraFilterPack/Distortion_BigFace");
}
#endif
}
void OnDisable ()
{
if(SCMaterial)
{
DestroyImmediate(SCMaterial);
}
}
} | {
"content_hash": "cde9c5df2d0937e7a5110f8466e4972a",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 107,
"avg_line_length": 20.97142857142857,
"alnum_prop": 0.6330608537693007,
"repo_name": "jackykschou/ProjectPool",
"id": "1f84bf51ed652f3faf1fc8ad56b7840de6493f59",
"size": "2204",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Project Pool/Assets/Camera Filter Pack/Scripts/CameraFilterPack_Distortion_BigFace.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "882609"
},
{
"name": "GLSL",
"bytes": "525555"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
///<reference path="typings/babylon.2.1.d.ts" />
///<reference path="typings/waa.d.ts" />
///<reference path="typings/jquery/jquery.d.ts" />
class BoxData {
public Image: string;
}
class CylinderData {
public Image: string;
}
class ObjectData {
public ID: string;
public Type: string;
public Meshes: BABYLON.Mesh[];
}
enum ARROW_TYPE {
Simple,
ArrowTip,
ArrowTipBothEnds
}
enum BOX2D_TYPE {
BorderOnly,
Filled
}
enum BOX_TYPE {
VM,
WebSite,
O365,
GitRepo,
GitHub,
VSO,
MachineLearning,
HDInsight,
StreamAnalytics,
EventHubs
}
enum LOWBOX_TYPE {
Server
}
enum TEXT_TYPE {
Flat,
Floating
}
enum IMAGE_TYPE {
Flat,
Floating
}
enum CYLINDER_TYPE {
AzureCache,
AzureSQL,
DocumentDB,
MySQL,
SQLDataSync,
SQLDatabase,
BlobStorage
}
class AzureLens {
private _definition;
private _canvas: HTMLCanvasElement;
private _engine: BABYLON.Engine;
private _scene: BABYLON.Scene;
private BOX_SIZE: number = 6;
private PLANE_SIZE: number = 600;
private _camera: BABYLON.TouchCamera;
private _cameraHidden: BABYLON.TouchCamera;
private _basePlane: BABYLON.Mesh;
private _light: BABYLON.HemisphericLight;
private _lightPoints: BABYLON.PointLight[];
private _objects = {};
private targetPosition: BABYLON.Vector3;
private targetLookat: BABYLON.Vector3;
private manualMode: boolean = false;
private selectedItem = null;
private menu = null;
private moving = {
down: false,
up: false,
left: false,
right: false,
front: false,
back: false
}
private rotating = {
down: false,
up: false,
left: false,
right: false
}
constructor() {
this._objects = {};
this._lightPoints = [];
document.getElementById("popupExpand").addEventListener("click",(evt) => { this.popupExpand(evt); });
document.getElementById("expandedClose").addEventListener("click",(evt) => { this.expandedClose(evt); });
window.addEventListener('click',(evt) => {
if (this._scene != null) {
var pickResult: BABYLON.PickingInfo = this._scene.pick(evt.clientX, evt.clientY);
if (pickResult.hit) {
this.handleObjectClick(pickResult);
}
}
});
window.addEventListener('keyup',(evt) => {
switch (evt.keyCode) {
case 37:
this.moving.left = false;
break;
case 38:
this.moving.front = false;
break;
case 39:
this.moving.right = false;
break;
case 40:
this.moving.back = false;
break;
}
}, false);
window.addEventListener('keydown',(evt) => {
this.manualMode = true;
switch (evt.keyCode) {
case 37:
this.moving.left = true;
break;
case 38:
this.moving.front = true;
break;
case 39:
this.moving.right = true;
break;
case 40:
this.moving.back = true;
break;
}
}, false);
window.addEventListener('mousedown',(evt) => {
this.manualMode = true;
}, false);
window.addEventListener('pointerdown',(evt) => {
this.manualMode = true;
}, false);
window.addEventListener("resize",() => {
if (this._canvas != null) {
this._canvas.width = window.innerWidth;
this._canvas.height = window.innerHeight;
}
if (this._engine != null) {
this._engine.resize();
}
if (this.menu != null) {
this.menu.multilevelpushmenu('redraw');
}
});
this.menu = $('#menu');
this.menu.visible = false;
this.menu.multilevelpushmenu({
direction: 'ltr',
backItemIcon: 'fa fa-angle-left',
groupIcon: 'fa fa-angle-right',
collapsed: false,
menuHeight: '100%',
onExpandMenuStart: ()=> {
this.expandedClose(null);
},
onItemClick: () => {
this.expandedClose(null);
this.closePopup();
var element: HTMLElement = arguments[2][0];
var anchor: HTMLAnchorElement = <HTMLAnchorElement>element.firstElementChild;
if (anchor.href.indexOf('#nav') > 0) {
//Navigation menus
var id = anchor.href.substr(anchor.href.indexOf('#nav') + 4,
anchor.href.length - anchor.href.indexOf('#nav') - 4);
this.manualMode = false;
var value = id;
this._definition.objects.forEach((item) => {
if (value == item.id) {
this.navigateToMesh(item);
}
});
window.event.cancelBubble = true;
} else if (anchor.href.indexOf('diag') > 0) {
//Diagram menus
var id = anchor.href.substr(anchor.href.indexOf('#diag') + 5,
anchor.href.length - anchor.href.indexOf('#diag') - 5);
this.destroyScene();
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "SampleModels/" + id, true);
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
this.createScene(xmlhttp.responseText);
}
}
xmlhttp.send();
} else if (anchor.href.indexOf('#ni') > 0) {
this.notImplemented();
}
}
});
}
private createBasePlane() {
this._basePlane = BABYLON.Mesh.CreateBox("floor", this.PLANE_SIZE, this._scene);
this._basePlane.scaling.x = 1;
this._basePlane.scaling.z = 1;
this._basePlane.scaling.y = 0.001;
this._basePlane.material = new BABYLON.StandardMaterial("texture1", this._scene);
(<BABYLON.StandardMaterial>this._basePlane.material).diffuseColor = new BABYLON.Color3(0, 0, 1);
(<BABYLON.StandardMaterial>this._basePlane.material).specularColor = new BABYLON.Color3(0.5, 0.5, 0.5);
this._basePlane.position = new BABYLON.Vector3(-100, 0, 100);
this._basePlane.isPickable = false;
this._basePlane.material.backFaceCulling = false;
}
private navigateToMesh(item) {
var height: number = item.height == null ? 0 : item.height;
var position: BABYLON.Vector3;
var lookAt: BABYLON.Vector3;
if (item.position2 != null) {
position = new BABYLON.Vector3(item.position2.x, height + 35, item.position2.y - 50);
lookAt = new BABYLON.Vector3(item.position2.x, height, item.position2.y);
} else {
position = new BABYLON.Vector3(item.points2[0].x, height + 35, item.points2[0].y - 50);
lookAt = new BABYLON.Vector3(item.points2[0].x, height, item.points2[0].y);
}
this.targetPosition = position;
this.targetLookat = lookAt;
this.displayPopup(item);
this.manualMode = false;
}
private color3ToHex(color: BABYLON.Color3): string {
var result = "#" + this.rgbToHex(color.r * 255) + this.rgbToHex(color.g * 255) + this.rgbToHex(color.b * 255);
return result;
}
private rgbToHex(n: number): string {
n = Math.max(0, Math.min(n, 255));
return "0123456789ABCDEF".charAt((n - n % 16) / 16)
+ "0123456789ABCDEF".charAt(n % 16);
}
private createBaseBox(): BABYLON.Mesh {
var box = BABYLON.Mesh.CreateBox("box", this.BOX_SIZE, this._scene);
box.scaling.x = 1;
box.scaling.z = 1;
box.scaling.y = 1;
box.position = new BABYLON.Vector3(-100, this.PLANE_SIZE * 0.001 + this.BOX_SIZE / 2, 100);
box.isPickable = false;
return box;
}
private createBaseCylinder(): BABYLON.Mesh {
var cylinder = BABYLON.Mesh.CreateCylinder("cylinder", this.BOX_SIZE, this.BOX_SIZE, this.BOX_SIZE, 24, 1, this._scene);
cylinder.scaling.x = 1;
cylinder.scaling.z = 1;
cylinder.scaling.y = 1;
cylinder.position = new BABYLON.Vector3(-100, this.PLANE_SIZE * 0.001 + this.BOX_SIZE / 2, 100);
cylinder.isPickable = false;
return cylinder;
}
private setCylinder(cylinder: BABYLON.Mesh, cylinderType: CYLINDER_TYPE, id: string) {
var data: CylinderData = new CylinderData();
cylinder.isPickable = true;
cylinder.id = id;
switch (cylinderType) {
case CYLINDER_TYPE.AzureCache:
data.Image = "assets/logos/Azure Cache including Redis.png";
break;
case CYLINDER_TYPE.AzureSQL:
data.Image = "assets/logos/Azure SQL Database.png";
break;
case CYLINDER_TYPE.DocumentDB:
data.Image = "assets/logos/DocumentDB.png";
break;
case CYLINDER_TYPE.MySQL:
data.Image = "assets/logos/MySQL database.png";
break;
case CYLINDER_TYPE.SQLDatabase:
data.Image = "assets/logos/SQL Database (generic).png";
break;
case CYLINDER_TYPE.SQLDataSync:
data.Image = "assets/logos/SQL Data Sync.png";
break;
case CYLINDER_TYPE.BlobStorage:
data.Image = "assets/logos/Storage Blob.png";
break;
default:
break;
}
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material0.specularColor = new BABYLON.Color3(0.4, 0.4, 0.4);
material0.ambientColor = new BABYLON.Color3(0.1, 0.1, 0.1);
material0.emissiveTexture = new BABYLON.Texture(data.Image, this._scene, true, true);
(<BABYLON.Texture>material0.emissiveTexture).uAng = Math.PI;
(<BABYLON.Texture>material0.emissiveTexture).wAng = Math.PI;
(<BABYLON.Texture>material0.emissiveTexture).vAng = Math.PI;
(<BABYLON.Texture>material0.emissiveTexture).getAlphaFromRGB = true;
(<BABYLON.Texture>material0.emissiveTexture).hasAlpha = true;
(<BABYLON.Texture>material0.emissiveTexture).uScale = 3.5;
(<BABYLON.Texture>material0.emissiveTexture).uOffset = 0.77;
(<BABYLON.Texture>material0.emissiveTexture).vOffset = 0.1;
(<BABYLON.Texture>material0.emissiveTexture).vScale = 1.1;
material0.useAlphaFromDiffuseTexture = false;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material1.specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
cylinder.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI * 0.75, BABYLON.Space.LOCAL);
cylinder.material = multimat;
cylinder.subMeshes = [];
var verticesCount = cylinder.getTotalVertices();
cylinder.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 36, 232, cylinder));
cylinder.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 36, cylinder));
}
private createCylinder(id: string, cylinderType: CYLINDER_TYPE, position: BABYLON.Vector2) {
var cylinder = this.createBaseCylinder();
this.setCylinder(cylinder, cylinderType, id);
cylinder.position.x = position.x;
cylinder.position.z = position.y;
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "CYLINDER_TYPE." + CYLINDER_TYPE[cylinderType].toString();
o.Meshes = [cylinder];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
}
private createLowBox(id: string, lowboxType: LOWBOX_TYPE, position: BABYLON.Vector2) {
var box = this.createBaseBox();
this.setLowBox(box, lowboxType, id);
box.scaling.y = 1 / 3;
box.position.y = this.PLANE_SIZE * 0.001 + this.BOX_SIZE / 6
box.position.x = position.x;
box.position.z = position.y;
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "LOWBOX_TYPE." + LOWBOX_TYPE[lowboxType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
}
private setLowBox(box: BABYLON.Mesh, lowboxType: LOWBOX_TYPE, id: string) {
var data: BoxData = new BoxData();
box.isPickable = true;
box.id = id;
switch (lowboxType) {
case LOWBOX_TYPE.Server:
data.Image = "assets/logos/CustomServer.png";
break;
default:
break;
}
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(1, 1, 1);
material0.diffuseTexture = new BABYLON.Texture(data.Image, this._scene);
(<BABYLON.Texture>material0.diffuseTexture).wAng = Math.PI;
(<BABYLON.Texture>material0.diffuseTexture).getAlphaFromRGB = true;
(<BABYLON.Texture>material0.diffuseTexture).hasAlpha = true;
(<BABYLON.Texture>material0.diffuseTexture).uScale = 1;
(<BABYLON.Texture>material0.diffuseTexture).vScale = 1;
material0.bumpTexture = new BABYLON.Texture(data.Image, this._scene);
(<BABYLON.Texture>material0.bumpTexture).wAng = Math.PI;
(<BABYLON.Texture>material0.bumpTexture).uScale = 1;
(<BABYLON.Texture>material0.bumpTexture).vScale = 1;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
box.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI, BABYLON.Space.LOCAL);
box.material = multimat;
box.subMeshes = [];
var verticesCount = box.getTotalVertices();
box.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 6, box));
box.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 6, 30, box));
}
private createBox(id: string, boxType: BOX_TYPE, position: BABYLON.Vector2) {
var box = this.createBaseBox();
this.setBox(box, boxType, id);
box.position.x = position.x;
box.position.z = position.y;
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "BOX_TYPE." + BOX_TYPE[boxType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
}
private setBox(box: BABYLON.Mesh, boxType: BOX_TYPE, id: string) {
var data: BoxData = new BoxData();
box.isPickable = true;
box.id = id;
switch (boxType) {
case BOX_TYPE.VM:
data.Image = "assets/logos/VM symbol only.png";
break;
case BOX_TYPE.WebSite:
data.Image = "assets/logos/Azure Websites.png";
break;
case BOX_TYPE.O365:
data.Image = "assets/logos/Office 365.png";
break;
case BOX_TYPE.GitRepo:
data.Image = "assets/logos/Git repository.png";
break;
case BOX_TYPE.GitHub:
data.Image = "assets/logos/GitHub.png";
break;
case BOX_TYPE.VSO:
data.Image = "assets/logos/Visual Studio Online.png";
break;
case BOX_TYPE.MachineLearning:
data.Image = "assets/logos/Machine Learning.png";
break;
case BOX_TYPE.HDInsight:
data.Image = "assets/logos/HDInsight.png";
break;
case BOX_TYPE.StreamAnalytics:
data.Image = "assets/logos/Stream Analytics.png";
break;
case BOX_TYPE.EventHubs:
data.Image = "assets/logos/Event Hubs.png";
break;
default:
break;
}
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material0.emissiveTexture = new BABYLON.Texture(data.Image, this._scene);
(<BABYLON.Texture>material0.emissiveTexture).wAng = Math.PI;
(<BABYLON.Texture>material0.emissiveTexture).getAlphaFromRGB = true;
(<BABYLON.Texture>material0.emissiveTexture).hasAlpha = true;
(<BABYLON.Texture>material0.emissiveTexture).uScale = 1;
(<BABYLON.Texture>material0.emissiveTexture).vScale = 1;
material0.useAlphaFromDiffuseTexture = false;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
box.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI, BABYLON.Space.LOCAL);
box.material = multimat;
box.subMeshes = [];
var verticesCount = box.getTotalVertices();
box.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 6, box));
box.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 6, 30, box));
}
private drawArrow(id: string, arrowType: ARROW_TYPE, points: BABYLON.Vector2[], color: BABYLON.Color4) {
var point1: BABYLON.Vector2 = points[0];
var meshes: BABYLON.Mesh[] = [];
for (var count: number = 1; count < points.length; count++) {
var backgroundColor: BABYLON.Color3 = new BABYLON.Color3(color.r, color.g, color.b);
var point2: BABYLON.Vector2 = points[count];
var point3: BABYLON.Vector2 = point1.add(point2).multiplyByFloats(0.5, 0.5);
var arrow = BABYLON.Mesh.CreateBox("arrow", this.BOX_SIZE, this._scene);
arrow.scaling.x = point1.subtract(point2).length() / this.BOX_SIZE;
arrow.scaling.z = 0.05;
arrow.scaling.y = 0.001;
var angle = -Math.atan2(point1.y - point2.y, point1.x - point2.x) + Math.PI / 2;
arrow.position = new BABYLON.Vector3(point3.x, this.PLANE_SIZE * 0.001 + 0.11, point3.y);
arrow.rotate(new BABYLON.Vector3(0, 1, 0), -Math.PI / 2 + angle, BABYLON.Space.LOCAL);
arrow.material = new BABYLON.StandardMaterial("texture1", this._scene);
(<BABYLON.StandardMaterial>arrow.material).diffuseColor = backgroundColor;
(<BABYLON.StandardMaterial>arrow.material).specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
(<BABYLON.StandardMaterial>arrow.material).emissiveColor = backgroundColor;
(<BABYLON.StandardMaterial>arrow.material).alpha = color.a;
arrow.isPickable = true;
arrow.id = id;
meshes.push(arrow);
//Draw arrow tip?
if (count == points.length - 1 && (arrowType == ARROW_TYPE.ArrowTip || arrowType == ARROW_TYPE.ArrowTipBothEnds)) {
var tip = BABYLON.Mesh.CreateBox("arrow", this.BOX_SIZE, this._scene);
tip.scaling.x = 0.2;
tip.scaling.z = 0.2;
tip.scaling.y = 0.001;
angle = angle + Math.PI / 4;
tip.position = new BABYLON.Vector3(point2.x, this.PLANE_SIZE * 0.001 + 0.11, point2.y);
tip.rotate(new BABYLON.Vector3(0, 1, 0), -Math.PI / 2 + angle, BABYLON.Space.LOCAL);
tip.material = new BABYLON.StandardMaterial("texture1", this._scene);
(<BABYLON.StandardMaterial>tip.material).diffuseColor = backgroundColor;
(<BABYLON.StandardMaterial>tip.material).specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
(<BABYLON.StandardMaterial>tip.material).emissiveColor = new BABYLON.Color3(color.r, color.g, color.b);
(<BABYLON.StandardMaterial>tip.material).alpha = color.a;
tip.isPickable = true;
tip.id = id;
meshes.push(tip);
}
//Draw arrow tip at both ends?
if (count == points.length - 1 && arrowType == ARROW_TYPE.ArrowTipBothEnds) {
tip = BABYLON.Mesh.CreateBox("arrow", this.BOX_SIZE, this._scene);
tip.scaling.x = 0.2;
tip.scaling.z = 0.2;
tip.scaling.y = 0.001;
tip.position = new BABYLON.Vector3(point1.x, this.PLANE_SIZE * 0.001 + 0.11, point1.y);
tip.rotate(new BABYLON.Vector3(0, 1, 0), -Math.PI / 2 + angle, BABYLON.Space.LOCAL);
tip.material = new BABYLON.StandardMaterial("texture1", this._scene);
(<BABYLON.StandardMaterial>tip.material).diffuseColor = backgroundColor;
(<BABYLON.StandardMaterial>tip.material).specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
(<BABYLON.StandardMaterial>tip.material).emissiveColor = new BABYLON.Color3(color.r, color.g, color.b);
(<BABYLON.StandardMaterial>tip.material).alpha = color.a;
tip.isPickable = true;
tip.id = id;
meshes.push(tip);
}
point1 = point2;
}
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "ARROW_TYPE." + ARROW_TYPE[arrowType].toString();
o.Meshes = meshes;
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
}
private drawBox2D(id: string, box2DType: BOX2D_TYPE, points: BABYLON.Vector2[], color: BABYLON.Color4) {
switch (box2DType) {
case BOX2D_TYPE.BorderOnly:
var points2: BABYLON.Vector2[] = [];
//Define flat box points
points2.push(new BABYLON.Vector2(points[0].x, points[0].y));
points2.push(new BABYLON.Vector2(points[1].x, points[0].y));
points2.push(new BABYLON.Vector2(points[1].x, points[1].y));
points2.push(new BABYLON.Vector2(points[0].x, points[1].y));
points2.push(new BABYLON.Vector2(points[0].x, points[0].y));
var point1: BABYLON.Vector2 = points2[0];
var meshes: BABYLON.Mesh[] = [];
for (var count: number = 1; count < points2.length; count++) {
var point2: BABYLON.Vector2 = points2[count];
var point3: BABYLON.Vector2 = point1.add(point2).multiplyByFloats(0.5, 0.5);
var line = BABYLON.Mesh.CreateBox("box2d", this.BOX_SIZE, this._scene);
line.scaling.x = point1.subtract(point2).length() / this.BOX_SIZE;
line.scaling.z = 0.05;
line.scaling.y = 0.001;
var angle = -Math.atan2(point1.y - point2.y, point1.x - point2.x) + Math.PI / 2;
line.position = new BABYLON.Vector3(point3.x, this.PLANE_SIZE * 0.001, point3.y);
line.rotate(new BABYLON.Vector3(0, 1, 0), -Math.PI / 2 + angle, BABYLON.Space.LOCAL);
line.material = new BABYLON.StandardMaterial("texture1", this._scene);
(<BABYLON.StandardMaterial>line.material).diffuseColor = new BABYLON.Color3(0.7, 0.7, 0.7);
(<BABYLON.StandardMaterial>line.material).specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
(<BABYLON.StandardMaterial>line.material).emissiveColor = new BABYLON.Color3(color.r, color.g, color.b);
(<BABYLON.StandardMaterial>line.material).alpha = color.a;
line.isPickable = true;
line.id = id;
meshes.push(line);
point1 = point2;
}
for (var count: number = 0; count < 4; count++) {
var corner = BABYLON.Mesh.CreateBox("box2d", this.BOX_SIZE, this._scene);
corner.scaling.x = 0.05;
corner.scaling.z = 0.05;
corner.scaling.y = 0.001;
corner.position = new BABYLON.Vector3(points2[count].x, this.PLANE_SIZE * 0.001, points2[count].y);
corner.material = new BABYLON.StandardMaterial("texture1", this._scene);
(<BABYLON.StandardMaterial>corner.material).diffuseColor = new BABYLON.Color3(0.7, 0.7, 0.7);
(<BABYLON.StandardMaterial>corner.material).specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
(<BABYLON.StandardMaterial>corner.material).emissiveColor = new BABYLON.Color3(color.r, color.g, color.b);
(<BABYLON.StandardMaterial>corner.material).alpha = color.a;
corner.isPickable = true;
corner.id = id;
meshes.push(corner);
}
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "BOX2D_TYPE." + BOX2D_TYPE[box2DType].toString();
o.Meshes = meshes;
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
case BOX2D_TYPE.Filled:
var backgroundColor: BABYLON.Color3 = new BABYLON.Color3(color.r, color.g, color.b);
var point: BABYLON.Vector2 = points[0].add(points[1]).multiplyByFloats(0.5, 0.5);
var box = BABYLON.Mesh.CreateBox("box2d", this.BOX_SIZE, this._scene);
box.scaling.x = points[0].subtract(new BABYLON.Vector2(points[1].x, points[0].y)).length() / this.BOX_SIZE;
box.scaling.z = points[0].subtract(new BABYLON.Vector2(points[0].x, points[1].y)).length() / this.BOX_SIZE;;
box.scaling.y = 0.001;
box.position = new BABYLON.Vector3(point.x, this.PLANE_SIZE * 0.001, point.y);
box.material = new BABYLON.StandardMaterial("texture1", this._scene);
(<BABYLON.StandardMaterial>box.material).diffuseColor = backgroundColor;
(<BABYLON.StandardMaterial>box.material).specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
(<BABYLON.StandardMaterial>box.material).emissiveColor = backgroundColor;
(<BABYLON.StandardMaterial>box.material).alpha = color.a;
box.isPickable = true;
box.id = id;
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "BOX2D_TYPE." + BOX2D_TYPE[box2DType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
default:
break;
}
}
private drawImage(id: string, imageType: IMAGE_TYPE, image: string, position: BABYLON.Vector2, size: number, height: number) {
switch (imageType) {
case IMAGE_TYPE.Flat:
var box = this.createBaseBox();
box.isPickable = true;
box.id = id;
box.position.x = position.x;
box.position.z = position.y;
box.position.y = this.PLANE_SIZE * 0.001;
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material0.diffuseTexture = new BABYLON.Texture(image, this._scene);
(<BABYLON.Texture>material0.diffuseTexture).wAng = Math.PI;
(<BABYLON.Texture>material0.diffuseTexture).getAlphaFromRGB = true;
(<BABYLON.Texture>material0.diffuseTexture).hasAlpha = true;
(<BABYLON.Texture>material0.diffuseTexture).uScale = 1;
(<BABYLON.Texture>material0.diffuseTexture).vScale = 1;
material0.emissiveTexture = material0.diffuseTexture;
material0.specularTexture = material0.diffuseTexture;
material0.useAlphaFromDiffuseTexture = true;
material0.useSpecularOverAlpha = true;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.alpha = 0;
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
box.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI, BABYLON.Space.LOCAL);
box.rotate(new BABYLON.Vector3(1, 0, 0), -Math.PI / 2, BABYLON.Space.LOCAL);
box.scaling.z = 0.0001;
box.scaling.x = size / this.BOX_SIZE;
box.scaling.y = size / this.BOX_SIZE;
box.material = multimat;
box.subMeshes = [];
var verticesCount = box.getTotalVertices();
box.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 6, box));
box.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 6, 30, box));
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "IMAGE_TYPE." + IMAGE_TYPE[imageType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
case IMAGE_TYPE.Floating:
var box = this.createBaseBox();
box.isPickable = true;
box.id = id;
box.position.x = position.x;
box.position.z = position.y;
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material0.diffuseTexture = new BABYLON.Texture(image, this._scene);
(<BABYLON.Texture>material0.diffuseTexture).wAng = Math.PI;
(<BABYLON.Texture>material0.diffuseTexture).getAlphaFromRGB = true;
(<BABYLON.Texture>material0.diffuseTexture).hasAlpha = true;
(<BABYLON.Texture>material0.diffuseTexture).uScale = 1;
(<BABYLON.Texture>material0.diffuseTexture).vScale = 1;
material0.emissiveTexture = material0.diffuseTexture;
material0.specularTexture = material0.diffuseTexture;
material0.useAlphaFromDiffuseTexture = true;
material0.useSpecularOverAlpha = true;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.alpha = 0;
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
box.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI, BABYLON.Space.LOCAL);
box.scaling.z = 0.0001;
box.scaling.x = size / this.BOX_SIZE;
box.scaling.y = size / this.BOX_SIZE;
box.position.y = this.PLANE_SIZE * 0.001 + box.scaling.y * this.BOX_SIZE / 2 + height;
box.material = multimat;
box.subMeshes = [];
var verticesCount = box.getTotalVertices();
box.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 6, box));
box.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 6, 30, box));
box.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_Y;
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "IMAGE_TYPE." + IMAGE_TYPE[imageType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
default:
break;
}
}
private drawText(id: string, textType: TEXT_TYPE, position: BABYLON.Vector2, color: BABYLON.Color4, fontSize: number, text: string, fontName: string, height: number, rotate: number) {
switch (textType) {
case TEXT_TYPE.Flat:
var box = BABYLON.Mesh.CreateBox("textbox2d", this.BOX_SIZE, this._scene);
box.scaling.y = 0.00001;
box.material = new BABYLON.StandardMaterial("texture1", this._scene);
box.isPickable = false;
box.id = id;
var texture = new BABYLON.DynamicTexture("dynamic texture", 512, this._scene, true, BABYLON.Texture.CUBIC_MODE);
texture.hasAlpha = true;
texture.wAng = Math.PI / 2;
var textureContext = texture.getContext();
texture.canRescale = true;
textureContext.font = "bold " + fontSize + "px " + fontName;
var textSize = textureContext.measureText(text);
var width = textSize.width / 80;
if (width > box.scaling.x * this.BOX_SIZE)
box.scaling.x = width / this.BOX_SIZE;
box.position = new BABYLON.Vector3(position.x + (this.BOX_SIZE * box.scaling.x) / 2, this.PLANE_SIZE * 0.001 + 0.2, position.y - (this.BOX_SIZE * box.scaling.z) / 2);
var size = texture.getSize();
textureContext.save();
textureContext.fillStyle = "transparent";
textureContext.fillRect(0, 0, size.width, size.height);
textureContext.fillStyle = this.color3ToHex(new BABYLON.Color3(color.r, color.g, color.b));
textureContext.globalAlpha = color.a;
textureContext.textAlign = "left";
textureContext.fillText(text, 0, 80, size.width);
textureContext.restore();
texture.update();
(<BABYLON.StandardMaterial>box.material).diffuseTexture = texture;
(<BABYLON.StandardMaterial>box.material).emissiveTexture = texture;
(<BABYLON.StandardMaterial>box.material).specularTexture = texture;
(<BABYLON.StandardMaterial>box.material).useAlphaFromDiffuseTexture = true;
(<BABYLON.StandardMaterial>box.material).useSpecularOverAlpha = true;
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "TEXT_TYPE." + TEXT_TYPE[textType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
case TEXT_TYPE.Floating:
var box = BABYLON.Mesh.CreateBox("textbox2d", this.BOX_SIZE, this._scene);
box.scaling.z = 0.00001;
box.material = new BABYLON.StandardMaterial("texture1", this._scene);
box.isPickable = false;
box.id = id;
var texture = new BABYLON.DynamicTexture("dynamic texture", 512, this._scene, true);
texture.hasAlpha = true;
var textureContext = texture.getContext();
textureContext.font = "bold " + fontSize + "px " + fontName;
var size = texture.getSize();
textureContext.save();
textureContext.fillStyle = "transparent";
textureContext.fillRect(0, 0, size.width, size.height);
var textSize = textureContext.measureText(text);
var width = textSize.width / 80;
if (width > box.scaling.x * this.BOX_SIZE)
box.scaling.x = width / this.BOX_SIZE;
box.position = new BABYLON.Vector3(position.x + (this.BOX_SIZE * box.scaling.x) / 2, this.PLANE_SIZE * 0.001 + box.scaling.z / 2 + height, position.y - (this.BOX_SIZE * box.scaling.z) / 2);
textureContext.fillStyle = this.color3ToHex(new BABYLON.Color3(color.r, color.g, color.b));
textureContext.globalAlpha = color.a;
textureContext.textAlign = "left";
textureContext.fillText(text, 0, 80, size.width);
textureContext.restore();
texture.update();
(<BABYLON.StandardMaterial>box.material).diffuseTexture = texture;
(<BABYLON.StandardMaterial>box.material).emissiveTexture = texture;
(<BABYLON.StandardMaterial>box.material).specularTexture = texture;
(<BABYLON.StandardMaterial>box.material).useAlphaFromDiffuseTexture = true;
(<BABYLON.StandardMaterial>box.material).useSpecularOverAlpha = true;
if (rotate == null)
box.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_Y;
else
box.rotate(new BABYLON.Vector3(0, 1, 0), rotate * Math.PI / 180, BABYLON.Space.LOCAL);
var o: ObjectData = new ObjectData();
o.ID = id;
o.Type = "TEXT_TYPE." + TEXT_TYPE[textType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
default:
break;
}
}
public handleObjectClick(pickingInfo: BABYLON.PickingInfo) {
var mesh: BABYLON.AbstractMesh;
mesh = pickingInfo.pickedMesh;
if (mesh != null) {
this._definition.objects.forEach((item) => {
if (item.id == mesh.id && (item.position2 != null || item.points2!=null)) {
this.navigateToMesh(item);
}
});
}
}
public displayPopup(item) {
var popupDiv: HTMLDivElement = <HTMLDivElement>document.getElementById("popupDiv");
var popupName: HTMLDivElement = <HTMLDivElement>document.getElementById("popupName");
var popupDescription: HTMLDivElement = <HTMLDivElement>document.getElementById("popupDescription");
if (item.description != null) {
popupDiv.style.display = "block";
popupName.innerText = "Name: " + item.id;
popupDescription.innerText = item.description;
} else
popupDiv.style.display = "none";
}
public notImplemented() {
window.alert("This feature hasn't been implemented yet. Help us build it!");
}
public closePopup() {
var popupDiv: HTMLDivElement = <HTMLDivElement>document.getElementById("popupDiv");
popupDiv.style.display = "none";
}
public popupExpand(evt) {
this.closePopup();
var expandedPopupDiv: HTMLDivElement = <HTMLDivElement>document.getElementById("expandedPopupDiv");
expandedPopupDiv.style.display = "block";
this.menu.multilevelpushmenu('collapse');
}
public expandedClose(evt) {
this.closePopup();
var expandedPopupDiv: HTMLDivElement = <HTMLDivElement>document.getElementById("expandedPopupDiv");
expandedPopupDiv.style.display = "none";
}
public destroyScene() {
if (this._scene != null) {
this._engine.dispose();
this._scene.dispose();
this._scene = null;
this._definition = null;
this._canvas = null;
this._engine = null;
this._camera = null;
this._cameraHidden = null;
this._basePlane = null;
this._light = null;
this._lightPoints = [];
this._objects = {};
this.targetPosition = null;
this.targetLookat = null;
this.manualMode = false;
this.selectedItem = null;
}
}
public createScene(sceneData: string) {
this._canvas = <HTMLCanvasElement>document.getElementById("renderCanvas");
this._engine = new BABYLON.Engine(this._canvas, true);
this._scene = new BABYLON.Scene(this._engine);
this._scene.clearColor = new BABYLON.Color3(0, 0, 0);
this._camera = new BABYLON.TouchCamera("Camera", new BABYLON.Vector3(-100, 10, 0), this._scene);
this._camera.attachControl(this._canvas, true);
this._cameraHidden = new BABYLON.TouchCamera("Camera2", new BABYLON.Vector3(-100, 10, 0), this._scene);
this._cameraHidden.attachControl(this._canvas, true);
this._scene.setActiveCameraByName("Camera");
//Main light
this._light = new BABYLON.HemisphericLight("hemi", new BABYLON.Vector3(0, 1, 0), this._scene);
this._light.diffuse = new BABYLON.Color3(0.3, 0.3, 0.3);
this._light.specular = new BABYLON.Color3(1, 1, 1);
this._light.groundColor = new BABYLON.Color3(0, 0, 0);
//Point lights
var light0 = new BABYLON.PointLight("lpoint0", new BABYLON.Vector3(300, 40, 300), this._scene);
light0.diffuse = new BABYLON.Color3(0.7, 0.7, 0.7);
light0.specular = new BABYLON.Color3(0.9, 0.9, 0.9);
this._lightPoints.push(light0);
light0 = new BABYLON.PointLight("lpoint1", new BABYLON.Vector3(-500, 40, 300), this._scene);
light0.diffuse = new BABYLON.Color3(0.7, 0.7, 0.7);
light0.specular = new BABYLON.Color3(0.9, 0.9, 0.9);
this._lightPoints.push(light0);
this.createBasePlane();
var data = JSON.parse(sceneData);
this._definition = data;
data.objects.forEach((item) => {
switch (item.type.split(".")[0]) {
case "CYLINDER_TYPE":
this.createCylinder(item.id, CYLINDER_TYPE[<string>item.type.split(".")[1]], new BABYLON.Vector2(item.position2.x, item.position2.y));
break;
case "BOX_TYPE":
this.createBox(item.id, BOX_TYPE[<string>item.type.split(".")[1]], new BABYLON.Vector2(item.position2.x, item.position2.y));
break;
case "LOWBOX_TYPE":
this.createLowBox(item.id, LOWBOX_TYPE[<string>item.type.split(".")[1]], new BABYLON.Vector2(item.position2.x, item.position2.y));
break;
case "ARROW_TYPE":
var points: BABYLON.Vector2[] = [];
item.points2.forEach((p) => {
points.push(new BABYLON.Vector2(p.x, p.y));
});
var color: BABYLON.Color4 = new BABYLON.Color4(item.color4[0], item.color4[1], item.color4[2], item.color4[3]);
this.drawArrow(item.id, ARROW_TYPE[<string>item.type.split(".")[1]], points, color);
break;
case "BOX2D_TYPE":
var points: BABYLON.Vector2[] = [];
item.points2.forEach((p) => {
points.push(new BABYLON.Vector2(p.x, p.y));
});
if (points.length != 2)
throw "2D Boxes require 2 points";
var color: BABYLON.Color4 = new BABYLON.Color4(item.color4[0], item.color4[1], item.color4[2], item.color4[3]);
this.drawBox2D(item.id, BOX2D_TYPE[<string>item.type.split(".")[1]], points, color);
break;
case "TEXT_TYPE":
var color: BABYLON.Color4 = new BABYLON.Color4(item.color4[0], item.color4[1], item.color4[2], item.color4[3]);
var position: BABYLON.Vector2 = new BABYLON.Vector2(item.position2.x, item.position2.y);
this.drawText(item.id, TEXT_TYPE[<string>item.type.split(".")[1]], position, color, item.fontSize, item.text, item.fontName, item.height, item.rotate);
break;
case "IMAGE_TYPE":
var position: BABYLON.Vector2 = new BABYLON.Vector2(item.position2.x, item.position2.y);
this.drawImage(item.id, IMAGE_TYPE[<string>item.type.split(".")[1]], item.image, position, item.size, item.height);
break;
default:
break;
}
});
var slide1 = data.objects[0];
var height: number = slide1.height == null ? 0 : slide1.height;
this.targetPosition = new BABYLON.Vector3(slide1.position2.x, height + 35, slide1.position2.y - 50);
this.targetLookat = new BABYLON.Vector3(slide1.position2.x, height, slide1.position2.y);
this.manualMode = false;
//Diagrams menu
var diagramMenu = this.menu.multilevelpushmenu('finditemsbyname', 'Diagrams').first();
this.menu.multilevelpushmenu('removeitems', diagramMenu);
var $addTo = this.menu.multilevelpushmenu('findmenusbytitle', 'Browse').first();
var addItems = [{
name: 'Diagrams',
icon: '',
link: '#',
items: [
{
title: 'Diagrams',
icon: '',
link: '#',
items: [
]
}]
}];
addItems[0].items[0].items.unshift(
{
name: "Upload your own diagram",
icon: '',
link: '#ni'
});
addItems[0].items[0].items.unshift(
{
name: "How-old.Net architecture",
icon: '',
link: '#diagFaceDemo.json'
});
addItems[0].items[0].items.unshift(
{
name: "AzureLens architecture",
icon: '',
link: '#diagAzureLens.json'
});
this.menu.multilevelpushmenu('additems', addItems, $addTo, 0);
//Navigate menu
var navigateMenu = this.menu.multilevelpushmenu('finditemsbyname', 'Navigate').first();
this.menu.multilevelpushmenu('removeitems', navigateMenu);
$addTo = this.menu.multilevelpushmenu('findmenusbytitle', 'AzureLens').first();
var addItems2 = [{
name: 'Navigate',
icon: 'fa fa-eye',
link: '#',
items: [
{
title: 'Navigate',
icon: 'fa fa-eye',
link: '#',
items: [
]
}]
}];
data.objects.forEach((item) => {
if (item.pinnedToMenu == true) {
addItems2[0].items[0].items.unshift(
{
name: item.menuName,
icon: '',
link: '#nav' + item.id
});
}
});
addItems2[0].items[0].items = addItems2[0].items[0].items.sort(function (a, b) {
return a.name > b.name ? 1 : -1
});
this.menu.multilevelpushmenu('additems', addItems2, $addTo, 3);
this.menu.visible = true;
this.menu.multilevelpushmenu('expand', this.menu.multilevelpushmenu('findmenusbytitle', 'Navigate').first());
this._engine.runRenderLoop(() => {
this._scene.render();
if (!this.manualMode) {
this._camera.position = this._camera.position.add(new BABYLON.Vector3((this.targetPosition.x - this._camera.position.x) / 50,
(this.targetPosition.y - this._camera.position.y) / 50,
(this.targetPosition.z - this._camera.position.z) / 50));
this._cameraHidden.position = this._camera.position;
this._cameraHidden.setTarget(this.targetLookat);
var desiredRotation: BABYLON.Vector3 = this._cameraHidden.rotation;
this._camera.rotation = this._camera.rotation.add(desiredRotation.subtract(this._camera.rotation).divide(new BABYLON.Vector3(50, 50, 50)));
var y = this._camera.rotation.y;
}
if (this.moving.back) {
var speed = 0.1;
var transformationMatrix = this._camera.getWorldMatrix();
var direction: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, -speed);
var resultDirection: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, 0);
BABYLON.Vector3.TransformNormalToRef(direction, transformationMatrix, resultDirection);
this._camera.cameraDirection.addInPlace(resultDirection);
var camera;
camera = this._camera;
camera._offsetX = 0.000001;
} else if (this.moving.front) {
var speed = 0.1;
var transformationMatrix = this._camera.getWorldMatrix();
var direction: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, speed);
var resultDirection: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, 0);
BABYLON.Vector3.TransformNormalToRef(direction, transformationMatrix, resultDirection);
this._camera.cameraDirection.addInPlace(resultDirection);
var camera;
camera = this._camera;
camera._offsetX = 0.000001;
}
if (this.moving.left) {
var speed = 0.1;
var transformationMatrix = this._camera.getWorldMatrix();
var direction: BABYLON.Vector3 = new BABYLON.Vector3(-speed, 0, 0);
var resultDirection: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, 0);
BABYLON.Vector3.TransformNormalToRef(direction, transformationMatrix, resultDirection);
this._camera.cameraDirection.addInPlace(resultDirection);
var camera;
camera = this._camera;
camera._offsetX = 0.000001;
} else if (this.moving.right) {
var speed = 0.1;
var transformationMatrix = this._camera.getWorldMatrix();
var direction: BABYLON.Vector3 = new BABYLON.Vector3(speed, 0, 0);
var resultDirection: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, 0);
BABYLON.Vector3.TransformNormalToRef(direction, transformationMatrix, resultDirection);
this._camera.cameraDirection.addInPlace(resultDirection);
var camera;
camera = this._camera;
camera._offsetX = 0.000001;
}
});
this._canvas.width = window.innerWidth;
this._canvas.height = window.innerHeight;
this._engine.resize();
this.menu.multilevelpushmenu('redraw');
}
}
//*********************************************************
//
//AzureLens.Net, https://github.com/matvelloso/azurelens
//
//Copyright (c) Microsoft Corporation
//All rights reserved.
//
// MIT License:
// 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.
//
//*********************************************************
| {
"content_hash": "14f5e91c5665dad0a318b242fb9486fc",
"timestamp": "",
"source": "github",
"line_count": 1241,
"max_line_length": 205,
"avg_line_length": 43.47381144238517,
"alnum_prop": 0.5549480083779726,
"repo_name": "ahmedfaragnew/AzureLens",
"id": "c4f0f034a2e85612d230241ffbb80b8d7d451798",
"size": "53953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AzureLens/Scripts/app.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "C#",
"bytes": "153894"
},
{
"name": "CSS",
"bytes": "7681"
},
{
"name": "JavaScript",
"bytes": "2126842"
},
{
"name": "TypeScript",
"bytes": "53953"
}
],
"symlink_target": ""
} |
<?php
namespace MicrosoftAzure\Arm\Subscriptions;
use MicrosoftAzure\Common\Internal\Http\HttpClient;
use MicrosoftAzure\Common\Internal\Resources;
use MicrosoftAzure\Common\Internal\Utilities;
use MicrosoftAzure\Common\Internal\Validate;
/**
* Tenants.
*/
class Tenants
{
/**
* The service client object for the operations.
*
* @var SubscriptionClient
*/
private $_client;
/**
* Creates a new instance for Tenants.
*
* @param SubscriptionClient, Service client for Tenants
*/
public function __construct($client)
{
$this->_client = $client;
}
/**
* Gets a list of the tenantIds.
*
* @param array $customHeaders An array of custom headers ['key' => 'value'] that will be added to
* the HTTP request.
*
* @return array
* When the resposne status is OK(200),
* <pre>
* [
* 'value' => '',
* 'nextLink' => 'requiredNextLink'
* ];
* </pre>
*/
public function listOperation(array $customHeaders = [])
{
$response = $this->listOperationAsync($customHeaders);
if ($response->getBody()) {
$contents = $response->getBody()->getContents();
if ($contents) {
return $this->_client->getDataSerializer()->deserialize($contents);
}
}
return [];
}
/**
* Gets a list of the tenantIds.
*
* @param array $customHeaders An array of custom headers ['key' => 'value']
* that will be added to the HTTP request.
*
* @return \GuzzleHttp\Psr7\Response
*/
public function listOperationAsync(array $customHeaders = [])
{
if ($this->_client->getApiVersion() == null) {
Validate::notNullOrEmpty($this->_client->getApiVersion(), '$this->_client->getApiVersion()');
}
$path = '/tenants';
$statusCodes = [200];
$method = 'GET';
$path = strtr($path, []);
$queryParams = ['api-version' => $this->_client->getApiVersion()];
$headers = $customHeaders;
if ($this->_client->getAcceptLanguage() != null) {
$headers['accept-language'] = $this->_client->getAcceptLanguage();
}
if ($this->_client->getGenerateClientRequestId()) {
$headers[Resources::X_MS_REQUEST_ID] = Utilities::getGuid();
}
$body = '';
$response = HttpClient::send(
$method,
$headers,
$queryParams,
[],
$this->_client->getUrl($path),
$statusCodes,
$body,
$this->_client->getFilters()
);
return $response;
}
/**
* Gets a list of the tenantIds.
*
* @param string $nextPageLink The NextLink from the previous successful call
* to List operation.
* @param array $customHeaders An array of custom headers ['key' => 'value'] that will be added to
* the HTTP request.
*
* @return array
* When the resposne status is OK(200),
* <pre>
* [
* 'value' => '',
* 'nextLink' => 'requiredNextLink'
* ];
* </pre>
*/
public function listNext($nextPageLink, array $customHeaders = [])
{
$response = $this->listNextAsync($nextPageLink, $customHeaders);
if ($response->getBody()) {
$contents = $response->getBody()->getContents();
if ($contents) {
return $this->_client->getDataSerializer()->deserialize($contents);
}
}
return [];
}
/**
* Gets a list of the tenantIds.
*
* @param string $nextPageLink The NextLink from the previous successful call
* to List operation.
* @param array $customHeaders An array of custom headers ['key' => 'value']
* that will be added to the HTTP request.
*
* @return \GuzzleHttp\Psr7\Response
*/
public function listNextAsync($nextPageLink, array $customHeaders = [])
{
if ($nextPageLink == null) {
Validate::notNullOrEmpty($nextPageLink, '$nextPageLink');
}
$path = '{nextLink}';
$statusCodes = [200];
$method = 'GET';
$path = strtr($path, []);
$queryParams = [];
$headers = $customHeaders;
if ($this->_client->getAcceptLanguage() != null) {
$headers['accept-language'] = $this->_client->getAcceptLanguage();
}
if ($this->_client->getGenerateClientRequestId()) {
$headers[Resources::X_MS_REQUEST_ID] = Utilities::getGuid();
}
$body = '';
$response = HttpClient::send(
$method,
$headers,
$queryParams,
[],
$this->_client->getUrl($path),
$statusCodes,
$body,
$this->_client->getFilters()
);
return $response;
}
}
| {
"content_hash": "710ea3bcf16d0402ad5bddc85d656863",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 105,
"avg_line_length": 27.016393442622952,
"alnum_prop": 0.5370145631067961,
"repo_name": "yaqiyang/php-sdk-dev",
"id": "7d5865b0a719202eac929a59d0a9366500ff025e",
"size": "5466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Arm/Subscriptions/Tenants.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "5997325"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.