repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
rdp/rogerpack2005-golang
|
include/plan9/ureg_arm.h
|
<reponame>rdp/rogerpack2005-golang
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "../ureg_arm.h"
|
ed741/PathBench
|
src/algorithms/algorithm_manager.py
|
<filename>src/algorithms/algorithm_manager.py
from algorithms.algorithm import Algorithm
from utility.compatibility import HAS_OMPL
from utility.misc import static_class
from typing import Optional, List, Type, Dict, Any, Tuple
import importlib.util
import inspect
import os
import sys
import copy
import traceback
# planner testing
from algorithms.basic_testing import BasicTesting
from algorithms.classic.testing.a_star_testing import AStarTesting
from algorithms.classic.testing.combined_online_lstm_testing import CombinedOnlineLSTMTesting
from algorithms.classic.testing.dijkstra_testing import DijkstraTesting
from algorithms.classic.testing.wavefront_testing import WavefrontTesting
from algorithms.classic.testing.way_point_navigation_testing import WayPointNavigationTesting
# planner implementations
from algorithms.classic.graph_based.a_star import AStar
from algorithms.classic.graph_based.bug1 import Bug1
from algorithms.classic.graph_based.bug2 import Bug2
from algorithms.classic.graph_based.dijkstra import Dijkstra
from algorithms.classic.graph_based.potential_field import PotentialField
from algorithms.classic.sample_based.sprm import SPRM
from algorithms.classic.sample_based.rt import RT
from algorithms.classic.sample_based.rrt import RRT
from algorithms.classic.sample_based.rrt_star import RRT_Star
from algorithms.classic.sample_based.rrt_connect import RRT_Connect
from algorithms.classic.graph_based.wavefront import Wavefront
from algorithms.lstm.LSTM_tile_by_tile import OnlineLSTM
from algorithms.lstm.a_star_waypoint import WayPointNavigation
from algorithms.lstm.combined_online_LSTM import CombinedOnlineLSTM
if HAS_OMPL:
from algorithms.classic.sample_based.ompl_rrt import OMPL_RRT
from algorithms.classic.sample_based.ompl_prmstar import OMPL_PRMstar
from algorithms.classic.sample_based.ompl_lazyprmstar import OMPL_LazyPRMstar
from algorithms.classic.sample_based.ompl_rrtstar import OMPL_RRTstar
from algorithms.classic.sample_based.ompl_rrtsharp import OMPL_RRTsharp
from algorithms.classic.sample_based.ompl_rrtx import OMPL_RRTXstatic
from algorithms.classic.sample_based.ompl_informedrrt import OMPL_InformedRRT
from algorithms.classic.sample_based.ompl_kpiece1 import OMPL_KPIECE1
from algorithms.classic.sample_based.ompl_ltlplanner import OMPL_LTLPlanner
from algorithms.classic.sample_based.ompl_pdst import OMPL_PDST
from algorithms.classic.sample_based.ompl_sst import OMPL_SST
from algorithms.classic.sample_based.ompl_aitstar import OMPL_AITstar
from algorithms.classic.sample_based.ompl_anytimepathshortening import OMPL_AnytimePathShortening
from algorithms.classic.sample_based.ompl_bfmt import OMPL_BFMT
from algorithms.classic.sample_based.ompl_biest import OMPL_BiEST
from algorithms.classic.sample_based.ompl_rrtconnect import OMPL_RRTConnect
from algorithms.classic.sample_based.ompl_trrt import OMPL_TRRT
from algorithms.classic.sample_based.ompl_birlrt import OMPL_BiRLRT
from algorithms.classic.sample_based.ompl_bitrrt import OMPL_BiTRRT
from algorithms.classic.sample_based.ompl_bitstar import OMPL_BITstar
from algorithms.classic.sample_based.ompl_bkpiece1 import OMPL_BKPIECE1
from algorithms.classic.sample_based.ompl_syclop import OMPL_Syclop
from algorithms.classic.sample_based.ompl_cforest import OMPL_CForest
from algorithms.classic.sample_based.ompl_est import OMPL_EST
from algorithms.classic.sample_based.ompl_fmt import OMPL_FMT
from algorithms.classic.sample_based.ompl_lazylbtrrt import OMPL_LazyLBTRRT
from algorithms.classic.sample_based.ompl_lazyprm import OMPL_LazyPRM
from algorithms.classic.sample_based.ompl_lazyrrt import OMPL_LazyRRT
from algorithms.classic.sample_based.ompl_lbkpiece1 import OMPL_LBKPIECE1
from algorithms.classic.sample_based.ompl_lbtrrt import OMPL_LBTRRT
from algorithms.classic.sample_based.ompl_prm import OMPL_PRM
from algorithms.classic.sample_based.ompl_spars import OMPL_SPARS
from algorithms.classic.sample_based.ompl_spars2 import OMPL_SPARS2
from algorithms.classic.sample_based.ompl_vfrrt import OMPL_VFRRT
from algorithms.classic.sample_based.ompl_prrt import OMPL_pRRT
from algorithms.classic.sample_based.ompl_tsrrt import OMPL_TSRRT
from algorithms.classic.sample_based.ompl_psbl import OMPL_pSBL
from algorithms.classic.sample_based.ompl_sbl import OMPL_SBL
from algorithms.classic.sample_based.ompl_stride import OMPL_STRIDE
from algorithms.classic.sample_based.ompl_qrrt import OMPL_QRRT
@static_class
class AlgorithmManager():
MetaData = Tuple[Type[Algorithm], Type[BasicTesting], Tuple[List[Any], Dict[str, Any]]]
builtins: Dict[str, MetaData]
@classmethod
def _static_init_(cls):
cls.builtins = {
"A*": (AStar, AStarTesting, ([], {})),
"WPN":(WayPointNavigation, WayPointNavigationTesting, ([], {"global_kernel_max_it": 10, "global_kernel": (CombinedOnlineLSTM, ([], {}))})),
"WPN-view":(WayPointNavigation, WayPointNavigationTesting, ([], {"global_kernel_max_it": 20, "global_kernel": (OnlineLSTM, ([], {"load_name": "tile_by_tile_training_uniform_random_fill_10000_block_map_10000_house_10000_model"}))})),
"WPN-map": (WayPointNavigation, WayPointNavigationTesting, ([], {"global_kernel_max_it": 20, "global_kernel": (OnlineLSTM, ([], {"load_name": "caelstm_section_lstm_training_uniform_random_fill_10000_block_map_10000_house_10000_model"}))})),
"LSTM Bagging": (CombinedOnlineLSTM, CombinedOnlineLSTMTesting, ([], {})),
"Map Module (CAE) ": (OnlineLSTM, BasicTesting, ([], {"load_name": "caelstm_section_lstm_training_uniform_random_fill_10000_block_map_10000_house_10000_model"})),
"View Module (Online LSTM)": (OnlineLSTM, BasicTesting, ([], {"load_name": "tile_by_tile_training_uniform_random_fill_10000_block_map_10000_house_10000_model"})),
"SPRM": (SPRM, BasicTesting, ([], {})),
"RT": (RT, BasicTesting, ([], {})),
"RRT": (RRT, BasicTesting, ([], {})),
"RRT*": (RRT_Star, BasicTesting, ([], {})),
"RRT-Connect": (RRT_Connect, BasicTesting, ([], {})),
"Wave-front": (Wavefront, WavefrontTesting, ([], {})),
"Dijkstra": (Dijkstra, DijkstraTesting, ([], {})),
"Bug1": (Bug1, BasicTesting, ([], {})),
"Bug2": (Bug2, BasicTesting, ([], {})),
"Potential Field": (PotentialField, BasicTesting, ([], {}))
}
if HAS_OMPL:
cls.builtins.update({
"OMPL RRT": (OMPL_RRT, BasicTesting, ([], {})),
"OMPL PRM*": (OMPL_PRMstar, BasicTesting, ([], {})),
"OMPL Lazy PRM*": (OMPL_LazyPRMstar, BasicTesting, ([], {})),
"OMPL RRT*": (OMPL_RRTstar, BasicTesting, ([], {})),
"OMPL RRT#": (OMPL_RRTsharp, BasicTesting, ([], {})),
"OMPL RRTX": (OMPL_RRTXstatic, BasicTesting, ([], {})),
"OMPL KPIECE1": (OMPL_KPIECE1, BasicTesting, ([], {})),
"OMPL LazyLBTRRT": (OMPL_LazyLBTRRT, BasicTesting, ([], {})),
"OMPL LazyPRM": (OMPL_LazyPRM, BasicTesting, ([], {})),
"OMPL LazyRRT": (OMPL_LazyRRT, BasicTesting, ([], {})),
"OMPL LBKPIECE1": (OMPL_LBKPIECE1, BasicTesting, ([], {})),
"OMPL LBTRRT": (OMPL_LBTRRT, BasicTesting, ([], {})),
"OMPL PRM": (OMPL_PRM, BasicTesting, ([], {})),
"OMPL SBL": (OMPL_SBL, BasicTesting, ([], {})),
"OMPL STRIDE": (OMPL_STRIDE, BasicTesting, ([], {})),
"OMPL PDST": (OMPL_PDST, BasicTesting, ([], {})),
"OMPL SST": (OMPL_SST, BasicTesting, ([], {})),
"OMPL BiEst": (OMPL_BiEST, BasicTesting, ([], {})),
"OMPL TRRT": (OMPL_TRRT, BasicTesting, ([], {})),
"OMPL RRTConnect": (OMPL_RRTConnect, BasicTesting, ([], {})),
"OMPL BITstar": (OMPL_BITstar, BasicTesting, ([], {})),
"OMPL BKPIECE1": (OMPL_BKPIECE1, BasicTesting, ([], {})),
"OMPL EST": (OMPL_EST, BasicTesting, ([], {})),
# "OMPL LTLPlanner": (OMPL_LTLPlanner, BasicTesting, ([], {})),
# "OMPL AITstar": (OMPL_AITstar, BasicTesting, ([], {})),
# "OMPL AnytimePathShortening": (OMPL_AnytimePathShortening, BasicTesting, ([], {})),
# "OMPL BFMT": (OMPL_BFMT, BasicTesting, ([], {})),
# "OMPL BiRLRT": (OMPL_BiRLRT, BasicTesting, ([], {})),
# "OMPL BiTRRT": (OMPL_BiTRRT, BasicTesting, ([], {})),
# "OMPL Syclop ": (OMPL_Syclop, BasicTesting, ([], {})),
# "OMPL CForest": (OMPL_CForest, BasicTesting, ([], {})),
# "OMPL FMT": (OMPL_FMT, BasicTesting, ([], {})),
# "OMPL SPARS": (OMPL_SPARS, BasicTesting, ([], {})),
# "OMPL SPARS2": (OMPL_SPARS2, BasicTesting, ([], {})),
# "OMPL VFRRT": (OMPL_VFRRT, BasicTesting, ([], {})),
# "OMPL pRRT": (OMPL_pRRT, BasicTesting, ([], {})),
# "OMPL TSRRT": (OMPL_TSRRT, BasicTesting, ([], {})),
# "OMPL pSBL": (OMPL_pSBL, BasicTesting, ([], {})),
# "OMPL QRRT": (OMPL_QRRT, BasicTesting, ([], {})),
})
@staticmethod
def load_all(ids: List[str]) -> List[List[Tuple[str, MetaData]]]:
"""
Returns a list of algorithms from a list of names or file paths.
For each element in `ids`, if string is the display name
of a built-in algorithm, then we return that algorithm. Otherwise,
we return the result of AlgorithmManager.try_load_from_file().
"""
algs: List[List[Tuple[str, MetaData]]] = []
for alg in ids:
if alg in AlgorithmManager.builtins:
algs.append([copy.deepcopy((alg, AlgorithmManager.builtins[alg]))])
else:
algs.append(AlgorithmManager.try_load_from_file(alg))
return algs
@staticmethod
def try_load_from_file(path: str) -> List[Tuple[str, MetaData]]:
if not os.path.exists(path):
msg = "File '{}' does not exist".format(path)
print(msg, file=sys.stderr)
return []
try:
spec = importlib.util.spec_from_file_location("custom_loaded", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# return all classes that inherit from "Algorithm"
algs = []
for name in dir(module):
if name.startswith("_"):
continue
cls = getattr(module, name)
if inspect.isclass(cls) and cls is not Algorithm and issubclass(cls, Algorithm):
name = cls.name if "name" in cls.__dict__ else os.path.basename(path) + " ({})".format(name)
testing = cls.testing if "testing" in cls.__dict__ else BasicTesting
algs.append((name, (cls, testing, ([], {}))))
return algs
except:
msg = "Failed to load algorithms from file '{}', reason:\n{}".format(path, traceback.format_exc())
print(msg, file=sys.stderr)
return []
|
fieranmason/mem-admin
|
scripts/public-content/update-mines.js
|
'use strict';
var MongoClient = require('mongodb').MongoClient;
var Promise = require('promise');
var _ = require('lodash');
var defaultConnectionString = 'mongodb://localhost:27017/mem-dev';
var username = '';
var password = '';
var host = '';
var db = '';
var url = '';
var args = process.argv.slice(2);
if (args.length !== 4) {
console.log('Using default localhost connection:', defaultConnectionString);
url = defaultConnectionString;
} else {
username = args[0];
password = args[1];
host = args[2];
db = args[3];
url = 'mongodb://' + username + ':' + password + '@' + host + ':27017/' + db;
}
var getProjects = function(db) {
return new Promise(function(resolve, reject) {
// Find all of the projects
db.collection('projects').find({}).toArray(function(err, object) {
if (err) {
console.log('x failed to find projects');
reject(err);
} else {
console.log(': found ' + object.length + ' projects');
resolve(object);
}
});
});
};
var getContentHtml = function(project, page, type) {
var content = project.content ? project.content.filter(function(c) { return c.type === type && c.page === page; }) : [];
return content.length ? content[0].html : '';
};
var updateProject = function(db, project) {
return new Promise(function(resolve, reject) {
console.log(': updating project ' + project.code);
var activities = project.activities && project.activities.length ? project.activities : [{
name : 'Design',
status : ''
}, {
name : 'Construction',
status : ''
}, {
name : 'Operation',
status : ''
}, {
name : 'Closure',
status : ''
}, {
name : 'Reclamation',
status : ''
}, {
name : 'Monitoring & Reporting',
status : ''
}];
// Ensure order is set
_.each(activities, function(a, i) { a.order = i; });
db.collection('projects').updateOne({ code: project.code }, { $set: {
subtitle : getContentHtml(project, 'DETAILS', 'SUBTITLE') || project.subtitle || (project.name + ' Overview'),
activities : activities,
content : [{
page: 'Mines',
type: 'Intro',
html: getContentHtml(project, 'DETAILS', 'INTRO_TEXT') || getContentHtml(project, 'Mines', 'Intro') || project.description
} , {
page: 'Auth',
type: 'Intro',
html: getContentHtml(project, 'Auth', 'Intro') || 'Environmental assessment certificates and permits issued under the Mines Act and the Environmental Management Act (EMA) are the primary provincial authorizations for major mine projects in British Columbia. Below you will find a list of authorizations associated with each of these three acts (as applicable).'
} , {
page: 'Comp',
type: 'Intro',
html: getContentHtml(project, 'Comp', 'Intro') || 'Compliance and enforcement (C&E) activities begin after a claim is staked and continue through exploration and the life of a mine. The Ministry of Energy, Mines and Petroleum Resources (EMPR), Ministry of Environment and Climate Change Strategy (ENV) and Environmental Assessment Office (EAO) work together to provide integrated oversight of British Columbia's mining sector. Records of inspections conducted during the 2016 calendar year can be found below.'
} , {
page: 'Other',
type: 'Intro',
html: getContentHtml(project, 'Other', 'Intro') || 'Below you will find recent annual reports (including annual reclamation reports, annual dam safety inspection reports and related documents) as well as other select documents of interest. More documents will be added here on an ongoing basis.'
}]
}}, {}, function(err, obj) {
if (err) {
console.log('x Failed to update project ' + project.code);
reject(err);
} else if (obj.result.n === 0) {
console.log('x Failed to find project ' + project.code);
resolve(obj);
} else {
console.log(': Successfully updated project ' + project.code);
resolve(obj);
}
});
});
}
var run = function () {
var database = null;
return new Promise(function (resolve, reject) {
console.log('start');
MongoClient.connect(url)
.then(function(db) {
console.log(': db connected');
database = db;
})
.then(function() {
console.log(': getting projects');
return getProjects(database);
})
.then(function(projects) {
console.log(': updating projects...');
var projectPromises = []
_.each(projects, function(project) {
projectPromises.push(updateProject(database, project));
});
return Promise.all(projectPromises);
})
.then(function() {
database.close();
console.log('end');
resolve(':)');
}, function (err) {
console.log('ERROR: end err = ', JSON.stringify(err));
reject(err);
});
});
};
run().then(function(success) {
console.log('success ', success);
process.exit();
}).catch(function(error) {
console.error('error ', error);
process.exit();
});
|
avnishsachar/Open3D_homework_task
|
docs/_out/html/cpp_api/search/files_0.js
|
<filename>docs/_out/html/cpp_api/search/files_0.js
var searchData=
[
['azurekinectrecorder_2ecpp',['AzureKinectRecorder.cpp',['../_azure_kinect_recorder_8cpp.html',1,'']]],
['azurekinectrecorder_2eh',['AzureKinectRecorder.h',['../_azure_kinect_recorder_8h.html',1,'']]],
['azurekinectsensor_2ecpp',['AzureKinectSensor.cpp',['../_azure_kinect_sensor_8cpp.html',1,'']]],
['azurekinectsensor_2eh',['AzureKinectSensor.h',['../_azure_kinect_sensor_8h.html',1,'']]],
['azurekinectsensorconfig_2ecpp',['AzureKinectSensorConfig.cpp',['../_azure_kinect_sensor_config_8cpp.html',1,'']]],
['azurekinectsensorconfig_2eh',['AzureKinectSensorConfig.h',['../_azure_kinect_sensor_config_8h.html',1,'']]]
];
|
dreamer888/zhihuinongmao
|
zhnm/zhnm-miniapp/backend/mallweb/src/main/java/com/yq/controller/news/NewsController.java
|
package com.yq.controller.news;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.change.controller.base.BaseController;
import org.change.entity.Page;
import org.change.util.AppUtil;
import org.change.util.PageData;
import com.fh.util.Jurisdiction;
import com.google.gson.Gson;
import com.yq.service.news.NewsManager;
import com.yq.util.DatetimeUtil;
/**
* 说明:新闻信息 创建人:壹仟科技 qq 357788906 创建时间:2016-12-29
*/
@Controller
@RequestMapping(value = "/news")
public class NewsController extends BaseController {
String menuUrl = "news/list.do"; // 菜单地址(权限用)
@Resource(name = "newsService")
private NewsManager newsService;
private Gson gson = new Gson();
/**
* 保存
*
* @param
* @throws Exception
*/
@RequestMapping(value = "/save")
public ModelAndView save() throws Exception {
logBefore(logger, Jurisdiction.getUsername() + "新增News");
if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
return null;
} // 校验权限
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
System.out.println("save》》》》》》》》》》》》"+pd);
pd.put("addtime", DatetimeUtil.getDate());
pd.put("news_id", this.get32UUID()); // 主键
newsService.save(pd);
mv.setViewName("redirect:/news/list?type=" + pd.get("type"));
return mv;
}
/**
* 删除
*
* @param out
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/delete",produces = "application/json;charset=UTF-8")
public String delete() throws Exception {
logBefore(logger, Jurisdiction.getUsername() + "删除News");
int result = 0;
String message = "";
Map<String,Object> map = new HashMap<>();
PageData pd = new PageData();
pd = this.getPageData();
try {
if (Jurisdiction.buttonJurisdiction(menuUrl, "del")) {// 校验权限
newsService.delete(pd);
result = 1;
}
} catch (Exception e) {
result = 0;
message = "系统异常";
}
map.put("result",result);
map.put("message",message);
return gson.toJson(map);
}
/**
* 修改
*
* @param
* @throws Exception
*/
@RequestMapping(value = "/edit")
public ModelAndView edit() throws Exception {
logBefore(logger, Jurisdiction.getUsername() + "修改News");
if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
return null;
} // 校验权限
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
System.out.println("pd》》》》》》》》》》》》"+pd);
newsService.edit(pd);
mv.setViewName("redirect:/news/list?type=" + pd.get("type"));
return mv;
}
/**
* 列表
*
* @param page
* @throws Exception
*/
@RequestMapping(value = "/list")
public ModelAndView list(Page page) throws Exception {
logBefore(logger, Jurisdiction.getUsername() + "列表News");
// if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
// //校验权限(无权查看时页面会有提示,如果不注释掉这句代码就无法进入列表页面,所以根据情况是否加入本句代码)
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
String keywords = pd.getString("keywords"); // 关键词检索条件
if (null != keywords && !"".equals(keywords)) {
pd.put("keywords", keywords.trim());
}
pd.put("type", pd.getString("type"));
page.setPd(pd);
List<PageData> varList = newsService.list(page); // 列出News列表
mv.setViewName("news/news_list");
mv.addObject("varList", varList);
mv.addObject("pd", pd);
mv.addObject("qx", Jurisdiction.getHC()); // 按钮权限
return mv;
}
/**
* 去新增页面
*
* @param
* @throws Exception
*/
@RequestMapping(value = "/goAdd")
public ModelAndView goAdd() throws Exception {
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
mv.setViewName("news/news_edit");
mv.addObject("msg", "save");
mv.addObject("pd", pd);
return mv;
}
/**
* 去修改页面
*
* @param
* @throws Exception
*/
@RequestMapping(value = "/goEdit")
public ModelAndView goEdit() throws Exception {
ModelAndView mv = this.getModelAndView();
PageData pd = new PageData();
pd = this.getPageData();
pd = newsService.findById(pd); // 根据ID读取
mv.setViewName("news/news_edit");
mv.addObject("msg", "edit");
mv.addObject("pd", pd);
return mv;
}
/**
* 批量删除
*
* @param
* @throws Exception
*/
@RequestMapping(value = "/deleteAll")
@ResponseBody
public Object deleteAll() throws Exception {
logBefore(logger, Jurisdiction.getUsername() + "批量删除News");
if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
return null;
} // 校验权限
PageData pd = new PageData();
Map<String, Object> map = new HashMap<String, Object>();
pd = this.getPageData();
List<PageData> pdList = new ArrayList<PageData>();
String DATA_IDS = pd.getString("DATA_IDS");
if (null != DATA_IDS && !"".equals(DATA_IDS)) {
String ArrayDATA_IDS[] = DATA_IDS.split(",");
newsService.deleteAll(ArrayDATA_IDS);
pd.put("msg", "ok");
} else {
pd.put("msg", "no");
}
pdList.add(pd);
map.put("list", pdList);
return AppUtil.returnObject(pd, map);
}
}
|
steffenschroeder/tarnow
|
tarnow/switch.py
|
<gh_stars>0
import os
import fcntl
import subprocess
import sys
import syslog as log
from . import config
class Switch(object):
def __str__(self):
return "Name: '%s', NextSkip: '%s', AllSkip: '%s'" % (
self.name,
str(self.next_skip),
str(self.all_skip),
)
@classmethod
def toggle_all(cls, status):
switches = config.switches
for switch in switches.keys():
s = Switch(switch)
if not s.dontIncludeInAllRuns:
s.toggle(status)
def __init__(self, name):
self.name = name
self.next_skip = Skip(name, "skip")
self.all_skip = Skip(name, "pernament")
self._initAlwaysOn()
def toggle(self, status):
if self.is_skip_all():
log.syslog("Skipping permanently " + self.name)
return
elif self.is_skip_next():
log.syslog("Skipping " + self.name)
# delete the file
self.dont_skip_next()
return
if self.name in config.switches:
self._change_status(status)
elif self.name == "all":
Switch.toggle_all(status)
else:
log.syslog(log.LOG_WARNING, "Called with unknown switch: " + self.name)
def _change_status(self, status):
lock = Lock()
try:
lock.acquire()
switch_to_change = config.switches.get(self.name)
unit_code = str(switch_to_change.get("unitcode"))
log.syslog("changing status of '%s' to '%s'" % (self.name, status))
subprocess.call(
[
str(config.executable),
str(config.areacode),
str(unit_code),
str(status),
]
)
finally:
lock.release()
def is_skip_next(self):
return self.next_skip.enabled()
def is_skip_all(self):
return self.all_skip.enabled()
def dont_skip_next(self):
self.next_skip.delete()
def dont_skip_all(self):
self.all_skip.delete()
def skip_next(self):
self.next_skip.create()
def skip_all(self):
self.all_skip.create()
def _initAlwaysOn(self):
self.dontIncludeInAllRuns = False
if self.name in config.switches.keys():
s = config.switches.get(self.name)
self.dontIncludeInAllRuns = s.get("dontIncludeInAllRuns", False)
class Skip(object):
def __str__(self):
return "Name: '%s', Type: '%s', enabled: ''%s" % (
self.name,
self.type,
self.enabled(),
)
def __init__(self, name, skiptype):
self.name = name
self.type = skiptype
self._generate_file_name()
def enabled(self):
return os.path.exists(self.skipfilename)
def create(self):
with open(self.skipfilename, "a"):
os.utime(self.skipfilename, None)
def delete(self):
if os.path.exists(self.skipfilename):
os.remove(self.skipfilename)
def _generate_file_name(self):
home = os.path.expanduser("~")
current_path = home + os.sep + ".tarnow"
if not os.path.exists(current_path):
os.makedirs(current_path)
self.skipfilename = current_path + os.sep + self.type + self.name + ".skip"
# Inspired by: http://blog.vmfarms.com/2011/03/cross-process-locking-and.html """
class Lock:
def __init__(self, filename="tarnow.tmp"):
self.filename = filename
self.handle = open(filename, "w")
def acquire(self):
fcntl.flock(self.handle, fcntl.LOCK_EX)
def release(self):
fcntl.flock(self.handle, fcntl.LOCK_UN)
def __del__(self):
self.handle.close()
|
wuyaowei1989/CoolPlay
|
app/src/main/java/com/android/coolPlay/net/JanDanApi.java
|
package com.android.coolPlay.net;
import android.support.annotation.StringDef;
import com.android.coolPlay.bean.FreshNewsArticleBean;
import com.android.coolPlay.bean.FreshNewsBean;
import com.android.coolPlay.bean.JdDetailBean;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import io.reactivex.Observable;
/**
* desc: .
* author: Will .
* date: 2017/9/27 .
*/
public class JanDanApi {
public static final String TYPE_FRESH = "get_recent_posts";
public static final String TYPE_FRESHARTICLE = "get_post";
public static final String TYPE_BORED = "jandan.get_pic_comments";
public static final String TYPE_GIRLS = "jandan.get_drawings_comments";
public static final String TYPE_Duan = "jandan.get_duan_comments";
@StringDef({TYPE_FRESH, TYPE_BORED, TYPE_GIRLS, TYPE_Duan})
@Retention(RetentionPolicy.SOURCE)
public @interface Type {
}
public static JanDanApi sInstance;
private JanDanApiService mService;
public JanDanApi(JanDanApiService janDanApiService) {
this.mService = janDanApiService;
}
public static JanDanApi getInstance(JanDanApiService janDanApiService) {
if (sInstance == null)
sInstance = new JanDanApi(janDanApiService);
return sInstance;
}
/**
* 获取新鲜事列表
*
* @param page 页码
* @return
*/
public Observable<FreshNewsBean> getFreshNews(int page) {
return mService.getFreshNews(ApiConstants.sJanDanApi, TYPE_FRESH,
"url,date,tags,author,title,excerpt,comment_count,comment_status,custom_fields",
page, "thumb_c,views", "1");
}
/**
* 获取 无聊图,段子列表
*
* @param type {@link Type}
* @param page 页码
* @return
*/
public Observable<JdDetailBean> getJdDetails(@Type String type, int page) {
return mService.getDetailData(ApiConstants.sJanDanApi, type, page);
}
/**
* 获取新鲜事文章详情
*
* @param id PostsBean id {@link FreshNewsBean.PostsBean}
* @return
*/
public Observable<FreshNewsArticleBean> getFreshNewsArticle(int id) {
return mService.getFreshNewsArticle(ApiConstants.sJanDanApi, TYPE_FRESHARTICLE, "content,date,modified", id);
}
/**
* 获取流行图
*/
public Observable<JdDetailBean> getJdPopularList() {
return mService.getPopularList(ApiConstants.sJanDanMoyu);
}
}
|
lu1995happy/Leetcode
|
Leetcode/760_findAnagramMappings.java
|
import java.util.HashMap;
public class findAnagramMappings {
// Time: O(n), Space: O(n);
public int[] anagramMappings (int[] A, int[] B) {
int[] res = new int[A.length];
if (A == null || B == null || A.length == 0 || B.length == 0 || A.length != B.length)
return res;
// Since this problem accepts any possible answers, if only accept one answer, we could use
// HashMap<Integer, ArrayList<Integer>> map to handle this, and remove one after get one;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < B.length; i++) {
map.put(B[i], i);
}
for (int i = 0; i < A.length; i++) {
res[i] = map.get(A[i]);
}
return res;
}
}
|
jacebrowning/voc
|
tests/benchmarks/call_simple.py
|
#!/usr/bin/env python
"""Microbenchmark for function call overhead.
This measures simple function calls that are not methods, do not use varargs or
kwargs, and do not use tuple unpacking.
"""
# Python imports
import time
def foo(a, b, c, d):
# 20 calls
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
bar(a, b, c)
def bar(a, b, c):
# 20 calls
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
baz(a, b)
def baz(a, b):
# 20 calls
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
quux(a)
def quux(a):
# 20 calls
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
qux()
def qux():
pass
def test_calls(iterations):
times = []
for _ in range(iterations):
t0 = time.time()
# 40 calls
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
foo(1, 2, 3, 4)
t1 = time.time()
times.append(t1 - t0)
return times
if __name__ == "__main__":
# Priming run.
test_calls(1)
import sys
times = test_calls(int(sys.argv[1]))
print("Time elapsed: " + str(sum(times)))
|
cantona/NT6
|
nitan/cmds/arch/ftpuser.c
|
<filename>nitan/cmds/arch/ftpuser.c
// ftpuser.c
#include <ansi.h>
inherit F_CLEAN_UP;
int main(object me, string arg)
{
mixed ftp_sockets;
string msg, stat ="";
if (! SECURITY_D->valid_grant(me, "(arch)"))
return 0;
if (! find_object(FTP_D))
return notify_fail("傳輸精靈(FTP_D)尚未啟動。\n");
ftp_sockets = FTP_D->query_sockets();
if (! ftp_sockets || ! sizeof(ftp_sockets))
return notify_fail("傳輸精靈(FTP_D)目前沒有任何使用者連線。\n");
msg = sprintf("%-3s %-12s %-17s %-8s %-s\n", "FD", "帳號", "連線位置", "狀態", "最後指令");
foreach(string fd, mixed val in ftp_sockets)
{
if (! undefinedp(val["retr"])) stat += "<下載中>";
if (! undefinedp(val["stor"])) stat += "<上傳中>";
msg += sprintf("%3d %-12s %-17s %-8s %s\n",
fd,
(val["login"] ? val["user"]:"(未登入)"),
val["address"],
stat,
(val["lastcmd"] || "(無)"),
);
}
tell_object(me, msg);
return 1;
}
|
rsteube/carapace-completers
|
completers/tmux_completer/cmd/detachClient_generated.go
|
<reponame>rsteube/carapace-completers<filename>completers/tmux_completer/cmd/detachClient_generated.go<gh_stars>0
package cmd
import (
"github.com/rsteube/carapace"
"github.com/spf13/cobra"
)
var detachClientCmd = &cobra.Command{
Use: "detach-client",
Short: "",
Run: func(cmd *cobra.Command, args []string) {},
}
func init() {
carapace.Gen(detachClientCmd).Standalone()
detachClientCmd.Flags().StringS("E", "E", "", "shell-command")
detachClientCmd.Flags().BoolS("P", "P", false, "TODO description")
detachClientCmd.Flags().BoolS("a", "a", false, "TODO description")
detachClientCmd.Flags().StringS("s", "s", "", "target-session")
detachClientCmd.Flags().StringS("t", "t", "", "target-client")
rootCmd.AddCommand(detachClientCmd)
}
|
Kumar-Saksham/CSMM-CLI
|
test/commands/parseUserConfig.test.js
|
const { expect, test } = require("@oclif/test");
const {
saveDirValidation,
tmpDirValidation,
concurrencyValidation,
transferProgressTimeoutValidation,
dirValidation,
} = require("../../src/helperFunctions/userConfig/validation");
const path = require("path");
describe("HOOK parseUserConfig", () => {
// test
// .stdout()
// .hook('init', {id: 'mycommand'})
// .do(output => expect(output.stdout).to.contain('example hook running mycommand'))
// .it('shows a message')
test
.hook("prerun", { id: "parseUserConfig" })
.it("should set correct and valid saveDir globally", async () => {
expect(__saveDir).to.equal(global.testUserConfig.path.saveDir);
const isValid = await saveDirValidation(__saveDir);
expect(isValid).to.be.true;
});
test
.hook("prerun", { id: "parseUserConfig" })
.it("should set correct and valid tmpDir globally", async () => {
expect(__tmpDir).to.equal(global.testUserConfig.path.tmpDir);
const isValid = await tmpDirValidation(__tmpDir);
expect(isValid).to.be.true;
});
test
.hook("prerun", { id: "parseUserConfig" })
.it("should set correct and valid logDir globally", async () => {
expect(__logDir).to.equal(
path.join(global.testUserConfig.path.tmpDir, "logs")
);
const isValid = await dirValidation(__logDir);
expect(isValid).to.be.true;
});
test
.hook("prerun", { id: "parseUserConfig" })
.it("should set correct and valid packedDir globally", async () => {
expect(__packedDir).to.equal(
path.join(global.testUserConfig.path.tmpDir, "packed")
);
const isValid = await dirValidation(__packedDir);
expect(isValid).to.be.true;
});
test
.hook("prerun", { id: "parseUserConfig" })
.it("should set correct and valid unpackedDir globally", async () => {
expect(__unpackedDir).to.equal(
path.join(global.testUserConfig.path.tmpDir, "unpacked")
);
const isValid = await dirValidation(__unpackedDir);
expect(isValid).to.be.true;
});
test
.hook("prerun", { id: "parseUserConfig" })
.it("should set correct and valid concurrencyLimit value", async () => {
expect(__concurrencyLimit).to.equal(
global.testUserConfig.process.concurrency
);
const isValid = await concurrencyValidation(__concurrencyLimit);
expect(isValid).to.be.true;
});
test
.hook("prerun", { id: "parseUserConfig" })
.it(
"should set correct and valid transferProgressTimeout value",
async () => {
expect(__transferProgressTimeout).to.equal(
global.testUserConfig.process.transferProgressTimeout
);
const isValid = await transferProgressTimeoutValidation(
__transferProgressTimeout
);
expect(isValid).to.be.true;
}
);
});
|
scarybeasts/beebj
|
asm/asm_jit_defs.h
|
<gh_stars>10-100
#ifndef BEEBJIT_ASM_JIT_DEFS_H
#define BEEBJIT_ASM_JIT_DEFS_H
#include "asm_platform.h"
/* NOTE: this affects performance significantly.
* Smaller is generally faster, which I believe is an L1 icache effect.
* Going smaller than 7 is currently not feasible due to some opcodes not
* fitting in 64 bytes.
*/
#define K_JIT_BYTES_SHIFT 7
#define K_JIT_BYTES_PER_BYTE (1 << K_JIT_BYTES_SHIFT)
#define K_JIT_SIZE (65536 * K_JIT_BYTES_PER_BYTE)
/* NOTE: K_JIT_ADDR varies betweeen platforms, and is in asm_platform.h */
#define K_JIT_ADDR_END (K_JIT_ADDR + K_JIT_SIZE)
#define K_JIT_NO_CODE_JIT_PTR_PAGE (K_JIT_ADDR_END + 0)
#define K_JIT_CONTEXT_OFFSET_JIT_CALLBACK (K_CONTEXT_OFFSET_DRIVER_END + 0)
#define K_JIT_CONTEXT_OFFSET_INTURBO (K_CONTEXT_OFFSET_DRIVER_END + 8)
#define K_JIT_CONTEXT_OFFSET_JIT_PTRS (K_CONTEXT_OFFSET_DRIVER_END + 16)
/* TODO: these are x64 backend specific, and don't belong here. */
#define K_JIT_TRAMPOLINE_BYTES 16
#define K_JIT_TRAMPOLINES_ADDR 0x30000000
#endif /* BEEBJIT_ASM_JIT_DEFS_H */
|
lutris/openmsx
|
src/fdc/NowindHost.hh
|
#ifndef NOWINDHOST_HH
#define NOWINDHOST_HH
#include "NowindInterface.hh"
#include "DiskImageUtils.hh"
#include "circular_buffer.hh"
#include "openmsx.hh"
#include <vector>
#include <string>
#include <memory>
#include <iosfwd>
namespace openmsx {
class SectorAccessibleDisk;
class NowindHost
{
public:
explicit NowindHost(const NowindInterface::Drives& drives);
~NowindHost();
// public for usb-host implementation
bool isDataAvailable() const;
// read one byte of response-data from the host (msx <- pc)
byte read();
// like read(), but without side effects (doesn't consume the data)
byte peek() const;
// Write one byte of command-data to the host (msx -> pc)
// Time parameter is in milliseconds. Emulators can pass emulation
// time, usbhost can pass real time.
void write(byte value, unsigned time);
void setAllowOtherDiskroms(bool allow);
bool getAllowOtherDiskroms() const;
void setEnablePhantomDrives(bool enable);
bool getEnablePhantomDrives() const;
template<typename Archive>
void serialize(Archive& ar, unsigned version);
// public for serialization
enum State {
STATE_SYNC1, // waiting for AF
STATE_SYNC2, // waiting for 05
STATE_COMMAND, // waiting for command (9 bytes)
STATE_DISKREAD, // waiting for AF07
STATE_DISKWRITE, // waiting for AA<data>AA
STATE_DEVOPEN, // waiting for filename (11 bytes)
STATE_IMAGE, // waiting for filename
STATE_MESSAGE, // waiting for null-terminated message
};
private:
void msxReset();
SectorAccessibleDisk* getDisk() const;
void executeCommand();
void send(byte value);
void send16(word value);
void sendHeader();
void purge();
void DRIVES();
void DSKCHG();
void CHOICE();
void INIENV();
void setDateMSX();
unsigned getSectorAmount() const;
unsigned getStartSector() const;
unsigned getStartAddress() const;
unsigned getCurrentAddress() const;
void diskReadInit(SectorAccessibleDisk& disk);
void doDiskRead1();
void doDiskRead2();
void transferSectors(unsigned transferAddress, unsigned amount);
void transferSectorsBackwards(unsigned transferAddress, unsigned amount);
void diskWriteInit(SectorAccessibleDisk& disk);
void doDiskWrite1();
void doDiskWrite2();
unsigned getFCB() const;
std::string extractName(int begin, int end) const;
unsigned readHelper1(unsigned dev, char* buffer);
void readHelper2(unsigned len, const char* buffer);
int getDeviceNum() const;
int getFreeDeviceNum();
void deviceOpen();
void deviceClose();
void deviceWrite();
void deviceRead();
void callImage(const std::string& filename);
static const unsigned MAX_DEVICES = 16;
const NowindInterface::Drives& drives;
cb_queue<byte> hostToMsxFifo;
struct {
std::unique_ptr<std::fstream> fs; // not in use when fs == nullptr
unsigned fcb;
} devices[MAX_DEVICES];
// state-machine
std::vector<SectorBuffer> buffer;// work buffer for diskread/write
unsigned lastTime; // last time a byte was received from MSX
State state;
unsigned recvCount; // how many bytes recv in this state
unsigned transfered; // progress within diskread/write
unsigned retryCount; // only used for diskread
unsigned transferSize; // size of current chunk
byte cmdData[9]; // reg_[cbedlhfa] + cmd
byte extraData[240 + 2]; // extra data for diskread/write
byte romdisk; // index of romdisk (255 = no romdisk)
bool allowOtherDiskroms;
bool enablePhantomDrives;
};
} // namespace openmsx
#endif // NOWINDHOST_HH
|
ScipioAM/scipio-utils
|
scipio-utils-doc/src/main/java/com/github/ScipioAM/scipio_utils_doc/pdf/pdf_box/PdfboxOperatorBase.java
|
<gh_stars>0
package com.github.ScipioAM.scipio_utils_doc.pdf.pdf_box;
/**
* @author <NAME>
* @since 1.0.2-p3
* @date 2021/8/27
*/
public abstract class PdfboxOperatorBase {
}
|
Ladicek/arquillian-cube
|
docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/StarOperator.java
|
<reponame>Ladicek/arquillian-cube<gh_stars>0
package org.arquillian.cube.docker.impl.client.config;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import java.util.UUID;
public class StarOperator {
private static Random random = new Random();
private StarOperator(){
}
public static void adaptPortBindingToParallelRun(CubeContainer cubeContainer) {
final Collection<PortBinding> portBindings = cubeContainer.getPortBindings();
if (portBindings == null) {
return;
}
for (PortBinding portBinding : portBindings) {
final int randomPrivatePort = generateRandomPrivatePort();
portBinding.setBound(randomPrivatePort);
}
}
public static void adaptLinksToParallelRun(UUID uuid, CubeContainer cubeContainer) {
final Collection<Link> links = cubeContainer.getLinks();
if (links == null) {
return;
}
for (Link link : links) {
if (link.getName().endsWith("*")) {
String linkTemplate = link.getName().substring(0, link.getName().lastIndexOf('*'));
link.setName(generateNewName(linkTemplate, uuid));
String environmentVariable = linkTemplate.toUpperCase() + "_HOSTNAME=" + link.getName();
if (link.isAliasSet()) {
link.setAlias(generateNewName(link.getAlias(), uuid));
environmentVariable = linkTemplate.toUpperCase() + "_HOSTNAME=" + link.getAlias();
}
final Collection<String> env = cubeContainer.getEnv();
if (env != null) {
// to avoid duplicates
if (env.contains(environmentVariable)) {
env.remove(environmentVariable);
}
} else {
cubeContainer.setEnv(new ArrayList<>());
}
cubeContainer.getEnv().add(environmentVariable);
}
}
}
public static String generateNewName(String containerName, UUID uuid) {
return containerName + "_" + uuid;
}
public static int generateRandomPrivatePort() {
final int randomPort = random.nextInt(16383);
return randomPort + 49152;
}
}
|
usenixatc2021/SoftRefresh_Scheduling
|
linsched-linsched-alpha/arch/sparc/include/asm/tlbflush_64.h
|
#ifndef _SPARC64_TLBFLUSH_H
#define _SPARC64_TLBFLUSH_H
#include <linux/mm.h>
#include <asm/mmu_context.h>
/* TSB flush operations. */
#define TLB_BATCH_NR 192
struct tlb_batch {
struct mm_struct *mm;
unsigned long tlb_nr;
unsigned long vaddrs[TLB_BATCH_NR];
};
extern void flush_tsb_kernel_range(unsigned long start, unsigned long end);
extern void flush_tsb_user(struct tlb_batch *tb);
/* TLB flush operations. */
extern void flush_tlb_pending(void);
#define flush_tlb_range(vma,start,end) \
do { (void)(start); flush_tlb_pending(); } while (0)
#define flush_tlb_page(vma,addr) flush_tlb_pending()
#define flush_tlb_mm(mm) flush_tlb_pending()
/* Local cpu only. */
extern void __flush_tlb_all(void);
extern void __flush_tlb_kernel_range(unsigned long start, unsigned long end);
#ifndef CONFIG_SMP
#define flush_tlb_kernel_range(start,end) \
do { flush_tsb_kernel_range(start,end); \
__flush_tlb_kernel_range(start,end); \
} while (0)
#else /* CONFIG_SMP */
extern void smp_flush_tlb_kernel_range(unsigned long start, unsigned long end);
#define flush_tlb_kernel_range(start, end) \
do { flush_tsb_kernel_range(start,end); \
smp_flush_tlb_kernel_range(start, end); \
} while (0)
#endif /* ! CONFIG_SMP */
#endif /* _SPARC64_TLBFLUSH_H */
|
ANDROFAST/delivery_articulos
|
delivery/app-release_source_from_JADX/com/paypal/android/sdk/payments/PayPalOAuthScopes.java
|
<filename>delivery/app-release_source_from_JADX/com/paypal/android/sdk/payments/PayPalOAuthScopes.java
package com.paypal.android.sdk.payments;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import android.text.TextUtils;
import com.paypal.android.sdk.C0494N;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public final class PayPalOAuthScopes implements Parcelable {
public static final Creator CREATOR = new at();
public static final String PAYPAL_SCOPE_ADDRESS = C0494N.ADDRESS.m16a();
public static final String PAYPAL_SCOPE_EMAIL = C0494N.EMAIL.m16a();
public static final String PAYPAL_SCOPE_FUTURE_PAYMENTS = C0494N.FUTURE_PAYMENTS.m16a();
public static final String PAYPAL_SCOPE_OPENID = C0494N.OPENID.m16a();
public static final String PAYPAL_SCOPE_PAYPAL_ATTRIBUTES = C0494N.PAYPAL_ATTRIBUTES.m16a();
public static final String PAYPAL_SCOPE_PHONE = C0494N.PHONE.m16a();
public static final String PAYPAL_SCOPE_PROFILE = C0494N.PROFILE.m16a();
private List f785a;
public PayPalOAuthScopes() {
this.f785a = new ArrayList();
}
private PayPalOAuthScopes(Parcel parcel) {
this.f785a = new ArrayList();
int readInt = parcel.readInt();
for (int i = 0; i < readInt; i++) {
this.f785a.add(parcel.readString());
}
}
public PayPalOAuthScopes(Set set) {
this();
for (String add : set) {
this.f785a.add(add);
}
}
final List m564a() {
return this.f785a;
}
final String m565b() {
return TextUtils.join(" ", this.f785a);
}
public final int describeContents() {
return 0;
}
public final String toString() {
return String.format(PayPalOAuthScopes.class.getSimpleName() + ": {%s}", new Object[]{this.f785a});
}
public final void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(this.f785a.size());
for (int i2 = 0; i2 < this.f785a.size(); i2++) {
parcel.writeString((String) this.f785a.get(i2));
}
}
}
|
zou-zhicheng/awesome-java
|
book-spring-5-recipes/ch02/recipe_2_06_ii/src/main/java/com/apress/springrecipes/shop/Battery.java
|
package com.apress.springrecipes.shop;
public class Battery extends Product {
private boolean rechargeable;
public Battery() {
super();
}
public Battery(String name, double price, double discount) {
super(name, price, discount);
}
public boolean getRechargeable() {
return rechargeable;
}
// Getters and Setters
public void setRechargeable(boolean rechargeable) {
this.rechargeable = rechargeable;
}
}
|
arjinmc/SmartCam
|
core/src/main/java/com/arjinmc/smartcam/core/camera1/Camera1Wrapper.java
|
package com.arjinmc.smartcam.core.camera1;
import android.hardware.Camera;
import com.arjinmc.smartcam.core.SmartCamLog;
import com.arjinmc.smartcam.core.lock.CameraLock;
import com.arjinmc.smartcam.core.model.CameraFlashMode;
import com.arjinmc.smartcam.core.model.CameraSize;
import com.arjinmc.smartcam.core.model.CameraType;
import com.arjinmc.smartcam.core.model.SmartCamOpenError;
import com.arjinmc.smartcam.core.wrapper.AbsCameraWrapper;
import java.util.ArrayList;
import java.util.List;
import static android.hardware.Camera.getCameraInfo;
/**
* Wrapper for camera v1
* Created by <NAME> on 2019-10-14.
* email: <EMAIL>
*/
public class Camera1Wrapper extends AbsCameraWrapper {
private final String TAG = "Camera1Wrapper";
private Camera mCamera;
private CameraLock mCameraLock;
private int mFlashMode = CameraFlashMode.MODE_OFF;
private int mMaxZoom;
private int mZoom = 0;
public Camera1Wrapper() {
mCameraLock = new CameraLock();
}
@Override
public Camera1Wrapper getCameraWrapper() {
return this;
}
@Override
public Camera getCamera() {
return mCamera;
}
@Override
public void open() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
mCamera = null;
try {
//if camera is not open before
int numberOfCameras = getCameraCount();
int frontCameraId = 1;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
//default mCurrentCameraId is back camera id
mCurrentCameraId = i + "";
}
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
frontCameraId = i;
}
}
// attempt to get a Camera instance
mCamera = Camera.open();
if (mCamera != null) {
mCurrentCameraType = CameraType.CAMERA_BACK;
if (mSmartCamStateCallback != null) {
mSmartCamStateCallback.onConnected();
}
return;
} else {
mCamera = Camera.open(frontCameraId);
if (mCamera == null) {
if (mSmartCamStateCallback != null) {
mSmartCamStateCallback.onError(new SmartCamOpenError());
}
return;
}
mCurrentCameraType = CameraType.CAMERA_FRONT;
mCurrentCameraId = frontCameraId + "";
if (mSmartCamStateCallback != null) {
mSmartCamStateCallback.onConnected();
}
return;
}
} catch (Exception e) {
// Camera is not available (in use or does not exist)
e.printStackTrace();
if (mSmartCamStateCallback != null) {
mSmartCamStateCallback.onError(new SmartCamOpenError(e.getMessage()));
}
return;
}
}
@Override
public boolean resumeOpen() {
try {
if (mCurrentCameraType != CameraType.CAMERA_NULL) {
mCamera = Camera.open(Integer.valueOf(mCurrentCameraId));
if (mCamera != null) {
return true;
}
}
} catch (Exception e) {
// e.printStackTrace();
}
return false;
}
@Override
public void close() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
@Override
public void release() {
close();
}
@Override
public boolean isOpen() {
if (mCamera == null) {
return false;
}
return true;
}
@Override
public boolean isLock() {
return mCameraLock.isLock();
}
@Override
public int getCameraCount() {
return Camera.getNumberOfCameras();
}
@Override
public boolean canFocusAuto() {
if (mCamera == null) {
return false;
}
// get Camera parameters
Camera.Parameters params = mCamera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
return true;
}
return false;
}
@Override
public int getCurrentCameraType() {
if (mCamera == null) {
return CameraType.CAMERA_NULL;
}
return mCurrentCameraType;
}
@Override
public boolean isBackCamera() {
if (mCurrentCameraType == CameraType.CAMERA_BACK) {
return true;
}
return false;
}
@Override
public void switchToBackCamera() {
if (isBackCamera()) {
return;
}
switchCamera(CameraType.CAMERA_BACK);
}
@Override
public void switchToFrontCamera() {
if (!isBackCamera()) {
return;
}
switchCamera(CameraType.CAMERA_FRONT);
}
private void switchCamera(@CameraType.Type int type) {
mCamera.release();
int frontIndex = -1;
int backIndex = -1;
int cameraCount = getCameraCount();
Camera.CameraInfo info = new Camera.CameraInfo();
for (int cameraIndex = 0; cameraIndex < cameraCount; cameraIndex++) {
getCameraInfo(cameraIndex, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
frontIndex = cameraIndex;
} else if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
backIndex = cameraIndex;
}
}
mCurrentCameraType = type;
if (type == CameraType.CAMERA_FRONT && frontIndex != -1) {
mCurrentCameraId = frontIndex + "";
} else if (type == CameraType.CAMERA_BACK && backIndex != -1) {
mCurrentCameraId = backIndex + "";
}
}
@Override
public List<CameraSize> getSupportPreviewSizes() {
if (mCamera == null) {
return null;
}
List<Camera.Size> previewSizes = mCamera.getParameters().getSupportedPreviewSizes();
if (previewSizes != null && !previewSizes.isEmpty()) {
List<CameraSize> cameraSizes = new ArrayList<>();
for (Camera.Size previewSize : previewSizes) {
cameraSizes.add(new CameraSize(previewSize.width, previewSize.height));
}
return cameraSizes;
}
return null;
}
@Override
public List<CameraSize> getOutputSizes() {
if (mCamera == null) {
return null;
}
List<Camera.Size> pictureSizes = mCamera.getParameters().getSupportedPictureSizes();
if (pictureSizes == null || pictureSizes.isEmpty()) {
return null;
}
List<CameraSize> outputSize = new ArrayList<>();
for (Camera.Size pictureSize : pictureSizes) {
outputSize.add(new CameraSize(pictureSize.width, pictureSize.height));
}
return outputSize;
}
@Override
public int getOrientation() {
if ("-1".equals(mCurrentCameraId)) {
return 0;
}
Camera.CameraInfo info = new Camera.CameraInfo();
getCameraInfo(Integer.valueOf(mCurrentCameraId), info);
return info.orientation;
}
@Override
public void pause() {
if (mCamera != null) {
mCamera.stopPreview();
}
}
@Override
public void resume() {
if (mCamera != null) {
mCamera.startPreview();
}
}
@Override
public boolean isZoomAvailable() {
if (mCamera == null) {
return false;
}
Camera.Parameters parameters = mCamera.getParameters();
return parameters.isZoomSupported();
}
@Override
public int getZoom() {
if (mCamera != null) {
return mCamera.getParameters().getZoom();
}
return -1;
}
@Override
public void setZoom(int zoomLevel) {
if (mCamera == null || zoomLevel > getMaxZoom()) {
return;
}
try {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setZoom(zoomLevel);
mZoom = zoomLevel;
mCamera.setParameters(parameters);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getMaxZoom() {
if (mMaxZoom == 0) {
mMaxZoom = mCamera.getParameters().getMaxZoom();
}
return mMaxZoom;
}
/**
* reumse camera flash mode when start preview
*/
public Camera.Parameters resumeZoom(Camera.Parameters parameters) {
if (parameters == null) {
return parameters;
}
parameters.setZoom(mZoom);
return parameters;
}
@Override
public int getFlashMode() {
if (mCamera != null) {
return CameraFlashMode.getMode(mCamera.getParameters().getFlashMode());
}
return CameraFlashMode.MODE_UNKNOWN;
}
@Override
public void openFlashMode() {
switchCameraFlashMode(Camera.Parameters.FLASH_MODE_ON);
}
@Override
public void closeFlashMode() {
switchCameraFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}
@Override
public void autoFlashMode() {
switchCameraFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
}
@Override
public void torchFlashMode() {
switchCameraFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
}
/**
* reumse camera flash mode when start preview
*/
public Camera.Parameters resumeFlashMode(Camera.Parameters parameters) {
if (parameters == null) {
return parameters;
}
parameters.setFlashMode(CameraFlashMode.getModeForCamera1(mFlashMode));
return parameters;
}
/**
* switch camera1 flash mode
*
* @param mode
*/
public void switchCameraFlashMode(String mode) {
if (mCamera == null) {
return;
}
try {
mCamera.stopPreview();
Camera.Parameters parameters = mCamera.getParameters();
parameters.setFlashMode(mode);
mCamera.setParameters(parameters);
mCamera.startPreview();
mFlashMode = CameraFlashMode.getMode(mode);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void logFeatures() {
if (mCamera == null) {
SmartCamLog.i(TAG, "Camera is not open");
return;
}
Camera.Parameters parameters = mCamera.getParameters();
// SmartCamLog.i(TAG, "Antibanding:" + parameters.getAntibanding());
// SmartCamLog.i(TAG, "ColorEffect:" + parameters.getColorEffect());
// SmartCamLog.i(TAG, "FlashMode:" + parameters.getFlashMode());
// SmartCamLog.i(TAG, "FocusMode:" + parameters.getFocusMode());
SmartCamLog.i(TAG, "flatten:" + parameters.flatten());
}
@Override
public CameraSize getCompatPreviewSize(int width, int height) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) width / height;
List<CameraSize> previewSizes = getSupportPreviewSizes();
if (previewSizes == null) {
return null;
}
CameraSize optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = height;
for (CameraSize size : previewSizes) {
double ratio = (double) size.getWidth() / size.getHeight();
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) {
continue;
}
if (Math.abs(size.getHeight() - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.getHeight() - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (CameraSize size : previewSizes) {
if (Math.abs(size.getHeight() - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.getHeight() - targetHeight);
}
}
}
return optimalSize;
}
}
|
eugeneilyin/mdi-norm
|
es/SharpBrightness5.js
|
<reponame>eugeneilyin/mdi-norm<filename>es/SharpBrightness5.js<gh_stars>1-10
import { FilledBrightnessLow as SharpBrightness5 } from './FilledBrightnessLow';
export { SharpBrightness5 };
|
78182648/blibli-go
|
app/interface/main/account/dao/account/commercial_test.go
|
package account
import (
"context"
"net/url"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAccountCommercialSign(t *testing.T) {
var (
params = url.Values{}
)
params.Set("appkey", "test")
params.Set("appsecret", "e6c4c252dc7e3d8a90805eecd7c73396")
params.Set("key", "value")
result := url.Values{}
result.Set("appkey", "test")
result.Set("key", "value")
result.Set("sign", "f5c7329e9078e94ebf7d5852dfcd64f9")
convey.Convey("CommercialSign", t, func(ctx convey.C) {
query, err := CommercialSign(params)
ctx.Convey("Then err should be nil.query should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(query, convey.ShouldEqual, result.Encode())
})
})
}
func TestAccountisBusinessAccount(t *testing.T) {
var (
mids = []int64{1, 2, 3}
)
convey.Convey("isBusinessAccount", t, func(ctx convey.C) {
p1, err := d.isBusinessAccount(context.Background(), mids)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
if err != nil {
ctx.Printf("Failed to validate business account: %+v\n", err)
return
}
// ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAccountIsBusinessAccount(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("IsBusinessAccount", t, func(ctx convey.C) {
p1 := d.IsBusinessAccount(context.Background(), mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAccountBusinessAccountInfo(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("BusinessAccountInfo", t, func(ctx convey.C) {
p1, err := d.BusinessAccountInfo(context.Background(), mid)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
if err != nil {
ctx.Printf("Failed to get business account info: %+v\n", err)
return
}
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
|
mgsx-dev/gdx-kit
|
core/src/net/mgsx/game/plugins/camera/CameraPlugin.java
|
package net.mgsx.game.plugins.camera;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.FillViewport;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import net.mgsx.game.core.GameScreen;
import net.mgsx.game.core.annotations.PluginDef;
import net.mgsx.game.core.plugins.Plugin;
import net.mgsx.game.plugins.camera.components.ActiveCamera;
import net.mgsx.game.plugins.camera.components.CameraComponent;
import net.mgsx.game.plugins.camera.components.ViewportComponent;
import net.mgsx.game.plugins.camera.storage.CameraSerializer;
import net.mgsx.game.plugins.camera.storage.ViewportSerializer;
import net.mgsx.game.plugins.camera.systems.CameraSystem;
import net.mgsx.game.plugins.camera.systems.CameraTransformSystem;
@PluginDef(category="graphics", components={
CameraComponent.class, ActiveCamera.class, ViewportComponent.class})
public class CameraPlugin implements Plugin
{
@Override
public void initialize(GameScreen engine)
{
engine.entityEngine.addSystem(new CameraTransformSystem());
engine.entityEngine.addSystem(new CameraSystem(engine));
engine.registry.serializers.put(Camera.class, new CameraSerializer());
engine.registry.serializers.put(PerspectiveCamera.class, new CameraSerializer());
engine.registry.serializers.put(OrthographicCamera.class, new CameraSerializer());
engine.registry.serializers.put(Viewport.class, new ViewportSerializer());
engine.registry.serializers.put(ScreenViewport.class, new ViewportSerializer());
engine.registry.serializers.put(FitViewport.class, new ViewportSerializer());
engine.registry.serializers.put(FillViewport.class, new ViewportSerializer());
engine.registry.serializers.put(StretchViewport.class, new ViewportSerializer());
engine.registry.serializers.put(ExtendViewport.class, new ViewportSerializer());
}
}
|
Shivam-Singh851/egov-coexistence
|
egov/egov-egfweb/src/main/java/org/egov/egf/web/actions/masters/loangrant/LoanGrantBaseAction.java
|
/*
* eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) 2017 eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* 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
* 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/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
* Further, all user interfaces, including but not limited to citizen facing interfaces,
* Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any
* derived works should carry eGovernments Foundation logo on the top right corner.
*
* For the logo, please refer http://egovernments.org/html/logo/egov_logo.png.
* For any further queries on attribution, including queries on brand guidelines,
* please contact <EMAIL>
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at <EMAIL>.
*
*/
package org.egov.egf.web.actions.masters.loangrant;
import org.egov.infra.admin.master.entity.AppConfigValues;
import org.egov.infra.admin.master.service.AppConfigValueService;
import org.egov.infra.web.struts.actions.BaseFormAction;
import org.egov.infstr.utils.EgovMasterDataCaching;
import org.egov.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
public class LoanGrantBaseAction extends BaseFormAction {
private static final long serialVersionUID = -7332696247479705085L;
protected Date fromDate;
protected Date toDate;
protected Integer subSchemeId;
protected Integer schemeId;
protected Integer fundId;
protected @Autowired AppConfigValueService appConfigValuesService;
private Integer defaultFundId;
@Autowired
private EgovMasterDataCaching masterDataCache;
@Override
public void prepare()
{
super.prepare();
// if Fundid is present then it is defaulted else it is made mandatory to select
final List<AppConfigValues> appList = appConfigValuesService.getConfigValuesByModuleAndKey(Constants.EGF,
"loangrant.default.fundid");
final String fundId = appList.get(0).getValue();
if (fundId != null && !fundId.isEmpty())
defaultFundId = Integer.parseInt(fundId);
addDropdownData("fundList", masterDataCache.get("egi-fund"));
}
@Override
public Object getModel() {
return null;
}
public Integer getDefaultFundId() {
return defaultFundId;
}
public void setDefaultFundId(final Integer defaultFundId) {
this.defaultFundId = defaultFundId;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(final Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(final Date toDate) {
this.toDate = toDate;
}
public Integer getSubSchemeId() {
return subSchemeId;
}
public void setSubSchemeId(final Integer subSchemeId) {
this.subSchemeId = subSchemeId;
}
public Integer getSchemeId() {
return schemeId;
}
public void setSchemeId(final Integer schemeId) {
this.schemeId = schemeId;
}
public Integer getFundId() {
return fundId;
}
public void setFundId(final Integer fundId) {
this.fundId = fundId;
}
}
|
substantial/elasticsearch-rails
|
elasticsearch-model/test/unit/searching_test.rb
|
require 'test_helper'
class Elasticsearch::Model::SearchingTest < Test::Unit::TestCase
context "Searching module" do
class ::DummySearchingModel
extend Elasticsearch::Model::Searching::ClassMethods
def self.index_name; 'foo'; end
def self.document_type; 'bar'; end
end
setup do
@client = mock('client')
DummySearchingModel.stubs(:client).returns(@client)
end
should "have the search method" do
assert_respond_to DummySearchingModel, :search
end
should "initialize the search object" do
Elasticsearch::Model::Searching::SearchRequest
.expects(:new).with do |klass, query, options|
assert_equal DummySearchingModel, klass
assert_equal 'foo', query
assert_equal({default_operator: 'AND'}, options)
end
.returns( stub('search') )
DummySearchingModel.search 'foo', default_operator: 'AND'
end
should "not execute the search" do
Elasticsearch::Model::Searching::SearchRequest
.expects(:new).returns( mock('search').expects(:execute!).never )
DummySearchingModel.search 'foo'
end
end
end
|
SquirrelMobile/titanium-template-burger
|
app/lib/db.js
|
<gh_stars>1-10
/**
* @class Lib.db
* database lib
*/
module.exports = Ti.Database.open("datadb");
|
vmittal-msft/sonic-sairedis
|
syncd/ZeroMQNotificationProducer.cpp
|
<reponame>vmittal-msft/sonic-sairedis
#include "ZeroMQNotificationProducer.h"
#include <zmq.h>
using namespace syncd;
ZeroMQNotificationProducer::ZeroMQNotificationProducer(
_In_ const std::string& ntfEndpoint):
m_ntfContext(nullptr),
m_ntfSocket(nullptr)
{
SWSS_LOG_ENTER();
m_ntfContext = zmq_ctx_new();
m_ntfSocket = zmq_socket(m_ntfContext, ZMQ_PUSH);
SWSS_LOG_NOTICE("opening zmq ntf endpoint: %s", ntfEndpoint.c_str());
int rc = zmq_connect(m_ntfSocket, ntfEndpoint.c_str());
if (rc != 0)
{
SWSS_LOG_THROW("failed to open zmq ntf endpoint %s, zmqerrno: %d",
ntfEndpoint.c_str(),
zmq_errno());
}
}
ZeroMQNotificationProducer::~ZeroMQNotificationProducer()
{
SWSS_LOG_ENTER();
zmq_close(m_ntfSocket);
zmq_ctx_destroy(m_ntfContext);
}
void ZeroMQNotificationProducer::send(
_In_ const std::string& op,
_In_ const std::string& data,
_In_ const std::vector<swss::FieldValueTuple>& values)
{
SWSS_LOG_ENTER();
std::vector<swss::FieldValueTuple> vals = values;
swss::FieldValueTuple opdata(op, data);
vals.insert(vals.begin(), opdata);
std::string msg = swss::JSon::buildJson(vals);
SWSS_LOG_DEBUG("sending: %s", msg.c_str());
int rc = zmq_send(m_ntfSocket, msg.c_str(), msg.length(), 0);
if (rc < 0)
{
SWSS_LOG_THROW("zmq_send failed, zmqerrno: %d", zmq_errno());
}
}
|
not522/Competitive-Programming
|
old/AtCoder/agc008/A.cpp
|
<gh_stars>1-10
#include "graph/adjacency_list.hpp"
#include "graph/edge.hpp"
#include "graph/shortest_path.hpp"
int main() {
int x, y;
cin >> x >> y;
AdjacencyList<WeightedEdge<int>> g(4);
g.addUndirectedEdge(0, 1, 1);
g.addUndirectedEdge(2, 3, 1);
int v[] = {abs(x), -abs(x), abs(y), -abs(y)};
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (v[i] <= v[j]) g.addEdge(i, j, v[j] - v[i]);
}
}
cout << shortestPath(g, x > 0 ? 0 : 1, y > 0 ? 2 : 3) << endl;
}
|
francis-pouatcha/forgelab
|
adpharma/adpharma.modules/adpharma.client.core/src/main/java/org/adorsys/adpharma/client/jpa/permissionname/PermissionNameLoadService.java
|
package org.adorsys.adpharma.client.jpa.permissionname;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javax.inject.Inject;
public class PermissionNameLoadService extends Service<PermissionName>
{
@Inject
private PermissionNameService remoteService;
private Long id;
public PermissionNameLoadService setId(Long id)
{
this.id = id;
return this;
}
@Override
protected Task<PermissionName> createTask()
{
return new Task<PermissionName>()
{
@Override
protected PermissionName call() throws Exception
{
if (id == null)
return null;
return remoteService.findById(id);
}
};
}
}
|
BiobankLab/BioFace
|
bioserver/rest-api-bioface/src/main/java/com/bioface/model/ext/UpdateSampleRequest.java
|
package com.bioface.model.ext;
import com.bioface.model.EnumAccess;
public class UpdateSampleRequest {
private String id;
private EnumAccess enumAccess;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public EnumAccess getEnumAccess() {
return enumAccess;
}
public void setEnumAccess(EnumAccess enumAccess) {
this.enumAccess = enumAccess;
}
}
|
darrenhaken/admix
|
spec/unit/admix/mingle/mingle_wall_snapshot_spec.rb
|
<filename>spec/unit/admix/mingle/mingle_wall_snapshot_spec.rb<gh_stars>1-10
require 'rspec'
require_relative '../../../../lib/admix/mingle/mingle_wall_snapshot'
require_relative '../../../../lib/admix/mingle/mingle_card'
RSpec.describe MingleWallSnapshot do
before(:all) do
@xml_path = File.expand_path('../../../../assets/xml/',__FILE__)
@xml_file = @xml_path + '/mingle_wall_snapshot_with_five_cards.xml'
@xml_string = File.read(@xml_file)
@xml_file = @xml_path + '/number_of_card_response.xml'
@xml_live_card = File.read(@xml_file)
end
describe "Initialises MingleWallSnapshot from an XML string" do
before(:each) do
@mingle_wall = MingleWallSnapshot.new(@xml_string, @xml_live_card)
end
it "creates MingleWallSnapshot and returns an array of MingleCard objects" do
expect(@mingle_wall.cards.all? {|card| card.is_a? MingleCard}).to be true
end
it "creates MingleWallSnapshot with empty cards array if XML has no cards" do
@mingle_wall = MingleWallSnapshot.new('', @xml_live_card)
expect(@mingle_wall.cards).to be_nil
end
it "creates MingleWallSnapshot and returns an array of 7 MingleCard objects" do
expect(@mingle_wall.cards.length).to be 7
end
it "creates MingleWallSnapshot and returns an array of 84 as count of live cards" do
expect(@mingle_wall.number_of_live_cards).to be 83
end
end
describe "Returns card statistics based on card property" do
before(:all) do
@mingle_wall = MingleWallSnapshot.new(@xml_string, @xml_live_card)
end
it "return nill when given a Type that is not supported" do
expect(@mingle_wall.number_of_cards_of_type('not supported type')).to be_nil
end
it "always returns 0 for number of cards for a given Type when cards array is empty" do
@mingle_wall = MingleWallSnapshot.new('', @xml_live_card)
expect(@mingle_wall.number_of_cards_of_type('Story')).to eq 0
expect(@mingle_wall.number_of_cards_of_type('Defect')).to eq 0
expect(@mingle_wall.number_of_cards_of_type('Power Ups')).to eq 0
end
it "always returns 0 for number of cards for a given Status when cards array is empty" do
@mingle_wall = MingleWallSnapshot.new('', @xml_live_card)
expect(@mingle_wall.number_of_cards_with_status('Next')).to eq 0
expect(@mingle_wall.number_of_cards_with_status('Dev')).to eq 0
expect(@mingle_wall.number_of_cards_with_status('Dev done')).to eq 0
expect(@mingle_wall.number_of_cards_with_status('A & D')).to eq 0
expect(@mingle_wall.number_of_cards_with_status('A & D done')).to eq 0
expect(@mingle_wall.number_of_cards_with_status('QA')).to eq 0
expect(@mingle_wall.number_of_cards_with_status('QA done')).to eq 0
end
it "returns 4 as number of cards of type Story" do
expect(@mingle_wall.number_of_cards_of_type('Story')).to eq 4
end
it "returns 2 as number of cards of type Story" do
expect(@mingle_wall.number_of_cards_of_type('Defect')).to eq 2
end
it "returns 1 as number of cards of type Story" do
expect(@mingle_wall.number_of_cards_of_type('Power Ups')).to eq 1
end
it "returns 0 when no cards for the given Type is not found" do
expect(@mingle_wall.number_of_cards_of_type('TWS Content')).to eq 0
end
it "return nill when given a Status that is not supported" do
expect(@mingle_wall.number_of_cards_with_status('not supported status')).to be_nil
end
it "return 3 as number of cards in Status 'Next'" do
expect(@mingle_wall.number_of_cards_with_status('Next')).to be 3
end
it "return 2 as number of cards in Status 'Dev done'" do
expect(@mingle_wall.number_of_cards_with_status('Dev done')).to be 2
end
it "return 1 as number of cards in Status 'Dev'" do
expect(@mingle_wall.number_of_cards_with_status('Dev')).to be 1
end
it "return 0 when no cards for the given Status is not found" do
expect(@mingle_wall.number_of_cards_with_status('A & D')).to be 0
end
end
end
|
Corban10/pw-backend
|
portfolio/models.py
|
import datetime
from django.db import models
from django.utils import timezone
class Category(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def was_updated(self):
return self.updated_at >= self.created_at
class Skill(models.Model):
name = models.CharField(max_length=100)
link = models.CharField(max_length=100, default="#")
icon = models.FileField(upload_to="./skill")
def __str__(self):
return self.name
class Social(models.Model):
name = models.CharField(max_length=100)
link = models.CharField(max_length=100, default="#")
icon = models.FileField(upload_to="./social")
def __str__(self):
return self.name
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
github = models.CharField(max_length=100, blank=True, null=True)
url = models.CharField(max_length=100, blank=True, null=True)
show = models.BooleanField(default=False)
date = models.DateField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.description
def was_updated(self):
return self.updated_at >= self.created_at
class ProjectImage(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
image = models.ImageField(upload_to="./project")
class BlogPost(models.Model):
content = models.TextField()
slug = models.CharField(max_length=100)
desc = models.TextField()
date = models.DateField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.desc
def was_updated(self):
return self.updated_at >= self.created_at
class BlogPostImage(models.Model):
blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
image = models.ImageField(upload_to="./blog")
|
Multiface24111/hata
|
docs/examples/e03_utilities/main.py
|
<gh_stars>100-1000
from hata import Client
TOKEN = ''
Sakuya = Client(TOKEN)
@Sakuya.events
async def message_create(client, message):
if message.content == '!messageme':
# Client class has many useful high level methods implemented, so you do not need to deal with low level "rest"
# calls. Usually each high level `Client` method has a low level http method as well. Lets take
# `Client.message_create(...)` and it's low level `Client.http.message_create(...)` methods as examples.
#
# You cannot call api methods on simple `User` instances, since if you have multiple clients it won't know
# which client to use thus it should not decide which one to use - you need to specify the client.
channel = await client.channel_private_create(message.author)
await client.message_create(channel, 'Hello!')
@Sakuya.events
async def ready(client):
print(f'{client:f} is connected!')
Sakuya.start()
|
hemanshuchauhan/argos
|
src/review/modules/components/ProductHeader.js
|
<reponame>hemanshuchauhan/argos<filename>src/review/modules/components/ProductHeader.js
import React from 'react'
import PropTypes from 'prop-types'
import { withStyles } from 'material-ui/styles'
import Typography from 'material-ui/Typography'
import Paper from 'material-ui/Paper'
import LayoutBody from 'modules/components/LayoutBody'
const styles = theme => ({
root: {
minHeight: 300,
display: 'flex',
alignItems: 'center',
overflow: 'hidden',
},
wrapper: {
position: 'relative',
},
text: {
position: 'relative',
zIndex: 1,
},
headline: {
maxWidth: 500, // Don't use more space than the title.
marginBottom: theme.spacing.unit * 3,
},
})
function ProductHeader(props) {
const { beast, classes, children, display1, headline } = props
return (
<Paper component="header" square elevation={0} className={classes.root}>
<LayoutBody margin className={classes.wrapper}>
<div className={classes.text}>
<Typography variant="display1" component="h1" gutterBottom>
{display1}
</Typography>
<Typography
variant="headline"
component="h2"
className={classes.headline}
>
{headline}
</Typography>
{children}
</div>
{beast}
</LayoutBody>
</Paper>
)
}
ProductHeader.propTypes = {
beast: PropTypes.node,
children: PropTypes.node,
classes: PropTypes.object.isRequired,
display1: PropTypes.node.isRequired,
headline: PropTypes.node,
}
export default withStyles(styles)(ProductHeader)
|
opatomic/opac-c
|
src/opabuff.h
|
/*
* Copyright 2018-2019 Opatomic
* Open sourced with ISC license. Refer to LICENSE for details.
*/
#ifndef OPABUFF_H_
#define OPABUFF_H_
#include <stddef.h>
#include <stdint.h>
/**
* Try to lock allocation in memory and disable paging to disk. If an error occurs
* when locking the underlying allocation to memory, the error is silently ignored
* (unless OPABUFF_F_MLOCKERR flag is specified).
*/
#define OPABUFF_F_NOPAGING 0x02
/**
* Zero all used bytes when growing/shrinking/freeing data in buffer
* note: if buffer needs to grow then it must be allocated to a new address and the
* original allocation is zero'd which will be slower than using realloc
* note: if program crashes then memory will not be zero'd TODO?
*/
#define OPABUFF_F_ZERO 0x04
/**
* Return an error if OPABUFF_F_NOPAGING is enabled and cannot lock allocation into RAM
*/
#define OPABUFF_F_MLOCKERR 0x08
typedef struct {
uint8_t* data;
size_t len;
size_t cap;
unsigned int flags;
} opabuff;
/**
* Initialize a new buff and attempt to allocate enough memory to hold specified length.
* Will return a zero-capacity buffer if memory allocation error occurs.
*/
opabuff opabuffNew(size_t len);
/**
* Initialize a buff with specified flags. Pass 0 for flags to use default behavior
*/
void opabuffInit(opabuff* b, unsigned int flags);
/**
* Get a pointer to the underlying data at specified position. Return NULL if pos is greater
* than length of this buffer.
*/
uint8_t* opabuffGetPos(const opabuff* b, size_t pos);
/**
* Get the length of this buffer
*/
size_t opabuffGetLen(const opabuff* b);
/**
* Set the length of the used bytes in the buffer. If length is increasing then new bytes
* are not initialized (can be any random value).
* @return an error code if enough memory could not be allocated; else 0
*/
int opabuffSetLen(opabuff* b, size_t newlen);
/**
* Append specified bytes to the end of the buffer.
* @return an error code if enough memory could not be allocated; else 0
*/
int opabuffAppend(opabuff* b, const void* src, size_t srcLen);
/**
* Append a single byte to end of buffer
* @return an error code if enough memory could not be allocated; else 0
*/
int opabuffAppend1(opabuff* b, uint8_t v);
/**
* In case buffer allocated more memory than needed: try to realloc underlying memory so that it
* only uses enough to store the length of this buff.
*/
void opabuffRemoveFreeSpace(opabuff* b);
/**
* Free all memory associated with this buffer. Buffer length is set to zero.
* Buffer can be re-used.
*/
void opabuffFree(opabuff* b);
#endif
|
slt0111/jeeweb
|
jeeweb-web/jeeweb-generator/src/main/java/cn/jeeweb/generator/common/constant/Constants.java
|
<gh_stars>1-10
package cn.jeeweb.generator.common.constant;
public class Constants {
// 登陆成功关键字
public static final String LOGIN_SUCCES_KEY = "login_succes_key";
//错误消息
public static final String ERROR_MSG_KEY = "error";
}
|
mentaljam/msugeo
|
library/src/msutriangle.cpp
|
<filename>library/src/msutriangle.cpp
#include "msutriangle.h"
msumr::Triangle::Triangle(GCP &vertex1, GCP &vertex2, GCP &vertex3) :
mVertex0(&vertex1)
{
double x10, x20, y10, y20, z10R, z20R, z10L, z20L;
x10 = vertex2.lon - vertex1.lon;
x20 = vertex3.lon - vertex1.lon;
y10 = vertex2.lat - vertex1.lat;
y20 = vertex3.lat - vertex1.lat;
z10R = vertex2.x - vertex1.x;
z20R = vertex3.x - vertex1.x;
z10L = vertex2.y - vertex1.y;
z20L = vertex3.y - vertex1.y;
mACol = y10 * z20R - z10R * y20;
mBCol = x10 * z20R - x20 * z10R;
mARow = y10 * z20L - z10L * y20;
mBRow = x10 * z20L - x20 * z10L;
mC = x10 * y20 - x20 * y10;
}
void msumr::Triangle::sourceCoordinates(const double &dst_x, const double &dst_y,
double *src_x, double *src_y) const
{
double deltaX = dst_x - mVertex0->lon;
double deltaY = dst_y - mVertex0->lat;
*src_x = mVertex0->x - (deltaX * mACol - deltaY * mBCol) / mC;
*src_y = mVertex0->y - (deltaX * mARow - deltaY * mBRow) / mC;
}
|
jamhocken/aoc-2020
|
day17/python/jamhocken/solution.py
|
def process_input(file_contents):
temp = dict()
for i, line in enumerate(file_contents):
for j, seat in enumerate(line):
if seat != '\n':
temp.update({(0,0,i,j) : seat})
return temp, len(file_contents)
# Helper function to visualize room in the command line
def visualize_room(data,max_column,round_no):
temp_list = sorted(data)
for (z,w,x,y) in temp_list:
if y == max_column:
print(data[z,w,x,y])
if (x == max_column):
print('z=', z, 'w=', w,'\n')
else: print(data[z,w,x,y],end='')
print('')
def automat(dictionary,cycles,problem):
keys = max(dictionary.keys())
max_z = keys[0]
max_row = keys[2]
min_row = 0
max_column = keys[3]
min_column = 0
for cycle in range(cycles):
for z in range(-1*max_z,max_z+1):
for w in range(-1*max_z,max_z+1):
for x in range(min_row-1,max_row+2):
dictionary.update({(z,w,x,min_column-1) : '.'})
dictionary.update({(z,w,x,max_column+1) : '.'})
for y in range(min_column-1,max_column+2):
dictionary.update({(z,w,min_row-1,y) : '.'})
dictionary.update({(z,w,max_row+1,y) : '.'})
for z in [-1*max_z-1, max_z+1]:
for x in range(min_row-1,max_row+2):
for y in range(min_column-1,max_column+2):
for w in range(-1*max_z-1,max_z+2):
dictionary.update({(z,w,x,y) : '.'})
for w in [-1*max_z-1, max_z+1]:
for x in range(min_row-1,max_row+2):
for y in range(min_column-1,max_column+2):
for z in range(-1*max_z-1,max_z+2):
dictionary.update({(z,w,x,y) : '.'})
max_z += 1
max_row += 1
min_row -= 1
max_column += 1
min_column -= 1
dict_temp = dictionary.copy()
for key, value in dictionary.items():
if problem == 1: max_w = 0
else: max_w = max_z
neighbors = find_neighbors(dictionary,key,max_row,max_column,min_row,min_column,max_z,max_w)
if sum(neighbors) == 3:
dict_temp.update({key : '#'})
elif value == '#' and sum(neighbors) == 2:
dict_temp.update({key:'#'})
else: dict_temp.update({key:'.'})
dictionary = dict_temp.copy()
return dictionary
def find_neighbors(dictionary,key,max_row,max_column,min_row,min_column,max_z,max_w):
vectors = list()
for i in range(-1,2):
for j in range(-1,2):
for k in range(-1,2):
for l in range(-1,2):
vectors.append([i,j,k,l])
neighbors = list()
for vector in vectors:
new_key = tuple([a + b for a, b in zip(list(key), vector)])
if new_key[2] > max_row or new_key[2] < min_row or \
new_key[3] > max_column or new_key[3] < min_column or \
vector == [0,0,0,0] or \
new_key[0] < -1*max_z or new_key[0]>max_z or \
new_key[1] < -1*max_w or new_key[1]>max_w:
neighbors.append(0)
else:
if dictionary[new_key] == '#': neighbors.append(1)
else: neighbors.append(0)
return neighbors
with open("input.txt",'r') as code_file:
all_code_file = code_file.readlines()
initial_dimension, initial_size = process_input(all_code_file)
final_space1 = automat(initial_dimension.copy(), 6, 1)
count1 = 0
for key,value in final_space1.items():
if value == '#' and key[1]==0: count1 += 1
print(count1,'cubes are left in the active state after the sixth cycle in 3D problem.')
final_space2 = automat(initial_dimension.copy(), 6, 2)
count2 = 0
for key,value in final_space2.items():
if value == '#': count2 += 1
print(count2,'cubes are left in the active state after the sixth cycle in 4D problem.')
|
aitmlouk/stackn
|
components/studio/monitor/dash_demo.py
|
import uuid
import random
import requests
from datetime import datetime
from django.core.cache import cache
import dash
from dash.dependencies import MATCH, ALL
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dpd_components as dpd
from dash.exceptions import PreventUpdate
from django_plotly_dash import DjangoDash
from django_plotly_dash.consumers import send_to_pipe_channel
import pymongo
from projects.models import Project
from apps.models import AppInstance, Apps
app = DjangoDash("FEDnDashboard")
menu = html.Div([
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardBody([
dbc.Select(
id="reducer-select",
options=[],
className="form-control"
)
])
])
], className="col-4"),
dbc.Col(id="reducer-state", className="col-2")
]),
dbc.Row(id="submenu")
])
main = dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardBody([
html.H4("Combiners", className="card-title"),
dbc.Table([
html.Thead([
html.Tr([
html.Th("Name"),
html.Th("Active Clients"),
html.Th("IP"),
html.Th("Country"),
html.Th("Region"),
html.Th("City")
])
]),
html.Tbody([
], id="combiner-info-table")
])
])
]),
dbc.Card([
dbc.CardBody([
html.H4("Round Time", className="card-title"),
dcc.Graph(id="combiners-round-plot"),
])
]),
dbc.Card([
dbc.CardBody([
html.H4("Combiner Load", className="card-title"),
dcc.Graph(id="combiners-combiner-plot"),
])
]),
dbc.Card([
dbc.CardBody([
html.H4("Controller MEM and CPU Monitoring", className="card-title"),
dcc.Graph(id="combiners-memcpu-plot"),
])
])
])
])
app.layout = html.Div([menu, main])
@app.callback(
Output(component_id='combiner-info-table', component_property='children'),
Output(component_id='combiners-round-plot', component_property='figure'),
Output(component_id='combiners-combiner-plot', component_property='figure'),
Output(component_id='combiners-memcpu-plot', component_property='figure'),
Output(component_id='reducer-state', component_property='children'),
Output(component_id='reducer-select', component_property='options'),
Input(component_id='reducer-select', component_property='value')
)
def reducer_select(red_select, request):
if 'current_project' in request.session:
project_slug = request.session['current_project']
else:
raise PreventUpdate()
reducer_app = Apps.objects.get(slug='reducer')
this_project = Project.objects.get(slug=project_slug)
reducers = AppInstance.objects.filter(app=reducer_app, project=this_project)
options = []
for reducer in reducers:
options.append({"label": reducer.name, "value": str(reducer.pk)})
combiners_info = []
roundplot = {}
combinerplot = {}
memcpuplot = {}
state = ""
if red_select != None:
# TODO: Check that user has access to project.
sel_reducer = AppInstance.objects.get(pk=red_select, project__slug=project_slug)
reducer_params = sel_reducer.parameters
r_host = reducer_params['release']
r_domain = reducer_params['global']['domain']
# mongodb_params = reducer_params['apps']['mongodb']
# mdb_name = list(mongodb_params.keys())[0]
# mdb_host = mongodb_params[mdb_name]['release']
# mdb_domain = mongodb_params[mdb_name]['global']['domain']
#
# creds = mongodb_params[mdb_name]['credentials']
# client = pymongo.MongoClient('mongodb://{}:{}@{}:27017'.format(creds['username'], creds['password'], mdb_host))
# fndb = client['fedn-network']
# combiners = fndb['network.combiners']
# cursor = combiners.find({})
# for document in cursor:
# print(document)
try:
url = 'https://{}.{}/api/state'.format(r_host, r_domain)
res = requests.get(url, verify=False)
current_state = res.json()['state']
except Exception as err:
print(err)
state = dbc.Card([
dbc.CardBody(current_state)
])
try:
url = 'https://{}.{}/api/combiners/info'.format(r_host, r_domain)
print(url)
res = requests.get(url, verify=False)
combiners_raw = res.json()
except Exception as err:
print(err)
for combiner_raw in combiners_raw:
row = [
html.Td(combiner_raw['name']),
html.Td(combiner_raw['nr_active_clients']),
html.Td(combiner_raw['ip']),
html.Td(combiner_raw['country']),
html.Td(combiner_raw['region']),
html.Td(combiner_raw['city'])
]
combiners_info.append(html.Tr(row))
try:
url = 'https://{}.{}/api/combiners/roundplot'.format(r_host, r_domain)
print(url)
res = requests.get(url, verify=False)
roundplot = res.json()
except Exception as err:
print(err)
try:
url = 'https://{}.{}/api/combiners/combinerplot'.format(r_host, r_domain)
print(url)
res = requests.get(url, verify=False)
combinerplot = res.json()
except Exception as err:
print(err)
try:
url = 'https://{}.{}/api/combiners/memcpuplot'.format(r_host, r_domain)
print(url)
res = requests.get(url, verify=False)
memcpuplot = res.json()
except Exception as err:
print(err)
return combiners_info, roundplot, combinerplot, memcpuplot, state, options
|
sergeiWizard/waitio-test
|
src/client/components/Navigation/SocialButtons/SocialButtons.js
|
import React from 'react';
import { GoogleLogin } from 'react-google-login';
import FacebookLogin from 'react-facebook-login';
import { Icon } from 'antd';
import PropTypes from 'prop-types';
const SocialButtons = ({ responseSocial, className }) => (
<div className={className}>
<GoogleLogin
buttonText="Google"
clientId="623736583769-qlg46kt2o7gc4kjd2l90nscitf38vl5t.apps.googleusercontent.com"
onSuccess={response => responseSocial(response, 'google')}
onFailure={() => {}}
cookiePolicy={'single_host_origin'}
className="ModalSignUp__social-btn"
/>
<FacebookLogin
appId="754038848413420"
autoLoad={false}
fields="name,email,picture"
callback={response => responseSocial(response, 'facebook')}
onFailure={() => {}}
textButton="Facebook"
cssClass="ModalSignUp__social-btn ModalSignUp__social-btn--fb"
icon={<Icon type="facebook" className="ModalSignUp__icon-fb" />}
disableMobileRedirect
/>
</div>
);
SocialButtons.propTypes = {
responseSocial: PropTypes.func,
className: PropTypes.string,
};
SocialButtons.defaultProps = {
responseSocial: () => {},
className: '',
};
export default SocialButtons;
|
tonihenriques/GestaoSST
|
SESTEC/GISWeb/Scripts/Custom/DocumentosPessoal/Excluir.js
|
<filename>SESTEC/GISWeb/Scripts/Custom/DocumentosPessoal/Excluir.js<gh_stars>0
function DeletarDocumento(IDDocumento,Nome) {
var callback = function () {
$('.LoadingLayout').show();
$('#dynamic-table').css({ opacity: "0.5" });
$.ajax({
method: "POST",
url: "/DocumentosPessoal/TerminarComRedirect",
data: { IDDocumentosEmpregado: IDDocumento, NomeDocumento: Nome },
error: function (erro) {
$(".LoadingLayout").hide();
$("#dynamic-table").css({ opacity: '' });
ExibirMensagemGritter('Oops! Erro inesperado', erro.responseText, 'gritter-error')
},
success: function (content) {
$('.LoadingLayout').hide();
$("#dynamic-table").css({ opacity: '' });
TratarResultadoJSON(content.resultado);
if (content.resultado.Sucesso !== null && content.resultado.Sucesso !== "") {
$("#linha-" + IDDocumentosEmpregado).remove();
}
}
});
};
ExibirMensagemDeConfirmacaoSimples("Tem certeza que deseja excluir este Documento '" + Nome + "'?", "Exclusão de Documento", callback, "btn-danger");
}
|
SWuchterl/cmssw
|
ElectroWeakAnalysis/ZEE/python/simpleCutBasedSpring10SelectionBlocks_cfi.py
|
import FWCore.ParameterSet.Config as cms
#########################################################
## 95%
selection_95relIso = cms.PSet (
trackIso_EB = cms.untracked.double(1.5e-01),
ecalIso_EB = cms.untracked.double(2.0e+00),
hcalIso_EB = cms.untracked.double(1.2e-01),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(8.0e-01),
deta_EB = cms.untracked.double(7.0e-03),
hoe_EB = cms.untracked.double(1.5e-01),
cIso_EB = cms.untracked.double(10000.),
trackIso_EE = cms.untracked.double(8.0e-02),
ecalIso_EE = cms.untracked.double(6.0e-02),
hcalIso_EE = cms.untracked.double(5.0e-02),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(7.0e-01),
deta_EE = cms.untracked.double(1.0e-02),
hoe_EE = cms.untracked.double(7.0e-02),
cIso_EE = cms.untracked.double(10000. ),
useConversionRejection = cms.untracked.bool(False),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(1),
)
selection_95cIso = cms.PSet (
trackIso_EB = cms.untracked.double(100000.),
ecalIso_EB = cms.untracked.double(100000.),
hcalIso_EB = cms.untracked.double(100000.),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(8.0e-01),
deta_EB = cms.untracked.double(7.0e-03),
hoe_EB = cms.untracked.double(1.5e-01),
cIso_EB = cms.untracked.double(1.5e-01),
trackIso_EE = cms.untracked.double(100000.),
ecalIso_EE = cms.untracked.double(100000.),
hcalIso_EE = cms.untracked.double(100000.),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(7.0e-01),
deta_EE = cms.untracked.double(1.0e-02),
hoe_EE = cms.untracked.double(7.0e-02),
cIso_EE = cms.untracked.double(1.0e-01),
useConversionRejection = cms.untracked.bool(False),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(1),
)
#########################################################
## 90%
selection_90relIso = cms.PSet (
trackIso_EB = cms.untracked.double(1.2e-01),
ecalIso_EB = cms.untracked.double(9.0e-02),
hcalIso_EB = cms.untracked.double(1.0e-01),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(8.0e-01),
deta_EB = cms.untracked.double(7.0e-03),
hoe_EB = cms.untracked.double(1.2e-01),
cIso_EB = cms.untracked.double(10000. ),
trackIso_EE = cms.untracked.double(5.0e-02),
ecalIso_EE = cms.untracked.double(6.0e-02),
hcalIso_EE = cms.untracked.double(3.0e-02),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(7.0e-01),
deta_EE = cms.untracked.double(9.0e-03),
hoe_EE = cms.untracked.double(5.0e-02),
cIso_EE = cms.untracked.double(10000. ),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(1),
)
selection_90cIso = cms.PSet (
trackIso_EB = cms.untracked.double(100000.),
ecalIso_EB = cms.untracked.double(100000.),
hcalIso_EB = cms.untracked.double(100000.),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(8.0e-01),
deta_EB = cms.untracked.double(7.0e-03),
hoe_EB = cms.untracked.double(1.2e-01),
cIso_EB = cms.untracked.double(1.0e-01),
trackIso_EE = cms.untracked.double(100000.),
ecalIso_EE = cms.untracked.double(100000.),
hcalIso_EE = cms.untracked.double(100000.),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(7.0e-01),
deta_EE = cms.untracked.double(9.0e-03),
hoe_EE = cms.untracked.double(5.0e-02),
cIso_EE = cms.untracked.double(7.0e-02),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(1),
)
#########################################################
## 85%
selection_85relIso = cms.PSet (
trackIso_EB = cms.untracked.double(9.0e-02),
ecalIso_EB = cms.untracked.double(8.0e-02),
hcalIso_EB = cms.untracked.double(1.0e-01),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(6.0e-02),
deta_EB = cms.untracked.double(6.0e-03),
hoe_EB = cms.untracked.double(4.0e-02),
cIso_EB = cms.untracked.double(10000. ),
trackIso_EE = cms.untracked.double(5.0e-02),
ecalIso_EE = cms.untracked.double(5.0e-02),
hcalIso_EE = cms.untracked.double(2.5e-02),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(4.0e-02),
deta_EE = cms.untracked.double(7.0e-03),
hoe_EE = cms.untracked.double(2.5e-02),
cIso_EE = cms.untracked.double(10000. ),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(1),
)
selection_85cIso = cms.PSet (
trackIso_EB = cms.untracked.double(100000.),
ecalIso_EB = cms.untracked.double(100000.),
hcalIso_EB = cms.untracked.double(100000.),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(6.0e-02),
deta_EB = cms.untracked.double(6.0e-03),
hoe_EB = cms.untracked.double(4.0e-02),
cIso_EB = cms.untracked.double(9.0e-02),
trackIso_EE = cms.untracked.double(100000.),
ecalIso_EE = cms.untracked.double(100000.),
hcalIso_EE = cms.untracked.double(100000.),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(4.0e-02),
deta_EE = cms.untracked.double(7.0e-03),
hoe_EE = cms.untracked.double(2.5e-02),
cIso_EE = cms.untracked.double(6.0e-02),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(1),
)
#########################################################
## 80%
selection_80relIso = cms.PSet (
trackIso_EB = cms.untracked.double(9.0e-02),
ecalIso_EB = cms.untracked.double(7.0e-02),
hcalIso_EB = cms.untracked.double(1.0e-01),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(6.0e-02),
deta_EB = cms.untracked.double(4.0e-03),
hoe_EB = cms.untracked.double(4.0e-02),
cIso_EB = cms.untracked.double(100000.),
trackIso_EE = cms.untracked.double(4.0e-02),
ecalIso_EE = cms.untracked.double(5.0e-02),
hcalIso_EE = cms.untracked.double(2.5e-02),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(3.0e-02),
deta_EE = cms.untracked.double(7.0e-03),
hoe_EE = cms.untracked.double(2.5e-02),
cIso_EE = cms.untracked.double(100000.),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(0),
)
selection_80cIso = cms.PSet (
trackIso_EB = cms.untracked.double(100000.),
ecalIso_EB = cms.untracked.double(100000.),
hcalIso_EB = cms.untracked.double(100000.),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(6.0e-02),
deta_EB = cms.untracked.double(4.0e-03),
hoe_EB = cms.untracked.double(4.0e-02),
cIso_EB = cms.untracked.double(7.0e-02),
trackIso_EE = cms.untracked.double(100000.),
ecalIso_EE = cms.untracked.double(100000.),
hcalIso_EE = cms.untracked.double(100000.),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(3.0e-02),
deta_EE = cms.untracked.double(7.0e-03),
hoe_EE = cms.untracked.double(2.5e-02),
cIso_EE = cms.untracked.double(6.0e-02),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(0),
)
#########################################################
## 70% corrected with lower limits to cut values
selection_70relIso = cms.PSet (
trackIso_EB = cms.untracked.double(5.0e-02),
ecalIso_EB = cms.untracked.double(6.0e-02),
hcalIso_EB = cms.untracked.double(3.0e-02),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(3.0e-02),
deta_EB = cms.untracked.double(4.0e-03),
hoe_EB = cms.untracked.double(2.5e-02),
cIso_EB = cms.untracked.double(100000.),
trackIso_EE = cms.untracked.double(2.5e-02),
ecalIso_EE = cms.untracked.double(2.5e-02),
hcalIso_EE = cms.untracked.double(2.0e-02),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(2.0e-02),
deta_EE = cms.untracked.double(5.0e-03),
hoe_EE = cms.untracked.double(2.5e-02),
cIso_EE = cms.untracked.double(100000.),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(0),
)
selection_70cIso = cms.PSet (
trackIso_EB = cms.untracked.double(100000.),
ecalIso_EB = cms.untracked.double(100000.),
hcalIso_EB = cms.untracked.double(100000.),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(3.0e-02),
deta_EB = cms.untracked.double(4.0e-03),
hoe_EB = cms.untracked.double(2.5e-02),
cIso_EB = cms.untracked.double(4.0e-02),
trackIso_EE = cms.untracked.double(100000.),
ecalIso_EE = cms.untracked.double(100000.),
hcalIso_EE = cms.untracked.double(100000.),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(2.0e-02),
deta_EE = cms.untracked.double(5.0e-03),
hoe_EE = cms.untracked.double(2.5e-02),
cIso_EE = cms.untracked.double(3.0e-02),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(0),
)
#########################################################
## 60% corrected with lower limits to cut values
selection_60relIso = cms.PSet (
trackIso_EB = cms.untracked.double(4.0e-02),
ecalIso_EB = cms.untracked.double(4.0e-02),
hcalIso_EB = cms.untracked.double(3.0e-02),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(2.5e-02),
deta_EB = cms.untracked.double(4.0e-03),
hoe_EB = cms.untracked.double(2.5e-02),
cIso_EB = cms.untracked.double(100000.),
trackIso_EE = cms.untracked.double(2.5e-02),
ecalIso_EE = cms.untracked.double(2.0e-02),
hcalIso_EE = cms.untracked.double(2.0e-02),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(2.0e-02),
deta_EE = cms.untracked.double(5.0e-03),
hoe_EE = cms.untracked.double(2.5e-02),
cIso_EE = cms.untracked.double(100000.),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(0),
)
selection_60cIso = cms.PSet (
trackIso_EB = cms.untracked.double(100000.),
ecalIso_EB = cms.untracked.double(100000.),
hcalIso_EB = cms.untracked.double(100000.),
sihih_EB = cms.untracked.double(1.0e-02),
dphi_EB = cms.untracked.double(2.5e-02),
deta_EB = cms.untracked.double(4.0e-03),
hoe_EB = cms.untracked.double(2.5e-02),
cIso_EB = cms.untracked.double(3.0e-02),
trackIso_EE = cms.untracked.double(100000.),
ecalIso_EE = cms.untracked.double(100000.),
hcalIso_EE = cms.untracked.double(100000.),
sihih_EE = cms.untracked.double(3.0e-02),
dphi_EE = cms.untracked.double(2.0e-02),
deta_EE = cms.untracked.double(5.0e-03),
hoe_EE = cms.untracked.double(2.5e-02),
cIso_EE = cms.untracked.double(2.0e-02),
useConversionRejection = cms.untracked.bool(True),
useExpectedMissingHits = cms.untracked.bool(True),
maxNumberOfExpectedMissingHits = cms.untracked.int32(0),
)
#########################################################
|
munharsha/tp
|
src/main/java/seedu/address/logic/commands/sellercommands/DeleteSellerCommand.java
|
<reponame>munharsha/tp
package seedu.address.logic.commands.sellercommands;
import static java.util.Objects.requireNonNull;
import java.util.List;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.index.Index;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.CommandResult;
import seedu.address.logic.commands.EntityType;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.Model;
import seedu.address.model.person.seller.Seller;
/**
* Deletes a person identified using it's displayed index from the address book.
*/
public class DeleteSellerCommand extends Command {
public static final String COMMAND_WORD = "delete-s";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Deletes the seller identified by the index number used in the displayed seller list.\n"
+ "\n\nParameters: \nINDEX (must be a positive integer)\n"
+ "\n\nExample: " + COMMAND_WORD + " 1";
public static final String MESSAGE_DELETE_SELLER_SUCCESS = "Deleted Seller: %1$s"
+ "\nAll related properties and meetings have been deleted.\"";
private final Index targetIndex;
public DeleteSellerCommand(Index targetIndex) {
this.targetIndex = targetIndex;
}
@Override
public CommandResult execute(Model model) throws CommandException {
requireNonNull(model);
List<Seller> lastShownList = model.getFilteredSellerList();
if (targetIndex.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_SELLER_DISPLAYED_INDEX);
}
Seller sellerToDelete = lastShownList.get(targetIndex.getZeroBased());
model.deleteSeller(sellerToDelete);
return new CommandResult(String.format(MESSAGE_DELETE_SELLER_SUCCESS, sellerToDelete))
.setEntity(EntityType.SELLER);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof DeleteSellerCommand // instanceof handles nulls
&& targetIndex.equals(((DeleteSellerCommand) other).targetIndex)); // state check
}
}
|
chenying-wang/Tank-Game
|
js/util/vector.js
|
<gh_stars>1-10
"use strict"
class Vector {
constructor(arg1 = 0, arg2 = 0) {
if (arg1 instanceof Vector) {
this.x = arg1.x
this.y = arg1.y
} else {
this.x = arg1
this.y = arg2
}
}
static new(...args) {
return new this(...args)
}
set(arg1 = 0, arg2 = 0) {
if (arg1 instanceof Vector) {
this.x = arg1.x
this.y = arg1.y
} else {
this.x = arg1
this.y = arg2
}
return this
}
setLengthAngle(length, angle) {
let angleRad = angle * Math.PI / 180
this.x = length * Math.sin(angleRad)
this.y = length * Math.cos(angleRad)
return this.round()
}
setLength(length) {
this.setLengthAngle(length, this.angle())
return this.round()
}
setAngle(angle) {
this.setLengthAngle(this.length(), angle)
return this.round()
}
add(vector) {
return Vector.new(this).addEqual(vector)
}
minus(vector) {
return Vector.new(this).minusEqual(vector)
}
multiply(factor) {
return Vector.new(this).multiplyEqual(factor)
}
addEqual(vector) {
this.x += vector.x
this.y += vector.y
return this
}
minusEqual(vector) {
this.x -= vector.x
this.y -= vector.y
return this
}
multiplyEqual(factor) {
this.x *= factor
this.y *= factor
return this.round()
}
round() {
this.x = Math.round(this.x * 1000) / 1000
this.y = Math.round(this.y * 1000) / 1000
return this
}
length(vector) {
let v = this
if(vector instanceof Vector) v = vector.minus(v)
let l = v.x ** 2 + v.y ** 2
l = Math.sqrt(l)
return l
}
angle(vector) {
let v = this
if(vector instanceof Vector) v = vector.minus(v)
let a = Math.atan2(v.x, v.y) * 180 / Math.PI
a = (a + 360) % 360
return a
}
unit() {
return Vector.new(this).multiply(1 / this.length())
}
dot(a11, a12, a21, a22) {
let result = Vector.new()
result.x = Math.round(a11 * this.x + a12 * this.y)
result.y = Math.round(a21 * this.x + a22 * this.y)
return result.round()
}
}
|
phatblat/macOSPrivateFrameworks
|
PrivateFrameworks/AVConference/VCMediaNegotiationBlobVideoRuleCollection.h
|
<filename>PrivateFrameworks/AVConference/VCMediaNegotiationBlobVideoRuleCollection.h
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "PBCodable.h"
#import "NSCopying.h"
__attribute__((visibility("hidden")))
@interface VCMediaNegotiationBlobVideoRuleCollection : PBCodable <NSCopying>
{
unsigned int _formats;
int _operation;
unsigned int _preferredFormat;
int _transport;
struct {
unsigned int preferredFormat:1;
} _has;
}
@property(nonatomic) unsigned int preferredFormat; // @synthesize preferredFormat=_preferredFormat;
@property(nonatomic) unsigned int formats; // @synthesize formats=_formats;
@property(nonatomic) int operation; // @synthesize operation=_operation;
@property(nonatomic) int transport; // @synthesize transport=_transport;
- (void)mergeFrom:(id)arg1;
- (unsigned long long)hash;
- (BOOL)isEqual:(id)arg1;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (void)copyTo:(id)arg1;
- (void)writeTo:(id)arg1;
- (BOOL)readFrom:(id)arg1;
- (id)dictionaryRepresentation;
- (id)description;
@property(nonatomic) BOOL hasPreferredFormat;
- (int)StringAsOperation:(id)arg1;
- (id)operationAsString:(int)arg1;
- (int)StringAsTransport:(id)arg1;
- (id)transportAsString:(int)arg1;
@end
|
Simsch/jproperties
|
src/main/java/de/simsch/core/PropertyFileNotFoundException.java
|
package de.simsch.core;
/**
* @author simsch
*/
public class PropertyFileNotFoundException extends RuntimeException {
public PropertyFileNotFoundException() {
}
public PropertyFileNotFoundException(String message) {
super(message);
}
public PropertyFileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public PropertyFileNotFoundException(Throwable cause) {
super(cause);
}
public PropertyFileNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
NLeSC/Platinum
|
ptk-ui/src/test/java/uitests/jfx/SwingFxWebBrowser.java
|
package uitests.jfx;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.JFXPanel;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;
import static javafx.concurrent.Worker.State.FAILED;
/**
* Example Swing/WebKit Browser
*/
public class SwingFxWebBrowser implements Runnable {
//
protected String startUrl;
//
private JFXPanel jfxPanel;
private WebEngine engine;
private JFrame frame = new JFrame();
private JPanel panel = new JPanel(new BorderLayout());
private JLabel lblStatus = new JLabel();
private JButton btnGo = new JButton("Go");
private JTextField txtURL = new JTextField();
private JProgressBar progressBar = new JProgressBar();
private void initComponents() {
jfxPanel = new JFXPanel();
createScene();
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.err.println(">>> Action:" + txtURL.getText());
loadURL(txtURL.getText());
}
};
btnGo.addActionListener(al);
txtURL.addActionListener(al);
progressBar.setPreferredSize(new Dimension(150, 18));
progressBar.setStringPainted(true);
JPanel topBar = new JPanel(new BorderLayout(5, 0));
topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
topBar.add(txtURL, BorderLayout.CENTER);
topBar.add(btnGo, BorderLayout.EAST);
JPanel statusBar = new JPanel(new BorderLayout(5, 0));
statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
statusBar.add(lblStatus, BorderLayout.CENTER);
statusBar.add(progressBar, BorderLayout.EAST);
panel.add(topBar, BorderLayout.NORTH);
panel.add(jfxPanel, BorderLayout.CENTER);
panel.add(statusBar, BorderLayout.SOUTH);
frame.getContentPane().add(panel);
}
private void createScene() {
Platform.runLater(new Runnable() {
@Override
public void run() {
WebView view = new WebView();
engine = view.getEngine();
engine.titleProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateTitle(newValue);
}
});
}
});
engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
@Override
public void handle(final WebEvent<String> event) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateStatus(event);
}
});
}
});
engine.locationProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> ov,
final String oldValue, final String newValue) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateLocation(oldValue, newValue);
}
});
}
});
engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observableValue,
Number oldValue, final Number newValue) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setValue(newValue.intValue());
}
});
}
});
engine.getLoadWorker().exceptionProperty()
.addListener(new ChangeListener<Throwable>() {
public void changed(ObservableValue<? extends Throwable> o,
Throwable old, final Throwable value) {
if (engine.getLoadWorker().getState() == FAILED) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(
panel,
(value != null) ? engine.getLocation() + "\n"
+ value.getMessage() : engine
.getLocation() + "\nUnexpected error.",
"Loading error...", JOptionPane.ERROR_MESSAGE);
}
});
}
}
});
jfxPanel.setScene(new Scene(view));
}
});
}
public void loadURL(final String url) {
Platform.runLater(new Runnable() {
@Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
private static String toURL(String str) {
try {
return new URL(str).toExternalForm();
} catch (MalformedURLException exception) {
return null;
}
}
@Override
public void run() {
frame.setPreferredSize(new Dimension(1024, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
loadURL(startUrl);
frame.pack();
frame.setVisible(true);
}
public void setStartUrl(String startUrl) {
this.startUrl = startUrl;
}
protected void updateLocation(String oldText, String newText) {
txtURL.setText(newText);
}
protected void updateStatus(WebEvent<String> event) {
lblStatus.setText(event.getData());
}
protected void updateTitle(String text) {
frame.setTitle(text);
}
// ====
// Main
// ====
public static void main(String[] args) {
SwingFxWebBrowser browser = new SwingFxWebBrowser();
browser.setStartUrl("http://www.cnn.nl");
SwingUtilities.invokeLater(browser);
}
}
|
tusharchoudhary0003/Custom-Football-Game
|
sources/com/fasterxml/jackson/databind/exc/InvalidFormatException.java
|
package com.fasterxml.jackson.databind.exc;
import com.fasterxml.jackson.core.JsonParser;
public class InvalidFormatException extends MismatchedInputException {
protected final Object _value;
public InvalidFormatException(JsonParser p, String msg, Object value, Class<?> targetType) {
super(p, msg, targetType);
this._value = value;
}
public static InvalidFormatException from(JsonParser p, String msg, Object value, Class<?> targetType) {
return new InvalidFormatException(p, msg, value, targetType);
}
}
|
CLIP-HPC/reframe
|
unittests/test_cli.py
|
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import contextlib
import io
import itertools
import json
import os
import pytest
import re
import sys
import time
import reframe.core.environments as env
import reframe.frontend.runreport as runreport
import reframe.core.logging as logging
import reframe.core.runtime as rt
import unittests.utility as test_util
def run_command_inline(argv, funct, *args, **kwargs):
# Save current execution context
argv_save = sys.argv
environ_save = env.snapshot()
sys.argv = argv
exitcode = None
captured_stdout = io.StringIO()
captured_stderr = io.StringIO()
print(*sys.argv)
with contextlib.redirect_stdout(captured_stdout):
with contextlib.redirect_stderr(captured_stderr):
try:
with rt.temp_runtime(None):
exitcode = funct(*args, **kwargs)
except SystemExit as e:
exitcode = e.code
finally:
# Restore execution context
environ_save.restore()
sys.argv = argv_save
return (exitcode,
captured_stdout.getvalue(),
captured_stderr.getvalue())
@pytest.fixture
def perflogdir(tmp_path):
dirname = tmp_path / '.rfm-perflogs'
yield dirname
@pytest.fixture
def run_reframe(tmp_path, perflogdir, monkeypatch):
def _run_reframe(system='generic:default',
checkpath=['unittests/resources/checks/hellocheck.py'],
environs=['builtin'],
local=True,
action='run',
more_options=None,
mode=None,
config_file='unittests/resources/settings.py',
perflogdir=str(perflogdir)):
import reframe.frontend.cli as cli
# We always pass the --report-file option, because we don't want to
# pollute the user's home directory
argv = ['./bin/reframe', '--prefix', str(tmp_path), '--nocolor',
f'--report-file={tmp_path / "report.json"}']
if mode:
argv += ['--mode', mode]
if system:
argv += ['--system', system]
if config_file:
argv += ['-C', config_file]
argv += itertools.chain(*(['-c', c] for c in checkpath))
argv += itertools.chain(*(['-p', e] for e in environs))
if local:
argv += ['--force-local']
if action == 'run':
argv += ['-r']
elif action == 'list':
argv += ['-l']
elif action == 'list_detailed':
argv += ['-L']
elif action == 'list_tags':
argv += ['--list-tags']
elif action == 'help':
argv += ['-h']
if perflogdir:
argv += ['--perflogdir', perflogdir]
if more_options:
argv += more_options
return run_command_inline(argv, cli.main)
monkeypatch.setenv('HOME', str(tmp_path))
return _run_reframe
@pytest.fixture
def user_exec_ctx(make_exec_ctx_g):
if test_util.USER_CONFIG_FILE is None:
pytest.skip('no user configuration file supplied')
yield from make_exec_ctx_g(test_util.USER_CONFIG_FILE,
test_util.USER_SYSTEM)
@pytest.fixture
def remote_exec_ctx(user_exec_ctx):
partition = test_util.partition_by_scheduler()
if not partition:
pytest.skip('job submission not supported')
return partition, partition.environs[0]
def test_check_success(run_reframe, tmp_path):
returncode, stdout, _ = run_reframe(more_options=['--save-log-files'])
assert 'PASSED' in stdout
assert 'FAILED' not in stdout
assert returncode == 0
logfile = logging.log_files()[0]
assert os.path.exists(tmp_path / 'output' / logfile)
assert os.path.exists(tmp_path / 'report.json')
def test_check_restore_session_failed(run_reframe, tmp_path):
run_reframe(
checkpath=['unittests/resources/checks_unlisted/deps_complex.py'],
)
returncode, stdout, _ = run_reframe(
checkpath=[],
more_options=[
f'--restore-session={tmp_path}/report.json', '--failed'
]
)
report = runreport.load_report(f'{tmp_path}/report.json')
assert set(report.slice('name', when=('fail_phase', 'sanity'))) == {'T2'}
assert set(report.slice('name',
when=('fail_phase', 'startup'))) == {'T7', 'T9'}
assert set(report.slice('name', when=('fail_phase', 'setup'))) == {'T8'}
assert report['runs'][-1]['num_cases'] == 4
restored = {r['name'] for r in report['restored_cases']}
assert restored == {'T1', 'T6'}
def test_check_restore_session_succeeded_test(run_reframe, tmp_path):
run_reframe(
checkpath=['unittests/resources/checks_unlisted/deps_complex.py'],
more_options=['--keep-stage-files']
)
returncode, stdout, _ = run_reframe(
checkpath=[],
more_options=[
f'--restore-session={tmp_path}/report.json', '-n', 'T1'
]
)
report = runreport.load_report(f'{tmp_path}/report.json')
assert report['runs'][-1]['num_cases'] == 1
assert report['runs'][-1]['testcases'][0]['name'] == 'T1'
restored = {r['name'] for r in report['restored_cases']}
assert restored == {'T4', 'T5'}
def test_check_restore_session_check_search_path(run_reframe, tmp_path):
run_reframe(
checkpath=['unittests/resources/checks_unlisted/deps_complex.py']
)
returncode, stdout, _ = run_reframe(
checkpath=[f'{tmp_path}/foo'],
more_options=[
f'--restore-session={tmp_path}/report.json', '-n', 'T1', '-R'
],
action='list'
)
assert returncode == 0
assert 'Found 0 check(s)' in stdout
def test_check_success_force_local(run_reframe, tmp_path):
# We explicitly use a system here with a non-local scheduler and pass the
# `--force-local` option
returncode, stdout, _ = run_reframe(system='testsys:gpu', local=True)
assert 'PASSED' in stdout
assert 'FAILED' not in stdout
assert returncode == 0
def test_report_file_with_sessionid(run_reframe, tmp_path):
returncode, *_ = run_reframe(
more_options=[
f'--report-file={tmp_path / "rfm-report-{sessionid}.json"}'
]
)
assert returncode == 0
assert os.path.exists(tmp_path / 'rfm-report-0.json')
def test_report_ends_with_newline(run_reframe, tmp_path):
returncode, stdout, _ = run_reframe(
more_options=[
f'--report-file={tmp_path / "rfm-report.json"}'
]
)
assert returncode == 0
with open(tmp_path / 'rfm-report.json') as fp:
assert fp.read()[-1] == '\n'
def test_check_submit_success(run_reframe, remote_exec_ctx):
# This test will run on the auto-detected system
partition, environ = remote_exec_ctx
returncode, stdout, _ = run_reframe(
config_file=test_util.USER_CONFIG_FILE,
local=False,
system=partition.fullname,
# Pick up the programming environment of the partition
# Prepend ^ and append $ so as to much exactly the given name
environs=[f'^{environ.name}$']
)
assert 'FAILED' not in stdout
assert 'PASSED' in stdout
# Assert that we have run only one test case
assert 'Ran 2/2 test case(s)' in stdout
assert 0 == returncode
def test_check_failure(run_reframe):
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'BadSetupCheck']
)
assert 'FAILED' in stdout
assert returncode != 0
def test_check_setup_failure(run_reframe):
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'BadSetupCheckEarly'],
local=False,
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert 'FAILED' in stdout
assert returncode != 0
def test_check_kbd_interrupt(run_reframe):
returncode, stdout, stderr = run_reframe(
checkpath=[
'unittests/resources/checks_unlisted/kbd_interrupt.py'
],
more_options=['-t', 'KeyboardInterruptCheck'],
local=False,
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert 'FAILED' in stdout
assert returncode != 0
def test_check_sanity_failure(run_reframe, tmp_path):
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'SanityFailureCheck']
)
assert 'FAILED' in stdout
# This is a normal failure, it should not raise any exception
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode != 0
assert os.path.exists(
tmp_path / 'stage' / 'generic' / 'default' /
'builtin' / 'SanityFailureCheck'
)
def test_dont_restage(run_reframe, tmp_path):
run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'SanityFailureCheck']
)
# Place a random file in the test's stage directory and rerun with
# `--dont-restage` and `--max-retries`
stagedir = (tmp_path / 'stage' / 'generic' / 'default' /
'builtin' / 'SanityFailureCheck')
(stagedir / 'foobar').touch()
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'SanityFailureCheck',
'--dont-restage', '--max-retries=1']
)
assert os.path.exists(stagedir / 'foobar')
assert not os.path.exists(f'{stagedir}_retry1')
# And some standard assertions
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode != 0
def test_checkpath_symlink(run_reframe, tmp_path):
# FIXME: This should move to test_loader.py
checks_symlink = tmp_path / 'checks_symlink'
os.symlink(os.path.abspath('unittests/resources/checks'),
checks_symlink)
returncode, stdout, _ = run_reframe(
action='list',
more_options=['-R'],
checkpath=['unittests/resources/checks', str(checks_symlink)]
)
num_checks_default = re.search(
r'Found (\d+) check', stdout, re.MULTILINE).group(1)
num_checks_in_checkdir = re.search(
r'Found (\d+) check', stdout, re.MULTILINE).group(1)
assert num_checks_in_checkdir == num_checks_default
def test_performance_check_failure(run_reframe, tmp_path, perflogdir):
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'PerformanceFailureCheck']
)
assert 'FAILED' in stdout
# This is a normal failure, it should not raise any exception
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode != 0
assert os.path.exists(
tmp_path / 'stage' / 'generic' / 'default' /
'builtin' / 'PerformanceFailureCheck'
)
assert os.path.exists(perflogdir / 'generic' /
'default' / 'PerformanceFailureCheck.log')
def test_perflogdir_from_env(run_reframe, tmp_path, monkeypatch):
monkeypatch.setenv('FOODIR', str(tmp_path / 'perflogs'))
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'PerformanceFailureCheck'],
perflogdir='$FOODIR'
)
assert returncode == 1
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert os.path.exists(tmp_path / 'perflogs' / 'generic' /
'default' / 'PerformanceFailureCheck.log')
def test_performance_report(run_reframe):
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'PerformanceFailureCheck', '--performance-report']
)
assert r'PERFORMANCE REPORT' in stdout
assert r'perf: 10 Gflop/s' in stdout
def test_skip_system_check_option(run_reframe):
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['--skip-system-check', '-t', 'NoSystemCheck']
)
assert 'PASSED' in stdout
assert returncode == 0
def test_skip_prgenv_check_option(run_reframe):
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['--skip-prgenv-check', '-t', 'NoPrgEnvCheck']
)
assert 'PASSED' in stdout
assert returncode == 0
def test_sanity_of_checks(run_reframe, tmp_path):
# This test will effectively load all the tests in the checks path and
# will force a syntactic and runtime check at least for the constructor
# of the checks
returncode, *_ = run_reframe(
action='list',
checkpath=[]
)
assert returncode == 0
def test_unknown_system(run_reframe):
returncode, stdout, stderr = run_reframe(
action='list',
system='foo',
checkpath=[]
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 1
def test_sanity_of_optconfig(run_reframe):
# Test the sanity of the command line options configuration
returncode, *_ = run_reframe(
action='help',
checkpath=[]
)
assert returncode == 0
def test_checkpath_recursion(run_reframe):
_, stdout, _ = run_reframe(action='list', checkpath=[])
num_checks_default = re.search(r'Found (\d+) check', stdout).group(1)
_, stdout, _ = run_reframe(action='list',
checkpath=['checks/'],
more_options=['-R'])
num_checks_in_checkdir = re.search(r'Found (\d+) check', stdout).group(1)
assert num_checks_in_checkdir == num_checks_default
_, stdout, _ = run_reframe(action='list',
checkpath=['checks/'],
more_options=[])
num_checks_in_checkdir = re.search(r'Found (\d+) check', stdout).group(1)
assert num_checks_in_checkdir == '0'
def test_same_output_stage_dir(run_reframe, tmp_path):
output_dir = str(tmp_path / 'foo')
returncode, *_ = run_reframe(
more_options=['-o', output_dir, '-s', output_dir]
)
assert returncode == 1
# Retry with --keep-stage-files
returncode, *_ = run_reframe(
more_options=['-o', output_dir, '-s', output_dir, '--keep-stage-files']
)
assert returncode == 0
assert os.path.exists(output_dir)
def test_execution_modes(run_reframe):
returncode, stdout, stderr = run_reframe(
checkpath=[],
environs=[],
local=False,
mode='unittest'
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert 'FAILED' not in stdout
assert 'PASSED' in stdout
assert 'Ran 2/2 test case' in stdout
def test_timestamp_option(run_reframe):
timefmt = time.strftime('xxx_%F')
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks'],
action='list',
more_options=['-R', '--timestamp=xxx_%F']
)
assert returncode == 0
assert timefmt in stdout
def test_timestamp_option_default(run_reframe):
timefmt_date_part = time.strftime('%FT')
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks'],
action='list',
more_options=['-R', '--timestamp']
)
assert returncode == 0
assert timefmt_date_part in stdout
def test_list_empty_prgenvs_check_and_options(run_reframe):
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
action='list',
environs=[],
more_options=['-n', 'NoPrgEnvCheck'],
)
assert 'Found 0 check(s)' in stdout
assert returncode == 0
def test_list_check_with_empty_prgenvs(run_reframe):
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
action='list',
environs=['foo'],
more_options=['-n', 'NoPrgEnvCheck']
)
assert 'Found 0 check(s)' in stdout
assert returncode == 0
def test_list_empty_prgenvs_in_check_and_options(run_reframe):
returncode, stdout, _ = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
action='list',
environs=[],
more_options=['-n', 'NoPrgEnvCheck']
)
assert 'Found 0 check(s)' in stdout
assert returncode == 0
def test_list_with_details(run_reframe):
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
action='list_detailed'
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_list_tags(run_reframe):
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks/hellocheck.py',
'unittests/resources/checks/hellocheck_make.py'],
action='list_tags'
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert 'Found 2 tag(s)' in stdout
assert "'bar', 'foo'" in stdout
assert returncode == 0
def test_filtering_multiple_criteria(run_reframe):
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks'],
action='list',
more_options=['-t', 'foo', '-n', 'hellocheck']
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert 'Found 1 check(s)' in stdout
assert returncode == 0
def test_show_config_all(run_reframe):
# Just make sure that this option does not make the frontend crash
returncode, stdout, stderr = run_reframe(
more_options=['--show-config'],
system='testsys'
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_show_config_param(run_reframe):
# Just make sure that this option does not make the frontend crash
returncode, stdout, stderr = run_reframe(
more_options=['--show-config=systems'],
system='testsys'
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_show_config_unknown_param(run_reframe):
# Just make sure that this option does not make the frontend crash
returncode, stdout, stderr = run_reframe(
more_options=['--show-config=foo'],
system='testsys'
)
assert 'no such configuration parameter found' in stdout
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_verbosity(run_reframe):
returncode, stdout, stderr = run_reframe(
more_options=['-vvvvv'],
system='testsys',
action='list'
)
assert stdout != ''
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_verbosity_with_check(run_reframe):
returncode, stdout, stderr = run_reframe(
more_options=['-vvvvv'],
system='testsys',
action='list',
checkpath=['unittests/resources/checks/hellocheck.py']
)
assert '' != stdout
assert '--- Logging error ---' not in stdout
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert 0 == returncode
def test_quiesce_with_check(run_reframe):
returncode, stdout, stderr = run_reframe(
more_options=['-v', '-qqq'], # Show only errors
system='testsys',
action='list',
checkpath=['unittests/resources/checks/hellocheck.py']
)
assert stdout == ''
assert 'Traceback' not in stderr
assert 0 == returncode
def test_load_user_modules(run_reframe, user_exec_ctx):
with rt.module_use('unittests/modules'):
returncode, stdout, stderr = run_reframe(
more_options=['-m testmod_foo'],
action='list'
)
assert stdout != ''
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_unload_module(run_reframe, user_exec_ctx):
# This test is mostly for ensuring coverage. `run_reframe()` restores
# the current environment, so it is not easy to verify that the modules
# are indeed unloaded. However, this functionality is tested elsewhere
# more exhaustively.
ms = rt.runtime().modules_system
if not test_util.has_sane_modules_system():
pytest.skip('no modules system found')
with rt.module_use('unittests/modules'):
ms.load_module('testmod_foo')
returncode, stdout, stderr = run_reframe(
more_options=['-u testmod_foo'],
action='list'
)
ms.unload_module('testmod_foo')
assert stdout != ''
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_unuse_module_path(run_reframe, user_exec_ctx):
ms = rt.runtime().modules_system
if not test_util.has_sane_modules_system():
pytest.skip('no modules system found')
module_path = 'unittests/modules'
ms.searchpath_add(module_path)
returncode, stdout, stderr = run_reframe(
more_options=[f'--module-path=-{module_path}', '--module=testmod_foo'],
config_file=test_util.USER_CONFIG_FILE, action='run',
system=rt.runtime().system.name
)
ms.searchpath_remove(module_path)
assert "could not load module 'testmod_foo' correctly" in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_use_module_path(run_reframe, user_exec_ctx):
if not test_util.has_sane_modules_system():
pytest.skip('no modules system found')
module_path = 'unittests/modules'
returncode, stdout, stderr = run_reframe(
more_options=[f'--module-path=+{module_path}', '--module=testmod_foo'],
config_file=test_util.USER_CONFIG_FILE, action='run',
system=rt.runtime().system.name
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert "could not load module 'testmod_foo' correctly" not in stdout
assert returncode == 0
def test_overwrite_module_path(run_reframe, user_exec_ctx):
if not test_util.has_sane_modules_system():
pytest.skip('no modules system found')
module_path = 'unittests/modules'
with contextlib.suppress(KeyError):
module_path += f':{os.environ["MODULEPATH"]}'
returncode, stdout, stderr = run_reframe(
more_options=[f'--module-path={module_path}', '--module=testmod_foo'],
config_file=test_util.USER_CONFIG_FILE, action='run',
system=rt.runtime().system.name
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert "could not load module 'testmod_foo' correctly" not in stdout
assert returncode == 0
def test_failure_stats(run_reframe):
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks/frontend_checks.py'],
more_options=['-t', 'SanityFailureCheck', '--failure-stats']
)
assert r'FAILURE STATISTICS' in stdout
assert r'sanity 1 [SanityFailureCheck' in stdout
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode != 0
def test_maxfail_option(run_reframe):
returncode, stdout, stderr = run_reframe(
more_options=['--maxfail', '1'],
system='testsys',
checkpath=['unittests/resources/checks/hellocheck.py']
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert ('Ran 2/2 test case(s) from 2 check(s) '
'(0 failure(s), 0 skipped)') in stdout
assert returncode == 0
def test_maxfail_invalid_option(run_reframe):
returncode, stdout, stderr = run_reframe(
more_options=['--maxfail', 'foo'],
system='testsys',
checkpath=['unittests/resources/checks/hellocheck.py']
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert "--maxfail is not a valid integer: 'foo'" in stdout
assert returncode == 1
def test_maxfail_negative(run_reframe):
returncode, stdout, stderr = run_reframe(
more_options=['--maxfail', '-2'],
system='testsys',
checkpath=['unittests/resources/checks/hellocheck.py']
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert "--maxfail should be a non-negative integer: '-2'" in stdout
assert returncode == 1
def test_detect_host_topology(run_reframe):
from reframe.utility.cpuinfo import cpuinfo
returncode, stdout, stderr = run_reframe(
more_options=['--detect-host-topology']
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
assert stdout == json.dumps(cpuinfo(), indent=2) + '\n'
def test_detect_host_topology_file(run_reframe, tmp_path):
from reframe.utility.cpuinfo import cpuinfo
topo_file = tmp_path / 'topo.json'
returncode, stdout, stderr = run_reframe(
more_options=[f'--detect-host-topology={topo_file}']
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert returncode == 0
with open(topo_file) as fp:
assert json.load(fp) == cpuinfo()
def test_external_vars(run_reframe):
returncode, stdout, stderr = run_reframe(
checkpath=['unittests/resources/checks_unlisted/externalvars.py'],
more_options=['-S', 'external_x.foo=3', '-S', 'external_y.foo=2',
'-S', 'foolist=3,4', '-S', 'bar=@none',
'-S', 'external_x.ham=true',
'-S', 'external_y.baz=false']
)
assert 'Traceback' not in stdout
assert 'Ran 2/2 test case(s)' in stdout
assert 'Traceback' not in stderr
assert returncode == 0
def test_external_vars_invalid_expr(run_reframe):
returncode, stdout, stderr = run_reframe(
more_options=['-S', 'foo']
)
assert 'Traceback' not in stdout
assert 'Traceback' not in stderr
assert 'invalid test variable assignment' in stdout
assert returncode == 0
def test_fixture_registry_env_sys(run_reframe):
'''Test that the fixtures see the cli options.
The loaded checks have a system scope fixture named HelloFixture. Hence,
this fixture will take any partition+environ combination from the parent
tests. So by restricting the partition and the environment to only one
single option, here we test that the fixture has the valid_systems and
valid_prog_environs as passed throught the cli options.
'''
returncode, stdout, stderr = run_reframe(
system='sys1:p0',
environs=['e3'],
checkpath=['unittests/resources/checks_unlisted/fixtures_simple.py'],
more_options=['-n', 'HelloFixture'],
action='list_detailed'
)
assert returncode == 0
assert 'e3' in stdout
assert 'sys1:p0' in stdout
returncode, stdout, stderr = run_reframe(
system='sys1:p0',
environs=['e1'],
checkpath=['unittests/resources/checks_unlisted/fixtures_simple.py'],
more_options=['-n', 'HelloFixture'],
action='list_detailed'
)
assert returncode == 0
assert 'e1' in stdout
assert 'sys1:p0' in stdout
returncode, stdout, stderr = run_reframe(
system='sys1:p1',
environs=['e1'],
checkpath=['unittests/resources/checks_unlisted/fixtures_simple.py'],
more_options=['-n', 'HelloFixture'],
action='list_detailed'
)
assert returncode == 0
assert 'e1' in stdout
assert 'sys1:p1' in stdout
returncode, stdout, stderr = run_reframe(
system='sys1:p1',
environs=['e2'],
checkpath=['unittests/resources/checks_unlisted/fixtures_simple.py'],
more_options=['-n', 'HelloFixture'],
action='list_detailed'
)
assert returncode == 0
assert 'e2' in stdout
assert 'sys1:p1' in stdout
def test_fixture_resolution(run_reframe):
returncode, stdout, stderr = run_reframe(
system='sys1',
environs=[],
checkpath=['unittests/resources/checks_unlisted/fixtures_complex.py'],
action='run'
)
assert returncode == 0
|
knu-3-tochanenko/OOP
|
Sem 5/Lab 3/core/src/com/tochanenko/libgdx/GameCore.java
|
<filename>Sem 5/Lab 3/core/src/com/tochanenko/libgdx/GameCore.java<gh_stars>0
package com.tochanenko.libgdx;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class GameCore extends Game {
SpriteBatch batch;
private BitmapFont font;
public void create() {
batch = new SpriteBatch();
font = new BitmapFont();
this.setScreen(new MainMenuScreen(this));
}
public void render() {
super.render();
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE))
Gdx.app.exit();
}
public void dispose() {
batch.dispose();
font.dispose();
}
}
|
Chalarangelo/furl
|
src/components/ContextButton.js
|
import React from 'react';
import Button from './Button';
import { combineClassNames, omitProps, combineStyles } from '../utilities/utils';
const ContextButton = ({
text = 'normal',
size = 'normal',
color = 'plain',
verticalPosition = 'bottom',
horizontalPosition = 'right',
onClick,
className,
children,
...rest}) => {
let classNames = [className, `v-${verticalPosition}`, `h-${horizontalPosition}`, 'context-button'];
return (
<Button
className={combineClassNames(classNames)}
fill='solid'
text={text}
size={size}
color={color}
onClick={onClick}
style={combineStyles(rest, rest.style)}
{...omitProps(rest)}
>
{children}
</Button>
);
};
export default ContextButton;
|
dingchaolin/go-demo-2
|
src/demo6/point.go
|
package main
import (
"math"
"fmt"
)
type Point struct{
X, Y float64
}
func Distance( p, q Point) float64{
return math.Hypot(q.X - p.X, q.Y - p.Y)
}
func main(){
p := Point{1,2}
q := Point{4,6}
fmt.Println( Distance(p, q) )
}
|
ate47/consoleexperience
|
src/main/java/com/fuzs/consoleexperience/client/gui/PaperDollRenderer.java
|
<filename>src/main/java/com/fuzs/consoleexperience/client/gui/PaperDollRenderer.java<gh_stars>1-10
package com.fuzs.consoleexperience.client.gui;
import com.fuzs.consoleexperience.client.element.GameplayElements;
import com.fuzs.consoleexperience.client.element.HoveringHotbarElement;
import com.fuzs.consoleexperience.client.element.PaperDollElement;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Quaternion;
import net.minecraft.util.math.vector.Vector3f;
public class PaperDollRenderer {
private final float maxRotation = 30.0F;
private float prevRotationYaw;
@SuppressWarnings("deprecation")
public void drawEntityOnScreen(int posX, int posY, int scale, LivingEntity entity, float partialTicks) {
((HoveringHotbarElement) GameplayElements.HOVERING_HOTBAR).run(() -> {
// prepare
RenderSystem.pushMatrix();
RenderSystem.disableCull();
RenderSystem.translatef((float) posX, (float) posY, 950.0F);
RenderSystem.scalef(1.0F, 1.0F, -1.0F);
// set angles and lighting
MatrixStack stack = new MatrixStack();
stack.translate(0.0, 0.0, 1000.0);
stack.scale((float) scale, (float) scale, (float) scale);
Quaternion quaternionZ = Vector3f.ZP.rotationDegrees(180.0F);
Quaternion quaternionX = Vector3f.XP.rotationDegrees(15.0F);
quaternionZ.multiply(quaternionX);
stack.rotate(quaternionZ);
// save rotation as we don't want to change the actual entity
float rotationPitch = entity.rotationPitch;
float renderYawOffset = entity.renderYawOffset;
float rotationYawHead = entity.rotationYawHead;
float prevRotationPitch = entity.prevRotationPitch;
float prevRenderYawOffset = entity.prevRenderYawOffset;
float prevRotationYawHead = entity.prevRotationYawHead;
this.prevRotationYaw = this.updateRotation(entity, partialTicks, this.prevRotationYaw, rotationYawHead, prevRotationYawHead);
// do render
EntityRendererManager entityrenderermanager = Minecraft.getInstance().getRenderManager();
quaternionX.conjugate();
entityrenderermanager.setCameraOrientation(quaternionX);
entityrenderermanager.setRenderShadow(false);
IRenderTypeBuffer.Impl impl = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource();
RenderSystem.runAsFancy(() -> entityrenderermanager.renderEntityStatic(entity, 0.0, 0.0, 0.0, 0.0F, partialTicks, stack, impl, 15728880));
impl.finish();
entityrenderermanager.setRenderShadow(true);
// restore entity rotation
entity.rotationPitch = rotationPitch;
entity.renderYawOffset = renderYawOffset;
entity.rotationYawHead = rotationYawHead;
entity.prevRotationPitch = prevRotationPitch;
entity.prevRenderYawOffset = prevRenderYawOffset;
entity.prevRotationYawHead = prevRotationYawHead;
// finish
RenderSystem.enableCull();
RenderSystem.popMatrix();
});
}
private float updateRotation(LivingEntity entity, float partialTicks, float prevRotationYaw, float rotationYawHead, float prevRotationYawHead) {
HeadMovement headMovement = ((PaperDollElement) GameplayElements.PAPER_DOLL).headMovement;
// head rotation is used for doll rotation as it updates a lot more precisely than the body rotation
float defaultRotationYaw = 180.0F + ((PaperDollElement) GameplayElements.PAPER_DOLL).position.getRotation(this.maxRotation / 2.0F);
if (headMovement == HeadMovement.YAW || entity.isElytraFlying()) {
entity.rotationPitch = 7.5F;
entity.prevRotationPitch = 7.5F;
}
entity.renderYawOffset = defaultRotationYaw;
entity.prevRenderYawOffset = defaultRotationYaw;
if (headMovement == HeadMovement.PITCH) {
entity.prevRotationYawHead = defaultRotationYaw;
entity.rotationYawHead = defaultRotationYaw;
} else {
entity.prevRotationYawHead = defaultRotationYaw + prevRotationYaw;
prevRotationYaw = this.rotateEntity(prevRotationYaw, rotationYawHead - prevRotationYawHead, partialTicks);
entity.rotationYawHead = defaultRotationYaw + prevRotationYaw;
}
return prevRotationYaw;
}
/**
* Rotate entity according to its yaw, slowly spin back to default when yaw stays constant for a while
*/
private float rotateEntity(float rotationYaw, float renderYawOffsetDiff, float partialTicks) {
if (Minecraft.getInstance().isGamePaused()) {
return rotationYaw;
}
// apply rotation change from entity
rotationYaw = MathHelper.clamp(rotationYaw + renderYawOffsetDiff * 0.5F, -this.maxRotation, this.maxRotation);
// rotate back to origin, never overshoot 0
partialTicks = rotationYaw - partialTicks * rotationYaw / 15.0F;
if (rotationYaw < 0.0F) {
rotationYaw = Math.min(0, partialTicks);
} else if (rotationYaw > 0.0F) {
rotationYaw = Math.max(0, partialTicks);
}
return rotationYaw;
}
public void reset() {
this.prevRotationYaw = 0;
}
@SuppressWarnings("unused")
public enum HeadMovement {
YAW, PITCH, BOTH
}
}
|
danielogen/msc_research
|
selected projects/desktop/mars-sim-v3.1.0/mars-sim-core/org/mars_sim/msp/core/location/LocationTag.java
|
/**
* Mars Simulation Project
* LocationTag.java
* @version 3.1.0 2017-10-10
* @author <NAME>
*/
package org.mars_sim.msp.core.location;
import java.io.Serializable;
import java.util.Collection;
import org.mars_sim.msp.core.Coordinates;
import org.mars_sim.msp.core.Simulation;
import org.mars_sim.msp.core.Unit;
import org.mars_sim.msp.core.UnitManager;
import org.mars_sim.msp.core.equipment.Equipment;
import org.mars_sim.msp.core.mars.MarsSurface;
import org.mars_sim.msp.core.person.Person;
import org.mars_sim.msp.core.robot.Robot;
import org.mars_sim.msp.core.structure.Settlement;
import org.mars_sim.msp.core.structure.building.Building;
import org.mars_sim.msp.core.tool.Conversion;
import org.mars_sim.msp.core.vehicle.Vehicle;
public class LocationTag implements LocationState, Serializable {
private static final long serialVersionUID = 1L;
public static final String OUTSIDE_ON_MARS = Conversion.capitalize(LocationStateType.OUTSIDE_ON_THE_SURFACE_OF_MARS.getName());
public static final String VICINITY = " vicinity";
private static final String UNKNOWN = LocationStateType.UNKNOWN.getName();
private static final String IN = " in ";
private Unit unit;
private Person p = null;
private Robot r = null;
private Equipment e = null;
private Building b = null;
private Vehicle v = null;
private Settlement s = null;
private MarsSurface ms = null;
private static UnitManager unitManager = Simulation.instance().getUnitManager();
public LocationTag(Unit unit) {
this.unit = unit;
if (unit instanceof Person)
p = (Person) unit;
else if (unit instanceof Robot)
r = (Robot) unit;
else if (unit instanceof Equipment)
e = (Equipment) unit;
else if (unit instanceof Building)
b = (Building) unit;
else if (unit instanceof Vehicle)
v = (Vehicle) unit;
else if (unit instanceof Settlement)
s = (Settlement) unit;
else if (unit instanceof MarsSurface)
ms = (MarsSurface) unit;
}
/**
* Gets the name of the settlement the unit is at
*
* @return
*/
public String getSettlementName() {
if (p != null) {
if (LocationStateType.INSIDE_SETTLEMENT == p.getLocationStateType())
return p.getSettlement().getName();
else
return p.getCoordinates().getFormattedString();
} else if (e != null) {
if (LocationStateType.INSIDE_SETTLEMENT == e.getLocationStateType())
return e.getSettlement().getName();
else
return e.getCoordinates().getFormattedString();
} else if (r != null) {
if (LocationStateType.INSIDE_SETTLEMENT == r.getLocationStateType())
return r.getSettlement().getName();
else
return r.getCoordinates().getFormattedString();// OUTSIDE_ON_MARS;
} else if (b != null) {
return b.getSettlement().getName();
}
else if (v != null) {
if (LocationStateType.INSIDE_SETTLEMENT == v.getLocationStateType())
return v.getSettlement().getName();
else
return v.getCoordinates().getFormattedString();// OUTSIDE_ON_MARS;
}
return UNKNOWN;
}
/**
* Obtains the quick location name (either settlement, buried settlement,
* vehicle or coordinates)
*
* @return the name string of the location the unit is at
*/
public String getQuickLocation() {
if (p != null) {
if (LocationStateType.INSIDE_SETTLEMENT == p.getLocationStateType())
return p.getSettlement().getName();
else if (LocationStateType.INSIDE_VEHICLE == p.getLocationStateType())
return p.getVehicle().getName();
else if (p.isDeclaredDead()) {
if (p.getAssociatedSettlement() != null)
return p.getAssociatedSettlement().getName();
else if (p.isBuried() && p.getBuriedSettlement() != null)
return p.getBuriedSettlement().getName();
else
return p.getCoordinates().getFormattedString();
}
else
return p.getCoordinates().getFormattedString();
}
else if (e != null) {
if (e.getContainerID() != 0)
return e.getContainerUnit().getName();
else if (e.getTopContainerID() != 0)
return e.getTopContainerUnit().getName();
else
return e.getCoordinates().getFormattedString();
}
else if (r != null) {
if (LocationStateType.INSIDE_SETTLEMENT == r.getLocationStateType())
return r.getSettlement().getName();
else if (LocationStateType.INSIDE_VEHICLE == r.getLocationStateType())
return r.getVehicle().getName();
else
return r.getCoordinates().getFormattedString();
} else if (b != null) {
return b.getNickName() + " in " + b.getSettlement().getName();
}
else if (v != null) {
if (LocationStateType.INSIDE_SETTLEMENT == v.getLocationStateType())
return v.getSettlement().getName();
else if (LocationStateType.INSIDE_SETTLEMENT == v.getLocationStateType())
return v.getBuildingLocation().getNickName();
else
return v.getCoordinates().getFormattedString();
}
return UNKNOWN;
}
/**
* Obtains the general locale (settlement or coordinates)
*
* @return the exact or nearby settlement/vehicle
*/
public String getLocale() {
if (p != null) {
if (p.getPhysicalCondition() != null && p.getPhysicalCondition().isDead())
return p.getPhysicalCondition().getDeathDetails().getPlaceOfDeath();
else if (LocationStateType.INSIDE_SETTLEMENT == p.getLocationStateType())
return p.getSettlement().getName();
else if (LocationStateType.INSIDE_VEHICLE == p.getLocationStateType())
return p.getVehicle().getName();
else if (LocationStateType.WITHIN_SETTLEMENT_VICINITY == p.getLocationStateType())
return findSettlementVicinity().getName();
else if (LocationStateType.OUTSIDE_ON_THE_SURFACE_OF_MARS == p.getLocationStateType()) {
Settlement s = findSettlementVicinity();
if (s != null)
return s.getName();
Vehicle v = findNearbyVehicleVicinity();
if (v != null)
return v.getName();
}
else
return p.getCoordinates().getFormattedString();
}
else if (e != null) {
if (LocationStateType.INSIDE_SETTLEMENT == e.getLocationStateType())
return e.getSettlement().getName();
else
return e.getCoordinates().getFormattedString();
}
else if (r != null) {
if (LocationStateType.INSIDE_SETTLEMENT == r.getLocationStateType())
return r.getSettlement().getName();
else
return r.getCoordinates().getFormattedString();
}
else if (b != null) {
return b.getSettlement().getName();
}
else if (v != null) {
if (LocationStateType.INSIDE_SETTLEMENT == v.getLocationStateType())
return v.getSettlement().getName();
else
return v.getCoordinates().getFormattedString();
}
return UNKNOWN;
}
/**
* Obtains the extended location details
* e.g. Lander Hab 1 in New Pompeii
* @return the name string of the location the unit is at
*/
public String getExtendedLocations() {
String immediate = getImmediateLocation();
if (immediate.equals(OUTSIDE_ON_MARS))
return OUTSIDE_ON_MARS + " of " + getLocale();
if (immediate.equalsIgnoreCase(getLocale()))
return immediate;
return immediate + IN + getLocale();
}
/**
* Obtains the immediate location (either building, vehicle, a settlement's
* vicinity or outside on Mars)
*
* @return the name string of the location the unit is at
*/
public String getImmediateLocation() {
if (p != null) {
if (LocationStateType.INSIDE_SETTLEMENT == p.getLocationStateType()) {
if (p.getBuildingLocation() != null) {
return p.getBuildingLocation().getNickName();
}
else {
return p.getLocationStateType().getName();
}
} else if (LocationStateType.INSIDE_VEHICLE == p.getLocationStateType()) {
Vehicle v = p.getVehicle();
if (v.getBuildingLocation() == null) {
return v.getNickName();
} else {
return v.getBuildingLocation().getNickName();
}
}
else if (LocationStateType.WITHIN_SETTLEMENT_VICINITY == p.getLocationStateType() || p.isRightOutsideSettlement())
return findSettlementVicinity().getName() + VICINITY;
// TODO: check if it works in case of a trader arrives at any settlements for
// trades.
else
return OUTSIDE_ON_MARS;
}
else if (e != null) {
if (LocationStateType.ON_A_PERSON_OR_ROBOT == e.getLocationStateType())
return e.getContainerUnit().getLocationTag().getImmediateLocation();
else if (LocationStateType.WITHIN_SETTLEMENT_VICINITY == e.getLocationStateType() || e.isRightOutsideSettlement())
return findSettlementVicinity().getName() + VICINITY;
else if (e.isInside()) //!(e.getContainerUnit() instanceof MarsSurface))
return e.getContainerUnit().getName();
else
return OUTSIDE_ON_MARS;
}
else if (r != null) {
if (LocationStateType.INSIDE_SETTLEMENT == r.getLocationStateType()) {
if (r.getBuildingLocation() != null) {
return r.getBuildingLocation().getNickName();
} else {
return OUTSIDE_ON_MARS;
}
} else if (r.getVehicle() != null) {
Vehicle v = r.getVehicle();
if (v.getBuildingLocation() == null) {
return v.getNickName();
} else {
return v.getBuildingLocation().getNickName();
}
}
else if (LocationStateType.WITHIN_SETTLEMENT_VICINITY == r.getLocationStateType() || r.isRightOutsideSettlement())
return findSettlementVicinity().getName() + VICINITY;
else
return OUTSIDE_ON_MARS;
} else if (b != null) {
return b.getNickName();
}
else if (v != null) {
if (LocationStateType.INSIDE_SETTLEMENT == v.getLocationStateType()) {
if (v.getBuildingLocation() != null) {
return v.getBuildingLocation().getNickName();
} else {
return OUTSIDE_ON_MARS;
}
}
else if (LocationStateType.WITHIN_SETTLEMENT_VICINITY == v.getLocationStateType() || v.isRightOutsideSettlement())
return findSettlementVicinity().getName() + VICINITY;
else
return OUTSIDE_ON_MARS;
}
return UNKNOWN;
}
/**
* Finds the settlement that a person/robot is in its vicinity
*
* @return {@link Settlement}
*/
public Settlement findSettlementVicinity() {
Coordinates c = unit.getCoordinates();
if (unitManager == null)
unitManager = Simulation.instance().getUnitManager();
Collection<Settlement> ss = unitManager.getSettlements();
for (Settlement s : ss) {
if (s.getCoordinates().equals(c) || s.getCoordinates() == c)
return s;
}
// if (unit instanceof Person && ((Person) unit).getPhysicalCondition().isDead())
// return ((Person) unit).getBuriedSettlement();
return unit.getAssociatedSettlement();
}
/**
* Finds the vehicle that drops off a person/robot outside on Mars
*
* @return {@link Vehicle}
*/
public Vehicle findNearbyVehicleVicinity() {
Coordinates c = unit.getCoordinates();
if (unitManager == null)
unitManager = Simulation.instance().getUnitManager();
Collection<Vehicle> list = unitManager.getVehicles();
for (Vehicle v : list) {
if (v.getCoordinates().equals(c) || v.getCoordinates() == c)
return v;
}
return null;
}
/**
* Checks if an unit is in the vicinity of a settlement
*
* @return true if it is
*/
public boolean isInSettlementVicinity() {
Coordinates c = unit.getCoordinates();
if (unitManager == null)
unitManager = Simulation.instance().getUnitManager();
Collection<Settlement> ss = unitManager.getSettlements();
for (Settlement s : ss) {
if (s.getCoordinates() == c || s.getCoordinates().equals(c))
return true;
}
return false;
}
/*
* Gets the unit's location state type
*/
public LocationStateType getType() {
return unit.getLocationStateType();
}
// public LocationSituation getLocationSituation() {
// if (p != null) {
// if (p.getLocationSituation() != null)
// return p.getLocationSituation();
// } else if (e != null) {
// if (e.getLocationSituation() != null)
// return e.getLocationSituation();
// } else if (r != null) {
// if (r.getLocationSituation() != null)
// return r.getLocationSituation();
// }
// return LocationSituation.UNKNOWN;
// }
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
public void destroy() {
unit = null;
p = null;
r = null;
e = null;
b = null;
v = null;
}
}
|
fbi-octopus/biggles
|
include/biggles/kalman_filter.hpp
|
<reponame>fbi-octopus/biggles
/// @file kalman_filter.hpp Kalman filter and Rauch–Tung–Striebel smoother for track observations
#ifndef BIGGLES_KALMAN_FILTER_HPP__
#define BIGGLES_KALMAN_FILTER_HPP__
#include <Eigen/Dense>
#include <deque>
#include "observation.hpp"
#include "track.hpp"
#include "detail/physics.hpp"
namespace biggles
{
/// @brief A Kalman filter for predicting missing observations in tracks.
///
/// A Kalman filter is the optimal linear state space evaluator for tracking a hidden state given noisy observations.
/// Specifically we assume some hidden state vector at time \f$ T \f$, \f$ x_t \f$ which evolves with the following
/// model:
///
/// \f[
/// x_t = A x_{t-1} + V_t
/// \f]
///
/// where \f$ A \f$ is some state evolution matrix and \f$ V_t \f$ is a zero-mean Gaussian process with (known)
/// covariance matrix \f$ Q \f$.
///
/// We assume that we can make a noisy observation, \f$ y_t \f$:
///
/// \f[
/// y_t = B x_t + W_t
/// \f]
///
/// where \f$ B \f$ is an observation matrix and \f$ W_t \f$ is a zero-mean Gaussian process with (known) covariance
/// matrix \f$ R \f$.
///
/// A Kalman filter consists of a prediction step followed by an update step. In the prediction step, the current
/// estimate of the hidden state, \f$ \hat{x}_t \f$, is evolved via the state evolution matrix. In the update step, this
/// estimate is refined by fusing any observations made. In this implementation the lack of an observation causes this
/// update step to be skipped and the refined estimate is assumed to be equal to the prediction.
///
/// The prediction step is represented by the following recurrence relations:
///
/// \f[
/// \hat{x}_{t|t-1} = A \hat{x}_{t-1|t-1}, \quad P_{t|t-1} = A P_{t-1|t-1} A^T + Q
/// \f]
///
/// where \f$ P_{t|t-1} \f$ and \f$ P_{t|t} \f$ are, respectively, our prediction of the state estimation error and our
/// refined prediction of the state estimation error.
///
/// The update step is represented by the following recurrence relations:
///
/// \f[
/// \hat{x}_{t|t} = \hat{x}_{t|t-1} + K_t \tilde{z}_t, \quad P_{t|t} = (I - K_t B) P_{t|t-1}
/// \f]
///
/// where
///
/// \f[
/// \tilde{z}_t = y_t - B \hat{x}_{t|t-1}, \quad K_t = P_{t|t-1} B^T + S_t^{-1}, \quad S_t = B P_{t|t-1} B^T + R.
/// \f]
///
/// We initialise the filter by choosing some arbitrary initial state estimate, \f$ \hat{x}_{0|0} \f$, and setting the
/// initial state covariance matrix, \f$ P_{0|0} \f$, to some sufficiently large multiple of \f$ I \f$ so as to specify
/// almost no certainty on the initial estimate. We use the recurrence relations to compute estimates of states and
/// estimation error covariances up until the last time stamp for the track.
///
/// In our system, the state is a position and instantaneous velocity:
///
/// \f[
/// x_t = [ x, x', y, y' ]^T
/// \f]
///
/// States evolve using first order dynamics and the velocity is hidden:
///
/// \f[
/// A = \left[
/// \begin{array}{cccc}
/// 1 & d & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & d \\ 0 & 0 & 0 & 1
/// \end{array}
/// \right], \quad
///
/// B = \left[
/// \begin{array}{cccc}
/// 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0
/// \end{array}
/// \right].
/// \f]
///
/// The matrix \f$ R \f$ and dynamic drag \f$ d \f$ are given as parameters to the constructor. The matrix Q is set to
/// the following by default:
///
/// \f[
/// Q = \left[
/// \begin{array}{cccc}
/// 0.8^2 & 0 & 0 & 0 \\ 0 & 0.2^2 & 0 & 0 \\ 0 & 0 & 0.8^2 & 0 \\ 0 & 0 & 0 & 0.2^2
/// \end{array}
/// \right].
/// \f]
///
/// @sa rts_smooth()
/// @sa http://en.wikipedia.org/wiki/Kalman_filter
/// @sa http://automation.berkeley.edu/resources/KalmanSmoothing.ppt
class kalman_filter
{
public:
/// @brief The underlying state vector type.
///
/// The state vector represents the instantaneous position and velocity of the molecule as a vector \f$ X \equiv [x,
/// x', y, y'] \f$.
typedef Eigen::Vector4f state_vector;
/// @brief The covariance of the state.
///
/// The Kalman filter maintains an estimate of the instantaneous error in state estimation as a state covariance
/// matrix \f$ \Sigma \equiv E(XX^T) - E(X)E(X)^T \f$.
typedef Eigen::Matrix4f covariance_matrix;
/// @brief A pair holding an interpolated state vector and its associated covariance.
typedef std::pair<state_vector, covariance_matrix> state_covariance_pair;
/// @brief The collection type used to hold states and covariances.
//typedef std::deque<state_covariance_pair, Eigen::aligned_allocator<state_covariance_pair> > states_and_cov_deque;
typedef std::deque<state_covariance_pair> states_and_cov_deque;
/// @brief The default observation covariance.
///
/// The default value is
/// \f[
/// R = \left[
/// \begin{array}{cc}
/// 0.1^2 & 0 \\ 0 & 0.1^2
/// \end{array}
/// \right]
/// \f]
static const Eigen::Matrix2f default_observation_covariance;
/// @brief Default constructor.
kalman_filter() : dynamic_drag_(1.f) { }
/// @brief Initialise filter from a track's observations.
///
/// This constructor uses the observations from a track to interpolate states for all timestamps within a track.
///
/// @param t The track to initialise from.
/// @param observation_covariance The observation covariance matrix \f$ R \f$. The default is default_observation_covariance.
kalman_filter(const track& t, const matrix2f &R, const matrix4f &Q)
{
reinitialise(t.first_time_stamp(), t.last_time_stamp(), t.begin(), t.end(), R, Q, t.dynamic_drag());
}
/// @brief Initialise filter with a set of observations.
///
/// @tparam InputIterator An InputIterator yielding biggles::observation instances.
/// @param first_time_stamp The first time stamp of the track.
/// @param last_time_stamp The time stamp immediately after the last time stamp of the track: \p first_time_stamp +
/// duration.
/// @param first The first observation for the track.
/// @param last Just beyond the last observation for the track.
/// @param observation_covariance The observation covariance matrix \f$ R \f$.
/// @param dynamic_drag The dynamic drag factor.
//template<typename InputIterator>
kalman_filter(time_stamp first_time_stamp,
time_stamp last_time_stamp,
track::const_iterator first, track::const_iterator last,
const matrix2f &R, const matrix4f &Q,
float dynamic_drag)
{
reinitialise(first_time_stamp, last_time_stamp, first, last, R, Q, dynamic_drag);
}
/// @brief Copy constructor.
///
/// @param kf The biggles::kalman_filter instance to copy.
kalman_filter(const kalman_filter& kf)
: prediction_states_and_covs_(kf.prediction_states_and_covs_)
, correction_states_and_covs_(kf.correction_states_and_covs_)
, dynamic_drag_(kf.dynamic_drag_)
{ }
/// @brief Assignment operator.
///
/// @param kf The biggles::kalman_filter instance to copy.
const kalman_filter& operator = (const kalman_filter& kf)
{
prediction_states_and_covs_ = kf.prediction_states_and_covs_;
correction_states_and_covs_ = kf.correction_states_and_covs_;
dynamic_drag_ = kf.dynamic_drag_;
return *this;
}
/// @brief Re-initialise filter with a set of observations.
///
/// @tparam InputIterator An InputIterator yielding biggles::observation instances.
/// @param first_time_stamp The first time stamp of the track.
/// @param last_time_stamp The time stamp immediately after the last time stamp of the track: \p first_time_stamp +
/// duration.
/// @param first The first observation for the track.
/// @param last Just beyond the last observation for the track.
/// @param observation_covariance The observation covariance matrix \f$ R \f$.
/// @param dynamic_drag The dynamic drag factor.
//template<typename InputIterator>
void reinitialise(time_stamp first_time_stamp, time_stamp last_time_stamp,
track::const_iterator first, track::const_iterator last,
const matrix2f &R, const matrix4f &Q,
float dynamic_drag);
/// @brief The predicted states and covariances.
///
/// A collection of predicted states, \f$ x_{t|t-1} \f$, and covariances, \f$ P_{t|t-1} \f$, for all time stamps
/// covered by the input range.
const states_and_cov_deque& predictions() const { return prediction_states_and_covs_; }
/// @brief The corrected states and covariances.
///
/// A collection of corrected states, \f$ x_{t|t} \f$, and covariances, \f$ P_{t|t} \f$, for all time stamps
/// covered by the input range.
const states_and_cov_deque& corrections() const { return correction_states_and_covs_; }
/// @brief The dynamic drag factor associated with this filter.
float dynamic_drag() const { return dynamic_drag_; }
protected:
// NOTE: The situation with storing Eigen dense matrices in a std::vector is complex. To avoid this, we use a deque
// here even though our usage pattern would suggest a vector be more appropriate.
//
// See: http://eigen.tuxfamily.org/dox-devel/TopicStlContainers.html
/// @brief The collection of interpolated states and covariances of their errors.
states_and_cov_deque prediction_states_and_covs_;
/// @brief The collection of interpolated states and covariances of their errors.
states_and_cov_deque correction_states_and_covs_;
/// @brief The dynamic drag factor to use in state evolution matrices.
float dynamic_drag_;
};
/// @brief Perform a Rauch–Tung–Striebel backwards smoothing step on the Kalman filter predicted and corrected states.
///
/// @note Since this is a <em>backward</em> process, the results are written to \p
/// output_reversed_states_and_covariances in <em>reverse</em> order; i.e. the smoothed state and covariance for the
/// <em>last</em> time stamp is the first written out.
///
/// Once the forward prediction-update step has been completed for a Kalman filter, we can use a Rauch–Tung–Striebel
/// smoother to refine our earlier state estimates. This is a backwards step which starts from the final estimated state
/// (i.e. the one which has been influenced by all observed observations) and works backwards creating optimal estimates
/// of the hidden state, \f$ \hat{x}_{t|T} \f$, and estimation error covariance, \f$ P_{t|T} \f$. Note that these
/// estimates have been computed given all observations.
///
/// The estimates are computed via the following recurrence relations:
///
/// \f[
/// \hat{x}_{t|T} = \hat{x}_{t|t} + L_t ( \hat{x}_{t+1|T} - \hat{x}_{t+1|t} ), \quad
/// P_{t|T} = P_{t|t} + L_t ( P_{t+1|T} - P_{t+1|t} ) L^T_t
/// \f]
///
/// where \f$ L_t = P_{t|t} A^T P_{t+1|t}^{-1} \f$.
///
/// These smoothed estimates of state and estimation error generated by this function may be used as mean and
/// covariances of a multi-variate Gaussian in order to sample possible state-space configurations for a track. Biggles
/// uses these estimates not only as mean and covariances for evaluation log-likelihoods on track configurations but
/// also for sampling missing data from tracks.
///
/// @sa biggles::kalman_filter
///
/// @tparam OutputIterator Where entries of type kalman_filter::state_covariance_pair are written.
/// @param kalman A Kalman filter to take predicted and corrected states and covariances from.
/// @param output_reversed_states_and_covariances An iterator to write smoothed states and covariances to <em>in reverse
/// order</em>.
template<typename OutputIterator>
void rts_smooth(const kalman_filter& kalman,
OutputIterator output_reversed_states_and_covariances);
}
#define WITHIN_BIGGLES_KALMAN_FILTER_HPP__
#include "kalman_filter.tcc"
#undef WITHIN_BIGGLES_KALMAN_FILTER_HPP__
#endif // BIGGLES_KALMAN_FILTER_HPP__
|
silasdavis/hello-doug
|
apps/dual_integration/app.js
|
'use strict';
// app-level requires
var contracts = require('eris-contracts'),
docusign = require('docusign-esign'),
express = require('express'),
fs = require('fs'),
pdf = require('html-pdf');
// setup express app
var app = express(),
appPort = process.env.APP_PORT || 3000;
app.set('view engine', 'pug');
app.use(require('body-parser').urlencoded({ extended: false }));
// setup ipfs
var ipfsAPI = require('ipfs-api');
var ipfs = ipfsAPI({
host: process.env.IPFS_HOST || 'localhost',
port: '5001',
procotol: 'http'
});
// code contracts' variables populated
var abiDirectory = process.env.ABI_DIRECTORY || './abi/',
chainName = process.env.CHAIN_NAME || 'dualintegrator',
chainHost = process.env.CHAIN_HOST || 'localhost',
chainPort = process.env.CHAIN_PORT || 1337,
myHost = process.env.MY_HOST || 'localhost',
factoryContractName = process.env.FACTORY_CONTRACT_NAME || 'IntegratorFactory',
codeContractName = process.env.CODE_CONTRACT_NAME || 'DualIntegrator',
keyFile = process.env.KEY_FILE || './accounts.json',
jobsOutputFile = process.env.JOBS_FILE || './jobs_output.json';
var codeContractAddress = '';
var chainUrl = 'http://' + chainHost + ':' + chainPort + '/rpc';
var factoryContractAddress = require(jobsOutputFile)['deploy' + factoryContractName];
var keys = require(keyFile)[(chainName + '_full_000')];
var partyAAddress = keys.address;
var partyBAddress = require(keyFile)[(chainName + '_participant_000')].address;
var chainID = partyAAddress; // THIS IS A HACK UNTIL CHAINID's BETTER ON EDB/ERIS.js
var factory = contracts.newContractManagerDev(chainUrl, keys)
.newContractFactory(JSON.parse(fs.readFileSync(abiDirectory + factoryContractName, 'utf8')))
.at(factoryContractAddress);
// prose contracts' variables populated
var proseContractsDirectory = process.env.PROSE_CONTRACTS_DIR || './contracts/prose/',
proseContractsTemplateFile = process.env.PROSE_CONTRACTS_FILE_NAME || 'template.commonform',
proseContractsTitle = process.env.PROSE_CONTRACTS_TITLE || 'Sample Dual Integrated Contract',
proseContractsDefaultTerms = process.env.PROSE_CONTRACTS_DEFAULT_TERMS || 'template.json',
proseContractsHash = '',
proseContractOpts = {html5: true, title: proseContractsTitle};
var proseContractsDefaultTerms = JSON.parse(fs.readFileSync(proseContractsDirectory + proseContractsDefaultTerms, 'utf8'));
var proseContractsTemplateString = fs.readFileSync(proseContractsDirectory + proseContractsTemplateFile, 'utf8');
var proseContractAsHTML = '',
proseContractsHash = '';
// docusign variables populated
var hasDocusign = false;
if(process.env.DOCUSIGN_USER != null && process.env.DOCUSIGN_USER != "***") {
console.log("Docusign User detected. Will integrate Docusign. User: " + process.env.DOCUSIGN_USER)
hasDocusign = true;
var docusignUser = process.env.DOCUSIGN_USER,
docusignPass = process.env.DOCUSIGN_PASS,
docusignKey = process.env.DOCUSIGN_KEY,
docusignBaseUrl = process.env.DOCUSIGN_URL || 'https://demo.docusign.net/restapi',
docusignClient = new docusign.ApiClient(),
docusignEnvelopeID = '',
docusignLoginCreds = '{"Username":"' + docusignUser + '","Password":"' + <PASSWORD> + '","IntegratorKey":"' + docusignKey + '"}';
docusignClient.setBasePath(docusignBaseUrl);
docusignClient.addDefaultHeader('X-DocuSign-Authentication', docusignLoginCreds);
docusign.Configuration.default.setDefaultApiClient(docusignClient);
var docusignAuthApi = new docusign.AuthenticationApi();
var docusignLoginOps = new docusignAuthApi.LoginOptions();
docusignLoginOps.setApiPassword('<PASSWORD>');
docusignLoginOps.setIncludeAccountIdGuid('true');
} else {
console.log("No Docusign User detected. Will not integrate Docusign.")
}
// test prefill
proseContractsDefaultTerms['Contract Factory Address'] = factoryContractAddress;
proseContractsDefaultTerms['Chain ID'] = chainID;
proseContractsDefaultTerms['Party A Address'] = partyAAddress;
proseContractsDefaultTerms['Party B Address'] = partyBAddress;
proseContractsDefaultTerms['Party A Email'] = docusignUser;
// default route should submit the form.
app.get('/', function (req, res) {
function returnToSender() {
res.render('index', {
title: 'Dual Integrator | Home',
// static variables
partyAAddress: partyAAddress,
partyBAddress: partyBAddress,
factoryContractAddress: factoryContractAddress,
factoryContractAddresses: factoryContractAddresses,
myHost: myHost,
// fields users will fill in
partyAName: partyAName,
partyBName: partyBName,
partyAEmail: partyAEmail,
partyBEmail: partyBEmail,
numberOfMonths: numberOfMonths
});
};
// deploys the instrument contract
function getAllContracts() {
factory.getAddresses(function(error, result) {
if (error != null) {
throw error;
}
factoryContractAddresses = result;
return returnToSender();
});
};
// defaults
var factoryContractAddresses = [ ],
partyAName = proseContractsDefaultTerms['Party A Name'],
partyBName = proseContractsDefaultTerms['Party B Name'],
partyAEmail = proseContractsDefaultTerms['Party A Email'],
partyBEmail = proseContractsDefaultTerms['Party B Email'],
numberOfMonths = proseContractsDefaultTerms['Number of Months'];
getAllContracts();
});
// submit POST route is what accepts the parameters and performs the dual integration process
app.post('/contract', function(req, res) {
function signDocumentWithDocusign(){
console.log("Sending document for signature with Docusign")
var envelopeId = '';
docusignAuthApi.login(docusignLoginOps, function (error, loginInfo, response) {
if (error) {
throw('Error logging into Docusign API: ' + error);
}
if (loginInfo) {
var loginAccounts = loginInfo.getLoginAccounts();
var loginAccount = new docusign.LoginAccount();
loginAccount = loginAccounts[0];
var accountId = loginAccount.accountId;
// create an envelope that will store the document(s), field(s), and recipient(s)
var envDef = new docusign.EnvelopeDefinition();
envDef.setEmailSubject('Please sign this document from Dual Integrator Demonstrator Application');
pdf.create(proseContractAsHTML).toBuffer(function(err, buffer){
// add a document to the envelope
var doc = new docusign.Document();
var base64Doc = buffer.toString('base64');
doc.setDocumentBase64(base64Doc);
doc.setName(codeContractAddress + '.pdf'); // can be different from actual file name
doc.setDocumentId('1');
var docs = [];
docs.push(doc);
envDef.setDocuments(docs);
// add a recipient to sign the document, identified by name and email we used above
var signer = new docusign.Signer();
signer.setEmail(partyBEmail);
signer.setName(partyBName); // XXXX
signer.setRecipientId('1');
signer.setClientUserId(partyBAddress);
// create a signHere tab somewhere on the document for the signer to sign
// default unit of measurement is pixels, can be mms, cms, inches also
var signHere = new docusign.SignHere();
signHere.setDocumentId('1');
signHere.setPageNumber('1');
signHere.setRecipientId('1');
signHere.setXPosition('400');
signHere.setYPosition('700');
// can have multiple tabs, so need to add to envelope as a single element list
var signHereTabs = [];
signHereTabs.push(signHere);
var tabs = new docusign.Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// add recipients (in this case a single signer) to the envelope
envDef.setRecipients(new docusign.Recipients());
envDef.getRecipients().setSigners([]);
envDef.getRecipients().getSigners().push(signer);
// send the envelope by setting |status| to "sent". To save as a draft set to "created"
envDef.setStatus('sent');
// instantiate a new EnvelopesApi object
var envelopesApi = new docusign.EnvelopesApi();
// call the createEnvelope() API
envelopesApi.createEnvelope(accountId, envDef, null, function (error, envelopeSummary, response) {
if (error) {
throw('Error creating envelope: ' + error);
}
if (envelopeSummary) {
envelopeId = envelopeSummary.envelopeId;
// instantiate a new EnvelopesApi object
var envelopesApi = new docusign.EnvelopesApi();
// set the url where you want the recipient to go once they are done signing
var returnUrl = new docusign.RecipientViewRequest();
returnUrl.setReturnUrl('http://' + myHost + ':' + appPort + '/complete/' + codeContractAddress + '/' + envelopeId);
returnUrl.setAuthenticationMethod('email');
// recipient information must match embedded recipient info we provided in step #2
returnUrl.setEmail(partyBEmail);
returnUrl.setUserName(partyBName);
returnUrl.setRecipientId('1');
returnUrl.setClientUserId(partyBAddress);
// call the CreateRecipientView API
envelopesApi.createRecipientView(accountId, envelopeId, returnUrl, function (error, recipientView, response) {
if (error) {
throw('Error creating client view: ' + error);
}
if (recipientView) {
return res.redirect(recipientView.url);
}
});
}
});
});
}
});
}
// returns the formulated document
function renderProseContract(form, defaultTerms) {
// stolen from https://github.com/commonform/commonform-cli/blob/master/source/transform-for-format.js#L58-L70
console.log("Rendering a new prose contract via the prose factory template: " + proseContractsTemplateFile)
var terms = Object.keys(defaultTerms)
.reduce(function(output, key) {
var value = defaultTerms[key]
form.directions.filter(function(direction) {
return direction.identifier === key
})
.forEach(function(direction) {
output.push({
blank: direction.path,
value: value })
})
return output
},
[ ]
);
proseContractAsHTML = require('commonform-html')(form.form, terms, proseContractOpts);
if (hasDocusign) {
return signDocumentWithDocusign();
} else {
return res.redirect('/complete/' + codeContractAddress + '/' + 'n_a')
}
}
// ensures that the prose params are properly populated
function assembleProseParams(form) {
// recieve from the submission of the form
proseContractsDefaultTerms['Party A Name'] = partyAName;
proseContractsDefaultTerms['Party B Name'] = partyBName;
proseContractsDefaultTerms['Party A Email'] = partyAEmail;
proseContractsDefaultTerms['Party B Email'] = partyBEmail;
proseContractsDefaultTerms['Number of Months'] = numberOfMonths;
proseContractsDefaultTerms['Contract Address'] = codeContractAddress;
return renderProseContract(form, proseContractsDefaultTerms);
}
// returns a common form object with both form and directions
function parseProseContract() {
var form = require('commonform-markup-parse')(proseContractsTemplateString);
return assembleProseParams(form);
}
// deploys the instrument contract
function deployCodeContract() {
console.log("Deploying a new code contract via the code factory contract at address: " + factoryContractAddress)
factory.createInstrument(numberOfMonths, partyAAddress, partyBAddress, partyAName, partyBName, function(error, result) {
if (error != null) {
throw error;
}
codeContractAddress = result;
console.log("Code contract address: " + codeContractAddress)
return parseProseContract();
});
}
// defaults
var partyAName = req.body.partyAName,
partyBName = req.body.partyBName,
partyAEmail = req.body.partyAEmail,
partyBEmail = req.body.partyBEmail,
numberOfMonths = req.body.numberOfMonths;
console.log("\nNew contract request sent.\nInitiating Dual Integration sequence.\n")
deployCodeContract();
});
app.get('/complete/:address/:envelope', function(req, res) {
function addIPFSHashToCodeContract(hash) {
proseContractsHash = hash[0].hash;
console.log("Logging the hash of the prose contract from IPFS into the code contract's parameters. Hash: ", proseContractsHash)
var codeContract = contracts.newContractManagerDev(chainUrl, keys)
.newContractFactory(JSON.parse(fs.readFileSync(abiDirectory + codeContractName, 'utf8')))
.at(codeContractAddress);
codeContract.setHash(proseContractsHash, function(error, result) {
if (error != null) {
throw error;
}
console.log("Dual Integration sequence complete!")
return res.redirect('/contract/' + codeContractAddress);
});
}
function getSignedDocumentFromDocusign() {
console.log("Getting signed document from signature with Docusign")
docusignAuthApi.login(docusignLoginOps, function (error, loginInfo, response) {
if (error) {
throw('Error logging into Docusign API: ' + error);
}
if (loginInfo) {
var loginAccounts = loginInfo.getLoginAccounts();
var loginAccount = new docusign.LoginAccount();
loginAccount = loginAccounts[0];
var accountId = loginAccount.accountId;
// instantiate a new EnvelopesApi object
var envelopesApi = new docusign.EnvelopesApi();
// call the getDocument() API
envelopesApi.getDocument(accountId, envelopeId, documentId, function (error, document, response) {
if (error) {
throw('Error getting document from docusign: ' + error);
}
if (document) {
console.log("Adding prose contract to the IPFS distributed file storage system.")
ipfs.util.addFromStream(new Buffer(document, 'binary'), function(err, result) {
if (err) {
throw err
}
return addIPFSHashToCodeContract(result);
});
}
})
}
})
}
function sendHashToIPFS() {
ipfs.util.addFromStream(new Buffer(proseContractAsHTML, "utf-8"), function(err, result) {
if (err) {
throw err
}
return addIPFSHashToCodeContract(result);
});
}
// get defaults from request
var envelopeId = req.params.envelope,
codeContractAddress = req.params.address,
documentId = '1';
if (hasDocusign) {
getSignedDocumentFromDocusign();
} else {
sendHashToIPFS();
}
});
app.get('/contract/:address', function(req, res) {
function returnToSender() {
res.render('contract', {
title: "Dual Integrator | Contract: " + codeContractAddress,
// static variables
partyAAddress: partyAAddress,
partyBAddress: partyBAddress,
factoryContractAddress: factoryContractAddress,
codeContractAddress: codeContractAddress,
partyAName: partyAName,
partyBName: partyBName,
numberOfMonths: numberOfMonths,
proseContractsHash: proseContractsHash,
proseContractAsHTML: proseContractAsHTML,
myHost: myHost,
});
}
function populateHTML() {
ipfs.files.get(proseContractsHash, function(error, stream) {
if (error != null) {
throw error;
}
stream.on('data', (chunk) => {
proseContractAsHTML += chunk.content.read().toString();
})
stream.on('end', () => {
return returnToSender();
});
})
}
function populateSecondParams() {
codeContract.getNames(function(error, result) {
if (error != null) {
throw error;
}
proseContractsHash = result;
if (hasDocusign) {
return returnToSender();
} else {
return populateHTML();
}
});
};
function populateFirstParms() {
codeContract.getParams(function(error, result) {
if (error != null) {
throw error;
}
numberOfMonths = result[0]['c'][0];
partyAAddress = result[1];
partyBAddress = result[2];
return populateSecondParams();
});
};
// defaults
var numberOfMonths = '',
partyAName = '',
partyBName = '',
proseContractsHash = '',
proseContractAsHTML = '';
// correct contract
codeContractAddress = req.params.address;
var codeContract = contracts.newContractManagerDev(chainUrl, keys)
.newContractFactory(JSON.parse(fs.readFileSync(abiDirectory + codeContractName, 'utf8')))
.at(codeContractAddress);
populateFirstParms();
});
app.listen(appPort, function () {
console.log('Application listening on port: ' + appPort + '.');
});
|
w3hacker/swoole
|
include/tests.h
|
<gh_stars>1-10
/*
* tests.h
*
* Created on: 2013-4-22
* Author: htf
*/
#ifndef SW_TESTS_H_
#define SW_TESTS_H_
#define swUnitTest(x) int swUnitTest_##x(swUnitTest *object)
#define swUnitTest_steup(x,n) _swUnitTest_setup(swUnitTest_##x, #x, n)
typedef struct _swUnitTest
{
int argc;
char **argv;
} swUnitTest;
typedef int (*swUnitTest_Func)(swUnitTest *object);
void _swUnitTest_setup(swUnitTest_Func func, char *func_name, int run_times);
int swUnitTest_run(swUnitTest *object);
swUnitTest(mem_test1);
swUnitTest(mem_test2);
swUnitTest(mem_test3);
swUnitTest(client_test);
swUnitTest(server_test);
swUnitTest(hashmap_test1);
swUnitTest(ds_test2);
swUnitTest(ds_test1);
swUnitTest(chan_test);
swUnitTest(u1_test2);
swUnitTest(u1_test1);
swUnitTest(http_test2);
swUnitTest(type_test1);
void p_str(void *str);
swUnitTest(pool_thread);
#endif /* SW_TESTS_H_ */
|
Zhuinden/service-tree
|
service-tree-view-example/src/main/java/com/zhuinden/servicetreeviewexample/FirstView.java
|
<gh_stars>10-100
package com.zhuinden.servicetreeviewexample;
import android.annotation.TargetApi;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import com.zhuinden.servicetreeviewexample.injection.FirstComponent;
import com.zhuinden.simplestack.Backstack;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by Owner on 2017. 03. 07..
*/
public class FirstView
extends LinearLayout {
public static final String TAG = "FirstView";
@Inject
BackstackHolder backstackHolder;
public FirstView(Context context) {
super(context);
init(context);
}
public FirstView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FirstView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
if(!isInEditMode()) {
FirstComponent firstComponent = Services.getNode(Backstack.getKey(getContext())).getService(Services.DAGGER_COMPONENT);
firstComponent.inject(this);
}
}
@TargetApi(21)
public FirstView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
@OnClick(R.id.first_button)
public void clickFirst() {
backstackHolder.getBackstack().goTo(SecondKey.create());
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
ButterKnife.bind(this);
}
}
|
nptcl/npt
|
src/clos.h
|
#ifndef __CLOS_HEADER__
#define __CLOS_HEADER__
#include "clos_define.h"
#include "constant.h"
#include "execute.h"
#define Clos_standard_class _n(Clos_standard_class)
#define Clos_standard_generic _n(Clos_standard_generic)
#define Clos_standard_method _n(Clos_standard_method)
#define Clos_standard_combination _n(Clos_standard_combination)
#define Clos_standard_specializer _n(Clos_standard_specializer)
#define struct_slot _n(struct_slot)
#define getname_slot _n(getname_slot)
#define setname_slot _n(setname_slot)
#define gettype_slot _n(gettype_slot)
#define settype_slot _n(settype_slot)
#define getargs_slot _n(getargs_slot)
#define setargs_slot _n(setargs_slot)
#define getform_slot _n(getform_slot)
#define setform_slot _n(setform_slot)
#define getfunction_slot _n(getfunction_slot)
#define setfunction_slot _n(setfunction_slot)
#define getreaders_slot _n(getreaders_slot)
#define setreaders_slot _n(setreaders_slot)
#define getwriters_slot _n(getwriters_slot)
#define setwriters_slot _n(setwriters_slot)
#define getdocument_slot _n(getdocument_slot)
#define setdocument_slot _n(setdocument_slot)
#define getclass_slot _n(getclass_slot)
#define setclass_slot _n(setclass_slot)
#define getreadonly_slot _n(getreadonly_slot)
#define setreadonly_slot _n(setreadonly_slot)
#define getallocation_slot _n(getallocation_slot)
#define setallocation_slot _n(setallocation_slot)
#define getlocation_slot _n(getlocation_slot)
#define setlocation_slot _n(setlocation_slot)
#define getaccess_slot _n(getaccess_slot)
#define setaccess_slot _n(setaccess_slot)
#define struct_clos _n(struct_clos)
#define getclassof_clos _n(getclassof_clos)
#define setclassof_clos _n(setclassof_clos)
#define getslot_clos _n(getslot_clos)
#define setslot_clos _n(setslot_clos)
#define getvalue_clos _n(getvalue_clos)
#define setvalue_clos _n(setvalue_clos)
#define getfuncall_clos _n(getfuncall_clos)
#define setfuncall_clos _n(setfuncall_clos)
#define getversion_clos _n(getversion_clos)
#define setversion_clos _n(setversion_clos)
#define getslotvector _n(getslotvector)
#define setslotvector _n(setslotvector)
#define lenslotvector _n(lenslotvector)
#define getclosvalue _n(getclosvalue)
#define setclosvalue _n(setclosvalue)
#define lenclosvalue _n(lenclosvalue)
#define clos_standard_ignore _n(clos_standard_ignore)
#define clos_standard_class_p_debug _n(clos_standard_class_p_debug)
#define clos_standard_generic_p_debug _n(clos_standard_generic_p_debug)
#define clos_standard_method_p_debug _n(clos_standard_method_p_debug)
#define clos_standard_combination_p_debug _n(clos_standard_combination_p_debug)
#define clos_standard_specializer_p_debug _n(clos_standard_specializer_p_debug)
#define slot_alloc _n(slot_alloc)
#define slot_local _n(slot_local)
#define slot_heap _n(slot_heap)
#define slot_copy_alloc _n(slot_copy_alloc)
#define slot_copy_local _n(slot_copy_local)
#define slot_copy_heap _n(slot_copy_heap)
#define slot_vector_alloc _n(slot_vector_alloc)
#define slot_vector_local _n(slot_vector_local)
#define slot_vector_heap _n(slot_vector_heap)
#define slot_vector_copy_alloc _n(slot_vector_copy_alloc)
#define slot_vector_copy_local _n(slot_vector_copy_local)
#define slot_vector_copy_heap _n(slot_vector_copy_heap)
#define slot_vector_copyheap_alloc _n(slot_vector_copyheap_alloc)
#define slot_vector_clear _n(slot_vector_clear)
#define clos_value_heap _n(clos_value_heap)
#define clos_alloc _n(clos_alloc)
#define clos_local _n(clos_local)
#define clos_heap _n(clos_heap)
#define clos_destroy _n(clos_destroy)
#define clos_swap _n(clos_swap)
#define clos_copy_alloc _n(clos_copy_alloc)
#define clos_allcopy_alloc _n(clos_allcopy_alloc)
#define clos_getslots_heap _n(clos_getslots_heap)
#define closp _n(closp)
#define slotp _n(slotp)
#define clos_value_p _n(clos_value_p)
#define slot_vector_p _n(slot_vector_p)
#define clos_funcall_p _n(clos_funcall_p)
#define slot_class_p _n(slot_class_p)
#define slot_instance_p _n(slot_instance_p)
#define clos_set_funcall _n(clos_set_funcall)
#define slot_set_class _n(slot_set_class)
#define slot_set_instance _n(slot_set_instance)
#define slot_set_allocation_ _n(slot_set_allocation_)
#define clos_errorp _n(clos_errorp)
#define clos_getp _n(clos_getp)
#define clos_setp _n(clos_setp)
#define clos_checkp_ _n(clos_checkp_)
#define clos_get_ _n(clos_get_)
#define clos_set_ _n(clos_set_)
#define clos_check_ _n(clos_check_)
#define clos_getelt _n(clos_getelt)
#define clos_setelt _n(clos_setelt)
#define clos_checkelt_ _n(clos_checkelt_)
#define clos_getconst_ _n(clos_getconst_)
#define clos_setconst_ _n(clos_setconst_)
#define clos_checkconst_ _n(clos_checkconst_)
#define clos_slot_exists_p _n(clos_slot_exists_p)
#define clos_slot_boundp_nil _n(clos_slot_boundp_nil)
#define clos_slot_boundp_ _n(clos_slot_boundp_)
#define clos_slot_makunbound_nil_ _n(clos_slot_makunbound_nil_)
#define clos_slot_makunbound_ _n(clos_slot_makunbound_)
#define clos_find_class_nil _n(clos_find_class_nil)
#define clos_find_class_ _n(clos_find_class_)
#define clos_define_class _n(clos_define_class)
#define clos_find_generic_nil _n(clos_find_generic_nil)
#define clos_find_generic_ _n(clos_find_generic_)
#define clos_define_generic_ _n(clos_define_generic_)
#define clos_find_combination_nil _n(clos_find_combination_nil)
#define clos_find_combination_ _n(clos_find_combination_)
#define clos_define_combination _n(clos_define_combination)
#define clos_find_specializer_nil_ _n(clos_find_specializer_nil_)
#define clos_find_specializer_ _n(clos_find_specializer_)
#define clos_define_specializer_ _n(clos_define_specializer_)
#define clos_forget_all_specializer_unsafe _n(clos_forget_all_specializer_unsafe)
#define init_clos _n(init_clos)
#define build_clos _n(build_clos)
extern addr Clos_standard_class;
extern addr Clos_standard_generic;
extern addr Clos_standard_method;
extern addr Clos_standard_combination;
extern addr Clos_standard_specializer;
struct slot_struct {
size_t location, access;
};
struct clos_struct {
fixnum version;
};
#define PtrSlotStruct_Low(x) PtrBodySSa((x),SLOT_INDEX_SIZE)
#define SlotStruct_Low(x) ((struct slot_struct *)PtrSlotStruct_Low(x))
#define GetNameSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_NAME,(y))
#define SetNameSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_NAME,(y))
#define GetTypeSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_TYPE,(y))
#define SetTypeSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_TYPE,(y))
#define GetArgsSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_INITARGS,(y))
#define SetArgsSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_INITARGS,(y))
#define GetFormSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_INITFORM,(y))
#define SetFormSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_INITFORM,(y))
#define GetFunctionSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_INITFUNCTION,(y))
#define SetFunctionSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_INITFUNCTION,(y))
#define GetReadersSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_READERS,(y))
#define SetReadersSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_READERS,(y))
#define GetWritersSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_WRITERS,(y))
#define SetWritersSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_WRITERS,(y))
#define GetDocumentSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_DOCUMENT,(y))
#define SetDocumentSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_DOCUMENT,(y))
#define GetClassSlot_Low(x,y) GetArraySS((x),SLOT_INDEX_CLASS,(y))
#define SetClassSlot_Low(x,y) SetArraySS((x),SLOT_INDEX_CLASS,(y))
#define GetReadOnlySlot_Low(x,y) GetArraySS((x),SLOT_INDEX_READONLY,(y))
#define SetReadOnlySlot_Low(x,y) SetArraySS((x),SLOT_INDEX_READONLY,(y))
#define GetAllocationSlot_Low(x,y) (*(y) = GetUser((x)))
#define SetAllocationSlot_Low(x,y) (SetUser((x), (y) != 0))
#define GetLocationSlot_Low(x,y) (*(y) = SlotStruct_Low(x)->location)
#define SetLocationSlot_Low(x,y) (SlotStruct_Low(x)->location = (y))
#define GetAccessSlot_Low(x,y) (*(y) = SlotStruct_Low(x)->access)
#define SetAccessSlot_Low(x,y) (SlotStruct_Low(x)->access = (y))
#define PtrClosStruct_Low(x) PtrBodySSa((x),CLOS_INDEX_SIZE)
#define ClosStruct_Low(x) ((struct clos_struct *)PtrClosStruct_Low(x))
#define GetClassOfClos_Low(x,y) GetArraySS((x),CLOS_INDEX_CLASS_OF,(y))
#define SetClassOfClos_Low(x,y) SetArraySS((x),CLOS_INDEX_CLASS_OF,(y))
#define GetSlotClos_Low(x,y) GetArraySS((x),CLOS_INDEX_SLOT,(y))
#define SetSlotClos_Low(x,y) SetArraySS((x),CLOS_INDEX_SLOT,(y))
#define GetValueClos_Low(x,y) GetArraySS((x),CLOS_INDEX_VALUE,(y))
#define SetValueClos_Low(x,y) SetArraySS((x),CLOS_INDEX_VALUE,(y))
#define GetFuncallClos_Low(x,y) (*(y) = GetUser((x)))
#define SetFuncallClos_Low(x,y) (SetUser((x), (y) != 0))
#define GetVersionClos_Low(x,y) (*(y) = ClosStruct_Low(x)->version)
#define SetVersionClos_Low(x,y) (ClosStruct_Low(x)->version = (y))
#define GetSlotVector_Low GetArrayA4
#define SetSlotVector_Low SetArrayA4
#define LenSlotVector_Low LenArrayA4
#define GetClosValue_Low GetArrayA4
#define SetClosValue_Low SetArrayA4
#define LenClosValue_Low LenArrayA4
#define clos_standard_class_p_Low(x) (Clos_standard_class == (x))
#define clos_standard_generic_p_Low(x) (Clos_standard_generic == (x))
#define clos_standard_method_p_Low(x) (Clos_standard_method == (x))
#define clos_standard_combination_p_Low(x) (Clos_standard_combination == (x))
#define clos_standard_specializer_p_Low(x) (Clos_standard_specializer == (x))
#ifdef LISP_DEBUG
#define SlotStruct struct_slot
#define GetNameSlot getname_slot
#define SetNameSlot setname_slot
#define GetTypeSlot gettype_slot
#define SetTypeSlot settype_slot
#define GetArgsSlot getargs_slot
#define SetArgsSlot setargs_slot
#define GetFormSlot getform_slot
#define SetFormSlot setform_slot
#define GetFunctionSlot getfunction_slot
#define SetFunctionSlot setfunction_slot
#define GetReadersSlot getreaders_slot
#define SetReadersSlot setreaders_slot
#define GetWritersSlot getwriters_slot
#define SetWritersSlot setwriters_slot
#define GetDocumentSlot getdocument_slot
#define SetDocumentSlot setdocument_slot
#define GetClassSlot getclass_slot
#define SetClassSlot setclass_slot
#define GetReadOnlySlot getreadonly_slot
#define SetReadOnlySlot setreadonly_slot
#define GetAllocationSlot getallocation_slot
#define SetAllocationSlot setallocation_slot
#define GetLocationSlot getlocation_slot
#define SetLocationSlot setlocation_slot
#define GetAccessSlot getaccess_slot
#define SetAccessSlot setaccess_slot
#define ClosStruct struct_clos
#define GetClassOfClos getclassof_clos
#define SetClassOfClos setclassof_clos
#define GetSlotClos getslot_clos
#define SetSlotClos setslot_clos
#define GetValueClos getvalue_clos
#define SetValueClos setvalue_clos
#define GetFuncallClos getfuncall_clos
#define SetFuncallClos setfuncall_clos
#define GetVersionClos getversion_clos
#define SetVersionClos setversion_clos
#define GetSlotVector getslotvector
#define SetSlotVector setslotvector
#define LenSlotVector lenslotvector
#define GetClosValue getclosvalue
#define SetClosValue setclosvalue
#define LenClosValue lenclosvalue
#define clos_standard_class_p clos_standard_class_p_debug
#define clos_standard_generic_p clos_standard_generic_p_debug
#define clos_standard_method_p clos_standard_method_p_debug
#define clos_standard_combination_p clos_standard_combination_p_debug
#define clos_standard_specializer_p clos_standard_specializer_p_debug
#else
#define SlotStruct SlotStruct_Low
#define GetNameSlot GetNameSlot_Low
#define SetNameSlot SetNameSlot_Low
#define GetTypeSlot GetTypeSlot_Low
#define SetTypeSlot SetTypeSlot_Low
#define GetArgsSlot GetArgsSlot_Low
#define SetArgsSlot SetArgsSlot_Low
#define GetFormSlot GetFormSlot_Low
#define SetFormSlot SetFormSlot_Low
#define GetFunctionSlot GetFunctionSlot_Low
#define SetFunctionSlot SetFunctionSlot_Low
#define GetReadersSlot GetReadersSlot_Low
#define SetReadersSlot SetReadersSlot_Low
#define GetWritersSlot GetWritersSlot_Low
#define SetWritersSlot SetWritersSlot_Low
#define GetDocumentSlot GetDocumentSlot_Low
#define SetDocumentSlot SetDocumentSlot_Low
#define GetClassSlot GetClassSlot_Low
#define SetClassSlot SetClassSlot_Low
#define GetReadOnlySlot GetReadOnlySlot_Low
#define SetReadOnlySlot SetReadOnlySlot_Low
#define GetAllocationSlot GetAllocationSlot_Low
#define SetAllocationSlot SetAllocationSlot_Low
#define GetLocationSlot GetLocationSlot_Low
#define SetLocationSlot SetLocationSlot_Low
#define GetAccessSlot GetAccessSlot_Low
#define SetAccessSlot SetAccessSlot_Low
#define ClosStruct ClosStruct_Low
#define GetClassOfClos GetClassOfClos_Low
#define SetClassOfClos SetClassOfClos_Low
#define GetSlotClos GetSlotClos_Low
#define SetSlotClos SetSlotClos_Low
#define GetValueClos GetValueClos_Low
#define SetValueClos SetValueClos_Low
#define GetFuncallClos GetFuncallClos_Low
#define SetFuncallClos SetFuncallClos_Low
#define GetVersionClos GetVersionClos_Low
#define SetVersionClos SetVersionClos_Low
#define GetSlotVector GetSlotVector_Low
#define SetSlotVector SetSlotVector_Low
#define LenSlotVector LenSlotVector_Low
#define GetClosValue GetClosValue_Low
#define SetClosValue SetClosValue_Low
#define LenClosValue LenClosValue_Low
#define clos_standard_class_p clos_standard_class_p_Low
#define clos_standard_generic_p clos_standard_generic_p_Low
#define clos_standard_method_p clos_standard_method_p_Low
#define clos_standard_combination_p clos_standard_combination_p_Low
#define clos_standard_specializer_p clos_standard_specializer_p_Low
#endif
/* access */
struct slot_struct *struct_slot(addr pos);
void getname_slot(addr pos, addr *ret);
void setname_slot(addr pos, addr value);
void gettype_slot(addr pos, addr *ret);
void settype_slot(addr pos, addr value);
void getargs_slot(addr pos, addr *ret);
void setargs_slot(addr pos, addr value);
void getform_slot(addr pos, addr *ret);
void setform_slot(addr pos, addr value);
void getfunction_slot(addr pos, addr *ret);
void setfunction_slot(addr pos, addr value);
void getreaders_slot(addr pos, addr *ret);
void setreaders_slot(addr pos, addr value);
void getwriters_slot(addr pos, addr *ret);
void setwriters_slot(addr pos, addr value);
void getdocument_slot(addr pos, addr *ret);
void setdocument_slot(addr pos, addr value);
void getclass_slot(addr pos, addr *ret);
void setclass_slot(addr pos, addr value);
void getreadonly_slot(addr pos, addr *ret);
void setreadonly_slot(addr pos, addr value);
void getallocation_slot(addr pos, int *ret);
void setallocation_slot(addr pos, int value);
void getlocation_slot(addr pos, size_t *ret);
void setlocation_slot(addr pos, size_t value);
void getaccess_slot(addr pos, size_t *ret);
void setaccess_slot(addr pos, size_t value);
struct clos_struct *struct_clos(addr pos);
void getclassof_clos(addr pos, addr *ret);
void setclassof_clos(addr pos, addr value);
void getslot_clos(addr pos, addr *ret);
void setslot_clos(addr pos, addr value);
void getvalue_clos(addr pos, addr *ret);
void setvalue_clos(addr pos, addr value);
void getfuncall_clos(addr pos, int *ret);
void setfuncall_clos(addr pos, int value);
void getversion_clos(addr pos, fixnum *ret);
void setversion_clos(addr pos, fixnum value);
void getslotvector(addr pos, size_t index, addr *ret);
void setslotvector(addr pos, size_t index, addr value);
void lenslotvector(addr pos, size_t *ret);
void getclosvalue(addr pos, size_t index, addr *ret);
void setclosvalue(addr pos, size_t index, addr value);
void lenclosvalue(addr pos, size_t *ret);
void clos_standard_ignore(int value);
int clos_standard_class_p_debug(addr pos);
int clos_standard_generic_p_debug(addr pos);
int clos_standard_method_p_debug(addr pos);
int clos_standard_combination_p_debug(addr pos);
int clos_standard_specializer_p_debug(addr pos);
/* allocate */
void slot_alloc(LocalRoot local, addr *ret);
void slot_local(LocalRoot local, addr *ret);
void slot_heap(addr *ret);
void slot_copy_alloc(LocalRoot local, addr *ret, addr slot);
void slot_copy_local(LocalRoot local, addr *ret, addr slot);
void slot_copy_heap(addr *ret, addr slot);
void slot_vector_alloc(LocalRoot local, addr *ret, size_t size);
void slot_vector_local(LocalRoot local, addr *ret, size_t size);
void slot_vector_heap(addr *ret, size_t size);
void slot_vector_copy_alloc(LocalRoot local, addr *ret, addr pos);
void slot_vector_copy_local(LocalRoot local, addr *ret, addr pos);
void slot_vector_copy_heap(addr *ret, addr pos);
void slot_vector_copyheap_alloc(LocalRoot local, addr *ret, addr pos);
void slot_vector_clear(addr pos);
void clos_value_heap(addr *ret, size_t size);
void clos_alloc(LocalRoot local, addr *ret, addr slots);
void clos_local(LocalRoot local, addr *ret, addr slots);
void clos_heap(addr *ret, addr slots);
void clos_destroy(addr pos);
void clos_swap(addr a, addr b);
void clos_copy_alloc(LocalRoot local, addr pos, addr *ret);
void clos_allcopy_alloc(LocalRoot local, addr pos, addr *ret);
void clos_getslots_heap(addr pos, addr *ret);
/* control */
int closp(addr pos);
int slotp(addr pos);
int clos_value_p(addr pos);
int slot_vector_p(addr pos);
int clos_funcall_p(addr pos);
int slot_class_p(addr pos);
int slot_instance_p(addr pos);
void clos_set_funcall(addr pos);
void slot_set_class(addr pos);
void slot_set_instance(addr pos);
int slot_set_allocation_(addr pos, addr value);
int clos_errorp(addr pos, size_t index, constindex name);
int clos_getp(addr pos, addr key, addr *ret);
int clos_setp(addr pos, addr key, addr value);
int clos_checkp_(addr pos, addr key, addr *value, int *ret);
int clos_get_(addr pos, addr key, addr *ret);
int clos_set_(addr pos, addr key, addr value);
int clos_check_(addr pos, addr key, addr *ret);
void clos_getelt(addr pos, size_t index, addr *ret);
void clos_setelt(addr pos, size_t index, addr value);
int clos_checkelt_(addr pos, size_t index, addr *ret);
int clos_getconst_(addr pos, constindex index, addr *ret);
int clos_setconst_(addr pos, constindex index, addr value);
int clos_checkconst_(addr pos, constindex index, addr *ret);
#define ClosGetConst_(p,n,r) clos_getconst_((p),CONSTANT_##n,(r))
#define ClosSetConst_(p,n,v) clos_setconst_((p),CONSTANT_##n,(v))
#define ClosCheckConst_(p,n,r) clos_checkconst_((p),CONSTANT_##n,(r))
/* check */
int clos_slot_exists_p(addr pos, addr name);
int clos_slot_boundp_nil(addr pos, addr name);
int clos_slot_boundp_(addr pos, addr name, int *ret);
int clos_slot_makunbound_nil_(addr pos, addr name, int *ret);
int clos_slot_makunbound_(addr pos, addr name);
/* talbe */
void clos_find_class_nil(addr name, addr *ret);
int clos_find_class_(addr name, addr *ret);
void clos_define_class(addr name, addr value);
void clos_find_generic_nil(addr name, addr *ret);
int clos_find_generic_(addr name, addr *ret);
int clos_define_generic_(addr name, addr value);
void clos_find_combination_nil(addr name, addr *ret);
int clos_find_combination_(addr name, addr *ret);
void clos_define_combination(addr name, addr value);
int clos_find_specializer_nil_(addr name, addr *ret);
int clos_find_specializer_(addr name, addr *ret);
int clos_define_specializer_(addr name, addr value);
void clos_forget_all_specializer_unsafe(void);
/* build */
void init_clos(void);
void build_clos(Execute ptr);
#endif
|
Junhua91/tornesol
|
algo-study/src/main/java/com/junhua/algorithm/datastructure/link/TwoLinkCross.java
|
<filename>algo-study/src/main/java/com/junhua/algorithm/datastructure/link/TwoLinkCross.java<gh_stars>1-10
package com.junhua.algorithm.datastructure.link;
/**
* 两个单链表相交
* 1. 两个无环链表:相交、不相交
* 2. 两个有环链表相交:三种拓扑结构(不相交、入环节点相同,入环节点不相等)
* 3. 一个有环,一个无环的链表不可能相交
*/
public class TwoLinkCross {
public static Node getIntersect(Node head1, Node head2) {
if (head1 == null || head2 == null) return null;
Node loop1 = getLoopNode(head1);
Node loop2 = getLoopNode(head2);
if (loop1 == null && loop2 == null) {
return getIntersectNodeWithoutCycle(head1, head2);
}
if (loop1 != null && loop2 != null) {
return getIntersectNodeBothLoop(head1, loop1, head2, loop2);
}
//不存在一个有环,一个无环的情况
return null;
}
/**
* 无环链表相交
*
* @param head1
* @param head2
* @return
*/
public static Node getIntersectNodeWithoutCycle(Node head1, Node head2) {
if (head1 == null || head2 == null) return null;
int n1 = 0, n2 = 0;
Node h1 = head1, h2 = head2;
while (h1.next != null || h2.next != null) {
if (h1.next != null) {
n1++;
h1 = h1.next;
}
if (h2.next != null) {
n2++;
h2 = h2.next;
}
}
if (h1 != h2) return null;
//让长链表先走到和短链表一样的长度,然后在一起走去找相同的节点
h1 = head1;
h2 = head2;
Node longNode = (n1 > n2) ? h1 : h2;
Node shortNode = (n1 > n2) ? h2 : h1;
int index = (n1 > n2) ? n1 : n2;
int limit = n1 > n2 ? n2 : n1;
while (index != limit) {
longNode = longNode.next;
index--;
}
while (shortNode != longNode) {
longNode = longNode.next;
shortNode = shortNode.next;
}
return longNode;
}
/**
* 两个有环链表
*
* @param head1
* @param loop1
* @param head2
* @param loop2
* @return
*/
public static Node getIntersectNodeBothLoop(Node head1, Node loop1, Node head2, Node loop2) {
if (loop1 == loop2) {
int n = 0;
Node cur = head1;
while (cur != loop1) {
cur = cur.next;
n++;
}
cur = head2;
while (cur != loop1) {
cur = cur.next;
n--;
}
cur = (n > 0) ? head1 : head2;
Node shortNode = (n > 0) ? head2 : head1;
n = Math.abs(n);
while (n != 0) {
cur = cur.next;
n--;
}
while (cur != shortNode) {
cur = cur.next;
shortNode = shortNode.next;
}
return cur;
} else {
Node cur = loop1.next;
while (cur != loop1) {
if (cur == loop2) {
return loop1;
}
cur = cur.next;
}
return null;
}
}
/**
* 获取入环的节点: 在快指针和慢指针相遇的时候,将快指针移动到head位置,然后再以相同的速度同时移动快慢指针,
* 直到快慢指针相交,此时的相交点就是链表的入环点
* <p>
* 无环则返回null、有环则返回入环的点
*
* @param head
*/
public static Node getLoopNode(Node head) {
if (head == null || head.next == null || head.next.next == null) return null;
Node fast = head.next.next;
Node slow = head.next;
while (slow != fast) {
if (fast == null && fast.next == null) return null;
fast = fast.next.next;
slow = slow.next;
}
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
public static void main(String[] args) {
// 1->2->3->4->5->6->7->null
Node head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(4);
head1.next.next.next.next = new Node(5);
head1.next.next.next.next.next = new Node(6);
head1.next.next.next.next.next.next = new Node(7);
// 0->9->8->6->7->null
Node head2 = new Node(0);
head2.next = new Node(9);
head2.next.next = new Node(8);
head2.next.next.next = head1.next.next.next.next.next; // 8->6
// System.out.println(getIntersectNodeWithoutCycle(head1, head2).value);
// 1->2->3->4->5->6->7->4...
head1 = new Node(1);
head1.next = new Node(2);
head1.next.next = new Node(3);
head1.next.next.next = new Node(4);
head1.next.next.next.next = new Node(5);
head1.next.next.next.next.next = new Node(6);
head1.next.next.next.next.next.next = new Node(7);
head1.next.next.next.next.next.next = head1.next.next.next; // 7->4
// System.out.println(getLoopNode(head1).value);
//
// 0->9->8->2...
head2 = new Node(0);
head2.next = new Node(9);
head2.next.next = new Node(8);
head2.next.next.next = head1.next; // 8->2
System.out.println(getIntersect(head1, head2).value);
// 0->9->8->6->4->5->6..
head2 = new Node(0);
head2.next = new Node(9);
head2.next.next = new Node(8);
head2.next.next.next = head1.next.next.next.next.next; // 8->6
System.out.println(getIntersect(head1, head2).value);
}
}
|
VU-libtech/OLE-INST
|
ole-app/olefs/src/it/java/org/kuali/ole/deliver/bo/PatronBillPayment_IT.java
|
<filename>ole-app/olefs/src/it/java/org/kuali/ole/deliver/bo/PatronBillPayment_IT.java
package org.kuali.ole.deliver.bo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kuali.ole.SpringBaseTestCase;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.KRADServiceLocator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static junit.framework.Assert.assertEquals;
/**
* Created with IntelliJ IDEA.
* User: ?
* Date: 11/6/12
* Time: 11:34 AM
* To change this template use File | Settings | File Templates.
*/
public class PatronBillPayment_IT extends SpringBaseTestCase {
private BusinessObjectService boService ;
/**
* Gets the businessObjectService attribute.
* @return Returns the businessObjectService
*/
private BusinessObjectService getBusinessObjectService() {
if (null == boService) {
boService = KRADServiceLocator.getBusinessObjectService();
}
return boService;
}
@Test
@Transactional
public void testSaveAndSearch() {
PatronBillPayment patronBillPayment = new PatronBillPayment();
FeeType feeType = new FeeType();
patronBillPayment.setBillDate(new java.sql.Date(new Date().getTime()));
patronBillPayment.setBillNumber("9999");
patronBillPayment.setPatronId("Mock PatronId");
/* patronBillPayment.setFirstName("Mock FirstName");
patronBillPayment.setLastName("Mock LastName");*/
patronBillPayment.setOperatorId("Mock OperatorId");
//patronBillPayment.setMachineId("Mock MachineId"); //commented for jira OLE-5675
feeType.setFeeType("Mock Fine");
feeType.setBillNumber("9999");
feeType.setFeeAmount(new KualiDecimal(100.00));
patronBillPayment.setTotalAmount(new KualiDecimal(100.00));
//OlePaymentStatus olePaymentStatus = getPaymentStatus();
OlePaymentStatus olePaymentStatus = new OlePaymentStatus();
olePaymentStatus.setPaymentStatusId("1");
feeType.setPaymentStatusCode("1");
feeType.setPaymentStatus("1");
feeType.setOlePaymentStatus(olePaymentStatus);
/* if(olePaymentStatus!=null){
patronBillPayment.setOlePaymentStatus(olePaymentStatus);
patronBillPayment.setPaymentStatus(olePaymentStatus.getPaymentStatusId());
}*/
boService = KRADServiceLocator.getBusinessObjectService();
boService.save(patronBillPayment);
boService.save(feeType);
PatronBillPayment patronBillPaymentService = boService.findBySinglePrimaryKey(PatronBillPayment.class,patronBillPayment.getBillNumber());
assertEquals("Mock PatronId",patronBillPaymentService.getPatronId());
// assertEquals("Mock LastName",patronBillPaymentService.getLastName());
}
private OlePaymentStatus getPaymentStatus(){
Map statusMap = new HashMap();
statusMap.put("paymentStatusName", "Outstanding");
List<OlePaymentStatus> olePaymentStatusList = (List<OlePaymentStatus>)getBusinessObjectService().findMatching(OlePaymentStatus.class,statusMap);
return olePaymentStatusList!=null && olePaymentStatusList.size()>0 ? olePaymentStatusList.get(0): null;
}
}
|
ScalablyTyped/SlinkyTyped
|
p/pulumi__aws/src/main/scala/typingsSlinky/pulumiAws/outputMod/ec2/LaunchTemplateInstanceMarketOptions.scala
|
package typingsSlinky.pulumiAws.outputMod.ec2
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait LaunchTemplateInstanceMarketOptions extends StObject {
/**
* The market type. Can be `spot`.
*/
var marketType: js.UndefOr[String] = js.native
/**
* The options for [Spot Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html)
*/
var spotOptions: js.UndefOr[LaunchTemplateInstanceMarketOptionsSpotOptions] = js.native
}
object LaunchTemplateInstanceMarketOptions {
@scala.inline
def apply(): LaunchTemplateInstanceMarketOptions = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[LaunchTemplateInstanceMarketOptions]
}
@scala.inline
implicit class LaunchTemplateInstanceMarketOptionsMutableBuilder[Self <: LaunchTemplateInstanceMarketOptions] (val x: Self) extends AnyVal {
@scala.inline
def setMarketType(value: String): Self = StObject.set(x, "marketType", value.asInstanceOf[js.Any])
@scala.inline
def setMarketTypeUndefined: Self = StObject.set(x, "marketType", js.undefined)
@scala.inline
def setSpotOptions(value: LaunchTemplateInstanceMarketOptionsSpotOptions): Self = StObject.set(x, "spotOptions", value.asInstanceOf[js.Any])
@scala.inline
def setSpotOptionsUndefined: Self = StObject.set(x, "spotOptions", js.undefined)
}
}
|
macedo22/spectre
|
tests/Unit/IO/Observers/Test_ArrayComponentId.cpp
|
<filename>tests/Unit/IO/Observers/Test_ArrayComponentId.cpp<gh_stars>100-1000
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <ckarrayindex.h>
#include <functional>
#include <type_traits>
#include "Domain/Structure/ElementId.hpp"
#include "Framework/TestHelpers.hpp"
#include "IO/Observer/ArrayComponentId.hpp"
#include "Parallel/ArrayIndex.hpp"
namespace {
struct Component0 {};
struct Component1 {};
SPECTRE_TEST_CASE("Unit.IO.Observers.ArrayComponentId", "[Unit][Observers]") {
using ArrayComponentId = observers::ArrayComponentId;
using Hash = std::hash<ArrayComponentId>;
ArrayComponentId c0id0{std::add_pointer_t<Component0>{nullptr},
Parallel::ArrayIndex<ElementId<1>>(ElementId<1>{0})};
ArrayComponentId c0id1{std::add_pointer_t<Component0>{nullptr},
Parallel::ArrayIndex<ElementId<1>>(ElementId<1>{1})};
ArrayComponentId c1id0{std::add_pointer_t<Component1>{nullptr},
Parallel::ArrayIndex<ElementId<1>>(ElementId<1>{0})};
ArrayComponentId c1id1{std::add_pointer_t<Component1>{nullptr},
Parallel::ArrayIndex<ElementId<1>>(ElementId<1>{1})};
CHECK(c0id0 == c0id0);
CHECK_FALSE(c0id0 != c0id0);
CHECK(c0id0 != c0id1);
CHECK(c0id0 != c1id0);
CHECK(c0id0 != c1id1);
CHECK(c0id0.component_id() == c0id0.component_id());
CHECK_FALSE(c0id0.component_id() != c0id0.component_id());
CHECK(c0id0.component_id() == c0id1.component_id());
CHECK(c0id0.component_id() != c1id0.component_id());
CHECK(c0id0.component_id() != c1id1.component_id());
CHECK(c0id0.array_index() == c0id0.array_index());
CHECK_FALSE(c0id0.array_index() == c0id1.array_index());
CHECK(c0id0.array_index() == c1id0.array_index());
CHECK_FALSE(c0id0.array_index() == c1id1.array_index());
CHECK(Hash{}(c0id0) == Hash{}(c0id0));
CHECK(Hash{}(c0id0) != Hash{}(c0id1));
CHECK(Hash{}(c0id0) != Hash{}(c1id0));
CHECK(Hash{}(c0id0) != Hash{}(c1id1));
CHECK(Hash{}(c1id0) == Hash{}(c1id0));
CHECK(Hash{}(c1id0) != Hash{}(c1id1));
// Test PUP
test_serialization(c0id0);
test_serialization(c0id1);
test_serialization(c1id0);
test_serialization(c1id1);
}
} // namespace
|
utercero/SimionZoo
|
RLSimion/Lib/critic-tdc-lambda.cpp
|
/*
SimionZoo: A framework for online model-free Reinforcement Learning on continuous
control problems
Copyright (c) 2016 SimionSoft. https://github.com/simionsoft
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.
*/
#include "critic.h"
#include "vfa.h"
#include "features.h"
#include "etraces.h"
#include "experiment.h"
#include "vfa-critic.h"
#include "config.h"
#include "parameters-numeric.h"
#include "app.h"
#include "simgod.h"
TDCLambdaCritic::TDCLambdaCritic(ConfigNode* pConfigNode): VLearnerCritic(pConfigNode)
{
m_z= CHILD_OBJECT<ETraces>(pConfigNode,"E-Traces","Elilgibility traces of the critic",true);
m_z->setName("Critic/E-Traces");
m_s_features = new FeatureList("Critic/s");
m_s_p_features = new FeatureList("Critic/s_p");
m_a = new FeatureList("Critic/a");
m_b= new FeatureList("Critic/b");
m_omega = new FeatureList("Critic/omega");
m_pAlpha= CHILD_OBJECT_FACTORY<NumericValue>(pConfigNode,"Alpha","Learning gain of the critic");
m_pBeta = CHILD_OBJECT_FACTORY<NumericValue>(pConfigNode, "Beta","Learning gain applied to the omega vector");
}
TDCLambdaCritic::~TDCLambdaCritic()
{
delete m_b;
delete m_s_features;
delete m_s_p_features;
delete m_a;
delete m_omega;
}
/// <summary>
/// Updates the value function using the TDC update rule
/// </summary>
/// <param name="s">Initial state</param>
/// <param name="a">Action</param>
/// <param name="s_p">Resultant state</param>
/// <param name="r">Reward</param>
/// <param name="rho">Importance sampling</param>
/// <returns>The Temporal-Difference error</returns>
double TDCLambdaCritic::update(const State *s, const Action *a, const State *s_p, double r, double rho)
{
if (m_pAlpha->get()==0.0) return 0.0;
if (SimionApp::get()->pExperiment->isFirstStep())
{
m_omega->clear();
}
//double rho = 1.0;
m_pVFunction->getFeatures(s, m_s_features);
m_pVFunction->getFeatures(s_p, m_s_p_features);
//delta= r + gamma*omega(x_{t+1})- omega(x_t)
double oldValue = m_pVFunction->get(m_s_features);
double newValue = m_pVFunction->get(m_s_p_features);
double gamma = SimionApp::get()->pSimGod->getGamma();
double td= rho*r + gamma * newValue - oldValue;
//z_{k+1}= rho*gamma*lambda*z_k + omega(x_t)
m_z->update(rho*gamma);
m_z->addFeatureList(m_s_features,rho);
//\theta_{t+1}=\theta_{t}+\alpha(z_t*delta_t-gamma*rho(1-\lambda)\phi_t*(z_{t+1}^T*w_t))
//innerprod1= omega(x_t)^T*w //<----- used in the update of w
m_a->clear();
m_a->copy(m_s_p_features);
double innerprod1= m_a->innerProduct(m_omega);
//innerprod2= z_{t+1}^T*w_t
m_a->clear();
m_a->copy(m_z.ptr());
double innerprod2 = m_a->innerProduct(m_omega);
//theta_{t+1}=theta_t+alpha(z_t*delta_t)
m_pVFunction->add(m_z.ptr(), m_pAlpha->get() *td);
//theta_{t+1}= theta_t - gamma*rho(1-\lambda)*phi_t*innerprod2
double lambda = m_z->getLambda();
m_pVFunction->add(m_s_p_features, -1.0*gamma*rho*(1.0 - lambda)*innerprod2);
//omega_{t+1}=omega_t+beta(z_{t+1}*td - phi_{t+1}(phi{t+1}^T * omega_t)
double beta = m_pBeta->get();
m_omega->addFeatureList(m_z.ptr(), beta*td);
m_omega->addFeatureList(m_s_p_features,- innerprod1);
m_omega->applyThreshold(0.0001);
return td;
}
|
RoySRose/Monster
|
src/main/java/org/monster/build/initialProvider/buildSets/BaseBuild.java
|
package org.monster.build.initialProvider.buildSets;
import bwapi.TechType;
import bwapi.TilePosition;
import bwapi.UnitType;
import bwapi.UpgradeType;
import org.monster.build.base.BuildManager;
import org.monster.build.base.BuildOrderQueue;
import org.monster.build.base.SeedPositionStrategy;
public class BaseBuild {
public static void queueBuild(boolean blocking, UnitType... types) {
BuildOrderQueue bq = BuildManager.Instance().buildQueue;
SeedPositionStrategy defaultSeedPosition = SeedPositionStrategy.MainBaseLocation;
for (UnitType type : types) {
bq.queueAsLowestPriority(type, defaultSeedPosition, blocking);
}
}
public void queueBuild(boolean blocking, UnitType type, SeedPositionStrategy seedPosition) {
BuildOrderQueue bq = BuildManager.Instance().buildQueue;
bq.queueAsLowestPriority(type, seedPosition, blocking);
}
public void queueBuild(boolean blocking, UnitType type, TilePosition tilePosition) {
BuildOrderQueue bq = BuildManager.Instance().buildQueue;
// System.out.println("tilePosition ==> " + tilePosition);
if (tilePosition == TilePosition.None) {
// System.out.println("tilePosition is None");
bq.queueAsLowestPriority(type, SeedPositionStrategy.MainBaseLocation, blocking);
} else {
bq.queueAsLowestPriority(type, tilePosition, blocking);
}
}
public void queueBuild(TechType type) {
BuildOrderQueue bq = BuildManager.Instance().buildQueue;
bq.queueAsLowestPriority(type);
}
public void queueBuild(UpgradeType type) {
BuildOrderQueue bq = BuildManager.Instance().buildQueue;
bq.queueAsLowestPriority(type);
}
}
|
StephanPirnbaum/jqa-ddd-plugin
|
jqassistant-java-ddd-annotations/src/main/java/org/jqassistant/contrib/plugin/ddd/annotation/DDD.java
|
package org.jqassistant.contrib.plugin.ddd.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Representation of the DDD concepts.
*
* @author stephan.pirnbaum
*/
@Target({})
public @interface DDD {
/**
* jQAssistant annotation to mark a Java package as part of the specific Bounded Context. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface BoundedContext {
/**
* The name of the {@link BoundedContext}.
*
* @return The Bounded Contexts name.
*/
String name();
/**
* The name of the {@link BoundedContext}s this {@link BoundedContext} may depend on.
*
* @return All {@link BoundedContext}s to which dependencies are allowed.
*/
String[] dependsOn() default {};
}
/**
* jQAssistant annotation to mark a Java type as DDD Repository. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface Repository { }
/**
* jQAssistant annotation to mark a Java type as DDD Value Object. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface ValueObject { }
/**
* jQAssistant annotation to mark a Java type as DDD Factory. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface Factory { }
/**
* jQAssistant annotation to mark a Java type as DDD Service. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface Service { }
/**
* jQAssistant annotation to mark a Java type as DDD Entity. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface Entity { }
/**
* jQAssistant annotation to mark a Java type as DDD AggregateRoot. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface AggregateRoot { }
/**
* jQAssistant annotation to mark a Java type as DDD Domain Event. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface DomainEvent { }
/**
* Representation of the DDD Layer concept.
*/
@Target({})
@interface Layer {
/**
* jQAssistant annotation to mark a Java type as part of the Interface Layer. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface InterfaceLayer {}
/**
* jQAssistant annotation to mark a Java type as part of the Application Layer. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface ApplicationLayer {}
/**
* jQAssistant annotation to mark a Java type as part of the Domain Layer. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface DomainLayer {}
/**
* jQAssistant annotation to mark a Java type as part of the Infrastructure Layer. When applied to a package, the annotation is in effect for all contained types.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.PACKAGE})
@interface InfrastructureLayer {}
}
}
|
mark-watson/javascript_intelligent_systems
|
src/aws_s3_read.js
|
<filename>src/aws_s3_read.js
// @flow
const aws = require('aws-sdk');
aws.config.region = 'us-east-1';
const s3 = new aws.S3(), index, bucket;
s3.listBuckets(function(err, data) {
console.log("\n** list all buckets owned by this account:\n");
for (index in data.Buckets) {
bucket = data.Buckets[index];
console.log("Bucket: ", bucket.Name, ' : ', bucket.CreationDate);
}
});
const params = {
Bucket: 'mark64323762346hfjhjfs'
};
s3.listObjects(params, function(error, data) {
console.log("\n** list things in our test bucket:\n");
if (error) {
console.log("Error: " + error);
} else {
console.log(data);
}
});
const params = {
Bucket: 'mark64323762346hfjhjfs',
Key: 'mykey1',
ResponseContentType: 'string'
};
s3.getObject(params, function(error, data) {
console.log("\n** print out the one object added to test bucket:\n");
if (error) {
console.log("Error: " + error);
} else {
console.log(data);
// get body of response and convert Buffer to string:
console.log("\nBody as string: " + data.Body.toString());
}
});
|
mesinger/alphavantagecpp
|
alphavantagecpp/src/alphavantagecpp/api/sectorperformances.cpp
|
#include "alphavantagecpp/api/sectorperformances/sectorperformances.hpp"
using namespace av;
SECTOR::SECTOR(const std::string& key)
:AlphaVantageRequest("SECTOR", key)
{
}
|
pdpdds/sdldualsystem
|
sdl1/theclue/sound/newsound.c
|
<gh_stars>0
/* _________ _______
/ ___/ __ \/ __/ _ \ Der Clou!
/ /__/ /_/ /\ \/ ___/ Open Source Project
\___/\____/___/_/ http://cosp.sourceforge.net
Based on the original by neo Software GmbH
*/
/****************************************************************************
Portions copyright (c) 2005 <NAME>
Please read the license terms which should be contained with this
distribution.
****************************************************************************/
#include "SDL.h"
#include "disk/disk.h"
#include "sound/fx.h"
#include "sound/newsound.h"
#include "sound/mxr.h"
char currSoundName[256];
int currMusicVolume = 0;
int targetMusicVolume = 0;
void sndInit(void)
{
currSoundName[0] = '\0';
currMusicVolume = Config.MusicVolume;
targetMusicVolume = Config.MusicVolume;
}
void sndDone(void)
{
}
void sndPlaySound(char *name, ulong mode)
{
char path[256];
if (pAudioMixer) {
if (_stricmp(currSoundName, name)) {
strcpy(currSoundName, name);
dskBuildPathName(SOUND_DIRECTORY, name, path);
MXR_SetInput(pAudioMixer, MXR_INPUT_MUSIC, MXR_CreateInputHSC(path));
targetMusicVolume = Config.MusicVolume;
}
}
}
char *sndGetCurrSoundName(void)
{
return currSoundName;
}
// 2014-07-17 LucyG : called from inpDoPseudoMultiTasking
void sndDoFading(void)
{
if (currMusicVolume < targetMusicVolume) {
currMusicVolume++;
} else if (currMusicVolume > targetMusicVolume) {
currMusicVolume--;
}
}
void sndFading(short int targetVol)
{
if (pAudioMixer) {
/* 2014-07-17 LucyG : this is called from dialog.c (and intro.c)
with targetVol = 16 before and 0 after voice playback */
if (!targetVol) {
targetMusicVolume = Config.MusicVolume;
} else {
targetMusicVolume = Config.MusicVolume / 4;
}
}
}
void sndStopSound(ubyte dummy)
{
MXR_SetInput(pAudioMixer, MXR_INPUT_MUSIC, NULL);
}
|
mdsol-share/crichton
|
lib/crichton/descriptor/options_decorator.rb
|
require 'crichton/descriptor/options'
module Crichton
module Descriptor
##
# Decorates options for select lists to access source values from a target.
class OptionsDecorator < Options
def initialize(descriptor, target)
super(descriptor.descriptor_document)
@target = target
end
def options
@decorated_options ||= if super && (external = super[EXTERNAL])
source = external[SOURCE]
@target.respond_to?(source) ? respond_to_method(source, super) : super
else
super
end
end
private
def respond_to_method(method, options)
result = @target.send(method, options)
raise_if_invalid(result.is_a?(Hash), throw("#{method} method on target must return Hash object"))
[EXTERNAL, LIST, HASH].each do |x|
if opts = result[x]
raise_if_invalid(conditions[x].call(opts), throw)
return result
end
end
throw("#{result} is invalid response type.").call
end
def conditions
{
EXTERNAL => ->(opts) { (opts[SOURCE] && opts[TARGET] && opts[PROMPT]) },
HASH => ->(opts) { opts.is_a?(Hash) },
LIST => ->(opts) { opts.is_a?(Array) }
}
end
def raise_if_invalid(condition, throw_function)
throw_function.call unless condition
end
def throw(message = '')
->(message){ raise Crichton::TargetMethodResponseError, message }
end
end
end
end
|
madanagopaltcomcast/pxCore
|
src/rtJsonUtils.cpp
|
/*
pxCore Copyright 2005-2018 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "rtJsonUtils.h"
#include "rtObject.h"
#include <rapidjson/document.h>
#include <rapidjson/filereadstream.h>
#include <rapidjson/error/en.h>
// write
#include <rapidjson/filewritestream.h>
#include <rapidjson/writer.h>
namespace
{
const int FILE_BUFFER_SIZE = 65536;
rtError jsonValue2rtValue(const rapidjson::Value& jsonValue, rtValue& v)
{
// json array
if (jsonValue.IsArray())
{
rtArrayObject* o = new rtArrayObject;
for (rapidjson::SizeType k = 0; k < jsonValue.Size(); k++)
{
const rapidjson::Value& val = jsonValue[k];
rtValue val2;
if (jsonValue2rtValue(val, val2) == RT_OK)
o->pushBack(val2);
}
v = o;
}
// json object
else if (jsonValue.IsObject())
{
rtMapObject* o = new rtMapObject;
for (rapidjson::Value::ConstMemberIterator itr = jsonValue.MemberBegin(); itr != jsonValue.MemberEnd(); ++itr)
{
const rapidjson::Value& key = itr->name;
const rapidjson::Value& val = itr->value;
if (!key.IsString())
{
rtLogError("%s : map key is not string", __FUNCTION__);
continue;
}
rtValue val2;
if (jsonValue2rtValue(val, val2) == RT_OK)
o->Set(key.GetString(), &val2);
}
v = o;
}
// json string
else if (jsonValue.IsString())
v = jsonValue.GetString();
// json number
else if (jsonValue.IsUint())
v = jsonValue.GetUint();
else if (jsonValue.IsInt())
v = jsonValue.GetInt();
else if (jsonValue.IsInt64())
v = jsonValue.GetInt64();
else if (jsonValue.IsUint64())
v = jsonValue.GetUint64();
else if (jsonValue.IsDouble())
v = jsonValue.GetDouble();
// other types
else if (jsonValue.IsBool())
v = jsonValue.GetBool();
else if (jsonValue.IsNull())
v.setEmpty();
else
{
rtLogError("%s : value type is not supported", __FUNCTION__);
return RT_ERROR_NOT_IMPLEMENTED;
}
return RT_OK;
}
rtError rtValue2jsonValue(const rtValue& v, rapidjson::Document& doc, rapidjson::Value& jsonValue)
{
if (v.isEmpty())
jsonValue.SetNull();
else
{
rtType t = v.getType();
if (t == RT_boolType)
jsonValue = v.toBool();
else if (t == RT_int8_tType)
jsonValue = v.toInt8();
else if (t == RT_uint8_tType)
jsonValue = v.toUInt8();
else if (t == RT_intType || t == RT_int32_tType)
jsonValue = v.toInt32();
else if (t == RT_uint32_tType)
jsonValue = v.toUInt32();
else if (t == RT_int64_tType)
jsonValue = v.toInt64();
else if (t == RT_uint64_tType)
jsonValue = v.toUInt64();
else if (t == RT_floatType)
jsonValue = v.toFloat();
else if (t == RT_doubleType)
jsonValue = v.toDouble();
else if (t == RT_stringType || t == RT_rtStringType)
{
rtString s = v.toString();
jsonValue.SetString(s.cString(), s.byteLength(), doc.GetAllocator());
}
else
{
rtLogWarn("%s : unsupported value type: %c", __FUNCTION__, t);
return RT_ERROR_NOT_IMPLEMENTED;
}
}
return RT_OK;
}
}
rtError json2rtValue(const char* json, rtValue& val)
{
if (!json || *json == 0)
{
rtLogError("%s : empty", __FUNCTION__);
return RT_ERROR_INVALID_ARG;
}
rapidjson::Document doc;
rapidjson::ParseResult result = doc.Parse(json);
if (!result)
{
rapidjson::ParseErrorCode e = doc.GetParseError();
rtLogError("%s : [JSON parse error : %s (%ld)]", __FUNCTION__, rapidjson::GetParseError_En(e), result.Offset());
return RT_ERROR;
}
return jsonValue2rtValue(doc, val);
}
rtError jsonFile2rtValue(const char* path, rtValue& val)
{
if (!path || *path == 0)
{
rtLogError("%s : empty", __FUNCTION__);
return RT_ERROR_INVALID_ARG;
}
FILE* fp = fopen(path, "rb");
if (NULL == fp)
{
rtLogError("%s : cannot open '%s'", __FUNCTION__, path);
return RT_ERROR;
}
rapidjson::Document doc;
rapidjson::ParseResult result;
char readBuffer[FILE_BUFFER_SIZE];
memset(readBuffer, 0, sizeof(readBuffer));
rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
result = doc.ParseStream(is);
fclose(fp);
if (!result)
{
rapidjson::ParseErrorCode e = doc.GetParseError();
rtLogError("%s : [JSON parse error : %s (%ld)]", __FUNCTION__, rapidjson::GetParseError_En(e), result.Offset());
return RT_ERROR;
}
return jsonValue2rtValue(doc, val);
}
rtError rtValue2jsonFile(const rtValue& val, const char* path)
{
if (val.getType() != RT_objectType)
{
rtLogError("%s : value type is not supported", __FUNCTION__);
return RT_ERROR_NOT_IMPLEMENTED;
}
rapidjson::Document doc;
doc.SetObject();
rtObjectRef obj = val.toObject();
rtValue allKeys;
obj->Get("allKeys", &allKeys);
rtArrayObject* arr = (rtArrayObject*) allKeys.toObject().getPtr();
for (uint32_t i = 0; i < arr->length(); ++i)
{
rtString k = arr->get<rtString>(i);
rtValue v = obj.get<rtValue>(k);
rapidjson::Value j;
rtError e = rtValue2jsonValue(v, doc, j);
if (e != RT_OK)
return e;
rapidjson::Value key;
key.SetString(k.cString(), k.byteLength(), doc.GetAllocator());
doc.AddMember(key, j, doc.GetAllocator());
}
FILE* fp = fopen(path, "wb");
if (NULL == fp)
{
rtLogError("%s : cannot open '%s'", __FUNCTION__, path);
return RT_ERROR;
}
char writeBuffer[FILE_BUFFER_SIZE];
rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
rapidjson::Writer<rapidjson::FileWriteStream> writer(os);
doc.Accept(writer);
fclose(fp);
return RT_OK;
}
rtError json2rtObject(const char* json, rtObjectRef& obj)
{
rtError e;
rtValue v;
e = json2rtValue(json, v);
if (e == RT_OK)
{
rtObjectRef o;
e = v.getObject(o);
if (e == RT_OK)
obj = o;
}
return e;
}
|
UofTL/yard-sale
|
client/src/App.js
|
<filename>client/src/App.js
import React, { Component } from 'react';
// import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Redirect, Router, Route, Switch } from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import SafetyTips from "./pages/SafetyTips";
import Products from "./pages/Products";
import ShowProduct from "./pages/ShowProduct";
import NewProduct from "./pages/NewProduct";
import MemberProfile from "./pages/MemberProfile";
import MemberSignUp from "./pages/MemberSignUp";
import NoMatch from "./pages/NoMatch";
import EditListing from "./pages/EditListing";
import Navigation from "./components/Navigation";
import Footer from "./components/Footer";
import Wrapper from "./components/Wrapper";
import 'bootstrap/dist/css/bootstrap.min.css';
// Auth0 Adds ...
import Callback from './Callback/Callback';
import Auth from './Auth/Auth';
import history from './history';
const auth = new Auth();
const handleAuthentication = ({ location }) => {
if (/access_token|id_token|error/.test(location.hash)) {
auth.handleAuthentication();
}
}
// ... Auth0 Adds
class App extends Component {
constructor(props) {
super(props)
this.state = {
email: "",
password: "",
_id: ""
}
};
render() {
return (
// <Router>
<Router history={history}>
<div>
{/* <Navigation auth={auth} {...this.props} /> */}
<Route path="/" render={(props) => <Navigation auth={auth} {...props} />} />
<Route path="/callback" render={(newProps) => {
handleAuthentication(newProps);
return <Callback {...this.props} />
}} />
<Wrapper>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/home" component={Home} />
<Route exact path="/about" component={About} />
<Route exact path="/safetyTips" component={SafetyTips} />
<Route exact path="/products" component={Products} />
<Route exact path="/products/:id" component={ShowProduct} />
<Route exact path="/newProduct" component={NewProduct} />
<Route exact path="/memberSignUp" component={MemberSignUp} />
<Route exact path="/memberProfile" component={MemberProfile} />
<Route exact path="/memberProfile/:id" component={EditListing} />
<Route component={NoMatch} />
</ Switch>
</Wrapper>
<Footer />
</div>
</Router >
);
}
}
export default App;
|
C-B4/unifiedpush-server
|
service/src/main/java/org/jboss/aerogear/unifiedpush/service/metrics/DeleteOldPushMessageInformationScheduler.java
|
<filename>service/src/main/java/org/jboss/aerogear/unifiedpush/service/metrics/DeleteOldPushMessageInformationScheduler.java
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.aerogear.unifiedpush.service.metrics;
import javax.inject.Inject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class DeleteOldPushMessageInformationScheduler {
@Inject
private IPushMessageMetricsService service;
/**
* Job that triggers a delete of outdated metric information from the Server.
*
* Note: Occurring every day at midnight in the default time zone associated with the container
* in which the application is executing. These are the default values from the @Schedule annotation.
*/
@Scheduled(cron = "0 24 * * *")
public void deleteOutdatedFlatMetrics() {
service.deleteOutdatedFlatPushInformationData();
}
}
|
lechium/iOS1351Headers
|
System/Library/PrivateFrameworks/GameCenterUI.framework/GKTurnBasedMatchDetailViewController.h
|
<reponame>lechium/iOS1351Headers<filename>System/Library/PrivateFrameworks/GameCenterUI.framework/GKTurnBasedMatchDetailViewController.h
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:17:18 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/GameCenterUI.framework/GameCenterUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
#import <GameCenterUI/GKBasicCollectionViewController.h>
@protocol GKTurnBasedMatchDetailViewControllerDelegate;
@class NSObject, GKTurnBasedMatch, GKGame, GKTurnBasedParticipantsDataSource, GKTurnBasedMatchDetailHeaderView;
@interface GKTurnBasedMatchDetailViewController : GKBasicCollectionViewController {
BOOL _isInGame;
BOOL _shouldShowPlay;
BOOL _shouldShowQuit;
BOOL _didFloatInBubbles;
BOOL _isCompactHeader;
NSObject*<GKTurnBasedMatchDetailViewControllerDelegate> _delegateWeak;
GKTurnBasedMatch* _match;
GKGame* _game;
GKTurnBasedParticipantsDataSource* _participantsDataSource;
GKTurnBasedMatchDetailHeaderView* _headerView;
}
@property (nonatomic,retain) GKTurnBasedParticipantsDataSource * participantsDataSource; //@synthesize participantsDataSource=_participantsDataSource - In the implementation block
@property (nonatomic,retain) GKTurnBasedMatchDetailHeaderView * headerView; //@synthesize headerView=_headerView - In the implementation block
@property (assign,nonatomic) BOOL didFloatInBubbles; //@synthesize didFloatInBubbles=_didFloatInBubbles - In the implementation block
@property (assign,nonatomic) BOOL isCompactHeader; //@synthesize isCompactHeader=_isCompactHeader - In the implementation block
@property (nonatomic,retain) GKTurnBasedMatch * match; //@synthesize match=_match - In the implementation block
@property (nonatomic,retain) GKGame * game; //@synthesize game=_game - In the implementation block
@property (assign,nonatomic) BOOL isInGame; //@synthesize isInGame=_isInGame - In the implementation block
@property (assign,nonatomic) BOOL shouldShowPlay; //@synthesize shouldShowPlay=_shouldShowPlay - In the implementation block
@property (assign,nonatomic) BOOL shouldShowQuit; //@synthesize shouldShowQuit=_shouldShowQuit - In the implementation block
@property (assign,nonatomic) NSObject*<GKTurnBasedMatchDetailViewControllerDelegate> delegate; //@synthesize delegateWeak=_delegateWeak - In the implementation block
-(id)init;
-(void)dealloc;
-(NSObject*<GKTurnBasedMatchDetailViewControllerDelegate>)delegate;
-(void)setDelegate:(NSObject*<GKTurnBasedMatchDetailViewControllerDelegate>)arg1 ;
-(void)observeValueForKeyPath:(id)arg1 ofObject:(id)arg2 change:(id)arg3 context:(void*)arg4 ;
-(void)traitCollectionDidChange:(id)arg1 ;
-(void)viewWillAppear:(BOOL)arg1 ;
-(void)viewWillDisappear:(BOOL)arg1 ;
-(void)viewDidLoad;
-(void)viewDidAppear:(BOOL)arg1 ;
-(GKTurnBasedMatchDetailHeaderView *)headerView;
-(void)setHeaderView:(GKTurnBasedMatchDetailHeaderView *)arg1 ;
-(BOOL)collectionView:(id)arg1 shouldHighlightItemAtIndexPath:(id)arg2 ;
-(BOOL)collectionView:(id)arg1 shouldSelectItemAtIndexPath:(id)arg2 ;
-(void)acceptInvitation:(id)arg1 ;
-(void)declineInvitation:(id)arg1 ;
-(GKGame *)game;
-(void)setGame:(GKGame *)arg1 ;
-(GKTurnBasedMatch *)match;
-(void)setActionButtonEnabled:(BOOL)arg1 ;
-(void)setMatch:(GKTurnBasedMatch *)arg1 ;
-(void)didEnterNoContentState;
-(void)didUpdateModel;
-(void)configureDataSource;
-(void)floatInBubbles;
-(BOOL)shouldShowPlay;
-(void)setShouldShowPlay:(BOOL)arg1 ;
-(void)chooseMatch:(id)arg1 ;
-(void)quitMatch:(id)arg1 ;
-(void)removeMatch:(id)arg1 ;
-(void)handleTurnBasedEvent:(id)arg1 ;
-(BOOL)shouldShowQuit;
-(void)setShouldShowQuit:(BOOL)arg1 ;
-(GKTurnBasedParticipantsDataSource *)participantsDataSource;
-(void)configureViewFactories;
-(void)configureMatchDetailHeader:(id)arg1 ;
-(void)setNeedsFloatInBubbles;
-(void)setIsCompactHeader:(BOOL)arg1 ;
-(void)updateHeader;
-(void)buyButtonPressed:(id)arg1 ;
-(void)setupActionButton;
-(void)animateOutBubbleWithFocus:(long long)arg1 completion:(/*^block*/id)arg2 ;
-(id)_gkRepresentedObject;
-(BOOL)isInGame;
-(void)setIsInGame:(BOOL)arg1 ;
-(void)setParticipantsDataSource:(GKTurnBasedParticipantsDataSource *)arg1 ;
-(BOOL)didFloatInBubbles;
-(void)setDidFloatInBubbles:(BOOL)arg1 ;
-(BOOL)isCompactHeader;
@end
|
juamecos/frontend-merng-online-shop-react
|
src/App.js
|
import React, { lazy, Suspense } from "react";
import { ApolloProvider } from "@apollo/client";
import client from "./config/apollo";
import { Provider } from "react-redux";
import store from "./redux/store";
import "bootstrap/dist/css/bootstrap.min.css";
import "react-bootstrap-table-next/dist/react-bootstrap-table2.min.css";
import "react-bootstrap-table2-paginator/dist/react-bootstrap-table2-paginator.min.css";
const Navigation = lazy(() => import("./routes/Navigation"));
function App() {
return (
<ApolloProvider client={client} store={store}>
<Provider store={store}>
<div className="app">
<Suspense fallback={<span>Loading from suspense ...</span>}>
<Navigation />
</Suspense>
</div>
</Provider>
</ApolloProvider>
);
}
export default App;
|
digibib/ls.ext
|
redef/services/src/main/java/no/deichman/services/ontology/TranslationResource.java
|
<gh_stars>10-100
package no.deichman.services.ontology;
import com.google.gson.Gson;
import no.deichman.services.entity.EntityResource;
import no.deichman.services.entity.repository.RDFRepository;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;
/**
* Responsibility: Return translated strings.
*/
@Singleton
@Path("translations")
public class TranslationResource {
private String[] locales = {"no", "en"};
private Map<String, String> cachedTranslations = new HashMap<>();
private String query = ""
+ "select ?a ?b where { \n"
+ " ?a <http://www.w3.org/2000/01/rdf-schema#label> ?b ;\n"
+ " filter(lang(?b) = '__LOCALE__')\n"
+ "}";
public TranslationResource() {
EntityResource res = new EntityResource();
initCachedTranslations(res.getEntityService().getRepo());
}
public TranslationResource(RDFRepository repo) {
initCachedTranslations(repo);
}
private void initCachedTranslations(RDFRepository repo) {
Model model = repo.retrieveTranslationResources();
for (String locale : locales) {
Map<String, String> translations = new HashMap<>();
QueryExecution qe = QueryExecutionFactory.create(query.replace("__LOCALE__", locale), model);
ResultSet resultSet = qe.execSelect();
resultSet.forEachRemaining((result) -> {
// we are trimming the prefix 'file:///' from URIs, since Jena automaically adds it when URI schema is missing.
translations.put(result.getResource("a").toString().replaceFirst("http://server/unset-base/", ""), result.getLiteral("b").getString());
});
cachedTranslations.put(locale, new Gson().toJson(translations));
}
}
@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Path("{locale}")
public final Response getTranslations(@PathParam("locale") String locale) {
return Response.ok().entity(cachedTranslations.get(locale)).build();
}
}
|
collinkleest/WCFactory
|
packages/generator-wcfactory/generators/start/templates/templates/builds/GravCMS/webpack.mix.js
|
<gh_stars>100-1000
const mix = require("laravel-mix");
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix
.setPublicPath("dist")
.js("js/app.js", "js/app.js")
.sass("scss/app.scss", "css/app.css")
// .disableNotifications() // Disables native Laravel Mix notifications
.browserSync({
proxy: "localhost", // Point this to your Grav server
// notify: false, // Disables Browsersync notifications
files: [
"dist/**/*",
"templates/**/*"
]
});
// Source maps when not in production.
if (!mix.inProduction()) {
mix.sourceMaps();
}
// Hash and version files in production.
if (mix.inProduction()) {
mix.version();
}
|
qbit-t/qb
|
tests/memorypool.cpp
|
<reponame>qbit-t/qb
#include "memorypool.h"
#include "../mkpath.h"
using namespace qbit;
using namespace qbit::tests;
bool MemoryPoolQbitCreateSpend::execute() {
//
// 1. create qbit
//
// clean up
rmpath(settings_->dataPath().c_str());
// prepare wallet
if (!wallet_->open("")) {
error_ = "Wallet open failed.";
return false;
}
//
// Create key
//
wallet_->createKey(seedMy_);
//
// QBIT coinbase
//
// 1. create
TransactionContextPtr lCtx = wallet_->createTxCoinBase(10000);
// 2. check
TransactionProcessor lProcessor = TransactionProcessor(persistentStore_, wallet_, entityStore_) <<
TxCoinBaseVerify::instance() <<
TxSpendVerify::instance() <<
TxSpendOutVerify::instance() << TxAssetTypeVerify::instance() << // or
TxBalanceVerify::instance();
if (!lProcessor.process(lCtx)) {
if (lCtx->errors().size()) error_ = *lCtx->errors().begin();
mempool_->close();
wallet_->close();
return false;
}
// 3. push to persistent store
persistentStore_->pushTransaction(lCtx);
//
// MEMORY POOL
//
// 1. Create 3
// 1.1. create bob's key
SKey lBobKey(seedBob_); // init bob key
lBobKey.create();
PKey lBob = lBobKey.createPKey();
SKeyPtr lMyKey = wallet_->firstKey();
PKey lMy = lMyKey->createPKey();
// 1.2 create tx
lCtx = wallet_->createTxSpend(TxAssetType::qbitAsset(), lBob, 1000);
lCtx = mempool_->pushTransaction(lCtx->tx()); // re-create context
if (lCtx->errors().size()) {
error_ = *lCtx->errors().begin();
mempool_->close();
wallet_->close();
return false;
}
// 1.2.1 send to self
lCtx = wallet_->createTxSpend(TxAssetType::qbitAsset(), lMy, 8000);
lCtx = mempool_->pushTransaction(lCtx->tx()); // re-create context
if (lCtx->errors().size()) {
error_ = *lCtx->errors().begin();
mempool_->close();
wallet_->close();
return false;
}
// 1.3 create tx
lCtx = wallet_->createTxSpend(TxAssetType::qbitAsset(), lBob, 1100);
lCtx = mempool_->pushTransaction(lCtx->tx()); // re-create context
if (lCtx->errors().size()) {
error_ = *lCtx->errors().begin();
mempool_->close();
wallet_->close();
return false;
}
// 1.4 create tx
lCtx = wallet_->createTxSpend(TxAssetType::qbitAsset(), lBob, 1200);
lCtx = mempool_->pushTransaction(lCtx->tx()); // re-create context
if (lCtx->errors().size()) {
error_ = *lCtx->errors().begin();
mempool_->close();
wallet_->close();
return false;
}
// 2. compose block
BlockPtr lBlock = Block::instance();
BlockContextPtr lBlockCtx = mempool_->beginBlock(lBlock);
mempool_->commit(lBlockCtx);
//std::cout << "\n" << lBlock->toString() << "\n";
if (lBlock->transactions().size() != 4) {
error_ = "Tx count is invalid";
mempool_->close();
wallet_->close();
return false;
}
mempool_->close();
wallet_->close();
return true;
}
|
samisbakedham/0x-tracker-client
|
src/util/get-period-options.js
|
import prettyPeriod from './pretty-period';
const getPeriodOptions = (periods, defaultPeriod) =>
periods.map((period) => ({
default: defaultPeriod === period,
label: prettyPeriod(period),
value: period,
}));
export default getPeriodOptions;
|
dysTOS/ASPiK
|
docs/buttons/interface_v_s_t_g_u_i_popup.js
|
var interface_v_s_t_g_u_i_popup =
[
[ "doResignKey", "interface_v_s_t_g_u_i_popup.html#ae8e708ab95e5f9b71d14d3befd8241a2", null ],
[ "doResignKeyStackDepth", "interface_v_s_t_g_u_i_popup.html#adbf9d4d73d5620c03e46895b684f7409", null ],
[ "inSendEvent", "interface_v_s_t_g_u_i_popup.html#a94d606e82dc908c72266870f3e8c7129", null ],
[ "supportMovableByWindowBackground", "interface_v_s_t_g_u_i_popup.html#a7f0428b0690430091567a95097418ba6", null ]
];
|
bopopescu/sage-5
|
src/sage/combinat/species/series_order.py
|
<gh_stars>1-10
"""
Series Order
This file provides some utility classes which are useful when
working with unknown, known, and infinite series orders for
univariate power series.
This code is based on the work of <NAME> and <NAME>'s
Aldor-Combinat, which can be found at
http://www.risc.uni-linz.ac.at/people/hemmecke/aldor/combinat/index.html.
In particular, the relevant section for this file can be found at
http://www.risc.uni-linz.ac.at/people/hemmecke/AldorCombinat/combinatsu30.html.
"""
from sage.rings.all import Integer
class SeriesOrderElement:
pass
class InfiniteSeriesOrder(SeriesOrderElement):
def __repr__(self):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: o = InfiniteSeriesOrder(); o
Infinite series order
"""
return "Infinite series order"
def __add__(self, x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: o = InfiniteSeriesOrder()
sage: o + 2
Infinite series order
sage: o + o
Infinite series order
::
sage: u = UnknownSeriesOrder()
sage: o + u
Unknown series order
TESTS::
sage: o + -1
Traceback (most recent call last):
...
ValueError: x must be a positive integer
"""
if isinstance(x, (int, Integer)):
if x < 0:
raise ValueError, "x must be a positive integer"
return self
if isinstance(x, InfiniteSeriesOrder):
return self
if isinstance(x, UnknownSeriesOrder):
return x
raise TypeError, "x must be a positive integer or a SeriesOrderElement"
__radd__ = __add__
def __mul__(self, x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: o = InfiniteSeriesOrder()
sage: o * 2
Infinite series order
sage: o * o
Infinite series order
::
sage: u = UnknownSeriesOrder()
sage: o * u
Unknown series order
TESTS::
sage: o * -1
Traceback (most recent call last):
...
ValueError: x must be a positive integer
"""
if isinstance(x, (int, Integer)):
if x < 0:
raise ValueError, "x must be a positive integer"
elif x == 0:
return x
return self
if isinstance(x, InfiniteSeriesOrder):
return self
if isinstance(x, UnknownSeriesOrder):
return x
raise TypeError, "x must be a positive integer or a SeriesOrderElement"
__rmul__ = __mul__
def __lt__(self, x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: o = InfiniteSeriesOrder()
sage: o < 2
False
sage: o < o
False
::
sage: u = UnknownSeriesOrder()
sage: o < u
False
sage: 2 < o # TODO: Not Implemented
True
"""
if isinstance(x, (int, Integer)):
if x < 0:
raise ValueError, "x must be a positive integer"
return False
if isinstance(x, InfiniteSeriesOrder):
return False
if isinstance(x, UnknownSeriesOrder):
return False
raise TypeError, "x must be a positive integer or a SeriesOrderElement"
def __gt__(self, x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: o = InfiniteSeriesOrder()
sage: o > 2
True
"""
return True
class UnknownSeriesOrder(SeriesOrderElement):
def __repr__(self):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: u = UnknownSeriesOrder(); u
Unknown series order
"""
return "Unknown series order"
def __add__(self, x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: u = UnknownSeriesOrder()
sage: u + 2
Unknown series order
sage: u + u
Unknown series order
"""
if isinstance(x, (int, Integer)):
if x < 0:
raise ValueError, "x must be a positive integer"
return self
if isinstance(x, SeriesOrderElement):
return self
raise TypeError, "x must be a positive integer or a SeriesOrderElement"
__radd__ = __add__
def __mul__(self, x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: u = UnknownSeriesOrder()
sage: u * 2
Unknown series order
sage: u * u
Unknown series order
"""
if isinstance(x, (int, Integer)):
if x < 0:
raise ValueError, "x must be a positive integer"
return self
if isinstance(x, SeriesOrderElement):
return self
raise TypeError, "x must be a positive integer or a SeriesOrderElement"
__rmul__ = __mul__
def __lt__(self, x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: u = UnknownSeriesOrder()
sage: u < 2
True
sage: o = InfiniteSeriesOrder()
sage: u < o
True
"""
if isinstance(x, (int, Integer)):
if x < 0:
raise ValueError, "x must be a positive integer"
return True
if isinstance(x, SeriesOrderElement):
return True
raise TypeError, "x must be a positive integer or a SeriesOrderElement"
def __gt__(self, x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: u = UnknownSeriesOrder()
sage: u > 2
False
"""
return False
def bounded_decrement(x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: u = UnknownSeriesOrder()
sage: bounded_decrement(u)
Unknown series order
sage: bounded_decrement(4)
3
sage: bounded_decrement(0)
0
"""
if isinstance(x, SeriesOrderElement):
return x
if isinstance(x, (int, Integer)):
if x < 0:
raise ValueError, "x must be a positive integer"
return max(0, x - 1)
raise TypeError, "x must be a positive integer or a SeriesOrderElement"
def increment(x):
"""
EXAMPLES::
sage: from sage.combinat.species.series_order import *
sage: u = UnknownSeriesOrder()
sage: increment(u)
Unknown series order
sage: increment(2)
3
"""
if isinstance(x, SeriesOrderElement):
return x + 1
if isinstance(x, (int, Integer)):
if x < 0:
raise ValueError, "x must be a positive integer"
return x+1
raise TypeError, "x must be a positive integer or a SeriesOrderElement"
inf = InfiniteSeriesOrder()
unk = UnknownSeriesOrder()
|
freemo/AetherMUD
|
src/main/java/com/syncleus/aethermud/game/CharClasses/Pirate.java
|
/**
* Copyright 2017 Syncleus, Inc.
* with portions copyright 2004-2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.syncleus.aethermud.game.CharClasses;
import com.syncleus.aethermud.game.Abilities.StdAbility;
import com.syncleus.aethermud.game.Abilities.interfaces.Ability;
import com.syncleus.aethermud.game.Areas.interfaces.Area;
import com.syncleus.aethermud.game.Behaviors.interfaces.LegalBehavior;
import com.syncleus.aethermud.game.Common.interfaces.CMMsg;
import com.syncleus.aethermud.game.Common.interfaces.CharStats;
import com.syncleus.aethermud.game.Common.interfaces.LegalWarrant;
import com.syncleus.aethermud.game.Common.interfaces.PhyStats;
import com.syncleus.aethermud.game.Items.interfaces.*;
import com.syncleus.aethermud.game.Locales.interfaces.Room;
import com.syncleus.aethermud.game.MOBS.interfaces.MOB;
import com.syncleus.aethermud.game.core.CMClass;
import com.syncleus.aethermud.game.core.CMLib;
import com.syncleus.aethermud.game.core.CMath;
import com.syncleus.aethermud.game.core.collections.Pair;
import com.syncleus.aethermud.game.core.collections.SHashtable;
import com.syncleus.aethermud.game.core.collections.XVector;
import com.syncleus.aethermud.game.core.interfaces.Environmental;
import com.syncleus.aethermud.game.core.interfaces.Physical;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
public class Pirate extends Thief {
private final static String localizedStaticName = CMLib.lang().L("Pirate");
private final String[] raceRequiredList = new String[]{"All", "-Equine"};
@SuppressWarnings("unchecked")
private final Pair<String, Integer>[] minimumStatRequirements = new Pair[]
{
new Pair<String, Integer>("Dexterity", Integer.valueOf(5)),
new Pair<String, Integer>("Charisma", Integer.valueOf(5))
};
public Pirate() {
super();
maxStatAdj[CharStats.STAT_DEXTERITY] = 4;
maxStatAdj[CharStats.STAT_CHARISMA] = 4;
}
@Override
public String ID() {
return "Pirate";
}
@Override
public String name() {
return localizedStaticName;
}
@Override
public int availabilityCode() {
return Area.THEME_FANTASY;
}
@Override
public String[] getRequiredRaceList() {
return raceRequiredList;
}
@Override
public Pair<String, Integer>[] getMinimumStatRequirements() {
return minimumStatRequirements;
}
@Override
public String getOtherBonusDesc() {
return L("Bonus XP in ship combat, and combat bonus for each fake limb.");
}
@Override
public String getOtherLimitsDesc() {
return L("Get less leniency from the law, no limb recovery after death, and can be paid to leave combat.");
}
@Override
public void initializeClass() {
super.initializeClass();
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Skill_Write", 0, true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Specialization_Ranged", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Specialization_EdgedWeapon", 50, true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Specialization_Sword", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "ThievesCant", 50, true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Skill_Recall", 50, true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Skill_Swim", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Skill_Climb", 0, false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Thief_Superstition", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Thief_RopeSwing", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 1, "Thief_ImprovedBoarding", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 2, "Thief_LocateAlcohol", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 2, "Thief_HoldYourLiquor", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 3, "Thief_Belay", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 3, "Thief_Hide", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 4, "Thief_RideTheRigging", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 4, "Thief_Sneak", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 4, "Skill_SeaLegs", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 5, "Thief_BuriedTreasure", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 5, "Skill_WandUse", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 6, "Thief_Wenching", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 6, "Skill_Dodge", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 7, "Thief_TreasureMap", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 7, "Thief_Peek", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 8, "Thief_WalkThePlank", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 8, "Skill_SeaMapping", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 8, "Skill_Disarm", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 9, "Thief_Plunder", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 9, "Skill_Parry", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 10, "Skill_SeaCharting", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 10, "Thief_BackStab", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 11, "Skill_DeadReckoning", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 11, "Thief_Steal", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 11, "Skill_Trip", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 12, "Skill_SeaNavigation", false, new XVector<String>("Skill_SeaCharting"));
CMLib.ableMapper().addCharAbilityMapping(ID(), 12, "Skill_TwoWeaponFighting", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 12, "Thief_Listen", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 13, "Thief_Scuttle", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 13, "Thief_Bind", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 13, "Thief_FenceLoot", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 14, "Prayer_Curse", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 14, "Song_PirateShanty", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 14, "Thief_PiecesOfEight", false, new XVector<String>("Thief_BuriedTreasure"));
CMLib.ableMapper().addCharAbilityMapping(ID(), 15, "Thief_PirateFamiliar", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 15, "Thief_ConcealItem", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 16, "Thief_PubContacts", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 16, "Skill_Stability", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 17, "Thief_PetSpy", false, new XVector<String>("Thief_PirateFamiliar"));
CMLib.ableMapper().addCharAbilityMapping(ID(), 17, "Skill_Attack2", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 18, "Skill_CombatRepairs", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 18, "Thief_SilentLoot", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 18, "Thief_WarningShot", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 19, "Skill_FoulWeatherSailing", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 19, "Thief_Distract", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 19, "Thief_PayOff", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 19, "Salvaging", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 20, "Thief_PetSteal", false, new XVector<String>("Thief_PirateFamiliar"));
CMLib.ableMapper().addCharAbilityMapping(ID(), 20, "Thief_Alertness", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 21, "Thief_MerchantFlag", true);
CMLib.ableMapper().addCharAbilityMapping(ID(), 21, "Thief_Articles", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 22, "Thief_RammingSpeed", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 22, "Thief_SmugglersHold", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 23, "Skill_InterceptShip", false, new XVector<String>("Skill_SeaCharting"));
CMLib.ableMapper().addCharAbilityMapping(ID(), 23, "Thief_MastShot", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 24, "Thief_HideShip", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 24, "Skill_AttackHalf", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 25, "Skill_AwaitShip", false);
CMLib.ableMapper().addCharAbilityMapping(ID(), 30, "Thief_SilentRunning", true);
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg) {
if (!super.okMessage(myHost, msg))
return false;
if ((msg.source() == myHost) && (msg.sourceMinor() == CMMsg.TYP_DEATH)) {
final Ability A = msg.source().fetchEffect("Amputation");
if (A != null) {
msg.addTrailerRunnable(new Runnable() {
private final String amuText = A.text();
private final MOB mob = msg.source();
@Override
public void run() {
if (mob.fetchEffect("Amputation") == null) {
final Ability A = CMClass.getAbility("Amputation");
mob.addNonUninvokableEffect(A);
A.setMiscText(amuText);
mob.recoverCharStats();
mob.recoverMaxState();
mob.recoverPhyStats();
}
}
});
}
}
if (msg.amITarget(myHost)
&& (msg.targetMinor() == CMMsg.TYP_GIVE)
&& (msg.source() != myHost)
&& (msg.tool() instanceof Coins)
&& (myHost instanceof MOB)
&& (((MOB) myHost).getVictim() == msg.source())) {
final double amt = ((Coins) msg.tool()).getTotalValue();
final double min = (50.0 * ((MOB) myHost).phyStats().level());
if (amt >= min) {
final MOB pirate = (MOB) myHost;
msg.addTrailerRunnable(new Runnable() {
@Override
public void run() {
pirate.makePeace(true);
Room R = CMLib.map().roomLocation(msg.source());
Ability A = pirate.fetchEffect("Prop_PiratePaidOff");
if (A == null) {
pirate.addNonUninvokableEffect(A = new StdAbility() {
private final Map<MOB, Long> timeOuts = new SHashtable<MOB, Long>();
@Override
public String ID() {
return "Prop_PiratePaidOff";
}
@Override
public void setMiscText(String newMiscText) {
if (newMiscText.startsWith("+")) {
Room R = CMLib.map().roomLocation(affected);
if (R != null) {
final MOB M = R.fetchInhabitant(newMiscText.substring(1));
if (M != null) {
final Long newTime = Long.valueOf(System.currentTimeMillis() + (10L * 60L * 1000L));
synchronized (timeOuts) {
timeOuts.put(M, newTime);
}
}
}
} else
super.setMiscText(newMiscText);
final long now = System.currentTimeMillis();
synchronized (timeOuts) {
for (MOB M : timeOuts.keySet()) {
final Long L = timeOuts.get(M);
if ((L != null) && (L.longValue() < now)) {
timeOuts.remove(M);
}
}
}
}
@Override
public boolean isSavable() {
return false;
}
@Override
public boolean okMessage(Environmental myHost, CMMsg msg) {
if (!super.okMessage(myHost, msg))
return false;
if ((msg.target() instanceof MOB)
&& (CMath.bset(msg.targetMajor(), CMMsg.MASK_MALICIOUS))) {
if (msg.source() == pirate) {
final MOB victimM = (MOB) msg.target();
MOB paidOneM = victimM;
Long timeOut;
synchronized (timeOuts) {
timeOut = timeOuts.get(victimM);
}
final MOB ultiM = victimM.amUltimatelyFollowing();
if ((timeOut == null) && (ultiM != null)) {
synchronized (timeOuts) {
timeOut = timeOuts.get(ultiM);
}
if (timeOut != null)
paidOneM = ultiM;
}
if (timeOut != null) {
if (System.currentTimeMillis() < timeOut.longValue()) {
if (!CMath.bset(msg.sourceMajor(), CMMsg.MASK_ALWAYS))
msg.source().tell(L("@x1 paid you off, so you can't attack @x2 for awhile.", paidOneM.name(pirate), victimM.charStats().himher()));
victimM.makePeace(true);
msg.source().makePeace(true);
return false;
} else {
timeOuts.remove(paidOneM);
if (timeOuts.size() == 0)
pirate.delEffect(this);
}
}
} else if (msg.target() == pirate) {
final MOB attackerM = msg.source();
MOB paidOneM = attackerM;
Long timeOut;
synchronized (timeOuts) {
timeOut = timeOuts.get(attackerM);
}
final MOB ultiM = attackerM.amUltimatelyFollowing();
if ((timeOut == null) && (ultiM != null)) {
synchronized (timeOuts) {
timeOut = timeOuts.get(ultiM);
}
if (timeOut != null)
paidOneM = ultiM;
}
if (timeOut != null) {
if (System.currentTimeMillis() < timeOut.longValue()) {
if (!CMath.bset(msg.sourceMajor(), CMMsg.MASK_ALWAYS))
msg.source().tell(paidOneM, null, null, L("<S-NAME> paid off @x1, so you can't attack @x2 for awhile.", pirate.name(attackerM), pirate.charStats().himher()));
pirate.makePeace(true);
msg.source().makePeace(true);
return false;
} else {
timeOuts.remove(paidOneM);
if (timeOuts.size() == 0)
pirate.delEffect(this);
}
}
}
}
return true;
}
});
}
A.setMiscText("+" + R.getContextName(msg.source()));
}
});
} else {
final String minAmt = CMLib.moneyCounter().abbreviatedPrice(((Coins) msg.tool()).getCurrency(), min);
final String himHer = ((MOB) myHost).charStats().himher();
msg.source().tell(L("You'll need to fork over at lease @x1 to make @x2 go away.", minAmt, himHer));
return false;
}
}
return true;
}
@Override
public void executeMsg(Environmental myHost, CMMsg msg) {
super.executeMsg(myHost, msg);
if ((msg.sourceMinor() == CMMsg.TYP_EXPCHANGE)
&& (msg.value() > 0)
&& (msg.source().charStats().getCurrentClass() == this)
&& (CMLib.map().areaLocation(msg.source()) instanceof BoardableShip)
&& (msg.source() != msg.target())) {
if (msg.target() instanceof MOB)
msg.setValue(msg.value() * 3);
else if (msg.target() == null) {
BoardableShip shipArea = (BoardableShip) CMLib.map().areaLocation(msg.source());
Room R = CMLib.map().roomLocation(shipArea.getShipItem());
if (R != null) {
for (Enumeration<Item> i = R.items(); i.hasMoreElements(); ) {
Item I = i.nextElement();
if ((I instanceof BoardableShip)
&& (I.fetchEffect("Sinking") != null)
&& (I != shipArea.getShipItem())) {
msg.setValue(msg.value() * 2);
break;
}
}
}
}
}
if ((msg.targetMinor() == CMMsg.MSG_LEGALWARRANT)
&& (msg.target() instanceof MOB)
&& (((MOB) msg.target()).charStats().getCurrentClass() == this)
&& (((MOB) msg.target()).location() != null)) {
LegalBehavior behav = CMLib.law().getLegalBehavior(((MOB) msg.target()).location());
Area area = CMLib.law().getLegalObject(((MOB) msg.target()).location());
List<LegalWarrant> warrants = behav.getWarrantsOf(area, (MOB) msg.target());
for (LegalWarrant W : warrants) {
if ((W.victim() == msg.tool())
&& (W.crime() == msg.targetMessage()))
W.setPunishment(W.punishment() + 1);
}
}
}
@Override
public void affectPhyStats(Physical affected, PhyStats affectableStats) {
super.affectPhyStats(affected, affectableStats);
if (affected instanceof MOB) {
int numLimbs = 0;
for (Enumeration<Item> i = ((MOB) affected).items(); i.hasMoreElements(); ) {
final Item I = i.nextElement();
if ((I instanceof FalseLimb)
&& (!I.amWearingAt(Item.IN_INVENTORY))
&& (!I.amWearingAt(Wearable.WORN_HELD))) {
numLimbs++;
}
}
if (numLimbs > 0) {
affectableStats.setDamage(affectableStats.damage() + numLimbs);
affectableStats.setAttackAdjustment(affectableStats.damage() + (5 * numLimbs));
affectableStats.setArmor(affectableStats.armor() - (5 * numLimbs));
}
}
}
}
|
YvesBoyadjian/Koin3D
|
application/src/application/scenegraph/SoLODGroup.java
|
/**
*
*/
package application.scenegraph;
import jscenegraph.database.inventor.SbBox3f;
import jscenegraph.database.inventor.SbVec3f;
import jscenegraph.database.inventor.actions.SoGLRenderAction;
import jscenegraph.database.inventor.nodes.SoGroup;
/**
* @author <NAME>
*
*/
public class SoLODGroup extends SoGroup {
public final SbVec3f referencePoint = new SbVec3f();
public float[] maxDistance;
public final SbBox3f box = new SbBox3f();
private final SbVec3f dummy = new SbVec3f(); //SINGLE_THREAD
private boolean cleared = true;
public void GLRender(SoGLRenderAction action)
{
if( box.intersect(referencePoint)) {
cleared = false;
super.GLRender(action);
}
else {
SbVec3f closestPoint = box.getClosestExternalPoint(referencePoint);
if( closestPoint.operator_minus(referencePoint,dummy).length() <= maxDistance[0] ) {
cleared = false;
super.GLRender(action);
}
else if( !cleared ){
cleared = true;
int nbChildren = getNumChildren();
for( int i=0;i <nbChildren;i++) {
((SoLODIndexedFaceSet)getChild(i)).clear();
}
}
// else {
// closestPoint = box.getClosestPoint(referencePoint);
// closestPoint.operator_minus(referencePoint,dummy);
// int i=0;
// }
}
}
}
|
arsi-apli/cscm
|
CodeSnippetsCommunityManager-maven-plugin/src/main/java/sk/arsi/codesnippetscommunitymanager/maven/plugin/Release.java
|
<reponame>arsi-apli/cscm
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sk.arsi.codesnippetscommunitymanager.maven.plugin;
import java.util.List;
import org.apache.maven.plugins.annotations.Parameter;
/**
*
* @author arsi
*/
public class Release {
@Parameter(required = true, readonly = true, property = "serverId")
private String serverId;
@Parameter(required = true, readonly = true, property = "outFileName")
private String outFileName;
@Parameter(required = true, readonly = true, property = "sftpUrl")
private String sftpUrl;
@Parameter(required = true, readonly = true, property = "sftpPath")
private String sftpPath;
@Parameter(required = true, readonly = true, property = "subDirs")
private List<SubDir> subDirs;
public String getServerId() {
return serverId;
}
public String getOutFileName() {
return outFileName;
}
public String getSftpUrl() {
return sftpUrl;
}
public String getSftpPath() {
return sftpPath;
}
public List<SubDir> getSubDirs() {
return subDirs;
}
}
|
richard-hu/qcacld-2.0
|
CORE/SERVICES/HIF/common/hif_diag_reg_access.c
|
<gh_stars>1-10
/*
* Copyright (c) 2013-2014 The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* This file was originally distributed by Qualcomm Atheros, Inc.
* under proprietary terms before Copyright ownership was assigned
* to the Linux Foundation.
*/
#ifdef WIN_MOBILE7
#include <ntddk.h>
#endif
#include "athdefs.h"
#include "a_types.h"
#include "a_osapi.h"
#define ATH_MODULE_NAME hif
#include "a_debug.h"
#include "targaddrs.h"
#include "hif.h"
#include "if_ath_sdio.h"
#include "regtable.h"
#define CPU_DBG_SEL_ADDRESS 0x00000483
#define CPU_DBG_ADDRESS 0x00000484
/* set the window address register (using 4-byte register access ).
* This mitigates host interconnect issues with non-4byte aligned bus requests, some
* interconnects use bus adapters that impose strict limitations.
* Since diag window access is not intended for performance critical operations, the 4byte mode should
* be satisfactory even though it generates 4X the bus activity. */
static A_STATUS ar6000_SetAddressWindowRegister(HIF_DEVICE *hifDevice, A_UINT32 RegisterAddr, A_UINT32 Address)
{
A_STATUS status;
static A_UINT32 address;
address = Address;
/*AR6320 use new window register access procedure,not need confuse operation as below*/
#if 0
for (i = 1; i <= 3; i++) {
/* fill the buffer with the address byte value we want to hit 4 times*/
addrValue[0] = ((A_UINT8 *)&Address)[i];
addrValue[1] = addrValue[0];
addrValue[2] = addrValue[0];
addrValue[3] = addrValue[0];
/* hit each byte of the register address with a 4-byte write operation to the same address,
* this is a harmless operation */
status = HIFReadWrite(hifDevice,
RegisterAddr+i,
addrValue,
4,
HIF_WR_SYNC_BYTE_FIX,
NULL);
if (status != A_OK) {
break;
}
}
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("Cannot write initial bytes of 0x%x to window reg: 0x%X \n",
Address, RegisterAddr));
return status;
}
#endif
/*AR6320,just write the 4-byte address to window register*/
status = HIFReadWrite(hifDevice,
RegisterAddr,
(A_UCHAR *)(&address),
4,
HIF_WR_SYNC_BYTE_INC,
NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("Cannot write 0x%x to window reg: 0x%X \n",
Address, RegisterAddr));
return status;
}
return A_OK;
}
/*
* Read from the AR6000 through its diagnostic window.
* No cooperation from the Target is required for this.
*/
A_STATUS
HIFDiagReadAccess(HIF_DEVICE *hifDevice, A_UINT32 address, A_UINT32 *data)
{
A_STATUS status;
static A_UINT32 readvalue;
if(address&0x03)
{
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("[%s]addr is not 4 bytes align.addr[0x%08x]\n",__func__, address));
return A_BAD_ADDRESS;
}
/* set window register to start read cycle */
status = ar6000_SetAddressWindowRegister(hifDevice,
WINDOW_READ_ADDR_ADDRESS,
address);
if (status != A_OK) {
return status;
}
/* read the data */
status = HIFReadWrite(hifDevice,
WINDOW_DATA_ADDRESS,
(A_UCHAR *)&readvalue,
sizeof(A_UINT32),
HIF_RD_SYNC_BYTE_INC,
NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("Cannot read from WINDOW_DATA_ADDRESS\n"));
return status;
}
*data = readvalue;
return status;
}
/*
* Write to the AR6000 through its diagnostic window.
* No cooperation from the Target is required for this.
*/
A_STATUS HIFDiagWriteAccess(HIF_DEVICE *hifDevice, A_UINT32 address, A_UINT32 data)
{
A_STATUS status;
static A_UINT32 writeValue;
if(address&0x03)
{
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("[%s]addr is not 4 bytes align.addr[0x%08x]\n",__func__, address));
return A_BAD_ADDRESS;
}
writeValue = data;
/* set write data */
status = HIFReadWrite(hifDevice,
WINDOW_DATA_ADDRESS,
(A_UCHAR *)&writeValue,
sizeof(A_UINT32),
HIF_WR_SYNC_BYTE_INC,
NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("Cannot write 0x%x to WINDOW_DATA_ADDRESS\n", data));
return status;
}
/* set window register, which starts the write cycle */
return ar6000_SetAddressWindowRegister(hifDevice,
WINDOW_WRITE_ADDR_ADDRESS,
address);
}
/*
* Write a block data to the AR6000 through its diagnostic window.
* This function may take some time.
* No cooperation from the Target is required for this.
*/
A_STATUS
HIFDiagWriteMem(HIF_DEVICE *hif_device, A_UINT32 address, A_UINT8 *data, int nbytes)
{
A_STATUS status;
A_INT32 i;
A_UINT32 tmp_data;
if((address&0x03) || (nbytes&0x03))
{
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("[%s]addr or length is not 4 bytes align.addr[0x%08x] len[0x%08x]\n",__func__, address, nbytes));
return A_BAD_ADDRESS;
}
for(i=0;i<nbytes;i+=4)
{
tmp_data = data[i] | (data[i+1]<<8) | (data[i+2]<<16) | (data[i+3]<<24);
status = HIFDiagWriteAccess(hif_device, address + i , tmp_data);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("Diag Write mem failed.addr[0x%08x] value[0x%08x]\n", address + i , tmp_data));
return status;
}
}
return A_OK;
}
/*
* Reaad a block data to the AR6000 through its diagnostic window.
* This function may take some time.
* No cooperation from the Target is required for this.
*/
A_STATUS
HIFDiagReadMem(HIF_DEVICE *hif_device, A_UINT32 address, A_UINT8 *data, int nbytes)
{
A_STATUS status;
A_INT32 i;
A_UINT32 tmp_data;
if((address&0x03) || (nbytes&0x03))
{
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("[%s]addr or length is not 4 bytes align.addr[0x%08x] len[0x%08x]\n",__func__, address, nbytes));
return A_BAD_ADDRESS;
}
for(i=0;i<nbytes;i+=4)
{
status = HIFDiagReadAccess(hif_device, address + i , &tmp_data);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("Diag Write mem failed.addr[0x%08x] value[0x%08x]\n", address + i , tmp_data));
return status;
}
data[i] = tmp_data & 0xff;
data[i+1] = tmp_data>>8 & 0xff;
data[i+2] = tmp_data>>16 & 0xff;
data[i+3] = tmp_data>>24 & 0xff;
}
return A_OK;
}
/* TODO .. the following APIs are only available on register-based HIFs where the CPU_DBG_SEL_ADDRESS
* register is available */
A_STATUS
ar6k_ReadTargetRegister(HIF_DEVICE *hifDevice, int regsel, A_UINT32 *regval)
{
A_STATUS status;
A_UCHAR vals[4];
A_UCHAR register_selection[4];
register_selection[0] = register_selection[1] = register_selection[2] = register_selection[3] = (regsel & 0xff);
status = HIFReadWrite(hifDevice,
CPU_DBG_SEL_ADDRESS,
register_selection,
4,
HIF_WR_SYNC_BYTE_FIX,
NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("Cannot write CPU_DBG_SEL (%d)\n", regsel));
return status;
}
status = HIFReadWrite(hifDevice,
CPU_DBG_ADDRESS,
(A_UCHAR *)vals,
sizeof(vals),
HIF_RD_SYNC_BYTE_INC,
NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_LOG_ERR, ("Cannot read from CPU_DBG_ADDRESS\n"));
return status;
}
*regval = vals[0]<<0 | vals[1]<<8 | vals[2]<<16 | vals[3]<<24;
return status;
}
void
ar6k_FetchTargetRegs(HIF_DEVICE *hifDevice, A_UINT32 *targregs)
{
int i;
A_UINT32 val;
for (i=0; i<AR6003_FETCH_TARG_REGS_COUNT; i++) {
val=0xffffffff;
(void)ar6k_ReadTargetRegister(hifDevice, i, &val);
targregs[i] = val;
}
}
|
Joynann/Estudos
|
exercicios origamid/Javascript/js-iniciante/objetos/script.js
|
<filename>exercicios origamid/Javascript/js-iniciante/objetos/script.js
// Crie um objeto com os seus dados pessoais
// Deve possui pelo menos duas propriedades nome e sobrenome
var dadosPessoais = {
nome: 'Joynan',
sobrenome: '<NAME>',
idade: 22,
sexo: 'Masculino',
dataNascimento: '11/05/1999',
mae: '<NAME>',
pai: '<NAME>',
}
// Crie um método no objeto anterior, que mostre o seu nome completo
dadosPessoais.nomeCompleto = function() {
return `${this.nome} ${this.sobrenome}`;
}
// Modifique o valor da propriedade preco para 3000
var carro = {
preco: 1000,
portas: 4,
marca: 'Audi',
}
carro.preco = 3000;
// Crie um objeto de um cachorro que represente um labrador,
// preto com 10 anos, que late ao ver um homem
var labrador = {
cor: 'preto',
idade: 10,
latir(pessoa) {
if(pessoa === 'homem') {
return 'O labrador está latindo';
} else {
return 'O labrador não está latindo';
}
},
}
|
m-mizutani/minerva
|
internal/adaptor/sqs.go
|
package adaptor
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
// SQSClientFactory is interface SQSClient constructor
type SQSClientFactory func(region string) SQSClient
// SQSClient is interface of AWS SDK SQS
type SQSClient interface {
SendMessage(*sqs.SendMessageInput) (*sqs.SendMessageOutput, error)
ReceiveMessage(input *sqs.ReceiveMessageInput) (*sqs.ReceiveMessageOutput, error)
DeleteMessage(input *sqs.DeleteMessageInput) (*sqs.DeleteMessageOutput, error)
}
// NewSQSClient creates actual AWS SQS SDK client
func NewSQSClient(region string) SQSClient {
ssn := session.New(&aws.Config{Region: aws.String(region)})
return sqs.New(ssn)
}
|
sjhanson/hackerrank-interview-prep-kit-node
|
src/search/naive-string-search.js
|
<reponame>sjhanson/hackerrank-interview-prep-kit-node
module.exports = {
bruteForce(string, pattern) {
const strArr = string.split('');
const pattArr = pattern.split('');
const M = pattArr.length;
const N = strArr.length;
// Loop through string array
// We know there can't be a match if we've
// reached the position in the array where the
// pattern string won't fit anymore
for (let i = 0; i <= N - M; i++) {
// Loop through pattern
for (let j = 0; j < M; j++) {
if (strArr[i + j] !== pattArr[j]) {
// Not a match, move on to next string character
break;
}
// Check length of pattern matched
if (j === (M - 1)) {
// Full pattern matched
return true;
}
}
}
return false;
}
}
|
Tokelon/tokTales
|
tokTales-core/tokTales-core-library/src/main/java/com/tokelon/toktales/core/game/control/TimeTracker.java
|
package com.tokelon.toktales.core.game.control;
public class TimeTracker implements ITimeTracker {
private final ITimeProvider mTimeProvider;
private int state = STATE_PAUSED;
private long pastTimeMillis = 1; // Start with 1 or 0 ?
private long lastResumeTime;
public TimeTracker(ITimeProvider timeProvider) {
mTimeProvider = timeProvider;
}
private long currentPast() {
long currTime = mTimeProvider.getCurrentTimeMillis();
return currTime - lastResumeTime;
}
@Override
public int getState() {
return state;
}
@Override
public synchronized void pause() {
if(state == STATE_PAUSED) {
// What happens here?
return;
}
pastTimeMillis += currentPast();
state = STATE_PAUSED;
}
@Override
public synchronized void resume() {
if(state == STATE_RUNNING) {
// What happens here?
return;
}
lastResumeTime = mTimeProvider.getCurrentTimeMillis();
state = STATE_RUNNING;
}
@Override
public long getPastTimeMillis() {
long pastTime;
if(state == STATE_RUNNING) {
pastTime = pastTimeMillis + currentPast();
}
else if(state == STATE_PAUSED) {
pastTime = pastTimeMillis;
}
else {
pastTime = -1;
}
return pastTime;
}
}
|
RyuKojiro/v6502
|
as6502/error.c
|
/*
* Copyright (c) 2013 <NAME>
*
* 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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <term.h>
#include <assert.h>
#include "error.h"
#include "color.h"
const char *currentLineText;
unsigned long currentLineNum;
const char *currentFileName;
unsigned int currentErrorCount;
static int termcolors(void) {
int e;
if (setupterm(NULL, fileno(stdout), &e)) {
return 0;
}
return tigetnum("colors");
}
__attribute((noreturn)) void as6502_fatal(const char *reason) {
if (termcolors()) {
fprintf(stderr, ANSI_COLOR_BRIGHT_WHITE "as6502: " ANSI_COLOR_BRIGHT_RED "fatal:" ANSI_COLOR_BRIGHT_WHITE " %s\n" ANSI_COLOR_RESET, reason);
}
else {
fprintf(stderr, "as6502: fatal: %s\n", reason);
}
exit(EXIT_FAILURE);
}
#pragma clang diagnostic ignored "-Wformat-nonliteral"
static void as6502_vlog(unsigned long line, unsigned long loc, unsigned long len, const char *color, const char *type, const char *reason, va_list ap) {
// Only use color codes on real TTYs
if (termcolors()) {
fprintf(stderr,
ANSI_COLOR_BRIGHT_WHITE "%s:%lu:", currentFileName, line);
if (len) {
fprintf(stderr, "%lu:", loc);
}
fprintf(stderr,
" %s%s: "
ANSI_COLOR_BRIGHT_WHITE, color, type);
vfprintf(stderr, reason, ap);
fprintf(stderr, ANSI_COLOR_RESET);
}
else {
fprintf(stderr, "%s:%lu: %s: ", currentFileName, line, type);
vfprintf(stderr, reason, ap);
}
if (reason[strlen(reason)] != '\n') {
fprintf(stderr, "\n");
}
as6502_underline(currentLineText, loc, len);
}
#pragma clang diagnostic warning "-Wformat-nonliteral"
void as6502_error(unsigned long loc, unsigned long len, const char *reason, ...) {
currentErrorCount++;
va_list ap;
va_start(ap, reason);
as6502_vlog(currentLineNum, loc, len, ANSI_COLOR_BRIGHT_RED, "error", reason, ap);
va_end(ap);
}
void as6502_warn(unsigned long loc, unsigned long len, const char *reason, ...) {
va_list ap;
va_start(ap, reason);
as6502_vlog(currentLineNum, loc, len, ANSI_COLOR_BRIGHT_MAGENTA, "warning", reason, ap);
va_end(ap);
}
void as6502_note(unsigned long lineNumber, const char *reason, ...) {
va_list ap;
va_start(ap, reason);
as6502_vlog(lineNumber, 0, 0, ANSI_COLOR_BRIGHT_CYAN, "note", reason, ap);
va_end(ap);
}
static void printSpaces(unsigned long num, const char *str) {
assert(str);
for (/* num */; num > 0; num--) {
int whitespace = (str[num - 1] == '\t') ? '\t' : ' ';
fputc(whitespace, stderr);
}
}
void as6502_underline(const char *str, unsigned long loc, unsigned long len) {
// Don't do anything if we don't have a valid range (non-zero length)
if (!len) {
return;
}
fprintf(stderr, "%s", str);
// FIXME: Shouldn't this always need a newline or always not need a newline?
if (currentLineText[strlen(str) - 1] != '\n') {
fprintf(stderr, "\n");
}
printSpaces(loc, str);
int supportsColor = termcolors();
if (supportsColor) {
fprintf(stderr, ANSI_COLOR_BRIGHT_GREEN);
}
fputc('^', stderr);
for (len--; len; len--) {
fputc('~', stderr);
}
if (supportsColor) {
fprintf(stderr, ANSI_COLOR_RESET);
}
fputc('\n', stderr);
}
|
hari047/Ionic-Application
|
sources/com/google/zxing/client/result/ProductResultParser.java
|
<gh_stars>0
package com.google.zxing.client.result;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.oned.UPCEReader;
public final class ProductResultParser extends ResultParser {
public ProductParsedResult parse(Result result) {
String normalizedProductID;
BarcodeFormat format = result.getBarcodeFormat();
if (format != BarcodeFormat.UPC_A && format != BarcodeFormat.UPC_E && format != BarcodeFormat.EAN_8 && format != BarcodeFormat.EAN_13) {
return null;
}
String rawText = getMassagedText(result);
if (!isStringOfDigits(rawText, rawText.length())) {
return null;
}
if (format == BarcodeFormat.UPC_E && rawText.length() == 8) {
normalizedProductID = UPCEReader.convertUPCEtoUPCA(rawText);
} else {
normalizedProductID = rawText;
}
return new ProductParsedResult(rawText, normalizedProductID);
}
}
|
loskutnikov-spirent/openperf
|
src/modules/packet/generator/learning.cpp
|
#include "packet/generator/learning.hpp"
#include "lwip/priv/tcpip_priv.h"
#include "lwip/etharp.h"
#include "arpa/inet.h"
#include <future>
namespace openperf::packet::generator {
static constexpr std::chrono::seconds start_callback_timeout(1);
static constexpr std::chrono::seconds check_callback_timeout(1);
static constexpr std::chrono::seconds poll_check_interval(1);
static constexpr int max_poll_count = 30;
bool all_addresses_resolved(const learning_result_map& results)
{
return (std::none_of(
results.begin(), results.end(), [](const auto& address_pair) {
return std::holds_alternative<unresolved>(address_pair.second);
}));
}
// Structure that gets "passed" to the stack thread via tcpip_callback.
struct start_learning_params
{
netif* intf = nullptr; // lwip interface to use.
const learning_result_map& to_learn; // addresses to learn.
std::promise<err_t> barrier; // keep generator and stack threads in sync.
};
static void send_learning_requests(void* arg)
{
auto* slp = reinterpret_cast<start_learning_params*>(arg);
assert(slp);
// start_learning_params contains a unique list of IP addresses to learn.
// Addresses are assumed to be on-link. Caller must first apply routing
// logic. Caller must not send IP addresses from a different subnet.
err_t overall_result = ERR_OK;
std::for_each(
slp->to_learn.begin(), slp->to_learn.end(), [&](const auto& addr_pair) {
// If we've already had an error don't bother trying to learn this
// address.
if (overall_result != ERR_OK) { return; }
// Is this entry unresolved?
// Don't repeat learning for addresses we've already resolved.
if (!std::holds_alternative<unresolved>(addr_pair.second)) {
return;
}
ip4_addr_t target{
.addr = htonl(addr_pair.first.template load<uint32_t>())};
OP_LOG(OP_LOG_TRACE,
"Sending ARP request for IP: %s\n",
to_string(addr_pair.first).c_str());
auto result = etharp_query(slp->intf, &target, nullptr);
if (result != ERR_OK) {
OP_LOG(OP_LOG_ERROR,
"Error (%s) encountered while requesting ARP for "
"address: %s",
lwip_strerr(result),
to_string(addr_pair.first).c_str());
overall_result = result;
}
});
// Return ERR_OK if nothing went wrong, else first error we encountered.
// Since we stop trying after the first error technically that would be the
// only error.
slp->barrier.set_value(overall_result);
}
// Return true if learning started, false otherwise.
bool learning_state_machine::start_learning(
const std::vector<libpacket::type::ipv4_address>& to_learn,
resolve_complete_callback callback)
{
// If we're already learning, don't start again.
if (in_progress()) { return (false); }
// Are we being asked to learn nothing?
if (to_learn.empty()) { return (false); }
m_results.clear();
// Populate results with IP addresses.
std::transform(
to_learn.begin(),
to_learn.end(),
std::inserter(m_results, m_results.end()),
[](auto& ip_addr) { return (std::make_pair(ip_addr, unresolved{})); });
m_resolved_callback = std::move(callback);
return (start_learning_impl());
}
bool learning_state_machine::retry_failed()
{
// Are we being asked to retry when no items failed?
if (all_addresses_resolved(m_results)) { return (false); }
return (start_learning_impl());
}
bool learning_state_machine::start_learning_impl()
{
// If we're already learning, don't start again.
if (in_progress()) { return (false); }
// Are we being asked to learn nothing?
if (m_results.empty()) { return (false); }
// Do we have a valid interface to learn on?
if (m_intf == nullptr) { return (false); }
m_current_state = state_start{};
start_learning_params slp = {.intf = this->m_intf,
.to_learn = this->m_results};
auto barrier = slp.barrier.get_future();
// tcpip_callback executes the given function in the stack thread passing it
// the second argument as void*.
// send_learning_requests is smart enough to only send requests for results
// in the unresolved state.
if (auto res = tcpip_callback(send_learning_requests, &slp);
res != ERR_OK) {
m_current_state = state_timeout{};
return (true);
}
// Wait for the all the learning requests to send.
// We could just return. But it's useful to know if the process succeeded.
// Plus, the process is non-blocking on the stack side so this won't take
// long.
if (barrier.wait_for(start_callback_timeout) != std::future_status::ready) {
OP_LOG(OP_LOG_ERROR, "Timed out while starting learning.");
m_current_state = state_timeout{};
return (false);
}
auto learning_status = barrier.get();
if (learning_status != ERR_OK) { m_current_state = state_timeout{}; }
m_current_state = state_learning{};
return (start_status_polling());
}
static int handle_poll_timeout(const struct op_event_data* data, void* arg)
{
auto* lsm = reinterpret_cast<learning_state_machine*>(arg);
assert(lsm);
if (data->timeout_id != lsm->timeout_id()) {
throw std::runtime_error("Error with event loop while performing MAC learning.");
}
return (lsm->check_learning());
}
bool learning_state_machine::start_status_polling()
{
auto duration_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
poll_check_interval);
auto callbacks = op_event_callbacks{.on_timeout = handle_poll_timeout};
auto timeout = duration_ns.count();
uint32_t timeout_id = 0;
auto result = m_loop.add(timeout, &callbacks, this, &timeout_id);
if (result < 0) { return (false); }
m_loop_timeout_id = timeout_id;
m_polls_remaining = max_poll_count;
return (true);
}
// Structure that gets "passed" to the stack thread via tcpip_callback.
struct check_learning_params
{
learning_result_map& results;
std::promise<void> barrier;
};
static void check_arp_cache(void* arg)
{
auto* clp = reinterpret_cast<check_learning_params*>(arg);
assert(clp);
ip4_addr_t* entryAddrPtr = nullptr;
eth_addr* entryMacPtr = nullptr;
netif* entryIntfPtr = nullptr;
for (size_t i = 0; i < ARP_TABLE_SIZE; i++) {
// LwIP refers to resolved MACs as "stable entries" in the ARP cache.
auto stable_entry =
etharp_get_entry(i, &entryAddrPtr, &entryIntfPtr, &entryMacPtr);
if (!stable_entry) { continue; }
auto found_result = clp->results.find(
libpacket::type::ipv4_address(ntohl(entryAddrPtr->addr)));
if (found_result == clp->results.end()) {
// Guess we weren't looking for this address.
// Remember, the stack is shared by all generators.
continue;
}
if (std::holds_alternative<libpacket::type::mac_address>(
found_result->second)) {
// We already know this address.
continue;
}
found_result->second.emplace<libpacket::type::mac_address>(
reinterpret_cast<const uint8_t*>(entryMacPtr->addr));
}
clp->barrier.set_value();
}
int learning_state_machine::check_learning()
{
// Are there results to check?
if (m_results.empty()) { return (-1); }
// Are we in the process of learning?
if (!in_progress()) { return (-1); }
if ((m_polls_remaining--) <= 0) {
OP_LOG(OP_LOG_WARNING,
"Not all addresses resolved during ARP process.");
return (-1);
}
check_learning_params clp = {.results = this->m_results};
auto barrier = clp.barrier.get_future();
// tcpip_callback executes the given function in the stack thread passing it
// the second argument as void*.
if (auto res = tcpip_callback(check_arp_cache, &clp); res != ERR_OK) {
m_current_state = state_timeout{};
OP_LOG(OP_LOG_ERROR,
"Got error %s while checking stack ARP cache.",
strerror(res));
return (-1);
}
// Wait for the check to finish.
// We could just return. But it's useful to know if the process succeeded.
// Plus, the process is non-blocking on the stack side so this won't take
// long (essentially iterating over an in-memory array).
if (barrier.wait_for(check_callback_timeout) != std::future_status::ready) {
OP_LOG(OP_LOG_ERROR, "Timed out while checking learning status.");
m_current_state = state_timeout{};
return (-1);
}
if (all_addresses_resolved(m_results)) {
m_current_state = state_done{};
OP_LOG(OP_LOG_TRACE,
"Successfully resolved all %lu ARP requests.",
m_results.size());
// Deliver results via callback.
m_resolved_callback(*this);
return (-1);
}
return (0);
}
void learning_state_machine::stop_learning()
{
// If we're not in the progress of learning, we're already stopped.
if (!in_progress()) { return; }
// Delete the polling timer.
m_loop.del(m_loop_timeout_id);
// Figure out which state we're going to end in.
if (all_addresses_resolved(m_results)) {
m_current_state = state_done{};
return;
}
m_current_state = state_timeout{};
}
} // namespace openperf::packet::generator
|
matoruru/purescript-react-material-ui-svgicon
|
src/MaterialUI/SVGIcon/Icon/VideocamSharp.js
|
exports.videocamSharpImpl = require('@material-ui/icons/VideocamSharp').default;
|
walkerxiong/codeql-go
|
ql/test/library-tests/semmle/go/frameworks/K8sIoApiCoreV1/main.go
|
package main
import (
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
)
//go:generate depstubber -vendor k8s.io/api/core/v1 SecretList
//go:generate depstubber -vendor k8s.io/apimachinery/pkg/runtime ProtobufMarshaller,ProtobufReverseMarshaller
func source() interface{} {
return make([]byte, 1, 1)
}
func sink(...interface{}) {
}
func main() {
{
// func (in *Secret) DeepCopy() *Secret
sink(source().(*corev1.Secret).DeepCopy()) // $ KsIoApiCoreV
}
{
// func (in *Secret) DeepCopyInto(out *Secret)
var out *corev1.Secret
source().(*corev1.Secret).DeepCopyInto(out)
sink(out) // $ KsIoApiCoreV
}
{
// func (in *Secret) DeepCopyObject() runtime.Object
sink(source().(*corev1.Secret).DeepCopyObject()) // $ KsIoApiCoreV
}
{
// func (m *Secret) Marshal() (dAtA []byte, err error)
sink(source().(*corev1.Secret).Marshal()) // $ KsIoApiCoreV
}
{
// func (m *Secret) MarshalTo(dAtA []byte) (int, error)
var dAtA []byte
source().(*corev1.Secret).MarshalTo(dAtA)
sink(dAtA) // $ KsIoApiCoreV
}
{
// func (m *Secret) MarshalToSizedBuffer(dAtA []byte) (int, error)
var dAtA []byte
source().(*corev1.Secret).MarshalToSizedBuffer(dAtA)
sink(dAtA) // $ KsIoApiCoreV
}
{
// func (m *Secret) Unmarshal(dAtA []byte) error
var dAtA []byte
source().(*corev1.Secret).Unmarshal(dAtA)
sink(dAtA) // $ KsIoApiCoreV
}
{
// func (in *SecretList) DeepCopy() *SecretList
sink(source().(*corev1.SecretList).DeepCopy()) // $ KsIoApiCoreV
}
{
// func (in *SecretList) DeepCopyInto(out *SecretList)
var out *corev1.SecretList
source().(*corev1.SecretList).DeepCopyInto(out)
sink(out) // $ KsIoApiCoreV
}
{
// func (in *SecretList) DeepCopyObject() runtime.Object
sink(source().(*corev1.SecretList).DeepCopyObject()) // $ KsIoApiCoreV
}
{
// func (m *SecretList) Marshal() (dAtA []byte, err error)
sink(source().(*corev1.SecretList).Marshal()) // $ KsIoApiCoreV
}
{
// func (m *SecretList) MarshalTo(dAtA []byte) (int, error)
var dAtA []byte
source().(*corev1.SecretList).MarshalTo(dAtA)
sink(dAtA) // $ KsIoApiCoreV
}
{
// func (m *SecretList) MarshalToSizedBuffer(dAtA []byte) (int, error)
var dAtA []byte
source().(*corev1.SecretList).MarshalToSizedBuffer(dAtA)
sink(dAtA) // $ KsIoApiCoreV
}
{
// func (m *SecretList) Unmarshal(dAtA []byte) error
var dAtA []byte
source().(*corev1.SecretList).Unmarshal(dAtA)
sink(dAtA) // $ KsIoApiCoreV
}
}
func dummy1(runtime.ProtobufMarshaller) {}
func dummy2(runtime.ProtobufReverseMarshaller) {}
|
frontend-park-mail-ru/2018_1_tarados-feroces
|
src/app/modules/HttpModule/HttpModule.js
|
import {DOMEN, HEADER_CONTENT_TYPE, JSON_CONTENT_TYPE, POST, GET} from './HttpConstants';
/**
* Класс, отвечающий за отправку запросов на сервер
* @module HttpModule
*/
class HttpModule {
/**
* @constructor
*/
constructor() {
this.domen = DOMEN;
}
/**
* Делает GET-запрос
* @param {string} url
* @param {Object} headers
* @return {Promise<any>}
*/
doGet(url) {
return this.send(GET, url);
}
/**
* Делает POST-запрос
* @param {string} url
* @param {Object} data
* @param {Object} headers
* @return {Promise<any>}
*/
doPost(url, data = {}) {
return this.send(POST, url, data);
}
/**
* Отправляет запрос указанного типа
* @param {string} method
* @param {string} url
* @param {Object} data
* @param {Object} headers
* @return {Promise<any>}
* @private
*/
send(method, url = '/', data = {}, headers = []) {
const options = {
method: method,
mode: 'cors',
credentials: 'include'
};
if (method === POST) {
options.body = JSON.stringify(data);
const _headers = new Headers();
_headers.append(HEADER_CONTENT_TYPE, JSON_CONTENT_TYPE);
options.headers = _headers;
}
return fetch(`${this.domen}${url}`, options)
.then((response) => {
if (response.status >= 400) {
throw response;
}
return response.json();
});
}
}
const httpModule = new HttpModule();
export default httpModule;
|
eitam-ring/kubemq-targets
|
targets/gcp/bigquery/connector.go
|
<filename>targets/gcp/bigquery/connector.go
package bigquery
import "github.com/kubemq-hub/builder/connector/common"
func Connector() *common.Connector {
return common.NewConnector().
SetKind("gcp.bigquery").
SetDescription("GCP Bigquery Target").
AddProperty(
common.NewProperty().
SetKind("string").
SetName("project_id").
SetDescription("Set GCP project ID").
SetMust(true).
SetDefault(""),
).
AddProperty(
common.NewProperty().
SetKind("multilines").
SetName("credentials").
SetDescription("Set GCP credentials").
SetMust(true).
SetDefault(""),
).
AddMetadata(
common.NewMetadata().
SetName("method").
SetKind("string").
SetDescription("Set GCP BigQuery execution method").
SetOptions([]string{"query", "create_data_set", "delete_data_set", "create_table","delete_table", "get_table_info", "get_data_sets", "insert"}).
SetDefault("query").
SetMust(true),
).
AddMetadata(
common.NewMetadata().
SetName("table_name").
SetKind("string").
SetDescription("Set BigQuery table name").
SetDefault("").
SetMust(false),
).
AddMetadata(
common.NewMetadata().
SetName("dataset_id").
SetKind("string").
SetDescription("Set BigQuery dataset id").
SetDefault("").
SetMust(false),
).
AddMetadata(
common.NewMetadata().
SetName("location").
SetKind("string").
SetDescription("Set BigQuery location").
SetDefault("").
SetMust(false),
).
AddMetadata(
common.NewMetadata().
SetName("query").
SetKind("string").
SetDescription("Set BigQuery query").
SetDefault("").
SetMust(false),
)
}
|
ceekay1991/AliPayForDebug
|
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/APMTTSAudioPlayer.h
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
#import "APMSimpleAudioPlayerDelegate-Protocol.h"
@class APMSimpleAudioPlayer, NSString;
@interface APMTTSAudioPlayer : NSObject <APMSimpleAudioPlayerDelegate>
{
struct _tts_play_param *param_;
const struct _tts_play_callback *playCallback_;
_Bool _hasCallbackStartEvent;
_Bool _hasCallbackStopEvent;
long long _sid;
APMSimpleAudioPlayer *_player;
}
+ (void)initialize;
+ (id)findInstanceByIdentifier:(long long)arg1;
+ (void)removeInstance:(id)arg1;
+ (void)addInstance:(id)arg1;
@property(nonatomic) _Bool hasCallbackStopEvent; // @synthesize hasCallbackStopEvent=_hasCallbackStopEvent;
@property(nonatomic) _Bool hasCallbackStartEvent; // @synthesize hasCallbackStartEvent=_hasCallbackStartEvent;
@property(retain, nonatomic) APMSimpleAudioPlayer *player; // @synthesize player=_player;
@property(nonatomic) long long sid; // @synthesize sid=_sid;
- (void).cxx_destruct;
- (void)doPlayStoppedCallback:(int)arg1 msg:(id)arg2;
- (void)playFailed:(id)arg1;
- (void)playFinished:(_Bool)arg1;
- (void)doPlayStartedCallback;
- (void)player:(id)arg1 statusChangedTo:(long long)arg2 errorIfHas:(id)arg3;
- (void)stop;
- (void)play;
- (void)savePlaycallback:(const struct _tts_play_callback *)arg1;
- (void)savePlayerParam:(struct _tts_play_param *)arg1;
- (void)dealloc;
- (id)initWithFilePath:(id)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
|
danadel/sakai
|
providers/jldap/src/java/edu/amc/sakai/user/SimpleLdapConnectionManager.java
|
<gh_stars>0
package edu.amc.sakai.user;
import java.io.UnsupportedEncodingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPConstraints;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPTLSSocketFactory;
/**
* Allocates connected, constrained, and optionally
* bound and secure <code>LDAPConnections</code>
*
* @see LdapConnectionManagerConfig
* @author <NAME>, Unicon Inc
* @author <NAME>, Unicon Inc
*/
public class SimpleLdapConnectionManager implements LdapConnectionManager {
public static final String KEYSTORE_LOCATION_SYS_PROP_KEY =
"javax.net.ssl.trustStore";
public static final String KEYSTORE_PASSWORD_SYS_PROP_KEY =
"javax.net.ssl.trustStorePassword";
/** Class-specific logger */
private static Log M_log = LogFactory.getLog(SimpleLdapConnectionManager.class);
/** connection allocation configuration */
private LdapConnectionManagerConfig config;
/**
* {@inheritDoc}
*/
public void init() {
if ( M_log.isDebugEnabled() ) {
M_log.debug("init()");
}
if ( config.isSecureConnection() ) {
if ( M_log.isDebugEnabled() ) {
M_log.debug("init(): initializing secure socket factory");
}
initKeystoreLocation();
initKeystorePassword();
LDAPConnection.setSocketFactory(config.getSecureSocketFactory());
}
}
/**
* {@inheritDoc}
*/
public LDAPConnection getConnection() throws LDAPException {
if ( M_log.isDebugEnabled() ) {
M_log.debug("getConnection()");
}
LDAPConnection conn = new LDAPConnection();
applyConstraints(conn);
connect(conn);
if ( config.isAutoBind() ) {
if ( M_log.isDebugEnabled() ) {
M_log.debug("getConnection(): auto-binding");
}
try {
bind(conn, config.getLdapUser(), config.getLdapPassword());
} catch (LDAPException ldape) {
if (ldape.getResultCode() == LDAPException.INVALID_CREDENTIALS) {
M_log.warn("Failed to bind against: "+ conn.getHost()+ " with user: "+ config.getLdapUser()+ " password: "+ config.getLdapPassword().replaceAll(".", "*"));
}
throw ldape;
}
}
return conn;
}
/**
* {@inheritDoc}
*/
public LDAPConnection getBoundConnection(String dn, String pw) throws LDAPException {
if ( M_log.isDebugEnabled() ) {
M_log.debug("getBoundConnection(): [dn = " + dn + "]");
}
LDAPConnection conn = new LDAPConnection();
applyConstraints(conn);
connect(conn);
bind(conn, dn, pw);
return conn;
}
private void bind(LDAPConnection conn, String dn, String pw)
throws LDAPException {
if ( M_log.isDebugEnabled() ) {
M_log.debug("bind(): binding [dn = " + dn + "]");
}
try {
conn.bind(LDAPConnection.LDAP_V3, dn, pw.getBytes("UTF8"));
} catch ( UnsupportedEncodingException e ) {
throw new RuntimeException("Failed to encode user password", e);
}
}
/**
* {@inheritDoc}
*/
public void returnConnection(LDAPConnection conn) {
try {
if (conn != null)
conn.disconnect();
} catch (LDAPException e) {
M_log.error("returnConnection(): failed on disconnect: ", e);
}
}
/**
* {@inheritDoc}
*/
public void setConfig(LdapConnectionManagerConfig config) {
this.config = config;
}
/**
* {@inheritDoc}
*/
public LdapConnectionManagerConfig getConfig() {
return config;
}
/**
* Caches a keystore password as a system property. No-op
* if the {@link #KEYSTORE_PASSWORD_SYS_PROP_KEY} system property
* has a non-<code>null</code> value. Otherwise caches the
* keystore password from the currently assigned
* {@link LdapConnectionManagerConfig}.
*
* @param config
* @throws NullPointerException if a non-null keystore password
* cannot be resolved
*/
protected void initKeystorePassword() {
if ( M_log.isDebugEnabled() ) {
M_log.debug("initKeystorePassword()");
}
String sysKeystorePassword =
System.getProperty(KEYSTORE_PASSWORD_SYS_PROP_KEY);
if ( sysKeystorePassword == null ) {
String configuredKeystorePassword = config.getKeystorePassword();
if ( configuredKeystorePassword != null){
if ( M_log.isDebugEnabled() ) {
M_log.debug("initKeystorePassword(): setting system property");
}
System.setProperty(KEYSTORE_PASSWORD_SYS_PROP_KEY, configuredKeystorePassword);
}
} else {
if ( M_log.isDebugEnabled() ) {
M_log.debug("initKeystorePassword(): retained existing system property");
}
}
}
/**
* Caches a keystore location as a system property. No-op
* if the {@link #KEYSTORE_LOCATION_SYS_PROP_KEY} system property
* has a non-<code>null</code> value. Otherwise caches the
* keystore location from the currently assigned
* {@link LdapConnectionManagerConfig}.
*
* @param config
* @throws NullPointerException if a non-null keystore location
* cannot be resolved
*/
protected void initKeystoreLocation() {
if ( M_log.isDebugEnabled() ) {
M_log.debug("initKeystoreLocation()");
}
String sysKeystoreLocation =
System.getProperty(KEYSTORE_LOCATION_SYS_PROP_KEY);
if ( sysKeystoreLocation == null ) {
String configuredKeystoreLocation = config.getKeystoreLocation();
if ( configuredKeystoreLocation != null){
if ( M_log.isDebugEnabled() ) {
M_log.debug("initKeystoreLocation(): setting system property [location = " +
configuredKeystoreLocation + "]");
}
System.setProperty(KEYSTORE_LOCATION_SYS_PROP_KEY, configuredKeystoreLocation);
}
} else {
if ( M_log.isDebugEnabled() ) {
M_log.debug("initKeystoreLocation(): retained existing system property [location = " +
sysKeystoreLocation + "]");
}
}
}
/**
* Applies <code>LDAPConstraints</code>
* to the specified <code>LDAPConnection</code>.
* Implemented to assign <code>timeLimit</code> and
* <code>referralFollowing</code> constraint values
* retrieved from the currently assigned
* {@link LdapConnectionManagerConfig}.
*
* @param conn
*/
protected void applyConstraints(LDAPConnection conn) {
int timeout = config.getOperationTimeout();
boolean followReferrals = config.isFollowReferrals();
if ( M_log.isDebugEnabled() ) {
M_log.debug("applyConstraints(): values [timeout = " +
timeout + "][follow referrals = " + followReferrals + "]");
}
LDAPConstraints constraints = new LDAPConstraints();
constraints.setTimeLimit(timeout);
constraints.setReferralFollowing(followReferrals);
conn.setConstraints(constraints);
}
/**
* Connects the specified <code>LDAPConnection</code> to
* the currently configured host and port.
*
* @param conn an <code>LDAPConnection</code>
* @throws LDAPConnection if the connect attempt fails
*/
protected void connect(LDAPConnection conn) throws LDAPException {
if ( M_log.isDebugEnabled() ) {
M_log.debug("connect()");
}
conn.connect(config.getLdapHost(), config.getLdapPort());
try {
postConnect(conn);
} catch ( LDAPException e ) {
M_log.error("Failed to completely initialize a connection [host = " +
config.getLdapHost() + "][port = " +
config.getLdapPort() + "]", e);
try {
conn.disconnect();
} catch ( LDAPException ee ) {}
throw e;
} catch ( Throwable e ) {
M_log.error("Failed to completely initialize a connection [host = " +
config.getLdapHost() + "][port = " +
config.getLdapPort() + "]", e);
try {
conn.disconnect();
} catch ( LDAPException ee ) {}
if ( e instanceof Error ) {
throw (Error)e;
}
if ( e instanceof RuntimeException ) {
throw (RuntimeException)e;
}
throw new RuntimeException("LDAPConnection allocation failure", e);
}
}
protected void postConnect(LDAPConnection conn) throws LDAPException {
if ( M_log.isDebugEnabled() ) {
M_log.debug("postConnect()");
}
if ( config.isSecureConnection() && isTlsSocketFactory() ) {
if ( M_log.isDebugEnabled() ) {
M_log.debug("postConnect(): starting TLS");
}
conn.startTLS();
}
}
protected boolean isTlsSocketFactory() {
return config.getSecureSocketFactory() instanceof LDAPTLSSocketFactory;
}
/**
* {@inheritDoc}
*/
public void destroy() {
}
}
|
shumih/ckeditor5
|
packages/ckeditor5-basic-styles/tests/italic.js
|
/**
* @license Copyright (c) 2003-2019, CKSource - <NAME>. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
import Italic from '../src/italic';
import ItalicEditing from '../src/italic/italicediting';
import ItalicUI from '../src/italic/italicui';
describe('Italic', () => {
it('should require ItalicEditing and ItalicUI', () => {
expect(Italic.requires).to.deep.equal([ItalicEditing, ItalicUI]);
});
it('should be named', () => {
expect(Italic.pluginName).to.equal('Italic');
});
});
|
knuu/competitive-programming
|
leetcode/leet_028.py
|
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
haystack, needle = haystack + "\0", needle + "\0"
i, L = 0, len(haystack)
while haystack[i] != "\0":
if haystack[i] == needle[0]:
start, now = i, 0
while haystack[i] == needle[now] and haystack[i] != "\0" and needle[now] != "\0":
i += 1
start += 1
else:
if needle[now] == "\0":
return start
else:
i += 1
return -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.