repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
zly123987123/activemq
|
activemq-systest/src/main/java/org/apache/activemq/systest/impl/SeparateBrokerProcessAgentImpl.java
|
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.systest.impl;
import java.io.File;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.systest.BrokerAgent;
import javax.jms.ConnectionFactory;
/**
* Runs a broker in a separate process
*
* @version $Revision: 1.1 $
*/
public class SeparateBrokerProcessAgentImpl extends SeparateProcessAgent implements BrokerAgent {
private static final String ENV_HOME = "ACTIVEMQ_HOME";
private static int portCounter = 61616;
private int port;
private String connectionURI;
private String brokerScript;
private File workingDirectory = new File("target/test-brokers");
private String defaultPrefix = "~/activemq";
private String coreURI;
public SeparateBrokerProcessAgentImpl(String host) throws Exception {
port = portCounter++;
coreURI = "tcp://" + host + ":" + port;
connectionURI = "failover:(" + coreURI + ")?useExponentialBackOff=false&initialReconnectDelay=500&&maxReconnectAttempts=20";
}
public void kill() throws Exception {
stop();
}
public ConnectionFactory getConnectionFactory() {
return new ActiveMQConnectionFactory(getConnectionURI());
}
public String getConnectionURI() {
return connectionURI;
}
public void connectTo(BrokerAgent remoteBroker) throws Exception {
// lets assume discovery works! :)
}
public String getBrokerScript() {
if (brokerScript == null) {
brokerScript = createBrokerScript();
}
return brokerScript;
}
public void setBrokerScript(String activemqScript) {
this.brokerScript = activemqScript;
}
public String getDefaultPrefix() {
return defaultPrefix;
}
public void setDefaultPrefix(String defaultPrefix) {
this.defaultPrefix = defaultPrefix;
}
public File getWorkingDirectory() {
return workingDirectory;
}
public void setWorkingDirectory(File workingDirectory) {
this.workingDirectory = workingDirectory;
}
// Implementation methods
// -------------------------------------------------------------------------
protected Process createProcess() throws Exception {
String commands[] = getCommands();
System.out.print("About to execute command:");
for (int i=0; i<commands.length; i++) {
System.out.print(" ");
System.out.print(commands[i]);
}
System.out.println();
File workingDir = createBrokerWorkingDirectory();
System.out.println("In directory: " + workingDir);
Process answer = Runtime.getRuntime().exec(commands, null, workingDir);
return answer;
}
protected File createBrokerWorkingDirectory() {
workingDirectory.mkdirs();
// now lets create a new temporary directory
File brokerDir = new File(workingDirectory, "broker_" + port);
brokerDir.mkdirs();
File varDir = new File(brokerDir, "data");
varDir.mkdirs();
File workDir = new File(brokerDir, "work");
workDir.mkdirs();
return workDir;
}
protected String createBrokerScript() {
String version = null;
Package p = Package.getPackage("org.apache.activemq");
if (p != null) {
version = p.getImplementationVersion();
}
if (version == null) {
version = "activemq-4.0-SNAPSHOT";
}
return "../../../../../assembly/target/" + version + "/bin/" + version + "/bin/activemq";
}
protected String[] createCommand() {
// lets try load the broker script from a system property
String script = System.getProperty("brokerScript");
if (script == null) {
String home = System.getenv(ENV_HOME);
if (home == null) {
script = getBrokerScript();
}
else {
script = home + "/bin/" + brokerScript;
}
}
String[] answer = { "/bin/bash", script, "broker:" + coreURI };
return answer;
}
}
|
vmartinv/nek
|
kernel/arch/x86/generic/textmode_console.c
|
<reponame>vmartinv/nek
#include <types.h>
#include <arch/x86/ports.h>
#include <string.h>
volatile uint16_t *video_memory;
static unsigned lines, cols;
uint8_t attributeByte = (0 << 4) | (15 & 0x0F);
uint8_t defaultAttribute = (0 << 4) | (15 & 0x0F);
uint8_t tm_cfore = 0xF, tm_cback = 0x0;
void textmode_changedest(uint16_t *newdest){
video_memory=newdest;
}
void textmode_init(uint16_t *buffer, unsigned alines, unsigned acols){
video_memory=buffer;
lines=alines, cols=acols;
}
///Sets the Textmode cursor posititon
void textmode_setcursor(int x,int y)
{
#ifdef CONSOLE_ONLY
uint16_t location = y * cols + x;
outb(0x3D4, 14);
outb(0x3D5, location >> 8);
outb(0x3D4, 15);
outb(0x3D5, location);
#endif
}
///Sets the attribute byte
void textmode_setbackcolor(uint8_t back)
{
attributeByte=(back << 4) | (attributeByte&(1<<4));
}
void textmode_setforecolor(uint8_t fore){
attributeByte=(attributeByte&(-1<<4)) | (fore&0x0F);
}
///Resets the attribute byte
void textmode_resetcolor()
{
attributeByte = defaultAttribute;
}
///Writes data to the screen
void textmode_write(int x,int y,uint8_t data)
{
uint16_t attribute = attributeByte << 8;
volatile uint16_t *write_to;
write_to = video_memory + (y * cols) + x;
*write_to = data | attribute;
}
///Writes data with a custom attribute byte
void textmode_write_color(int x,int y,uint8_t data, uint8_t attr)
{
uint16_t attribute = attr << 8;
volatile uint16_t *write_to;
write_to = video_memory + ((y * cols) + x);
*write_to = data | attribute;
}
///Clears the screen
void textmode_clear()
{
memset((void *)video_memory, 0x00, cols * lines * sizeof(u16));
}
///FIXME: Get this to work.
uint8_t textmode_read(int x,int y)
{
return 0 * (x + y);
}
///Scrolls the screen.
void textmode_scroll(int from,int to) //0 and lines-1
{
uint16_t blank = 0x20 | (attributeByte << 8);
unsigned i;
for (i = from*cols; i < to*cols; i++)
video_memory[i] = video_memory[i+cols];
for (i = to*cols; i < (to+1)*cols; i++)
video_memory[i] = blank;
}
|
xingchenwan/nasbowl
|
benchmarks/nas201.py
|
<reponame>xingchenwan/nasbowl
# For use of the NAS-Bench-201 dataset version NAS-Bench-201-v1_0-e61699.pth
import os
import numpy as np
import networkx as nx
from benchmarks.objectives import ObjectiveFunction
from nas_201_api import NASBench201API as API
import ConfigSpace
import random
class NAS201(ObjectiveFunction):
def __init__(self, data_dir, task='cifar10-valid', log_scale=True, negative=True,
use_12_epochs_result=False,
seed=None):
"""
data_dir: data directory that contains NAS-Bench-201-v1_0-e61699.pth file
task: the target image tasks. Options: cifar10-valid, cifar100, ImageNet16-120
log_scale: whether output the objective in log scale
negative: whether output the objective in negative form
use_12_epochs_result: whether use the statistics at the end of training of the 12th epoch instead of all the
way till the end.
seed: set the random seed to access trained model performance: Options: 0, 1, 2
seed=None will select the seed randomly
"""
self.api = API(os.path.join(data_dir, 'NAS-Bench-201-v1_1-096897.pth'))
if isinstance(task, list):
task = task[0]
self.task = task
self.use_12_epochs_result = use_12_epochs_result
if task == 'cifar10-valid':
best_val_arch_index = 6111
best_val_acc = 91.60666665039064 / 100
best_test_arch_index = 1459
best_test_acc = 91.52333333333333 / 100
elif task == 'cifar100':
best_val_arch_index = 9930
best_val_acc = 73.49333323567708 / 100
best_test_arch_index = 9930
best_test_acc = 73.51333326009114 / 100
elif task == 'ImageNet16-120':
best_val_arch_index = 10676
best_val_acc = 46.766666727701825 / 100
best_test_arch_index = 857
best_test_acc = 47.311111097547744 / 100
else:
raise NotImplementedError("task" + str(task) + " is not implemented in the dataset.")
if log_scale:
best_val_acc = np.log(best_val_acc)
best_val_err = 1. - best_val_acc
best_test_err = 1. - best_test_acc
if log_scale:
best_val_err = np.log(best_val_err)
best_test_err = np.log(best_val_err)
if negative:
best_val_err = -best_val_err
best_test_err = -best_test_err
self.best_val_err = best_val_err
self.best_test_err = best_test_err
self.best_val_acc = best_val_acc
self.best_test_acc = best_test_acc
super(NAS201, self).__init__(dim=None, optimum_location=best_test_arch_index, optimal_val=best_test_err,
bounds=None)
self.log_scale = log_scale
self.seed = seed
self.X = []
self.y_valid_acc = []
self.y_test_acc = []
self.costs = []
self.negative = negative
# self.optimal_val = # lowest mean validation error
# self.y_star_test = # lowest mean test error
def _retrieve(self, G, budget, which='eval'):
# set random seed for evaluation
if which == 'test':
seed = 3
else:
seed_list = [777, 888, 999]
if self.seed is None:
seed = random.choice(seed_list)
elif self.seed >= 3:
seed = self.seed
else:
seed = seed_list[self.seed]
# find architecture index
arch_str = G.name
# print(arch_str)
try:
arch_index = self.api.query_index_by_arch(arch_str)
acc_results = self.api.query_by_index(arch_index, self.task, use_12epochs_result=self.use_12_epochs_result,)
if seed is not None and 3 <= seed < 777:
# some architectures only contain 1 seed result
acc_results = self.api.get_more_info(arch_index, self.task, None,
use_12epochs_result=self.use_12_epochs_result,
is_random=False)
val_acc = acc_results['valid-accuracy'] / 100
test_acc = acc_results['test-accuracy'] / 100
else:
try:
acc_results = self.api.get_more_info(arch_index, self.task, None,
use_12epochs_result=self.use_12_epochs_result,
is_random=seed)
val_acc = acc_results['valid-accuracy'] / 100
test_acc = acc_results['test-accuracy'] / 100
# val_acc = acc_results[seed].get_eval('x-valid')['accuracy'] / 100
# if self.task == 'cifar10-valid':
# test_acc = acc_results[seed].get_eval('ori-test')['accuracy'] / 100
# else:
# test_acc = acc_results[seed].get_eval('x-test')['accuracy'] / 100
except:
# some architectures only contain 1 seed result
acc_results = self.api.get_more_info(arch_index, self.task, None,
use_12epochs_result=self.use_12_epochs_result,
is_random=False)
val_acc = acc_results['valid-accuracy'] / 100
test_acc = acc_results['test-accuracy'] / 100
auxiliary_info = self.api.query_meta_info_by_index(arch_index,
use_12epochs_result=self.use_12_epochs_result)
cost_info = auxiliary_info.get_compute_costs(self.task)
# auxiliary cost results such as number of flops and number of parameters
cost_results = {'flops': cost_info['flops'], 'params': cost_info['params'],
'latency': cost_info['latency']}
except FileNotFoundError:
val_acc = 0.01
test_acc = 0.01
print('missing arch info')
cost_results = {'flops': None, 'params': None,
'latency': None}
# store val and test performance + auxiliary cost information
self.X.append(arch_str)
self.y_valid_acc.append(val_acc)
self.y_test_acc.append(test_acc)
self.costs.append(cost_results)
if which == 'eval':
err = 1 - val_acc
elif which == 'test':
err = 1 - test_acc
else:
raise ValueError("Unknown query parameter: which = " + str(which))
if self.log_scale:
y = np.log(err)
else:
y = err
if self.negative:
y = -y
return y
def eval(self, G, budget=199, n_repeat=1):
# input is a list of graphs [G1,G2, ....]
if n_repeat == 1:
return self._retrieve(G, budget, 'eval'), [np.nan]
return np.mean(np.array([self._retrieve(G, budget, 'eval') for _ in range(n_repeat)])), [np.nan]
def test(self, G, budget=199, n_repeat=1):
return np.mean(np.array([self._retrieve(G, budget, 'test') for _ in range(n_repeat)]))
def get_results(self, ignore_invalid_configs=False):
regret_validation = []
regret_test = []
costs = []
model_graph_specs = []
inc_valid = 0
inc_test = 0
for i in range(len(self.X)):
if inc_valid < self.y_valid_acc[i]:
inc_valid = self.y_valid_acc[i]
inc_test = self.y_test_acc[i]
regret_validation.append(float(self.best_val_acc - inc_valid))
regret_test.append(float(self.best_test_acc - inc_test))
model_graph_specs.append(self.X[i])
costs.append(self.costs[i])
res = dict()
res['regret_validation'] = regret_validation
res['regret_test'] = regret_test
res['costs'] = costs
res['model_graph_specs'] = model_graph_specs
return res
@staticmethod
def get_configuration_space():
# for unpruned graph
cs = ConfigSpace.ConfigurationSpace()
ops_choices = ['nor_conv_3x3', 'nor_conv_1x1', 'avg_pool_3x3', 'skip_connect', 'none']
for i in range(6):
cs.add_hyperparameter(ConfigSpace.CategoricalHyperparameter("edge_%d" % i, ops_choices))
return cs
class NAS201edge(NAS201):
def _retrieve(self, G, budget, which='eval'):
# set random seed for evaluation
seed_list = [777, 888, 999]
if self.seed is None:
seed = random.choice(seed_list)
elif self.seed >= 3:
seed = self.seed
else:
seed = seed_list[self.seed]
# find architecture index
arch_str = G.name
# print(arch_str)
try:
arch_index = self.api.query_index_by_arch(arch_str)
acc_results = self.api.query_by_index(arch_index, self.task)
if seed >= 3:
# some architectures only contain 1 seed result
acc_results = self.api.get_more_info(arch_index, self.task, None, self.use_12_epochs_result, False)
val_acc = acc_results['valid-accuracy'] / 100
test_acc = acc_results['test-accuracy'] / 100
else:
try:
val_acc = acc_results[seed].get_eval('x-valid')['accuracy'] / 100
if self.task == 'cifar10-valid':
test_acc = acc_results[seed].get_eval('ori-test')['accuracy'] / 100
else:
test_acc = acc_results[seed].get_eval('x-test')['accuracy'] / 100
except:
# some architectures only contain 1 seed result
acc_results = self.api.get_more_info(arch_index, self.task, None, self.use_12_epochs_result, False)
val_acc = acc_results['valid-accuracy'] / 100
test_acc = acc_results['test-accuracy'] / 100
auxiliary_info = self.api.query_meta_info_by_index(arch_index)
cost_info = auxiliary_info.get_compute_costs(self.task)
# auxiliary cost results such as number of flops and number of parameters
cost_results = {'flops': cost_info['flops'], 'params': cost_info['params'],
'latency': cost_info['latency']}
except FileNotFoundError:
val_acc = 0.01
test_acc = 0.01
print('missing arch info')
cost_results = {'flops': None, 'params': None,
'latency': None}
# store val and test performance + auxiliary cost information
self.X.append(arch_str)
self.y_valid_acc.append(val_acc)
self.y_test_acc.append(test_acc)
self.costs.append(cost_results)
if which == 'eval':
err = 1. - val_acc
elif which == 'test':
err = 1. - test_acc
else:
raise ValueError("Unknown query parameter: which = " + str(which))
if self.log_scale:
y = np.log(err)
else:
y = err
if self.negative:
y = -y
return y
class NAS201MultiTask(ObjectiveFunction):
def __init__(self, data_dir, tasks,
task_weights=None,
log_scale=True, negative=True, use_12_epochs_result=False,
seed=None):
self.tasks = tasks
# Normalize the task_weights so that they sum to 1
if task_weights is None:
self.task_weights = np.array([1. / len(tasks)] * len(tasks))
else:
self.task_weights = np.array(task_weights).flatten() / np.sum(np.array(task_weights))
assert len(self.tasks) == self.task_weights.shape[0], " mismatch between the task_weights and tasks!"
self.nas201 = [NAS201(data_dir, t, log_scale, negative, use_12_epochs_result, seed) for t in tasks]
super(NAS201MultiTask, self).__init__(dim=None, optimum_location=None, optimal_val=None, bounds=None)
def eval(self, G, budget=100, n_repeat=1, scalarize=True):
evals = np.array([n.eval(G, budget, n_repeat) for n in self.nas201])
return np.sum(evals * self.task_weights) if scalarize else evals
def test(self, G, budget=100, n_repeat=1, scalarize=True):
tests = np.array([n.test(G, budget, n_repeat) for n in self.nas201])
return np.sum(tests * self.task_weights) if scalarize else tests
def __getattr__(self, item):
method = getattr(self.nas201, item)
return [method() for n in self.nas201]
if __name__ == '__main__':
import pickle
from bayesopt.generate_test_graphs import create_nasbench201_graph
output_path = '../data/'
op_node_labelling = ['nor_conv_3x3', 'none', 'avg_pool_3x3', 'skip_connect', 'nor_conv_3x3', 'skip_connect']
G = create_nasbench201_graph(op_node_labelling)
nascifar10 = NAS201(data_dir=output_path, task='cifar10-valid', seed=0, negative=False, log_scale=False)
f = nascifar10.eval
result = f(G)
|
smith750/kc
|
coeus-impl/src/main/java/org/kuali/kra/protocol/ProtocolDao.java
|
/*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.protocol;
import org.kuali.kra.protocol.noteattachment.ProtocolAttachmentBase;
import org.kuali.kra.protocol.noteattachment.TypedAttachment;
import java.sql.Date;
import java.util.List;
import java.util.Map;
/**
*
* This class is used to run ojb query directly.
*/
public interface ProtocolDao<GenericProtocol extends ProtocolBase> {
/**
*
* This method get protocols lookup search results.
* @param fieldValues
* @return
*/
List<GenericProtocol> getProtocols(Map<String,String> fieldValues);
/**
*
* This method Check if there are any pending amendmends/renewals for this protocols.
* @param protocolNumber
* @return
*/
boolean getProtocolSubmissionCountFromProtocol(String protocolNumber);
/**
* Gets all the attachment versions based on the passed in attachment. This will include the pass-in attachment.
* @param attachment the attachment to base the query off of
* @param type a class token used for retrieving the attachments
* @return the list of attachments, empty list if none to return or the attachment is invalid for a lookup
*/
<T extends ProtocolAttachmentBase & TypedAttachment> List<T> retrieveAttachmentVersions(T attachment, Class<T> type);
/**
* This method returns all Protocols that were approved by the specified committee and
* expires in the specified date range.
*
* @param committeeId of the most recent protocol submission that approved the protocol.
* @param startDate of the date range for the expiration date of the protocol. The start date is
* optional. If no start date is specified, the beginning of time will be used.
* @param endDate of the date range for the expiration date of the protocol. The end date is
* optional. If no end date is specified, the end of time will be used.
* @return List of the requested Protocols
*/
List<GenericProtocol> getExpiringProtocols(String committeeId, Date startDate, Date endDate);
/**
* This method returns all Protocols that were given a decision status of "Specify Minor Revision" (SMR)
* or "Substantive Revision Required" (SRR) by the specified committee in the specified date range.
*
* @param committeeId of the
* @param startDate
* @param endDate of the date range for the
* @return List of the requested Protocols
*/
List<ProtocolBase> getNotifiedProtocols(String committeeId, Date startDate, Date endDate);
}
|
agaveplatform/science-apis
|
agave-systems/systems-core/src/main/java/org/iplantc/service/transfer/exceptions/InvalidTransferException.java
|
<filename>agave-systems/systems-core/src/main/java/org/iplantc/service/transfer/exceptions/InvalidTransferException.java
package org.iplantc.service.transfer.exceptions;
public class InvalidTransferException extends RemoteDataException {
public InvalidTransferException() {
}
public InvalidTransferException(String arg0) {
super(arg0);
}
public InvalidTransferException(Throwable arg0) {
super(arg0);
}
public InvalidTransferException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
|
KimTou/Open-LetFit
|
src/main/java/com/letfit/service/SourceService.java
|
package com.letfit.service;
import com.letfit.pojo.dto.ResultInfo;
import com.letfit.pojo.entity.Source;
import com.letfit.pojo.vo.IndexInfo;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author cjt
* @date 2021/5/7 22:22
*/
@Service
public interface SourceService {
/**
* 获取首页信息
* @param userId
* @return
*/
ResultInfo<IndexInfo> getIndexInfo(Integer userId);
/**
* 获取模块对应的资源
* @param moduleId
* @return
*/
ResultInfo<List<Source>> getSourceByModuleId(Integer moduleId);
/**
* 根据标题关键字模糊查询资源
* @param title
* @return
*/
ResultInfo<List<Source>> searchSource(String title);
}
|
jayliang701/CRM-Template-React
|
src/components/PageFooter.js
|
import React from 'react';
import classnames from 'classnames';
const s = require('./PageFooter.scss');
const PageFooter = (props, state) => (
<div className={classnames(s.footer, props.className)}>
{ props.children }
</div>
)
export default PageFooter;
|
quiggs/krb5-krb5-1.2
|
src/lib/krb4/g_phost.c
|
<reponame>quiggs/krb5-krb5-1.2
/*
* g_phost.c
*
* Copyright 1988 by the Massachusetts Institute of Technology.
*
* For copying and distribution information, please see the file
* <mit-copyright.h>.
*/
#include "mit-copyright.h"
#define DEFINE_SOCKADDR /* For struct hostent, <netdb.h>, etc */
#include "krb.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
/*
* This routine takes an alias for a host name and returns the first
* field, lower case, of its domain name. For example, if "menel" is
* an alias for host officially named "menelaus" (in /etc/hosts), for
* the host whose official name is "MENELAUS.MIT.EDU", the name "menelaus"
* is returned.
*
* This is done for historical Athena reasons: the Kerberos name of
* rcmd servers (rlogin, rsh, rcp) is of the form "rcmd.host@realm"
* where "host"is the lowercase for of the host name ("menelaus").
* This should go away: the instance should be the domain name
* (MENELAUS.MIT.EDU). But for now we need this routine...
*
* A pointer to the name is returned, if found, otherwise a pointer
* to the original "alias" argument is returned.
*/
KRB5_DLLIMP char FAR * KRB5_CALLCONV
krb_get_phost(alias)
char FAR *alias;
{
struct hostent FAR *h;
char *p;
static char hostname_mem[MAXHOSTNAMELEN];
#ifdef DO_REVERSE_RESOLVE
char *rev_addr; int rev_type, rev_len;
#endif
if ((h=gethostbyname(alias)) != (struct hostent *)NULL ) {
#ifdef DO_REVERSE_RESOLVE
if (! h->h_addr_list ||! h->h_addr_list[0]) {
return(0);
}
rev_type = h->h_addrtype;
rev_len = h->h_length;
rev_addr = malloc(rev_len);
_fmemcpy(rev_addr, h->h_addr_list[0], rev_len);
h = gethostbyaddr(rev_addr, rev_len, rev_type);
free(rev_addr);
if (h == 0) {
return (0);
}
#endif
/* We don't want to return a FAR *, so we copy to a safe location. */
strncpy (hostname_mem, h->h_name, sizeof (hostname_mem));
hostname_mem[MAXHOSTNAMELEN-1]='\0';
p = strchr( hostname_mem, '.' );
if (p)
*p = 0;
p = hostname_mem;
do {
if (isupper(*p)) *p=tolower(*p);
} while (*p++);
}
return(hostname_mem);
}
|
nikosoik/stacksearch
|
src/post_classifier/classifier.py
|
<filename>src/post_classifier/classifier.py
import os
import sys
import datetime
from timeit import default_timer as timer
import numpy as np
from keras.layers import LSTM
from keras.layers import Dense
from keras.models import load_model
from keras.models import Sequential
from keras.preprocessing import sequence
from keras.layers.embeddings import Embedding
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from metrics import f1, precision, recall
## Folders
vec_folder = 'training_data/vec_data/'
model_folder = 'models/'
## Filter out INFO, WARNING logging in Tensorflow backend
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
class PostClassifier:
def __init__(self, model_path=None):
self.model = None
if model_path:
self.model = load_model(model_path)
def load_data_from_file(self, data_path):
return np.load(data_path)
def retain_top_words(self, data_matrix, ntop_tokens):
"""
Given a matrix data (list of np.array) retain the n most frequent tokens
(ntop_tokens) of each row-vector.
"""
res_matrix = []
for row in data_matrix:
if isinstance(row, list):
res_matrix.append([el for el in row if el < ntop_tokens])
else:
res_matrix.append(row[row < ntop_tokens])
return res_matrix
def process_vecs(self, data_matrix, ntop_tokens, max_length):
"""
Given a data matrix retain the n most frequent tokens and pad each
row-vector to max_length length.
"""
data_matrix = self.retain_top_words(data_matrix, ntop_tokens)
data_matrix = sequence.pad_sequences(data_matrix, maxlen=max_length)
return np.array(data_matrix)
def feed_data(self,
data_matrix,
ntop_tokens=12000,
max_length=4000,
batch_size=6000,
verbose=0):
"""
Utility function to feed data into the prediction system.
In case the rows of the data matrix is bigger than batch_size the matrix
is split into batches in order to conserve memory during the prediction
process.
"""
def progress(iterable, max_n=30, verbose=0):
n = len(iterable)
for index, element in enumerate(iterable):
if verbose:
j = (index + 1) / n
print(
'\r[{:{}s}] {}%'.format('=' * int(max_n * j), max_n,
int(100 * j)),
end=' ')
print(str(index + 1) + '/' + str(n), end=' ')
stime = timer()
yield index, element
print(
' ETA:',
datetime.timedelta(
seconds=((n - index - 1) * (timer() - stime))),
end='')
else:
yield index, element
if verbose:
print()
nrows = len(data_matrix)
n_batches = 1
if nrows > batch_size:
n_batches = round(nrows / batch_size)
print('Batches:', n_batches)
data_matrix = np.array_split(data_matrix, n_batches)
for ii, batch in progress(data_matrix, verbose=verbose):
yield self.process_vecs(batch, ntop_tokens, max_length)
def make_prediction(self, data_matrix, verbose=1):
"""
Make a prediction (1 unclean, 0 clean) for every row-vector of the given
vectorized data matrix.
"""
if self.model:
predictions = self.model.predict(
data_matrix, batch_size=128, verbose=verbose)
return predictions.round()
else:
raise ValueError('Classifier model path unknown.')
def save_predictions(self, output_path, predictions):
predictions = predictions.round()
np.savetxt(output_path, predictions, fmt='%u')
def load_training_data(vec_path,
label_path,
ntop_tokens=12000,
max_length=4000):
dmatrix = np.load(vec_path)
labels = np.load(label_path)
dmatrix = PostClassifier().retain_top_words(dmatrix, ntop_tokens)
dmatrix = sequence.pad_sequences(dmatrix, maxlen=max_length)
return dmatrix, labels
def compile_model(max_features=12000,
embed_len=35,
nrows=4000,
kernel_size=3,
pool_size=3,
dropout=0.6,
recurrent_dropout=0.05,
metrics=['accuracy']):
model = Sequential()
model.add(
Embedding(
input_dim=max_features, output_dim=embed_len, input_length=nrows))
model.add(
Conv1D(
filters=embed_len,
kernel_size=kernel_size,
padding='same',
activation='relu'))
model.add(MaxPooling1D(pool_size=pool_size))
model.add(LSTM(100, dropout=dropout, recurrent_dropout=recurrent_dropout))
model.add(Dense(1, activation='sigmoid'))
model.compile(
loss='binary_crossentropy', optimizer='adagrad', metrics=metrics)
return model
def train_model(model, vec_path, label_path, epochs=6, batch_size=40):
X, Y = load_training_data(vec_path, label_path)
model.fit(X, Y, epochs=epochs, batch_size=batch_size)
return model
def keras_evaluation(model,
X_train,
X_test,
y_train,
y_test,
epochs=6,
batch_size=40,
verbose=1):
# Fit the model on the train dataset
model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size)
# Final evaluation of the model
score, acc = model.evaluate(X_test, y_test, verbose=verbose)
print('Test score:', score, '__ Test accuracy:', acc * 100)
def scikit_evaluation(X,
Y,
build_fn,
epochs=6,
batch_size=40,
splits=5,
verbose=1,
seed=1200,
shuffle=True,
metrics=['accuracy', 'precision', 'f1']):
model = KerasClassifier(
build_fn=build_fn,
epochs=epochs,
batch_size=batch_size,
verbose=verbose)
kfold = StratifiedKFold(
n_splits=splits, shuffle=shuffle, random_state=seed)
for metric in metrics:
results = cross_val_score(model, X, Y, cv=kfold, scoring=metric)
print(results.mean())
print(results)
def parameter_optimization(param_grid, model, X, Y, cv=5, threads=1,
verbose=1):
#param_grid parameter dictionary
grid = GridSearchCV(
estimator=model,
param_grid=param_grid,
cv=cv,
n_jobs=threads,
verbose=verbose)
grid_result = grid.fit(X, Y)
# summarize results
print("Best: %f using %s" % (grid_result.best_score_,
grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
print("%f (%f) with: %r" % (mean, stdev, param))
if __name__ == '__main__':
# fix random seed for reproducibility
seed = 1200
np.random.seed(seed)
#scikit_evaluation(X, Y, compile_model)
model = compile_model(metrics=['accuracy'])
model = train_model(model, vec_folder + 'post_vecs_extra.npy',
vec_folder + 'labels_extra.npy')
model.save(model_folder + 'c-lstm_v1.1.hdf5')
|
adobe-research/beacon-aug
|
beacon_aug/advanced/__init__.py
|
<gh_stars>10-100
# Copyright 2021 Adobe
# All Rights Reserved.
# NOTICE: Adobe permits you to use, modify, and distribute this file in
# accordance with the terms of the Adobe license agreement accompanying
# it.
|
tonycody/tencent-tdw
|
qe/jdbc/src/java/org/apache/hadoop/hive/jdbc/HiveConnection.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.jdbc;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.service.HiveClient;
import org.apache.hadoop.hive.service.HiveInterface;
import org.apache.hadoop.hive.service.HiveServer;
import org.apache.hadoop.hive.service.HiveServerException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.Socket;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
public class HiveConnection implements java.sql.Connection, TDWConnection {
private TTransport transport;
public HiveInterface client;
public boolean isClosed = true;
private SQLWarning warningChain = null;
private Socket socket;
private String currentDB = null;
private String currentUser = null;
private String source = null;
private static final String URI_PREFIX = "jdbc:hive://";
public HiveConnection(String uri, Properties info) throws SQLException {
if (!uri.startsWith(URI_PREFIX)) {
throw new SQLException("Invalid URL: " + uri, "08S01");
}
if (info != null) {
source = info.getProperty("source");
}
String db = "default_db";
uri = uri.substring(URI_PREFIX.length());
if (uri.isEmpty()) {
try {
client = new HiveServer.HiveServerHandler();
try {
if (client.audit(info.getProperty("user"),
info.getProperty("password"), db) != 0) {
throw new SQLException("user :" + info.getProperty("user")
+ ",pass : " + info.getProperty("password") + ",db : " + db
+ " auldit failed!");
}
} catch (HiveServerException e) {
e.printStackTrace();
throw new SQLException(e.getMessage());
} catch (TException e) {
e.printStackTrace();
throw new SQLException(e.getMessage());
}
} catch (MetaException e) {
throw new SQLException("Error accessing Hive metastore: "
+ e.getMessage(), "08S01");
}
} else {
String[] parts = uri.split("/");
db = parts[1];
String[] hostport = parts[0].split(":");
int port = 10000;
String host = hostport[0];
try {
port = Integer.parseInt(hostport[1]);
} catch (Exception e) {
}
try {
socket = new Socket(host, port);
socket.setKeepAlive(true);
transport = new TSocket(socket);
} catch (Exception x) {
x.printStackTrace();
throw new SQLException("Could not establish connecton to " + uri + ": "
+ x.getMessage(), "08S01");
}
TProtocol protocol = new TBinaryProtocol(transport);
client = new HiveClient(protocol);
try {
if (client.audit(info.getProperty("user"),
info.getProperty("password"), db) != 0) {
throw new SQLException("user :" + info.getProperty("user")
+ ",pass : " + info.getProperty("password") + ",db : " + db
+ " auldit failed!");
}
Random rd = new Random();
int randID = rd.nextInt(100000000);
String sessionName = info.getProperty("user") + "_"
+ System.getProperty("user.name") + "_"
+ new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
+ "_" + randID;
if (source != null) {
sessionName += source;
}
client.createSession(sessionName);
} catch (HiveServerException e) {
e.printStackTrace();
throw new SQLException(e.getMessage());
} catch (TException e) {
e.printStackTrace();
throw new SQLException(e.getMessage());
}
}
currentDB = db;
currentUser = info.getProperty("user");
isClosed = false;
configureConnection();
}
private void configureConnection() throws SQLException {
Statement stmt = createStatement();
stmt.execute("set hive.fetch.output.serde = org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe");
stmt.execute("set tdw.username=" + currentUser);
stmt.close();
}
public void clearWarnings() throws SQLException {
warningChain = null;
}
public void close() throws SQLException {
try {
client.dropSession(null, null);
} catch (Exception x) {
}
try {
if (transport != null) {
transport.close();
}
} finally {
isClosed = true;
}
}
public void commit() throws SQLException {
throw new SQLException("Method HiveConnection.commit() not supported");
}
public Array createArrayOf(String arg0, Object[] arg1) throws SQLException {
throw new SQLException(
"Method HiveConnection.createArrayOf(String arg0, Object[] arg1) not supported");
}
public Blob createBlob() throws SQLException {
throw new SQLException("Method HiveConnection.createBlob() not supported");
}
public Clob createClob() throws SQLException {
throw new SQLException("Method HiveConnection.createClob() not supported");
}
public NClob createNClob() throws SQLException {
throw new SQLException("Method HiveConnection.createNClob() not supported");
}
public SQLXML createSQLXML() throws SQLException {
throw new SQLException("Method HiveConnection.createSQLXML() not supported");
}
public Statement createStatement() throws SQLException {
if (isClosed) {
throw new SQLException("Can't create Statement, connection is closed");
}
HiveStatement stmt = new HiveStatement(client);
stmt.setSocket(socket);
return stmt;
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
throw new SQLException(
"Method HiveConnection.createStatement(int resultSetType, int resultSetConcurrency) not supported");
}
public Statement createStatement(int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
throw new SQLException(
"Method HiveConnection.createStatement(int resultSetType, int resultSetConcurrency,int resultSetHoldability) not supported");
}
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
throw new SQLException(
"Method HiveConnection.createStruct(String typeName, Object[] attributes) not supported");
}
public boolean getAutoCommit() throws SQLException {
return true;
}
public String getCatalog() throws SQLException {
return currentDB;
}
public Properties getClientInfo() throws SQLException {
throw new SQLException(
"Method HiveConnection.getClientInfo() not supported");
}
public String getClientInfo(String name) throws SQLException {
throw new SQLException(
"Method HiveConnection.getClientInfo(String name) not supported");
}
public int getHoldability() throws SQLException {
throw new SQLException(
"Method HiveConnection.getHoldability() not supported");
}
public DatabaseMetaData getMetaData() throws SQLException {
return new HiveDatabaseMetaData(client, currentDB);
}
public int getTransactionIsolation() throws SQLException {
return Connection.TRANSACTION_NONE;
}
public Map<String, Class<?>> getTypeMap() throws SQLException {
throw new SQLException("Method HiveConnection.getTypeMap() not supported");
}
public SQLWarning getWarnings() throws SQLException {
return warningChain;
}
public boolean isClosed() throws SQLException {
return isClosed;
}
public boolean isReadOnly() throws SQLException {
return false;
}
public boolean isValid(int timeout) throws SQLException {
throw new SQLException(
"Method HiveConnection.isValid(int timeout) not supported");
}
public String nativeSQL(String sql) throws SQLException {
throw new SQLException(
"Method HiveConnection.nativeSQL(String sql) not supported");
}
public CallableStatement prepareCall(String sql) throws SQLException {
throw new SQLException(
"Method HiveConnection.prepareCall(String sql) not supported");
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
throw new SQLException(
"Method HiveConnection.prepareCall(String sql, int resultSetType,int resultSetConcurrency) not supported");
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability) throws SQLException {
throw new SQLException(
"Method HiveConnection.prepareCall(String sql, int resultSetType,int resultSetConcurrency, int resultSetHoldability) not supported");
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
return new HivePreparedStatement(client, sql);
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
return new HivePreparedStatement(client, sql);
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
throw new SQLException(
"Method HiveConnection.prepareStatement(String sql, int[] columnIndexes) not supported");
}
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
throw new SQLException(
"Method HiveConnection.prepareStatement(String sql, String[] columnNames) not supported");
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
return new HivePreparedStatement(client, sql);
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability) throws SQLException {
throw new SQLException(
"Method HiveConnection.prepareStatement(String sql, int resultSetType,int resultSetConcurrency, int resultSetHoldability) not supported");
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
throw new SQLException(
"Method HiveConnection.releaseSavepoint(Savepoint savepoint) not supported");
}
public void rollback() throws SQLException {
throw new SQLException("Method HiveConnection.rollback() not supported");
}
public void rollback(Savepoint savepoint) throws SQLException {
throw new SQLException(
"Method HiveConnection.rollback(Savepoint savepoint) not supported");
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
throw new SQLException(
"Method HiveConnection.setAutoCommit(boolean autoCommit) not supported");
}
public void setCatalog(String catalog) throws SQLException {
throw new SQLException(
"Method HiveConnection.setCatalog(String catalog) not supported");
}
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
throw new SQLClientInfoException(
"Method HiveConnection.setClientInfo(Properties properties) not supported",
null);
}
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
throw new SQLClientInfoException(
"Method HiveConnection.setClientInfo(String name, String value) not supported",
null);
}
public void setHoldability(int holdability) throws SQLException {
throw new SQLException(
"Method HiveConnection.setHoldability(int holdability) not supported");
}
public void setReadOnly(boolean readOnly) throws SQLException {
throw new SQLException(
"Method HiveConnection.setReadOnly(boolean readOnly) not supported");
}
public Savepoint setSavepoint() throws SQLException {
throw new SQLException("Method HiveConnection.setSavepoint() not supported");
}
public Savepoint setSavepoint(String name) throws SQLException {
throw new SQLException(
"Method HiveConnection.setSavepoint(String name) not supported");
}
public void setTransactionIsolation(int level) throws SQLException {
throw new SQLException(
"Method HiveConnection.setTransactionIsolation(int level) not supported");
}
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
throw new SQLException(
"Method HiveConnection.setTypeMap(Map<String, Class<?>> map) not supported");
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
throw new SQLException(
"Method HiveConnection.isWrapperFor(Class<?> iface) not supported");
}
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new SQLException(
"Method HiveConnection.unwrap(Class<T> iface) not supported");
}
public boolean compile(String path) throws SQLException, IOException {
if (isClosed) {
throw new SQLException("Can't execute after statement has been closed");
}
BufferedReader in = new BufferedReader(new FileReader(path));
boolean curSQLOpen = false;
int linenr = 0;
String curSQL = "";
String curLine = null;
int first = 0;
int end = 0;
String rt = "";
while (true) {
curLine = in.readLine();
if (curLine != null)
linenr += 1;
else
return true;
while (curLine.contains("'''")) {
if (curSQLOpen) {
end = curLine.indexOf("'''");
curSQL += curLine.substring(0, end);
if (curSQL.trim().length() == 0) {
curSQL = "";
curSQLOpen = false;
curLine = curLine.substring(end + 3);
} else {
try {
rt = client.compile(curSQL);
} catch (HiveServerException e) {
throw new SQLException(e.getMessage());
} catch (TException e) {
throw new SQLException(e.getMessage());
}
System.out.println("Check SQL @L :" + linenr + " " + curSQL + " "
+ rt);
if (rt != null && !rt.equalsIgnoreCase("success"))
return false;
curSQL = "";
curSQLOpen = false;
curLine = curLine.substring(end + 3);
}
} else {
first = curLine.indexOf("'''");
curLine = curLine.substring(first + 3);
curSQLOpen = true;
}
}
if (curSQLOpen)
curSQL += curLine + " ";
}
}
}
|
matyax/Pi-prestaciones
|
app/lib/pageWindow.js
|
var ui = require('ui');
var screenWidth = ui.screenWidth();
exports.createParagraph = function (item) {
var textAlign = Ti.UI.TEXT_ALIGNMENT_LEFT;
if (item.style_align == 'right') {
textAlign = Ti.UI.TEXT_ALIGNMENT_RIGHT;
} else if (item.style_align == 'center') {
textAlign = Ti.UI.TEXT_ALIGNMENT_CENTER;
}
var width = screenWidth - 40;
var foreColor = item.style_foreground || 'black';
return Ti.UI.createLabel({
text: item.value,
color: foreColor,
font: {
fontSize: item.style_font_size
},
width: width,
height: Ti.UI.SIZE,
top: 20,
left: 20,
textAlign: textAlign
});
};
exports.createTitle = function (item) {
var textAlign = Ti.UI.TEXT_ALIGNMENT_LEFT;
if (item.style_align == 'right') {
textAlign = Ti.UI.TEXT_ALIGNMENT_RIGHT;
} else if (item.style_align == 'center') {
textAlign = Ti.UI.TEXT_ALIGNMENT_CENTER;
}
var view = Ti.UI.createView({
layout: 'vertical',
backgroundColor: item.style_background,
width: '100%',
height: Ti.UI.SIZE,
top: 20
});
view.add(Ti.UI.createView({
width: '100%',
height: 5
}));
var labelWidth = screenWidth - 40;
view.add(Ti.UI.createLabel({
text: item.value,
color: item.style_foreground,
font: {
fontSize: item.style_font_size
},
top: 0,
left: 20,
textAlign: textAlign,
width: labelWidth,
height: Ti.UI.SIZE
}));
view.add(Ti.UI.createView({
width: '100%',
height: 5
}));
return view;
};
exports.createImage = function (item) {
var view = Ti.UI.createView({
width: '100%',
height: Ti.UI.SIZE,
top: 20
});
view.add(Ti.UI.createImageView({
image: item.value,
width: Ti.UI.SIZE,
height: Ti.UI.SIZE
}));
if (item.url) {
view.addEventListener('click', function () {
Ti.Platform.openURL(item.url);
});
}
return view;
};
exports.createLine = function (item) {
var view = Ti.UI.createView({
width: '100%',
height: item.style_height,
backgroundColor: item.style_background,
top: 20
});
return view;
};
exports.createButton = function (item) {
var view = Ti.UI.createView({
width: '100%',
height: Ti.UI.SIZE
});
var width = Math.round(item.value.length * (item.style_font_size * 0.8));
if (item.style_font_size == 24) {
width = Math.round(item.value.length * (item.style_font_size * 0.7));
}
if (item.value.length < 8) {
width += item.style_font_size * 2;
}
var button = Ti.UI.createButton({
width: width,
font: {
fontSize: item.style_font_size
},
title: item.value,
backgroundColor: item.style_background,
borderColor: item.style_background,
color: item.style_foreground,
borderRadius: item.style_border_radius || 0,
top: 20
});
button.addEventListener('click', function (e) {
Ti.Platform.openURL(item.url);
});
view.add(button);
return view;
};
exports.createAgendaShareView = function (item, eventData) {
var shareView = Ti.UI.createView({
layout: 'horizontal',
backgroundColor: eventData.styles.share_background,
width: '100%',
height: 35,
left: 0,
bottom: 0,
zIndex: 2
});
var favoriteButton = Titanium.UI.createButton({
backgroundImage: '/icons' + eventData.favorites_icon,
width: 25,
height: 25,
top: 5,
left: 20
});
var favoriteLabel = Titanium.UI.createLabel({
text: eventData.favorites_label,
color: eventData.styles.share_foreground,
font: {
fontSize: 12
},
top: 9,
left: 10
});
if (eventData.hashtag) {
var tweet = Ti.UI.createImageView({
image: '/icons/dark/1410146719_f099-128.png',
width: 19,
height: 25,
top: 5,
left: 70
});
var tweetLabel = Titanium.UI.createLabel({
text: 'Twittear',
color: eventData.styles.share_foreground,
font: {
fontSize: 12
},
top: 9,
left: 10
});
tweet.addEventListener('click', function (e) {
var social = require('social');
social.tweet(eventData, item);
});
tweetLabel.addEventListener('click', function (e) {
var social = require('social');
social.tweet(eventData, item);
});
}
favoriteButton.addEventListener('click', function(e) {
var favorites = require('favorites');
favorites.toggle(eventData.id_event, item, eventData.favorites_label);
});
favoriteLabel.addEventListener('click', function(e) {
var favorites = require('favorites');
favorites.toggle(eventData.id_event, item, eventData.favorites_label);
});
shareView.add(favoriteButton);
shareView.add(favoriteLabel);
if (eventData.hashtag) {
shareView.add(tweet);
shareView.add(tweetLabel);
}
return shareView;
};
|
NitroRobotto/StS_TheEdgeheg
|
theEdgeheg/src/main/java/theEdgeheg/powers/DodgePower.java
|
<reponame>NitroRobotto/StS_TheEdgeheg
package theEdgeheg.powers;
import com.megacrit.cardcrawl.actions.common.ReducePowerAction;
import com.megacrit.cardcrawl.actions.common.RemoveSpecificPowerAction;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.core.AbstractCreature;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.localization.PowerStrings;
import com.megacrit.cardcrawl.powers.AbstractPower;
import theEdgeheg.DefaultMod;
/**
* Reduces the damage from the next attack to 0. Removed at the end of turn.
* Not removed if the player has the "Superspeed" power.
* @author NITRO
* @version 1.1
* @since 2020-07-15
*/
public class DodgePower extends AbstractPower {
public static final String POWER_ID = DefaultMod.makeID(DodgePower.class.getSimpleName());
private static final PowerStrings powerStrings;
public static final String NAME;
public static final String[] DESCRIPTIONS;
public DodgePower(AbstractCreature owner, int stacks) {
this.name = NAME;
this.ID = POWER_ID;
this.owner = owner;
this.amount = stacks;
this.updateDescription();
this.loadRegion("intangible");
this.priority = 75;
}
public DodgePower(AbstractCreature owner) {
this(owner, 1);
}
public void playApplyPowerSfx() {
CardCrawlGame.sound.play("POWER_INTANGIBLE", 0.05F);
}
public void stackPower(int stackAmount) {
this.fontScale = 8.0F;
this.amount += stackAmount;
}
public void updateDescription() {
if (this.amount <= 1) {
this.description = DESCRIPTIONS[0] + DESCRIPTIONS[1];
} else {
this.description = DESCRIPTIONS[0] + this.amount + DESCRIPTIONS[2];
}
}
public int onAttackedToChangeDamage(DamageInfo info, int damageAmount) {
if (damageAmount > 0) {
this.addToTop(new ReducePowerAction(this.owner, this.owner, this.ID, 1));
}
return 0;
}
@Override
public void atStartOfTurn() {
if (!owner.hasPower(Superspeed.POWER_ID)) {
this.addToBot(new RemoveSpecificPowerAction(this.owner, this.owner, this.ID));
}
}
static {
powerStrings = CardCrawlGame.languagePack.getPowerStrings(POWER_ID);
NAME = powerStrings.NAME;
DESCRIPTIONS = powerStrings.DESCRIPTIONS;
}
}
|
webtouchbr/deepstream.io-client-java
|
src/main/java/io/deepstream/DeepstreamFactory.java
|
<filename>src/main/java/io/deepstream/DeepstreamFactory.java
package io.deepstream;
import com.google.j2objc.annotations.ObjectiveCName;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* A singleton to stop you ( the developer ) from having to pass around the deepstream client reference
* around the codebase, making application development easier in frameworks such android.
* <p>
* Currently this only contains a single deepstream client;
*/
public class DeepstreamFactory {
private static DeepstreamFactory ourInstance = new DeepstreamFactory();
Map<String, DeepstreamClient> clients;
String lastUrl;
/**
* DeepstreamFactory is a map of all url connections created
*/
private DeepstreamFactory() {
this.clients = new HashMap();
this.lastUrl = null;
}
public static DeepstreamFactory getInstance() {
return ourInstance;
}
/**
* Returns the last client that was created. This is useful for most applications that
* only require a single connection. The first time a client is connected however it has to be
* via {@link DeepstreamFactory#getClient(String)} or {@link DeepstreamFactory#getClient(String, Properties)}
*
* @return A deepstream client
*/
public DeepstreamClient getClient() {
if (this.lastUrl == null) {
return null;
}
return this.clients.get(this.lastUrl);
}
/**
* Returns a client that was previous created via the same url using this method or {@link DeepstreamFactory#getClient(String, Properties)}.
* If one wasn't created, it creates it first and stores it for future reference.
*
* @param url The url to connect to, also the key used to retrieve in future calls
* @return A deepstream client
* @throws URISyntaxException An error if the url syntax is invalid
*/
@ObjectiveCName("getClient:")
public DeepstreamClient getClient(String url) throws URISyntaxException {
DeepstreamClient client = this.clients.get(url);
this.lastUrl = url;
if (clientDoesNotExist(client)) {
client = new DeepstreamClient(url, new DeepstreamConfig(), new JavaEndpointFactory());
this.clients.put(url, client);
}
return client;
}
/**
* Returns a client that was previous created via the same url using this method or {@link DeepstreamFactory#getClient(String)}.
* If one wasn't created, it creates it first and stores it for future reference.
*
* @param url The url to connect to, also the key used to retrieve in future calls
* @param options The options to use within the deepstream connection
* @return A deepstream client
* @throws URISyntaxException An error if the url syntax is invalid
* @throws InvalidDeepstreamConfig An exception if any of the options are invalid
*/
@ObjectiveCName("getClient:options:")
public DeepstreamClient getClient(String url, Properties options) throws URISyntaxException, InvalidDeepstreamConfig {
DeepstreamClient client = this.clients.get(url);
if (clientDoesNotExist(client)) {
client = new DeepstreamClient(url, new DeepstreamConfig(options), new JavaEndpointFactory());
this.clients.put(url, client);
}
return client;
}
@ObjectiveCName("clientDoesNotExist:")
private boolean clientDoesNotExist(DeepstreamClient client) {
return client == null || client.getConnectionState() == ConnectionState.CLOSED || client.getConnectionState() == ConnectionState.ERROR;
}
}
|
ericjavier/yaml
|
test/append.cpp
|
<reponame>ericjavier/yaml
#include <gtest/gtest.h>
#include <yaml/config.hpp>
#include <yaml/sequence/append.hpp>
#include "test_utils.hpp"
using namespace YAML_NSP;
using expected = list<t<1>, t<2>, t<3>, t<4>, t<4>, t<3>, t<2>, t<1>>;
TEST(append, list_seq) {
expect_same_seq<expected, append::ret<lst1, seq2>>();
}
TEST(append, seq_list) {
expect_same_seq<expected, append::ret<seq1, lst2>>();
}
|
fbacchella/LogHub
|
src/main/java/loghub/encoders/ToJson.java
|
package loghub.encoders;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import loghub.BuilderClass;
import loghub.CanBatch;
import loghub.jackson.JacksonBuilder;
import lombok.Setter;
@BuilderClass(ToJson.Builder.class)
@CanBatch
public class ToJson extends AbstractJacksonEncoder<ToJson.Builder> {
public static class Builder extends AbstractJacksonEncoder.Builder<ToJson> {
@Setter
private boolean pretty = false;
@Setter
private boolean dateAsText = false;
@Override
public ToJson build() {
return new ToJson(this);
}
};
public static Builder getBuilder() {
return new Builder();
}
private ToJson(Builder builder) {
super(builder);
}
@Override
protected JacksonBuilder<?> getWriterBuilder(Builder builder) {
JacksonBuilder<JsonMapper> jbuilder = JacksonBuilder.get(JsonMapper.class)
.setConfigurator(om -> om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, ! (builder.pretty || builder.dateAsText)))
;
if (builder.pretty) {
jbuilder.feature(SerializationFeature.INDENT_OUTPUT);
}
return jbuilder;
}
}
|
1065672644894730302/Chromium
|
chrome/service/cloud_print/cloud_print_helpers.h
|
<reponame>1065672644894730302/Chromium<filename>chrome/service/cloud_print/cloud_print_helpers.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_SERVICE_CLOUD_PRINT_CLOUD_PRINT_HELPERS_H_
#define CHROME_SERVICE_CLOUD_PRINT_CLOUD_PRINT_HELPERS_H_
#pragma once
#include <map>
#include <string>
#include <vector>
#include "chrome/service/cloud_print/print_system.h"
#include "googleurl/src/gurl.h"
namespace base {
class DictionaryValue;
}
// Helper methods for the cloud print proxy code.
class CloudPrintHelpers {
public:
static GURL GetUrlForPrinterRegistration(const GURL& cloud_print_server_url);
static GURL GetUrlForPrinterUpdate(const GURL& cloud_print_server_url,
const std::string& printer_id);
static GURL GetUrlForPrinterDelete(const GURL& cloud_print_server_url,
const std::string& printer_id,
const std::string& reason);
static GURL GetUrlForPrinterList(const GURL& cloud_print_server_url,
const std::string& proxy_id);
static GURL GetUrlForJobFetch(const GURL& cloud_print_server_url,
const std::string& printer_id,
const std::string& reason);
static GURL GetUrlForJobStatusUpdate(const GURL& cloud_print_server_url,
const std::string& job_id,
cloud_print::PrintJobStatus status);
static GURL GetUrlForJobStatusUpdate(
const GURL& cloud_print_server_url,
const std::string& job_id,
const cloud_print::PrintJobDetails& details);
static GURL GetUrlForUserMessage(const GURL& cloud_print_server_url,
const std::string& message_id);
static GURL GetUrlForGetAuthCode(const GURL& cloud_print_server_url,
const std::string& oauth_client_id,
const std::string& proxy_id);
// Generates an MD5 hash of the contents of a string map.
static std::string GenerateHashOfStringMap(
const std::map<std::string, std::string>& string_map);
static void GenerateMultipartPostDataForPrinterTags(
const std::map<std::string, std::string>& printer_tags,
const std::string& mime_boundary,
std::string* post_data);
// Returns true is tags indicate a dry run (test) job.
static bool IsDryRunJob(const std::vector<std::string>& tags);
// Created CloudPrint auth header from the auth token stored in the store.
static std::string GetCloudPrintAuthHeaderFromStore();
// Created CloudPrint auth header from the auth token.
static std::string GetCloudPrintAuthHeader(const std::string& auth_token);
private:
CloudPrintHelpers() {}
};
#endif // CHROME_SERVICE_CLOUD_PRINT_CLOUD_PRINT_HELPERS_H_
|
amc8391/mage
|
Mage.Sets/src/mage/cards/r/RoninCliffrider.java
|
package mage.cards.r;
import java.util.List;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.AttacksTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.keyword.BushidoAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Outcome;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.permanent.ControllerIdPredicate;
import mage.game.Game;
import mage.game.permanent.Permanent;
/**
*
* @author LevelX2
*/
public final class RoninCliffrider extends CardImpl {
public RoninCliffrider(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{R}{R}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.SAMURAI);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Bushido 1
this.addAbility(new BushidoAbility(1));
// Whenever Ronin Cliffrider attacks, you may have it deal 1 damage to each creature defending player controls.
this.addAbility(new AttacksTriggeredAbility(new RoninCliffriderEffect(), true));
}
public RoninCliffrider(final RoninCliffrider card) {
super(card);
}
@Override
public RoninCliffrider copy() {
return new RoninCliffrider(this);
}
}
class RoninCliffriderEffect extends OneShotEffect {
public RoninCliffriderEffect() {
super(Outcome.Damage);
this.staticText = "you may have it deal 1 damage to each creature defending player controls";
}
public RoninCliffriderEffect(final RoninCliffriderEffect effect) {
super(effect);
}
@Override
public RoninCliffriderEffect copy() {
return new RoninCliffriderEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
UUID defenderId = game.getCombat().getDefenderId(source.getSourceId());
if (defenderId != null) {
FilterCreaturePermanent filter = new FilterCreaturePermanent();
filter.add(new ControllerIdPredicate(defenderId));
List<Permanent> permanents = game.getBattlefield().getActivePermanents(filter, source.getControllerId(), source.getSourceId(), game);
for (Permanent permanent : permanents) {
permanent.damage(1, source.getSourceId(), source, game, false, true);
}
return true;
}
return false;
}
}
|
justinslee/Wai-Not-Makahiki
|
makahiki/apps/lib/avatar/admin.py
|
from django.contrib import admin
from apps.lib.avatar.models import Avatar
from apps.managers.challenge_mgr import challenge_mgr
from apps.admin.admin import developer_site
admin.site.register(Avatar)
developer_site.register(Avatar)
Avatar.admin_tool_tip = "Player Avatars"
challenge_mgr.register_developer_challenge_info_model("Players", 2, Avatar, 4)
|
pipecraft/pipes
|
pipes-core/src/test/java/org/pipecraft/pipes/CallbackPipeTest.java
|
package org.pipecraft.pipes;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.apache.commons.lang3.mutable.MutableInt;
import org.junit.jupiter.api.Test;
import org.pipecraft.pipes.sync.inter.CallbackPipe;
import org.pipecraft.pipes.sync.source.CollectionReaderPipe;
import org.pipecraft.pipes.sync.source.EmptyPipe;
/**
* A test for the {@link CallbackPipe}, which supports item level and completion level callbacks
*
* @author <NAME>
*/
public class CallbackPipeTest {
@Test
public void testItemCallback() throws Exception {
MutableInt last = new MutableInt(-1);
CollectionReaderPipe<Integer> p1 = new CollectionReaderPipe<>(1, 2, 3);
try (CallbackPipe<Integer> p = new CallbackPipe<>(p1, v -> {last.setValue(v);})) {
p.start();
assertEquals(Integer.valueOf(-1), last.getValue());
p.next();
assertEquals(Integer.valueOf(1), last.getValue());
p.next();
assertEquals(Integer.valueOf(2), last.getValue());
p.next();
assertEquals(Integer.valueOf(3), last.getValue());
assertNull(p.next());
assertEquals(Integer.valueOf(3), last.getValue());
}
}
@Test
public void testTerminationCallback() throws Exception {
MutableInt last = new MutableInt(-1);
CollectionReaderPipe<Integer> p1 = new CollectionReaderPipe<>(1, 2, 3);
try (CallbackPipe<Integer> p = new CallbackPipe<>(p1, () -> last.increment())) {
p.start();
assertEquals(Integer.valueOf(-1), last.getValue());
for (int i = 0; i < 3; i++) {
p.next();
assertEquals(Integer.valueOf(-1), last.getValue());
}
p.next();
assertEquals(Integer.valueOf(0), last.getValue());
p.next();
assertEquals(Integer.valueOf(0), last.getValue()); // Termination callback should not be executed more than once
}
}
@Test
public void testTerminationCallbackThroughPeek() throws Exception {
MutableInt last = new MutableInt(-1);
EmptyPipe<Integer> p1 = EmptyPipe.instance();
try (CallbackPipe<Integer> p = new CallbackPipe<>(p1, () -> last.increment())) {
p.start();
assertEquals(Integer.valueOf(-1), last.getValue());
p.peek();
assertEquals(Integer.valueOf(0), last.getValue());
}
}
}
|
akashdhruv/IBAMR
|
tests/IIM/hagen_poiseuille_FeedbackForcer.h
|
<reponame>akashdhruv/IBAMR<gh_stars>0
// ---------------------------------------------------------------------
//
// Copyright (c) 2018 - 2021 by the IBAMR developers
// All rights reserved.
//
// This file is part of IBAMR.
//
// IBAMR is free software and is distributed under the 3-clause BSD
// license. The full text of the license can be found in the file
// COPYRIGHT at the top level directory of IBAMR.
//
// ---------------------------------------------------------------------
#ifndef included_hagen_poiseuille_FeedbackForcer
#define included_hagen_poiseuille_FeedbackForcer
#include <ibamr/INSHierarchyIntegrator.h>
#include <ibamr/app_namespaces.h>
/////////////////////////////// CLASS DEFINITION /////////////////////////////
/*!
* \brief Class hagen_poiseuille_FeedbackForcer is an implementation of the strategy class
* CartGridFunction that is used to specify velocity boundary conditions via a
* feedback forcing (i.e., penalty) method.
*/
class hagen_poiseuille_FeedbackForcer : public CartGridFunction
{
public:
/*!
* \brief Constructor
*/
hagen_poiseuille_FeedbackForcer(const double height,
const double diameter,
const INSHierarchyIntegrator* fluid_solver,
Pointer<PatchHierarchy<NDIM> > patch_hierarchy);
/*!
* \brief Destructor.
*/
virtual ~hagen_poiseuille_FeedbackForcer();
/*!
* \name Implementation of CartGridFunction interface.
*/
//\{
/*!
* \brief Indicates whether the concrete CartGridFunction object is
* time-dependent.
*/
bool isTimeDependent() const;
/*!
* \brief Set data on the specified patch interior.
*/
void setDataOnPatch(int data_idx,
Pointer<hier::Variable<NDIM> > var,
Pointer<Patch<NDIM> > patch,
double data_time,
bool initial_time = false,
Pointer<PatchLevel<NDIM> > patch_level = Pointer<PatchLevel<NDIM> >(NULL));
//\}
private:
/*!
* \brief Default constructor.
*
* \note This constructor is not implemented and should not be used.
*/
hagen_poiseuille_FeedbackForcer();
/*!
* \brief Copy constructor.
*
* \note This constructor is not implemented and should not be used.
*
* \param from The value to copy to this object.
*/
hagen_poiseuille_FeedbackForcer(const hagen_poiseuille_FeedbackForcer& from);
/*!
* \brief Assignment operator.
*
* \note This operator is not implemented and should not be used.
*
* \param that The value to assign to this object.
*
* \return A reference to this object.
*/
hagen_poiseuille_FeedbackForcer& operator=(const hagen_poiseuille_FeedbackForcer& that);
const double d_H;
const double d_D;
const INSHierarchyIntegrator* const d_fluid_solver;
Pointer<PatchHierarchy<NDIM> > d_patch_hierarchy;
};
#endif //#ifndef included_hagen_poiseuille_FeedbackForcer
|
elonazoulay/incubator-pinot
|
pinot-common/src/main/java/org/apache/pinot/common/response/ServerInstance.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.common.response;
import com.google.common.net.InternetDomainName;
import java.net.InetAddress;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.pinot.common.utils.CommonConstants;
import org.apache.pinot.common.utils.EqualityUtils;
/**
* Service abstraction.
* A service is identified by its host, port and sequence id.
*/
public class ServerInstance {
public static final String NAME_PORT_DELIMITER = ":";
public static final String NAME_PORT_DELIMITER_FOR_INSTANCE_NAME = "_";
private static class HostNamePair {
String _hostName;
String _shortHostName;
HostNamePair(String hostName, String shortHostName) {
_hostName = hostName;
_shortHostName = shortHostName;
}
}
private static final ConcurrentHashMap<String, HostNamePair> HOST_NAME_MAP = new ConcurrentHashMap<>();
/** Host-name where the service is running **/
private final String _hostName;
private final String _shortHostName;
/** Service Port **/
private final int _port;
private final int _seq;
/**
* Use this constructor if the name and port are embedded as string with ":" as delimiter
*/
public ServerInstance(String namePortPair) {
this(namePortPair.split(NAME_PORT_DELIMITER)[0], Integer.parseInt(namePortPair.split(NAME_PORT_DELIMITER)[1]));
}
public ServerInstance(String name, int port) {
this(name, port, 0);
}
public ServerInstance(String name, int port, int seq) {
HostNamePair hostNamePair = HOST_NAME_MAP.computeIfAbsent(name, key -> {
String hostName = getHostName(name);
String shortHostName = getShortHostName(hostName);
return new HostNamePair(hostName, shortHostName);
});
_hostName = hostNamePair._hostName;
_shortHostName = hostNamePair._shortHostName;
_port = port;
_seq = seq;
}
private ServerInstance(String hostName, String shortHostName, int port, int seq) {
_hostName = hostName;
_shortHostName = shortHostName;
_port = port;
_seq = seq;
}
/**
* Server instance name is formatted as {@code Server_<host>_<port>}
*/
public static ServerInstance forInstanceName(String instanceName) {
String[] parts = instanceName.split(CommonConstants.Helix.PREFIX_OF_SERVER_INSTANCE)[1]
.split(NAME_PORT_DELIMITER_FOR_INSTANCE_NAME);
return new ServerInstance(parts[0], Integer.parseInt(parts[1]));
}
/**
* Name can either be a machine name, or a textual representation of its IP address.
*/
private static String getHostName(String name) {
try {
return InetAddress.getByName(name).getHostName();
} catch (Exception e) {
return name;
}
}
/**
* As per <a href="https://tools.ietf.org/html/rfc952">RFC-952</a> domain names should begin with a letter.
* That said, <a href="https://tools.ietf.org/html/rfc1123#page-13">RFC-1123</a> updated it say that it may also begin
* with a digit. Indeed, <a href="http://9292.nl/">this</a> is a valid domain name. Only the top-level domain (i.e. the
* last portion) has to be non-numeric. More clarification on this matter is in
* <a href="https://tools.ietf.org/html/rfc3696#section-2">RFC-3696</a>
*
* A potentially faster solution is
*
* if (first char is a digit) {
* it is probably ipv4;
* return name;
* } else {
* it could be ipv6 (in which case no dots), or a hostname
* return substring before the first dot.
* }
*
* It will fail if there are host names starting with a digit, but will work right otherwise.
*/
private static String getShortHostName(String hostName) {
try {
return InternetDomainName.from(hostName).parts().get(0);
} catch (Exception e) {
return hostName;
}
}
public String getHostname() {
return _hostName;
}
public String getShortHostName() {
return _shortHostName;
}
public int getPort() {
return _port;
}
public ServerInstance withSeq(int seq) {
return new ServerInstance(_hostName, _shortHostName, _port, seq);
}
@Override
public int hashCode() {
return EqualityUtils.hashCodeOf(EqualityUtils.hashCodeOf(_hostName.hashCode(), _port), _seq);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof ServerInstance) {
ServerInstance that = (ServerInstance) obj;
return _hostName.equals(that._hostName) && _port == that._port && _seq == that._seq;
}
return false;
}
@Override
public String toString() {
return _hostName + "_" + _port;
}
}
|
willwybrow/starlines
|
src/main/java/dev/wycobar/starlines/domain/Starline.java
|
<gh_stars>0
package dev.wycobar.starlines.domain;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.neo4j.core.schema.Node;
import dev.wycobar.starlines.domain.star.Star;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@Getter
@NoArgsConstructor
@Node("Starline")
public class Starline extends GameObject {
private Set<StarlineSpan> network;
public Set<Star> starsInStarline() {
return Optional
.ofNullable(network)
.stream()
.flatMap(Set::stream)
.map(StarlineSpan::getStar)
.collect(Collectors.toSet());
}
public Starline(UUID id, Set<StarlineSpan> network) {
super(id);
this.network = network;
}
}
|
plocinskipiotr/Design_Patterns
|
structural/proxy/iservice.py
|
"""
Interface service
"""
from abc import ABCMeta, abstractmethod
class IService(metaclass=ABCMeta):
"""Interface Service"""
@abstractmethod
def get_data(self):
"""get data"""
|
Zoltan45/Mame-mkp119
|
src/emu/mame.h
|
/***************************************************************************
mame.h
Controls execution of the core MAME system.
Copyright (c) 1996-2007, <NAME> and the MAME Team.
Visit http://mamedev.org for licensing and usage restrictions.
***************************************************************************/
#ifndef __MAME_H__
#define __MAME_H__
#include "mamecore.h"
#include "video.h"
#include "restrack.h"
#include "options.h"
#include <stdarg.h>
#ifdef MESS
#include "device.h"
#endif /* MESS */
/***************************************************************************
CONSTANTS
***************************************************************************/
/* return values from run_game */
#define MAMERR_NONE 0 /* no error */
#define MAMERR_FAILED_VALIDITY 1 /* failed validity checks */
#define MAMERR_MISSING_FILES 2 /* missing files */
#define MAMERR_FATALERROR 3 /* some other fatal error */
#define MAMERR_DEVICE 4 /* device initialization error (MESS-specific) */
#define MAMERR_NO_SUCH_GAME 5 /* game was specified but doesn't exist */
#define MAMERR_INVALID_CONFIG 6 /* some sort of error in configuration */
#define MAMERR_IDENT_NONROMS 7 /* identified all non-ROM files */
#define MAMERR_IDENT_PARTIAL 8 /* identified some files but not all */
#define MAMERR_IDENT_NONE 9 /* identified no files */
/* program phases */
#define MAME_PHASE_PREINIT 0
#define MAME_PHASE_INIT 1
#define MAME_PHASE_RESET 2
#define MAME_PHASE_RUNNING 3
#define MAME_PHASE_EXIT 4
/* maxima */
#define MAX_GFX_ELEMENTS 32
#define MAX_MEMORY_REGIONS 32
/* MESS vs. MAME abstractions */
#ifndef MESS
#define APPNAME "MAME"
#define APPNAME_LOWER "mame"
#define CONFIGNAME "mame"
#define APPLONGNAME "M.A.M.E."
#define CAPGAMENOUN "GAME"
#define CAPSTARTGAMENOUN "Game"
#define GAMENOUN "game"
#define GAMESNOUN "games"
#define HISTORYNAME "History"
#define COPYRIGHT "Copyright 2007, <NAME>\nand the MAME team\nhttp://mamedev.org"
#else
#define APPNAME "MESS"
#define APPNAME_LOWER "mess"
#define CONFIGNAME "mess"
#define APPLONGNAME "M.E.S.S."
#define CAPGAMENOUN "SYSTEM"
#define CAPSTARTGAMENOUN "System"
#define GAMENOUN "system"
#define GAMESNOUN "systems"
#define HISTORYNAME "System Info"
#define COPYRIGHT "Copyright 2007, the MESS team\nhttp://mess.org"
#endif
/* output channels */
enum _output_channel
{
OUTPUT_CHANNEL_ERROR,
OUTPUT_CHANNEL_WARNING,
OUTPUT_CHANNEL_INFO,
OUTPUT_CHANNEL_DEBUG,
OUTPUT_CHANNEL_VERBOSE,
OUTPUT_CHANNEL_LOG,
OUTPUT_CHANNEL_COUNT
};
typedef enum _output_channel output_channel;
/* memory region types */
enum
{
REGION_INVALID = 0x80,
REGION_CPU1,
REGION_CPU2,
REGION_CPU3,
REGION_CPU4,
REGION_CPU5,
REGION_CPU6,
REGION_CPU7,
REGION_CPU8,
REGION_GFX1,
REGION_GFX2,
REGION_GFX3,
REGION_GFX4,
REGION_GFX5,
REGION_GFX6,
REGION_GFX7,
REGION_GFX8,
REGION_PROMS,
REGION_SOUND1,
REGION_SOUND2,
REGION_SOUND3,
REGION_SOUND4,
REGION_SOUND5,
REGION_SOUND6,
REGION_SOUND7,
REGION_SOUND8,
REGION_USER1,
REGION_USER2,
REGION_USER3,
REGION_USER4,
REGION_USER5,
REGION_USER6,
REGION_USER7,
REGION_USER8,
REGION_DISKS,
REGION_PLDS,
REGION_MAX
};
extern const char *memory_region_names[REGION_MAX];
/***************************************************************************
TYPE DEFINITIONS
***************************************************************************/
/* output channel callback */
typedef void (*output_callback)(void *param, const char *format, va_list argptr);
/* forward type declarations */
typedef struct _mame_private mame_private;
typedef struct _video_private video_private;
typedef struct _palette_private palette_private;
typedef struct _streams_private streams_private;
typedef struct _devices_private devices_private;
/* description of the currently-running machine */
/* typedef struct _running_machine running_machine; -- in mamecore.h */
struct _running_machine
{
/* game-related information */
const game_driver * gamedrv; /* points to the definition of the game machine */
const machine_config * drv; /* points to the constructed machine_config */
const char * basename; /* basename used for game-related paths */
/* video-related information */
gfx_element * gfx[MAX_GFX_ELEMENTS];/* array of pointers to graphic sets (chars, sprites) */
screen_state screen[MAX_SCREENS];/* current screen state */
palette_t * palette; /* global palette object */
/* palette-related information */
/* fix me - some games try to modify remapped_colortable directly */
/* search for "palette hack" to find instances */
const pen_t * pens; /* remapped palette pen numbers */
const UINT16 * game_colortable; /* lookup table used to map gfx pen numbers to color numbers */
const pen_t * remapped_colortable;/* the above, already remapped through Machine->pens */
pen_t * shadow_table; /* table for looking up a shadowed pen */
/* audio-related information */
int sample_rate; /* the digital audio sample rate */
/* input-related information */
input_port_entry * input_ports; /* the input ports definition from the driver is copied here and modified */
mame_file * record_file; /* recording file (NULL if not recording) */
mame_file * playback_file; /* playback file (NULL if not recording) */
/* debugger-related information */
int debug_mode; /* was debug mode enabled? */
/* MESS-specific information */
#ifdef MESS
struct IODevice * devices;
#endif /* MESS */
/* internal core information */
mame_private * mame_data; /* internal data from mame.c */
video_private * video_data; /* internal data from video.c */
palette_private * palette_data; /* internal data from palette.c */
streams_private * streams_data; /* internal data from streams.c */
devices_private * devices_data; /* internal data from devices.c */
/* driver-specific information */
void * driver_data; /* drivers can hang data off of here instead of using globals */
};
typedef struct _mame_system_tm mame_system_tm;
struct _mame_system_tm
{
UINT8 second; /* seconds (0-59) */
UINT8 minute; /* minutes (0-59) */
UINT8 hour; /* hours (0-23) */
UINT8 mday; /* day of month (1-31) */
UINT8 month; /* month (0-11) */
INT32 year; /* year (1=1 AD) */
UINT8 weekday; /* day of week (0-6) */
UINT16 day; /* day of year (0-365) */
UINT8 is_dst; /* is this daylight savings? */
};
typedef struct _mame_system_time mame_system_time;
struct _mame_system_time
{
INT64 time; /* number of seconds elapsed since midnight, January 1 1970 UTC */
mame_system_tm local_time; /* local time */
mame_system_tm utc_time; /* UTC coordinated time */
};
/***************************************************************************
GLOBALS
***************************************************************************/
extern running_machine *Machine;
extern const char *mame_disclaimer;
extern char giant_string_buffer[];
extern char build_version[];
/***************************************************************************
FUNCTION PROTOTYPES
***************************************************************************/
/* ----- core system management ----- */
/* execute as configured by the OPTION_GAMENAME option on the specified options */
int mame_execute(core_options *options);
/* accesses the core_options for the currently running emulation */
core_options *mame_options(void);
/* return the current phase */
int mame_get_phase(running_machine *machine);
/* request callback on frame update */
void add_frame_callback(running_machine *machine, void (*callback)(running_machine *));
/* request callback on reset */
void add_reset_callback(running_machine *machine, void (*callback)(running_machine *));
/* request callback on pause */
void add_pause_callback(running_machine *machine, void (*callback)(running_machine *, int));
/* request callback on termination */
void add_exit_callback(running_machine *machine, void (*callback)(running_machine *));
/* handle update tasks for a frame boundary */
void mame_frame_update(running_machine *machine);
/* ----- global system states ----- */
/* schedule an exit */
void mame_schedule_exit(running_machine *machine);
/* schedule a hard reset */
void mame_schedule_hard_reset(running_machine *machine);
/* schedule a soft reset */
void mame_schedule_soft_reset(running_machine *machine);
/* schedule a new driver */
void mame_schedule_new_driver(running_machine *machine, const game_driver *driver);
/* schedule a save */
void mame_schedule_save(running_machine *machine, const char *filename);
/* schedule a load */
void mame_schedule_load(running_machine *machine, const char *filename);
/* is a scheduled event pending? */
int mame_is_scheduled_event_pending(running_machine *machine);
/* pause the system */
void mame_pause(running_machine *machine, int pause);
/* get the current pause state */
int mame_is_paused(running_machine *machine);
/* ----- memory region management ----- */
/* allocate a new memory region */
UINT8 *new_memory_region(running_machine *machine, int type, UINT32 length, UINT32 flags);
/* free an allocated memory region */
void free_memory_region(running_machine *machine, int num);
/* return a pointer to a specified memory region */
UINT8 *memory_region(int num);
/* return the size (in bytes) of a specified memory region */
UINT32 memory_region_length(int num);
/* return the type of a specified memory region */
UINT32 memory_region_type(running_machine *machine, int num);
/* return the flags (defined in romload.h) for a specified memory region */
UINT32 memory_region_flags(running_machine *machine, int num);
/* ----- output management ----- */
/* set the output handler for a channel, returns the current one */
void mame_set_output_channel(output_channel channel, output_callback callback, void *param, output_callback *prevcb, void **prevparam);
/* built-in default callbacks */
void mame_file_output_callback(void *param, const char *format, va_list argptr);
void mame_null_output_callback(void *param, const char *format, va_list argptr);
/* calls to be used by the code */
void mame_printf_error(const char *format, ...) ATTR_PRINTF(1,2);
void mame_printf_warning(const char *format, ...) ATTR_PRINTF(1,2);
void mame_printf_info(const char *format, ...) ATTR_PRINTF(1,2);
void mame_printf_verbose(const char *format, ...) ATTR_PRINTF(1,2);
void mame_printf_debug(const char *format, ...) ATTR_PRINTF(1,2);
/* discourage the use of printf directly */
/* sadly, can't do this because of the ATTR_PRINTF under GCC */
/*
#undef printf
#define printf !MUST_USE_MAME_PRINTF_*_CALLS_WITHIN_THE_CORE!
*/
/* ----- miscellaneous bits & pieces ----- */
/* pop-up a user visible message */
void CLIB_DECL popmessage(const char *text,...) ATTR_PRINTF(1,2);
/* log to the standard error.log file */
void CLIB_DECL logerror(const char *text,...) ATTR_PRINTF(1,2);
/* adds a callback to be called on logerror() */
void add_logerror_callback(running_machine *machine, void (*callback)(running_machine *, const char *));
/* parse the configured INI files */
void mame_parse_ini_files(core_options *options, const game_driver *driver);
/* standardized random number generator */
UINT32 mame_rand(running_machine *machine);
/* return the index of the given CPU, or -1 if not found */
int mame_find_cpu_index(running_machine *machine, const char *tag);
/* retrieve the base system time */
void mame_get_base_datetime(running_machine *machine, mame_system_time *systime);
/* retrieve the current system time */
void mame_get_current_datetime(running_machine *machine, mame_system_time *systime);
#ifdef MESS
#include "mess.h"
#endif /* MESS */
#endif /* __MAME_H__ */
|
The0x539/wasp
|
libc/libgloss/sparc_leon/asm-leon/leon3.h
|
/*
* Copyright (c) 2011 <NAME>
*
* BSD 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.
*/
#ifndef _INCLUDE_LEON3_h
#define _INCLUDE_LEON3_h
#ifndef __ASSEMBLER__
#ifdef __cplusplus
extern "C"
{
#endif
#define ASI_LEON3_CACHEMISS 1
#define ASI_LEON3_SYSCTRL 0x02
#define ASI_LEON3_DFLUSH 0x11
#define ASI_LEON3_SYSCTRL_ICFG 0x08
#define ASI_LEON3_SYSCTRL_DCFG 0x0c
#define ASI_LEON3_SYSCTRL_CFG_SNOOPING (1<<27)
#define ASI_LEON3_SYSCTRL_CFG_SSIZE(c) (1<<((c>>20)&0xf))
extern __inline__ unsigned long sparc_leon23_get_psr (void)
{
unsigned int retval;
__asm__ __volatile__ ("rd %%psr, %0\n\t":"=r" (retval):);
return (retval);
}
extern __inline__ unsigned long sparc_leon23_get_psr_version (void)
{
unsigned int psr = sparc_leon23_get_psr ();
return (psr >> 24) & 0xf;
}
#define LEON_ISLEON2 (sparc_leon23_get_psr_version() == 2 || sparc_leon23_get_psr_version() == 0)
#define LEON_ISLEON3 (sparc_leon23_get_psr_version() == 3)
extern __inline__ unsigned long sparc_leon3_get_dcachecfg (void)
{
unsigned int retval;
__asm__
__volatile__ ("lda [%1] %2, %0\n\t":"=r" (retval):"r"
(ASI_LEON3_SYSCTRL_DCFG), "i" (ASI_LEON3_SYSCTRL));
return (retval);
}
extern __inline__ void sparc_leon3_enable_snooping (void)
{
/*enable snooping */
__asm__ volatile ("lda [%%g0] 2, %%l1\n\t"
"set 0x800000, %%l2\n\t"
"or %%l2, %%l1, %%l2\n\t"
"sta %%l2, [%%g0] 2\n\t":::"l1", "l2");
};
extern __inline__ void sparc_leon3_disable_cache (void)
{
/*asi 2 */
__asm__ volatile ("lda [%%g0] 2, %%l1\n\t"
"set 0x00000f, %%l2\n\t"
"andn %%l2, %%l1, %%l2\n\t"
"sta %%l2, [%%g0] 2\n\t":::"l1", "l2");
};
extern __inline__ void sparc_leon3_dcache_flush (void)
{
__asm__ __volatile__ (" flush "); //iflush
__asm__
__volatile__ ("sta %%g0, [%%g0] %0\n\t"::"i"
(ASI_LEON3_DFLUSH):"memory");
};
#ifdef __cplusplus
}
#endif
#endif /* !ASM */
#endif /* !_INCLUDE_LEON3_h */
/* end of include file */
|
zhe-sun/dcos-ui
|
src/js/stores/BaseStore.js
|
<gh_stars>0
import {EventEmitter} from 'events';
class BaseStore extends EventEmitter {
addChangeListener(eventName, callback) {
this.on(eventName, callback);
}
removeChangeListener(eventName, callback) {
this.removeListener(eventName, callback);
}
}
module.exports = BaseStore;
|
ooooo-youwillsee/leetcode
|
1534-Count-Good-Triplets/java_1534/src/com/ooooo/Solution1.java
|
<filename>1534-Count-Good-Triplets/java_1534/src/com/ooooo/Solution1.java
package com.ooooo;
class Solution1 {
public int countGoodTriplets(int[] arr, int a, int b, int c) {
int count = 0;
for (int i = 0; i < arr.length - 2; i++) {
for (int j = i + 1; j < arr.length - 1; j++) {
// 先判断一个
if (Math.abs(arr[i] - arr[j]) > a) continue;
for (int k = j + 1; k < arr.length; k++) {
if (Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) {
count++;
}
}
}
}
return count;
}
private static void test(int[] arr, int a, int b, int c) {
Solution1 solution = new Solution1();
int i = solution.countGoodTriplets(arr, a, b, c);
System.out.println(i);
}
public static void main(String[] args) {
test(new int[]{
3, 0, 1, 1, 9, 7
}, 7, 2, 3); // 4
test(new int[]{
1, 1, 2, 2, 3
}, 0, 0, 1); // 0
}
}
|
eurecom-s3/invscov
|
daikon/tests/kvasir-tests/GlobalTest/GlobalTest.c
|
<gh_stars>10-100
#include <stdio.h>
#include <stdlib.h>
typedef long long int rhubarbInt64;
typedef unsigned long long int UrhubarbInt64;
typedef unsigned int* UIntPtr;
char* globalStr = "MR FURLEY\t\nis a good man\rhello\tworld\t\n\n\n\\ \r \r a\r \\b \\c";
unsigned char* localAddr;
int globalInt = 5555;
double globalDouble = 12345.67890123;
unsigned long long int globalLong = 6969696969696969;
static const int globalWkdayA = 4;
char* returnChar(char** charPtr)
{
return 0;
}
int main()
{
printf("char* globalStr: %p\n", &globalStr);
printf("unsigned char* localAddr: %p\n", &localAddr);
printf("int globalInt: %p\n", &globalInt);
printf("double globalDouble: %p\n", &globalDouble);
printf("unsigned long long int globalLong: %p\n", &globalLong);
printf("static const int globalWkdayA: %p\n", &globalWkdayA);
return 0;
}
|
kkcookies99/UAST
|
Dataset/Leetcode/train/102/733.py
|
class Solution:
def XXX(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
queue = [root,]
output = []
while len(queue)!=0:
size = len(queue)
list1 = []
while size > 0:
temp = queue[0]
del queue[0]
if temp:
list1.append(temp.val)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
size = size -1
output.append(list1)
return output
|
noob/HousingMarket-Server
|
src/main/java/com/dale/ms/entities/HmUser.java
|
package com.dale.ms.entities;
import java.sql.Timestamp;
/**
* HmUser entity. @author MyEclipse Persistence Tools
*/
public class HmUser implements java.io.Serializable {
// Fields
private Long userId;
private String userName;
private String password;
private String userImg;
private Integer gender;
private String idCard;
private Timestamp createTime;
private String mobile;
private String address;
private Timestamp lastLoginTime;
private Long storeId;
private Integer isStore;
private String bussinessLicense;
private String storeAddress;
private String storeName;
private String storeMobile;
private String getuiClientId;
private String deviceInfo;
// Constructors
/** default constructor */
public HmUser() {
}
/** minimal constructor */
public HmUser(String userName, String password, Timestamp createTime) {
this.userName = userName;
this.password = password;
this.createTime = createTime;
}
/** full constructor */
public HmUser(String userName, String password, String userImg,
Integer gender, String idCard, Timestamp createTime, String mobile,
String address, Timestamp lastLoginTime, Long storeId,
Integer isStore, String bussinessLicense, String storeAddress,
String storeName, String storeMobile, String getuiClientId,
String deviceInfo) {
this.userName = userName;
this.password = password;
this.userImg = userImg;
this.gender = gender;
this.idCard = idCard;
this.createTime = createTime;
this.mobile = mobile;
this.address = address;
this.lastLoginTime = lastLoginTime;
this.storeId = storeId;
this.isStore = isStore;
this.bussinessLicense = bussinessLicense;
this.storeAddress = storeAddress;
this.storeName = storeName;
this.storeMobile = storeMobile;
this.getuiClientId = getuiClientId;
this.deviceInfo = deviceInfo;
}
// Property accessors
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserImg() {
return this.userImg;
}
public void setUserImg(String userImg) {
this.userImg = userImg;
}
public Integer getGender() {
return this.gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getIdCard() {
return this.idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public Timestamp getCreateTime() {
return this.createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getMobile() {
return this.mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Timestamp getLastLoginTime() {
return this.lastLoginTime;
}
public void setLastLoginTime(Timestamp lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public Long getStoreId() {
return this.storeId;
}
public void setStoreId(Long storeId) {
this.storeId = storeId;
}
public Integer getIsStore() {
return this.isStore;
}
public void setIsStore(Integer isStore) {
this.isStore = isStore;
}
public String getBussinessLicense() {
return this.bussinessLicense;
}
public void setBussinessLicense(String bussinessLicense) {
this.bussinessLicense = bussinessLicense;
}
public String getStoreAddress() {
return this.storeAddress;
}
public void setStoreAddress(String storeAddress) {
this.storeAddress = storeAddress;
}
public String getStoreName() {
return this.storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public String getStoreMobile() {
return this.storeMobile;
}
public void setStoreMobile(String storeMobile) {
this.storeMobile = storeMobile;
}
public String getGetuiClientId() {
return this.getuiClientId;
}
public void setGetuiClientId(String getuiClientId) {
this.getuiClientId = getuiClientId;
}
public String getDeviceInfo() {
return this.deviceInfo;
}
public void setDeviceInfo(String deviceInfo) {
this.deviceInfo = deviceInfo;
}
}
|
rajeev02101987/arangodb
|
3rdParty/boost/1.71.0/libs/random/test/statistic_tests.hpp
|
<filename>3rdParty/boost/1.71.0/libs/random/test/statistic_tests.hpp
/* statistic_tests.hpp header file
*
* Copyright <NAME> 2000
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* $Id$
*
*/
#ifndef STATISTIC_TESTS_HPP
#define STATISTIC_TESTS_HPP
#include <stdexcept>
#include <iterator>
#include <vector>
#include <boost/limits.hpp>
#include <algorithm>
#include <cmath>
#include <boost/config.hpp>
#include <boost/bind.hpp>
#include <boost/random/uniform_01.hpp>
#include <boost/random/variate_generator.hpp>
#include "integrate.hpp"
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
namespace std
{
inline double pow(double a, double b) { return ::pow(a,b); }
inline double ceil(double x) { return ::ceil(x); }
} // namespace std
#endif
template<class T>
inline T fac(int k)
{
T result = 1;
for(T i = 2; i <= k; ++i)
result *= i;
return result;
}
template<class T>
T binomial(int n, int k)
{
if(k < n/2)
k = n-k;
T result = 1;
for(int i = k+1; i<= n; ++i)
result *= i;
return result / fac<T>(n-k);
}
template<class T>
T stirling2(int n, int m)
{
T sum = 0;
for(int k = 0; k <= m; ++k)
sum += binomial<T>(m, k) * std::pow(double(k), n) *
( (m-k)%2 == 0 ? 1 : -1);
return sum / fac<T>(m);
}
/*
* Experiments which create an empirical distribution in classes,
* suitable for the chi-square test.
*/
// std::floor(gen() * classes)
class experiment_base
{
public:
experiment_base(int cls) : _classes(cls) { }
unsigned int classes() const { return _classes; }
protected:
unsigned int _classes;
};
class equidistribution_experiment : public experiment_base
{
public:
explicit equidistribution_experiment(unsigned int classes)
: experiment_base(classes) { }
template<class NumberGenerator, class Counter>
void run(NumberGenerator & f, Counter & count, int n) const
{
assert((f.min)() == 0 &&
static_cast<unsigned int>((f.max)()) == classes()-1);
for(int i = 0; i < n; ++i)
count(f());
}
double probability(int /*i*/) const { return 1.0/classes(); }
};
// two-dimensional equidistribution experiment
class equidistribution_2d_experiment : public equidistribution_experiment
{
public:
explicit equidistribution_2d_experiment(unsigned int classes)
: equidistribution_experiment(classes) { }
template<class NumberGenerator, class Counter>
void run(NumberGenerator & f, Counter & count, int n) const
{
unsigned int range = (f.max)()+1;
assert((f.min)() == 0 && range*range == classes());
for(int i = 0; i < n; ++i) {
int y1 = f();
int y2 = f();
count(y1 + range * y2);
}
}
};
// distribution experiment: assume a probability density and
// count events so that an equidistribution results.
class distribution_experiment : public equidistribution_experiment
{
public:
template<class Distribution>
distribution_experiment(Distribution dist , unsigned int classes)
: equidistribution_experiment(classes), limit(classes)
{
for(unsigned int i = 0; i < classes-1; ++i)
limit[i] = quantile(dist, (i+1)*0.05);
limit[classes-1] = std::numeric_limits<double>::infinity();
if(limit[classes-1] < (std::numeric_limits<double>::max)())
limit[classes-1] = (std::numeric_limits<double>::max)();
#if 0
std::cout << __PRETTY_FUNCTION__ << ": ";
for(unsigned int i = 0; i < classes; ++i)
std::cout << limit[i] << " ";
std::cout << std::endl;
#endif
}
template<class NumberGenerator, class Counter>
void run(NumberGenerator & f, Counter & count, int n) const
{
for(int i = 0; i < n; ++i) {
limits_type::const_iterator it =
std::lower_bound(limit.begin(), limit.end(), f());
count(it-limit.begin());
}
}
private:
typedef std::vector<double> limits_type;
limits_type limit;
};
template<bool up, bool is_float>
struct runs_direction_helper
{
template<class T>
static T init(T)
{
return (std::numeric_limits<T>::max)();
}
};
template<>
struct runs_direction_helper<true, true>
{
template<class T>
static T init(T)
{
return -(std::numeric_limits<T>::max)();
}
};
template<>
struct runs_direction_helper<true, false>
{
template<class T>
static T init(T)
{
return (std::numeric_limits<T>::min)();
}
};
// runs-up/runs-down experiment
template<bool up>
class runs_experiment : public experiment_base
{
public:
explicit runs_experiment(unsigned int classes) : experiment_base(classes) { }
template<class NumberGenerator, class Counter>
void run(NumberGenerator & f, Counter & count, int n) const
{
typedef typename NumberGenerator::result_type result_type;
result_type init =
runs_direction_helper<
up,
!std::numeric_limits<result_type>::is_integer
>::init(result_type());
result_type previous = init;
unsigned int length = 0;
for(int i = 0; i < n; ++i) {
result_type val = f();
if(up ? previous <= val : previous >= val) {
previous = val;
++length;
} else {
count((std::min)(length, classes())-1);
length = 0;
previous = init;
// don't use this value, so that runs are independent
}
}
}
double probability(unsigned int r) const
{
if(r == classes()-1)
return 1.0/fac<double>(classes());
else
return static_cast<double>(r+1)/fac<double>(r+2);
}
};
// gap length experiment
class gap_experiment : public experiment_base
{
public:
template<class Dist>
gap_experiment(unsigned int classes, const Dist & dist, double alpha, double beta)
: experiment_base(classes), alpha(alpha), beta(beta), low(quantile(dist, alpha)), high(quantile(dist, beta)) {}
template<class NumberGenerator, class Counter>
void run(NumberGenerator & f, Counter & count, int n) const
{
typedef typename NumberGenerator::result_type result_type;
unsigned int length = 0;
for(int i = 0; i < n; ) {
result_type value = f();
if(value < low || value > high)
++length;
else {
count((std::min)(length, classes()-1));
length = 0;
++i;
}
}
}
double probability(unsigned int r) const
{
double p = beta-alpha;
if(r == classes()-1)
return std::pow(1-p, static_cast<double>(r));
else
return p * std::pow(1-p, static_cast<double>(r));
}
private:
double alpha, beta;
double low, high;
};
// poker experiment
class poker_experiment : public experiment_base
{
public:
poker_experiment(unsigned int d, unsigned int k)
: experiment_base(k), range(d)
{
assert(range > 1);
}
template<class UniformRandomNumberGenerator, class Counter>
void run(UniformRandomNumberGenerator & f, Counter & count, int n) const
{
typedef typename UniformRandomNumberGenerator::result_type result_type;
assert(std::numeric_limits<result_type>::is_integer);
assert((f.min)() == 0);
assert((f.max)() == static_cast<result_type>(range-1));
std::vector<result_type> v(classes());
for(int i = 0; i < n; ++i) {
for(unsigned int j = 0; j < classes(); ++j)
v[j] = f();
std::sort(v.begin(), v.end());
result_type prev = v[0];
int r = 1; // count different values in v
for(unsigned int i = 1; i < classes(); ++i) {
if(prev != v[i]) {
prev = v[i];
++r;
}
}
count(r-1);
}
}
double probability(unsigned int r) const
{
++r; // transform to 1 <= r <= 5
double result = range;
for(unsigned int i = 1; i < r; ++i)
result *= range-i;
return result / std::pow(range, static_cast<double>(classes())) *
stirling2<double>(classes(), r);
}
private:
unsigned int range;
};
// coupon collector experiment
class coupon_collector_experiment : public experiment_base
{
public:
coupon_collector_experiment(unsigned int d, unsigned int cls)
: experiment_base(cls), d(d)
{
assert(d > 1);
}
template<class UniformRandomNumberGenerator, class Counter>
void run(UniformRandomNumberGenerator & f, Counter & count, int n) const
{
typedef typename UniformRandomNumberGenerator::result_type result_type;
assert(std::numeric_limits<result_type>::is_integer);
assert((f.min)() == 0);
assert((f.max)() == static_cast<result_type>(d-1));
std::vector<bool> occurs(d);
for(int i = 0; i < n; ++i) {
occurs.assign(d, false);
unsigned int r = 0; // length of current sequence
int q = 0; // number of non-duplicates in current set
for(;;) {
result_type val = f();
++r;
if(!occurs[val]) { // new set element
occurs[val] = true;
++q;
if(q == d)
break; // one complete set
}
}
count((std::min)(r-d, classes()-1));
}
}
double probability(unsigned int r) const
{
if(r == classes()-1)
return 1-fac<double>(d)/
std::pow(static_cast<double>(d), static_cast<double>(d+classes()-2)) *
stirling2<double>(d+classes()-2, d);
else
return fac<double>(d)/
std::pow(static_cast<double>(d), static_cast<double>(d+r)) *
stirling2<double>(d+r-1, d-1);
}
private:
int d;
};
// permutation test
class permutation_experiment : public equidistribution_experiment
{
public:
permutation_experiment(unsigned int t)
: equidistribution_experiment(fac<int>(t)), t(t)
{
assert(t > 1);
}
template<class UniformRandomNumberGenerator, class Counter>
void run(UniformRandomNumberGenerator & f, Counter & count, int n) const
{
typedef typename UniformRandomNumberGenerator::result_type result_type;
std::vector<result_type> v(t);
for(int i = 0; i < n; ++i) {
for(int j = 0; j < t; ++j) {
v[j] = f();
}
int x = 0;
for(int r = t-1; r > 0; r--) {
typename std::vector<result_type>::iterator it =
std::max_element(v.begin(), v.begin()+r+1);
x = (r+1)*x + (it-v.begin());
std::iter_swap(it, v.begin()+r);
}
count(x);
}
}
private:
int t;
};
// birthday spacing experiment test
class birthday_spacing_experiment : public experiment_base
{
public:
birthday_spacing_experiment(unsigned int d, int n, int m)
: experiment_base(d), n(n), m(m)
{
}
template<class UniformRandomNumberGenerator, class Counter>
void run(UniformRandomNumberGenerator & f, Counter & count, int n_total) const
{
typedef typename UniformRandomNumberGenerator::result_type result_type;
assert(std::numeric_limits<result_type>::is_integer);
assert((f.min)() == 0);
assert((f.max)() == static_cast<result_type>(m-1));
for(int j = 0; j < n_total; j++) {
std::vector<result_type> v(n);
std::generate_n(v.begin(), n, f);
std::sort(v.begin(), v.end());
std::vector<result_type> spacing(n);
for(int i = 0; i < n-1; i++)
spacing[i] = v[i+1]-v[i];
spacing[n-1] = v[0] + m - v[n-1];
std::sort(spacing.begin(), spacing.end());
unsigned int k = 0;
for(int i = 0; i < n-1; ++i) {
if(spacing[i] == spacing[i+1])
++k;
}
count((std::min)(k, classes()-1));
}
}
double probability(unsigned int r) const
{
assert(classes() == 4);
assert(m == (1<<25));
assert(n == 512);
static const double prob[] = { 0.368801577, 0.369035243, 0.183471182,
0.078691997 };
return prob[r];
}
private:
int n, m;
};
/*
* Misc. helper functions.
*/
template<class Float>
struct distribution_function
{
typedef Float result_type;
typedef Float argument_type;
typedef Float first_argument_type;
typedef Float second_argument_type;
};
// computes P(K_n <= t) or P(t1 <= K_n <= t2). See Knuth, 3.3.1
class kolmogorov_smirnov_probability : public distribution_function<double>
{
public:
kolmogorov_smirnov_probability(int n)
: approx(n > 50), n(n), sqrt_n(std::sqrt(double(n)))
{
if(!approx)
n_n = std::pow(static_cast<double>(n), n);
}
double cdf(double t) const
{
if(approx) {
return 1-std::exp(-2*t*t)*(1-2.0/3.0*t/sqrt_n);
} else {
t *= sqrt_n;
double sum = 0;
for(int k = static_cast<int>(std::ceil(t)); k <= n; k++)
sum += binomial<double>(n, k) * std::pow(k-t, k) *
std::pow(t+n-k, n-k-1);
return 1 - t/n_n * sum;
}
}
//double operator()(double t1, double t2) const
//{ return operator()(t2) - operator()(t1); }
private:
bool approx;
int n;
double sqrt_n;
double n_n;
};
inline double cdf(const kolmogorov_smirnov_probability& dist, double val)
{
return dist.cdf(val);
}
inline double quantile(const kolmogorov_smirnov_probability& dist, double val)
{
return invert_monotone_inc(boost::bind(&cdf, dist, _1), val, 0.0, 1000.0);
}
/*
* Experiments for generators with continuous distribution functions
*/
class kolmogorov_experiment
{
public:
kolmogorov_experiment(int n) : n(n), ksp(n) { }
template<class NumberGenerator, class Distribution>
double run(NumberGenerator & gen, Distribution distrib) const
{
const int m = n;
typedef std::vector<double> saved_temp;
saved_temp a(m,1.0), b(m,0);
std::vector<int> c(m,0);
for(int i = 0; i < n; ++i) {
double val = static_cast<double>(gen());
double y = cdf(distrib, val);
int k = static_cast<int>(std::floor(m*y));
if(k >= m)
--k; // should not happen
a[k] = (std::min)(a[k], y);
b[k] = (std::max)(b[k], y);
++c[k];
}
double kplus = 0, kminus = 0;
int j = 0;
for(int k = 0; k < m; ++k) {
if(c[k] > 0) {
kminus = (std::max)(kminus, a[k]-j/static_cast<double>(n));
j += c[k];
kplus = (std::max)(kplus, j/static_cast<double>(n) - b[k]);
}
}
kplus *= std::sqrt(double(n));
kminus *= std::sqrt(double(n));
// std::cout << "k+ " << kplus << " k- " << kminus << std::endl;
return kplus;
}
double probability(double x) const
{
return cdf(ksp, x);
}
private:
int n;
kolmogorov_smirnov_probability ksp;
};
struct power_distribution
{
power_distribution(double t) : t(t) {}
double t;
};
double cdf(const power_distribution& dist, double val)
{
return std::pow(val, dist.t);
}
// maximum-of-t test (KS-based)
template<class UniformRandomNumberGenerator>
class maximum_experiment
{
public:
typedef UniformRandomNumberGenerator base_type;
maximum_experiment(base_type & f, int n, int t) : f(f), ke(n), t(t)
{ }
double operator()() const
{
generator gen(f, t);
return ke.run(gen, power_distribution(t));
}
private:
struct generator {
generator(base_type & f, int t) : f(f, boost::uniform_01<>()), t(t) { }
double operator()()
{
double mx = f();
for(int i = 1; i < t; ++i)
mx = (std::max)(mx, f());
return mx;
}
private:
boost::variate_generator<base_type&, boost::uniform_01<> > f;
int t;
};
base_type & f;
kolmogorov_experiment ke;
int t;
};
// compute a chi-square value for the distribution approximation error
template<class ForwardIterator, class UnaryFunction>
typename UnaryFunction::result_type
chi_square_value(ForwardIterator first, ForwardIterator last,
UnaryFunction probability)
{
typedef std::iterator_traits<ForwardIterator> iter_traits;
typedef typename iter_traits::value_type counter_type;
typedef typename UnaryFunction::result_type result_type;
unsigned int classes = std::distance(first, last);
result_type sum = 0;
counter_type n = 0;
for(unsigned int i = 0; i < classes; ++first, ++i) {
counter_type count = *first;
n += count;
sum += (count/probability(i)) * count; // avoid overflow
}
#if 0
for(unsigned int i = 0; i < classes; ++i) {
// std::cout << (n*probability(i)) << " ";
if(n * probability(i) < 5)
std::cerr << "Not enough test runs for slot " << i
<< " p=" << probability(i) << ", n=" << n
<< std::endl;
}
#endif
// std::cout << std::endl;
// throw std::invalid_argument("not enough test runs");
return sum/n - n;
}
template<class RandomAccessContainer>
class generic_counter
{
public:
explicit generic_counter(unsigned int classes) : container(classes, 0) { }
void operator()(int i)
{
assert(i >= 0);
assert(static_cast<unsigned int>(i) < container.size());
++container[i];
}
typename RandomAccessContainer::const_iterator begin() const
{ return container.begin(); }
typename RandomAccessContainer::const_iterator end() const
{ return container.end(); }
private:
RandomAccessContainer container;
};
// chi_square test
template<class Experiment, class Generator>
double run_experiment(const Experiment & experiment, Generator & gen, int n)
{
generic_counter<std::vector<int> > v(experiment.classes());
experiment.run(gen, v, n);
return chi_square_value(v.begin(), v.end(),
boost::bind(&Experiment::probability,
experiment, boost::placeholders::_1));
}
// chi_square test
template<class Experiment, class Generator>
double run_experiment(const Experiment & experiment, const Generator & gen, int n)
{
generic_counter<std::vector<int> > v(experiment.classes());
experiment.run(gen, v, n);
return chi_square_value(v.begin(), v.end(),
boost::bind(&Experiment::probability,
experiment, boost::placeholders::_1));
}
// number generator with experiment results (for nesting)
template<class Experiment, class Generator>
class experiment_generator_t
{
public:
experiment_generator_t(const Experiment & exper, Generator & gen, int n)
: experiment(exper), generator(gen), n(n) { }
double operator()() const { return run_experiment(experiment, generator, n); }
private:
const Experiment & experiment;
Generator & generator;
int n;
};
template<class Experiment, class Generator>
experiment_generator_t<Experiment, Generator>
experiment_generator(const Experiment & e, Generator & gen, int n)
{
return experiment_generator_t<Experiment, Generator>(e, gen, n);
}
template<class Experiment, class Generator, class Distribution>
class ks_experiment_generator_t
{
public:
ks_experiment_generator_t(const Experiment & exper, Generator & gen,
const Distribution & distrib)
: experiment(exper), generator(gen), distribution(distrib) { }
double operator()() const { return experiment.run(generator, distribution); }
private:
const Experiment & experiment;
Generator & generator;
Distribution distribution;
};
template<class Experiment, class Generator, class Distribution>
ks_experiment_generator_t<Experiment, Generator, Distribution>
ks_experiment_generator(const Experiment & e, Generator & gen,
const Distribution & distrib)
{
return ks_experiment_generator_t<Experiment, Generator, Distribution>
(e, gen, distrib);
}
#endif /* STATISTIC_TESTS_HPP */
|
NunoEdgarGFlowHub/presto
|
presto-main/src/main/java/com/facebook/presto/operator/RoundRobinPartitionGenerator.java
|
<filename>presto-main/src/main/java/com/facebook/presto/operator/RoundRobinPartitionGenerator.java
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator;
import com.facebook.presto.spi.Page;
import com.google.common.base.MoreObjects;
public class RoundRobinPartitionGenerator
implements PartitionGenerator
{
private int counter;
public RoundRobinPartitionGenerator() {}
@Override
public int getPartitionBucket(int partitionCount, int position, Page page)
{
int bucket = counter % partitionCount;
counter = (counter + 1) & 0x7fff_ffff;
return bucket;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("counter", counter)
.toString();
}
}
|
surli/spinefm
|
spinefm-eclipseplugins-root/spinefm-core/src-gen/fr/unice/spinefm/ConfigurationModel/exceptions/ExceptionsPackage.java
|
<reponame>surli/spinefm
/**
*/
package fr.unice.spinefm.ConfigurationModel.exceptions;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EPackage;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see fr.unice.spinefm.ConfigurationModel.exceptions.ExceptionsFactory
* @model kind="package"
* @generated
*/
public interface ExceptionsPackage extends EPackage
{
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "exceptions";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "exceptions.cm.spinefm.unice.fr";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "cm.exceptions";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
ExceptionsPackage eINSTANCE = fr.unice.spinefm.ConfigurationModel.exceptions.impl.ExceptionsPackageImpl.init();
/**
* The meta object id for the '<em>Config Not Found Exception</em>' data type.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see fr.unice.spinefm.ConfigurationModel.exceptions.ConfigNotFoundException
* @see fr.unice.spinefm.ConfigurationModel.exceptions.impl.ExceptionsPackageImpl#getConfigNotFoundException()
* @generated
*/
int CONFIG_NOT_FOUND_EXCEPTION = 0;
/**
* The meta object id for the '<em>Invalid Association Exception</em>' data type.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see fr.unice.spinefm.ConfigurationModel.exceptions.InvalidAssociationException
* @see fr.unice.spinefm.ConfigurationModel.exceptions.impl.ExceptionsPackageImpl#getInvalidAssociationException()
* @generated
*/
int INVALID_ASSOCIATION_EXCEPTION = 1;
/**
* The meta object id for the '<em>Link Not Found Exception</em>' data type.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see fr.unice.spinefm.ConfigurationModel.exceptions.LinkNotFoundException
* @see fr.unice.spinefm.ConfigurationModel.exceptions.impl.ExceptionsPackageImpl#getLinkNotFoundException()
* @generated
*/
int LINK_NOT_FOUND_EXCEPTION = 2;
/**
* Returns the meta object for data type '{@link fr.unice.spinefm.ConfigurationModel.exceptions.ConfigNotFoundException <em>Config Not Found Exception</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for data type '<em>Config Not Found Exception</em>'.
* @see fr.unice.spinefm.ConfigurationModel.exceptions.ConfigNotFoundException
* @model instanceClass="fr.unice.spinefm.ConfigurationModel.exceptions.ConfigNotFoundException"
* @generated
*/
EDataType getConfigNotFoundException();
/**
* Returns the meta object for data type '{@link fr.unice.spinefm.ConfigurationModel.exceptions.InvalidAssociationException <em>Invalid Association Exception</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for data type '<em>Invalid Association Exception</em>'.
* @see fr.unice.spinefm.ConfigurationModel.exceptions.InvalidAssociationException
* @model instanceClass="fr.unice.spinefm.ConfigurationModel.exceptions.InvalidAssociationException"
* @generated
*/
EDataType getInvalidAssociationException();
/**
* Returns the meta object for data type '{@link fr.unice.spinefm.ConfigurationModel.exceptions.LinkNotFoundException <em>Link Not Found Exception</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for data type '<em>Link Not Found Exception</em>'.
* @see fr.unice.spinefm.ConfigurationModel.exceptions.LinkNotFoundException
* @model instanceClass="fr.unice.spinefm.ConfigurationModel.exceptions.LinkNotFoundException"
* @generated
*/
EDataType getLinkNotFoundException();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
ExceptionsFactory getExceptionsFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals
{
/**
* The meta object literal for the '<em>Config Not Found Exception</em>' data type.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see fr.unice.spinefm.ConfigurationModel.exceptions.ConfigNotFoundException
* @see fr.unice.spinefm.ConfigurationModel.exceptions.impl.ExceptionsPackageImpl#getConfigNotFoundException()
* @generated
*/
EDataType CONFIG_NOT_FOUND_EXCEPTION = eINSTANCE.getConfigNotFoundException();
/**
* The meta object literal for the '<em>Invalid Association Exception</em>' data type.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see fr.unice.spinefm.ConfigurationModel.exceptions.InvalidAssociationException
* @see fr.unice.spinefm.ConfigurationModel.exceptions.impl.ExceptionsPackageImpl#getInvalidAssociationException()
* @generated
*/
EDataType INVALID_ASSOCIATION_EXCEPTION = eINSTANCE.getInvalidAssociationException();
/**
* The meta object literal for the '<em>Link Not Found Exception</em>' data type.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see fr.unice.spinefm.ConfigurationModel.exceptions.LinkNotFoundException
* @see fr.unice.spinefm.ConfigurationModel.exceptions.impl.ExceptionsPackageImpl#getLinkNotFoundException()
* @generated
*/
EDataType LINK_NOT_FOUND_EXCEPTION = eINSTANCE.getLinkNotFoundException();
}
} //ExceptionsPackage
|
yanzhe-chen/LeetCode
|
include/ValidSudoku.hpp
|
<reponame>yanzhe-chen/LeetCode
#ifndef VALID_SUDOKU_HPP_
#define VALID_SUDOKU_HPP_
#include <vector>
using namespace std;
class ValidSudoku {
public:
bool isValidSudoku(vector<vector<char>> &board);
};
#endif // VALID_SUDOKU_HPP_
|
GenaAiv/portfolio-website
|
node_modules/type/test/finite/coerce.js
|
<reponame>GenaAiv/portfolio-website
"use strict";
var assert = require("chai").assert
, coerceToFinite = require("../../finite/coerce");
describe("finite/coerce", function () {
it("Should return input number", function () {
assert.equal(coerceToFinite(123.123), 123.123);
});
it("Should coerce string", function () { assert.equal(coerceToFinite("12"), 12); });
it("Should coerce booleans", function () { assert.equal(coerceToFinite(true), 1); });
it("Should coerce number objects", function () {
assert.equal(coerceToFinite(new Number(343)), 343);
});
it("Should coerce objects", function () {
assert.equal(coerceToFinite({ valueOf: function () { return 23; } }), 23);
});
it("Should reject infinite number", function () {
assert.equal(coerceToFinite(Infinity), null);
});
it("Should reject NaN", function () { assert.equal(coerceToFinite(NaN), null); });
if (typeof Object.create === "function") {
it("Should not coerce objects with no number representation", function () {
assert.equal(coerceToFinite(Object.create(null)), null);
});
}
it("Should not coerce null", function () { assert.equal(coerceToFinite(null), null); });
it("Should not coerce undefined", function () {
assert.equal(coerceToFinite(undefined), null);
});
if (typeof Symbol === "function") {
it("Should not coerce symbols", function () {
assert.equal(coerceToFinite(Symbol("foo")), null);
});
}
});
|
cquiroz/ocs
|
bundle/edu.gemini.spdb.shell/src/main/java/edu/gemini/spdb/shell/misc/LsProgs.java
|
<filename>bundle/edu.gemini.spdb.shell/src/main/java/edu/gemini/spdb/shell/misc/LsProgs.java
package edu.gemini.spdb.shell.misc;
import edu.gemini.pot.sp.ISPNode;
import edu.gemini.spModel.core.SPProgramID;
import edu.gemini.pot.spdb.DBAbstractQueryFunctor;
import edu.gemini.pot.spdb.IDBDatabaseService;
import java.security.Principal;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public final class LsProgs extends DBAbstractQueryFunctor {
private final SortedSet<SPProgramID> ids = new TreeSet<SPProgramID>();
public void execute(IDBDatabaseService arg0, ISPNode arg1, Set<Principal> principals) {
SPProgramID id = arg1.getProgramID();
if (id != null)
ids.add(id);
}
public SortedSet<SPProgramID> ids() {
return ids;
}
}
|
SettingDust/MistyWorld_Open
|
src/main/java/ru/liahim/mist/block/gizmos/Remains.java
|
<gh_stars>1-10
package ru.liahim.mist.block.gizmos;
import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.EnumPushReaction;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import ru.liahim.mist.api.block.IShiftPlaceable;
import ru.liahim.mist.api.item.MistItems;
import ru.liahim.mist.entity.EntityGraveBug;
import ru.liahim.mist.init.ModAdvancements;
import ru.liahim.mist.tileentity.TileEntityRemains;
public class Remains extends MistBlockContainer implements IShiftPlaceable {
public static final PropertyInteger LAYERS = PropertyInteger.create("layers", 0, 7);
public static final PropertyBool OLD = PropertyBool.create("old");
public Remains() {
super(Material.GROUND);
this.setSoundType(SoundType.GROUND);
this.setDefaultState(this.blockState.getBaseState().withProperty(LAYERS, 0).withProperty(OLD, false));
this.setHardness(1.0F);
this.setHarvestLevel("shovel", 0);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
return new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, (state.getValue(LAYERS) + 1) * 0.125D, 1.0D);
}
@Override
@Nullable
public AxisAlignedBB getCollisionBoundingBox(IBlockState state, IBlockAccess worldIn, BlockPos pos) {
return new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, state.getValue(LAYERS) * 0.125D + 0.0625D, 1.0D);
}
@Override
public boolean isPassable(IBlockAccess world, BlockPos pos) {
return (world.getBlockState(pos).getValue(LAYERS)) < 4;
}
@Override
public boolean isTopSolid(IBlockState state) {
return (state.getValue(LAYERS)) == 7;
}
@Override
public BlockFaceShape getBlockFaceShape(IBlockAccess world, IBlockState state, BlockPos pos, EnumFacing face) {
return face == EnumFacing.DOWN || state.getValue(LAYERS) == 7 ? BlockFaceShape.SOLID : BlockFaceShape.UNDEFINED;
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
ItemStack heldItem = player.getHeldItem(hand);
if (Block.getBlockFromItem(heldItem.getItem()) == this) return false;
if (!heldItem.isEmpty()) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof TileEntityRemains) {
TileEntityRemains remains = (TileEntityRemains) te;
if (heldItem.getItem() == MistItems.REMAINS) {
if (side != EnumFacing.UP) return false;
if (state.getValue(LAYERS) < 7) {
NBTTagCompound tag = remains.writeItems(new NBTTagCompound());
if (world.setBlockState(pos, state.withProperty(LAYERS, state.getValue(LAYERS) + 1))) {
((TileEntityRemains) world.getTileEntity(pos)).readItems(tag);
world.playSound(null, pos, SoundEvents.BLOCK_GRAVEL_PLACE, SoundCategory.BLOCKS, 1.0F, 0.8F);
if (!player.capabilities.isCreativeMode) heldItem.shrink(1);
return true;
}
} else if (world.getBlockState(pos.up()).getMaterial().isReplaceable()) {
world.setBlockState(pos.up(), this.getDefaultState());
world.playSound(null, pos, SoundEvents.BLOCK_GRAVEL_PLACE, SoundCategory.BLOCKS, 1.0F, 0.8F);
if (!player.capabilities.isCreativeMode) heldItem.setCount(heldItem.getCount() - 1);
return true;
}
} else if (remains.putStack(heldItem)) {
world.playSound(null, pos, SoundEvents.ITEM_HOE_TILL, SoundCategory.BLOCKS, 0.8F, 1.0F);
return true;
}
}
}
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state) {
return isFullCube(state);
}
@Override
public boolean isFullCube(IBlockState state) {
return state.getValue(LAYERS) == 7;
}
@Override
public void onBlockHarvested(World world, BlockPos pos, IBlockState state, EntityPlayer player) {
if (state.getValue(OLD) && player instanceof EntityPlayerMP) {
ModAdvancements.REMAINS.trigger((EntityPlayerMP)player, world, pos, state);
}
}
@Override
public void neighborChanged(IBlockState state, World world, BlockPos pos, Block block, BlockPos fromPos) {
if (!world.isRemote && !state.getValue(OLD) && !world.isSideSolid(pos.down(), EnumFacing.UP))
world.destroyBlock(pos, true);
}
@Override
public TileEntity createNewTileEntity(World world, int meta) {
TileEntityRemains te = new TileEntityRemains();
te.init(((meta & 7) + 1) * 3);
return te;
}
@Override
public EnumPushReaction getMobilityFlag(IBlockState state) {
return EnumPushReaction.DESTROY;
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state) {
return EnumBlockRenderType.MODEL;
}
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
list.add(new ItemStack(this, 1, 7));
}
@Override
public void breakBlock(World world, BlockPos pos, IBlockState state) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof IInventory) {
dropInventoryItems(world, pos, (IInventory)te);
world.updateComparatorOutputLevel(pos, this);
}
if (state.getValue(OLD)) {
for (EnumFacing face : EnumFacing.HORIZONTALS) {
IBlockState neighbor = world.getBlockState(pos.offset(face));
if (neighbor.getBlock() == this && neighbor.getValue(OLD)) world.destroyBlock(pos.offset(face), true);
}
EntityGraveBug.spawnBug(world, pos, world.rand);
}
super.breakBlock(world, pos, state);
}
private static void dropInventoryItems(World world, BlockPos pos, IInventory inventory) {
for (int i = 0; i < inventory.getSizeInventory(); ++i) {
ItemStack stack = inventory.getStackInSlot(i);
if (!stack.isEmpty()) spawnItemStack(world, pos, stack, world.rand);
}
}
private static void spawnItemStack(World world, BlockPos pos, ItemStack stack, Random rand) {
float f = rand.nextFloat() * 0.8F + 0.1F;
float f1 = rand.nextFloat() * 0.8F + 0.1F;
float f2 = rand.nextFloat() * 0.8F + 0.1F;
while (!stack.isEmpty()) {
EntityItem entity = new EntityItem(world, pos.getX() + (double) f, pos.getY() + (double) f1, pos.getZ() + (double) f2, stack.splitStack(rand.nextInt(21) + 10));
entity.motionX = rand.nextGaussian() * 0.05D;
entity.motionY = rand.nextGaussian() * 0.05D + 0.2D;
entity.motionZ = rand.nextGaussian() * 0.05D;
entity.setPickupDelay(20);
world.spawnEntity(entity);
}
}
@Override
public Item getItemDropped(IBlockState state, Random rand, int fortune) {
return MistItems.REMAINS;
}
@Override
public int quantityDropped(IBlockState state, int fortune, Random rand) {
return state.getValue(OLD) ? rand.nextInt(rand.nextInt(state.getValue(LAYERS) + 1) + 1) : state.getValue(LAYERS) + 1;
}
@Nullable
public ILockableContainer getLockableContainer(World world, BlockPos pos) {
return this.getContainer(world, pos, false);
}
@Nullable
public ILockableContainer getContainer(World world, BlockPos pos, boolean allowBlocking) {
TileEntity tileentity = world.getTileEntity(pos);
if (!(tileentity instanceof TileEntityRemains)) return null;
if (!allowBlocking) return null;
return (TileEntityRemains)tileentity;
}
@Override
public boolean hasComparatorInputOverride(IBlockState state) {
return true;
}
@Override
public int getComparatorInputOverride(IBlockState state, World world, BlockPos pos) {
return Container.calcRedstoneFromInventory(this.getLockableContainer(world, pos));
}
@Override
public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) {
int layer = state.getValue(LAYERS);
if (entity.posY < pos.getY() + (layer + 1) * 0.125D) {
if (!world.isRemote && !state.getValue(OLD) && entity != null && entity instanceof EntityItem) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof TileEntityRemains) {
TileEntityRemains remains = (TileEntityRemains) te;
if (remains.cooldown < 0) {
ItemStack stack = ((EntityItem)entity).getItem();
if (stack.getItem() == MistItems.REMAINS) {
if (layer < 7) {
NBTTagCompound tag = remains.writeItems(new NBTTagCompound());
if (world.setBlockState(pos, state.withProperty(LAYERS, state.getValue(LAYERS) + 1))) {
((TileEntityRemains) world.getTileEntity(pos)).readItems(tag);
((EntityItem)entity).getItem().shrink(1);
entity.setPosition(entity.posX, entity.posY + 0.125D, entity.posZ);
}
}
} else if (Block.getBlockFromItem(stack.getItem()) != this) {
remains.pullStack((EntityItem)entity);
}
remains.cooldown = 8;
} else --remains.cooldown;
}
}
entity.motionX *= 0.4D;
entity.motionZ *= 0.4D;
}
}
@Override
public int getMetaFromState(IBlockState state) {
return ((state.getValue(OLD) ? 1 : 0) << 3) | state.getValue(LAYERS);
}
@Override
public IBlockState getStateFromMeta(int meta) {
return this.getDefaultState().withProperty(LAYERS, meta & 7).withProperty(OLD, meta > 7);
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, new IProperty[] { LAYERS, OLD });
}
@Override
public boolean canSilkHarvest(World world, BlockPos pos, IBlockState state, EntityPlayer player) {
return false;
}
@Override
@SideOnly(Side.CLIENT)
public boolean shouldSideBeRendered(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
if (side == EnumFacing.UP) return true;
IBlockState checkState = world.getBlockState(pos.offset(side));
return checkState.getBlock() == this && checkState.getValue(LAYERS) >= state.getValue(LAYERS) ? false : super.shouldSideBeRendered(state, world, pos, side);
}
@Override
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) {
return state.getValue(LAYERS) == 7 ? new ItemStack(this, 1, 7) : new ItemStack(MistItems.REMAINS, 1);
}
@Override
public boolean onShiftPlacing(World world, BlockPos pos, ItemStack stack, EntityPlayer player, float hitX, float hitY, float hitZ, BlockFaceShape bfs) {
if (bfs != BlockFaceShape.SOLID) return false;
if (stack.getItem() == MistItems.REMAINS && world.setBlockState(pos, this.getDefaultState())) {
world.playSound(null, pos, SoundEvents.BLOCK_GRAVEL_PLACE, SoundCategory.BLOCKS, 1.0F, 0.8F);
//if (player instanceof EntityPlayerMP) ModAdvancements.COMPOST.trigger((EntityPlayerMP)player, stack);
if (!player.capabilities.isCreativeMode) stack.setCount(stack.getCount() - 1);
return true;
}
return false;
}
}
|
thiamchi/micropython_custom
|
lib/btstack/test/obex/obex_message_builder_test.c
|
#include "CppUTest/TestHarness.h"
#include "CppUTest/CommandLineTestRunner.h"
#include "btstack_util.h"
#include "btstack_debug.h"
#include "classic/obex.h"
#include "classic/obex_message_builder.h"
static const uint8_t service_uuid[] = {0xbb, 0x58, 0x2b, 0x40, 0x42, 0xc, 0x11, 0xdb, 0xb0, 0xde, 0x8, 0x0, 0x20, 0xc, 0x9a, 0x66};
static const uint8_t application_parameters[] = {0x29, 4, 0, 0, 0xFF, 0xFF};
static const char path_element[] = "test";
static const uint8_t flags = 1 << 1;
static const uint16_t maximum_obex_packet_length = 0xFFFF;
static const uint32_t connection_id = 10;
static const uint8_t obex_version_number = OBEX_VERSION;
TEST_GROUP(OBEX_MESSAGE_BUILDER){
uint8_t actual_message[300];
uint16_t actual_message_len;
void setup(void){
actual_message_len = sizeof(actual_message);
memset(actual_message, 0, actual_message_len);
}
void CHECK_EQUAL_ARRAY(const uint8_t * expected, uint8_t * actual, int size){
for (int i=0; i<size; i++){
BYTES_EQUAL(expected[i], actual[i]);
}
}
void validate(uint8_t * expected_message, uint16_t expected_len, uint8_t actual_status, uint8_t expected_status){
CHECK_EQUAL(actual_status, expected_status);
uint16_t actual_len = big_endian_read_16(actual_message, 1);
CHECK_EQUAL(actual_len, expected_len);
CHECK_EQUAL_ARRAY(actual_message, expected_message, expected_len);
}
void validate_invalid_parameter(uint8_t * expected_message, uint16_t expected_len, uint8_t actual_status){
validate(expected_message, expected_len, actual_status, ERROR_CODE_PARAMETER_OUT_OF_MANDATORY_RANGE);
}
void validate_success(uint8_t * expected_message, uint16_t expected_len, uint8_t actual_status){
validate(expected_message, expected_len, actual_status, ERROR_CODE_SUCCESS);
}
};
TEST(OBEX_MESSAGE_BUILDER, CreateConnect){
uint8_t expected_message[] = {OBEX_OPCODE_CONNECT, 0, 0, obex_version_number, flags, 0, 0};
expected_message[2] = sizeof(expected_message);
big_endian_store_16(expected_message, 5, maximum_obex_packet_length);
uint8_t actual_status = obex_message_builder_request_create_connect(actual_message, actual_message_len, obex_version_number, flags, maximum_obex_packet_length);
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateGet){
uint8_t expected_message[] = {OBEX_OPCODE_GET | OBEX_OPCODE_FINAL_BIT_MASK, 0, 0, OBEX_HEADER_CONNECTION_ID, 0, 0, 0, 0};
expected_message[2] = sizeof(expected_message);
big_endian_store_32(expected_message, 4, connection_id);
uint8_t actual_status = obex_message_builder_request_create_get(actual_message, actual_message_len, connection_id);
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateGetInvalidConnectionID){
uint8_t expected_message[] = {OBEX_OPCODE_GET | OBEX_OPCODE_FINAL_BIT_MASK, 0, 0};
expected_message[2] = sizeof(expected_message);
uint8_t actual_status = obex_message_builder_request_create_get(actual_message, actual_message_len, OBEX_CONNECTION_ID_INVALID);
validate_invalid_parameter(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreatePut){
uint8_t expected_message[] = {OBEX_OPCODE_PUT | OBEX_OPCODE_FINAL_BIT_MASK, 0, 0, OBEX_HEADER_CONNECTION_ID, 0, 0, 0, 0};
expected_message[2] = sizeof(expected_message);
big_endian_store_32(expected_message, 4, connection_id);
uint8_t actual_status = obex_message_builder_request_create_put(actual_message, actual_message_len, connection_id);
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateSetPath){
uint8_t expected_message[] = {OBEX_OPCODE_SETPATH, 0, 0, flags, 0, OBEX_HEADER_CONNECTION_ID, 0, 0, 0, 0};
expected_message[2] = sizeof(expected_message);
big_endian_store_32(expected_message, 6, connection_id);
uint8_t actual_status = obex_message_builder_request_create_set_path(actual_message, actual_message_len, flags, connection_id);
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateAbort){
uint8_t expected_message[] = {OBEX_OPCODE_ABORT, 0, 0, OBEX_HEADER_CONNECTION_ID, 0, 0, 0, 0};
expected_message[2] = sizeof(expected_message);
big_endian_store_32(expected_message, 4, connection_id);
uint8_t actual_status = obex_message_builder_request_create_abort(actual_message, actual_message_len, connection_id);
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateDisconnect){
uint8_t expected_message[] = {OBEX_OPCODE_DISCONNECT, 0, 0, OBEX_HEADER_CONNECTION_ID, 0, 0, 0, 0};
expected_message[2] = sizeof(expected_message);
big_endian_store_32(expected_message, 4, connection_id);
uint8_t actual_status = obex_message_builder_request_create_disconnect(actual_message, actual_message_len, connection_id);
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateGetAddHeader){
uint8_t expected_message[] = {OBEX_OPCODE_GET | OBEX_OPCODE_FINAL_BIT_MASK, 0, 0, OBEX_HEADER_CONNECTION_ID, 0, 0, 0, 0, OBEX_HEADER_SINGLE_RESPONSE_MODE, OBEX_SRM_ENABLE};
expected_message[2] = 8; // only get request
big_endian_store_32(expected_message, 4, connection_id);
uint8_t actual_status = obex_message_builder_request_create_get(actual_message, actual_message_len, connection_id);
validate_success(expected_message, expected_message[2], actual_status);
actual_status = obex_message_builder_header_add_srm_enable(actual_message, actual_message_len);
expected_message[2] += 2;
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateConnectWithHeaderTarget){
uint8_t expected_message[] = {OBEX_OPCODE_CONNECT, 0, 0, obex_version_number, flags, 0, 0,
// service UUID
OBEX_HEADER_TARGET, 0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
};
int header_len = 3 + sizeof(service_uuid);
expected_message[2] = 7;
big_endian_store_16(expected_message, 5, maximum_obex_packet_length);
big_endian_store_16(expected_message, 8, header_len);
memcpy(expected_message + 10, service_uuid, sizeof(service_uuid));
uint8_t actual_status = obex_message_builder_request_create_connect(actual_message, actual_message_len, obex_version_number, flags, maximum_obex_packet_length);
validate_success(expected_message, expected_message[2], actual_status);
actual_status = obex_message_builder_header_add_target(actual_message, actual_message_len, service_uuid, sizeof(service_uuid));
expected_message[2] += header_len;
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateConnectWithHeaderApplicationParameters){
uint8_t expected_message[] = {OBEX_OPCODE_CONNECT, 0, 0, obex_version_number, flags, 0, 0,
OBEX_HEADER_APPLICATION_PARAMETERS, 0,0, 0,0,0,0,0,0
};
int header_len = 3 + sizeof(application_parameters);
expected_message[2] = 7;
big_endian_store_16(expected_message, 5, maximum_obex_packet_length);
big_endian_store_16(expected_message, 8, header_len);
memcpy(expected_message + 10, application_parameters, sizeof(application_parameters));
uint8_t actual_status = obex_message_builder_request_create_connect(actual_message, actual_message_len, obex_version_number, flags, maximum_obex_packet_length);
validate_success(expected_message, expected_message[2], actual_status);
actual_status = obex_message_builder_header_add_application_parameters(actual_message, actual_message_len, &application_parameters[0], sizeof(application_parameters));
expected_message[2] += header_len;
validate_success(expected_message, expected_message[2], actual_status);
}
TEST(OBEX_MESSAGE_BUILDER, CreateSetPathWithName){
uint8_t expected_message[] = {OBEX_OPCODE_SETPATH, 0, 0, flags, 0, OBEX_HEADER_CONNECTION_ID, 0, 0, 0, 0, OBEX_HEADER_NAME, 0x00, 0x0D, 0x00, 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x00};
expected_message[2] = 10;
big_endian_store_32(expected_message, 6, connection_id);
uint8_t actual_status = obex_message_builder_request_create_set_path(actual_message, actual_message_len, flags, connection_id);
validate_success(expected_message, expected_message[2], actual_status);
expected_message[2] += 13;
actual_status = obex_message_builder_header_add_name(actual_message, actual_message_len, (const char *) path_element);
validate_success(expected_message, expected_message[2], actual_status);
}
int main (int argc, const char * argv[]){
return CommandLineTestRunner::RunAllTests(argc, argv);
}
|
laxika/daggers-and-sorcery
|
swords-attribute/src/main/java/com/morethanheroic/swords/attribute/service/modifier/calculator/GlobalAttributeModifierCalculator.java
|
package com.morethanheroic.swords.attribute.service.modifier.calculator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.morethanheroic.swords.attribute.domain.*;
import com.morethanheroic.swords.attribute.service.modifier.domain.AttributeModifierEntry;
import com.morethanheroic.swords.user.domain.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class GlobalAttributeModifierCalculator {
@Autowired
private SkillAttributeModifierCalculator skillAttributeModifierCalculator;
@Autowired
private GeneralAttributeModifierCalculator generalAttributeModifierCalculator;
@Autowired
private CombatAttributeModifierCalculator combatAttributeModifierCalculator;
@Autowired
private BasicAttributeModifierCalculator basicAttributeModifierCalculator;
@Autowired
private SpecialAttributeModifierCalculator specialAttributeModifierCalculator;
@Autowired
@Qualifier("equipmentAttributeModifierCalculator")
private AttributeModifierCalculator equipmentAttributeModifierCalculator;
@Autowired
private RaceAttributeModifierCalculator raceAttributeModifierCalculator;
@Autowired
private List<AttributeModifierProvider> attributeModifierProviders;
private Map<Class<? extends Attribute>, AttributeModifierCalculator> modifierCalculatorMap;
@PostConstruct
public void initialize() {
modifierCalculatorMap = ImmutableMap.of(
SkillAttribute.class, skillAttributeModifierCalculator,
GeneralAttribute.class, generalAttributeModifierCalculator,
CombatAttribute.class, combatAttributeModifierCalculator,
BasicAttribute.class, basicAttributeModifierCalculator,
SpecialAttribute.class, specialAttributeModifierCalculator
);
}
@SuppressWarnings("unchecked")
public List<AttributeModifierEntry> calculateModifierData(UserEntity user, Attribute attribute) {
final ArrayList<AttributeModifierEntry> attributeModifierEntryList = new ArrayList<>();
attributeModifierEntryList.addAll(modifierCalculatorMap.get(attribute.getClass()).calculate(user, attribute));
attributeModifierEntryList.addAll(equipmentAttributeModifierCalculator.calculate(user, attribute));
attributeModifierEntryList.addAll(raceAttributeModifierCalculator.calculate(user, attribute));
attributeModifierEntryList.addAll(attributeModifierProviders.stream()
.flatMap(attributeModifierProvider -> attributeModifierProvider.calculateModifiers(user, attribute).stream())
.collect(Collectors.toList())
);
return ImmutableList.copyOf(attributeModifierEntryList);
}
}
|
bptran/geowave
|
extensions/adapters/vector/src/test/java/mil/nga/giat/geowave/adapter/vector/utils/FeatureDataUtilsTest.java
|
<reponame>bptran/geowave
package mil.nga.giat.geowave.adapter.vector.utils;
import static org.junit.Assert.assertEquals;
import mil.nga.giat.geowave.adapter.vector.util.FeatureDataUtils;
import mil.nga.giat.geowave.core.index.StringUtils;
import org.geotools.feature.SchemaException;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;
public class FeatureDataUtilsTest
{
@Test
public void testWithSRID()
throws SchemaException {
SimpleFeatureType type = FeatureDataUtils.decodeType(
"http://somens.org",
"type1",
"geometry:Geometry:srid=4326,pop:java.lang.Long,when:Date,whennot:Date,pid:String",
"east");
assertEquals(
"type1",
type.getName().getLocalPart());
}
/**
*
* This test only works in some versions. So, comment out for now.
*
* public void testWithSRIDAndMisMatch() throws SchemaException {
* SimpleFeatureType type = FeatureDataUtils.decodeType("http://somens.org",
* "type1",
* "geometry:Geometry:srid=4326,pop:java.lang.Long,when:Date,whennot:Date,pid:String"
* , "north"); assertEquals("type1",type.getName().getLocalPart());
* assertEquals
* ("NORTH",type.getCoordinateReferenceSystem().getCoordinateSystem
* ().getAxis(0).getDirection().name()); }
*/
@Test
public void testWithoutSRID()
throws SchemaException {
SimpleFeatureType type = FeatureDataUtils.decodeType(
"http://somens.org",
"type1",
"geometry:Geometry,pop:java.lang.Long,when:Date,whennot:Date,pid:String",
StringUtils.stringFromBinary(new byte[0]));
assertEquals(
"type1",
type.getName().getLocalPart());
}
}
|
EGM/droidscript-alt
|
dist/codeedit.js
|
<filename>dist/codeedit.js
import View from "./view";
export default class CodeEdit extends View {
constructor(id) {
super(id);
}
clearHistory() {
prompt(this.id, "Cde.ClearHistory(");
}
copy() {
prompt(this.id, "Cde.Copy(");
}
cut() {
prompt(this.id, "Cde.Cut(");
}
getCursorLine() {
return parseInt(prompt(this.id, "Cde.GetCursorLine("));
}
getCursorPos() {
return parseInt(prompt(this.id, "Cde.GetCursorPos("));
}
getLineStart(line) {
return parseInt(prompt(this.id, `Cde.GetLineStart(${line}`));
}
getSelectedText() {
return prompt(this.id, "Cde.GetSelectedText(");
}
getSelectMode() {
return prompt(this.id, "Cde.GetSelectMode(") === "true";
}
getText() {
return prompt(this.id, "Cde.GetText(");
}
getType() {
return "CodeEdit";
}
highlightLine(line) {
prompt(this.id, `Cde.HighlightLine(\f${line}`);
}
insertText(text, start) {
prompt(this.id, `Cde.InsertText(\f${text}\f${start}`);
}
paste() {
prompt(this.id, "Cde.Paste(");
}
redo() {
prompt(this.id, "Cde.Redo(");
}
replace(text) {
prompt(this.id, `Cde.Replace(\f${text}`);
}
replaceAll(text, newText, matchCase, wholeWord) {
prompt(this.id, `Cde.ReplaceAll(\f${text}\f${newText}\f${matchCase}\f${wholeWord}`);
}
replaceText(text, start, end) {
prompt(this.id, `Cde.ReplaceText(\f${text}\f${start}\f${end}`);
}
search(text, direction, matchCase, wholeWord) {
prompt(this.id, `Cde.Search(\f${text}\f${direction}\f${matchCase}\f${wholeWord}`);
}
selectAll() {
prompt(this.id, "Cde.SelectAll(");
}
setColorScheme(scheme) {
prompt(this.id, `Cde.SetColorScheme(\f${scheme}`);
return this;
}
setCursorPos(position) {
prompt(this.id, `Cde.SetCursorPos(${position}`);
return this;
}
setHtml(html) {
prompt(this.id, `Cde.SetText(\f${html}`);
return this;
}
setLanguage(ext) {
prompt(this.id, `Cde.SetLanguage(\f${ext}`);
return this;
}
setOnChange(callback) {
prompt(this.id, `Cde.SetOnChange(\f${_Cbm(callback)}`);
return this;
}
setOnDoubleTap(callback) {
prompt(this.id, `Cde.SetOnDoubleTap(\f${_Cbm(callback)}`);
return this;
}
setOnKey(callback) {
prompt(this.id, `Cde.SetOnKey(\f${_Cbm(callback)}`);
return this;
}
setNavigationMethod(method) {
prompt(this.id, `Cde.SetNavigationMethod(\f${method}`);
return this;
}
setSelection(start, stop) {
prompt(this.id, `Cde.SetSelection(\f${start}\f${stop}`);
return this;
}
setText(text) {
prompt(this.id, `Cde.SetText(\f${text}`);
return this;
}
setTextColor(color) {
prompt(this.id, `Cde.SetTextColor(\f${color}`);
return this;
}
setTextSize(size, mode) {
prompt(this.id, `Cde.SetTextSize(\f${size}\f${mode}`);
return this;
}
setUseKeyboard(onOff) {
prompt(this.id, `Cde.SetUseKeyboard(\f${onOff}`);
return this;
}
undo() {
prompt(this.id, "Cde.Undo(");
}
}
|
oystr-foss/oxy-service
|
src/main/java/oystr/actors/PeersRegistryActor.java
|
package oystr.actors;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Scheduler;
import com.fasterxml.jackson.databind.JsonNode;
import com.typesafe.config.Config;
import org.asynchttpclient.Response;
import org.asynchttpclient.proxy.ProxyServer;
import oystr.models.Peer;
import oystr.models.messages.*;
import oystr.services.CacheClient;
import oystr.services.HttpClient;
import oystr.services.Services;
import play.Logger;
import play.libs.Json;
import scala.concurrent.ExecutionContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static oystr.models.PeerState.*;
public class PeersRegistryActor extends AbstractActor {
private final HttpClient<Response> http;
private final CacheClient cache;
private final String loadBalancerUrl;
private final Logger.ALogger logger;
private final String checkUrl;
private final Boolean isLeader;
private Map<String, Peer> luminatiPeers;
@SuppressWarnings("WrapperTypeMayBePrimitive")
public PeersRegistryActor(Services services, HttpClient<Response> http, CacheClient cacheClient) {
Config conf = services.conf();
this.loadBalancerUrl = conf.getString("oplb.url");
this.http = http;
this.cache = cacheClient;
this.logger = services.logger("application");
this.checkUrl = conf.getString("oxy.health-check.url");
String role = conf.getString("oxy.role");
this.isLeader = role.equalsIgnoreCase("leader");
// If the leader is starting, then flush the cache to avoid showing stale/offline peers.
if(isLeader) {
cache.flush();
}
Duration healthCheckDelay = conf.getDuration("oxy.health-check.delay");
Duration healthCheckInterval = conf.getDuration("oxy.health-check.interval");
Duration discoveryDelay = conf.getDuration("oxy.discovery.delay");
Duration discoveryInterval = conf.getDuration("oxy.discovery.interval");
Integer threadPoolSize = conf.getInt("oxy.thread-pool.size");
ExecutionContext ctx = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(threadPoolSize));
Scheduler scheduler = services.sys().scheduler();
scheduler.schedule(
healthCheckDelay,
healthCheckInterval,
getSelf(),
new HealthCheck(),
ctx,
ActorRef.noSender()
);
scheduler.schedule(
discoveryDelay,
discoveryInterval,
getSelf(),
new Discovery(),
ctx,
ActorRef.noSender()
);
if(conf.hasPath("luminati.address")) {
String luminatiAddress = conf.getString("luminati.address");
Peer default1 = Peer.builder().name("default1").host(luminatiAddress).port(24000).build();
Peer default2 = Peer.builder().name("default2").host(luminatiAddress).port(24001).build();
luminatiPeers = new HashMap<>();
luminatiPeers.put(default1.toHash(), default1);
luminatiPeers.put(default2.toHash(), default2);
}
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(Discovery.class, this::autoDiscovery)
.match(HealthCheck.class, req -> healthCheck())
.match(AddPeerRequest.class, req -> cache.add(req.getPeer()))
.match(FindPeersRequest.class, req -> {
Boolean onlyRunning = req.getOnlyRunning();
JsonNode res = onlyRunning ? findAllActive() : findAll();
getSender().tell(Optional.of(res), getSelf());
})
.match(DeletePeerRequest.class, req -> {
Boolean deleteAll = req.getDeleteAll();
if(deleteAll) {
cache.flush();
} else {
delete(req);
}
getSender().tell(true, getSelf());
})
.match(MetadataRequest.class, req -> {
if(req.getExecutionId().isPresent()) {
String execution = req.getExecutionId().get();
getContext()
.findChild("metrics-actor")
.ifPresent(actor -> actor.tell(execution, getSelf()));
}
getSender().tell(loadBalancerUrl, getSelf());
})
.matchAny(req -> logger.debug(req.toString()))
.build();
}
private JsonNode findAll() {
return cache.size() == 0 && luminatiPeers != null ?
Json.toJson(luminatiPeers.values()) :
Json.toJson(cache.findAll());
}
private JsonNode findAllActive() {
List<Peer> listServices = cache.findAllRunning();
return listServices.isEmpty() && luminatiPeers != null ?
Json.toJson(luminatiPeers.values()) :
Json.toJson(listServices);
}
private void delete(DeletePeerRequest req) {
String payload = String.format("%s-%s-%s", req.getServiceId(), req.getHost(), req.getPort());
String key = Base64.getEncoder().encodeToString(payload.getBytes());
cache.remove(key);
}
private void autoDiscovery(Discovery req) throws IOException, InterruptedException {
if (!isLeader) {
return;
}
// TODO: It's our internal use case. Since OpenVPN knows who are connected, we may discover clients automatically.
// TODO: We are sharing the /tmp directory of both containers.
String[] cmd = {"/bin/sh", "-c", "cat /tmp/openvpn-status.log | grep \"192.168.255\" | awk -F\",\" '{print $1 \" \" $2}'"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line = reader.readLine()) != null) {
String[] raw = line.split(" ");
if(raw.length < 2) {
continue;
}
String host = raw[0];
String name = raw[1];
Peer peer = Peer
.builder()
.serviceId(String.format("proxy-%s", name))
.host(host)
.port(8888)
.name(name)
.registeredAt(LocalDateTime.now())
.state(UNKNOWN)
.build();
Peer existingPeer = cache.getIfPresent(peer.toHash());
if(existingPeer == null || existingPeer.getState() == DISABLED) {
logger.info(String.format("Discovered: %s", peer));
cache.add(peer);
}
}
}
private void healthCheck() {
if(!isLeader || cache.size() == 0) {
return;
}
logger.debug("running health check with " + cache.size() + " registered peers (even those not running)");
Collection<Peer> peers = cache.findAll();
peers.forEach(value -> {
ProxyServer proxy = new ProxyServer.Builder(value.getHost(), value.getPort()).build();
try {
Response res = http
.head(checkUrl, proxy)
.get(10, TimeUnit.SECONDS);
logger.debug(String.format("healthcheck finished for %s with %d and no errors.", value, res.getStatusCode()));
value.setLastHealthCheck(LocalDateTime.now());
value.setState(RUNNING);
cache.add(value);
} catch (Exception e) {
logger.debug(String.format("[%s] healthcheck finished for %s with an error: '%s'.", e.getClass().getSimpleName(), value, e.getMessage()));
value.setLastHealthCheck(LocalDateTime.now());
switch (value.getState()) {
case UNKNOWN:
case RUNNING:
value.setState(PENDING);
cache.add(value);
break;
case PENDING:
value.setState(FAILING);
cache.add(value);
break;
case FAILING:
value.setState(DISABLED);
cache.add(value);
break;
case DISABLED:
logger.debug("Peer removed: " + value);
cache.remove(value.toHash());
}
}
});
}
}
|
ananthdurai/pinot
|
pinot-tools/src/main/java/org/apache/pinot/tools/RealtimeQuickStartWithMinion.java
|
<gh_stars>1000+
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.tools;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.pinot.common.utils.ZkStarter;
import org.apache.pinot.spi.stream.StreamDataProducer;
import org.apache.pinot.spi.stream.StreamDataProvider;
import org.apache.pinot.spi.stream.StreamDataServerStartable;
import org.apache.pinot.tools.Quickstart.Color;
import org.apache.pinot.tools.admin.PinotAdministrator;
import org.apache.pinot.tools.admin.command.QuickstartRunner;
import org.apache.pinot.tools.utils.KafkaStarterUtils;
import static org.apache.pinot.tools.Quickstart.prettyPrintResponse;
import static org.apache.pinot.tools.Quickstart.printStatus;
/**
* This quickstart shows how RealtimeToOfflineSegmentsTask and MergeRollupTask minion
* tasks continuously optimize segments as data gets ingested into Realtime table.
*/
public class RealtimeQuickStartWithMinion extends QuickStartBase {
@Override
public List<String> types() {
return Arrays.asList("REALTIME_MINION", "REALTIME-MINION");
}
private StreamDataServerStartable _kafkaStarter;
public static void main(String[] args)
throws Exception {
List<String> arguments = new ArrayList<>();
arguments.addAll(Arrays.asList("QuickStart", "-type", "REALTIME-MINION"));
arguments.addAll(Arrays.asList(args));
PinotAdministrator.main(arguments.toArray(new String[arguments.size()]));
}
public Map<String, Object> getConfigOverrides() {
Map<String, Object> properties = new HashMap<>();
properties.put("controller.task.scheduler.enabled", true);
return properties;
}
public void execute()
throws Exception {
File quickstartTmpDir = new File(_tmpDir, String.valueOf(System.currentTimeMillis()));
File baseDir = new File(quickstartTmpDir, "githubEvents");
File dataDir = new File(baseDir, "rawdata");
Preconditions.checkState(dataDir.mkdirs());
File schemaFile = new File(baseDir, "githubEvents_schema.json");
File realtimeTableConfigFile = new File(baseDir, "githubEvents_realtime_table_config.json");
File offlineTableConfigFile = new File(baseDir, "githubEvents_offline_table_config.json");
File inputDataFile = new File(baseDir, "2021-07-21-few-hours.json");
ClassLoader classLoader = Quickstart.class.getClassLoader();
URL resource = classLoader.getResource("examples/minions/stream/githubEvents/githubEvents_schema.json");
Preconditions.checkNotNull(resource);
FileUtils.copyURLToFile(resource, schemaFile);
resource = classLoader.getResource("examples/minions/stream/githubEvents/githubEvents_realtime_table_config.json");
Preconditions.checkNotNull(resource);
FileUtils.copyURLToFile(resource, realtimeTableConfigFile);
resource = classLoader.getResource("examples/minions/stream/githubEvents/githubEvents_offline_table_config.json");
Preconditions.checkNotNull(resource);
FileUtils.copyURLToFile(resource, offlineTableConfigFile);
resource = Quickstart.class.getClassLoader()
.getResource("examples/minions/stream/githubEvents/rawdata/2021-07-21-few-hours.json");
Preconditions.checkNotNull(resource);
FileUtils.copyURLToFile(resource, inputDataFile);
QuickstartTableRequest request = new QuickstartTableRequest(baseDir.getAbsolutePath());
QuickstartRunner runner =
new QuickstartRunner(Lists.newArrayList(request), 1, 1, 1, 1, dataDir, true, null, getConfigOverrides());
printStatus(Color.CYAN, "***** Starting Kafka *****");
final ZkStarter.ZookeeperInstance zookeeperInstance = ZkStarter.startLocalZkServer();
try {
_kafkaStarter = StreamDataProvider.getServerDataStartable(KafkaStarterUtils.KAFKA_SERVER_STARTABLE_CLASS_NAME,
KafkaStarterUtils.getDefaultKafkaConfiguration(zookeeperInstance));
} catch (Exception e) {
throw new RuntimeException("Failed to start " + KafkaStarterUtils.KAFKA_SERVER_STARTABLE_CLASS_NAME, e);
}
_kafkaStarter.start();
printStatus(Color.CYAN, "***** Starting Zookeeper, controller, server and broker *****");
runner.startAll();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
printStatus(Color.GREEN, "***** Shutting down realtime-minion quick start *****");
runner.stop();
_kafkaStarter.stop();
ZkStarter.stopLocalZkServer(zookeeperInstance);
FileUtils.deleteDirectory(quickstartTmpDir);
} catch (Exception e) {
e.printStackTrace();
}
}));
printStatus(Color.CYAN, "***** Sending events to Kafka *****");
_kafkaStarter.createTopic("githubEvents", KafkaStarterUtils.getTopicCreationProps(2));
publishGithubEventsToKafka("githubEvents", inputDataFile);
printStatus(Color.CYAN, "***** Bootstrap githubEvents tables *****");
runner.bootstrapTable();
printStatus(Color.CYAN, "***** Waiting for 5 seconds for a few events to get populated *****");
Thread.sleep(5000);
printStatus(Color.YELLOW, "***** Realtime-minion quickstart setup complete *****");
String q1 = "select count(*) from githubEvents limit 1";
printStatus(Color.YELLOW, "Current number of documents in the table");
printStatus(Color.CYAN, "Query : " + q1);
printStatus(Color.YELLOW, prettyPrintResponse(runner.runQuery(q1)));
printStatus(Color.GREEN, "***************************************************");
printStatus(Color.GREEN, "You can always go to http://localhost:9000 to play around in the query console");
printStatus(Color.GREEN, "In particular, you will find that OFFLINE table gets segments from REALTIME table;");
printStatus(Color.GREEN, "and segments in OFFLINE table get merged into larger ones within a few minutes.");
}
private static void publishGithubEventsToKafka(String topicName, File dataFile)
throws Exception {
Properties properties = new Properties();
properties.put("metadata.broker.list", KafkaStarterUtils.DEFAULT_KAFKA_BROKER);
properties.put("serializer.class", "kafka.serializer.DefaultEncoder");
properties.put("request.required.acks", "1");
StreamDataProducer producer =
StreamDataProvider.getStreamDataProducer(KafkaStarterUtils.KAFKA_PRODUCER_CLASS_NAME, properties);
try {
LineIterator dataStream = FileUtils.lineIterator(dataFile);
while (dataStream.hasNext()) {
producer.produce(topicName, dataStream.nextLine().getBytes(StandardCharsets.UTF_8));
}
} finally {
producer.close();
}
}
}
|
wizedkyle/sumocli
|
pkg/cmd/access-keys/access-keys.go
|
<filename>pkg/cmd/access-keys/access-keys.go
package access_keys
import (
cmdAccessKeysCreate "github.com/SumoLogic-Incubator/sumocli/pkg/cmd/access-keys/create"
cmdAccessKeysDelete "github.com/SumoLogic-Incubator/sumocli/pkg/cmd/access-keys/delete"
cmdAccessKeysListAll "github.com/SumoLogic-Incubator/sumocli/pkg/cmd/access-keys/list_all"
cmdAccessKeysListPersonal "github.com/SumoLogic-Incubator/sumocli/pkg/cmd/access-keys/list_personal"
cmdAccessKeysUpdate "github.com/SumoLogic-Incubator/sumocli/pkg/cmd/access-keys/update"
"github.com/SumoLogic-Incubator/sumologic-go-sdk/service/cip"
"github.com/spf13/cobra"
)
func NewCmdAccessKeys(client *cip.APIClient) *cobra.Command {
cmd := &cobra.Command{
Use: "access-keys",
Short: "Manage access keys",
Long: "Commands that allow you to manage access keys in your Sumo Logic tenant",
}
cmd.AddCommand(cmdAccessKeysCreate.NewCmdAccessKeysCreate(client))
cmd.AddCommand(cmdAccessKeysDelete.NewCmdAccessKeysDelete(client))
cmd.AddCommand(cmdAccessKeysListAll.NewCmdAccessKeysListAll(client))
cmd.AddCommand(cmdAccessKeysListPersonal.NewCmdAccessKeysListPersonal(client))
cmd.AddCommand(cmdAccessKeysUpdate.NewCmdAccessKeysUpdate(client))
return cmd
}
|
jeanbez/spack
|
var/spack/repos/builtin/packages/pinfo/package.py
|
<reponame>jeanbez/spack<gh_stars>0
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Pinfo(AutotoolsPackage):
"""Pinfo is user-friendly, console-based viewer for Info documents."""
homepage = "https://github.com/baszoetekouw/pinfo"
url = "https://github.com/baszoetekouw/pinfo/archive/v0.6.13.tar.gz"
version('0.6.13', sha256='9dc5e848a7a86cb665a885bc5f0fdf6d09ad60e814d75e78019ae3accb42c217')
version('0.6.12', sha256='82af48ba23b8c26b1f4e67b45f718142eb0f760326b782f80c765801d3532077')
version('0.6.11', sha256='fd26017ac9db179d709b49e450c3097e7d6f99cd94de7b5da824ec757c6992b2')
depends_on('autoconf', type='build')
depends_on('automake', type='build')
depends_on('libtool', type='build')
depends_on('m4', type='build')
depends_on('gettext', type='build')
depends_on('texinfo', type='build')
def configure_args(self):
args = ['CFLAGS=-Wno-unused-parameter']
return args
|
BatchLabs/Batch-Android-SDK
|
Sources/sdk/src/main/java/com/batch/android/messaging/PayloadParsingException.java
|
package com.batch.android.messaging;
/**
* Exception that represents a messaging payload parsing error
*
*/
public class PayloadParsingException extends Exception {
public PayloadParsingException() {}
public PayloadParsingException(String detailMessage) {
super(detailMessage);
}
public PayloadParsingException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public PayloadParsingException(Throwable throwable) {
super(throwable);
}
}
|
knightjdr/prohits-viz-2.0
|
src/state/selectors/visualization/annotation-selector.test.js
|
import annotationSelector from './annotation-selector';
describe('Annotation selector', () => {
it('should return an array of annotations', () => {
const state = {
annotations: {
color: '#ff0000',
list: [
{
text: 'annotation1',
x: 0,
y: 20,
},
{
text: 'annotation2',
x: 40,
y: 60,
},
],
show: false,
},
};
expect(annotationSelector(state)).toEqual(state.annotations);
});
});
|
lumi-io/postings
|
src/components/Admin/ApplicantDashboard/components/EssayCard.js
|
import React from "react";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import { makeStyles } from "@material-ui/core/styles";
import { withStyles } from "@material-ui/core/styles";
import EssayCardPrompts from "./EssayCardPrompts";
export default function EssayCard(props) {
const useStyles = makeStyles({});
const classes = useStyles();
const prompts = props.prompts;
return (
<ContentCard className={classes.root} variant="outlined">
<CardContent>
{prompts && (prompts.map((prompt) => (
<EssayCardPrompts question={prompt["question"]} answer={prompt["answer"]} />
)))}
</CardContent>
</ContentCard>
);
}
const ContentCard = withStyles({
root: {
"background-color": "white",
"margin-top": "1vw",
"margin-bottom": "1vw",
"margin-right": "1.5vw",
"margin-left": "1.5vw",
"padding-right": "0.5vw",
"padding-left": "0.5vw",
},
})(Card);
|
soramitsu/ios-crypto
|
Tests/BIP39/IRBIP39TestData.h
|
<filename>Tests/BIP39/IRBIP39TestData.h<gh_stars>1-10
//
// IRBIP39TestData.h
// IrohaCryptoTests
//
// Created by <NAME> on 27.02.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface IRBIP39TestData : NSObject
@property(strong, nonatomic, readonly)NSString * _Nonnull entropy;
@property(strong, nonatomic, readonly)NSString * _Nonnull mnemonic;
@property(strong, nonatomic, readonly)NSString * _Nonnull seed;
- (nonnull instancetype)initWithEntropy:(nonnull NSString*)entropy
mnemonic:(nonnull NSString*)mnemonic
seed:(nonnull NSString*)seed;
@end
|
fossabot/Pay2Spawn
|
src/main/java/net/doubledoordev/pay2spawn/types/MusicType.java
|
/*
* Copyright (c) 2014, DoubleDoorDevelopment
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the project nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.doubledoordev.pay2spawn.types;
import com.google.gson.JsonObject;
import net.doubledoordev.pay2spawn.Pay2Spawn;
import net.doubledoordev.pay2spawn.network.MusicMessage;
import net.doubledoordev.pay2spawn.permissions.Node;
import net.doubledoordev.pay2spawn.types.guis.MusicTypeGui;
import net.doubledoordev.pay2spawn.util.Constants;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static net.doubledoordev.pay2spawn.util.Constants.NBTTypes;
import static net.doubledoordev.pay2spawn.util.Constants.STRING;
/**
* @author Dries007
*/
public class MusicType extends TypeBase
{
public static final String SOUND_KEY = "song";
public static final HashMap<String, String> typeMap = new HashMap<>();
private static final String NAME = "music";
public static File musicFolder;
static
{
typeMap.put(SOUND_KEY, NBTTypes[STRING]);
}
@Override
public String getName()
{
return NAME;
}
@Override
public NBTTagCompound getExample()
{
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString(SOUND_KEY, "Rickroll.mp3");
return nbt;
}
@Override
public void spawnServerSide(EntityPlayerMP player, NBTTagCompound dataFromClient, NBTTagCompound rewardData)
{
Pay2Spawn.getSnw().sendTo(new MusicMessage(dataFromClient.getString(SOUND_KEY)), (EntityPlayerMP) player);
}
@Override
public void printHelpList(File configFolder)
{
musicFolder = new File(configFolder, "music");
if (musicFolder.mkdirs())
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
File zip = new File(musicFolder, "music.zip");
FileUtils.copyURLToFile(new URL(Constants.MUSICURL), zip);
ZipFile zipFile = new ZipFile(zip);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
File entryDestination = new File(musicFolder, entry.getName());
entryDestination.getParentFile().mkdirs();
InputStream in = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(entryDestination);
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
zipFile.close();
zip.delete();
}
catch (IOException e)
{
Pay2Spawn.getLogger().warn("Error downloading music file. Get from github and unpack yourself please.");
e.printStackTrace();
}
}
}, "Pay2Spawn music download and unzip").start();
}
}
@Override
public void openNewGui(int rewardID, JsonObject data)
{
new MusicTypeGui(rewardID, NAME, data, typeMap);
}
@Override
public Collection<Node> getPermissionNodes()
{
return new HashSet<>();
}
@Override
public Node getPermissionNode(EntityPlayer player, NBTTagCompound dataFromClient)
{
return new Node(NAME, dataFromClient.getString(SOUND_KEY).split(" ")[0]);
}
@Override
public String replaceInTemplate(String id, JsonObject jsonObject)
{
switch (id)
{
case "song":
return jsonObject.get(SOUND_KEY).getAsString().replace(typeMap.get(SOUND_KEY) + ":", "");
}
return id;
}
}
|
mdelapenya/generated-crud-play
|
app/models/scproductscreenshot/Scproductscreenshot.java
|
package models.scproductscreenshot;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import controllers.scproductscreenshot.ScproductscreenshotFormData;
import play.db.ebean.Model;
import play.data.format.Formats;
import play.data.validation.Constraints;
/**
* @author <NAME>
* @generated
*/
@Entity
public class Scproductscreenshot extends Model {
// model attributes
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
public long productScreenshotId;
public long companyId;
public long groupId;
public long productEntryId;
public long thumbnailId;
public long fullImageId;
public int priority;
// model finder attribute
public static Finder<Long,Scproductscreenshot> find = new Finder<Long,Scproductscreenshot>(
Long.class, Scproductscreenshot.class
);
// getters and setters
public long getProductScreenshotId() {
return productScreenshotId;
}
public void setProductScreenshotId(long productScreenshotId) {
this.productScreenshotId = productScreenshotId;
}
public long getCompanyId() {
return companyId;
}
public void setCompanyId(long companyId) {
this.companyId = companyId;
}
public long getGroupId() {
return groupId;
}
public void setGroupId(long groupId) {
this.groupId = groupId;
}
public long getProductEntryId() {
return productEntryId;
}
public void setProductEntryId(long productEntryId) {
this.productEntryId = productEntryId;
}
public long getThumbnailId() {
return thumbnailId;
}
public void setThumbnailId(long thumbnailId) {
this.thumbnailId = thumbnailId;
}
public long getFullImageId() {
return fullImageId;
}
public void setFullImageId(long fullImageId) {
this.fullImageId = fullImageId;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public Scproductscreenshot(){
}
// constructor using a formData
public Scproductscreenshot(ScproductscreenshotFormData formData) {
productScreenshotId = Long.valueOf(formData.productScreenshotId);
companyId = Long.valueOf(formData.companyId);
groupId = Long.valueOf(formData.groupId);
productEntryId = Long.valueOf(formData.productEntryId);
thumbnailId = Long.valueOf(formData.thumbnailId);
fullImageId = Long.valueOf(formData.fullImageId);
priority = Integer.valueOf(formData.priority);
}
public ScproductscreenshotFormData toFormData() {
if (productScreenshotId < 0) {
productScreenshotId = 0L;
}
ScproductscreenshotFormData formData = new ScproductscreenshotFormData(
String.valueOf(productScreenshotId)
,
String.valueOf(companyId)
,
String.valueOf(groupId)
,
String.valueOf(productEntryId)
,
String.valueOf(thumbnailId)
,
String.valueOf(fullImageId)
,
String.valueOf(priority)
);
return formData;
}
}
|
questnr/questnr-core
|
src/main/java/com/questnr/model/repositories/SharePostActionRepository.java
|
package com.questnr.model.repositories;
import com.questnr.model.entities.PostAction;
import com.questnr.model.entities.SharedPostAction;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Date;
public interface SharePostActionRepository extends JpaRepository<SharedPostAction, Long> {
SharedPostAction findBySharedPostActionId(Long sharedPostActionId);
Long countAllByPostActionAndCreatedAtBetween(PostAction postAction, Date startingDate, Date endingDate);
}
|
kevmo314/transformers
|
src/python/fundamentals/regressions/solutions/a.py
|
from typing import List, Tuple
def rss(data: numpy.ndarray, a: float, b: float) -> float:
x_i = data[:, 0]
y_i = data[:, 1]
return numpy.sum((y_i - (a * x_i + b)) ** 2)
|
Martin-Seysen/mmgroup
|
src/mmgroup/structures/order_vector_data.py
|
<filename>src/mmgroup/structures/order_vector_data.py
# This file has been created automatically, do not change!
# For documentation see module mmgroup.structures.find_order_vector.py.
S_G71 = "M0<t_1*l_1*y_0d8h*x_1973h*d_15bh*p_80797417>"
S_V71 = "MV<3;-T_195_30h-T_505_0h-X_8fh_5-X_25ch_5+X_632h_1>"
S_GA = "M0<d_558h*p_214180475*l_1*d_376h*p_240307562*l_1*d_3h*p_20944*l_1>"
DIAG_VA = 2
S_G94 = "M0<t_2*l_1*y_287h*x_1833h*d_15ch*p_44983552>"
S_V94 = "MV<15;3*T_352_19h+6*T_643_28h+6*X_73eh_17+9*Z_1c9h_15+12*Y_4b6h_22>"
TAGS_Y = [
0x200010c, 0x2000205, 0x2000309, 0x2000406, 0x2000509, 0x2000606,
0x2000804, 0x2000904, 0x2000a01, 0x2000c06, 0x2001008,
]
TAGS_X = [
0x400010b, 0x4000201, 0x4000301, 0x4000402, 0x4000503, 0x4000603,
0x4000806, 0x4000904, 0x4000b06, 0x4000c09, 0x4001007, 0x6000101,
0xa00000b, 0xa00400a, 0xa008003, 0xa010004, 0xa02000c, 0xa080005,
0xa10000a, 0xa200002, 0xa400007, 0xa800005, 0xa040108, 0xb000106,
]
TAG_SIGN = [
0xc000001,
]
|
MicrosoftCore/atis-coco-admin
|
src/components/element/ElementTable/methods/index.js
|
export default {
methods: [
'clearSelection',
'toggleRowSelection',
'toggleAllSelection',
'toggleRowExpansion',
'setCurrentRow',
'clearSort',
'clearFilter',
'doLayout',
'sort'
].reduce((methods, methodName) => {
methods[methodName] = function () {
const { table } = this.$refs.main.$refs
if (table && table[methodName]) {
table[methodName](...arguments)
}
}
return methods
}, {})
}
|
appecapps/tuinstrflt
|
src/test/java/com/tuin/business/service/mapping/RolServiceMapperTest.java
|
/*
* Created on 28 ago 2017 ( Time 17:51:18 )
* Generated by Telosys Tools Generator ( version 2.1.1 )
*/
package com.tuin.business.service.mapping;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.stereotype.Component;
import com.tuin.bean.Rol;
import com.tuin.bean.jpa.RolEntity;
import com.tuin.test.MockValues;
/**
* Test : Mapping between entity beans and display beans.
*/
public class RolServiceMapperTest {
private RolServiceMapper rolServiceMapper;
private static ModelMapper modelMapper = new ModelMapper();
private MockValues mockValues = new MockValues();
@BeforeClass
public static void setUp() {
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
}
@Before
public void before() {
rolServiceMapper = new RolServiceMapper();
rolServiceMapper.setModelMapper(modelMapper);
}
/**
* Mapping from 'RolEntity' to 'Rol'
* @param rolEntity
*/
@Test
public void testMapRolEntityToRol() {
// Given
RolEntity rolEntity = new RolEntity();
rolEntity.setNombre(mockValues.nextString(45));
rolEntity.setActivo(mockValues.nextByte());
// When
Rol rol = rolServiceMapper.mapRolEntityToRol(rolEntity);
// Then
assertEquals(rolEntity.getNombre(), rol.getNombre());
assertEquals(rolEntity.getActivo(), rol.getActivo());
}
/**
* Test : Mapping from 'Rol' to 'RolEntity'
*/
@Test
public void testMapRolToRolEntity() {
// Given
Rol rol = new Rol();
rol.setNombre(mockValues.nextString(45));
rol.setActivo(mockValues.nextByte());
RolEntity rolEntity = new RolEntity();
// When
rolServiceMapper.mapRolToRolEntity(rol, rolEntity);
// Then
assertEquals(rol.getNombre(), rolEntity.getNombre());
assertEquals(rol.getActivo(), rolEntity.getActivo());
}
}
|
stori-es/stories
|
dashboard/src/main/java/org/consumersunion/stories/dashboard/client/application/ui/addto/AddToPopup.java
|
package org.consumersunion.stories.dashboard.client.application.ui.addto;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
public class AddToPopup extends Composite {
interface Binder extends UiBinder<Widget, AddToPopup> {
}
private final AddToMenuHandler addToMenuHandler;
@Inject
AddToPopup(
Binder uiBinder,
@Assisted AddToMenuHandler addToMenuHandler) {
initWidget(uiBinder.createAndBindUi(this));
this.addToMenuHandler = addToMenuHandler;
}
@UiHandler("addToCollections")
void onAddToCollectionsClicked(ClickEvent clickEvent) {
addToMenuHandler.onAddToCollections();
}
@UiHandler("addTags")
void onAddTagsClicked(ClickEvent clickEvent) {
addToMenuHandler.onAddTags();
}
@UiHandler("addNote")
void onAddNoteClicked(ClickEvent clickEvent) {
addToMenuHandler.onAddNote();
}
}
|
nickjcroucher/pp-sketchlib
|
src/sketch/stHashIterator.hpp
|
#ifndef STHASH__ITERATOR_H
#define STHASH__ITERATOR_H 1
#include <string>
#include <limits>
#include "nthash.hpp"
/**
* Iterate over hash values for k-mers in a
* given DNA sequence.
*
* This implementation uses ntHash
* function to efficiently calculate
* hash values for successive k-mers.
*/
class stHashIterator
{
public:
static std::vector<std::vector<unsigned>> parseSeed(const std::vector<std::string> &seedString)
{
std::vector<std::vector<unsigned>> seedSet;
for (unsigned i = 0; i < seedString.size(); i++)
{
std::vector<unsigned> sSeed;
for (unsigned j = 0; j < seedString[i].size(); j++)
{
if (seedString[i][j] != '1')
sSeed.push_back(j);
}
seedSet.push_back(sSeed);
}
return seedSet;
}
/**
* Default constructor. Creates an iterator pointing to
* the end of the iterator range.
*/
stHashIterator() : m_hVec(NULL),
m_hStn(NULL),
m_pos(std::numeric_limits<std::size_t>::max())
{
}
/**
* Constructor.
* @param seq address of DNA sequence to be hashed
* @param seed address of spaced seed
* @param k k-mer size
* @param h number of seeds
* @param h2 number of hashes per seed
* @param rc use canonical k-mers (allow reverse complement)
* @param ss use spaced seeds
*/
stHashIterator(const std::string &seq, const std::vector<std::vector<unsigned>> &seed, unsigned h, unsigned h2, unsigned k, bool rc, bool ss) : m_seq(seq), m_seed(seed), m_h(h), m_h2(h2), m_k(k), m_rc(rc), m_ss(ss),
m_hVec(new uint64_t[h * h2]), m_minhVec(new uint64_t[h2]), m_hStn(new bool[h * h2]), m_pos(0)
{
init();
}
/** Initialize internal state of iterator */
void init()
{
if (m_k > m_seq.length())
{
m_pos = std::numeric_limits<std::size_t>::max();
return;
}
unsigned locN = 0;
if (m_ss)
{
while (m_pos < m_seq.length() - m_k + 1 && (m_rc ? !NTMSMC64(m_seq.data() + m_pos, m_seed, m_k, m_h, m_h2, m_fhVal, m_rhVal, locN, m_hVec, m_minhVec, m_hStn)
: !NTMSM64(m_seq.data() + m_pos, m_seed, m_k, m_h, m_h2, m_fhVal, locN, m_hVec, m_minhVec)))
m_pos += locN + 1;
}
else
{
while (m_pos < m_seq.length() - m_k + 1 && (m_rc ? !NTMC64(m_seq.data() + m_pos, m_k, m_h2, m_fhVal, m_rhVal, locN, m_hVec)
: !NTM64(m_seq.data() + m_pos, m_k, m_h2, m_fhVal, locN, m_hVec)))
m_pos += locN + 1;
}
if (m_pos >= m_seq.length() - m_k + 1)
m_pos = std::numeric_limits<std::size_t>::max();
}
/** Advance iterator right to the next valid k-mer */
void next()
{
++m_pos;
if (m_pos >= m_seq.length() - m_k + 1)
{
m_pos = std::numeric_limits<std::size_t>::max();
return;
}
if (seedTab[(unsigned char)(m_seq.at(m_pos + m_k - 1))] == seedN)
{
m_pos += m_k;
init();
}
else
{
if (m_rc && m_ss)
{
NTMSMC64(m_seq.data() + m_pos, m_seed, m_seq.at(m_pos - 1), m_seq.at(m_pos - 1 + m_k), m_k, m_h, m_h2, m_fhVal, m_rhVal, m_hVec, m_minhVec, m_hStn);
}
else if (m_ss)
{
NTMSM64(m_seq.data() + m_pos, m_seed, m_seq.at(m_pos - 1), m_seq.at(m_pos - 1 + m_k), m_k, m_h, m_h2, m_fhVal, m_hVec, m_minhVec);
}
else if (m_rc)
{
NTMC64(m_seq.at(m_pos - 1), m_seq.at(m_pos - 1 + m_k), m_k, m_h, m_fhVal, m_rhVal, m_hVec);
}
else
{
NTM64(m_seq.at(m_pos - 1), m_seq.at(m_pos - 1 + m_k), m_k, m_h, m_hVec);
}
}
}
size_t pos() const
{
return m_pos;
}
/** get pointer to strand for current k-mer */
const bool *strandArray() const
{
return m_hStn;
}
/** get pointer to hash values for current k-mer */
const uint64_t *operator*() const
{
if (m_ss)
{
return m_minhVec;
}
else
{
return m_hVec;
}
}
/** test equality with another iterator */
bool operator==(const stHashIterator &it) const
{
return m_pos == it.m_pos;
}
/** test inequality with another iterator */
bool operator!=(const stHashIterator &it) const
{
return !(*this == it);
}
/** pre-increment operator */
stHashIterator &operator++()
{
next();
return *this;
}
/** iterator pointing to one past last element */
static const stHashIterator end()
{
return stHashIterator();
}
/** destructor */
~stHashIterator()
{
if (m_hVec != NULL)
{
delete[] m_hVec;
delete[] m_minhVec;
delete[] m_hStn;
}
}
private:
/** DNA sequence */
std::string m_seq;
/** Spaced Seed sequence */
std::vector<std::vector<unsigned>> m_seed;
/** number of seeds */
unsigned m_h;
/** number of hashes per seed */
unsigned m_h2;
/** k-mer size */
unsigned m_k;
/** canonical k-mers */
bool m_rc;
/** spaced seeds */
bool m_ss;
/** hash values
* For m_h = n and m_h2 = m:
* [seed1Hash1, seed1Hash2 ... seed(n)Hash(m-1), seed(n)Hash(m)]
* minhVec is the minimum across all seeds
*/
uint64_t *m_hVec;
uint64_t *m_minhVec;
/** hash strands, forward = 0, reverse-complement = 1 */
bool *m_hStn;
/** position of current k-mer */
size_t m_pos;
/** forward-strand k-mer hash value */
uint64_t m_fhVal;
/** reverse-complement k-mer hash value */
uint64_t m_rhVal;
};
#endif
|
CodingAir/PacketManagement
|
src/main/java/de/codingair/packetmanagement/utils/FormedPacket.java
|
package de.codingair.packetmanagement.utils;
import de.codingair.packetmanagement.packets.Packet;
import java.util.UUID;
public class FormedPacket {
private final Packet packet;
private final boolean hasFuture;
private final UUID futureId;
public FormedPacket(Packet packet, boolean hasFuture, UUID futureId) {
this.packet = packet;
this.hasFuture = hasFuture;
this.futureId = futureId;
}
public Packet getPacket() {
return packet;
}
public boolean hasFuture() {
return hasFuture;
}
public UUID getFutureId() {
return futureId;
}
}
|
valentinjacot/backupETHZ
|
Java/SiteDuZero/src/Garage/Option.java
|
<filename>Java/SiteDuZero/src/Garage/Option.java
package Garage;
public interface Option {
double getPrix();
String toString();
}
|
minos-framework/minos-python
|
packages/core/minos-microservice-common/minos/common/database/__init__.py
|
from .clients import (
ConnectionException,
DatabaseClient,
DatabaseClientBuilder,
DatabaseClientException,
IntegrityException,
ProgrammingException,
)
from .locks import (
DatabaseLock,
LockDatabaseOperationFactory,
)
from .managements import (
ManagementDatabaseOperationFactory,
)
from .mixins import (
DatabaseMixin,
)
from .operations import (
ComposedDatabaseOperation,
DatabaseOperation,
DatabaseOperationFactory,
)
from .pools import (
DatabaseClientPool,
DatabaseLockPool,
)
|
bloock/bloock-sdk-go
|
internal/infrastructure/hashing_client.go
|
<filename>internal/infrastructure/hashing_client.go
package infrastructure
type HashingClient interface {
GenerateHash(data []byte) string
}
|
alexcheng1982/happy-takeaway
|
lib/common/base/src/main/java/io/vividcode/happytakeaway/common/base/PageRequest.java
|
package io.vividcode.happytakeaway.common.base;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PageRequest {
private int page;
private int size;
public int getOffset() {
return this.page * this.size;
}
public static PageRequest of(int page, int size) {
return PageRequest.builder()
.page(page)
.size(size)
.build();
}
}
|
jacnugent/fv3net
|
workflows/dataflow/tests/integration/test_submission.py
|
<filename>workflows/dataflow/tests/integration/test_submission.py
import pathlib
import subprocess
import uuid
submission = """
bash -x {root}/dataflow.sh submit \
-m fv3net.pipelines.dataflow_test_job \
--save_main_session \
--job_name test-{uuid} \
--project vcm-ml \
--region us-central1 \
--runner DataFlow \
--temp_location gs://vcm-ml-scratch/tmp_dataflow \
--num_workers 1 \
--autoscaling_algorithm=NONE \
--worker_machine_type n1-standard-1 \
--disk_size_gb 30
"""
def test_submit_dataflow():
DATAFLOW_ROOT = pathlib.Path(__file__).parent.parent.parent.absolute()
subprocess.check_call(
[submission.format(root=DATAFLOW_ROOT, uuid=uuid.uuid1().hex)], shell=True
)
|
codeoneline/cross2way-robot
|
src/chain/web3_dev.js
|
const BaseChain = require('../lib/web3_chain');
const { signTx } = require('../lib/dev-helper');
class DevChain extends BaseChain {
constructor() {
super(process.env.RPC_URL_DEV, process.env.CHAINTYPE_DEV);
}
}
const devChain = new DevChain();
module.exports = {
core: devChain,
web3: devChain.web3,
signTx: signTx,
}
|
hboutemy/hedera-services
|
hedera-node/src/main/java/com/hedera/services/state/merkle/MerkleDiskFs.java
|
<reponame>hboutemy/hedera-services
package com.hedera.services.state.merkle;
/*-
*
* Hedera Services Node
*
* Copyright (C) 2018 - 2020 Hedera Hashgraph, 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.
*
*/
import com.google.common.base.MoreObjects;
import com.hederahashgraph.api.proto.java.FileID;
import com.swirlds.common.crypto.Hash;
import com.swirlds.common.io.SerializableDataInputStream;
import com.swirlds.common.io.SerializableDataOutputStream;
import com.swirlds.common.merkle.MerkleExternalLeaf;
import com.swirlds.common.merkle.utility.AbstractMerkleLeaf;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.hedera.services.ledger.HederaLedger.FILE_ID_COMPARATOR;
import static com.hedera.services.legacy.proto.utils.CommonUtils.noThrowSha384HashOf;
import static com.hedera.services.utils.EntityIdUtils.asLiteralString;
import static com.swirlds.common.CommonUtils.hex;
/**
* Save some special system files on the local file system instead of database to improve access efficiency.
*
* All that is kept in memory is a map from {@code FileID} to the SHA-384 hash of the current contents.
*/
public class MerkleDiskFs extends AbstractMerkleLeaf implements MerkleExternalLeaf {
static Logger log = LogManager.getLogger(MerkleDiskFs.class);
private static final long RUNTIME_CONSTRUCTABLE_ID = 0xd8a59882c746d0a3L;
private static final String UNKNOWN_PATH_SEGMENT = null;
static final byte[] MISSING_CONTENT = new byte[0];
static final int HASH_BYTES = 48;
static final int MAX_FILE_BYTES = 1_024 * 1_024 * 1_024;
static final int MERKLE_VERSION = 1;
static ThrowingBytesWriter writeHelper = (p, c) -> FileUtils.writeByteArrayToFile(p.toFile(), c);
static ThrowingBytesGetter bytesHelper = p -> FileUtils.readFileToByteArray(p.toFile());
private String fsBaseDir = UNKNOWN_PATH_SEGMENT;
private String fsNodeScopedDir = UNKNOWN_PATH_SEGMENT;
private Map<FileID, byte[]> fileHashes = new HashMap<>();
/* --- RuntimeConstructable --- */
public MerkleDiskFs() {
setHashFromContents();
}
public MerkleDiskFs(String fsBaseDir, String fsNodeScopedDir) {
this.fsBaseDir = fsBaseDir;
this.fsNodeScopedDir = fsNodeScopedDir;
setHashFromContents();
}
public MerkleDiskFs(Map<FileID, byte[]> fileHashes, String fsBaseDir, String fsNodeScopedDir) {
this.fsBaseDir = fsBaseDir;
this.fileHashes = fileHashes;
this.fsNodeScopedDir = fsNodeScopedDir;
setHashFromContents();
}
public MerkleDiskFs copy() {
Map<FileID, byte[]> fileHashesCopy = fileHashes.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, HashMap::new));
return new MerkleDiskFs(fileHashesCopy, fsBaseDir, fsNodeScopedDir);
}
public void setFsBaseDir(String fsBaseDir) {
this.fsBaseDir = fsBaseDir;
}
public void setFsNodeScopedDir(String fsNodeScopedDir) {
this.fsNodeScopedDir = fsNodeScopedDir;
}
public void checkHashesAgainstDiskContents() {
for (FileID fid : fileHashes.keySet()) {
byte[] expectedHash = fileHashes.get(fid);
byte[] actualHash = diskContentHash(fid);
if (!Arrays.equals(expectedHash, actualHash)) {
log.error(
"State hash doesn't match disk hash for content of '{}'!\n State :: {}\n Disk :: {}",
asLiteralString(fid),
hex(expectedHash),
hex(actualHash));
}
}
}
public byte[] diskContentHash(FileID fid) {
return noThrowSha384HashOf(contentsOf(fid));
}
public synchronized byte[] contentsOf(FileID fid) {
try {
return bytesHelper.allBytesFrom(pathToContentsOf(fid));
} catch (IOException e) {
log.error("Error reading '{}' @ {}!", asLiteralString(fid), pathToContentsOf(fid), e);
return MISSING_CONTENT;
}
}
public synchronized void put(FileID fid, byte[] contents) {
try {
byte[] hash = noThrowSha384HashOf(contents);
writeHelper.allBytesTo(pathToContentsOf(fid), contents);
log.info("Updated '{}' with {} bytes; new hash :: {}", asLiteralString(fid), contents.length, hex(hash));
fileHashes.put(fid, hash);
setHashFromContents();
} catch (IOException e) {
log.error(
"Error writing new contents for '{}' to disk @ {}!",
asLiteralString(fid),
pathToContentsOf(fid),
e);
}
}
public boolean contains(FileID fileID) {
return fileHashes.containsKey(fileID);
}
/* --- MerkleExternalLeaf --- */
@Override
public void serializeAbbreviated(SerializableDataOutputStream out) throws IOException {
out.writeInt(fileHashes.size());
serializeFidInfo(out, fileHashes::get);
}
@Override
public void deserializeAbbreviated(SerializableDataInputStream in, Hash hash, int version) throws IOException {
int numSavedHashes = in.readInt();
for (int i = 0; i < numSavedHashes; i++) {
var fid = FileID.newBuilder()
.setShardNum(in.readLong())
.setRealmNum(in.readLong())
.setFileNum(in.readLong())
.build();
byte[] fileHash = in.readByteArray(HASH_BYTES);
fileHashes.put(fid, fileHash);
log.info("Recovered file '{}' with hash :: {}", asLiteralString(fid), hex(fileHash));
}
super.setHash(hash);
}
/* -- Hashable -- */
@Override
public void setHash(Hash hash) {
/* No-op, hash is managed internally. */
}
private void setHashFromContents() {
var baos = new ByteArrayOutputStream();
try (SerializableDataOutputStream out = new SerializableDataOutputStream(baos)) {
serializeFidInfo(out, fileHashes::get);
} catch (IOException improbable) {
throw new IllegalStateException(improbable);
}
try {
baos.close();
baos.flush();
} catch (IOException improbable) {
throw new IllegalStateException(improbable);
}
super.setHash(new Hash(noThrowSha384HashOf(baos.toByteArray())));
}
/* --- SelfSerializable --- */
@Override
public void deserialize(SerializableDataInputStream in, int version) throws IOException {
int numSavedHashes = in.readInt();
for (int i = 0; i < numSavedHashes; i++) {
var fid = FileID.newBuilder()
.setShardNum(in.readLong())
.setRealmNum(in.readLong())
.setFileNum(in.readLong())
.build();
byte[] contents = in.readByteArray(MAX_FILE_BYTES);
writeHelper.allBytesTo(pathToContentsOf(fid), contents);
byte[] fileHash = noThrowSha384HashOf(contents);
fileHashes.put(fid, fileHash);
log.info("Restored file '{}' with hash :: {}", asLiteralString(fid), hex(fileHash));
}
setHashFromContents();
}
@Override
public void serialize(SerializableDataOutputStream out) throws IOException {
out.writeInt(fileHashes.size());
serializeFidInfo(out, fid -> {
try {
return bytesHelper.allBytesFrom(pathToContentsOf(fid));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
/* --- MerkleNode --- */
@Override
public long getClassId() {
return RUNTIME_CONSTRUCTABLE_ID;
}
@Override
public int getVersion() {
return MERKLE_VERSION;
}
/* --- Object --- */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || MerkleDiskFs.class != o.getClass()) {
return false;
}
MerkleDiskFs that = (MerkleDiskFs) o;
return Objects.equals(this.fsBaseDir, that.fsBaseDir) &&
Objects.equals(this.fsNodeScopedDir, that.fsNodeScopedDir) &&
allFileHashesMatch(this.fileHashes, that.fileHashes);
}
@Override
public int hashCode() {
return Objects.hash(fileHashes, fsBaseDir, fsNodeScopedDir);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(MerkleDiskFs.class)
.add("baseDir", fsBaseDir)
.add("nodeScopedDir", fsNodeScopedDir)
.add("fileHashes", readableFileHashes())
.toString();
}
private String readableFileHashes() {
var sb = new StringBuilder("[");
sb.append(orderedFids()
.map(fid -> asLiteralString(fid) + " :: " + hex(fileHashes.get(fid)))
.collect(Collectors.joining(", ")));
return sb.append("]").toString();
}
private boolean allFileHashesMatch(Map<FileID, byte[]> a, Map<FileID, byte[]> b) {
if (a.keySet().equals(b.keySet())) {
for (FileID fid : a.keySet()) {
if (!Arrays.equals(a.get(fid), b.get(fid))) {
return false;
}
}
return true;
}
return false;
}
Path pathToContentsOf(FileID fid) {
return Paths.get(String.format(
"%s%sFile%s",
separatorSuffixed(fsBaseDir),
separatorSuffixed(fsNodeScopedDir),
asLiteralString(fid)));
}
private String separatorSuffixed(String dir) {
return dir.endsWith(File.separator) ? dir : (dir + File.separator);
}
private void serializeFidInfo(
SerializableDataOutputStream out,
Function<FileID, byte[]> infoReprFn
) {
orderedFids().forEach(fid -> {
try {
out.writeLong(fid.getShardNum());
out.writeLong(fid.getRealmNum());
out.writeLong(fid.getFileNum());
out.writeByteArray(infoReprFn.apply(fid));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
private Stream<FileID> orderedFids() {
return fileHashes.keySet().stream().sorted(FILE_ID_COMPARATOR);
}
@FunctionalInterface
interface ThrowingBytesGetter {
byte[] allBytesFrom(Path loc) throws IOException;
}
@FunctionalInterface
interface ThrowingBytesWriter {
void allBytesTo(Path loc, byte[] contents) throws IOException;
}
}
|
maciejg-git/vue-bootstrap-icons
|
dist-mdi/mdi/archive-eye.js
|
import { h } from 'vue'
export default {
name: "ArchiveEye",
vendor: "Mdi",
type: "",
tags: ["archive","eye"],
render() {
return h(
"svg",
{"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-archive-eye","innerHTML":"<path d='M21 7H3V3H21V7M9.14 19.75C9.32 20.19 9.54 20.61 9.78 21H4V8H20V13.55C19.06 13.19 18.05 13 17 13C13.5 13 10.43 15.06 9.14 18.25L8.85 19L9.14 19.75M9 13H15V11.5C15 11.22 14.78 11 14.5 11H9.5C9.22 11 9 11.22 9 11.5V13M17 18C16.44 18 16 18.44 16 19S16.44 20 17 20 18 19.56 18 19 17.56 18 17 18M23 19C22.06 21.34 19.73 23 17 23S11.94 21.34 11 19C11.94 16.66 14.27 15 17 15S22.06 16.66 23 19M19.5 19C19.5 17.62 18.38 16.5 17 16.5S14.5 17.62 14.5 19 15.62 21.5 17 21.5 19.5 20.38 19.5 19Z' />"},
)
}
}
|
suraj-testing2/Flowers_Shoe
|
http/node_modules/jsDAV/node_modules/gnu-tools/findutils-src/lib/waitpid.c
|
<gh_stars>10-100
/* Emulate waitpid on systems that just have wait.
Copyright 1994, 1995, 1998, 1999 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <errno.h>
#ifndef errno
extern int errno;
#endif
#if defined _MSC_VER || defined __MINGW32__
/* Native Woe32 API. */
#include <process.h>
#else
/* Unix API. */
#include "wait.h"
#endif
#define WAITPID_CHILDREN 8
static pid_t waited_pid[WAITPID_CHILDREN];
static int waited_status[WAITPID_CHILDREN];
pid_t
waitpid (pid_t pid, int *stat_loc, int options)
{
int i;
pid_t p;
if (!options && (pid == -1 || 0 < pid))
{
/* If we have already waited for this child, return it immediately. */
for (i = 0; i < WAITPID_CHILDREN; i++)
{
p = waited_pid[i];
if (p && (p == pid || pid == -1))
{
waited_pid[i] = 0;
goto success;
}
}
/* The child has not returned yet; wait for it, accumulating status. */
for (i = 0; i < WAITPID_CHILDREN; i++)
if (! waited_pid[i])
{
p = wait (&waited_status[i]);
if (p < 0)
return p;
if (p == pid || pid == -1)
goto success;
waited_pid[i] = p;
}
}
/* We cannot emulate this wait call, e.g. because of too many children. */
errno = EINVAL;
return -1;
success:
if (stat_loc)
*stat_loc = waited_status[i];
return p;
}
|
yashashrirane/interlok
|
interlok-core/src/test/java/com/adaptris/core/services/metadata/WriteMetadataToFilesystemTest.java
|
<gh_stars>0
/*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core.services.metadata;
import static com.adaptris.core.services.metadata.ReadMetadataFromFilesystemTest.BASE_DIR;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.junit.Test;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.ConfiguredProduceDestination;
import com.adaptris.core.CoreException;
import com.adaptris.core.DefaultMessageFactory;
import com.adaptris.core.EmptyFileNameCreator;
import com.adaptris.core.FormattedFilenameCreator;
import com.adaptris.core.ServiceException;
import com.adaptris.core.fs.FsHelper;
import com.adaptris.core.metadata.NoOpMetadataFilter;
import com.adaptris.core.metadata.RegexMetadataFilter;
import com.adaptris.core.services.metadata.WriteMetadataToFilesystem.OutputStyle;
import com.adaptris.core.util.LifecycleHelper;
import com.adaptris.util.GuidGenerator;
public class WriteMetadataToFilesystemTest extends MetadataServiceExample {
@Override
public boolean isAnnotatedForJunit4() {
return true;
}
@Test
public void testDestination() throws Exception {
WriteMetadataToFilesystem service = new WriteMetadataToFilesystem();
assertNull(service.getDestination());
try {
LifecycleHelper.init(service);
fail("Service initialised with a null destination");
}
catch (CoreException expected) {
}
service.setDestination(new ConfiguredProduceDestination("dest"));
assertNotNull(service.getDestination());
assertEquals("dest", service.getDestination().getDestination(new DefaultMessageFactory().newMessage()));
try {
service.setDestination(null);
fail();
}
catch (IllegalArgumentException e) {
}
assertNotNull(service.getDestination());
assertEquals("dest", service.getDestination().getDestination(new DefaultMessageFactory().newMessage()));
}
@Test
public void testSetMetadataFilter() throws Exception {
WriteMetadataToFilesystem service = new WriteMetadataToFilesystem();
assertNull(service.getMetadataFilter());
service.setMetadataFilter(new RegexMetadataFilter());
assertEquals(RegexMetadataFilter.class, service.getMetadataFilter().getClass());
service.setMetadataFilter(null);
assertEquals(NoOpMetadataFilter.class, service.metadataFilter().getClass());
}
@Test
public void testOverwriteIfExists() throws Exception {
WriteMetadataToFilesystem service = new WriteMetadataToFilesystem();
assertNull(service.getOverwriteIfExists());
assertFalse(service.overwriteIfExists());
service.setOverwriteIfExists(null);
assertFalse(service.overwriteIfExists());
service.setOverwriteIfExists(Boolean.TRUE);
assertNotNull(service.getOverwriteIfExists());
assertTrue(service.overwriteIfExists());
}
@Test
public void testOutputStyle() throws Exception {
WriteMetadataToFilesystem service = new WriteMetadataToFilesystem();
assertNull(service.getOutputStyle());
service.setOutputStyle(OutputStyle.Text);
assertEquals(OutputStyle.Text, service.getOutputStyle());
}
@Test
public void testFilenameCreator() throws Exception {
WriteMetadataToFilesystem service = new WriteMetadataToFilesystem();
assertEquals(FormattedFilenameCreator.class, service.filenameCreator().getClass());
service.setFilenameCreator(new EmptyFileNameCreator());
assertEquals(EmptyFileNameCreator.class, service.getFilenameCreator().getClass());
service.setFilenameCreator(null);
assertEquals(FormattedFilenameCreator.class, service.filenameCreator().getClass());
}
@Test
public void testService_Default() throws Exception {
String subDir = new GuidGenerator().getUUID().replaceAll(":", "").replaceAll("-", "");
AdaptrisMessage msg = createMessage();
WriteMetadataToFilesystem service = createService(subDir);
File parentDir = FsHelper.createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_DIR), true));
String propsFilename = parentDir.getCanonicalPath() + "/" + subDir + "/" + msg.getUniqueId();
execute(service, msg);
Properties p = readProperties(new File(propsFilename), false);
assertTrue(p.containsKey("key5"));
assertEquals("v5", p.getProperty("key5"));
}
@Test
public void testService_OutputXml() throws Exception {
String subDir = new GuidGenerator().getUUID().replaceAll(":", "").replaceAll("-", "");
AdaptrisMessage msg = createMessage();
WriteMetadataToFilesystem service = createService(subDir);
service.setOutputStyle(OutputStyle.XML);
File parentDir = FsHelper.createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_DIR), true));
String propsFilename = parentDir.getCanonicalPath() + "/" + subDir + "/" + msg.getUniqueId();
execute(service, msg);
Properties p = readProperties(new File(propsFilename), true);
assertTrue(p.containsKey("key5"));
assertEquals("v5", p.getProperty("key5"));
}
@Test
public void testService_OutputUnknown() throws Exception {
String subDir = new GuidGenerator().getUUID().replaceAll(":", "").replaceAll("-", "");
AdaptrisMessage msg = createMessage();
WriteMetadataToFilesystem service = createService(subDir);
File parentDir = FsHelper.createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_DIR), true));
String propsFilename = parentDir.getCanonicalPath() + "/" + subDir + "/" + msg.getUniqueId();
execute(service, msg);
Properties p = readProperties(new File(propsFilename), false);
assertTrue(p.containsKey("key5"));
assertEquals("v5", p.getProperty("key5"));
}
@Test
public void testService_Filter() throws Exception {
String subDir = new GuidGenerator().getUUID().replaceAll(":", "").replaceAll("-", "");
AdaptrisMessage msg = createMessage();
WriteMetadataToFilesystem service = createService(subDir);
RegexMetadataFilter filter = new RegexMetadataFilter();
filter.addIncludePattern("alt_key.*");
filter.addExcludePattern("^key.*");
service.setMetadataFilter(filter);
File parentDir = FsHelper.createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_DIR), true));
String propsFilename = parentDir.getCanonicalPath() + "/" + subDir + "/" + msg.getUniqueId();
execute(service, msg);
Properties p = readProperties(new File(propsFilename), false);
assertFalse(p.containsKey("key5"));
assertTrue(p.containsKey("alt_key5"));
assertEquals("av5", p.getProperty("alt_key5"));
}
@Test
public void testService_OverwriteFalseFileNonExistent() throws Exception {
String subDir = new GuidGenerator().getUUID().replaceAll(":", "").replaceAll("-", "");
AdaptrisMessage msg = createMessage();
WriteMetadataToFilesystem service = createService(subDir);
service.setOverwriteIfExists(false);
File parentDir = FsHelper.createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_DIR), true));
String propsFilename = parentDir.getCanonicalPath() + "/" + subDir + "/" + msg.getUniqueId();
execute(service, msg);
Properties p = readProperties(new File(propsFilename), false);
assertTrue(p.containsKey("key5"));
assertEquals("v5", p.getProperty("key5"));
}
@Test
public void testService_OverwriteFalseFileExists() throws Exception {
String subDir = new GuidGenerator().getUUID().replaceAll(":", "").replaceAll("-", "");
AdaptrisMessage msg = createMessage();
WriteMetadataToFilesystem service = createService(subDir);
service.setOverwriteIfExists(false);
File parentDir = FsHelper.createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_DIR), true));
String propsFilename = parentDir.getCanonicalPath() + "/" + subDir + "/" + msg.getUniqueId();
createEmptyFile(new File(propsFilename));
try {
execute(service, msg);
fail();
}
catch (ServiceException expected) {
}
}
@Test
public void testService_OverwriteTrueFileNonExistent() throws Exception {
String subDir = new GuidGenerator().getUUID().replaceAll(":", "").replaceAll("-", "");
AdaptrisMessage msg = createMessage();
WriteMetadataToFilesystem service = createService(subDir);
service.setOverwriteIfExists(true);
File parentDir = FsHelper.createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_DIR), true));
String propsFilename = parentDir.getCanonicalPath() + "/" + subDir + "/" + msg.getUniqueId();
execute(service, msg);
Properties p = readProperties(new File(propsFilename), false);
assertTrue(p.containsKey("key5"));
assertEquals("v5", p.getProperty("key5"));
}
@Test
public void testService_OverwriteTrueFileExists() throws Exception {
String subDir = new GuidGenerator().getUUID().replaceAll(":", "").replaceAll("-", "");
AdaptrisMessage msg = createMessage();
WriteMetadataToFilesystem service = createService(subDir);
service.setOverwriteIfExists(true);
File parentDir = FsHelper.createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_DIR), true));
String propsFilename = parentDir.getCanonicalPath() + "/" + subDir + "/" + msg.getUniqueId();
createEmptyFile(new File(propsFilename));
execute(service, msg);
Properties p = readProperties(new File(propsFilename), false);
assertTrue(p.containsKey("key5"));
assertEquals("v5", p.getProperty("key5"));
}
private void createEmptyFile(File f) throws IOException {
File parent = f.getParentFile();
if (parent != null) {
parent.mkdirs();
}
FileOutputStream out = new FileOutputStream(f);
out.write(new byte[0]);
out.close();
}
private AdaptrisMessage createMessage() {
AdaptrisMessage msg = new DefaultMessageFactory().newMessage();
for (int i = 1; i <= 10; i++) {
msg.addMetadata("key" + i, "v" + i);
msg.addMetadata("alt_key" + i, "av" + i);
}
return msg;
}
private WriteMetadataToFilesystem createService(String subDir) {
String baseString = PROPERTIES.getProperty(BASE_DIR);
WriteMetadataToFilesystem service = new WriteMetadataToFilesystem(new ConfiguredProduceDestination(baseString + "/" + subDir));
return service;
}
private Properties readProperties(File filename, boolean xml) throws IOException {
Properties p = new Properties();
try (InputStream in = new FileInputStream(filename)) {
if (xml) {
p.loadFromXML(in);
}
else {
p.load(in);
}
}
return p;
}
@Override
protected WriteMetadataToFilesystem retrieveObjectForSampleConfig() {
WriteMetadataToFilesystem service = new WriteMetadataToFilesystem();
service.setDestination(new ConfiguredProduceDestination("file:////path/to/directory"));
service.setOutputStyle(OutputStyle.Text);
return service;
}
}
|
otaniemen-lukio/projects
|
vpython/painovoima/aurinkokunta.py
|
<filename>vpython/painovoima/aurinkokunta.py
from vpython import *
#GlowScript 3.0 VPython
gc = 6.67428*10**(-11) # gravitaatiovakio
m_sun = 1.989e30
m_earth = 5.974*10**(24)
r_earth = 6.378*10**(6) # Maan säde meterissä
v_earth =107200/3.6
AU = 149597871000 # etäisyys m
#Merkurius
m_merkurius = 330.104*10**21
v_merkurius = 47870
r_merkurius =0.39*AU
#Venus
m_venus = 6.39*10**23
v_venus = 35020
r_venus =0.7*AU
class Body():
def __init__(self, m, r, v):
self.m = m
self.r = r
if mag(r) !=0:
unit_n = r/mag(r)
unit_t =rotate(unit_n, angle=pi/2)
self.v = unit_t*v
else:
self.v = vector(0,0,0)
self.a = 0
self.new_r = r
if mag(r) == 0:
self.s = sphere (pos = r, color = color.yellow, radius = (1 * m ** (1/3)), make_trail=True)
else:
self.s = sphere (pos = r, color = color.red, radius = (50 * m ** (1/3)), make_trail=True)
def act(self, force, dt):
self.a = force / self.m
self.v += self.a * dt
self.new_r = self.r + self.v * dt
def update(self):
self.r = self.new_r
self.s.pos = self.r
body_list = [Body(m_sun, vector(0, 0, 0), 0), \
Body(m_earth, vector(0,AU,0), v_earth),\
Body(m_merkurius, vector(r_merkurius*cos(45),r_merkurius*sin(45),0), v_merkurius),\
Body(m_venus, vector(-r_venus*cos(45),-r_venus*sin(45),0), v_venus)]
total_time = 0
#RATE = 1000
dt = 60
RATE = dt*60*24*365
while True:
rate(RATE)
for i, body in enumerate(body_list):
for j, target in enumerate(body_list):
if body == target:
continue
fg_mag = gc * (target.m * body.m) / (mag(target.r - body.r) ** 2)
dir = (target.r - body.r) / mag(target.r - body.r)
fg = fg_mag * dir
body.act(fg, dt)
#fe_mag = -E * (target.q * body.q) / (mag(target.p - body.p) ** 2)
#fe = fe_mag * dir
#body.act(fe, dt)
for body in body_list:
body.update()
total_time+=dt
|
colt3k/utils
|
crypt/encrypt/stream/stream3_test.go
|
package stream
import (
"fmt"
"io/ioutil"
"log"
"os"
"testing"
"github.com/colt3k/utils/file/filenative"
"github.com/colt3k/utils/crypt"
"github.com/colt3k/utils/crypt/encrypt/scrypt"
)
func TestEncrypt(t *testing.T) {
testfile := "/Users/gcollins/Desktop/b2test/hello1.txt"
fo, err := os.Open(testfile)
if err != nil {
panic(err)
}
tf, err := ioutil.TempFile(os.TempDir(), "ctcloud")
if err != nil {
panic(err)
}
saltAR := crypt.GenSalt(nil, ScryptParams.SaltLen)
ScryptParams.Salt = saltAR
derivedKey, err := scrypt.Key(string("mypass"), ScryptParams)
if err != nil {
panic(err)
}
aesKey2 := derivedKey[0:16]
//aesIv2 := derivedKey[16:32]
hmacKey := []byte("this is my hmackey")
err = Encrypt(fo, tf, aesKey2, hmacKey)
if err != nil {
panic(err)
}
fmt.Println("Temp at ", tf.Name())
fo.Close()
tf.Close()
// DECRYPT
f := filenative.NewFile(tf.Name())
fo, err = os.Open(f.Path())
if err != nil {
panic(err)
}
tf, err = os.Create("./hello1.txt")
if err != nil {
panic(err)
}
err = Decrypt(fo, tf, aesKey2, hmacKey)
if err != nil {
panic(err)
}
}
//type devZero byte
//
//func (z devZero) Read(b []byte) (int, error) {
// for i := range b {
// b[i] = byte(z)
// }
// return len(b), nil
//}
//
//func mockDataSrc(size int64) io.Reader {
// fmt.Printf("dev/zero of size %d (%d MB)\n", size, size/1024/1024)
// var z devZero
// return io.LimitReader(z, size)
//}
func TestDecrypt(t *testing.T) {
testfile := "/Users/gcollins/Desktop/b2test/hello1.txt"
fo, err := os.Open(testfile)
if err != nil {
panic(err)
}
tf, err := ioutil.TempFile(os.TempDir(), "ctcloud")
if err != nil {
panic(err)
}
fmt.Println("Here is the temp: ", tf.Name())
//keyAes, _ := hex.DecodeString(strings.Repeat("6368616e676520746869732070617373", 2))
//keyHmac := keyAes // don't do this
saltAR := crypt.GenSalt(nil, ScryptParams.SaltLen)
ScryptParams.Salt = saltAR
derivedKey, err := scrypt.Key(string("mypass"), ScryptParams)
if err != nil {
panic(err)
}
aesKey2 := derivedKey[0:16]
//aesIv2 := derivedKey[16:32]
err = Encrypt(fo, tf, aesKey2, aesKey2)
if err != nil {
log.Fatal(err)
}
tf.Sync()
tf.Close()
f := filenative.NewFile(tf.Name())
fo, err = os.Open(f.Path())
if err != nil {
panic(err)
}
tf, err = os.Create("./hello1.txt")
if err != nil {
panic(err)
}
err = Decrypt(fo, tf, aesKey2, aesKey2)
if err != nil {
log.Fatal(err)
}
}
|
kylekrol/psim
|
src/psim/fc/detumbler.cpp
|
//
// MIT License
//
// Copyright (c) 2020 Pathfinder for Autonomous Navigation (PAN)
//
// 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.
//
/** @file psim/fc/detumbler.cpp
* @author <NAME>
*/
#include <psim/fc/detumbler.hpp>
#include <lin/core.hpp>
#include <lin/generators.hpp>
#include <lin/math.hpp>
#include <lin/queries.hpp>
namespace psim {
void Detumbler::step() {
this->Super::step();
auto const &b_body = sensors_satellite_magnetometer_b->get();
auto &m_body = truth_satellite_magnetorquers_m->get();
gnc::DetumbleControllerData data;
data.b_body = b_body;
gnc::DetumbleActuation actutation;
gnc::control_detumble(_detumbler, data, actutation);
if (lin::all(lin::isfinite(actutation.mtr_body_cmd))) {
m_body = lin::cast<Real>(actutation.mtr_body_cmd);
} else {
m_body = lin::zeros<Vector3>();
}
}
} // namespace psim
|
albailey/config
|
sysinv/cgts-client/cgts-client/cgtsclient/v1/idns_shell.py
|
#
# Copyright (c) 2013-2015 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# All Rights Reserved.
#
from cgtsclient.common import utils
from cgtsclient import exc
def _print_idns_show(idns):
fields = ['uuid', 'nameservers', 'isystem_uuid',
'created_at', 'updated_at']
data = [(f, getattr(idns, f, '')) for f in fields]
utils.print_tuple_list(data)
def do_dns_show(cc, args):
"""Show DNS (Domain Name Server) attributes."""
idnss = cc.idns.list()
# idns = cc.idns.get(idnss[0])
_print_idns_show(idnss[0])
def donot_dns_list(cc, args):
"""List dnss."""
idnss = cc.idns.list()
field_labels = ['uuid', 'nameservers']
fields = ['uuid', 'nameservers']
utils.print_list(idnss, fields, field_labels, sortby=1)
@utils.arg('cname',
metavar='<dns name>',
help="Name of dns [REQUIRED]")
def donot_dns_add(cc, args):
"""Add an dns."""
field_list = ['cname']
fields = {}
user_specified_fields = dict((k, v) for (k, v) in vars(args).items()
if k in field_list and not (v is None))
fields.update(user_specified_fields)
try:
idns = cc.idns.create(**fields)
suuid = getattr(idns, 'uuid', '')
except exc.HTTPNotFound:
raise exc.CommandError('DNS create failed: name %s, fields %s ' %
(args.cname, fields))
try:
idns = cc.idns.get(suuid)
except exc.HTTPNotFound:
raise exc.CommandError('dns not found: %s' % suuid)
_print_idns_show(idns)
@utils.arg('attributes',
metavar='<path=value>',
nargs='+',
action='append',
default=[],
help="DNS attributes to modify ")
def do_dns_modify(cc, args):
"""Modify DNS attributes."""
idnss = cc.idns.list()
idns = idnss[0]
op = "replace"
for attribute in args.attributes:
if 'nameservers=' in attribute:
nameservers = attribute[0].split('=')[1]
if not nameservers.strip():
args.attributes[0][0] = 'nameservers=NC'
if not any('action=' in att for att in args.attributes[0]):
args.attributes[0].append('action=apply')
patch = utils.args_array_to_patch(op, args.attributes[0])
try:
idns = cc.idns.update(idns.uuid, patch)
except exc.HTTPNotFound:
raise exc.CommandError('DNS not found: %s' % idns.uuid)
_print_idns_show(idns)
|
Lukermelesh/rich-content
|
applitools.config.js
|
<reponame>Lukermelesh/rich-content
const { execSync } = require('child_process');
let privateConfig = {};
try {
privateConfig = require('./applitools.private.config.js');
} catch (e) {}
function getBranchName() {
return execSync('git rev-parse --abbrev-ref HEAD')
.toString()
.trim();
}
module.exports = {
...privateConfig,
concurrency: 200,
dontCloseBatches: true,
batchName: `LOCAL - ${getBranchName()}`,
parentBranchName: 'wix-incubator/rich-content/master',
branchName: `wix-incubator/rich-content/${getBranchName()}`,
};
|
dengzhicheng092/o2oshop
|
User-App/app/src/main/java/com/tecmanic/gogrocer/Adapters/CategoryGridAdapter.java
|
package com.tecmanic.gogrocer.Adapters;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Movie;
import android.media.Image;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tecmanic.gogrocer.Activity.ProductDetails;
import com.tecmanic.gogrocer.Categorygridquantity;
import com.tecmanic.gogrocer.Config.BaseURL;
import com.tecmanic.gogrocer.Constans.RecyclerTouchListener;
import com.tecmanic.gogrocer.Fragments.Recent_Details_Fragment;
import com.tecmanic.gogrocer.ModelClass.CartModel;
import com.tecmanic.gogrocer.ModelClass.CategoryGrid;
import com.tecmanic.gogrocer.ModelClass.varient_product;
import com.tecmanic.gogrocer.R;
import com.tecmanic.gogrocer.util.DatabaseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.tecmanic.gogrocer.Config.BaseURL.IMG_URL;
import static com.tecmanic.gogrocer.Config.BaseURL.ProductVarient;
public class CategoryGridAdapter extends RecyclerView.Adapter<CategoryGridAdapter.MyViewHolder> {
private List<CategoryGrid> CategoryGridList;
Context context;
RecyclerView recyler_popup;
LinearLayout cancl;
private DatabaseHandler dbcart;
Categorygridquantity categorygridquantity;
private List<varient_product> varientProducts = new ArrayList<>();
// public CategoryGridAdapter(Context context, List<CategoryGrid> categoryGridList, Categorygridquantity categorygridquantity) {
// CategoryGridList = categoryGridList;
// dbcart = new DatabaseHandler(context);
// this.categorygridquantity = categorygridquantity;
//
// }
//
//
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView prodNAme, pDescrptn, pQuan, pPrice, pdiscountOff, pMrp, minus, plus, txtQuan, txt_unitvalue;
ImageView image;
LinearLayout btn_Add, ll_addQuan;
int minteger = 0;
RelativeLayout rlQuan;
String catId, catName;
public MyViewHolder(View view) {
super(view);
prodNAme = (TextView) view.findViewById(R.id.txt_pName);
pDescrptn = (TextView) view.findViewById(R.id.txt_pInfo);
pQuan = (TextView) view.findViewById(R.id.txt_unit);
pPrice = (TextView) view.findViewById(R.id.txt_Pprice);
image = (ImageView) view.findViewById(R.id.prodImage);
pdiscountOff = (TextView) view.findViewById(R.id.txt_discountOff);
pMrp = (TextView) view.findViewById(R.id.txt_Mrp);
rlQuan = view.findViewById(R.id.rlQuan);
btn_Add = view.findViewById(R.id.btn_Add);
ll_addQuan = view.findViewById(R.id.ll_addQuan);
txtQuan = view.findViewById(R.id.txtQuan);
minus = view.findViewById(R.id.minus);
plus = view.findViewById(R.id.plus);
txt_unitvalue = view.findViewById(R.id.txt_unitvalue);
ll_addQuan = view.findViewById(R.id.ll_addQuan);
// btn_Add.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// btn_Add.setVisibility(View.GONE);
// ll_addQuan.setVisibility(View.VISIBLE);
// txtQuan.setText("1");
// updateMultiply();
// }
// });
// plus.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// increaseInteger();
// updateMultiply();
//
// if (Float.parseFloat(txtQuan.getText().toString()) == 1) {
// /* minus.setClickable(false);
// minus.setFocusable(false);*/
// } else if (Float.parseFloat(txtQuan.getText().toString()) > 1) {
// minus.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// decreaseInteger();
// updateMultiply();
// }
// });
// }
// }
// });
// minus.setOnClickListener(this);
// plus.setOnClickListener(this);
}
}
// private void updateMultiply() {
// int position = getAdapterPosition();
// HashMap<String, String> map = new HashMap<>();
//// map.put("varient_id",CategoryGridList.get(position).getpId());
// map.put("varient_id", CategoryGridList.get(position).getVarient_id());
// Log.d("dfass", CategoryGridList.get(position).getVarient_id());
// map.put("product_name", CategoryGridList.get(position).getName());
//// map.put("category_id",CategoryGridList.get(position).get());
// map.put("title", CategoryGridList.get(position).getDescription());
// map.put("price", CategoryGridList.get(position).getPrice());
// Log.d("dsfa", CategoryGridList.get(position).getPrice());
// map.put("mrp", CategoryGridList.get(position).getMrp());
// Log.d("fd", CategoryGridList.get(position).getImage());
// map.put("product_image", CategoryGridList.get(position).getImage());
//// map.put("status",CategoryGridList.get(position).get());
//// map.put("in_stock",CategoryGridList.get(position).getIn_stock());
// map.put("unit_value", CategoryGridList.get(position).getQuantity());
// map.put("unit", CategoryGridList.get(position).getUnit());
// map.put("increament", "0");
// map.put("rewards", "0");
// map.put("stock", "0");
// map.put("product_description", "0");
//
// Log.d("fgh", txtQuan.getText().toString());
//// Log.d("fghfgh",CategoryGridList.get(position).getpPrice());
// /* map.put("start_date", CategoryGridList.get(position).getStart_date());
// map.put("start_time", CategoryGridList.get(position).getStart_time());
// map.put("end_date", CategoryGridList.get(position).getEnd_date());
// map.put("end_time", CategoryGridList.get(position).getEnd_time());*/
// if (!txtQuan.getText().toString().equalsIgnoreCase("0")) {
// if (dbcart.isInCart(map.get("varient_id"))) {
// dbcart.setCart(map, Integer.valueOf(txtQuan.getText().toString()));
// Log.d("sdf", "update");
// // Toast.makeText(context, "Product quantity is updated in your cart", Toast.LENGTH_SHORT).show();
//
// } else {
// dbcart.setCart(map, Integer.valueOf(txtQuan.getText().toString()));
// // Toast.makeText(context, "Product quantity is added in your cart", Toast.LENGTH_SHORT).show();
//
// }
// } else {
// dbcart.removeItemFromCart(map.get("varient_id"));
// }
// try {
// int items = (int) Double.parseDouble(dbcart.getInCartItemQty(map.get("varient_id")));
// Double price = Double.parseDouble(map.get("price").trim());
// Double mrp = Double.parseDouble(map.get("mrp").trim());
// // Double reward = Double.parseDouble(map.get("rewards"));
// // tv_reward.setText("" + reward * items);
//// pDescrptn.setText(""+CategoryGridList.get(position).getpDes());
// pPrice.setText("" + price * items);
// txtQuan.setText("" + items);
// pMrp.setText("" + mrp * items);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// // ((MainActivity) context).setCartCounter("" + dbcart.getCartCount());
// }
// } catch (IndexOutOfBoundsException e) {
// e.toString();
// Log.d("qwer", e.toString());
// }
// }
//
// public void increaseInteger() {
// minteger = minteger + 1;
// display(minteger);
// }
//
// public void decreaseInteger() {
// if (minteger == 1) {
// minteger = 1;
// display(minteger);
// ll_addQuan.setVisibility(View.GONE);
// btn_Add.setVisibility(View.VISIBLE);
// } else {
// minteger = minteger - 1;
// display(minteger);
//
// }
// }
//
// private void display(Integer number) {
//
// txtQuan.setText("" + number);
// }
public CategoryGridAdapter(List<CategoryGrid> categoryGridList, Context context,Categorygridquantity categorygridquantity) {
this.CategoryGridList = categoryGridList;
this.dbcart = new DatabaseHandler(context);
this.categorygridquantity=categorygridquantity;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_category_list, parent, false);
context = parent.getContext();
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
dbcart = new DatabaseHandler(context);
CategoryGrid cc = CategoryGridList.get(position);
holder.prodNAme.setText(cc.getName());
holder.pPrice.setText(cc.getPrice());
holder.txt_unitvalue.setText(cc.getUnit());
holder.pQuan.setText(cc.getQuantity());
holder.pMrp.setText(cc.getMrp());
Glide.with(context)
.load(IMG_URL + cc.getImage())
.centerCrop()
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.dontAnimate()
.into(holder.image);
double price = Double.parseDouble(CategoryGridList.get(position).getPrice());
double mrp = Double.parseDouble(CategoryGridList.get(position).getMrp());
holder.image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, ProductDetails.class);
intent.putExtra("sId", cc.getId());
intent.putExtra("sName", cc.getName());
intent.putExtra("descrip", cc.getDescription());
intent.putExtra("price", cc.getPrice());
intent.putExtra("mrp", cc.getMrp());
intent.putExtra("unit", cc.getUnit());
intent.putExtra("qty", cc.getQuantity());
intent.putExtra("image", BaseURL.IMG_URL+cc.getVarient_image());
intent.putExtra("sVariant_id", cc.getVarient_id());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Glide.with(context)
.load(IMG_URL + cc.getVarient_image())
.centerCrop()
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.dontAnimate()
.into(holder.image);
holder.rlQuan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
categorygridquantity.onClick(view, position, cc.getId(),cc.getName());
// final Dialog dialog = new Dialog(context);
// Window window = dialog.getWindow();
// WindowManager.LayoutParams wlp = window.getAttributes();
//
// wlp.gravity = Gravity.BOTTOM;
// wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
// window.setAttributes(wlp);
// dialog.setContentView(R.layout.layout_dialog_varient);
// dialog.setCanceledOnTouchOutside(false);
// TextView txt = dialog.findViewById(R.id.txt);
// txt.setText(cc.getName());
// cancl = dialog.findViewById(R.id.cancl);
// recyler_popup = dialog.findViewById(R.id.recyclerVarient);
// recyler_popup.setLayoutManager(new GridLayoutManager(context.getApplicationContext(), 1));
//
// Varient_product(cc.getId());
// cancl.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// dialog.dismiss();
// }
// });
// recyler_popup.addOnItemTouchListener(new RecyclerTouchListener(context, recyler_popup, new RecyclerTouchListener.OnItemClickListener() {
// @Override
// public void onItemClick(View view, int position) {
//
// String mrp = varientProducts.get(position).getVariant_mrp();
// String price = varientProducts.get(position).getVariant_price();
// String vQuan = varientProducts.get(position).getVariant_unit_value();
// Log.d("asdff", cc.getPrice());
//
// cc.setPrice(price);
//
// Log.d("asdff", cc.getPrice());
// holder.pMrp.setText(" " + mrp);
// holder.pPrice.setText(" " + price);
// holder.pQuan.setText(varientProducts.get(position).getVariant_unit());
//// holder.txtQuan.setText(varientProducts.get(position).getVariant_unit());
// holder.txt_unitvalue.setText(varientProducts.get(position).getVariant_unit_value());
//
// cc.setVarient_image(varientProducts.get(position).getVarient_imqge());
// Glide.with(context)
// .load(IMG_URL + varientProducts.get(position).getVarient_imqge())
// .centerCrop()
// .crossFade()
// .diskCacheStrategy(DiskCacheStrategy.ALL)
// .dontAnimate()
// .into(holder.image);
// dialog.dismiss();
//
// }
//
// @Override
// public void onLongItemClick(View view, int position) {
//
// }
// }));
//
//
// dialog.show();
}
});
holder.plus.setOnClickListener(v -> {
holder.btn_Add.setVisibility(View.GONE);
holder.ll_addQuan.setVisibility(View.VISIBLE);
int i = Integer.parseInt(cc.getQuantity());
CategoryGridList.get(position).setQuantity(String.valueOf(i+1));
holder.txtQuan.setText(""+(i+1));
holder.pPrice.setText(""+(price*(i+1)));
holder.pMrp.setText(""+(mrp*(i+1)) );
updateMultiply(position);
// notifyItemChanged(position);
});
holder.minus.setOnClickListener(v -> {
int i = Integer.parseInt(cc.getQuantity());
CategoryGridList.get(position).setQuantity(String.valueOf(i-1));
holder.txtQuan.setText(""+(i-1));
holder.pPrice.setText(""+(price*(i-1)));
holder.pMrp.setText(""+(mrp*(i-1)) );
if ((i-1)<0||(i-1)==0){
holder.btn_Add.setVisibility(View.VISIBLE);
holder.ll_addQuan.setVisibility(View.GONE);
}
updateMultiply(position);
});
holder.btn_Add.setOnClickListener(v -> {
holder.btn_Add.setVisibility(View.GONE);
holder.ll_addQuan.setVisibility(View.VISIBLE);
CategoryGridList.get(position).setQuantity("1");
holder.txtQuan.setText("1");
updateMultiply(position);
});
}
private void updateMultiply(int pos) {
HashMap<String, String> map = new HashMap<>();
// map.put("varient_id",cartList.get(position).getpId());
map.put("varient_id",CategoryGridList.get(pos).getVarient_id());
map.put("product_name",CategoryGridList.get(pos).getName());
map.put("category_id",CategoryGridList.get(pos).getId());
map.put("title",CategoryGridList.get(pos).getDescription());
map.put("price",CategoryGridList.get(pos).getPrice());
map.put("mrp",CategoryGridList.get(pos).getMrp());
// Log.d("fd",CategoryGridList.get(pos).getImage());
map.put("product_image",CategoryGridList.get(pos).getImage());
map.put("status","0");
map.put("in_stock","");
map.put("unit_value","");
map.put("unit",CategoryGridList.get(pos).getUnit());
map.put("increament","0");
map.put("rewards","0");
map.put("stock","0");
map.put("product_description","0");
// Log.d("fgh",cartList.get(position).getUnit()+cartList.get(position).getpQuan());
// Log.d("fghfgh",cartList.get(position).getpPrice());
if (!CategoryGridList.get(pos).getQuantity().equalsIgnoreCase("0")) {
if (dbcart.isInCart(map.get("varient_id"))) {
dbcart.setCart(map, Integer.parseInt(CategoryGridList.get(pos).getQuantity()));
} else {
dbcart.setCart(map, Integer.parseInt(CategoryGridList.get(pos).getQuantity()));
}
} else {
dbcart.removeItemFromCart(map.get("varient_id"));
}
try {
// int items = (int) Double.parseDouble(dbcart.getInCartItemQty(map.get("varient_id")));
// double price = Double.parseDouble(Objects.requireNonNull(map.get("price")).trim());
// double mrp = Double.parseDouble(Objects.requireNonNull(map.get("mrp")).trim());
// Double reward = Double.parseDouble(map.get("rewards"));
// tv_reward.setText("" + reward * items);
// pDescrptn.setText(""+cartList.get(position).getpDes());
// pPrice.setText("" +price* items);
// txtQuan.setText("" + items);
// pMrp.setText("" + mrp* items );
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
SharedPreferences preferences = context.getSharedPreferences("GOGrocer", Context.MODE_PRIVATE);
preferences.edit().putInt("cardqnty",dbcart.getCartCount()).apply();
}
}catch (IndexOutOfBoundsException e){
Log.d("qwer",e.toString());
}
}
// private void Varient_product(String pId) {
// varientProducts.clear();
// StringRequest stringRequest = new StringRequest(Request.Method.POST, ProductVarient, new Response.Listener<String>() {
// @Override
// public void onResponse(String response) {
// Log.d("Prod detail", response);
// try {
// varientProducts.clear();
// JSONObject jsonObject = new JSONObject(response);
// String status = jsonObject.getString("status");
// if (status.equals("1")) {
// JSONArray jsonArray = jsonObject.getJSONArray("data");
// for (int i = 0; i < jsonArray.length(); i++) {
//
// JSONObject jsonObject1 = jsonArray.getJSONObject(i);
// String product_id = jsonObject1.getString("product_id");
// String varient_id = jsonObject1.getString("varient_id");
// String price = jsonObject1.getString("price");
// String quantity = jsonObject1.getString("quantity");
// String varient_image = jsonObject1.getString("varient_image");
// String mrp = jsonObject1.getString("mrp");
// String unit = jsonObject1.getString("unit");
// String description = jsonObject1.getString("description");
//
//
// // Picasso.get().load(IMG_URL+varient_image).into(pImage);
// //prodMrp.setText(mrp);
//
// varient_product selectCityModel = new varient_product();
// selectCityModel.setVarient_imqge(IMG_URL + varient_image);
// selectCityModel.setVariant_unit_value(unit);
// selectCityModel.setVariant_price(price);
// selectCityModel.setVariant_mrp(mrp);
// selectCityModel.setVariant_unit(quantity);
// selectCityModel.setVariant_id(varient_id);
//
//
// varientProducts.add(selectCityModel);
//
// Adapter_popup selectCityAdapter = new Adapter_popup(varientProducts);
// recyler_popup.setAdapter(selectCityAdapter);
//
//
// }
//
// } else {
// varientProducts.clear();
// //JSONObject resultObj = jsonObject.getJSONObject("results");
//
// }
// } catch (JSONException e) {
// e.printStackTrace();
// }
//
// }
// }, new Response.ErrorListener() {
// @Override
// public void onErrorResponse(VolleyError error) {
//
// }
// }) {
// @Override
// protected Map<String, String> getParams() throws AuthFailureError {
// HashMap<String, String> params = new HashMap<>();
// params.put("product_id", pId);
// Log.d("kj", pId);
// return params;
// }
// };
//
// RequestQueue requestQueue = Volley.newRequestQueue(context);
// requestQueue.getCache().clear();
// requestQueue.add(stringRequest);
// }
@Override
public int getItemCount() {
return CategoryGridList.size();
}
}
|
LocalOrbit/localorb
|
config/initializers/quickbooks.rb
|
OAUTH_CONSUMER_KEY = ENV['QB_CONSUMER_KEY']
OAUTH_CONSUMER_SECRET = ENV['QB_CONSUMER_SECRET']
::QB_OAUTH_CONSUMER = OAuth::Consumer.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, {
:site => "https://oauth.intuit.com",
:request_token_path => "/oauth/v1/get_request_token",
:authorize_url => "https://appcenter.intuit.com/Connect/Begin",
:access_token_path => "/oauth/v1/get_access_token"
})
if Rails.env.test? || Rails.env.development?
Quickbooks.sandbox_mode = true
else
Quickbooks.sandbox_mode = false
end
|
CottonMC/Trion
|
src/main/java/io/github/cottonmc/trion/trigger/ChameleonTrigger.java
|
package io.github.cottonmc.trion.trigger;
import io.github.cottonmc.trion.api.Trigger;
import io.github.cottonmc.trion.api.TriggerItem;
import io.github.cottonmc.trion.api.TrionComponent;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.Hand;
public class ChameleonTrigger implements Trigger {
@Override
public void tick(TrionComponent component) {
PlayerEntity player = (PlayerEntity)component.getEntity();
if (player.world.getTime() % 50 == 0
&& player.getStackInHand(Hand.MAIN_HAND).isEmpty()
&& player.getStackInHand(Hand.OFF_HAND).isEmpty()) {
component.setTrion(component.getTrion() - 1, true);
}
}
@Override
public TriggerItem getItem() {
return TriggerItem.NONE;
}
}
|
FiniteSingularity/aoc-2021
|
21/script2.py
|
<filename>21/script2.py<gh_stars>0
step_outcomes = {
3: 1,
4: 3,
5: 6,
6: 7,
7: 6,
8: 3,
9: 1,
}
def run_game(position, num_rolls_count={}, score=0, num_rolls=1):
for outcome, occurrances in step_outcomes.items():
new_position = 1 + (position + outcome - 1) % 10
new_score = score + new_position
if new_score < 21:
outcome_num_rolls_count = run_game(
new_position, {}, new_score, num_rolls + 1)
for key, item in outcome_num_rolls_count.items():
if key not in num_rolls_count:
num_rolls_count[key] = 0
num_rolls_count[key] += item * occurrances
else:
if num_rolls not in num_rolls_count:
num_rolls_count[num_rolls] = 0
num_rolls_count[num_rolls] += occurrances
return num_rolls_count
def calc_continues(games):
last_continue = 1
for i in range(1, max(games.keys())+1):
if i not in games:
games[i] = {'wins': 0, 'continues': 0}
else:
games[i] = {'wins': games[i], 'continues': 0}
plays = last_continue * 27
games[i]['continues'] = plays - games[i]['wins']
last_continue = games[i]['continues']
return games
players = []
with open('./input', encoding='utf8') as file:
for line in file.readlines():
players.append({
'position': int(line.strip().split(': ')[1]),
'score': 0
})
res_1 = run_game(players[0]['position'], {})
res_2 = run_game(players[1]['position'], {})
res_1 = calc_continues(res_1)
res_2 = calc_continues(res_2)
p1_wins = 0
p2_wins = 0
for key, val in res_1.items():
if val['wins'] > 0:
p1_wins += val['wins'] * res_2[key-1]['continues']
for key, val in res_2.items():
if val['wins'] > 0:
p2_wins += val['wins'] * res_1[key]['continues']
print(p1_wins)
print(p2_wins)
|
mp4nguyen/OnlineBookingApp
|
js/components/my-bookings/Item.js
|
<reponame>mp4nguyen/OnlineBookingApp
import React, { Component, PropTypes } from 'react';
import { Image, View, Platform, TouchableOpacity } from 'react-native';
import R from 'ramda';
import { Container, Content, Text, Icon, Item, Input } from 'native-base';
import { Grid, Col } from 'react-native-easy-grid';
import moment from 'moment';
import styles from './styles';
const ApptItem = ({ appt, onPress, showAddress }) => {
const { apptTime, address, clinicName, doctorName } = appt;
return (
<View>
<View style={styles.timelineView}>
<View style={styles.timelineContent}>
<Text />
</View>
</View>
<View style={styles.contentContainer}>
<TouchableOpacity onPress={() => onPress(appt)}>
<Grid>
<Col style={{ flexDirection: 'row' }}>
<Icon name="ios-time-outline" style={styles.timelineIcon} />
<View style={{ paddingLeft: 10 }}>
<Text style={styles.timeText}>{moment(apptTime).format('h:mm a')}</Text>
<Text style={styles.timeText}>{moment(apptTime).format('ddd, MMM D, YYYY')}</Text>
</View>
</Col>
<Col style={{ alignItems: 'flex-end' }}>
<Text style={styles.timelineTextHeader}>{clinicName}</Text>
<Text style={styles.time}>{doctorName}</Text>
</Col>
</Grid>
{showAddress && <Text style={styles.addressText}>{address}</Text>}
</TouchableOpacity>
</View>
</View>
);
};
ApptItem.propTypes = {
appt: PropTypes.object,
onPress: PropTypes.func,
showAddress: PropTypes.bool,
};
export default ApptItem;
|
camelcc/leetcode
|
src/S0125ValidPalindrome.java
|
public class S0125ValidPalindrome {
public boolean isPalindrome(String s) {
int lo = 0, hi = s.length()-1;
while (lo < hi) {
char lc = s.charAt(lo);
if ((lc >= 'a' && lc <= 'z') || (lc >= '0' && lc <= '9') || (lc >= 'A' && lc <= 'Z')) {
if (lc >= 'A' && lc <= 'Z') {
lc = (char)(lc-'A'+'a');
}
} else {
lo++;
continue;
}
char hc = s.charAt(hi);
if ((hc >= 'a' && hc <= 'z') || (hc >= '0' && hc <= '9') || (hc >= 'A' && hc <= 'Z')) {
if (hc >= 'A' && hc <= 'Z') {
hc = (char)(hc-'A'+'a');
}
} else {
hi--;
continue;
}
if (lc != hc) {
return false;
}
lo++;
hi--;
}
return true;
}
}
|
owlas/magpy
|
test/convergence/task5.cpp
|
<reponame>owlas/magpy
/////////////////////////////////////////
// CONVERGENCE TESTS //
// //
// TASK 5 //
// Stochastic LLG (Heun vs. implicit) //
// Single particle, applied field only //
/////////////////////////////////////////
#include "../../include/integrators.hpp"
#include "../../include/rng.hpp"
#include "../../include/io.hpp"
#include "../../include/llg.hpp"
#include "../../include/field.hpp"
#include "../../include/constants.hpp"
#include <functional>
#include <cmath>
#include <stdio.h>
#include <iostream>
void task5()
{
// aout bout j_a j_b x_in t_a t_b
using sde_jac = std::function<void(double*,double*,double*,double*,const double*,const double,const double)>;
// drift diff state t
using sde = std::function<void(double*,double*,const double*,const double)>;
///////////////////////////////////////
// LAUNDAU-LIFSHITZ-GILBERT EQUATION //
///////////////////////////////////////
// LLG parameters
double H=0.01;
double alpha=0.1; double alpha_arr[1] = {alpha};
double thermal_strength=0.01; double thermal_strength_arr[1] = {thermal_strength};
size_t n_particles=1;
double *heff = new double[3]; // allocate work arrays
double *jeff = new double[9]; // allocate work arrays
// Define the effective field (constant in z_direction [index 2])
std::function<double(const double)> happ = [H](const double) {return H;};
std::function<void(double*,const double*,const double)> heff_func =
[happ](double *out, const double*, const double t)
{
field::zero_all_field_terms( out, 3 );
field::multi_add_applied_Z_field_function( out, happ, t, 1 );
};
std::function<void(double*, const double*, const double)> heff_jac =
[](double *out, const double*, const double)
{
field::zero_all_field_terms( out, 9 );
};
// Define the SDE representing the LLG
sde_jac llg_sde_jac = [heff_func, heff_jac, heff, jeff,
n_particles, alpha_arr, thermal_strength_arr]
(double *drift, double *diffusion, double *jdrift, double *jdiffusion,
const double *state, const double a_t, const double )
{
llg::multi_stochastic_llg_jacobians_field_update(
drift, diffusion,
jdrift, jdiffusion,
heff, jeff,
state,
a_t,
alpha_arr,
thermal_strength_arr,
n_particles,
heff_func,
heff_jac );
};
// Very inefficient hack for Heun scheme (need to change interface)
std::function<void(double*,double*,const double*,const double)> llg_sde =
[llg_sde_jac] (double *drift, double*diffusion,
const double*state, const double time)
{
double jdrift[9];
double jdiffusion[27];
llg_sde_jac( drift, diffusion, jdrift, jdiffusion, state, time, time );
};
// Initial condition
double m0[3] = {1.0, 0.0, 0.0};
double t0 = 0.0;
// STEP SIZE
size_t n_steps=6400;
double dt = 1e-2;
size_t n_dt=7;
int dt_multipliers[7] = {1, 2, 4, 8, 16, 32, 64};
size_t dt_mult;
double dts[7];
for( unsigned int i=0; i<n_dt; i++ )
dts[i] = dt * dt_multipliers[i];
io::write_array( "output/task5/dt", dts, n_dt );
// RANDOM NUMBER GENERATOR
size_t n_runs = 5000;
long *seeds = new long[n_runs];
for ( size_t i=0; i<n_runs; i++ )
seeds[i] = i*13*( i%5 ); // allocate some seeds
RngMtNorm rng( 1001, std::sqrt(dt) ); // preallocate, seed is changed later
double *dw;
// IMPLICIT SCHEME PARAMS
double eps = 1e-9;
double max_iter = 100;
size_t n_dim=3;
size_t w_dim=3;
// ALLOCATE MEM FOR RESULTS
// store final state for each run for each dt
double *implicit_errs = new double[n_runs*3];
double *heun_errs = new double[n_runs*3];
double *x = new double[3*(n_steps+1)]; // +1 for the initial condition
char fname[100];
// SIMULATE
std::cout << std::endl;
std::cout << "Executing task 5..." << std::endl;
for( unsigned int i=0; i<n_dt; i++ )
{
std::cout << "Simulating dt " << i << " of " << n_dt << std::endl;
std::cout << "----------" << std::endl;
dt_mult = dt_multipliers[i];
dw = new double[3*n_steps/dt_mult];
// Do multiple runs
for( unsigned int run=0; run<n_runs; run++ )
{
if( (run%100) == 0)
std::cout << "Simulating run " << run << " of " << n_runs << std::endl;
// Set up 3-dimensional Wiener process
rng = RngMtNorm(seeds[run], 1.0/std::sqrt((double) dt_mult) );
for( size_t n=0; n<n_steps/dt_mult; n++ )
{
for( size_t i=0; i<3; i++ )
dw[n*3 + i] = 0.0;
for( unsigned int i=0; i<dt_mult; i++)
for( size_t j=0; j<3; j++ )
dw[n*3 + j] += rng.get();
}
// IMPLICIT MIDPOINT
driver::implicit_midpoint( x, m0, dw, llg_sde_jac, n_dim, w_dim,
n_steps/dt_mult, t0, dt*dt_mult, eps, max_iter );
implicit_errs[run*3 + 0] = x[n_steps/dt_mult*3 + 0];
implicit_errs[run*3 + 1] = x[n_steps/dt_mult*3 + 1];
implicit_errs[run*3 + 2] = x[n_steps/dt_mult*3 + 2];
if( (i==0) && (run==0) )
io::write_array( "output/task5/example_sol", x, 3*(n_steps+1));
// HEUN SCHEME
driver::heun( x, m0, dw, llg_sde, n_steps/dt_mult,
n_dim, w_dim, dt*dt_mult );
heun_errs[run*3 + 0] = x[n_steps/dt_mult*3 + 0];
heun_errs[run*3 + 1] = x[n_steps/dt_mult*3 + 1];
heun_errs[run*3 + 2] = x[n_steps/dt_mult*3 + 2];
}
sprintf( fname, "output/task5/implicit%d", i );
io::write_array( fname, implicit_errs, n_runs*3);
sprintf( fname, "output/task5/heun%d", i );
io::write_array( fname, heun_errs, n_runs*3);
delete[] dw;
}
delete[] x; delete[] heff; delete[] jeff; delete[] seeds;
delete[] implicit_errs; delete[] heun_errs;
}
|
zstared/oa
|
src/config/dev.js
|
<gh_stars>1-10
const config={
origin:'https://localhost:8081',
/**监听端口 */
port:8081,
/**数据库连接配置 */
mysql_host: '192.168.3.11',
mysql_port:3306,
mysql_db: 'mes',
mysql_userid: 'root',
mysql_password: '<PASSWORD>',
/**redis连接配置 */
redis_host: '192.168.3.11',
redis_port: 6379,
redis_password: '<PASSWORD>',
redis_session_db: 1,
};
export default config;
|
dranawhite/study-java
|
study-framework/study-springboot/src/main/java/com/dranawhite/study/springboot/transaction/UserService.java
|
<filename>study-framework/study-springboot/src/main/java/com/dranawhite/study/springboot/transaction/UserService.java
package com.dranawhite.study.springboot.transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
/**
* @author dranawhite
* @version : UserService.java, v 0.1 2019-09-10 16:11 dranawhite Exp $$
*/
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional(rollbackFor = Exception.class)
public void insert() throws IOException {
String sql = "insert into t_user (name, address, phone) values ('jerry', 'queen street', '18976452354')";
jdbcTemplate.execute(sql);
if (1 == 1) {
throw new IOException();
}
jdbcTemplate.execute(sql);
}
}
|
lemkova/Yorozuya
|
YorozuyaGSLib/source/_qry_case_post_storage_list_getDetail.cpp
|
#include <_qry_case_post_storage_list_getDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Detail
{
Info::_qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_ptr _qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_next(nullptr);
Info::_qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_clbk _qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_user(nullptr);
Info::_qry_case_post_storage_list_getsize4_ptr _qry_case_post_storage_list_getsize4_next(nullptr);
Info::_qry_case_post_storage_list_getsize4_clbk _qry_case_post_storage_list_getsize4_user(nullptr);
void _qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_wrapper(struct _qry_case_post_storage_list_get* _this)
{
_qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_user(_this, _qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_next);
};
int _qry_case_post_storage_list_getsize4_wrapper(struct _qry_case_post_storage_list_get* _this)
{
return _qry_case_post_storage_list_getsize4_user(_this, _qry_case_post_storage_list_getsize4_next);
};
::std::array<hook_record, 2> _qry_case_post_storage_list_get_functions =
{
_hook_record {
(LPVOID)0x1400ca650L,
(LPVOID *)&_qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_user,
(LPVOID *)&_qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_next,
(LPVOID)cast_pointer_function(_qry_case_post_storage_list_getctor__qry_case_post_storage_list_get2_wrapper),
(LPVOID)cast_pointer_function((void(_qry_case_post_storage_list_get::*)())&_qry_case_post_storage_list_get::ctor__qry_case_post_storage_list_get)
},
_hook_record {
(LPVOID)0x1400ca6d0L,
(LPVOID *)&_qry_case_post_storage_list_getsize4_user,
(LPVOID *)&_qry_case_post_storage_list_getsize4_next,
(LPVOID)cast_pointer_function(_qry_case_post_storage_list_getsize4_wrapper),
(LPVOID)cast_pointer_function((int(_qry_case_post_storage_list_get::*)())&_qry_case_post_storage_list_get::size)
},
};
}; // end namespace Detail
END_ATF_NAMESPACE
|
changhugo/decrediton
|
app/components/indicators/NoProposals.js
|
import { FormattedMessage as T } from "react-intl";
export default () => (
<div className="no-proposals-indicator">
<T id="noProposals.description" m="No Proposals Available" />
</div>
);
|
johnlemon93/blog-page
|
src/components/layout/Footer/index.js
|
import React, { Component } from 'react';
class Footer extends Component {
render() {
return (
<footer>
<a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="Creative Commons License" src="https://i.creativecommons.org/l/by-nc-nd/4.0/80x15.png" /></a>
<p>Created with <a href="https://github.com/johnlemon93/blog-page-ssr">Blog Page SSR</a></p>
<div className="social">
<a target="_blank" rel="noopener noreferrer" href="https://www.facebook.com/blogchanhday"><i className="icon-facebook-squared"></i></a>
<a target="_blank" rel="noopener noreferrer" href="https://github.com/johnlemon93"><i className="icon-github-squared"></i></a>
<a target="_blank" rel="noopener noreferrer" href="https://blogchanhday.com"><i className="icon-emo-coffee"></i></a>
</div>
</footer>
);
}
}
export default Footer;
|
paulondc/mebo
|
data/docs/tweaks.js
|
<gh_stars>0
// converts the node style specifics to es6 style (this is only
// used to process the documentation)
const requiredToken = '__import_module__';
exports.onHandleCode = (ev) => {
ev.data.code = ev.data.code
.replace(/module\.exports = /g, 'export default ')
.replace(/const (.*)require\((.*)\)/g, `const ${requiredToken}$1require($2)`)
.replace(/\\\n../g, '');
};
// Customize HTML texting/formating
exports.onHandleHTML = (ev) => {
ev.data.html = ev.data.html
.replace('<header>', '<header><a href="./index.html"><img src="data/icon.png?v=1" id="meboSmallLogo" width="40" height="40" align="top"/></a>')
.replace('>Repository</a>', '>Mebo GitHub</a>')
.replace(/#http#:\//g, `http:/`)
.replace(new RegExp('https://mebohq.github.io/docs/data/', 'g'), 'data/')
.replace('Mebo API Document', 'Mebo')
.replace('<img src="data/logo.png">', '<p align="center"><img src="data/logo.png"></p>')
.replace('<img src="data/meboHi.png">', '<p align="center"><img src="data/meboHi.png"></p>')
.replace('<img src="./image/search.png">', '<img src="data/docs/search.png">')
.replace('<a href="identifiers.html">Reference</a>', '')
.replace('data-ice="manualHeaderLink">Manual</a>', 'data-ice="manualHeaderLink">Intro</a>')
.replace('./manual/index.html', './manual/overview/INTRODUCTION.html')
.replace('"data/manual/INTRODUCTION.md"', '"manual/overview/INTRODUCTION.html"')
.replace(new RegExp(requiredToken, 'g'), '')
.replace(new RegExp('<li data-ice="manualNav" class="indent-h4"', 'g'), '<li data-ice="manualNav" class="indent-h3"')
.replace(new RegExp('::none::', 'g'), '<img src="data/docs/value/none.png" title="none">')
.replace(new RegExp('::null::', 'g'), '<img src="data/docs/value/null.png" title="null">')
.replace(new RegExp('::true::', 'g'), '<img src="data/docs/value/true.png" title="true">')
.replace(new RegExp('::false::', 'g'), '<img src="data/docs/value/false.png" title="false">')
.replace(new RegExp('::auto::', 'g'), '<img src="data/docs/value/auto.png" title="auto">')
.replace(new RegExp('::on::', 'g'), '<img src="data/docs/toggle/on.png" title="yes">')
.replace(new RegExp('::off::', 'g'), '<img src="data/docs/toggle/off.png" title="no">')
// adding the star button to the README displayed in the index page
if (ev.data.html.indexOf(' alt="Esdocs"></a>' !== -1)){
ev.data.html = ev.data.html
.replace('</head>', '<link rel="icon" type="image/png" sizes="64x64" href="data/icon.png?v=1"><script async defer src="https://buttons.github.io/buttons.js"></script></head>')
.replace(' alt="Esdocs"></a>', ' alt=Esdocs"></a> <a class="github-button" href="https://github.com/meboHQ/mebo" data-icon="octicon-star" data-style="mega" data-count-href="/meboHQ/mebo/stargazers" data-count-api="/repos/meboHQ/mebo#stargazers_count" data-count-aria-label="# stargazers on GitHub" aria-label="Star Mebo on GitHub">Star</a>');
}
// replacing the domain that is hard coded in the INTRODUCTION to the relative doc location
if (ev.data.html.indexOf('<div data-ice="manual" data-toc-name="overview">') !== -1){
ev.data.html = ev.data.html
.replace(new RegExp('https://mebohq.github.io/docs/', 'g'), '');
ev.data.html = ev.data.html.replace('indent-h1 manual-color manual-color-reference', 'indent-h1');
}
// removing the public column from the class summary
if (ev.data.html.indexOf('<title data-ice="title">Index | Mebo</title>') !== -1){
ev.data.html = ev.data.html
.replace(new RegExp('<td>\n <span class="access" data-ice="access">public</span>', 'g'), '<td style="display:none">')
.replace(new RegExp('<td data-ice="title" colspan="3">Static Public Class Summary</td>', 'g'), '');
}
};
|
lechium/iPhoneOS_12.1.1_Headers
|
System/Library/PrivateFrameworks/OfficeImport.framework/OAXTextBody.h
|
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, June 1, 2019 at 6:51:41 PM Mountain Standard Time
* Operating System: Version 12.1.1 (Build 16C5050a)
* Image Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <OfficeImport/OfficeImport-Structs.h>
@interface OAXTextBody : NSObject
+(unsigned char)readFlowType:(id)arg1 ;
+(unsigned char)readAnchorType:(id)arg1 ;
+(unsigned char)readHorizontalOverflowType:(id)arg1 ;
+(void)readTextBodyFromXmlNode:(xmlNode*)arg1 textBody:(id)arg2 drawingState:(id)arg3 ;
+(void)readTextBodyProperties:(xmlNode*)arg1 textBodyProperties:(id)arg2 drawingState:(id)arg3 ;
+(void)readFlowType:(id)arg1 textBodyProperties:(id)arg2 ;
+(void)readWrapType:(id)arg1 textBodyProperties:(id)arg2 ;
+(void)readVerticalOverflowType:(id)arg1 textBodyProperties:(id)arg2 ;
+(void)readHorizontalOverflowType:(id)arg1 textBodyProperties:(id)arg2 ;
+(id)stringWithTextBodyVerticalOverflowType:(unsigned char)arg1 ;
+(id)stringWithTextBodyHorizontalOverflowType:(unsigned char)arg1 ;
+(id)stringWithTextBodyFlowType:(unsigned char)arg1 ;
+(id)stringWithTextBodyWrapType:(unsigned char)arg1 ;
+(id)stringWithTextAnchorType:(unsigned char)arg1 ;
+(void)writeTextBodyAutoFit:(id)arg1 to:(id)arg2 ;
@end
|
shayff/SmartShifter
|
server/ShiftManagerService/create_shift.py
|
<filename>server/ShiftManagerService/create_shift.py
from server.ShiftManagerService import db
from flask import jsonify
from flask_jwt_extended import get_jwt_identity
from server.ShiftManagerService.schemas.create_shift import validate_create_shift
def create_shift(user_input):
data = validate_create_shift(user_input)
if data["ok"]:
new_shift = data["data"]
logged_in_user = get_jwt_identity()
user_from_db = db.get_user(logged_in_user["_id"])
# check if user has company
if "company" in user_from_db:
company_id = user_from_db["company"]
# update id shift
shift_id = db.inc_shifts_counter(company_id)
new_shift.update({"id": shift_id})
# add shift status
if "status" not in new_shift:
new_shift.update({"status": "not_scheduled"})
# insert to db
db.insert_shift(company_id, new_shift)
print(new_shift)
return jsonify({"ok": True, "msg": 'Update Company successfully'}), 200
else:
return jsonify({"ok": False, "msg": 'User has no company'}), 401
else:
return jsonify({"ok": False, "msg": 'Bad request parameters: {}'.format(data["msg"])}), 400
|
luongnvUIT/prowide-iso20022
|
model-caaa-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/AcceptorAuthorisationResponseV04.java
|
package com.prowidesoftware.swift.model.mx.dic;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* The AcceptorAuthorisationResponse message is sent by the acquirer (or its agent) to an acceptor (or its agent), to return the result of the validation made by issuer about the payment transaction.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AcceptorAuthorisationResponseV04", propOrder = {
"hdr",
"authstnRspn",
"sctyTrlr"
})
public class AcceptorAuthorisationResponseV04 {
@XmlElement(name = "Hdr", required = true)
protected Header10 hdr;
@XmlElement(name = "AuthstnRspn", required = true)
protected AcceptorAuthorisationResponse4 authstnRspn;
@XmlElement(name = "SctyTrlr", required = true)
protected ContentInformationType11 sctyTrlr;
/**
* Gets the value of the hdr property.
*
* @return
* possible object is
* {@link Header10 }
*
*/
public Header10 getHdr() {
return hdr;
}
/**
* Sets the value of the hdr property.
*
* @param value
* allowed object is
* {@link Header10 }
*
*/
public AcceptorAuthorisationResponseV04 setHdr(Header10 value) {
this.hdr = value;
return this;
}
/**
* Gets the value of the authstnRspn property.
*
* @return
* possible object is
* {@link AcceptorAuthorisationResponse4 }
*
*/
public AcceptorAuthorisationResponse4 getAuthstnRspn() {
return authstnRspn;
}
/**
* Sets the value of the authstnRspn property.
*
* @param value
* allowed object is
* {@link AcceptorAuthorisationResponse4 }
*
*/
public AcceptorAuthorisationResponseV04 setAuthstnRspn(AcceptorAuthorisationResponse4 value) {
this.authstnRspn = value;
return this;
}
/**
* Gets the value of the sctyTrlr property.
*
* @return
* possible object is
* {@link ContentInformationType11 }
*
*/
public ContentInformationType11 getSctyTrlr() {
return sctyTrlr;
}
/**
* Sets the value of the sctyTrlr property.
*
* @param value
* allowed object is
* {@link ContentInformationType11 }
*
*/
public AcceptorAuthorisationResponseV04 setSctyTrlr(ContentInformationType11 value) {
this.sctyTrlr = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
trebol-ecommerce/spring-boot-backend
|
src/main/java/org/trebol/security/services/ClaimsAuthorizationHeaderParserServiceImpl.java
|
/*
* Copyright (c) 2022 The Trebol eCommerce Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.trebol.security.services;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.trebol.security.IAuthorizationHeaderParserService;
import javax.crypto.SecretKey;
@Service
public class ClaimsAuthorizationHeaderParserServiceImpl
implements IAuthorizationHeaderParserService<Claims> {
private final SecretKey secretKey;
@Autowired
public ClaimsAuthorizationHeaderParserServiceImpl(SecretKey secretKey) {
this.secretKey = secretKey;
}
@Override
public Claims parseToken(String token) throws IllegalStateException {
try {
Jws<Claims> claimsJws = Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token);
return claimsJws.getBody();
} catch (JwtException e) {
throw new IllegalStateException(String.format("Token %s can't be trusted", token));
}
}
@Nullable
@Override
public String extractAuthorizationHeader(HttpHeaders httpHeaders) {
String authHeaderKey = HttpHeaders.AUTHORIZATION;
return httpHeaders.containsKey(authHeaderKey) ? httpHeaders.getFirst(authHeaderKey) : null;
}
}
|
zreren/helath-welcome
|
node_modules/ant-design-vue/es/vc-tree/src/TreeNode.js
|
<filename>node_modules/ant-design-vue/es/vc-tree/src/TreeNode.js
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _typeof from "@babel/runtime/helpers/esm/typeof";
import _extends from "@babel/runtime/helpers/esm/extends";
import { createVNode as _createVNode } from "vue";
import { defineComponent, inject, provide } from 'vue';
import PropTypes from '../../_util/vue-types';
import classNames from '../../_util/classNames';
import { getNodeChildren as _getNodeChildren, mapChildren, warnOnlyTreeNode, getDataAndAria } from './util';
import { initDefaultProps, getComponent, getSlot } from '../../_util/props-util';
import BaseMixin from '../../_util/BaseMixin';
import { getTransitionProps, Transition } from '../../_util/transition';
function noop() {}
var ICON_OPEN = 'open';
var ICON_CLOSE = 'close';
var defaultTitle = '---';
var TreeNode = defineComponent({
name: 'TreeNode',
mixins: [BaseMixin],
inheritAttrs: false,
__ANT_TREE_NODE: true,
props: initDefaultProps({
eventKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
prefixCls: PropTypes.string,
// className: PropTypes.string,
root: PropTypes.object,
// onSelect: PropTypes.func,
// By parent
expanded: PropTypes.looseBool,
selected: PropTypes.looseBool,
checked: PropTypes.looseBool,
loaded: PropTypes.looseBool,
loading: PropTypes.looseBool,
halfChecked: PropTypes.looseBool,
title: PropTypes.any,
pos: PropTypes.string,
dragOver: PropTypes.looseBool,
dragOverGapTop: PropTypes.looseBool,
dragOverGapBottom: PropTypes.looseBool,
// By user
isLeaf: PropTypes.looseBool,
checkable: PropTypes.looseBool,
selectable: PropTypes.looseBool,
disabled: PropTypes.looseBool,
disableCheckbox: PropTypes.looseBool,
icon: PropTypes.any,
dataRef: PropTypes.object,
switcherIcon: PropTypes.any,
label: PropTypes.any,
value: PropTypes.any
}, {}),
setup: function setup() {
return {
vcTree: inject('vcTree', {}),
vcTreeNode: inject('vcTreeNode', {})
};
},
data: function data() {
this.children = null;
return {
dragNodeHighlight: false
};
},
created: function created() {
provide('vcTreeNode', this);
},
// Isomorphic needn't load data in server side
mounted: function mounted() {
var eventKey = this.eventKey,
registerTreeNode = this.vcTree.registerTreeNode;
this.syncLoadData(this.$props);
registerTreeNode && registerTreeNode(eventKey, this);
},
updated: function updated() {
this.syncLoadData(this.$props);
},
beforeUnmount: function beforeUnmount() {
var eventKey = this.eventKey,
registerTreeNode = this.vcTree.registerTreeNode;
registerTreeNode && registerTreeNode(eventKey, null);
},
methods: {
onSelectorClick: function onSelectorClick(e) {
// Click trigger before select/check operation
var onNodeClick = this.vcTree.onNodeClick;
onNodeClick(e, this);
if (this.isSelectable()) {
this.onSelect(e);
} else {
this.onCheck(e);
}
},
onSelectorDoubleClick: function onSelectorDoubleClick(e) {
var onNodeDoubleClick = this.vcTree.onNodeDoubleClick;
onNodeDoubleClick(e, this);
},
onSelect: function onSelect(e) {
if (this.isDisabled()) return;
var onNodeSelect = this.vcTree.onNodeSelect;
e.preventDefault();
onNodeSelect(e, this);
},
onCheck: function onCheck(e) {
if (this.isDisabled()) return;
var disableCheckbox = this.disableCheckbox,
checked = this.checked;
var onNodeCheck = this.vcTree.onNodeCheck;
if (!this.isCheckable() || disableCheckbox) return;
e.preventDefault();
var targetChecked = !checked;
onNodeCheck(e, this, targetChecked);
},
onMouseEnter: function onMouseEnter(e) {
var onNodeMouseEnter = this.vcTree.onNodeMouseEnter;
onNodeMouseEnter(e, this);
},
onMouseLeave: function onMouseLeave(e) {
var onNodeMouseLeave = this.vcTree.onNodeMouseLeave;
onNodeMouseLeave(e, this);
},
onContextMenu: function onContextMenu(e) {
var onNodeContextMenu = this.vcTree.onNodeContextMenu;
onNodeContextMenu(e, this);
},
onDragStart: function onDragStart(e) {
var onNodeDragStart = this.vcTree.onNodeDragStart;
e.stopPropagation();
this.setState({
dragNodeHighlight: true
});
onNodeDragStart(e, this);
try {
// ie throw error
// firefox-need-it
e.dataTransfer.setData('text/plain', '');
} catch (error) {// empty
}
},
onDragEnter: function onDragEnter(e) {
var onNodeDragEnter = this.vcTree.onNodeDragEnter;
e.preventDefault();
e.stopPropagation();
onNodeDragEnter(e, this);
},
onDragOver: function onDragOver(e) {
var onNodeDragOver = this.vcTree.onNodeDragOver;
e.preventDefault();
e.stopPropagation();
onNodeDragOver(e, this);
},
onDragLeave: function onDragLeave(e) {
var onNodeDragLeave = this.vcTree.onNodeDragLeave;
e.stopPropagation();
onNodeDragLeave(e, this);
},
onDragEnd: function onDragEnd(e) {
var onNodeDragEnd = this.vcTree.onNodeDragEnd;
e.stopPropagation();
this.setState({
dragNodeHighlight: false
});
onNodeDragEnd(e, this);
},
onDrop: function onDrop(e) {
var onNodeDrop = this.vcTree.onNodeDrop;
e.preventDefault();
e.stopPropagation();
this.setState({
dragNodeHighlight: false
});
onNodeDrop(e, this);
},
// Disabled item still can be switch
onExpand: function onExpand(e) {
var onNodeExpand = this.vcTree.onNodeExpand;
onNodeExpand(e, this);
},
// Drag usage
setSelectHandle: function setSelectHandle(node) {
this.selectHandle = node;
},
getNodeChildren: function getNodeChildren() {
var originList = this.children;
var targetList = _getNodeChildren(originList);
if (originList.length !== targetList.length) {
warnOnlyTreeNode();
}
return targetList;
},
getNodeState: function getNodeState() {
var expanded = this.expanded;
if (this.isLeaf2()) {
return null;
}
return expanded ? ICON_OPEN : ICON_CLOSE;
},
isLeaf2: function isLeaf2() {
var isLeaf = this.isLeaf,
loaded = this.loaded;
var loadData = this.vcTree.loadData;
var hasChildren = this.getNodeChildren().length !== 0;
if (isLeaf === false) {
return false;
}
return isLeaf || !loadData && !hasChildren || loadData && loaded && !hasChildren;
},
isDisabled: function isDisabled() {
var disabled = this.disabled;
var treeDisabled = this.vcTree.disabled; // Follow the logic of Selectable
if (disabled === false) {
return false;
}
return !!(treeDisabled || disabled);
},
isCheckable: function isCheckable() {
var checkable = this.$props.checkable;
var treeCheckable = this.vcTree.checkable; // Return false if tree or treeNode is not checkable
if (!treeCheckable || checkable === false) return false;
return treeCheckable;
},
// Load data to avoid default expanded tree without data
syncLoadData: function syncLoadData(props) {
var expanded = props.expanded,
loading = props.loading,
loaded = props.loaded;
var _this$vcTree = this.vcTree,
loadData = _this$vcTree.loadData,
onNodeLoad = _this$vcTree.onNodeLoad;
if (loading) return; // read from state to avoid loadData at same time
if (loadData && expanded && !this.isLeaf2()) {
// We needn't reload data when has children in sync logic
// It's only needed in node expanded
var hasChildren = this.getNodeChildren().length !== 0;
if (!hasChildren && !loaded) {
onNodeLoad(this);
}
}
},
isSelectable: function isSelectable() {
var selectable = this.selectable;
var treeSelectable = this.vcTree.selectable; // Ignore when selectable is undefined or null
if (typeof selectable === 'boolean') {
return selectable;
}
return treeSelectable;
},
// Switcher
renderSwitcher: function renderSwitcher() {
var expanded = this.expanded;
var prefixCls = this.vcTree.prefixCls;
var switcherIcon = getComponent(this, 'switcherIcon', {}, false) || getComponent(this.vcTree, 'switcherIcon', {}, false);
if (this.isLeaf2()) {
return _createVNode("span", {
"key": "switcher",
"class": classNames("".concat(prefixCls, "-switcher"), "".concat(prefixCls, "-switcher-noop"))
}, [typeof switcherIcon === 'function' ? switcherIcon(_extends(_extends(_extends({}, this.$props), this.$props.dataRef), {
isLeaf: true
})) : switcherIcon]);
}
var switcherCls = classNames("".concat(prefixCls, "-switcher"), "".concat(prefixCls, "-switcher_").concat(expanded ? ICON_OPEN : ICON_CLOSE));
return _createVNode("span", {
"key": "switcher",
"onClick": this.onExpand,
"class": switcherCls
}, [typeof switcherIcon === 'function' ? switcherIcon(_extends(_extends(_extends({}, this.$props), this.$props.dataRef), {
isLeaf: false
})) : switcherIcon]);
},
// Checkbox
renderCheckbox: function renderCheckbox() {
var checked = this.checked,
halfChecked = this.halfChecked,
disableCheckbox = this.disableCheckbox;
var prefixCls = this.vcTree.prefixCls;
var disabled = this.isDisabled();
var checkable = this.isCheckable();
if (!checkable) return null; // [Legacy] Custom element should be separate with `checkable` in future
var $custom = typeof checkable !== 'boolean' ? checkable : null;
return _createVNode("span", {
"key": "checkbox",
"class": classNames("".concat(prefixCls, "-checkbox"), checked && "".concat(prefixCls, "-checkbox-checked"), !checked && halfChecked && "".concat(prefixCls, "-checkbox-indeterminate"), (disabled || disableCheckbox) && "".concat(prefixCls, "-checkbox-disabled")),
"onClick": this.onCheck
}, [$custom]);
},
renderIcon: function renderIcon() {
var loading = this.loading;
var prefixCls = this.vcTree.prefixCls;
return _createVNode("span", {
"key": "icon",
"class": classNames("".concat(prefixCls, "-iconEle"), "".concat(prefixCls, "-icon__").concat(this.getNodeState() || 'docu'), loading && "".concat(prefixCls, "-icon_loading"))
}, null);
},
// Icon + Title
renderSelector: function renderSelector() {
var selected = this.selected,
loading = this.loading,
dragNodeHighlight = this.dragNodeHighlight;
var icon = getComponent(this, 'icon', {}, false);
var _this$vcTree2 = this.vcTree,
prefixCls = _this$vcTree2.prefixCls,
showIcon = _this$vcTree2.showIcon,
treeIcon = _this$vcTree2.icon,
draggable = _this$vcTree2.draggable,
loadData = _this$vcTree2.loadData;
var disabled = this.isDisabled();
var title = getComponent(this, 'title', {}, false);
var wrapClass = "".concat(prefixCls, "-node-content-wrapper"); // Icon - Still show loading icon when loading without showIcon
var $icon;
if (showIcon) {
var currentIcon = icon || treeIcon;
$icon = currentIcon ? _createVNode("span", {
"class": classNames("".concat(prefixCls, "-iconEle"), "".concat(prefixCls, "-icon__customize"))
}, [typeof currentIcon === 'function' ? currentIcon(_extends(_extends({}, this.$props), this.$props.dataRef)) : currentIcon]) : this.renderIcon();
} else if (loadData && loading) {
$icon = this.renderIcon();
}
var currentTitle = title;
var $title = currentTitle ? _createVNode("span", {
"class": "".concat(prefixCls, "-title")
}, [typeof currentTitle === 'function' ? currentTitle(_extends(_extends({}, this.$props), this.$props.dataRef)) : currentTitle]) : _createVNode("span", {
"class": "".concat(prefixCls, "-title")
}, [defaultTitle]);
return _createVNode("span", {
"key": "selector",
"ref": this.setSelectHandle,
"title": typeof title === 'string' ? title : '',
"class": classNames("".concat(wrapClass), "".concat(wrapClass, "-").concat(this.getNodeState() || 'normal'), !disabled && (selected || dragNodeHighlight) && "".concat(prefixCls, "-node-selected"), !disabled && draggable && 'draggable'),
"draggable": !disabled && draggable || undefined,
"aria-grabbed": !disabled && draggable || undefined,
"onMouseenter": this.onMouseEnter,
"onMouseleave": this.onMouseLeave,
"onContextmenu": this.onContextMenu,
"onClick": this.onSelectorClick,
"onDblclick": this.onSelectorDoubleClick,
"onDragstart": draggable ? this.onDragStart : noop
}, [$icon, $title]);
},
// Children list wrapped with `Animation`
renderChildren: function renderChildren() {
var expanded = this.expanded,
pos = this.pos;
var _this$vcTree3 = this.vcTree,
prefixCls = _this$vcTree3.prefixCls,
openTransitionName = _this$vcTree3.openTransitionName,
openAnimation = _this$vcTree3.openAnimation,
renderTreeNode = _this$vcTree3.renderTreeNode;
var animProps = {};
if (openTransitionName) {
animProps = getTransitionProps(openTransitionName);
} else if (_typeof(openAnimation) === 'object') {
animProps = _extends(_extends(_extends({}, openAnimation), {
css: false
}), animProps);
} // Children TreeNode
var nodeList = this.getNodeChildren();
if (nodeList.length === 0) {
return null;
}
var $children;
if (expanded) {
$children = _createVNode("ul", {
"class": classNames("".concat(prefixCls, "-child-tree"), expanded && "".concat(prefixCls, "-child-tree-open")),
"data-expanded": expanded,
"role": "group"
}, [mapChildren(nodeList, function (node, index) {
return renderTreeNode(node, index, pos);
})]);
}
return _createVNode(Transition, animProps, {
default: function _default() {
return [$children];
}
});
}
},
render: function render() {
var _ref;
this.children = getSlot(this);
var _this$$props = this.$props,
dragOver = _this$$props.dragOver,
dragOverGapTop = _this$$props.dragOverGapTop,
dragOverGapBottom = _this$$props.dragOverGapBottom,
isLeaf = _this$$props.isLeaf,
expanded = _this$$props.expanded,
selected = _this$$props.selected,
checked = _this$$props.checked,
halfChecked = _this$$props.halfChecked,
loading = _this$$props.loading;
var _this$vcTree4 = this.vcTree,
prefixCls = _this$vcTree4.prefixCls,
filterTreeNode = _this$vcTree4.filterTreeNode,
draggable = _this$vcTree4.draggable;
var disabled = this.isDisabled();
var dataOrAriaAttributeProps = getDataAndAria(_extends(_extends({}, this.$props), this.$attrs));
var _this$$attrs = this.$attrs,
className = _this$$attrs.class,
style = _this$$attrs.style;
return _createVNode("li", _objectSpread({
"class": (_ref = {}, _defineProperty(_ref, className, className), _defineProperty(_ref, "".concat(prefixCls, "-treenode-disabled"), disabled), _defineProperty(_ref, "".concat(prefixCls, "-treenode-switcher-").concat(expanded ? 'open' : 'close'), !isLeaf), _defineProperty(_ref, "".concat(prefixCls, "-treenode-checkbox-checked"), checked), _defineProperty(_ref, "".concat(prefixCls, "-treenode-checkbox-indeterminate"), halfChecked), _defineProperty(_ref, "".concat(prefixCls, "-treenode-selected"), selected), _defineProperty(_ref, "".concat(prefixCls, "-treenode-loading"), loading), _defineProperty(_ref, 'drag-over', !disabled && dragOver), _defineProperty(_ref, 'drag-over-gap-top', !disabled && dragOverGapTop), _defineProperty(_ref, 'drag-over-gap-bottom', !disabled && dragOverGapBottom), _defineProperty(_ref, 'filter-node', filterTreeNode && filterTreeNode(this)), _ref),
"style": style,
"role": "treeitem",
"onDragenter": draggable ? this.onDragEnter : noop,
"onDragover": draggable ? this.onDragOver : noop,
"onDragleave": draggable ? this.onDragLeave : noop,
"onDrop": draggable ? this.onDrop : noop,
"onDragend": draggable ? this.onDragEnd : noop
}, dataOrAriaAttributeProps), [this.renderSwitcher(), this.renderCheckbox(), this.renderSelector(), this.renderChildren()]);
}
});
TreeNode.isTreeNode = 1;
export default TreeNode;
|
dcat52/wpi-humanoid-tough
|
tough_gui/src/configurationreader.cpp
|
#include "tough_gui/configurationreader.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <typeinfo>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
ConfigurationReader::ConfigurationReader()
{
delimiter_ = '=';
}
ConfigurationReader::ConfigurationReader(const char *file_name)
{
readConfiguration(file_name);
}
void ConfigurationReader::readConfiguration(){
return readConfiguration("config.ini");
}
void ConfigurationReader::readConfiguration(const char *file_name){
std::string current_line,token;
std::cout<<file_name<<std::endl;
std::ifstream config_file(file_name);
std::string topicName;
std::string topicType;
bool isValue = false;
if(config_file.is_open()){
while(std::getline(config_file,current_line)){
current_line = trim(current_line);
if(current_line.substr(0,1)=="#")
continue;
boost::char_separator<char> token("=");
boost::tokenizer<boost::char_separator<char> > tokens(current_line, token);
BOOST_FOREACH(std::string t, tokens)
{
if(isValue){
currentTopics[topicType] = trim(t);
isValue=false;
}
else{
topicType = trim(t);
isValue = true;
}
}
}
config_file.close();
}
else
std::cout<<"Could not read the file"<<std::endl;
}
|
leonardon473/my-dinner-backend
|
src/apps/menu/migrations/0001_initial.py
|
# Generated by Django 3.2 on 2021-12-09 21:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="TypeOfCuisine",
fields=[
(
"type_of_cuisine_id",
models.AutoField(primary_key=True, serialize=False),
),
("name", models.CharField(max_length=50)),
],
options={
"verbose_name": "Type of cuisine",
"verbose_name_plural": "Types of cuisine",
},
),
migrations.CreateModel(
name="MenuItem",
fields=[
("menu_item_id", models.AutoField(primary_key=True, serialize=False)),
("name", models.CharField(max_length=50)),
("description", models.TextField(max_length=2000)),
("price", models.DecimalField(decimal_places=2, max_digits=7)),
("is_available", models.BooleanField(default=True)),
(
"type_of_cuisine",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
to="menu.typeofcuisine",
),
),
],
options={
"verbose_name": "Product",
"verbose_name_plural": "Products",
},
),
]
|
lksone/spring-boot-demo
|
spring-rabbitmq/src/main/java/com/lks/demo/core/mq/topic/consumer/TopicMessageConsumer1.java
|
<filename>spring-rabbitmq/src/main/java/com/lks/demo/core/mq/topic/consumer/TopicMessageConsumer1.java
package com.lks.demo.core.mq.topic.consumer;
import com.lks.demo.core.mq.config.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
/**
* @author lks
* @Time 2020/1/17
**/
public class TopicMessageConsumer1 {
private static final String EXCHANGE_NAME = "exchange_topic";
private static final String QUEUE_NAME = "topic_queue_test1";
public static void main(String[] args) throws Exception {
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
//聲明隊列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
/**
* 綁定交換機
*
* 注意點:該匹配需要通過 .去区分*;
* 例如:roututungkey* 是不能够被区分和匹配的
* roututungkey.* 是可以匹配到指定的数据
*
*/
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "routingkey.*");
channel.basicQos(1);
//獲取消費者對象
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
// 监听队列,手动返回完成
channel.basicConsume(QUEUE_NAME, false, queueingConsumer);
while (true){
QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
String string = new String(delivery.getBody());
System.out.println(string);
Thread.sleep(10);
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
}
}
|
anandprabhakar0507/golang-samples
|
jobs/v3/howto/basic_company_sample.go
|
<reponame>anandprabhakar0507/golang-samples<filename>jobs/v3/howto/basic_company_sample.go
// Copyright 2018 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package sample
import (
"context"
"fmt"
"io"
"log"
"time"
"golang.org/x/oauth2/google"
talent "google.golang.org/api/jobs/v3"
)
// [START create_service]
// createCTSService creates service of Cloud Talent Solution.
func createCTSService() (*talent.Service, error) {
// Authorize the client using Application Default Credentials.
// See https://g.co/dv/identity/protocols/application-default-credentials
ctx := context.Background()
client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
if err != nil {
return nil, fmt.Errorf("google.DefaultClient: %v", err)
}
// Create the jobs service client.
ctsService, err := talent.New(client)
if err != nil {
return nil, fmt.Errorf("talent.New: %v", err)
}
return ctsService, nil
}
// [END create_service]
// [START basic_company]
// constructCompanyWithRequiredFields constructs a company with required fields: ExternalId and DisplayName.
func constructCompanyWithRequiredFields() *talent.Company {
externalID := fmt.Sprintf("sample-company-%d", time.Now().UnixNano())
return &talent.Company{
ExternalId: externalID,
DisplayName: "Google Sample",
}
}
// [END basic_company]
// [START create_company]
// createCompany creates a company as given.
func createCompany(service *talent.Service, parent string, companyToCreate *talent.Company) (*talent.Company, error) {
createCompanyRquest := &talent.CreateCompanyRequest{
Company: companyToCreate,
}
company, err := service.Projects.Companies.Create(parent, createCompanyRquest).Do()
if err != nil {
return nil, fmt.Errorf("failed to create company %q: %v", companyToCreate.DisplayName, err)
}
return company, nil
}
// [END create_company]
// [START get_company]
// getCompany gets an existing company by name.
func getCompany(service *talent.Service, name string) (*talent.Company, error) {
company, err := service.Projects.Companies.Get(name).Do()
if err != nil {
return nil, fmt.Errorf("failed to get company %q: %v", name, err)
}
return company, nil
}
// [END get_company]
// [START update_company]
// updateCompany update a company with all fields.
func updateCompany(service *talent.Service, name string, companyToUpdate *talent.Company) (*talent.Company, error) {
updateCompanyRequest := &talent.UpdateCompanyRequest{
Company: companyToUpdate,
}
company, err := service.Projects.Companies.Patch(name, updateCompanyRequest).Do()
if err != nil {
return nil, fmt.Errorf("failed to update company %q: %v", name, err)
}
return company, nil
}
// [END update_company]
// [START update_company_with_field_mask]
// updateCompanyWithMask updates a company with specific fields.
// mask: comma separated top-level fields of Company
func updateCompanyWithMask(service *talent.Service, name string, mask string, companyToUpdate *talent.Company) (*talent.Company, error) {
updateCompanyRequest := &talent.UpdateCompanyRequest{
Company: companyToUpdate,
UpdateMask: mask,
}
company, err := service.Projects.Companies.Patch(name, updateCompanyRequest).Do()
if err != nil {
return nil, fmt.Errorf("failed to update company %q with mask %q: %v", name, mask, err)
}
return company, nil
}
// [END update_company_with_field_mask]
// [START delete_company]
// deleteCompany deletes an existing company by name.
func deleteCompany(service *talent.Service, name string) (*talent.Empty, error) {
empty, err := service.Projects.Companies.Delete(name).Do()
if err != nil {
return nil, fmt.Errorf("failed to delete company %q: %v", name, err)
}
return empty, nil
}
// [END delete_company
// [START list_companies]
// listCompanies lists all companies in the project
func listCompanies(service *talent.Service, parent string) (*talent.ListCompaniesResponse, error) {
resp, err := service.Projects.Companies.List(parent).Do()
if err != nil {
return nil, fmt.Errorf("failed to list companies: %v", err)
}
return resp, nil
}
// [END list_companies]
// [START run_basic_company_sample]
func runBasicCompanySample(w io.Writer, projectID string) {
parent := fmt.Sprintf("projects/%s", projectID)
service, err := createCTSService()
if err != nil {
log.Fatal(err)
}
companyToCreate := constructCompanyWithRequiredFields()
companyCreated, err := createCompany(service, parent, companyToCreate)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "CreateCompany: %s\n", companyCreated.DisplayName)
name := companyCreated.Name
companyGot, err := getCompany(service, name)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "GetCompany: %s\n", companyGot.DisplayName)
companyToUpdate := companyCreated
companyToUpdate.DisplayName = "Google Sample (updated)"
companyUpdated, err := updateCompany(service, name, companyToUpdate)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "UpdateCompany: %s\n", companyUpdated.DisplayName)
companyUpdated.WebsiteUri = "http://googlesample.com"
companyUpdated.DisplayName = "Google Sample (updated with mask)"
companyUpdatedWithMask, err := updateCompanyWithMask(service, name, "WebSiteUri,DisplayName", companyUpdated)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "UpdateCompanyWithMask: %s\n", companyUpdatedWithMask.DisplayName)
empty, err := deleteCompany(service, name)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "DeleteCompany StatusCode: %d\n", empty.ServerResponse.HTTPStatusCode)
resp, err := listCompanies(service, parent)
if err != nil {
log.Fatal(err)
}
fmt.Fprintf(w, "ListCompanies Request ID: %q\n", resp.Metadata.RequestId)
for _, company := range resp.Companies {
fmt.Fprintf(w, "-- Company: %q\n", company.Name)
}
}
// [END run_basic_company_sample]
|
swedenconnect/eidas-eu-mock
|
EIDAS-Sources-2.3.1-MDSL/EIDAS-SAMLEngine/src/main/java/eu/eidas/auth/engine/core/ProtocolEncrypterI.java
|
/*
# Copyright (c) 2017 European Commission
# Licensed under the EUPL, Version 1.2 or – as soon they will be
# approved by the European Commission - subsequent versions of the
# EUPL (the "Licence");
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at:
# * https://joinup.ec.europa.eu/page/eupl-text-11-12
# *
# Unless required by applicable law or agreed to in writing, software
# distributed under the Licence is distributed on an "AS IS" basis,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Licence for the specific language governing permissions and limitations under the Licence.
*/
package eu.eidas.auth.engine.core;
import eu.eidas.engine.exceptions.EIDASSAMLEngineException;
import org.opensaml.saml.saml2.core.Response;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.security.cert.X509Certificate;
/**
* Interface responsible for encrypting.
* <p>
* Typically this interface encrypts responses sent to several nodes with their public certificates (e.g. found in their
* metadata).
*
* @since 1.1
*/
public interface ProtocolEncrypterI extends ProtocolCipherI {
/**
* Encrypts the given response with the given destination certificate.
*
* @param authResponse the response to encrypt
* @param destinationCertificate the certificate to encrypt with
* @return the encrypted response
* @throws EIDASSAMLEngineException if any error occurs
*/
@Nonnull
Response encryptSamlResponse(@Nonnull Response authResponse, @Nonnull X509Certificate destinationCertificate, boolean encryptAssertionWithKey)
throws EIDASSAMLEngineException;
/**
* Returns the encryption certificate to be used to encrypt a response for the given country
*
* @return the encryption certificate to be used to encrypt a response for the given country
*/
@Nullable
X509Certificate getEncryptionCertificate(@Nullable String destinationCountryCode) throws EIDASSAMLEngineException;
/**
* Returns whether encryption is enabled for the given country.
*
* @param countryCode the 2-letter country code as defined in ISO 3166 of the country the response is being sent
* to.
* @return whether encryption is enabled for the given country.
* @see ProtocolEncrypterI#isResponseEncryptionMandatory()
*/
boolean isEncryptionEnabled(@Nonnull String countryCode);
boolean isAssertionEncryptWithKey();
}
|
dnalborczyk/rollup
|
test/chunking-form/samples/dynamically-import-untainted-entry/_expected/cjs/importer.js
|
'use strict';
function _interopNamespaceDefaultOnly (e) { return Object.freeze({ __proto__: null, 'default': e }); }
Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespaceDefaultOnly(require('./main.js')); }).then(result => console.log('importer', result));
|
poanchen/azure-sdk-for-ruby
|
management/azure_mgmt_sql/lib/2015-05-01-preview/generated/azure_mgmt_sql/models/server_update.rb
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::SQL::Mgmt::V2015_05_01_preview
module Models
#
# An update request for an Azure SQL Database server.
#
class ServerUpdate
include MsRestAzure
# @return [String] Administrator username for the server. Once created it
# cannot be changed.
attr_accessor :administrator_login
# @return [String] The administrator login password (required for server
# creation).
attr_accessor :administrator_login_password
# @return [String] The version of the server.
attr_accessor :version
# @return [String] The state of the server.
attr_accessor :state
# @return [String] The fully qualified domain name of the server.
attr_accessor :fully_qualified_domain_name
# @return [Hash{String => String}] Resource tags.
attr_accessor :tags
#
# Mapper for ServerUpdate class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ServerUpdate',
type: {
name: 'Composite',
class_name: 'ServerUpdate',
model_properties: {
administrator_login: {
client_side_validation: true,
required: false,
serialized_name: 'properties.administratorLogin',
type: {
name: 'String'
}
},
administrator_login_password: {
client_side_validation: true,
required: false,
serialized_name: 'properties.administratorLoginPassword',
type: {
name: 'String'
}
},
version: {
client_side_validation: true,
required: false,
serialized_name: 'properties.version',
type: {
name: 'String'
}
},
state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.state',
type: {
name: 'String'
}
},
fully_qualified_domain_name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.fullyQualifiedDomainName',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
}
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.