text stringlengths 2 1.04M | meta dict |
|---|---|
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "3a04765f958f3ead81df79ecc569aa9d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "2b593fd823268ee60700c0cad978faed912dc2d5",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Moraceae/Dorstenia/Dorstenia infundibuliformis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
---
device.platform
===============
Get the device's operating system name.
var string = device.platform;
Supported Platforms
-------------------
- Android
- BlackBerry
- BlackBerry WebWorks (OS 5.0 and higher)
- iPhone
Quick Example
-------------
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry"
// - "iPhone"
// - "webOS"
//
var devicePlatform = device.platform;
Full Example
------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-0.9.4.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
//
function onDeviceReady() {
var element = document.getElementById('deviceProperties');
element.innerHTML = 'Device Name: ' + device.name + '<br />' +
'Device PhoneGap: ' + device.phonegap + '<br />' +
'Device Platform: ' + device.platform + '<br />' +
'Device UUID: ' + device.uuid + '<br />' +
'Device Version: ' + device.version + '<br />';
}
</script>
</head>
<body onload="onLoad()">
<p id="deviceProperties">Loading device properties...</p>
</body>
</html>
iPhone Quirks
-------------
All devices return `iPhone` as the platform. This is inaccurate because Apple has rebranded the iPhone operating system as `iOS`.
BlackBerry Quirks
-----------------
Devices may return the device platform version instead of the platform name. For example, the Storm2 9550 would return '2.13.0.95' or similar. | {
"content_hash": "a6ff4bb0aed8887dddcdd67aabc69be6",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 143,
"avg_line_length": 32.63333333333333,
"alnum_prop": 0.5812053115423902,
"repo_name": "maveriklko9719/Coffee-Spills",
"id": "29ebc1feeefe272e3e33a5a36b70c05f86f1e74b",
"size": "2941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/en/0.9.4/phonegap/device/device.platform.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10947"
},
{
"name": "JavaScript",
"bytes": "2656"
},
{
"name": "Ruby",
"bytes": "53938"
},
{
"name": "Shell",
"bytes": "643"
}
],
"symlink_target": ""
} |
<?php
namespace Netdudes\DataSourceryBundle\Extension;
interface UqlExtensionInterface
{
/**
* An array of functions that will be available to use in UQL
*
* @return UqlFunction[]
*/
public function getFunctions();
}
| {
"content_hash": "43b7f3c84d86e672898f6d1aadc0f46e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 65,
"avg_line_length": 19,
"alnum_prop": 0.6761133603238867,
"repo_name": "netdudes/DataSourceryBundle",
"id": "e6ec7b2ed979544dc691b505f08fd79371e95a5d",
"size": "247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Extension/UqlExtensionInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "233902"
}
],
"symlink_target": ""
} |
import React, { Component } from "react";
import { observer, inject } from "mobx-react";
import AddIcon from '@material-ui/icons/Add';
import CreateBlogAction from './Actions/createBlog';
import BrowserToolsAction from './Actions/browserTools';
import BrowserBooksAction from './Actions/browserBooks';
import SignInAction from './Actions/signIn';
import SignOutAction from './Actions/signOut';
import history from "app/utils/history";
import {
Container,
ClickableContainer,
} from "./elements";
import Tooltip from "common/components/Tooltip";
import HoverMenu from "app/components/HoverMenu/index";
import Menu from "./Menu";
class MoreActionsMenu extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
componentDidMount() { }
render() {
const hasLogged = !!this.props.store.user;
return (
<Container>
<ClickableContainer>
<Tooltip title="jackdon" size={"small"}>
<AddIcon
color={"action"}
onClick={e => {
this.setState({
open: true
});
}}
/>
</Tooltip>
</ClickableContainer>
{this.state.open === true && (
<HoverMenu
onClose={e => {
this.setState({
open: false
});
}}
>
<Menu {...this.props} menuActions={
[
{
onClick: () => {
history
.push('/blog?flag=new_blog');
},
children: <CreateBlogAction />
},
{
onClick: () => {
history
.push('/tools');
},
children: <BrowserToolsAction />
},
{
onClick: () => {
history
.push('/books');
},
children: <BrowserBooksAction />
},
{
onClick: () => {},
children: <SignInAction hasLogged={hasLogged} {...this.props}/>
},
{
onClick: () => { },
children: <SignOutAction hasLogged={hasLogged} {...this.props} />
}
]
} />
</HoverMenu>
)}
</Container>
);
}
}
export default inject("store", "signals")(observer(MoreActionsMenu));
| {
"content_hash": "0ddf58e3574d74e45a40001a10b2b46a",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 83,
"avg_line_length": 27.606382978723403,
"alnum_prop": 0.4504816955684008,
"repo_name": "jackdon/snoopy",
"id": "7ef1a72dedd855cd79863f516fc5ae1f9bfeef37",
"size": "2595",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/pages/Blog/MoreActionsMenu/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4923"
},
{
"name": "HTML",
"bytes": "3107"
},
{
"name": "JavaScript",
"bytes": "322126"
}
],
"symlink_target": ""
} |
from oslo.config import cfg
import socket
import netaddr
from ryu.base import app_manager
from ryu.controller import handler
from ryu.services.protocols.vrrp import event as vrrp_event
from ryu.services.protocols.vrrp import api as vrrp_api
from ryu.lib import rpc
from ryu.lib import hub
from ryu.lib import mac
VRRP_RPC_PORT = 50004 # random
CONF = cfg.CONF
CONF.register_opts([
cfg.IntOpt('vrrp-rpc-port', default=VRRP_RPC_PORT,
help='port for vrrp rpc interface')])
class RPCError(Exception):
pass
class Peer(object):
def __init__(self, queue):
super(Peer, self).__init__()
self.queue = queue
def _handle_vrrp_request(self, data):
self.queue.put((self, data))
class RpcVRRPManager(app_manager.RyuApp):
def __init__(self, *args, **kwargs):
super(RpcVRRPManager, self).__init__(*args, **kwargs)
self._args = args
self._kwargs = kwargs
self._peers = []
self._rpc_events = hub.Queue(128)
self.server_thread = hub.spawn(self._peer_accept_thread)
self.event_thread = hub.spawn(self._rpc_request_loop_thread)
def _rpc_request_loop_thread(self):
while True:
(peer, data) = self._rpc_events.get()
msgid, target_method, params = data
error = None
result = None
try:
if target_method == "vrrp_config":
result = self._config(msgid, params)
elif target_method == "vrrp_list":
result = self._list(msgid, params)
elif target_method == "vrrp_config_change":
result = self._config_change(msgid, params)
else:
error = 'Unknown method %s' % (target_method)
except RPCError as e:
error = str(e)
peer._endpoint.send_response(msgid, error=error, result=result)
def _peer_loop_thread(self, peer):
peer._endpoint.serve()
# the peer connection is closed
self._peers.remove(peer)
def peer_accept_handler(self, new_sock, addr):
peer = Peer(self._rpc_events)
table = {
rpc.MessageType.REQUEST: peer._handle_vrrp_request,
}
peer._endpoint = rpc.EndPoint(new_sock, disp_table=table)
self._peers.append(peer)
hub.spawn(self._peer_loop_thread, peer)
def _peer_accept_thread(self):
server = hub.StreamServer(('', CONF.vrrp_rpc_port),
self.peer_accept_handler)
server.serve_forever()
def _params_to_dict(self, params, keys):
d = {}
for k, v in params.items():
if k in keys:
d[k] = v
return d
def _config(self, msgid, params):
self.logger.debug('handle vrrp_config request')
try:
param_dict = params[0]
except:
raise RPCError('parameters are missing')
if_params = self._params_to_dict(param_dict,
('primary_ip_address',
'device_name'))
# drop vlan support later
if_params['vlan_id'] = None
if_params['mac_address'] = mac.DONTCARE_STR
try:
interface = vrrp_event.VRRPInterfaceNetworkDevice(**if_params)
except:
raise RPCError('parameters are invalid, %s' % (str(param_dict)))
config_params = self._params_to_dict(param_dict,
('vrid', # mandatory
'ip_addresses', # mandatory
'version',
'admin_state',
'priority',
'advertisement_interval',
'preempt_mode',
'preempt_delay',
'statistics_interval'))
try:
config = vrrp_event.VRRPConfig(**config_params)
except:
raise RPCError('parameters are invalid, %s' % (str(param_dict)))
config_result = vrrp_api.vrrp_config(self, interface, config)
api_result = [
config_result.config.vrid,
config_result.config.priority,
str(netaddr.IPAddress(config_result.config.ip_addresses[0]))]
return api_result
def _lookup_instance(self, vrid):
for instance in vrrp_api.vrrp_list(self).instance_list:
if vrid == instance.config.vrid:
return instance.instance_name
return None
def _config_change(self, msgid, params):
self.logger.debug('handle vrrp_config_change request')
try:
config_values = params[0]
except:
raise RPCError('parameters are missing')
vrid = config_values.get('vrid')
instance_name = self._lookup_instance(vrid)
if not instance_name:
raise RPCError('vrid %d is not found' % (vrid))
priority = config_values.get('priority')
interval = config_values.get('advertisement_interval')
vrrp_api.vrrp_config_change(self, instance_name, priority=priority,
advertisement_interval=interval)
return {}
def _list(self, msgid, params):
self.logger.debug('handle vrrp_list request')
result = vrrp_api.vrrp_list(self)
instance_list = result.instance_list
ret_list = []
for instance in instance_list:
c = instance.config
info_dict = {
"instance_name": instance.instance_name,
"vrid": c.vrid,
"version": c.version,
"advertisement_interval": c.advertisement_interval,
"priority": c.priority,
"virtual_ip_address": str(netaddr.IPAddress(c.ip_addresses[0]))
}
ret_list.append(info_dict)
return ret_list
@handler.set_ev_cls(vrrp_event.EventVRRPStateChanged)
def vrrp_state_changed_handler(self, ev):
self.logger.info('handle EventVRRPStateChanged')
name = ev.instance_name
old_state = ev.old_state
new_state = ev.new_state
vrid = ev.config.vrid
self.logger.info('VRID:%s %s: %s -> %s', vrid, name, old_state,
new_state)
params = {'vrid': vrid, 'old_state': old_state, 'new_state': new_state}
for peer in self._peers:
peer._endpoint.send_notification("notify_status", [params])
| {
"content_hash": "5109556ee73bf6f4897f58d3c670821e",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 79,
"avg_line_length": 36.67213114754098,
"alnum_prop": 0.5371777678438385,
"repo_name": "tashaband/RYU295",
"id": "0ba15e1da45f2166980a7aa09e66280ca3b0d08d",
"size": "7324",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ryu/services/protocols/vrrp/rpc_manager.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "846874"
},
{
"name": "CSS",
"bytes": "5449"
},
{
"name": "Erlang",
"bytes": "849217"
},
{
"name": "JavaScript",
"bytes": "1757"
},
{
"name": "Python",
"bytes": "3989777"
},
{
"name": "Shell",
"bytes": "68712"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.Collections.Generic;
using Hydra.Framework;
using Hydra.Framework.Collections;
using Hydra.Framework.Extensions;
namespace Hydra.Framework.StateMachine
{
public interface IEventActionExceptionHandler<T>
where T : StateMachine
{
void HandleException(T stateMachine, Event @event, object parameter, Exception exception);
}
public class ExceptionActionDictionary<T> :
IEnumerable<ExceptionAction<T>>, IEventActionExceptionHandler<T> where T : StateMachine<T>
{
private readonly Dictionary<Type, ExceptionAction<T>> _exceptionEvents = new Dictionary<Type, ExceptionAction<T>>();
public IEnumerator<ExceptionAction<T>> GetEnumerator()
{
return _exceptionEvents.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(params ExceptionAction<T>[] exceptionActions)
{
exceptionActions.Each(exceptionAction => _exceptionEvents.Add(exceptionAction.ExceptionType, exceptionAction));
}
public void HandleException(T stateMachine, Event @event, object parameter, Exception exception)
{
Type exceptionType = exception.GetType();
if (_exceptionEvents.ContainsKey(exceptionType))
{
_exceptionEvents[exceptionType].Execute(stateMachine, @event, parameter, exception);
}
else
{
string message = string.Format("Exception occurred in {0} during state {1} while handling {2}",
typeof (T).FullName,
stateMachine.CurrentState.Name,
@event.Name);
throw new StateMachineException(message, exception);
}
}
}
} | {
"content_hash": "11235bca6b0f44aa9977d91afaf7e9f7",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 118,
"avg_line_length": 30.6,
"alnum_prop": 0.7136066547831253,
"repo_name": "andywiddess/Hydra",
"id": "55269736af2624b2aa75e0e022773a68ebec7707",
"size": "1683",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "1/Framework/StateMachine/ExceptionActionDictionary.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "10373404"
},
{
"name": "XSLT",
"bytes": "12550"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>AWS IoT Embedded C Device SDK: aws_iot_shadow_interface.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">AWS IoT Embedded C Device SDK
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_abfcfcfc84ac60d48c338b8a657a9e1d.html">shadow</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">Data Structures</a> |
<a href="#typedef-members">Typedefs</a> |
<a href="#enum-members">Enumerations</a> |
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">aws_iot_shadow_interface.h File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Interface for thing shadow.
<a href="#details">More...</a></p>
<div class="textblock"><code>#include "<a class="el" href="aws__iot__mqtt__interface_8h_source.html">aws_iot_mqtt_interface.h</a>"</code><br />
<code>#include "<a class="el" href="aws__iot__shadow__json__data_8h_source.html">aws_iot_shadow_json_data.h</a>"</code><br />
</div>
<p><a href="aws__iot__shadow__interface_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Data Structures</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structShadowParameters__t.html">ShadowParameters_t</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Shadow Connect parameters. <a href="structShadowParameters__t.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="typedef-members"></a>
Typedefs</h2></td></tr>
<tr class="memitem:ab20a49b955606347ac9d18aef0e421c2"><td class="memItemLeft" align="right" valign="top">typedef void(* </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#ab20a49b955606347ac9d18aef0e421c2">fpActionCallback_t</a>) (const char *pThingName, <a class="el" href="aws__iot__shadow__interface_8h.html#a1fc9e025434023d44d33737f8b7c2a8c">ShadowActions_t</a> action, <a class="el" href="aws__iot__shadow__interface_8h.html#ad946163c2ac5df0aa896520949d47956">Shadow_Ack_Status_t</a> status, const char *pReceivedJsonDocument, void *pContextData)</td></tr>
<tr class="memdesc:ab20a49b955606347ac9d18aef0e421c2"><td class="mdescLeft"> </td><td class="mdescRight">Function Pointer typedef used as the callback for every action. <a href="#ab20a49b955606347ac9d18aef0e421c2">More...</a><br /></td></tr>
<tr class="separator:ab20a49b955606347ac9d18aef0e421c2"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="enum-members"></a>
Enumerations</h2></td></tr>
<tr class="memitem:ad946163c2ac5df0aa896520949d47956"><td class="memItemLeft" align="right" valign="top">enum  </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#ad946163c2ac5df0aa896520949d47956">Shadow_Ack_Status_t</a> { <b>SHADOW_ACK_TIMEOUT</b>,
<b>SHADOW_ACK_REJECTED</b>,
<b>SHADOW_ACK_ACCEPTED</b>
}<tr class="memdesc:ad946163c2ac5df0aa896520949d47956"><td class="mdescLeft"> </td><td class="mdescRight">Thing Shadow Acknowledgment enum. <a href="aws__iot__shadow__interface_8h.html#ad946163c2ac5df0aa896520949d47956">More...</a><br /></td></tr>
<tr class="separator:ad946163c2ac5df0aa896520949d47956"><td class="memSeparator" colspan="2"> </td></tr>
</td></tr>
<tr class="memitem:a1fc9e025434023d44d33737f8b7c2a8c"><td class="memItemLeft" align="right" valign="top">enum  </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a1fc9e025434023d44d33737f8b7c2a8c">ShadowActions_t</a> { <b>SHADOW_GET</b>,
<b>SHADOW_UPDATE</b>,
<b>SHADOW_DELETE</b>
}<tr class="memdesc:a1fc9e025434023d44d33737f8b7c2a8c"><td class="mdescLeft"> </td><td class="mdescRight">Thing Shadow Action type enum. <a href="aws__iot__shadow__interface_8h.html#a1fc9e025434023d44d33737f8b7c2a8c">More...</a><br /></td></tr>
<tr class="separator:a1fc9e025434023d44d33737f8b7c2a8c"><td class="memSeparator" colspan="2"> </td></tr>
</td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a79596d860d0f30ece4d2ee167784a2aa"><td class="memItemLeft" align="right" valign="top"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a79596d860d0f30ece4d2ee167784a2aa">aws_iot_shadow_init</a> (<a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> *pClient)</td></tr>
<tr class="memdesc:a79596d860d0f30ece4d2ee167784a2aa"><td class="mdescLeft"> </td><td class="mdescRight">Initialize the Thing Shadow before use. <a href="#a79596d860d0f30ece4d2ee167784a2aa">More...</a><br /></td></tr>
<tr class="separator:a79596d860d0f30ece4d2ee167784a2aa"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2c923cc396a5e82f0c7d3468400fea2c"><td class="memItemLeft" align="right" valign="top"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a2c923cc396a5e82f0c7d3468400fea2c">aws_iot_shadow_connect</a> (<a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> *pClient, <a class="el" href="structShadowParameters__t.html">ShadowParameters_t</a> *pParams)</td></tr>
<tr class="memdesc:a2c923cc396a5e82f0c7d3468400fea2c"><td class="mdescLeft"> </td><td class="mdescRight">Connect to the AWS IoT Thing Shadow service over MQTT. <a href="#a2c923cc396a5e82f0c7d3468400fea2c">More...</a><br /></td></tr>
<tr class="separator:a2c923cc396a5e82f0c7d3468400fea2c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0c5d153544c57027f0f802bf29376f87"><td class="memItemLeft" align="right" valign="top"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a0c5d153544c57027f0f802bf29376f87">aws_iot_shadow_yield</a> (<a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> *pClient, int timeout)</td></tr>
<tr class="memdesc:a0c5d153544c57027f0f802bf29376f87"><td class="mdescLeft"> </td><td class="mdescRight">Yield function to let the background tasks of MQTT and Shadow. <a href="#a0c5d153544c57027f0f802bf29376f87">More...</a><br /></td></tr>
<tr class="separator:a0c5d153544c57027f0f802bf29376f87"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:afdd8ea8d0677badf06b2765b5ec27109"><td class="memItemLeft" align="right" valign="top"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#afdd8ea8d0677badf06b2765b5ec27109">aws_iot_shadow_disconnect</a> (<a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> *pClient)</td></tr>
<tr class="memdesc:afdd8ea8d0677badf06b2765b5ec27109"><td class="mdescLeft"> </td><td class="mdescRight">Disconnect from the AWS IoT Thing Shadow service over MQTT. <a href="#afdd8ea8d0677badf06b2765b5ec27109">More...</a><br /></td></tr>
<tr class="separator:afdd8ea8d0677badf06b2765b5ec27109"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab762304e44b7315a39e9f1ed5462a498"><td class="memItemLeft" align="right" valign="top"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#ab762304e44b7315a39e9f1ed5462a498">aws_iot_shadow_update</a> (<a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> *pClient, const char *pThingName, char *pJsonString, <a class="el" href="aws__iot__shadow__interface_8h.html#ab20a49b955606347ac9d18aef0e421c2">fpActionCallback_t</a> callback, void *pContextData, uint8_t timeout_seconds, bool isPersistentSubscribe)</td></tr>
<tr class="memdesc:ab762304e44b7315a39e9f1ed5462a498"><td class="mdescLeft"> </td><td class="mdescRight">This function is the one used to perform an Update action to a Thing Name's Shadow. <a href="#ab762304e44b7315a39e9f1ed5462a498">More...</a><br /></td></tr>
<tr class="separator:ab762304e44b7315a39e9f1ed5462a498"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adf3d2ab4117b6061aeb756a6ec639966"><td class="memItemLeft" align="right" valign="top"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#adf3d2ab4117b6061aeb756a6ec639966">aws_iot_shadow_get</a> (<a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> *pClient, const char *pThingName, <a class="el" href="aws__iot__shadow__interface_8h.html#ab20a49b955606347ac9d18aef0e421c2">fpActionCallback_t</a> callback, void *pContextData, uint8_t timeout_seconds, bool isPersistentSubscribe)</td></tr>
<tr class="memdesc:adf3d2ab4117b6061aeb756a6ec639966"><td class="mdescLeft"> </td><td class="mdescRight">This function is the one used to perform an Get action to a Thing Name's Shadow. <a href="#adf3d2ab4117b6061aeb756a6ec639966">More...</a><br /></td></tr>
<tr class="separator:adf3d2ab4117b6061aeb756a6ec639966"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a826d6fd7d28b753d8cef2cc4ed717f7a"><td class="memItemLeft" align="right" valign="top"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a826d6fd7d28b753d8cef2cc4ed717f7a">aws_iot_shadow_delete</a> (<a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> *pClient, const char *pThingName, <a class="el" href="aws__iot__shadow__interface_8h.html#ab20a49b955606347ac9d18aef0e421c2">fpActionCallback_t</a> callback, void *pContextData, uint8_t timeout_seconds, bool isPersistentSubscriptions)</td></tr>
<tr class="memdesc:a826d6fd7d28b753d8cef2cc4ed717f7a"><td class="mdescLeft"> </td><td class="mdescRight">This function is the one used to perform an Delete action to a Thing Name's Shadow. <a href="#a826d6fd7d28b753d8cef2cc4ed717f7a">More...</a><br /></td></tr>
<tr class="separator:a826d6fd7d28b753d8cef2cc4ed717f7a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2018994362d1ecc99af2151227d5bb41"><td class="memItemLeft" align="right" valign="top"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a2018994362d1ecc99af2151227d5bb41">aws_iot_shadow_register_delta</a> (<a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> *pClient, <a class="el" href="aws__iot__shadow__json__data_8h.html#a429dd7999755780be803c160a8f72549">jsonStruct_t</a> *pStruct)</td></tr>
<tr class="memdesc:a2018994362d1ecc99af2151227d5bb41"><td class="mdescLeft"> </td><td class="mdescRight">This function is used to listen on the delta topic of <a class="el" href="aws__iot__config_8h.html#ae5283c01e3f612fd5eb92dbc3e446d38" title="Thing Name of the Shadow this device is associated with. ">AWS_IOT_MY_THING_NAME</a> mentioned in the <a class="el" href="aws__iot__config_8h.html" title="AWS IoT specific configuration file. ">aws_iot_config.h</a> file. <a href="#a2018994362d1ecc99af2151227d5bb41">More...</a><br /></td></tr>
<tr class="separator:a2018994362d1ecc99af2151227d5bb41"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2885a09ae8254c80f9db61c50c3018ca"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a2885a09ae8254c80f9db61c50c3018ca">aws_iot_shadow_reset_last_received_version</a> (void)</td></tr>
<tr class="memdesc:a2885a09ae8254c80f9db61c50c3018ca"><td class="mdescLeft"> </td><td class="mdescRight">Reset the last received version number to zero. This will be useful if the Thing Shadow is deleted and would like to to reset the local version. <a href="#a2885a09ae8254c80f9db61c50c3018ca">More...</a><br /></td></tr>
<tr class="separator:a2885a09ae8254c80f9db61c50c3018ca"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a416a959f46ab39f97ca4e137e8d8ed71"><td class="memItemLeft" align="right" valign="top">uint32_t </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a416a959f46ab39f97ca4e137e8d8ed71">aws_iot_shadow_get_last_received_version</a> (void)</td></tr>
<tr class="memdesc:a416a959f46ab39f97ca4e137e8d8ed71"><td class="mdescLeft"> </td><td class="mdescRight">Version of a document is received with every accepted/rejected and the SDK keeps track of the last received version of the JSON document of <a class="el" href="aws__iot__config_8h.html#ae5283c01e3f612fd5eb92dbc3e446d38" title="Thing Name of the Shadow this device is associated with. ">AWS_IOT_MY_THING_NAME</a> shadow. <a href="#a416a959f46ab39f97ca4e137e8d8ed71">More...</a><br /></td></tr>
<tr class="separator:a416a959f46ab39f97ca4e137e8d8ed71"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a764d85d53cff3f15f8a3d8047002a487"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#a764d85d53cff3f15f8a3d8047002a487">aws_iot_shadow_enable_discard_old_delta_msgs</a> (void)</td></tr>
<tr class="memdesc:a764d85d53cff3f15f8a3d8047002a487"><td class="mdescLeft"> </td><td class="mdescRight">Enable the ignoring of delta messages with old version number. <a href="#a764d85d53cff3f15f8a3d8047002a487">More...</a><br /></td></tr>
<tr class="separator:a764d85d53cff3f15f8a3d8047002a487"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af539707306365d92f333efdb5b4d0046"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af539707306365d92f333efdb5b4d0046"></a>
void </td><td class="memItemRight" valign="bottom"><a class="el" href="aws__iot__shadow__interface_8h.html#af539707306365d92f333efdb5b4d0046">aws_iot_shadow_disable_discard_old_delta_msgs</a> (void)</td></tr>
<tr class="memdesc:af539707306365d92f333efdb5b4d0046"><td class="mdescLeft"> </td><td class="mdescRight">Disable the ignoring of delta messages with old version number. <br /></td></tr>
<tr class="separator:af539707306365d92f333efdb5b4d0046"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>These are the functions and structs to manage/interact the Thing Shadow(in the cloud). This SDK will let you interact with your own thing shadow or any other shadow using its Thing Name. There are totally 3 actions a device can perform on the shadow - Get, Update and Delete.</p>
<p>Currently the device should use MQTT/S underneath. In the future this will also support other protocols. As it supports MQTT, the shadow needs to connect and disconnect. It will also work on the pub/sub model. On performing any action, the acknowledgment will be received in either accepted or rejected. For Example: If we want to perform a GET on the thing shadow the following messages will be sent and received:</p><ol type="1">
<li>A MQTT Publish on the topic - $aws/things/{thingName}/shadow/get</li>
<li>Subscribe to MQTT topics - $aws/things/{thingName}/shadow/get/accepted and $aws/things/{thingName}/shadow/get/rejected. If the request was successful we will receive the things json document in the accepted topic. </li>
</ol>
</div><h2 class="groupheader">Typedef Documentation</h2>
<a class="anchor" id="ab20a49b955606347ac9d18aef0e421c2"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">typedef void(* fpActionCallback_t) (const char *pThingName, <a class="el" href="aws__iot__shadow__interface_8h.html#a1fc9e025434023d44d33737f8b7c2a8c">ShadowActions_t</a> action, <a class="el" href="aws__iot__shadow__interface_8h.html#ad946163c2ac5df0aa896520949d47956">Shadow_Ack_Status_t</a> status, const char *pReceivedJsonDocument, void *pContextData)</td>
</tr>
</table>
</div><div class="memdoc">
<p>This function will be called from the context of <code><a class="el" href="aws__iot__shadow__interface_8h.html#a0c5d153544c57027f0f802bf29376f87" title="Yield function to let the background tasks of MQTT and Shadow. ">aws_iot_shadow_yield()</a></code> context</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pThingName</td><td>Thing Name of the response received </td></tr>
<tr><td class="paramname">action</td><td>The response of the action </td></tr>
<tr><td class="paramname">status</td><td>Informs if the action was Accepted/Rejected or Timed out </td></tr>
<tr><td class="paramname">pReceivedJsonDocument</td><td>Received JSON document </td></tr>
<tr><td class="paramname">pContextData</td><td>the void* data passed in during the action call(update, get or delete) </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<h2 class="groupheader">Enumeration Type Documentation</h2>
<a class="anchor" id="ad946163c2ac5df0aa896520949d47956"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">enum <a class="el" href="aws__iot__shadow__interface_8h.html#ad946163c2ac5df0aa896520949d47956">Shadow_Ack_Status_t</a></td>
</tr>
</table>
</div><div class="memdoc">
<p>This enum type is use in the callback for the action response </p>
</div>
</div>
<a class="anchor" id="a1fc9e025434023d44d33737f8b7c2a8c"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">enum <a class="el" href="aws__iot__shadow__interface_8h.html#a1fc9e025434023d44d33737f8b7c2a8c">ShadowActions_t</a></td>
</tr>
</table>
</div><div class="memdoc">
<p>This enum type is use in the callback for the action response </p>
</div>
</div>
<h2 class="groupheader">Function Documentation</h2>
<a class="anchor" id="a2c923cc396a5e82f0c7d3468400fea2c"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> aws_iot_shadow_connect </td>
<td>(</td>
<td class="paramtype"><a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> * </td>
<td class="paramname"><em>pClient</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="structShadowParameters__t.html">ShadowParameters_t</a> * </td>
<td class="paramname"><em>pParams</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>This function does the TLSv1.2 handshake and establishes the MQTT connection</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pClient</td><td>MQTT Client used as the protocol layer </td></tr>
<tr><td class="paramname">pParams</td><td>Shadow Conenction parameters like TLS cert location </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An IoT Error Type defining successful/failed Connection </dd></dl>
</div>
</div>
<a class="anchor" id="a826d6fd7d28b753d8cef2cc4ed717f7a"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> aws_iot_shadow_delete </td>
<td>(</td>
<td class="paramtype"><a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> * </td>
<td class="paramname"><em>pClient</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const char * </td>
<td class="paramname"><em>pThingName</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="aws__iot__shadow__interface_8h.html#ab20a49b955606347ac9d18aef0e421c2">fpActionCallback_t</a> </td>
<td class="paramname"><em>callback</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">void * </td>
<td class="paramname"><em>pContextData</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">uint8_t </td>
<td class="paramname"><em>timeout_seconds</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">bool </td>
<td class="paramname"><em>isPersistentSubscriptions</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>This is not a very common use case for device. It is generally the responsibility of the accompanying app to do the delete. It is similar to the Update function internally except it does not take a JSON document as the input. The Thing Shadow referred by the ThingName will be deleted.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pClient</td><td>MQTT Client used as the protocol layer </td></tr>
<tr><td class="paramname">pThingName</td><td>Thing Name of the Shadow that should be deleted </td></tr>
<tr><td class="paramname">callback</td><td>This is the callback that will be used to inform the caller of the response from the AWS IoT Shadow service.Callback could be set to NULL if response is not important </td></tr>
<tr><td class="paramname">pContextData</td><td>This is an extra parameter that could be passed along with the callback. It should be set to NULL if not used </td></tr>
<tr><td class="paramname">timeout_seconds</td><td>It is the time the SDK will wait for the response on either accepted/rejected before declaring timeout on the action </td></tr>
<tr><td class="paramname">isPersistentSubscribe</td><td>As mentioned above, every time if a device deletes the same Sahdow (JSON document) then this should be set to true to avoid repeated subscription and un-subscription. If the Thing Name is one off delete then this should be set to false </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An IoT Error Type defining successful/failed delete action </dd></dl>
</div>
</div>
<a class="anchor" id="afdd8ea8d0677badf06b2765b5ec27109"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> aws_iot_shadow_disconnect </td>
<td>(</td>
<td class="paramtype"><a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> * </td>
<td class="paramname"><em>pClient</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>This will close the underlying TCP connection, MQTT connection will also be closed</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pClient</td><td>MQTT Client used as the protocol layer </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An IoT Error Type defining successful/failed disconnect status </dd></dl>
</div>
</div>
<a class="anchor" id="a764d85d53cff3f15f8a3d8047002a487"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void aws_iot_shadow_enable_discard_old_delta_msgs </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>As we use MQTT underneath, there could be more than 1 of the same message if we use QoS 0. To avoid getting called for the same message, this functionality should be enabled. All the old message will be ignored </p>
</div>
</div>
<a class="anchor" id="adf3d2ab4117b6061aeb756a6ec639966"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> aws_iot_shadow_get </td>
<td>(</td>
<td class="paramtype"><a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> * </td>
<td class="paramname"><em>pClient</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const char * </td>
<td class="paramname"><em>pThingName</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="aws__iot__shadow__interface_8h.html#ab20a49b955606347ac9d18aef0e421c2">fpActionCallback_t</a> </td>
<td class="paramname"><em>callback</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">void * </td>
<td class="paramname"><em>pContextData</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">uint8_t </td>
<td class="paramname"><em>timeout_seconds</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">bool </td>
<td class="paramname"><em>isPersistentSubscribe</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>One use of this function is usually to get the config of a device at boot up. It is similar to the Update function internally except it does not take a JSON document as the input. The entire JSON document will be sent over the accepted topic</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pClient</td><td>MQTT Client used as the protocol layer </td></tr>
<tr><td class="paramname">pThingName</td><td>Thing Name of the JSON document that is needed </td></tr>
<tr><td class="paramname">callback</td><td>This is the callback that will be used to inform the caller of the response from the AWS IoT Shadow service.Callback could be set to NULL if response is not important </td></tr>
<tr><td class="paramname">pContextData</td><td>This is an extra parameter that could be passed along with the callback. It should be set to NULL if not used </td></tr>
<tr><td class="paramname">timeout_seconds</td><td>It is the time the SDK will wait for the response on either accepted/rejected before declaring timeout on the action </td></tr>
<tr><td class="paramname">isPersistentSubscribe</td><td>As mentioned above, every time if a device gets the same Sahdow (JSON document) then this should be set to true to avoid repeated subscription and un-subscription. If the Thing Name is one off get then this should be set to false </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An IoT Error Type defining successful/failed get action </dd></dl>
</div>
</div>
<a class="anchor" id="a416a959f46ab39f97ca4e137e8d8ed71"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">uint32_t aws_iot_shadow_get_last_received_version </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>One exception to this version tracking is that, the SDK will ignore the version from update/accepted topic. Rest of the responses will be scanned to update the version number. Accepting version change for update/accepted may cause version conflicts for delta message if the update message is received before the delta.</p>
<dl class="section return"><dt>Returns</dt><dd>version number of the last received response </dd></dl>
</div>
</div>
<a class="anchor" id="a79596d860d0f30ece4d2ee167784a2aa"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> aws_iot_shadow_init </td>
<td>(</td>
<td class="paramtype"><a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> * </td>
<td class="paramname"><em>pClient</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>This function takes care of initializing the internal book-keeping data structures</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pClient</td><td>MQTT Client used as the protocol layer </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An IoT Error Type defining successful/failed Initialization </dd></dl>
</div>
</div>
<a class="anchor" id="a2018994362d1ecc99af2151227d5bb41"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> aws_iot_shadow_register_delta </td>
<td>(</td>
<td class="paramtype"><a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> * </td>
<td class="paramname"><em>pClient</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="aws__iot__shadow__json__data_8h.html#a429dd7999755780be803c160a8f72549">jsonStruct_t</a> * </td>
<td class="paramname"><em>pStruct</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Any time a delta is published the Json document will be delivered to the pStruct->cb. If you don't want the parsing done by the SDK then use the jsonStruct_t key set to "state". A good example of this is displayed in the sample_apps/shadow_console_echo.c</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pClient</td><td>MQTT Client used as the protocol layer </td></tr>
<tr><td class="paramname">pStruct</td><td>The struct used to parse JSON value </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An IoT Error Type defining successful/failed delta registering </dd></dl>
</div>
</div>
<a class="anchor" id="a2885a09ae8254c80f9db61c50c3018ca"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void aws_iot_shadow_reset_last_received_version </td>
<td>(</td>
<td class="paramtype">void </td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<dl class="section return"><dt>Returns</dt><dd>no return values </dd></dl>
</div>
</div>
<a class="anchor" id="ab762304e44b7315a39e9f1ed5462a498"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> aws_iot_shadow_update </td>
<td>(</td>
<td class="paramtype"><a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> * </td>
<td class="paramname"><em>pClient</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const char * </td>
<td class="paramname"><em>pThingName</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">char * </td>
<td class="paramname"><em>pJsonString</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="aws__iot__shadow__interface_8h.html#ab20a49b955606347ac9d18aef0e421c2">fpActionCallback_t</a> </td>
<td class="paramname"><em>callback</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">void * </td>
<td class="paramname"><em>pContextData</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">uint8_t </td>
<td class="paramname"><em>timeout_seconds</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">bool </td>
<td class="paramname"><em>isPersistentSubscribe</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>update is one of the most frequently used functionality by a device. In most cases the device may be just reporting few params to update the thing shadow in the cloud Update Action if no callback or if the JSON document does not have a client token then will just publish the update and not track it.</p>
<dl class="section note"><dt>Note</dt><dd>The update has to subscribe to two topics update/accepted and update/rejected. This function waits 2 seconds to ensure the subscriptions are registered before publishing the update message. The following steps are performed on using this function:<ol type="1">
<li>Subscribe to Shadow topics - $aws/things/{thingName}/shadow/update/accepted and $aws/things/{thingName}/shadow/update/rejected</li>
<li>wait for 2 seconds for the subscription to take effect</li>
<li>Publish on the update topic - $aws/things/{thingName}/shadow/update</li>
<li>In the <code><a class="el" href="aws__iot__shadow__interface_8h.html#a0c5d153544c57027f0f802bf29376f87" title="Yield function to let the background tasks of MQTT and Shadow. ">aws_iot_shadow_yield()</a></code> function the response will be handled. In case of timeout or if the response is received, the subscription to shadow response topics are un-subscribed from. On the contrary if the persistent subscription is set to true then the un-subscribe will not be done. The topics will always be listened to.</li>
</ol>
</dd></dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pClient</td><td>MQTT Client used as the protocol layer </td></tr>
<tr><td class="paramname">pThingName</td><td>Thing Name of the shadow that needs to be Updated </td></tr>
<tr><td class="paramname">pJsonString</td><td>The update action expects a JSON document to send. The JSO String should be a null terminated string. This JSON document should adhere to the AWS IoT Thing Shadow specification. To help in the process of creating this document- SDK provides apis in <code><a class="el" href="aws__iot__shadow__json__data_8h.html" title="This file is the interface for all the Shadow related JSON functions. ">aws_iot_shadow_json_data.h</a></code> </td></tr>
<tr><td class="paramname">callback</td><td>This is the callback that will be used to inform the caller of the response from the AWS IoT Shadow service.Callback could be set to NULL if response is not important </td></tr>
<tr><td class="paramname">pContextData</td><td>This is an extra parameter that could be passed along with the callback. It should be set to NULL if not used </td></tr>
<tr><td class="paramname">timeout_seconds</td><td>It is the time the SDK will wait for the response on either accepted/rejected before declaring timeout on the action </td></tr>
<tr><td class="paramname">isPersistentSubscribe</td><td>As mentioned above, every time if a device updates the same shadow then this should be set to true to avoid repeated subscription and unsubscription. If the Thing Name is one off update then this should be set to false </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An IoT Error Type defining successful/failed update action </dd></dl>
</div>
</div>
<a class="anchor" id="a0c5d153544c57027f0f802bf29376f87"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="aws__iot__error_8h.html#a329da5c3a42979b72561e28e749f6921">IoT_Error_t</a> aws_iot_shadow_yield </td>
<td>(</td>
<td class="paramtype"><a class="el" href="structMQTTClient__t.html">MQTTClient_t</a> * </td>
<td class="paramname"><em>pClient</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">int </td>
<td class="paramname"><em>timeout</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>This function could be use in a separate thread waiting for the incoming messages, ensuring the connection is kept alive with the AWS Service. It also ensures the expired requests of Shadow actions are cleared and Timeout callback is executed. </p><dl class="section note"><dt>Note</dt><dd>All callbacks ever used in the SDK will be executed in the context of this function.</dd></dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">pClient</td><td>MQTT Client used as the protocol layer </td></tr>
<tr><td class="paramname">timeout</td><td>in milliseconds, This is the maximum time the yield function will wait for a message and/or read the messages from the TLS buffer </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>An IoT Error Type defining successful/failed Yield </dd></dl>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.10
</small></address>
</body>
</html>
| {
"content_hash": "077e3cf2446fa457830910b5757b2d09",
"timestamp": "",
"source": "github",
"line_count": 646,
"max_line_length": 691,
"avg_line_length": 66.94582043343654,
"alnum_prop": 0.6761625083820844,
"repo_name": "greatlevi/mqtt",
"id": "278422669e00136b2deff4ce84fb7ec55554a19c",
"size": "43247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/html/aws__iot__shadow__interface_8h.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "263031"
},
{
"name": "C++",
"bytes": "45276"
},
{
"name": "HTML",
"bytes": "10835"
},
{
"name": "Makefile",
"bytes": "13639"
}
],
"symlink_target": ""
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Azure.Messaging.ServiceBus;
using Microsoft.Extensions.Logging;
namespace Microsoft.Azure.WebJobs.Extensions.ServiceBus.Tests.Samples
{
public static class TriggerBatch
{
#region Snippet:ServiceBusTriggerBatch
[FunctionName("TriggerBatch")]
public static void Run(
[ServiceBusTrigger("<queue_name>", Connection = "<connection_name>")] ServiceBusReceivedMessage[] messages,
ILogger logger)
{
foreach (ServiceBusReceivedMessage message in messages)
{
logger.LogInformation($"C# function triggered to process a message: {message.Body}");
logger.LogInformation($"EnqueuedTime={message.EnqueuedTime}");
}
}
#endregion
}
} | {
"content_hash": "6be28d1b921144162398f966d6635587",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 119,
"avg_line_length": 37.12,
"alnum_prop": 0.6637931034482759,
"repo_name": "ayeletshpigelman/azure-sdk-for-net",
"id": "ffa36b9f754969ed7796d2a78ce3e556f6ccc40f",
"size": "930",
"binary": false,
"copies": "4",
"ref": "refs/heads/ayshpige/InternalBranchForDebuging",
"path": "sdk/servicebus/Microsoft.Azure.WebJobs.Extensions.ServiceBus/tests/Samples/TriggerBatch.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "118"
},
{
"name": "Batchfile",
"bytes": "28895"
},
{
"name": "C#",
"bytes": "45912328"
},
{
"name": "CSS",
"bytes": "685"
},
{
"name": "HTML",
"bytes": "45212"
},
{
"name": "JavaScript",
"bytes": "7875"
},
{
"name": "PowerShell",
"bytes": "24250"
},
{
"name": "Shell",
"bytes": "1470"
},
{
"name": "XSLT",
"bytes": "6114"
}
],
"symlink_target": ""
} |
<?php
namespace console\rbac;
use common\models\User;
use Yii;
use yii\rbac\Rule;
/**
* Created by PhpStorm.
* User: DezMonT
* Date: 31.03.2015
* Time: 14:46
*/
class CanEdit extends Rule
{
public $name = __CLASS__;
/**
* Executes the rule.
*
* @param string|integer $user the user ID. This should be either an integer or a string representing
* the unique identifier of a user. See [[\yii\web\User::id]].
* @param \yii\rbac\Item $item the role or permission that this rule is associated with
* @param array $params parameters passed to [[ManagerInterface::checkAccess()]].
* @return boolean a value indicating whether the rule permits the auth item it is associated with.
*/
public function execute($user, $item, $params)
{
/**@var User $user*/
$user = Yii::$app->user->identity;
return (isset($params['user'])) ? $user->id == $params['user']->id || $user->canEdit($params['user']->role) : false;
}
} | {
"content_hash": "5e236fe3f8687a2b7423d111871a41e5",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 125,
"avg_line_length": 31.03125,
"alnum_prop": 0.6314199395770392,
"repo_name": "djrosl/travel",
"id": "77e78cd350d7d663cac958b08cce6f9389c3b784",
"size": "993",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "console/rbac/CanEdit.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "42916"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "844288"
},
{
"name": "HTML",
"bytes": "1329918"
},
{
"name": "JavaScript",
"bytes": "729181"
},
{
"name": "PHP",
"bytes": "9309381"
}
],
"symlink_target": ""
} |
class Proxmark3 < Formula
desc "Proxmark3 client, CDC flasher, HID flasher and firmware bundle"
homepage "http://www.proxmark.org"
url "https://github.com/proxmark/proxmark3/archive/v3.1.0.tar.gz"
sha256 "855bf191479b1389c0761dc34fa6c738dc775599e95e679847f4c7f1c276d8de"
head "https://github.com/pwpiwi/proxmark3.git", :branch => "travis_test"
# depends_on "automake" => :build
depends_on "readline"
# depends_on "p7zip" => :build
depends_on "libusb"
depends_on "libusb-compat"
depends_on "pkg-config" => :build
# depends_on "wget"
depends_on "qt5"
depends_on "perl" => :build
depends_on "proxmark/proxmark3/arm-none-eabi-gcc" => :build
def install
ENV.deparallelize
# system "make", "-C", "client/hid-flasher/"
system "make", "clean"
system "make", "all"
bin.mkpath
bin.install "client/flasher" => "proxmark3-flasher"
# bin.install "client/hid-flasher/flasher" => "proxmark3-hid-flasher"
bin.install "client/proxmark3" => "proxmark3"
bin.install "client/fpga_compress" => "fpga_compress"
# default keys
bin.install "client/default_keys.dic" => "default_keys.dic"
bin.install "client/default_pwd.dic" => "default_pwd.dic"
# hardnested files
(bin/"hardnested/tables").mkpath
(bin/"hardnested").install "client/hardnested/bf_bench_data.bin"
(bin/"hardnested/tables").install Dir["client/hardnested/tables/*"]
# lua libs for proxmark3 scripts
(bin/"lualibs").mkpath
(bin/"lualibs").install Dir["client/lualibs/*"]
# lua scripts
(bin/"scripts").mkpath
(bin/"scripts").install Dir["client/scripts/*"]
# trace files for experimentations
(bin/"traces").mkpath
(bin/"traces").install Dir["traces/*"]
# emv public keys file
if File.exist?("client/emv/capk.txt") then
(bin/"emv").mkpath
(bin/"emv").install "client/emv/capk.txt"
end
share.mkpath
# compiled firmware for flashing
(share/"firmware").mkpath
(share/"firmware").install "armsrc/obj/fullimage.elf" => "fullimage.elf"
(share/"firmware").install "bootrom/obj/bootrom.elf" => "bootrom.elf"
# ohai "Install success! Upgrade devices on HID firmware with proxmark3-hid-flasher, or devices on more modern firmware with proxmark3-flasher."
ohai "Install success! Only proxmark3-flasher (modern firmware) is available."
ohai "The latest bootloader and firmware binaries are ready and waiting in the current homebrew Cellar within share/firmware."
end
test do
system "proxmark3", "-h"
end
end
| {
"content_hash": "5dface666638ff1cbfe32efcfd8e3f55",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 147,
"avg_line_length": 34.527027027027025,
"alnum_prop": 0.6825831702544032,
"repo_name": "pwpiwi/homebrew-proxmark3",
"id": "752549f0976641887ce0b777298e46aba892a4c1",
"size": "2555",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "proxmark3.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "2993"
}
],
"symlink_target": ""
} |
/*
Theme Name: Kelly Anne T. Pipe Web Design
Theme URI: http://roots.io/
Description: Roots is a WordPress starter theme based on HTML5 Boilerplate & Bootstrap. <a href="https://github.com/roots/roots/contributors">Contribute on GitHub</a>
Version: 6.5.1
Author: Ben Word
Author URI: http://benword.com/
License: MIT License
License URI: http://opensource.org/licenses/MIT
*/
| {
"content_hash": "d2547ad08e6883f168cbc0988537f581",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 173,
"avg_line_length": 40.90909090909091,
"alnum_prop": 0.6311111111111111,
"repo_name": "kellygrape/kapipe-roots",
"id": "09a63f5b38ba0c5f2248d5404137b5b464adf361",
"size": "450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "style.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "228962"
},
{
"name": "JavaScript",
"bytes": "4634"
},
{
"name": "PHP",
"bytes": "58566"
}
],
"symlink_target": ""
} |
package com.jeff.chaser.models.systems.common
import com.badlogic.ashley.core._
import com.badlogic.ashley.systems.IteratingSystem
import com.badlogic.gdx.graphics.g2d.Animation.PlayMode
import com.jeff.chaser.models.components.util.NonStaticComponent
import com.jeff.chaser.models.components.view.{AnimatorComponent, RenderComponent}
import com.jeff.chaser.models.util.AnimInfo
class AnimatorSystem extends IteratingSystem(Family.all(classOf[AnimatorComponent],
classOf[RenderComponent], classOf[NonStaticComponent]).get()) {
private val am = ComponentMapper.getFor(classOf[AnimatorComponent])
private val rm = ComponentMapper.getFor(classOf[RenderComponent])
override def processEntity(entity: Entity, deltaTime: Float): Unit = {
val animComp = am.get(entity)
val renderComp = rm.get(entity)
if (animComp.curState != animComp.nextState) {
animComp.states.get(animComp.curState).elapsed = 0
animComp.curState = animComp.nextState
}
val animInfo: AnimInfo = animComp.states.get(animComp.curState)
if (animInfo.animation.isAnimationFinished(animInfo.elapsed)) {
animInfo.elapsed = 0
}
val frame = animInfo.animation.getKeyFrame(animInfo.elapsed, animInfo.animation.getPlayMode match {
case PlayMode.LOOP | PlayMode.LOOP_PINGPONG | PlayMode.LOOP_RANDOM | PlayMode.LOOP_REVERSED => true
case _ => false
})
renderComp.tex = frame
animInfo.elapsed += deltaTime
}
}
| {
"content_hash": "7a8f523eaee466fc3c061cd2ff299262",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 105,
"avg_line_length": 37.256410256410255,
"alnum_prop": 0.7591190640055059,
"repo_name": "jregistr/Academia",
"id": "621024fccb37ae1e24084327709f7f0f2405c8c1",
"size": "1453",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CSC455-Game-Programming/Chaser/core/src/com/jeff/chaser/models/systems/common/AnimatorSystem.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "9640"
},
{
"name": "C",
"bytes": "26783"
},
{
"name": "CSS",
"bytes": "161326"
},
{
"name": "Common Lisp",
"bytes": "4503"
},
{
"name": "FreeMarker",
"bytes": "31427"
},
{
"name": "GLSL",
"bytes": "3859"
},
{
"name": "Groovy",
"bytes": "314959"
},
{
"name": "HTML",
"bytes": "426918"
},
{
"name": "Java",
"bytes": "948334"
},
{
"name": "JavaScript",
"bytes": "708937"
},
{
"name": "Kotlin",
"bytes": "20648"
},
{
"name": "Makefile",
"bytes": "438"
},
{
"name": "Prolog",
"bytes": "1130"
},
{
"name": "Python",
"bytes": "24771"
},
{
"name": "Scala",
"bytes": "103751"
},
{
"name": "Shell",
"bytes": "20351"
},
{
"name": "TypeScript",
"bytes": "67347"
}
],
"symlink_target": ""
} |
#include "VariableSet.h"
#include <QtCore/QByteArray>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QVariant>
#include "../eirBase/BaseLog.h"
#include "VariableIdList.h"
VariableSetData::VariableSetData(const VariableSetData & other)
: QSharedData(other)
, name_s(other.name_s)
, key_u64(other.key_u64)
, id_s(other.id_s)
, vbl_map(other.vbl_map)
, var_list(other.var_list)
, _ba(other._ba)
{
}
VariableSet::VariableSet(const QString & name)
: data(new VariableSetData)
{
data->name_s = name;
}
VariableSet::VariableSet(const quint64 key,
const QString & id,
const QString & name)
: data(new VariableSetData)
{
data->name_s = name;
data->key_u64 = key;
data->id_s = id;
}
VariableSet::VariableSet(const VariableSet & other)
: data(other.data)
{
}
VariableSet &VariableSet::operator=(const VariableSet & rhs)
{
if (this != &rhs)
data.operator=(rhs.data);
return *this;
}
VariableSet::~VariableSet()
{
}
QString VariableSet::name(void) const
{
return data->name_s;
}
quint64 VariableSet::key(void) const
{
return data->key_u64;
}
QString VariableSet::id(void) const
{
return data->id_s;
}
void VariableSet::setName(const QString & newName)
{
data->name_s = newName;
}
void VariableSet::setKey(const quint64 key)
{
data->key_u64 = key;
}
void VariableSet::setId(const QString & id)
{
data->id_s = id;
}
void VariableSet::clear(void)
{
data->vbl_map.clear();
data->var_list.clear();
data->_ba.clear();
}
int VariableSet::binarySize(void) const
{
return data->_ba.size();
}
int VariableSet::listSize(void) const
{
return data->var_list.size();
}
int VariableSet::mapSize(void) const
{
return data->vbl_map.size();
}
bool VariableSet::contains(const VariableId & vid) const
{
return data->vbl_map.contains(vid.sortable());
}
void VariableSet::reset(void)
{
foreach (QString key, data->vbl_map.keys())
data->vbl_map[key].reset();
}
/** @fn blog()
*
* @todo Stringify QVariants
*/
void VariableSet::blog(void) const
{
#if 0
BLOG(Severity::Dump, "VariableSet: name=%s, key=%d 0x%X, id=%s",
qPrintable(data->name_s), data->key_u64,
data->key_u64, qPrintable(data->id_s));
foreach (QString key, data->vbl_map.keys())
{
Variable vbl(data->vbl_map.value(key));
BLOG(Severity::Dump, "%s = {%s}",
qPrintable(vbl.id()), qPrintable(vbl.var().toString()));
}
for (int x = 0; x < data->var_list.size(); ++x)
BLOG(Severity::Dump, "%i. {%s}", x,
qPrintable(data->var_list.at(x).toString()));
BLOG(Severity::Dump, "%d bytes of Binary", data->_ba.size());
#endif
}
bool VariableSet::isEmpty(void) const
{
return data->vbl_map.isEmpty()
&& data->var_list.isEmpty()
&& data->_ba.isEmpty();
}
void VariableSet::set(const QVariantList & vl)
{
data->var_list = vl;
}
void VariableSet::set(const Variable & vbl)
{
//data->vbl_map.insert(vbl.id().sortable(), vbl);
data->vbl_map[vbl.id().sortable()] = vbl;
}
void VariableSet::set(const VariableId & vid,
const QVariant & value)
{
//data->vbl_map.insert(vid.sortable(), Variable(vid, value));
QVariant def(data->vbl_map[vid.sortable()].defaultVar());
data->vbl_map[vid.sortable()] = Variable(vid, value, def);
}
void VariableSet::set(const int index,
const QVariant & value)
{
while (data->var_list.size() <= index)
data->var_list.append(QVariant());
data->var_list[index] = value;
}
void VariableSet::set(const QByteArray & ba)
{
data->_ba = ba;
}
void VariableSet::reset(const VariableId & id)
{
if (data->vbl_map.contains(id.sortable()))
data->vbl_map[id.sortable()].reset();
}
void VariableSet::append(const QVariant & value)
{
data->var_list.append(value);
}
Variable VariableSet::at(const VariableId & id) const
{
return data->vbl_map.value(id.sortable());
}
QVariant VariableSet::value(const VariableId & id,
const QVariant & defaultValue) const
{
#if 1 // def QT_DEBUG
QString key(id.sortable());
if (data->vbl_map.contains(key))
{
Variable vbl(data->vbl_map.value(key));
QVariant var(vbl.var());
return var;
}
else
return defaultValue;
#else
return data->vbl_map.value(id.sortable()).var();
#endif
}
QVariant VariableSet::value(const int index) const
{
return (index >= 0 && index < data->var_list.size())
? data->var_list.at(index)
: QVariant();
}
QByteArray VariableSet::value(void) const
{
return data->_ba;
}
QVariantList VariableSet::values(void) const
{
return data->var_list;
}
VariableSet VariableSet::exportSection(const VariableId & sectionId) const
{
VariableSet result;
int n = sectionId.sectionCount();
foreach (VariableId vid, ids(sectionId))
{
VariableId newId(vid.sections(n));
result.set(newId, value(vid));
}
return result;
}
VariableIdList VariableSet::ids(const VariableId & within) const
{
VariableIdList result;
if (within.isNull())
foreach (Variable vbl, data->vbl_map.values())
result.append(vbl.id());
else
{
QString prefix(within.sortable());
foreach (Variable vbl, data->vbl_map.values())
if (vbl.id().sortable().startsWith(prefix))
result.append(vbl.id());
}
return result;
}
VariableIdList VariableSet::sectionIds(const VariableId & within) const
{
VariableIdList result;
if (within.isNull())
foreach (Variable vbl, data->vbl_map.values())
{
QString section(vbl.id().section(0));
if ( ! result.contains(VariableId(section)))
result.append(VariableId(section));
}
else
{
int n = within.sectionCount();
foreach (Variable vbl, data->vbl_map.values())
{
QString section(vbl.id().section(n));
if (QString(within) == vbl.id().sections(0, n-1))
if ( ! result.contains(VariableId(section)))
result.append(VariableId(section));
}
}
return result;
}
void VariableSet::import(const VariableSet & other,
const VariableId & sectionId)
{
foreach (Variable vbl, other.data->vbl_map.values())
{
VariableId vid(vbl.id());
vid.prepend(sectionId);
set(vid, vbl.var());
}
}
QList<Variable> VariableSet::all(void) const
{
return data->vbl_map.values();
}
| {
"content_hash": "e55da19a002ee576b1607e9fbf9efb67",
"timestamp": "",
"source": "github",
"line_count": 299,
"max_line_length": 74,
"avg_line_length": 23.25752508361204,
"alnum_prop": 0.5812482024733966,
"repo_name": "eirTony/INDI1",
"id": "f7afa1b5ba82ad6a04fc24808c6882acf410b68c",
"size": "6954",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "incoming/BitBucket-INDI1/trunk186/If1main/EIRlibs/eirCore/VariableSet.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2182"
},
{
"name": "C",
"bytes": "987751"
},
{
"name": "C++",
"bytes": "25614243"
},
{
"name": "CMake",
"bytes": "723934"
},
{
"name": "CSS",
"bytes": "175949"
},
{
"name": "Cuda",
"bytes": "311879"
},
{
"name": "HTML",
"bytes": "839417"
},
{
"name": "Java",
"bytes": "127925"
},
{
"name": "JavaScript",
"bytes": "199216"
},
{
"name": "M4",
"bytes": "200"
},
{
"name": "Makefile",
"bytes": "6245411"
},
{
"name": "Mathematica",
"bytes": "284"
},
{
"name": "Objective-C++",
"bytes": "53970"
},
{
"name": "Prolog",
"bytes": "2474"
},
{
"name": "Python",
"bytes": "415039"
},
{
"name": "QMake",
"bytes": "173988"
},
{
"name": "Shell",
"bytes": "3748"
},
{
"name": "TeX",
"bytes": "1530252"
}
],
"symlink_target": ""
} |
package org.ukettle.service.router.entity;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.ukettle.basics.base.entity.BaseEntity;
import org.ukettle.www.xstream.annotations.XStream2Field;
@XStreamAlias("response")
public class Message extends BaseEntity {
private static final long serialVersionUID = 3668575797512981091L;
@XStreamAlias("code")
@XStream2Field
private String code;
@XStreamAlias("message")
@XStream2Field
private String message;
public Message() {
}
public Message(Error code) {
this.code = String.valueOf(code.getKey());
this.message = code.getMessage();
}
public Message(Error code, String message) {
this.code = String.valueOf(code.getKey());
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public enum Error {
/** 访问权限 */
ACCESS_VALID_FAIL(100, "Authentication Failed"),
ACCESS_VALID_ERROR(101, "Permission Error"),
/** 系统权限 */
SYSTEM_VALID_USER(200, "Uknown User"),
SYSTEM_VALID_ERROR(201,"Unknown Error"),
/** API业务参数 */
API_MISSING_PARAMS(300, "Missing Parameter"),
API_MISSING_ID(201,"Missing id"),
API_MISSING_SIGNATURE(302, "Missing signature"),
API_MISSING_TIMESTAMP(303, "Missing timestamp"),
API_INVALID_TIMESTAMP(304, "Invalid timestamp"),
API_VALID_FAIL(305, "Valid Fail"),
/** 其他参数 */
ERROR(0, "service error"), UNKNOWN(-1, "unknown error");
final int key;
final String message;
private Error(int key, String message) {
this.key = key;
this.message = message;
}
public static Error getErrorCode(int key) {
for (Error err : values()) {
if (err.key == key)
return err;
}
return UNKNOWN;
}
public int getKey() {
return key;
}
public String getMessage() {
return message;
}
}
} | {
"content_hash": "a97610e86bf336f4f1a52e2e107768ed",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 67,
"avg_line_length": 21.755555555555556,
"alnum_prop": 0.6899897854954035,
"repo_name": "uKettle/kettle",
"id": "a3b8132372a444734477697077a7099d5244488d",
"size": "1990",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/ukettle/service/router/entity/Message.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "81662"
},
{
"name": "HTML",
"bytes": "493"
},
{
"name": "Java",
"bytes": "510546"
},
{
"name": "JavaScript",
"bytes": "98946"
}
],
"symlink_target": ""
} |
from dataflows import Flow, find_replace
from datapackage_pipelines.wrapper import ingest
from datapackage_pipelines.utilities.flow_utils import spew_flow
def flow(parameters):
return Flow(
find_replace(
parameters.get('fields', []),
resources=parameters.get('resources')
)
)
if __name__ == '__main__':
with ingest() as ctx:
spew_flow(flow(ctx.parameters), ctx)
| {
"content_hash": "9b3825f89cba11032491a89cb975f54c",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 64,
"avg_line_length": 25.058823529411764,
"alnum_prop": 0.6431924882629108,
"repo_name": "frictionlessdata/datapackage-pipelines",
"id": "e427fe657ae512b7665270c863fb59dd429cbe59",
"size": "426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "datapackage_pipelines/lib/find_replace.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "721"
},
{
"name": "HTML",
"bytes": "15588"
},
{
"name": "Jupyter Notebook",
"bytes": "27225"
},
{
"name": "Makefile",
"bytes": "2416"
},
{
"name": "Python",
"bytes": "191172"
},
{
"name": "Shell",
"bytes": "9696"
},
{
"name": "Slim",
"bytes": "775"
}
],
"symlink_target": ""
} |
package com.alibaba.rocketmq.client.producer;
import com.alibaba.rocketmq.common.message.Message;
/**
* @author shijia.wxr
*/
public interface LocalTransactionExecuter {
public LocalTransactionState executeLocalTransactionBranch(final Message msg, final Object arg);
}
| {
"content_hash": "54a203049bbc72cee05fd2cf3ebf7e2b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 100,
"avg_line_length": 24.25,
"alnum_prop": 0.7628865979381443,
"repo_name": "lusong1986/RocketMQExt",
"id": "b1f1e039c9ec061249b767968739da14f32f7925",
"size": "1113",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "rocketmq-client/src/main/java/com/alibaba/rocketmq/client/producer/LocalTransactionExecuter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "118"
},
{
"name": "Java",
"bytes": "2778466"
},
{
"name": "Shell",
"bytes": "37927"
}
],
"symlink_target": ""
} |
# Exercice 2 : développement d'un écran de recherche

Le but de cet exercice est de réaliser l'écran de recherche d'un utilisateur
pour cet exercice nous aurons besoin :
* d'un model de critère
* d'un model de resultat
* d'une collection pour la liste des resultats
* d'une vue pour le critère
* d'une vue pour le résultat
* d'un template pour le critere
* d'un template pour le resultat
## 1 création d'une route
* ajouter une route "user" dans le routeur d'utilisateurs
## 2 Création des modèles
* créer l'arborescence suivante:
```javascript
|app
__models
__user
__userRecherche
* userCriteria.js
* userResult.js
* userResultCollection.js
```
* créer les modèles comme dans l'exercice précédent
```javascript
Fmk.Models.Model.extend({
});
// modelName = user.userCriteria et user.userResult
```
* créer la collection de résultats
```javascript
module.exports = Fmk.Models.PaginatedCollection.extend({
/**
* Metadata property of the model.
* @type {String}
*/
modelName: "user.userResult",
/**
* Reference on the single Model.
* @type {[type]}
*/
model: [modèle de ligne de la collection]
});
```
## 3 Création des vues
* créer l'arborescence suivante
```javascript
|app
__views
__user
__userRecherche
* userCriteria.js
* userResults.js
```
* dans le serviceUser, créer le service de recherche
* créer la vue de critère :
```javascript
module.exports = Fmk.Views.SearchView.extend({
/**
* Service call in order to load the data from the given criteria.
* @type {[type]}
*/
search: [service de recherche],
/**
* Template use to display the criteria.
* @type {[type]}
*/
template: [template de critere],
/**
* Collection contenant les résultats.
* @type {Collection}
*/
Results: [collection],
/**
* View used in order to display the Results.
* @type {View}
*/
ResultsView: [vue de résultat],
});
```
* créer la vue de résultats
module.exports = ResultsView.extend({
/**
* Template in order to display all the results.
* @type {function}
*/
template: [template de résultat]
});
## Création des templates
| {
"content_hash": "cfbf53d6e56cabedb0685b97407a975b",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 77,
"avg_line_length": 20.38317757009346,
"alnum_prop": 0.6740027510316369,
"repo_name": "KleeGroup/focus-workshop",
"id": "b947a8406ef56a47efb41243e64fc09690b1dc39",
"size": "2210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ExerciceFormation/02_focus/00_enonce/recherche.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6130"
},
{
"name": "JavaScript",
"bytes": "217027"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="blitz" default="default" basedir=".">
<description>Builds, tests, and runs the project blitz.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="blitz-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project> | {
"content_hash": "7eef82dc841eb2cbbf59ee71febed991",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 86,
"avg_line_length": 58.55,
"alnum_prop": 0.6552803871335041,
"repo_name": "STOzaki/blitzScoring",
"id": "2ef61b037a12d641b2811da607e2226b6cd3d8a0",
"size": "3513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "34379"
}
],
"symlink_target": ""
} |
package sqlstore
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"strings"
"sync"
"time"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/util/keys"
)
// ErrInvalidLength is returned by some database getters if the database returned a byte array with an unexpected length.
// This should be impossible, as the database schema contains CHECK()s for all the relevant columns.
var ErrInvalidLength = errors.New("database returned byte array with illegal length")
// PostgresArrayWrapper is a function to wrap array values before passing them to the sql package.
//
// When using github.com/lib/pq, you should set
// whatsmeow.PostgresArrayWrapper = pq.Array
var PostgresArrayWrapper func(interface{}) interface {
driver.Valuer
sql.Scanner
}
type SQLStore struct {
*Container
JID string
preKeyLock sync.Mutex
contactCache map[types.JID]*types.ContactInfo
contactCacheLock sync.Mutex
}
// NewSQLStore creates a new SQLStore with the given database container and user JID.
// It contains implementations of all the different stores in the store package.
//
// In general, you should use Container.NewDevice or Container.GetDevice instead of this.
func NewSQLStore(c *Container, jid types.JID) *SQLStore {
return &SQLStore{
Container: c,
JID: jid.String(),
contactCache: make(map[types.JID]*types.ContactInfo),
}
}
var _ store.IdentityStore = (*SQLStore)(nil)
var _ store.SessionStore = (*SQLStore)(nil)
var _ store.PreKeyStore = (*SQLStore)(nil)
var _ store.SenderKeyStore = (*SQLStore)(nil)
var _ store.AppStateSyncKeyStore = (*SQLStore)(nil)
var _ store.AppStateStore = (*SQLStore)(nil)
var _ store.ContactStore = (*SQLStore)(nil)
const (
putIdentityQuery = `
INSERT INTO whatsmeow_identity_keys (our_jid, their_id, identity) VALUES ($1, $2, $3)
ON CONFLICT (our_jid, their_id) DO UPDATE SET identity=excluded.identity
`
deleteAllIdentitiesQuery = `DELETE FROM whatsmeow_identity_keys WHERE our_jid=$1 AND their_id LIKE $2`
deleteIdentityQuery = `DELETE FROM whatsmeow_identity_keys WHERE our_jid=$1 AND their_id=$2`
getIdentityQuery = `SELECT identity FROM whatsmeow_identity_keys WHERE our_jid=$1 AND their_id=$2`
)
func (s *SQLStore) PutIdentity(address string, key [32]byte) error {
_, err := s.db.Exec(putIdentityQuery, s.JID, address, key[:])
return err
}
func (s *SQLStore) DeleteAllIdentities(phone string) error {
_, err := s.db.Exec(deleteAllIdentitiesQuery, s.JID, phone+":%")
return err
}
func (s *SQLStore) DeleteIdentity(address string) error {
_, err := s.db.Exec(deleteAllIdentitiesQuery, s.JID, address)
return err
}
func (s *SQLStore) IsTrustedIdentity(address string, key [32]byte) (bool, error) {
var existingIdentity []byte
err := s.db.QueryRow(getIdentityQuery, s.JID, address).Scan(&existingIdentity)
if errors.Is(err, sql.ErrNoRows) {
// Trust if not known, it'll be saved automatically later
return true, nil
} else if err != nil {
return false, err
} else if len(existingIdentity) != 32 {
return false, ErrInvalidLength
}
return *(*[32]byte)(existingIdentity) == key, nil
}
const (
getSessionQuery = `SELECT session FROM whatsmeow_sessions WHERE our_jid=$1 AND their_id=$2`
hasSessionQuery = `SELECT true FROM whatsmeow_sessions WHERE our_jid=$1 AND their_id=$2`
putSessionQuery = `
INSERT INTO whatsmeow_sessions (our_jid, their_id, session) VALUES ($1, $2, $3)
ON CONFLICT (our_jid, their_id) DO UPDATE SET session=excluded.session
`
deleteAllSessionsQuery = `DELETE FROM whatsmeow_sessions WHERE our_jid=$1 AND their_id LIKE $2`
deleteSessionQuery = `DELETE FROM whatsmeow_sessions WHERE our_jid=$1 AND their_id=$2`
)
func (s *SQLStore) GetSession(address string) (session []byte, err error) {
err = s.db.QueryRow(getSessionQuery, s.JID, address).Scan(&session)
if errors.Is(err, sql.ErrNoRows) {
err = nil
}
return
}
func (s *SQLStore) HasSession(address string) (has bool, err error) {
err = s.db.QueryRow(hasSessionQuery, s.JID, address).Scan(&has)
if errors.Is(err, sql.ErrNoRows) {
err = nil
}
return
}
func (s *SQLStore) PutSession(address string, session []byte) error {
_, err := s.db.Exec(putSessionQuery, s.JID, address, session)
return err
}
func (s *SQLStore) DeleteAllSessions(phone string) error {
_, err := s.db.Exec(deleteAllSessionsQuery, s.JID, phone+":%")
return err
}
func (s *SQLStore) DeleteSession(address string) error {
_, err := s.db.Exec(deleteSessionQuery, s.JID, address)
return err
}
const (
getLastPreKeyIDQuery = `SELECT MAX(key_id) FROM whatsmeow_pre_keys WHERE jid=$1`
insertPreKeyQuery = `INSERT INTO whatsmeow_pre_keys (jid, key_id, key, uploaded) VALUES ($1, $2, $3, $4)`
getUnuploadedPreKeysQuery = `SELECT key_id, key FROM whatsmeow_pre_keys WHERE jid=$1 AND uploaded=false ORDER BY key_id LIMIT $2`
getPreKeyQuery = `SELECT key_id, key FROM whatsmeow_pre_keys WHERE jid=$1 AND key_id=$2`
deletePreKeyQuery = `DELETE FROM whatsmeow_pre_keys WHERE jid=$1 AND key_id=$2`
markPreKeysAsUploadedQuery = `UPDATE whatsmeow_pre_keys SET uploaded=true WHERE jid=$1 AND key_id<=$2`
getUploadedPreKeyCountQuery = `SELECT COUNT(*) FROM whatsmeow_pre_keys WHERE jid=$1 AND uploaded=true`
)
func (s *SQLStore) genOnePreKey(id uint32, markUploaded bool) (*keys.PreKey, error) {
key := keys.NewPreKey(id)
_, err := s.db.Exec(insertPreKeyQuery, s.JID, key.KeyID, key.Priv[:], markUploaded)
return key, err
}
func (s *SQLStore) getNextPreKeyID() (uint32, error) {
var lastKeyID sql.NullInt32
err := s.db.QueryRow(getLastPreKeyIDQuery, s.JID).Scan(&lastKeyID)
if err != nil {
return 0, fmt.Errorf("failed to query next prekey ID: %w", err)
}
return uint32(lastKeyID.Int32) + 1, nil
}
func (s *SQLStore) GenOnePreKey() (*keys.PreKey, error) {
s.preKeyLock.Lock()
defer s.preKeyLock.Unlock()
nextKeyID, err := s.getNextPreKeyID()
if err != nil {
return nil, err
}
return s.genOnePreKey(nextKeyID, true)
}
func (s *SQLStore) GetOrGenPreKeys(count uint32) ([]*keys.PreKey, error) {
s.preKeyLock.Lock()
defer s.preKeyLock.Unlock()
res, err := s.db.Query(getUnuploadedPreKeysQuery, s.JID, count)
if err != nil {
return nil, fmt.Errorf("failed to query existing prekeys: %w", err)
}
newKeys := make([]*keys.PreKey, count)
var existingCount uint32
for res.Next() {
var key *keys.PreKey
key, err = scanPreKey(res)
if err != nil {
return nil, err
} else if key != nil {
newKeys[existingCount] = key
existingCount++
}
}
if existingCount < uint32(len(newKeys)) {
var nextKeyID uint32
nextKeyID, err = s.getNextPreKeyID()
if err != nil {
return nil, err
}
for i := existingCount; i < count; i++ {
newKeys[i], err = s.genOnePreKey(nextKeyID, false)
if err != nil {
return nil, fmt.Errorf("failed to generate prekey: %w", err)
}
nextKeyID++
}
}
return newKeys, nil
}
func scanPreKey(row scannable) (*keys.PreKey, error) {
var priv []byte
var id uint32
err := row.Scan(&id, &priv)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
} else if err != nil {
return nil, err
} else if len(priv) != 32 {
return nil, ErrInvalidLength
}
return &keys.PreKey{
KeyPair: *keys.NewKeyPairFromPrivateKey(*(*[32]byte)(priv)),
KeyID: id,
}, nil
}
func (s *SQLStore) GetPreKey(id uint32) (*keys.PreKey, error) {
return scanPreKey(s.db.QueryRow(getPreKeyQuery, s.JID, id))
}
func (s *SQLStore) RemovePreKey(id uint32) error {
_, err := s.db.Exec(deletePreKeyQuery, s.JID, id)
return err
}
func (s *SQLStore) MarkPreKeysAsUploaded(upToID uint32) error {
_, err := s.db.Exec(markPreKeysAsUploadedQuery, s.JID, upToID)
return err
}
func (s *SQLStore) UploadedPreKeyCount() (count int, err error) {
err = s.db.QueryRow(getUploadedPreKeyCountQuery, s.JID).Scan(&count)
return
}
const (
getSenderKeyQuery = `SELECT sender_key FROM whatsmeow_sender_keys WHERE our_jid=$1 AND chat_id=$2 AND sender_id=$3`
putSenderKeyQuery = `
INSERT INTO whatsmeow_sender_keys (our_jid, chat_id, sender_id, sender_key) VALUES ($1, $2, $3, $4)
ON CONFLICT (our_jid, chat_id, sender_id) DO UPDATE SET sender_key=excluded.sender_key
`
)
func (s *SQLStore) PutSenderKey(group, user string, session []byte) error {
_, err := s.db.Exec(putSenderKeyQuery, s.JID, group, user, session)
return err
}
func (s *SQLStore) GetSenderKey(group, user string) (key []byte, err error) {
err = s.db.QueryRow(getSenderKeyQuery, s.JID, group, user).Scan(&key)
if errors.Is(err, sql.ErrNoRows) {
err = nil
}
return
}
const (
putAppStateSyncKeyQuery = `
INSERT INTO whatsmeow_app_state_sync_keys (jid, key_id, key_data, timestamp, fingerprint) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (jid, key_id) DO UPDATE
SET key_data=excluded.key_data, timestamp=excluded.timestamp, fingerprint=excluded.fingerprint
`
getAppStateSyncKeyQuery = `SELECT key_data, timestamp, fingerprint FROM whatsmeow_app_state_sync_keys WHERE jid=$1 AND key_id=$2`
)
func (s *SQLStore) PutAppStateSyncKey(id []byte, key store.AppStateSyncKey) error {
_, err := s.db.Exec(putAppStateSyncKeyQuery, s.JID, id, key.Data, key.Timestamp, key.Fingerprint)
return err
}
func (s *SQLStore) GetAppStateSyncKey(id []byte) (*store.AppStateSyncKey, error) {
var key store.AppStateSyncKey
err := s.db.QueryRow(getAppStateSyncKeyQuery, s.JID, id).Scan(&key.Data, &key.Timestamp, &key.Fingerprint)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return &key, err
}
const (
putAppStateVersionQuery = `
INSERT INTO whatsmeow_app_state_version (jid, name, version, hash) VALUES ($1, $2, $3, $4)
ON CONFLICT (jid, name) DO UPDATE SET version=excluded.version, hash=excluded.hash
`
getAppStateVersionQuery = `SELECT version, hash FROM whatsmeow_app_state_version WHERE jid=$1 AND name=$2`
deleteAppStateVersionQuery = `DELETE FROM whatsmeow_app_state_version WHERE jid=$1 AND name=$2`
putAppStateMutationMACsQuery = `INSERT INTO whatsmeow_app_state_mutation_macs (jid, name, version, index_mac, value_mac) VALUES `
deleteAppStateMutationMACsQueryPostgres = `DELETE FROM whatsmeow_app_state_mutation_macs WHERE jid=$1 AND name=$2 AND index_mac=ANY($3::bytea[])`
deleteAppStateMutationMACsQueryGeneric = `DELETE FROM whatsmeow_app_state_mutation_macs WHERE jid=$1 AND name=$2 AND index_mac IN `
getAppStateMutationMACQuery = `SELECT value_mac FROM whatsmeow_app_state_mutation_macs WHERE jid=$1 AND name=$2 AND index_mac=$3 ORDER BY version DESC LIMIT 1`
)
func (s *SQLStore) PutAppStateVersion(name string, version uint64, hash [128]byte) error {
_, err := s.db.Exec(putAppStateVersionQuery, s.JID, name, version, hash[:])
return err
}
func (s *SQLStore) GetAppStateVersion(name string) (version uint64, hash [128]byte, err error) {
var uncheckedHash []byte
err = s.db.QueryRow(getAppStateVersionQuery, s.JID, name).Scan(&version, &uncheckedHash)
if errors.Is(err, sql.ErrNoRows) {
// version will be 0 and hash will be an empty array, which is the correct initial state
err = nil
} else if err != nil {
// There's an error, just return it
} else if len(uncheckedHash) != 128 {
// This shouldn't happen
err = ErrInvalidLength
} else {
// No errors, convert hash slice to array
hash = *(*[128]byte)(uncheckedHash)
}
return
}
func (s *SQLStore) DeleteAppStateVersion(name string) error {
_, err := s.db.Exec(deleteAppStateVersionQuery, s.JID, name)
return err
}
type execable interface {
Exec(query string, args ...interface{}) (sql.Result, error)
}
func (s *SQLStore) putAppStateMutationMACs(tx execable, name string, version uint64, mutations []store.AppStateMutationMAC) error {
values := make([]interface{}, 3+len(mutations)*2)
queryParts := make([]string, len(mutations))
values[0] = s.JID
values[1] = name
values[2] = version
placeholderSyntax := "($1, $2, $3, $%d, $%d)"
if s.dialect == "sqlite3" {
placeholderSyntax = "(?1, ?2, ?3, ?%d, ?%d)"
}
for i, mutation := range mutations {
baseIndex := 3 + i*2
values[baseIndex] = mutation.IndexMAC
values[baseIndex+1] = mutation.ValueMAC
queryParts[i] = fmt.Sprintf(placeholderSyntax, baseIndex+1, baseIndex+2)
}
_, err := tx.Exec(putAppStateMutationMACsQuery+strings.Join(queryParts, ","), values...)
return err
}
const mutationBatchSize = 400
func (s *SQLStore) PutAppStateMutationMACs(name string, version uint64, mutations []store.AppStateMutationMAC) error {
if len(mutations) > mutationBatchSize {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to start transaction: %w", err)
}
for i := 0; i < len(mutations); i += mutationBatchSize {
var mutationSlice []store.AppStateMutationMAC
if len(mutations) > i+mutationBatchSize {
mutationSlice = mutations[i : i+mutationBatchSize]
} else {
mutationSlice = mutations[i:]
}
err = s.putAppStateMutationMACs(tx, name, version, mutationSlice)
if err != nil {
_ = tx.Rollback()
return err
}
}
err = tx.Commit()
if err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
} else if len(mutations) > 0 {
return s.putAppStateMutationMACs(s.db, name, version, mutations)
}
return nil
}
func (s *SQLStore) DeleteAppStateMutationMACs(name string, indexMACs [][]byte) (err error) {
if len(indexMACs) == 0 {
return
}
if s.dialect == "postgres" && PostgresArrayWrapper != nil {
_, err = s.db.Exec(deleteAppStateMutationMACsQueryPostgres, s.JID, name, PostgresArrayWrapper(indexMACs))
} else {
args := make([]interface{}, 2+len(indexMACs))
args[0] = s.JID
args[1] = name
queryParts := make([]string, len(indexMACs))
for i, item := range indexMACs {
args[2+i] = item
queryParts[i] = fmt.Sprintf("$%d", i+3)
}
_, err = s.db.Exec(deleteAppStateMutationMACsQueryGeneric+"("+strings.Join(queryParts, ",")+")", args...)
}
return
}
func (s *SQLStore) GetAppStateMutationMAC(name string, indexMAC []byte) (valueMAC []byte, err error) {
err = s.db.QueryRow(getAppStateMutationMACQuery, s.JID, name, indexMAC).Scan(&valueMAC)
if errors.Is(err, sql.ErrNoRows) {
err = nil
}
return
}
const (
putContactNameQuery = `
INSERT INTO whatsmeow_contacts (our_jid, their_jid, first_name, full_name) VALUES ($1, $2, $3, $4)
ON CONFLICT (our_jid, their_jid) DO UPDATE SET first_name=excluded.first_name, full_name=excluded.full_name
`
putManyContactNamesQuery = `
INSERT INTO whatsmeow_contacts (our_jid, their_jid, first_name, full_name)
VALUES %s
ON CONFLICT (our_jid, their_jid) DO UPDATE SET first_name=excluded.first_name, full_name=excluded.full_name
`
putPushNameQuery = `
INSERT INTO whatsmeow_contacts (our_jid, their_jid, push_name) VALUES ($1, $2, $3)
ON CONFLICT (our_jid, their_jid) DO UPDATE SET push_name=excluded.push_name
`
putBusinessNameQuery = `
INSERT INTO whatsmeow_contacts (our_jid, their_jid, business_name) VALUES ($1, $2, $3)
ON CONFLICT (our_jid, their_jid) DO UPDATE SET business_name=excluded.business_name
`
getContactQuery = `
SELECT first_name, full_name, push_name, business_name FROM whatsmeow_contacts WHERE our_jid=$1 AND their_jid=$2
`
getAllContactsQuery = `
SELECT their_jid, first_name, full_name, push_name, business_name FROM whatsmeow_contacts WHERE our_jid=$1
`
)
func (s *SQLStore) PutPushName(user types.JID, pushName string) (bool, string, error) {
s.contactCacheLock.Lock()
defer s.contactCacheLock.Unlock()
cached, err := s.getContact(user)
if err != nil {
return false, "", err
}
if cached.PushName != pushName {
_, err = s.db.Exec(putPushNameQuery, s.JID, user, pushName)
if err != nil {
return false, "", err
}
previousName := cached.PushName
cached.PushName = pushName
cached.Found = true
return true, previousName, nil
}
return false, "", nil
}
func (s *SQLStore) PutBusinessName(user types.JID, businessName string) (bool, string, error) {
s.contactCacheLock.Lock()
defer s.contactCacheLock.Unlock()
cached, err := s.getContact(user)
if err != nil {
return false, "", err
}
if cached.BusinessName != businessName {
_, err = s.db.Exec(putBusinessNameQuery, s.JID, user, businessName)
if err != nil {
return false, "", err
}
previousName := cached.BusinessName
cached.BusinessName = businessName
cached.Found = true
return true, previousName, nil
}
return false, "", nil
}
func (s *SQLStore) PutContactName(user types.JID, firstName, fullName string) error {
s.contactCacheLock.Lock()
defer s.contactCacheLock.Unlock()
cached, err := s.getContact(user)
if err != nil {
return err
}
if cached.FirstName != firstName || cached.FullName != fullName {
_, err = s.db.Exec(putContactNameQuery, s.JID, user, firstName, fullName)
if err != nil {
return err
}
cached.FirstName = firstName
cached.FullName = fullName
cached.Found = true
}
return nil
}
const contactBatchSize = 300
func (s *SQLStore) putContactNamesBatch(tx execable, contacts []store.ContactEntry) error {
values := make([]interface{}, 1, 1+len(contacts)*3)
queryParts := make([]string, 0, len(contacts))
values[0] = s.JID
placeholderSyntax := "($1, $%d, $%d, $%d)"
if s.dialect == "sqlite3" {
placeholderSyntax = "(?1, ?%d, ?%d, ?%d)"
}
i := 0
handledContacts := make(map[types.JID]struct{}, len(contacts))
for _, contact := range contacts {
if contact.JID.IsEmpty() {
s.log.Warnf("Empty contact info in mass insert: %+v", contact)
continue
}
// The whole query will break if there are duplicates, so make sure there aren't any duplicates
_, alreadyHandled := handledContacts[contact.JID]
if alreadyHandled {
s.log.Warnf("Duplicate contact info for %s in mass insert", contact.JID)
continue
}
handledContacts[contact.JID] = struct{}{}
baseIndex := i*3 + 1
values = append(values, contact.JID.String(), contact.FirstName, contact.FullName)
queryParts = append(queryParts, fmt.Sprintf(placeholderSyntax, baseIndex+1, baseIndex+2, baseIndex+3))
i++
}
_, err := tx.Exec(fmt.Sprintf(putManyContactNamesQuery, strings.Join(queryParts, ",")), values...)
return err
}
func (s *SQLStore) PutAllContactNames(contacts []store.ContactEntry) error {
if len(contacts) > contactBatchSize {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to start transaction: %w", err)
}
for i := 0; i < len(contacts); i += contactBatchSize {
var contactSlice []store.ContactEntry
if len(contacts) > i+contactBatchSize {
contactSlice = contacts[i : i+contactBatchSize]
} else {
contactSlice = contacts[i:]
}
err = s.putContactNamesBatch(tx, contactSlice)
if err != nil {
_ = tx.Rollback()
return err
}
}
err = tx.Commit()
if err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
} else if len(contacts) > 0 {
err := s.putContactNamesBatch(s.db, contacts)
if err != nil {
return err
}
} else {
return nil
}
s.contactCacheLock.Lock()
// Just clear the cache, fetching pushnames and business names would be too much effort
s.contactCache = make(map[types.JID]*types.ContactInfo)
s.contactCacheLock.Unlock()
return nil
}
func (s *SQLStore) getContact(user types.JID) (*types.ContactInfo, error) {
cached, ok := s.contactCache[user]
if ok {
return cached, nil
}
var first, full, push, business sql.NullString
err := s.db.QueryRow(getContactQuery, s.JID, user).Scan(&first, &full, &push, &business)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, err
}
info := &types.ContactInfo{
Found: err == nil,
FirstName: first.String,
FullName: full.String,
PushName: push.String,
BusinessName: business.String,
}
s.contactCache[user] = info
return info, nil
}
func (s *SQLStore) GetContact(user types.JID) (types.ContactInfo, error) {
s.contactCacheLock.Lock()
info, err := s.getContact(user)
s.contactCacheLock.Unlock()
if err != nil {
return types.ContactInfo{}, err
}
return *info, nil
}
func (s *SQLStore) GetAllContacts() (map[types.JID]types.ContactInfo, error) {
s.contactCacheLock.Lock()
defer s.contactCacheLock.Unlock()
rows, err := s.db.Query(getAllContactsQuery, s.JID)
if err != nil {
return nil, err
}
output := make(map[types.JID]types.ContactInfo, len(s.contactCache))
for rows.Next() {
var jid types.JID
var first, full, push, business sql.NullString
err = rows.Scan(&jid, &first, &full, &push, &business)
if err != nil {
return nil, fmt.Errorf("error scanning row: %w", err)
}
info := types.ContactInfo{
Found: true,
FirstName: first.String,
FullName: full.String,
PushName: push.String,
BusinessName: business.String,
}
output[jid] = info
s.contactCache[jid] = &info
}
return output, nil
}
const (
putChatSettingQuery = `
INSERT INTO whatsmeow_chat_settings (our_jid, chat_jid, %[1]s) VALUES ($1, $2, $3)
ON CONFLICT (our_jid, chat_jid) DO UPDATE SET %[1]s=excluded.%[1]s
`
getChatSettingsQuery = `
SELECT muted_until, pinned, archived FROM whatsmeow_chat_settings WHERE our_jid=$1 AND chat_jid=$2
`
)
func (s *SQLStore) PutMutedUntil(chat types.JID, mutedUntil time.Time) error {
var val int64
if !mutedUntil.IsZero() {
val = mutedUntil.Unix()
}
_, err := s.db.Exec(fmt.Sprintf(putChatSettingQuery, "muted_until"), s.JID, chat, val)
return err
}
func (s *SQLStore) PutPinned(chat types.JID, pinned bool) error {
_, err := s.db.Exec(fmt.Sprintf(putChatSettingQuery, "pinned"), s.JID, chat, pinned)
return err
}
func (s *SQLStore) PutArchived(chat types.JID, archived bool) error {
_, err := s.db.Exec(fmt.Sprintf(putChatSettingQuery, "archived"), s.JID, chat, archived)
return err
}
func (s *SQLStore) GetChatSettings(chat types.JID) (settings types.LocalChatSettings, err error) {
var mutedUntil int64
err = s.db.QueryRow(getChatSettingsQuery, s.JID, chat).Scan(&mutedUntil, &settings.Pinned, &settings.Archived)
if errors.Is(err, sql.ErrNoRows) {
err = nil
} else if err != nil {
return
} else {
settings.Found = true
}
if mutedUntil != 0 {
settings.MutedUntil = time.Unix(mutedUntil, 0)
}
return
}
| {
"content_hash": "c0c95776fac67cb2307b6dc9a8619955",
"timestamp": "",
"source": "github",
"line_count": 682,
"max_line_length": 172,
"avg_line_length": 32.39882697947214,
"alnum_prop": 0.6992668356263577,
"repo_name": "42wim/matterbridge",
"id": "abea5fe24914f1debedd981fbeb7511f489c46cf",
"size": "22435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/go.mau.fi/whatsmeow/store/sqlstore/store.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2029"
},
{
"name": "Go",
"bytes": "456275"
},
{
"name": "Shell",
"bytes": "513"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe 'User visits their profile' do
let(:user) { create(:user) }
before do
sign_in(user)
end
it 'shows correct menu item' do
visit(profile_path)
expect(page).to have_active_navigation('Profile')
end
it 'shows profile info' do
visit(profile_path)
expect(page).to have_content "This information will appear on your profile"
end
context 'when user has groups' do
let(:group) do
create :group do |group|
group.add_owner(user)
end
end
let!(:project) do
create(:project, :repository, namespace: group) do |project|
create(:closed_issue_event, project: project)
project.add_maintainer(user)
end
end
def click_on_profile_picture
find(:css, '.header-user-dropdown-toggle').click
page.within ".header-user" do
click_link "Profile"
end
end
it 'shows user groups', :js do
visit(profile_path)
click_on_profile_picture
page.within ".cover-block" do
expect(page).to have_content user.name
expect(page).to have_content user.username
end
page.within ".content" do
click_link "Groups"
end
page.within "#groups" do
expect(page).to have_content group.name
end
end
end
end
| {
"content_hash": "8d91252d219cd3c987f08011eb7459eb",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 79,
"avg_line_length": 21.225806451612904,
"alnum_prop": 0.6246200607902735,
"repo_name": "stoplightio/gitlabhq",
"id": "1c90a794099dc8d07c5e437a578450b67bf52853",
"size": "1347",
"binary": false,
"copies": "1",
"ref": "refs/heads/stoplight/develop",
"path": "spec/features/profiles/user_visits_profile_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "632980"
},
{
"name": "Clojure",
"bytes": "79"
},
{
"name": "Dockerfile",
"bytes": "1676"
},
{
"name": "HTML",
"bytes": "1264236"
},
{
"name": "JavaScript",
"bytes": "3425347"
},
{
"name": "Ruby",
"bytes": "16497064"
},
{
"name": "Shell",
"bytes": "34509"
},
{
"name": "Vue",
"bytes": "752795"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="CommuBBSMaster">
<resultMap id="boardMasterList" type="egovframework.com.cop.bbs.service.BoardMasterVO">
<result property="bbsId" column="BBS_ID"/>
<result property="bbsTyCode" column="BBS_TY_CODE"/>
<result property="bbsTyCodeNm" column="BBS_TY_CODE_NM"/>
<result property="bbsNm" column="BBS_NM"/>
<result property="tmplatId" column="TMPLAT_ID"/>
<result property="useAt" column="USE_AT"/>
<result property="frstRegisterPnttm" column="FRST_REGIST_PNTTM"/>
</resultMap>
<select id="selectCommuBBSMasterListMain" parameterType="egovframework.com.cop.bbs.service.BoardMasterVO" resultMap="boardMasterList">
SELECT
a.BBS_ID, a.BBS_TY_CODE,
a.BBS_NM
FROM
COMTNBBSMASTER a
WHERE 1=1
AND a.CMMNTY_ID = #{cmmntyId}
AND a.USE_AT = 'Y'
</select>
</mapper> | {
"content_hash": "86917ab4fb89e41acc2585a0d1ec13e1",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 135,
"avg_line_length": 32.63333333333333,
"alnum_prop": 0.693564862104188,
"repo_name": "dasomel/egovframework",
"id": "d3fe6f0699945fab178ac88e927bda2853566ef7",
"size": "979",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "common-component/v3.8.0/src/main/resources/egovframework/mapper/com/cop/cmy/EgovCommuBBSMaster_SQL_altibase.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/**
* Retrieves data from a filePro database
*
* @phpstub
*
* @param int $row_number
* @param int $field_number
*
* @return string Returns the specified data, or false on errors.
*/
function filepro_retrieve($row_number, $field_number)
{
} | {
"content_hash": "0dcc8f6f22a0151e41e49beb04e3e4b7",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 65,
"avg_line_length": 17,
"alnum_prop": 0.6745098039215687,
"repo_name": "schmittjoh/php-stubs",
"id": "265659a26cd503a7f3e79675bdfd5d7dd1ab6f6e",
"size": "255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/php/filepro/functions/filepro-retrieve.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "2203628"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="b97cd9d1-0f33-413d-bd04-60aab72821e7" name="Default" comment="">
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" />
</list>
<ignored path="Startup Weekend.iws" />
<ignored path=".idea/workspace.xml" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
<component name="CreatePatchCommitExecutor">
<option name="PATCH_PATH" value="" />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
<component name="FavoritesManager">
<favorites_list name="Startup Weekend" />
</component>
<component name="FileEditorManager">
<splitter split-orientation="horizontal" split-proportion="0.6025641">
<split-first>
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file leaf-file-name="home.html" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/home.html">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.33278418">
<caret line="208" column="47" selection-start-line="208" selection-start-column="43" selection-end-line="208" selection-end-column="47" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="bootstrap.css" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/css/bootstrap.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3517" column="1" selection-start-line="3517" selection-start-column="1" selection-end-line="3517" selection-end-column="1" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="jquery.onepagenav.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/js/jquery.onepagenav.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="n#!!doc" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file leaf-file-name="typed.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/js/typed.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="typewriter.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/js/typewriter.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="8" column="26" selection-start-line="8" selection-start-column="26" selection-end-line="8" selection-end-column="26" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="wow.min.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/js/wow.min.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="tooltip.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/js/tooltip.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
</file>
<file leaf-file-name="main.js" pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/js/main.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="106" column="53" selection-start-line="106" selection-start-column="53" selection-end-line="106" selection-end-column="53" />
<folding />
</state>
</provider>
</entry>
</file>
</leaf>
</split-first>
<split-second>
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file leaf-file-name="override.css" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/css/override.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.686747">
<caret line="541" column="20" selection-start-line="541" selection-start-column="20" selection-end-line="541" selection-end-column="20" />
<folding />
</state>
</provider>
</entry>
</file>
</leaf>
</split-second>
</splitter>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/../slideout-menu2.svg" />
<option value="$PROJECT_DIR$/../New folder/slideout-menu2.js" />
<option value="$PROJECT_DIR$/js/typed.js" />
<option value="$PROJECT_DIR$/js/typewriter.js" />
<option value="$PROJECT_DIR$/js/wow.min.js" />
<option value="$PROJECT_DIR$/js/main.js" />
<option value="$PROJECT_DIR$/index.html" />
<option value="$PROJECT_DIR$/css/cardio.css" />
<option value="$PROJECT_DIR$/css/override.css" />
<option value="$PROJECT_DIR$/home.html" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" />
<component name="JsBuildToolPackageJson" detection-done="true" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
</component>
<component name="ProjectFrameBounds">
<option name="x" value="448" />
<option name="y" value="29" />
<option name="width" value="1126" />
<option name="height" value="850" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectView">
<navigator currentView="ProjectPane" proportions="" version="1">
<flattenPackages />
<showMembers />
<showModules />
<showLibraryContents />
<hideEmptyPackages />
<abbreviatePackageNames />
<autoscrollToSource />
<autoscrollFromSource />
<sortByType />
<manualOrder />
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="Scratches" />
<pane id="Scope" />
<pane id="ProjectPane">
<subPane>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="Startup Weekend" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="Startup Weekend" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Startup Weekend" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
<PATH>
<PATH_ELEMENT>
<option name="myItemId" value="Startup Weekend" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="Startup Weekend" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
<option name="myItemId" value="js" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
</subPane>
</pane>
</panes>
</component>
<component name="PropertiesComponent">
<property name="last_opened_file_path" value="$PROJECT_DIR$/../New Site" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="HbShouldOpenHtmlAsHb" value="" />
<property name="js-jscs-nodeInterpreter" value="C:\Program Files\nodejs\node.exe" />
<property name="js-jscs-package" value="C:\Users\user\AppData\Roaming\npm\node_modules\jscs" />
<property name="restartRequiresConfirmation" value="false" />
<property name="settings.editor.selected.configurable" value="project.propDebugger" />
<property name="settings.editor.splitter.proportion" value="0.2" />
</component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="C:\Users\user\Desktop\New folder" />
<recent name="C:\Users\user\Desktop" />
</key>
</component>
<component name="RunManager" selected="JavaScript Debug.Unnamed">
<configuration default="true" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application">
<method />
</configuration>
<configuration default="true" type="DartTestRunConfigurationType" factoryName="Dart Test">
<method />
</configuration>
<configuration default="true" type="JavaScriptTestRunnerKarma" factoryName="Karma" config-file="">
<envs />
<method />
</configuration>
<configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug">
<method />
</configuration>
<configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" working-dir="">
<method />
</configuration>
<configuration default="true" type="cucumber.js" factoryName="Cucumber.js">
<option name="cucumberJsArguments" value="" />
<option name="executablePath" />
<option name="filePath" />
<method />
</configuration>
<configuration default="true" type="js.build_tools.gulp" factoryName="Gulp.js">
<node-options />
<gulpfile />
<tasks />
<arguments />
<envs />
<method />
</configuration>
<configuration default="true" type="js.build_tools.npm" factoryName="npm">
<command value="run-script" />
<scripts />
<envs />
<method />
</configuration>
<configuration default="true" type="mocha-javascript-test-runner" factoryName="Mocha">
<node-options />
<working-directory>$PROJECT_DIR$</working-directory>
<pass-parent-env>true</pass-parent-env>
<envs />
<ui>bdd</ui>
<extra-mocha-options />
<test-kind>DIRECTORY</test-kind>
<test-directory />
<recursive>false</recursive>
<method />
</configuration>
<configuration default="false" name="Unnamed" type="JavascriptDebugType" factoryName="JavaScript Debug" uri="http://localhost:63342/Startup Weekend/home.html">
<method />
</configuration>
<list size="1">
<item index="0" class="java.lang.String" itemvalue="JavaScript Debug.Unnamed" />
</list>
</component>
<component name="ShelveChangesManager" show_recycled="false" />
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="b97cd9d1-0f33-413d-bd04-60aab72821e7" name="Default" comment="" />
<created>1453587707106</created>
<option name="number" value="Default" />
<updated>1453587707106</updated>
</task>
<servers />
</component>
<component name="TodoView">
<todo-panel id="selected-file">
<is-autoscroll-to-source value="true" />
</todo-panel>
<todo-panel id="all">
<are-packages-shown value="true" />
<is-autoscroll-to-source value="true" />
</todo-panel>
</component>
<component name="ToolWindowManager">
<frame x="448" y="29" width="1126" height="850" extended-state="0" />
<editor active="true" />
<layout>
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.13970588" sideWeight="0.5" order="1" side_tool="false" content_ui="combo" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3293011" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3158602" sideWeight="0.517744" order="0" side_tool="true" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3293011" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="10" side_tool="false" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.34005377" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="true" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="8" side_tool="false" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3293011" sideWeight="0.49746513" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.14516129" sideWeight="0.48225603" order="6" side_tool="false" content_ui="tabs" />
</layout>
<layout-to-restore>
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3293011" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32985657" sideWeight="0.5" order="0" side_tool="true" content_ui="tabs" />
<window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="8" side_tool="false" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3293011" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
<window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.34005377" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.11596958" sideWeight="0.5" order="1" side_tool="false" content_ui="combo" />
<window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
<window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="true" content_ui="tabs" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.25403225" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
</layout-to-restore>
</component>
<component name="Vcs.Log.UiProperties">
<option name="RECENTLY_FILTERED_USER_GROUPS">
<collection />
</option>
<option name="RECENTLY_FILTERED_BRANCH_GROUPS">
<collection />
</option>
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager />
<watches-manager />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/css/bootstrap.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3517" column="1" selection-start-line="3517" selection-start-column="1" selection-end-line="3517" selection-end-column="1" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/jquery.onepagenav.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="n#!!doc" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/typed.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/typewriter.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="8" column="26" selection-start-line="8" selection-start-column="26" selection-end-line="8" selection-end-column="26" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/wow.min.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/tooltip.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/main.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="106" column="53" selection-start-line="106" selection-start-column="53" selection-end-line="106" selection-end-column="53" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/override.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/tooltip.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/main.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="106" column="53" selection-start-line="106" selection-start-column="53" selection-end-line="106" selection-end-column="53" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/cardio.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1131" column="5" selection-start-line="1131" selection-start-column="5" selection-end-line="1131" selection-end-column="5" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/et-icons.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/override.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/home.html">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="162" column="86" selection-start-line="162" selection-start-column="78" selection-end-line="162" selection-end-column="86" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/bootstrap.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3517" column="1" selection-start-line="3517" selection-start-column="1" selection-end-line="3517" selection-end-column="1" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/jquery.onepagenav.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="n#!!doc" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/typed.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/typewriter.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="8" column="26" selection-start-line="8" selection-start-column="26" selection-end-line="8" selection-end-column="26" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/wow.min.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/tooltip.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/main.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="106" column="53" selection-start-line="106" selection-start-column="53" selection-end-line="106" selection-end-column="53" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/cardio.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1131" column="5" selection-start-line="1131" selection-start-column="5" selection-end-line="1131" selection-end-column="5" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/et-icons.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/override.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/bootstrap.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3517" column="1" selection-start-line="3517" selection-start-column="1" selection-end-line="3517" selection-end-column="1" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/jquery.onepagenav.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="n#!!doc" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/typed.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/typewriter.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="8" column="26" selection-start-line="8" selection-start-column="26" selection-end-line="8" selection-end-column="26" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/wow.min.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/tooltip.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/main.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3" column="19" selection-start-line="3" selection-start-column="19" selection-end-line="3" selection-end-column="19" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/cardio.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="557" column="4" selection-start-line="557" selection-start-column="4" selection-end-line="561" selection-end-column="50" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/override.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/bootstrap.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3512" column="10" selection-start-line="3512" selection-start-column="10" selection-end-line="3512" selection-end-column="10" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/main.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3" column="19" selection-start-line="3" selection-start-column="19" selection-end-line="3" selection-end-column="19" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/cardio.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="557" column="4" selection-start-line="557" selection-start-column="4" selection-end-line="561" selection-end-column="50" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/override.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/img/favicons/manifest.json">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/normalize.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/owl.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/jquery.onepagenav.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding>
<element signature="n#!!doc" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/typed.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/typewriter.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="8" column="26" selection-start-line="8" selection-start-column="26" selection-end-line="8" selection-end-column="26" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/wow.min.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/tooltip.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/js/main.js">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="106" column="53" selection-start-line="106" selection-start-column="53" selection-end-line="106" selection-end-column="53" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/bootstrap.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="3517" column="1" selection-start-line="3517" selection-start-column="1" selection-end-line="3517" selection-end-column="1" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/et-icons.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/cardio.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.0">
<caret line="1131" column="5" selection-start-line="1131" selection-start-column="5" selection-end-line="1131" selection-end-column="5" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/css/override.css">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.686747">
<caret line="541" column="20" selection-start-line="541" selection-start-column="20" selection-end-line="541" selection-end-column="20" />
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/home.html">
<provider selected="true" editor-type-id="text-editor">
<state vertical-scroll-proportion="0.33278418">
<caret line="208" column="47" selection-start-line="208" selection-start-column="43" selection-end-line="208" selection-end-column="47" />
<folding />
</state>
</provider>
</entry>
</component>
</project> | {
"content_hash": "baeede98063873dcaa4ceb3c62d4cda5",
"timestamp": "",
"source": "github",
"line_count": 777,
"max_line_length": 252,
"avg_line_length": 54.25997425997426,
"alnum_prop": 0.622011385199241,
"repo_name": "sesa-uottawa/startup-weekend-website",
"id": "05579a00bc052309190bf8fc99e6a5bd0398ef24",
"size": "42160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "W2016/.idea/workspace.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "771367"
},
{
"name": "HTML",
"bytes": "213482"
},
{
"name": "JavaScript",
"bytes": "63329"
},
{
"name": "PHP",
"bytes": "35"
}
],
"symlink_target": ""
} |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo
{
public class AzureVMConfigInfo
{
public string vmName;
public string imageName;
public VMSizeInfo vmSize;
public AzureVMConfigInfo(string vmName, VMSizeInfo vmSize, string imageName)
{
this.vmName = vmName;
this.vmSize = vmSize;
this.imageName = imageName;
}
}
} | {
"content_hash": "b53f824cdf7374683b877f16f9946cd0",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 97,
"avg_line_length": 41.5,
"alnum_prop": 0.5975903614457831,
"repo_name": "saratrallapalli/azure-sdk-tools",
"id": "1ae679022edaab68b624ac9052009aef0d338a8b",
"size": "1247",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "WindowsAzurePowershell/src/Management.ServiceManagement.Test/FunctionalTests/ConfigDataInfo/AzureVMConfigInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace rentcar.Authorization.Roles
{
public static class StaticRoleNames
{
public static class Host
{
public const string Admin = "Admin";
}
public static class Tenants
{
public const string Admin = "Admin";
}
}
} | {
"content_hash": "c4b18dfa213742e65f418360d9f64068",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 48,
"avg_line_length": 20.066666666666666,
"alnum_prop": 0.5481727574750831,
"repo_name": "xxmgkxx/core-rent-car",
"id": "6d5a4d7f02e9d4f294558301a118ed9c10c2cea0",
"size": "301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/rentcar.Core/Authorization/Roles/StaticRoleNames.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "224535"
},
{
"name": "CSS",
"bytes": "710250"
},
{
"name": "HTML",
"bytes": "26393"
},
{
"name": "JavaScript",
"bytes": "5723624"
},
{
"name": "PowerShell",
"bytes": "468"
}
],
"symlink_target": ""
} |
import datetime
import json
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.forms.formsets import formset_factory
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.datastructures import MultiValueDictKeyError
from django.utils.translation import ugettext as _, ungettext as ngettext
from olympia import amo
from olympia.constants import editors as rvw
from olympia.access import acl
from olympia.addons.models import Addon, Persona
from olympia.amo.decorators import json_view, post_required
from olympia.amo.urlresolvers import reverse
from olympia.amo.utils import paginate
from olympia.devhub.models import ActivityLog
from olympia.editors import forms
from olympia.editors.models import RereviewQueueTheme, ReviewerScore, ThemeLock
from olympia.editors.views import base_context as context
from olympia.search.views import name_only_query
from olympia.zadmin.decorators import admin_required
from .decorators import personas_reviewer_required
QUEUE_PER_PAGE = 100
@personas_reviewer_required
def home(request):
data = context(
reviews_total=ActivityLog.objects.total_reviews(theme=True)[:5],
reviews_monthly=ActivityLog.objects.monthly_reviews(theme=True)[:5],
queue_counts=queue_counts_themes(request)
)
return render(request, 'editors/themes/home.html', data)
def queue_counts_themes(request):
counts = {
'themes': Persona.objects.no_cache()
.filter(addon__status=amo.STATUS_PENDING)
.count(),
}
if acl.action_allowed(request, 'SeniorPersonasTools', 'View'):
counts.update({
'flagged_themes': (Persona.objects.no_cache()
.filter(addon__status=amo.STATUS_REVIEW_PENDING)
.count()),
'rereview_themes': RereviewQueueTheme.objects.count()
})
rv = {}
if isinstance(type, basestring):
return counts[type]
for k, v in counts.items():
if not isinstance(type, list) or k in type:
rv[k] = v
return rv
@personas_reviewer_required
def themes_list(request, flagged=False, rereview=False):
"""Themes queue in list format."""
themes = []
if flagged:
# TODO (ngoke): rename to STATUS_FLAGGED.
themes = Addon.objects.filter(status=amo.STATUS_REVIEW_PENDING,
type=amo.ADDON_PERSONA,
persona__isnull=False)
elif rereview:
themes = [
rqt.theme.addon for rqt in
RereviewQueueTheme.objects.select_related('theme__addon')]
else:
themes = Addon.objects.filter(status=amo.STATUS_PENDING,
type=amo.ADDON_PERSONA,
persona__isnull=False)
search_form = forms.ThemeSearchForm(request.GET)
per_page = request.GET.get('per_page', QUEUE_PER_PAGE)
pager = paginate(request, themes, per_page)
return render(request, 'editors/themes/queue_list.html', context(
**{'addons': pager.object_list,
'flagged': flagged,
'pager': pager,
'rereview': rereview,
'theme_search_form': search_form,
'statuses': dict((k, unicode(v)) for k, v in
amo.STATUS_CHOICES_API.items()),
'tab': ('rereview_themes' if rereview else
'flagged_themes' if flagged else 'pending_themes')}))
def _themes_queue(request, flagged=False, rereview=False):
"""Themes queue in interactive format."""
themes = _get_themes(request, request.user, flagged=flagged,
rereview=rereview)
ThemeReviewFormset = formset_factory(forms.ThemeReviewForm)
formset = ThemeReviewFormset(
initial=[{'theme': _rereview_to_theme(rereview, theme).id} for theme
in themes])
return render(request, 'editors/themes/queue.html', context(
**{'actions': get_actions_json(),
'formset': formset,
'flagged': flagged,
'reject_reasons': rvw.THEME_REJECT_REASONS,
'rereview': rereview,
'reviewable': True,
'theme_formsets': zip(themes, formset),
'theme_count': len(themes),
'tab': (
'flagged' if flagged else
'rereview' if rereview else 'pending')}))
def _get_themes(request, reviewer, flagged=False, rereview=False):
"""Check out themes.
:param flagged: Flagged themes (amo.STATUS_REVIEW_PENDING)
:param rereview: Re-uploaded themes (RereviewQueueTheme)
"""
num = 0
themes = []
locks = []
status = (amo.STATUS_REVIEW_PENDING if flagged else
amo.STATUS_PUBLIC if rereview else amo.STATUS_PENDING)
if rereview:
# Rereview themes.
num, themes, locks = _get_rereview_themes(reviewer)
else:
# Pending and flagged themes.
locks = ThemeLock.objects.no_cache().filter(
reviewer=reviewer, theme__addon__status=status)
num, themes = _calc_num_themes_checkout(locks)
if themes:
return themes
themes = Persona.objects.no_cache().filter(
addon__status=status, themelock=None)
# Don't allow self-reviews.
if (not settings.ALLOW_SELF_REVIEWS and
not acl.action_allowed(request, 'Admin', '%')):
if rereview:
themes = themes.exclude(theme__addon__addonuser__user=reviewer)
else:
themes = themes.exclude(addon__addonuser__user=reviewer)
# Check out themes by setting lock.
themes = list(themes)[:num]
expiry = get_updated_expiry()
for theme in themes:
ThemeLock.objects.create(theme=_rereview_to_theme(rereview, theme),
reviewer=reviewer, expiry=expiry)
# Empty pool? Go look for some expired locks.
if not themes:
expired_locks = ThemeLock.objects.filter(
expiry__lte=datetime.datetime.now(),
theme__addon__status=status)[:rvw.THEME_INITIAL_LOCKS]
# Steal expired locks.
for lock in expired_locks:
lock.reviewer = reviewer
lock.expiry = expiry
lock.save()
if expired_locks:
locks = expired_locks
if rereview:
return (RereviewQueueTheme.objects.no_cache()
.filter(theme__themelock__reviewer=reviewer)
.exclude(theme__addon__status=amo.STATUS_REJECTED))
# New theme locks may have been created, grab all reviewer's themes again.
return [lock.theme for lock in locks]
@json_view
@personas_reviewer_required
def themes_search(request):
search_form = forms.ThemeSearchForm(request.GET)
if search_form.is_valid():
q = search_form.cleaned_data['q']
rereview = search_form.cleaned_data['queue_type'] == 'rereview'
flagged = search_form.cleaned_data['queue_type'] == 'flagged'
# ES query on name.
themes = Addon.search().filter(type=amo.ADDON_PERSONA)
if rereview:
themes = themes.filter(has_theme_rereview=True)
else:
themes = themes.filter(status=(amo.STATUS_REVIEW_PENDING if flagged
else amo.STATUS_PENDING),
has_theme_rereview=False)
themes = themes.query(or_=name_only_query(q))[:100]
now = datetime.datetime.now()
reviewers = []
for theme in themes:
try:
themelock = theme.persona.themelock
if themelock.expiry > now:
reviewers.append(themelock.reviewer.email)
else:
reviewers.append('')
except ObjectDoesNotExist:
reviewers.append('')
themes = list(themes.values_dict('name', 'slug', 'status'))
for theme, reviewer in zip(themes, reviewers):
# Collapse single value fields from a list.
theme['id'] = theme['id'][0]
theme['slug'] = theme['slug'][0]
theme['status'] = theme['status'][0]
# Dehydrate.
theme['reviewer'] = reviewer
return {'objects': themes, 'meta': {'total_count': len(themes)}}
@personas_reviewer_required
def themes_queue(request):
# By default, redirect back to the queue after a commit.
request.session['theme_redirect_url'] = reverse(
'editors.themes.queue_themes')
return _themes_queue(request)
@admin_required(theme_reviewers=True)
def themes_queue_flagged(request):
# By default, redirect back to the queue after a commit.
request.session['theme_redirect_url'] = reverse(
'editors.themes.queue_flagged')
return _themes_queue(request, flagged=True)
@admin_required(theme_reviewers=True)
def themes_queue_rereview(request):
# By default, redirect back to the queue after a commit.
request.session['theme_redirect_url'] = reverse(
'editors.themes.queue_rereview')
return _themes_queue(request, rereview=True)
def _rereview_to_theme(rereview, theme):
"""
Follows foreign key of RereviewQueueTheme object to theme if in rereview
queue.
"""
if rereview:
return theme.theme
return theme
def _calc_num_themes_checkout(locks):
"""
Calculate number of themes to check out based on how many themes user
currently has checked out.
"""
current_num = locks.count()
if current_num < rvw.THEME_INITIAL_LOCKS:
# Check out themes from the pool if none or not enough checked out.
return rvw.THEME_INITIAL_LOCKS - current_num, []
else:
# Update the expiry on currently checked-out themes.
locks.update(expiry=get_updated_expiry())
return 0, [lock.theme for lock in locks]
def _get_rereview_themes(reviewer):
"""Check out re-uploaded themes."""
locks = (ThemeLock.objects.select_related().no_cache()
.filter(reviewer=reviewer,
theme__rereviewqueuetheme__isnull=False)
.exclude(theme__addon__status=amo.STATUS_REJECTED))
num, updated_locks = _calc_num_themes_checkout(locks)
if updated_locks:
locks = updated_locks
themes = (RereviewQueueTheme.objects.no_cache()
.filter(theme__addon__isnull=False, theme__themelock=None)
.exclude(theme__addon__status=amo.STATUS_REJECTED))
return num, themes, locks
@post_required
@personas_reviewer_required
def themes_commit(request):
ThemeReviewFormset = formset_factory(forms.ThemeReviewForm)
formset = ThemeReviewFormset(request.POST)
scores = []
for form in formset:
try:
lock = ThemeLock.objects.filter(
theme_id=form.data[form.prefix + '-theme'],
reviewer=request.user)
except MultiValueDictKeyError:
# Address off-by-one error caused by management form.
continue
if lock and form.is_valid():
scores.append(form.save())
# Success message.
points = sum(scores)
success = ngettext(
# L10n: {0} is the number of reviews. {1} is the points just earned.
# L10n: {2} is the total number of points the reviewer has overall.
'{0} theme review successfully processed (+{1} points, {2} total).',
'{0} theme reviews successfully processed (+{1} points, {2} total).',
len(scores)).format(len(scores), points,
ReviewerScore.get_total(request.user))
amo.messages.success(request, success)
if 'theme_redirect_url' in request.session:
return redirect(request.session['theme_redirect_url'])
else:
return redirect(reverse('editors.themes.queue_themes'))
@personas_reviewer_required
def release_locks(request):
ThemeLock.objects.filter(reviewer=request.user).delete()
amo.messages.success(
request,
_('Your theme locks have successfully been released. '
'Other reviewers may now review those released themes. '
'You may have to refresh the page to see the changes reflected in '
'the table below.'))
return redirect(reverse('editors.themes.list'))
@personas_reviewer_required
def themes_single(request, slug):
"""
Like a detail page, manually review a single theme if it is pending
and isn't locked.
"""
reviewer = request.user
reviewable = True
# Don't review an already reviewed theme.
theme = get_object_or_404(Persona, addon__slug=slug)
if (theme.addon.status != amo.STATUS_PENDING and
not theme.rereviewqueuetheme_set.all()):
reviewable = False
if (not settings.ALLOW_SELF_REVIEWS and
not acl.action_allowed(request, 'Admin', '%') and
theme.addon.has_author(request.user)):
reviewable = False
else:
# Don't review a locked theme (that's not locked to self).
try:
lock = theme.themelock
if (lock.reviewer.id != reviewer.id and
lock.expiry > datetime.datetime.now()):
reviewable = False
elif (lock.reviewer.id != reviewer.id and
lock.expiry < datetime.datetime.now()):
# Steal expired lock.
lock.reviewer = reviewer
lock.expiry = get_updated_expiry()
lock.save()
else:
# Update expiry.
lock.expiry = get_updated_expiry()
lock.save()
except ThemeLock.DoesNotExist:
# Create lock if not created.
ThemeLock.objects.create(theme=theme, reviewer=reviewer,
expiry=get_updated_expiry())
ThemeReviewFormset = formset_factory(forms.ThemeReviewForm)
formset = ThemeReviewFormset(initial=[{'theme': theme.id}])
# Since we started the review on the single page, we want to return to the
# single page rather than get shot back to the queue.
request.session['theme_redirect_url'] = reverse('editors.themes.single',
args=[theme.addon.slug])
rereview = (theme.rereviewqueuetheme_set.all()[0] if
theme.rereviewqueuetheme_set.exists() else None)
return render(request, 'editors/themes/single.html', context(
**{'formset': formset,
'theme': rereview if rereview else theme,
'theme_formsets': zip([rereview if rereview else theme], formset),
'theme_reviews': paginate(request, ActivityLog.objects.filter(
action=amo.LOG.THEME_REVIEW.id,
_arguments__contains=theme.addon.id)),
'actions': get_actions_json(),
'theme_count': 1,
'rereview': rereview,
'reviewable': reviewable,
'reject_reasons': rvw.THEME_REJECT_REASONS,
'action_dict': rvw.REVIEW_ACTIONS,
'tab': ('flagged' if theme.addon.status == amo.STATUS_REVIEW_PENDING
else 'rereview' if rereview else 'pending')}))
@personas_reviewer_required
def themes_logs(request):
data = request.GET.copy()
if not data.get('start') and not data.get('end'):
today = datetime.date.today()
data['start'] = datetime.date(today.year, today.month, 1)
form = forms.ReviewAppLogForm(data)
theme_logs = ActivityLog.objects.filter(action=amo.LOG.THEME_REVIEW.id)
if form.is_valid():
data = form.cleaned_data
if data.get('start'):
theme_logs = theme_logs.filter(created__gte=data['start'])
if data.get('end'):
theme_logs = theme_logs.filter(created__lte=data['end'])
if data.get('search'):
term = data['search']
theme_logs = theme_logs.filter(
Q(_details__icontains=term) |
Q(user__display_name__icontains=term) |
Q(user__username__icontains=term)).distinct()
pager = paginate(request, theme_logs, 30)
data = context(form=form, pager=pager,
ACTION_DICT=rvw.REVIEW_ACTIONS,
REJECT_REASONS=rvw.THEME_REJECT_REASONS, tab='themes')
return render(request, 'editors/themes/logs.html', data)
@admin_required(theme_reviewers=True)
def deleted_themes(request):
data = request.GET.copy()
deleted = Addon.unfiltered.filter(type=amo.ADDON_PERSONA,
status=amo.STATUS_DELETED)
if not data.get('start') and not data.get('end'):
today = datetime.date.today()
data['start'] = datetime.date(today.year, today.month, 1)
form = forms.DeletedThemeLogForm(data)
if form.is_valid():
data = form.cleaned_data
if data.get('start'):
deleted = deleted.filter(modified__gte=data['start'])
if data.get('end'):
deleted = deleted.filter(modified__lte=data['end'])
if data.get('search'):
term = data['search']
deleted = deleted.filter(
Q(name__localized_string__icontains=term))
return render(request, 'editors/themes/deleted.html', {
'form': form,
'pager': paginate(request, deleted.order_by('-modified'), 30),
'tab': 'deleted'
})
@personas_reviewer_required
def themes_history(request, username):
if not username:
username = request.user.username
return render(request, 'editors/themes/history.html', context(
**{'theme_reviews':
paginate(request, ActivityLog.objects.filter(
action=amo.LOG.THEME_REVIEW.id, user__username=username), 20),
'user_history': True,
'username': username,
'reject_reasons': rvw.THEME_REJECT_REASONS,
'action_dict': rvw.REVIEW_ACTIONS}))
def get_actions_json():
return json.dumps({
'moreinfo': rvw.ACTION_MOREINFO,
'flag': rvw.ACTION_FLAG,
'duplicate': rvw.ACTION_DUPLICATE,
'reject': rvw.ACTION_REJECT,
'approve': rvw.ACTION_APPROVE,
})
def get_updated_expiry():
return (datetime.datetime.now() +
datetime.timedelta(minutes=rvw.THEME_LOCK_EXPIRY))
| {
"content_hash": "62f75cc4370379f7260e4b0a709cf945",
"timestamp": "",
"source": "github",
"line_count": 504,
"max_line_length": 79,
"avg_line_length": 36.36309523809524,
"alnum_prop": 0.613084520106946,
"repo_name": "andymckay/addons-server",
"id": "82c56211c2fece1430266ca5e229d49d03b0a591",
"size": "18327",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/olympia/editors/views_themes.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "249"
},
{
"name": "CSS",
"bytes": "846032"
},
{
"name": "HTML",
"bytes": "1589366"
},
{
"name": "JavaScript",
"bytes": "1316196"
},
{
"name": "Makefile",
"bytes": "4442"
},
{
"name": "PLSQL",
"bytes": "74"
},
{
"name": "Python",
"bytes": "4128481"
},
{
"name": "Shell",
"bytes": "9112"
},
{
"name": "Smarty",
"bytes": "1930"
}
],
"symlink_target": ""
} |
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>
#include <err.h>
#include <math.h>
#include <errno.h>
#include <X11/X.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xproto.h>
#include <X11/extensions/Xinerama.h>
// GDK
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gdk-pixbuf-xlib/gdk-pixbuf-xlib.h>
// CLI: argument parsing
static int find_arg( const int argc, char * const argv[], const char * const key )
{
int i;
for ( i = 0; i < argc && strcasecmp( argv[i], key ); i++ );
return i < argc ? i: -1;
}
static void find_arg_str( int argc, char *argv[], char *key, char** val )
{
int i = find_arg( argc, argv, key );
if ( val != NULL && i > 0 && i < argc-1 ) {
*val = argv[i+1];
}
}
// Monitor layout stuff.
typedef struct {
double x,y;
double w,h;
} MMB_Rectangle;
typedef struct {
// Size of the total screen area.
MMB_Rectangle base;
// Number of monitors.
int num_monitors;
// List of monitors;
MMB_Rectangle *monitors;
} MMB_Screen;
/**
* @param display An X11 Display
*
* Create MMB_Screen that holds the monitor layout of display.
*
* @returns filled in MMB_Screen
*/
static MMB_Screen *mmb_screen_create( Display *display )
{
// Create empty structure.
MMB_Screen *retv = malloc( sizeof( *retv ) );
memset( retv, 0, sizeof( *retv ) );
Screen *screen = DefaultScreenOfDisplay( display );
retv->base.w = WidthOfScreen( screen );
retv->base.h = HeightOfScreen( screen );
// Parse xinerama setup.
if ( XineramaIsActive( display ) ) {
XineramaScreenInfo *info = XineramaQueryScreens( display, &( retv->num_monitors ) );
if ( info != NULL ) {
retv->monitors = malloc( retv->num_monitors*sizeof( MMB_Rectangle ) );
for ( int i = 0; i < retv->num_monitors; i++ ) {
retv->monitors[i].x = info[i].x_org;
retv->monitors[i].y = info[i].y_org;
retv->monitors[i].w = info[i].width;
retv->monitors[i].h = info[i].height;
}
XFree( info );
}
}
if ( retv->monitors == NULL ) {
retv->num_monitors = 1;
retv->monitors = malloc( 1*sizeof( MMB_Rectangle ) );
retv->monitors[0] = retv->base;
}
return retv;
}
/**
* @param screen a Pointer to the MMB_Screen pointer to free.
*
* Free MMB_Screen object and set pointer to NULL.
*/
static void mmb_screen_free( MMB_Screen **screen )
{
if ( screen == NULL || *screen == NULL ) return;
if ( ( *screen )->monitors != NULL ) free( ( *screen )->monitors );
free( *screen );
screen = NULL;
}
static void mmb_screen_print( const MMB_Screen *screen )
{
printf( "Total size: %.0f %.0f\n", screen->base.w, screen->base.h );
printf( "Num. monitors: %d\n", screen->num_monitors );
for ( int i =0; i < screen->num_monitors; i++ ) {
printf( "\t%2d: %.0f %.0f -> %.0f %.0f\n",
i,
screen->monitors[i].x,
screen->monitors[i].y,
screen->monitors[i].w,
screen->monitors[i].h
);
}
}
static void renderer_init( Display *display )
{
// Init gdk for this display.
gdk_pixbuf_xlib_init( display, DefaultScreen( display ) );
}
static GdkPixbuf * renderer_create_empty_background( MMB_Screen *screen )
{
GdkPixbuf *pb = gdk_pixbuf_new( GDK_COLORSPACE_RGB, TRUE, 8, screen->base.w, screen->base.h );
if ( pb == NULL ) {
fprintf( stderr, "Failed to create background pixmap\n" );
exit( EXIT_FAILURE );
}
// Make the wallpaper black.
gdk_pixbuf_fill( pb, 0x000000FF );
return pb;
}
static int renderer_overlay_wallpaper( GdkPixbuf *background,
const char *wallpaper,
MMB_Screen *screen,
int clip )
{
GError *error = NULL;
GdkPixbuf *image = gdk_pixbuf_new_from_file( wallpaper, &error );
if ( error != NULL ) {
fprintf( stderr, "Failed to parse image: %s\n" , error->message );
return 0;
}
double wp_width = gdk_pixbuf_get_width( image );
double wp_height = gdk_pixbuf_get_height( image );
for ( int monitor = 0; monitor < screen->num_monitors; monitor++ ) {
MMB_Rectangle rectangle = screen->monitors[monitor];
double w_scale = wp_width/( double )( rectangle.w );
double h_scale = wp_height/( double )( rectangle.h );
// Picture is small then screen, center it.
if ( w_scale < 1 && h_scale < 1 ) {
gdk_pixbuf_copy_area( image, 0,0,
wp_width, wp_height,
background,
rectangle.x + ( rectangle.w-wp_width )/2,
rectangle.y + ( rectangle.h-wp_height )/2
);
}
// Picture is smaller on one of the sides and we want to clip.
else if ( clip && ( w_scale < 1 || h_scale < 1 ) ) {
double x_off = ( ( float )rectangle.w-wp_width )/2.0;
double y_off = ( ( float )rectangle.h-wp_height )/2.0;
gdk_pixbuf_copy_area( image,
-( x_off < 0 )*x_off,-( y_off < 0 )*y_off,
wp_width+( x_off < 0 )*2*x_off,
wp_height+( y_off < 0 )*2*y_off,
background,
rectangle.x + ( ( x_off> 0 )?x_off:0 ),
rectangle.y + ( ( y_off> 0 )?y_off:0 ) );
}
// Picture is bigger/equal then screen.
// Scale to fit.
else {
int new_w= 0;
int new_h = 0;
double x_off = 0;
double y_off = 0;
if ( clip ) {
if ( w_scale < h_scale ) {
new_w = wp_width/w_scale;
new_h = wp_height/w_scale;
} else {
new_w = wp_width/h_scale;
new_h = wp_height/h_scale;
}
x_off = ( ( new_w-rectangle.w )/2.0 );
y_off = ( ( new_h-rectangle.h )/2.0 );
} else {
if ( w_scale > h_scale ) {
new_w = wp_width/w_scale;
new_h = wp_height/w_scale;
} else {
new_w = wp_width/h_scale;
new_h = wp_height/h_scale;
}
}
GdkPixbuf *scaled_wp = gdk_pixbuf_scale_simple( image, new_w, new_h, GDK_INTERP_HYPER );
gdk_pixbuf_copy_area(
scaled_wp,
( int )ceil( x_off ),( int )ceil( y_off ),
new_w-ceil(x_off)*2,
new_h-ceil(y_off)*2,
background,
rectangle.x + ( ( double )rectangle.w-new_w+x_off*2 )/2,
rectangle.y + ( ( double )rectangle.h-new_h+y_off*2 )/2 );
g_object_unref( scaled_wp );
}
}
g_object_unref( image );
return 1;
}
static void renderer_store_image( GdkPixbuf *bg, const char *output )
{
gdk_pixbuf_save( bg, output, "png", NULL, NULL );
}
static void renderer_update_X11_background( Display *display, GdkPixbuf *image )
{
Atom prop_root, prop_esetroot, type;
Window root;
Pixmap pmap_d1, pmap_d1_mask;
int format;
root = RootWindow( display, DefaultScreen( display ) );
// Create the Pixmap and the transparency map (we do not use)
gdk_pixbuf_xlib_render_pixmap_and_mask( image,
&pmap_d1,
&pmap_d1_mask,
0 );
// Free the mask
XFreePixmap( display, pmap_d1_mask );
// Not sure about this one, copied from FEH.
prop_root = XInternAtom( display, "_XROOTPMAP_ID", True );
prop_esetroot = XInternAtom( display, "ESETROOT_PMAP_ID", True );
// If properties exist, kill the client that set this data.
// and free it resources.
if ( prop_root != None && prop_esetroot != None ) {
unsigned long length,after;
unsigned char *data_root, *data_esetroot;
XGetWindowProperty( display, root, prop_root, 0L, 1L,
False, AnyPropertyType, &type, &format, &length, &after, &data_root );
if ( type == XA_PIXMAP ) {
XGetWindowProperty( display, root,
prop_esetroot, 0L, 1L,
False, AnyPropertyType,
&type, &format, &length, &after, &data_esetroot );
if ( data_root && data_esetroot ) {
if ( type == XA_PIXMAP && *( ( Pixmap * ) data_root ) == *( ( Pixmap * ) data_esetroot ) ) {
XKillClient( display, *( ( Pixmap * )
data_root ) );
XSync( display, False );
}
}
if ( data_esetroot ) XFree( ( void * )data_esetroot );
}
if ( data_root ) XFree( ( void * )data_root );
}
/* This will locate the property, creating it if it doesn't exist */
prop_root = XInternAtom( display, "_XROOTPMAP_ID", False );
prop_esetroot = XInternAtom( display, "ESETROOT_PMAP_ID", False );
if ( prop_root == None || prop_esetroot == None ) {
fprintf( stderr, "creation of pixmap property failed." );
return;
}
// Store the pmap_d1 in the X server.
XChangeProperty( display, root, prop_root, XA_PIXMAP, 32,
PropModeReplace, ( unsigned char * ) &pmap_d1, 1 );
XChangeProperty( display, root, prop_esetroot, XA_PIXMAP, 32,
PropModeReplace, ( unsigned char * ) &pmap_d1, 1 );
// Set it
XSetWindowBackgroundPixmap( display, root, pmap_d1 );
XClearWindow( display, root );
XSync( display, True );
// Make sure X keeps the data we set.
XSetCloseDownMode( display, RetainPermanent );
}
// X error handler
static int ( *xerror )( Display *, XErrorEvent * );
int X11_oops( Display *display, XErrorEvent *ee )
{
if ( ee->error_code == BadWindow
|| ( ee->request_code == X_GrabButton && ee->error_code == BadAccess )
|| ( ee->request_code == X_GrabKey && ee->error_code == BadAccess )
) return 0;
fprintf( stderr, "error: request code=%d, error code=%d\n", ee->request_code, ee->error_code );
return xerror( display, ee );
}
static void help()
{
int code = execlp( "man","man", MANPAGE_PATH,NULL );
if ( code == -1 ) {
fprintf( stderr, "Failed to execute man: %s\n", strerror( errno ) );
}
}
int main ( int argc, char **argv )
{
g_type_init();
Display *display;
// catch help request
if ( find_arg( argc, argv, "-help" ) >= 0
|| find_arg( argc, argv, "--help" ) >= 0
|| find_arg( argc, argv, "-h" ) >= 0 ) {
help();
return EXIT_SUCCESS;
}
// Get DISPLAY
const char *display_str= getenv( "DISPLAY" );
if ( !( display = XOpenDisplay( display_str ) ) ) {
fprintf( stderr, "cannot open display!\n" );
return EXIT_FAILURE;
}
// Setup error handler.
XSync( display, False );
xerror = XSetErrorHandler( X11_oops );
XSync( display, False );
// Initialize renderer
renderer_init( display );
// Get monitor layout. (xinerama aware)
MMB_Screen *mmb_screen = mmb_screen_create( display );
// Check input file.
char *image_file = NULL;
find_arg_str( argc, argv, "-input", &image_file );
if ( image_file ) {
int clip = ( find_arg( argc, argv, "-clip" ) >= 0 );
GdkPixbuf *pb = renderer_create_empty_background( mmb_screen );
if ( renderer_overlay_wallpaper( pb, image_file, mmb_screen,clip ) ) {
char *output_file = NULL;
find_arg_str( argc, argv, "-output", &output_file );
if ( output_file ) {
renderer_store_image( pb, output_file );
} else {
renderer_update_X11_background( display, pb );
}
}
g_object_unref( pb );
}
// Print layout
if ( find_arg( argc, argv, "-print" ) >= 0 ) {
mmb_screen_print( mmb_screen );
}
// Cleanup
mmb_screen_free( &mmb_screen );
XCloseDisplay( display );
}
| {
"content_hash": "57a77199e681e03cad8b98b2a31484ec",
"timestamp": "",
"source": "github",
"line_count": 420,
"max_line_length": 108,
"avg_line_length": 30.15714285714286,
"alnum_prop": 0.5166587715142902,
"repo_name": "DaveDavenport/MultiMonitorBackground",
"id": "1391ffec2d604161381b48befcb181a3d88790c0",
"size": "13857",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/mmb.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "13857"
}
],
"symlink_target": ""
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TraceListenerForTest.cs" company="CloudLibrary">
// Copyright (c) CloudLibrary 2016. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CloudLibrary.Shared.CommonUnitTestHelper
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Common.Diagnostics;
/// <summary>
/// Trace listener for test
/// </summary>
/// <remarks>
/// To use the listener, need to add following in app.config in test project
/// <![CDATA[
/// <configuration>
/// ...
/// <system.diagnostics>
/// <trace autoflush = "false" indentsize="4">
/// <listeners>
/// <add name="TraceForTest"
/// type="CloudLibrary.Shared.CommonUnitTestHelper.TraceListenerForTest, CloudLibrary.Shared.CommonUnitTestHelper"
/// initializeData="" />
/// </listeners>
/// ...
/// </trace>
/// </system.diagnostics>
/// ...
/// </configuration>
/// /// ]]>
/// </remarks>
/// <history>
/// <create time="2016/5/16" author="lixinxu" />
/// </history>
[ExcludeFromCodeCoverage]
public class TraceListenerForTest : TraceListener
{
/// <summary>
/// Trace message storage
/// </summary>
/// <remarks>
/// This class is used for unit test so we can get the trace information.
/// </remarks>
private static readonly IList<string> MessageStore = new List<string>();
/// <summary>
/// Initializes a new instance of the <see cref="TraceListenerForTest" /> class.
/// </summary>
public TraceListenerForTest() : base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TraceListenerForTest" /> class.
/// </summary>
/// <param name="name">listener name</param>
public TraceListenerForTest(string name) : base(name)
{
}
/// <summary>
/// Clear message
/// </summary>
public static void ClearMessage()
{
lock (MessageStore)
{
MessageStore.Clear();
}
}
/// <summary>
/// Copy messages for validation
/// </summary>
/// <returns>messages from message store</returns>
public static IReadOnlyList<string> CopyMessges()
{
List<string> copy;
lock (MessageStore)
{
copy = new List<string>(MessageStore);
}
return copy;
}
/// <summary>
/// Write trace message
/// </summary>
/// <param name="message">message to write</param>
/// <remarks>
/// If the message does not contain trace prefix, the message will be ignore. The reason is that we want to trace the
/// message from our system only.
/// </remarks>
public override void Write(string message)
{
if ((message != null) && message.StartsWith(TraceLogger.TracePrefix, StringComparison.Ordinal))
{
lock (MessageStore)
{
MessageStore.Add(message);
}
}
}
/// <summary>
/// Write message with new line
/// </summary>
/// <param name="message">message to write</param>
public override void WriteLine(string message)
{
this.Write(message + Environment.NewLine);
}
}
}
| {
"content_hash": "b3485506899bfe32b70497cba4da079a",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 139,
"avg_line_length": 32.675,
"alnum_prop": 0.4881407804131599,
"repo_name": "lixinxu/CloudLibiary",
"id": "e76d7901b2f5e18f085d6077190015851e5292f6",
"size": "3923",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DotNet/Shared/CommonUnitTestHelper/TraceListenerForTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "172463"
}
],
"symlink_target": ""
} |
package org.exbin.bined;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Interface for code area caret.
*
* @version 0.2.0 2019/07/07
* @author ExBin Project (https://exbin.org)
*/
public interface CodeAreaCaret {
/**
* Returns caret position.
*
* Returned value should not be cast for editing.
*
* @return caret position
*/
@Nonnull
CodeAreaCaretPosition getCaretPosition();
/**
* Returns currently active section.
*
* @return section
*/
@Nonnull
CodeAreaSection getSection();
/**
* Sets current caret position to provided value.
*
* @param caretPosition caret position
*/
void setCaretPosition(@Nullable CodeAreaCaretPosition caretPosition);
/**
* Sets current caret position to given position preserving section.
*
* @param dataPosition data position
* @param codeOffset code offset
*/
void setCaretPosition(long dataPosition, int codeOffset);
/**
* Sets current caret position to given position resetting offset and
* preserving section.
*
* @param dataPosition data position
*/
void setCaretPosition(long dataPosition);
}
| {
"content_hash": "3958dff25c1e6a2de692ca766811ee7e",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 73,
"avg_line_length": 22.418181818181818,
"alnum_prop": 0.6520681265206812,
"repo_name": "exbin/deltahex-java",
"id": "fe27ad57970f7539b79583afe8578367863a9893",
"size": "1828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/bined-core/src/main/java/org/exbin/bined/CodeAreaCaret.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "969634"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d632142c4dc2c9952b4cd9c9ed537a6b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "1abacebbd57615399276b25e8c3caff39479e747",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Hypericaceae/Hypericum/Hypericum assamicum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "falcon.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| {
"content_hash": "ea58c08ea553bc437573c6434550dd8e",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 70,
"avg_line_length": 25.22222222222222,
"alnum_prop": 0.7092511013215859,
"repo_name": "prathik/falcon-web",
"id": "89a3c5895260011ad6740bd075ae1d509857d11a",
"size": "249",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "falcon/manage.py",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
FOUNDATION_EXPORT double Pods_ChatBotVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_ChatBotVersionString[];
| {
"content_hash": "c49a5777a349f83aa27776fc5f06213c",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 66,
"avg_line_length": 40,
"alnum_prop": 0.8583333333333333,
"repo_name": "johnamcruz/chatbot",
"id": "063cc6461cd1cfe59488fefb6c6d95656fc51f3e",
"size": "316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pods/Target Support Files/Pods-ChatBot/Pods-ChatBot-umbrella.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "301"
},
{
"name": "Swift",
"bytes": "12016"
}
],
"symlink_target": ""
} |
package nsq
import (
"context"
"errors"
"github.com/nsqio/go-nsq"
"github.com/tsaikd/KDGoLib/version"
"github.com/tsaikd/gogstash/config"
"github.com/tsaikd/gogstash/config/goglog"
"github.com/tsaikd/gogstash/config/logevent"
"github.com/tsaikd/gogstash/config/queue"
)
// ModuleName is the name used in config file
const ModuleName = "nsq"
// OutputConfig holds the configuration json fields and internal objects
type OutputConfig struct {
config.OutputConfig
NSQ string `json:"nsq" yaml:"nsq"` // NSQd to connect to
Topic string `json:"topic" yaml:"topic"` // topic to publish to
InFlight uint `json:"max_inflight" yaml:"max_inflight"` // max number of messages inflight
producer *nsq.Producer
ctx context.Context
msg chan []byte // channel to push message from codec to
queue queue.Queue // our queue for backpressure handling
}
// DefaultOutputConfig returns an OutputConfig struct with default values
func DefaultOutputConfig() OutputConfig {
return OutputConfig{
OutputConfig: config.OutputConfig{
CommonConfig: config.CommonConfig{
Type: ModuleName,
},
},
InFlight: 150,
msg: make(chan []byte),
}
}
// InitHandler initialize the output plugin
func InitHandler(
ctx context.Context,
raw config.ConfigRaw,
control config.Control,
) (config.TypeOutputConfig, error) {
conf := DefaultOutputConfig()
err := config.ReflectConfig(raw, &conf)
if err != nil {
return nil, err
}
if len(conf.NSQ) == 0 {
return nil, errors.New("Missing NSQ server")
}
if len(conf.Topic) == 0 {
return nil, errors.New("Missing topic")
}
conf.Codec, err = config.GetCodecOrDefault(ctx, raw["codec"])
if err != nil {
return nil, err
}
conf.ctx = ctx
cfg := nsq.NewConfig()
cfg.MaxInFlight = int(conf.InFlight)
cfg.UserAgent = "gogstash/" + version.VERSION
conf.producer, err = nsq.NewProducer(conf.NSQ, cfg)
if err != nil {
return nil, err
}
conf.queue = queue.NewSimpleQueue(ctx, control, &conf, conf.msg, 10, 30) // last values are queue size and retry interval in seconds
go conf.nsqbackgroundtask()
return conf.queue, nil
}
// nsqbackgroundtask runs in the background and handles messages and termination
func (t *OutputConfig) nsqbackgroundtask() {
for {
select {
case <-t.ctx.Done():
goglog.Logger.Debug("outputnsq: stopping")
t.producer.Stop()
goglog.Logger.Debug("outputnsq: stopped")
close(t.msg)
return
case msg := <-t.msg:
err := t.producer.Publish(t.Topic, msg)
if err != nil {
err = t.queue.Queue(t.ctx, msg)
if err != nil {
goglog.Logger.Errorf("outputnsq: %s", err.Error())
}
} else {
_ = t.queue.Resume(t.ctx)
}
}
}
}
// Output event
func (t *OutputConfig) OutputEvent(ctx context.Context, event logevent.LogEvent) (err error) {
_, err = t.Codec.Encode(ctx, event, t.msg)
return
}
| {
"content_hash": "a991932c5390f360be60661af00660b3",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 133,
"avg_line_length": 26.321100917431192,
"alnum_prop": 0.6890902753572673,
"repo_name": "tsaikd/gogstash",
"id": "34cf67d4d3bedd29fdae82a275b330b40ce856b9",
"size": "2869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "output/nsq/outputnsq.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1609"
},
{
"name": "Go",
"bytes": "485307"
},
{
"name": "Shell",
"bytes": "364"
}
],
"symlink_target": ""
} |
<?php
namespace Tests\XmlSoccer;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PeterColes\XmlSoccer\ApiClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Exception\RequestException;
final class JsonConversionTest extends TestCase
{
public function testCanConvertLeagues()
{
$mock = new MockHandler([ new Response(200, [], $this->getData('all-leagues')) ]);
$handler = HandlerStack::create($mock);
$guzzleClient = new Client([ 'handler' => $handler ]);
$client = new ApiClient('MADE_UP_API_KEY', true, $guzzleClient);
$response = $client->GetAllLeagues()->json();
$this->assertIsJson($response);
$response = json_decode($response);
$this->assertObjectHasAttribute('League', $response);
$this->assertEquals(3, count($response->League));
$this->assertEquals('English Premier League', $response->League[0]->Name);
$this->assertEquals('Scotland', $response->League[2]->Country);
$this->assertEquals('Blah.', $response->AccountInformation);
}
public function testCanConvertMatches()
{
$mock = new MockHandler([ new Response(200, [], $this->getData('live-scores')) ]);
$handler = HandlerStack::create($mock);
$guzzleClient = new Client([ 'handler' => $handler ]);
$client = new ApiClient('MADE_UP_API_KEY', true, $guzzleClient);
$response = $client->GetLiveScore()->json();
$this->assertIsJson($response);
$homeGoals = [
(object) [ 'Minute' => 50, 'Player' => 'Riccardo Orsolini', 'Own' => false ],
(object) [ 'Minute' => 38, 'Player' => 'Andrea Favilli', 'Own' => false ],
(object) [ 'Minute' => 4, 'Player' => 'A N Other', 'Own' => true ],
];
$homeYellowCards = [
(object) [ 'Minute' => 55, 'Player' => 'Andrea Mengoni' ],
(object) [ 'Minute' => 36, 'Player' => 'Blazey Augustyn' ],
(object) [ 'Minute' => 34, 'Player' => 'Gian Filippo Felicioli' ],
];
$awaySubstitutions = [
(object) [ 'Minute' => 46, 'Type' => 'Out', 'Player' => 'Simone Emmanuello' ],
(object) [ 'Minute' => 46, 'Type' => 'In', 'Player' => 'Armando Vajushi' ],
];
$response = json_decode($response);
$this->assertObjectHasAttribute('Match', $response);
$this->assertEquals(2, count($response->Match));
$this->assertEquals('Serie B', $response->Match[0]->League);
$this->assertEquals([ 'Bright Addae', 'Francesco Cassata', 'Luigi Giorgi' ], $response->Match[0]->HomeLineupMidfield);
$this->assertEquals("57'", $response->Match[0]->Time);
$this->assertEquals('Not started', $response->Match[1]->Time);
$this->assertEquals(3, $response->Match[0]->HomeGoals);
$this->assertEquals($homeGoals, $response->Match[0]->HomeGoalDetails);
$this->assertEquals($homeYellowCards, $response->Match[0]->HomeTeamYellowCardDetails);
$this->assertEquals([], $response->Match[0]->AwayTeamYellowCardDetails);
$this->assertEquals([], $response->Match[0]->HomeSubDetails);
$this->assertEquals($awaySubstitutions, $response->Match[0]->AwaySubDetails);
}
public function testCanConvertOdds()
{
$mock = new MockHandler([ new Response(200, [], $this->getData('odds')) ]);
$handler = HandlerStack::create($mock);
$guzzleClient = new Client([ 'handler' => $handler ]);
$client = new ApiClient('MADE_UP_API_KEY', true, $guzzleClient);
$response = $client->GetOddsByFixture()->json();
$this->assertIsJson($response);
$response = json_decode($response);
$this->assertObjectHasAttribute('Odds', $response);
$this->assertEquals(4, count($response->Odds));
$this->assertEquals(12.75, $response->Odds[1]->_10Bet_Home_Away);
$this->assertObjectHasAttribute('WilliamHill_Away', $response->Odds[1]);
$this->assertObjectNotHasAttribute('WilliamHill_Away', $response->Odds[2]);
}
}
| {
"content_hash": "403e855c2fcf0a738d8d27163c215066",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 126,
"avg_line_length": 42.79381443298969,
"alnum_prop": 0.6099735003613587,
"repo_name": "petercoles/xml-soccer",
"id": "89ee7ac7e7b70cac221989da295cfd15b3d8aa14",
"size": "4151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/JsonConversionTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "28223"
}
],
"symlink_target": ""
} |
import chalk from 'chalk';
import gradient from 'gradient-string';
const log = console.log;
let currentAnimation = null;
const consoleFunctions = {
log: log.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console)
};
// eslint-disable-next-line guard-for-in
for (const k in consoleFunctions) {
console[k] = function () {
stopLastAnimation();
consoleFunctions[k].apply(console, arguments);
};
}
const glitchChars = 'x*0987654321[]0-~@#(____!!!!\\|?????....0000\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t';
const longHsv = {interpolation: 'hsv', hsvSpin: 'long'};
const effects = {
rainbow(str, frame) {
const hue = 5 * frame;
const leftColor = {h: hue % 360, s: 1, v: 1};
const rightColor = {h: (hue + 1) % 360, s: 1, v: 1};
return gradient(leftColor, rightColor)(str, longHsv);
},
pulse(str, frame) {
frame = (frame % 120) + 1;
const transition = 6;
const duration = 10;
const on = '#ff1010';
const off = '#e6e6e6';
if (frame >= (2 * transition) + duration) {
return chalk.hex(off)(str); // All white
}
if (frame >= transition && frame <= transition + duration) {
return chalk.hex(on)(str); // All red
}
frame = frame >= transition + duration ? (2 * transition) + duration - frame : frame; // Revert animation
const g = frame <= transition / 2 ?
gradient([
{color: off, pos: 0.5 - (frame / transition)},
{color: on, pos: 0.5},
{color: off, pos: 0.5 + (frame / transition)}
]) :
gradient([
{color: off, pos: 0},
{color: on, pos: 1 - (frame / transition)},
{color: on, pos: frame / transition},
{color: off, pos: 1}
]);
return g(str);
},
glitch(str, frame) {
if ((frame % 2) + (frame % 3) + (frame % 11) + (frame % 29) + (frame % 37) > 52) {
return str.replace(/[^\r\n]/g, ' ');
}
const chunkSize = Math.max(3, Math.round(str.length * 0.02));
const chunks = [];
for (let i = 0, length = str.length; i < length; i++) {
const skip = Math.round(Math.max(0, (Math.random() - 0.8) * chunkSize));
chunks.push(str.substring(i, i + skip).replace(/[^\r\n]/g, ' '));
i += skip;
if (str[i]) {
if (str[i] !== '\n' && str[i] !== '\r' && Math.random() > 0.995) {
chunks.push(glitchChars[Math.floor(Math.random() * glitchChars.length)]);
} else if (Math.random() > 0.005) {
chunks.push(str[i]);
}
}
}
let result = chunks.join('');
if (Math.random() > 0.99) {
result = result.toUpperCase();
} else if (Math.random() < 0.01) {
result = result.toLowerCase();
}
return result;
},
radar(str, frame) {
const depth = Math.floor(Math.min(str.length, str.length * 0.2));
const step = Math.floor(255 / depth);
const globalPos = frame % (str.length + depth);
const chars = [];
for (let i = 0, length = str.length; i < length; i++) {
const pos = -(i - globalPos);
if (pos > 0 && pos <= depth - 1) {
const shade = (depth - pos) * step;
chars.push(chalk.rgb(shade, shade, shade)(str[i]));
} else {
chars.push(' ');
}
}
return chars.join('');
},
neon(str, frame) {
const color = (frame % 2 === 0) ? chalk.dim.rgb(88, 80, 85) : chalk.bold.rgb(213, 70, 242);
return color(str);
},
karaoke(str, frame) {
const chars = (frame % (str.length + 20)) - 10;
if (chars < 0) {
return chalk.white(str);
}
return chalk.rgb(255, 187, 0).bold(str.substr(0, chars)) + chalk.white(str.substr(chars));
}
};
function animateString(str, effect, delay, speed) {
stopLastAnimation();
speed = speed === undefined ? 1 : parseFloat(speed);
if (!speed || speed <= 0) {
throw new Error('Expected `speed` to be an number greater than 0');
}
currentAnimation = {
text: str.split(/\r\n|\r|\n/),
lines: str.split(/\r\n|\r|\n/).length,
stopped: false,
init: false,
f: 0,
render() {
const self = this;
if (!this.init) {
log('\n'.repeat(this.lines - 1));
this.init = true;
}
log(this.frame());
setTimeout(() => {
if (!self.stopped) {
self.render();
}
}, delay / speed);
},
frame() {
this.f++;
return '\u001B[' + this.lines + 'F\u001B[G\u001B[2K' + this.text.map(str => effect(str, this.f)).join('\n');
},
replace(str) {
this.text = str.split(/\r\n|\r|\n/);
this.lines = str.split(/\r\n|\r|\n/).length;
return this;
},
stop() {
this.stopped = true;
return this;
},
start() {
this.stopped = false;
this.render();
return this;
}
};
setTimeout(() => {
if (!currentAnimation.stopped) {
currentAnimation.start();
}
}, delay / speed);
return currentAnimation;
}
function stopLastAnimation() {
if (currentAnimation) {
currentAnimation.stop();
}
}
const chalkAnimation = {
rainbow: (str, speed) => animateString(str, effects.rainbow, 15, speed),
pulse: (str, speed) => animateString(str, effects.pulse, 16, speed),
glitch: (str, speed) => animateString(str, effects.glitch, 55, speed),
radar: (str, speed) => animateString(str, effects.radar, 50, speed),
neon: (str, speed) => animateString(str, effects.neon, 500, speed),
karaoke: (str, speed) => animateString(str, effects.karaoke, 50, speed)
};
export default chalkAnimation;
| {
"content_hash": "cf3e3c1a75aaa9858ef851cd56dd950c",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 111,
"avg_line_length": 26.670103092783506,
"alnum_prop": 0.5910320834943951,
"repo_name": "bokub/chalk-animation",
"id": "b2414005498e92bc42ce7c0618d927a78994f0f3",
"size": "5174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "8552"
},
{
"name": "Shell",
"bytes": "55"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- == PROJECT COORDINATES ============================================= -->
<groupId>de.monticore.mchammercoder.example</groupId>
<artifactId>Fuzzing</artifactId>
<version>0.1</version>
<name>Fuzzing</name>
<properties>
<!-- .. Plugins ....................................................... -->
<assembly.plugin>2.5.4</assembly.plugin>
<compiler.plugin>3.3</compiler.plugin>
<!-- .. Misc .......................................................... -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<antlr.version>4.5</antlr.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- MontiCore Dependencies -->
<dependency>
<groupId>de.monticore</groupId>
<artifactId>monticore-runtime</artifactId>
<version>4.5.0.1</version>
</dependency>
<dependency>
<groupId>de.monticore</groupId>
<artifactId>monticore-generator</artifactId>
<version>4.5.0.1</version>
</dependency>
<dependency>
<groupId>com.upstandinghackers.hammer</groupId>
<artifactId>hammer</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4</artifactId>
<version>${antlr.version}</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>${antlr.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.monticore.mchammercoder.lang</groupId>
<artifactId>dns-simple-lang</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.plugin}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>de.monticore.mchammercoder.examples.Fuzzing</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "24a235709dd71acb69e8d5eda2888496",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 204,
"avg_line_length": 29.5188679245283,
"alnum_prop": 0.5816554809843401,
"repo_name": "McHammerCoder/McHammerCoder",
"id": "7577eb3b5a7c04ec248b203284c85293af71a349",
"size": "3129",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/Fuzzing/pom.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "157"
},
{
"name": "Groovy",
"bytes": "27341"
},
{
"name": "Shell",
"bytes": "574"
}
],
"symlink_target": ""
} |
<div class="os-modal os-error-modal">
<div class="os-modal-header">
<span class="fa fa-exclamation-circle"></span>
<span translate="common.error"></span>
</div>
<div class="os-modal-body">
<div ng-if="errCtx.fixedMsg">
<div translate="{{errCtx.fixedMsg}}" translate-values="errCtx.input"></div>
</div>
<div ng-if="errCtx.apiMsg">
<div ng-repeat="msg in errCtx.apiMsg">
<div>{{msg}}</div>
<div class="os-divider" ng-if="!$last"></div>
</div>
</div>
</div>
<div class="os-modal-footer">
<button class="btn os-btn-secondary" ng-click="cancel()">
<span translate="common.buttons.dismiss">Dismiss</span>
</button>
<button class="btn btn-primary" ng-click="copyToClipboard()">
<span translate="common.buttons.copy_to_clipboard">Copy to Clipboard</span>
</button>
</div>
</div>
| {
"content_hash": "e5429245ea420899fa1c83acb9a22d3d",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 81,
"avg_line_length": 34.76,
"alnum_prop": 0.6144994246260069,
"repo_name": "krishagni/openspecimen",
"id": "215fa02d1f5e89d1a1d89c90e8695e42925a0366",
"size": "869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/app/modules/common/show-error-messages.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "106704"
},
{
"name": "HTML",
"bytes": "1089677"
},
{
"name": "Java",
"bytes": "5324932"
},
{
"name": "JavaScript",
"bytes": "2990486"
},
{
"name": "PLSQL",
"bytes": "5253"
},
{
"name": "Roff",
"bytes": "3349"
},
{
"name": "Vue",
"bytes": "661942"
}
],
"symlink_target": ""
} |
<?php
namespace NF\Roles;
use Illuminate\Support\ServiceProvider;
class LumenRolesServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->registerBladeExtensions();
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__ . '/../../config/roles.php', 'roles');
}
/**
* Register Blade extensions.
*
* @return void
*/
protected function registerBladeExtensions()
{
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->directive('role', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->is{$expression}): ?>";
});
$blade->directive('endrole', function () {
return "<?php endif; ?>";
});
$blade->directive('permission', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->can{$expression}): ?>";
});
$blade->directive('endpermission', function () {
return "<?php endif; ?>";
});
$blade->directive('level', function ($expression) {
$level = trim($expression, '()');
return "<?php if (Auth::check() && Auth::user()->level() >= {$level}): ?>";
});
$blade->directive('endlevel', function () {
return "<?php endif; ?>";
});
$blade->directive('allowed', function ($expression) {
return "<?php if (Auth::check() && Auth::user()->allowed{$expression}): ?>";
});
$blade->directive('endallowed', function () {
return "<?php endif; ?>";
});
}
}
| {
"content_hash": "5517f49326763f48c92a0bfe1aa1ee1b",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 90,
"avg_line_length": 25.583333333333332,
"alnum_prop": 0.511943539630836,
"repo_name": "codersvn/roles",
"id": "e896a1803ec8d729a66a1918d0da88ae6ca1412e",
"size": "1842",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/NF/Roles/LumenRolesServiceProvider.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "33654"
}
],
"symlink_target": ""
} |
"use strict";
const _ = require("lodash");
const should = require("should");
const mockrequire = require("mock-require");
const KuzzleMock = require("../../mocks/kuzzle.mock");
describe("Backend", () => {
let application;
let Backend;
beforeEach(() => {
mockrequire("../../../lib/kuzzle", KuzzleMock);
({ Backend } = mockrequire.reRequire("../../../lib/core/backend/backend"));
application = new Backend("black-mesa");
});
afterEach(() => {
mockrequire.stopAll();
});
describe("BackendVault#key", () => {
it("should sets the vault key", () => {
application.vault.key = "unforeseen-consequences";
should(application._vaultKey).be.eql("unforeseen-consequences");
});
it("should throw an error if the application is already started", () => {
application.started = true;
should(() => {
application.vault.key = "unforeseen-consequences";
}).throwError({ id: "plugin.runtime.already_started" });
});
});
describe("BackendVault#file", () => {
it("should sets the vault file", () => {
application.vault.file = "xen.bmp";
should(application._secretsFile).be.eql("xen.bmp");
});
it("should throw an error if the application is already started", () => {
application.started = true;
should(() => {
application.vault.file = "xen.bmp";
}).throwError({ id: "plugin.runtime.already_started" });
});
});
describe("BackendVault.secrets", () => {
it("should exposes Kuzzle vault secrets when application is started", () => {
application.started = true;
_.set(application, "_kuzzle.vault.secrets", { beware: "vortigaunt" });
should(application.vault.secrets).be.eql({ beware: "vortigaunt" });
});
});
});
| {
"content_hash": "624ae71139fe00b5e3929b79683e22e4",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 81,
"avg_line_length": 27.323076923076922,
"alnum_prop": 0.6007882882882883,
"repo_name": "kuzzleio/kuzzle",
"id": "eb9e5074f1509df23b528b419644de5b54b54635",
"size": "1776",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/core/backend/BackendVault.test.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "6056"
},
{
"name": "Gherkin",
"bytes": "224013"
},
{
"name": "JavaScript",
"bytes": "2825543"
},
{
"name": "Ruby",
"bytes": "4058"
},
{
"name": "Shell",
"bytes": "12645"
},
{
"name": "TypeScript",
"bytes": "455364"
}
],
"symlink_target": ""
} |
"""
.. _tut-configure-mne:
Configuring MNE-Python
======================
This tutorial covers how to configure MNE-Python to suit your local system and
your analysis preferences.
We begin by importing the necessary Python modules:
"""
import os
import mne
###############################################################################
# .. _config-get-set:
#
# Getting and setting configuration variables
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Configuration variables are read and written using the functions
# :func:`mne.get_config` and :func:`mne.set_config`. To read a specific
# configuration variable, pass its name to :func:`~mne.get_config` as the
# ``key`` parameter (``key`` is the first parameter so you can pass it unnamed
# if you want):
print(mne.get_config('MNE_USE_CUDA'))
print(type(mne.get_config('MNE_USE_CUDA')))
###############################################################################
# Note that the string values read from the JSON file are not parsed in any
# way, so :func:`~mne.get_config` returns a string even for true/false config
# values, rather than a Python :ref:`boolean <bltin-boolean-values>`.
# Similarly, :func:`~mne.set_config` will only set string values (or ``None``
# values, to unset a variable):
try:
mne.set_config('MNE_USE_CUDA', True)
except TypeError as err:
print(err)
###############################################################################
# If you're unsure whether a config variable has been set, there is a
# convenient way to check it and provide a fallback in case it doesn't exist:
# :func:`~mne.get_config` has a ``default`` parameter.
print(mne.get_config('missing_config_key', default='fallback value'))
###############################################################################
# There are also two convenience modes of :func:`~mne.get_config`. The first
# will return a :class:`dict` containing all config variables (and their
# values) that have been set on your system; this is done by passing
# ``key=None`` (which is the default, so it can be omitted):
print(mne.get_config()) # same as mne.get_config(key=None)
###############################################################################
# The second convenience mode will return a :class:`tuple` of all the keys that
# MNE-Python recognizes and uses, regardless of whether they've been set on
# your system. This is done by passing an empty string ``''`` as the ``key``:
print(mne.get_config(key=''))
###############################################################################
# It is possible to add config variables that are not part of the recognized
# list, by passing any arbitrary key to :func:`~mne.set_config`. This will
# yield a warning, however, which is a nice check in cases where you meant to
# set a valid key but simply misspelled it:
mne.set_config('MNEE_USE_CUUDAA', 'false')
###############################################################################
# Let's delete that config variable we just created. To unset a config
# variable, use :func:`~mne.set_config` with ``value=None``. Since we're still
# dealing with an unrecognized key (as far as MNE-Python is concerned) we'll
# still get a warning, but the key will be unset:
mne.set_config('MNEE_USE_CUUDAA', None)
assert 'MNEE_USE_CUUDAA' not in mne.get_config('')
###############################################################################
# Where configurations are stored
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# MNE-Python stores configuration variables in a `JSON`_ file. By default, this
# file is located in :file:`{%USERPROFILE%}\\.mne\\mne-python.json` on Windows
# and :file:`{$HOME}/.mne/mne-python.json` on Linux or macOS. You can get the
# full path to the config file with :func:`mne.get_config_path`.
print(mne.get_config_path())
###############################################################################
# However it is not a good idea to directly edit files in the :file:`.mne`
# directory; use the getting and setting functions described in :ref:`the
# previous section <config-get-set>`.
#
# If for some reason you want to load the configuration from a different
# location, you can pass the ``home_dir`` parameter to
# :func:`~mne.get_config_path`, specifying the parent directory of the
# :file:`.mne` directory where the configuration file you wish to load is
# stored.
#
#
# Using environment variables
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# For compatibility with :doc:`MNE-C <../../install/mne_c>`, MNE-Python
# also reads and writes `environment variables`_ to specify configuration. This
# is done with the same functions that read and write the JSON configuration,
# and is controlled with the parameters ``use_env`` and ``set_env``. By
# default, :func:`~mne.get_config` will check :data:`os.environ` before
# checking the MNE-Python JSON file; to check *only* the JSON file use
# ``use_env=False``. To demonstrate, here's an environment variable that is not
# specific to MNE-Python (and thus is not in the JSON config file):
# make sure it's not in the JSON file (no error means our assertion held):
assert mne.get_config('PATH', use_env=False) is None
# but it *is* in the environment:
print(mne.get_config('PATH'))
###############################################################################
# Also by default, :func:`~mne.set_config` will set values in both the JSON
# file and in :data:`os.environ`; to set a config variable *only* in the JSON
# file use ``set_env=False``. Here we'll use :func:`print` statement to confirm
# that an environment variable is being created and deleted (we could have used
# the Python :ref:`assert statement <assert>` instead, but it doesn't print any
# output when it succeeds so it's a little less obvious):
mne.set_config('foo', 'bar', set_env=False)
print('foo' in os.environ.keys())
mne.set_config('foo', 'bar')
print('foo' in os.environ.keys())
mne.set_config('foo', None) # unsetting a key deletes var from environment
print('foo' in os.environ.keys())
###############################################################################
# .. _tut_logging:
#
# Logging
# ^^^^^^^
#
# One important configuration variable is ``MNE_LOGGING_LEVEL``. Throughout the
# module, messages are generated describing the actions MNE-Python is taking
# behind-the-scenes. How you set ``MNE_LOGGING_LEVEL`` determines how many of
# those messages you see. The default logging level on a fresh install of
# MNE-Python is ``info``:
print(mne.get_config('MNE_LOGGING_LEVEL'))
###############################################################################
# The logging levels that can be set as config variables are ``debug``,
# ``info``, ``warning``, ``error``, and ``critical``. Around 90% of the log
# messages in MNE-Python are ``info`` messages, so for most users the choice is
# between ``info`` (tell me what is happening) and ``warning`` (tell me only if
# something worrisome happens). The ``debug`` logging level is intended for
# MNE-Python developers.
#
#
# In :ref:`an earlier section <config-get-set>` we saw how
# :func:`mne.set_config` is used to change the logging level for the current
# Python session and all future sessions. To change the logging level only for
# the current Python session, you can use :func:`mne.set_log_level` instead.
# The :func:`~mne.set_log_level` function takes the same five string options
# that are used for the ``MNE_LOGGING_LEVEL`` config variable; additionally, it
# can accept :class:`int` or :class:`bool` values that are equivalent to those
# strings. The equivalencies are given in this table:
#
# .. _table-log-levels:
#
# +----------+---------+---------+
# | String | Integer | Boolean |
# +==========+=========+=========+
# | DEBUG | 10 | |
# +----------+---------+---------+
# | INFO | 20 | True |
# +----------+---------+---------+
# | WARNING | 30 | False |
# +----------+---------+---------+
# | ERROR | 40 | |
# +----------+---------+---------+
# | CRITICAL | 50 | |
# +----------+---------+---------+
#
# With many MNE-Python functions it is possible to change the logging level
# temporarily for just that function call, by using the ``verbose`` parameter.
# To illustrate this, we'll load some sample data with different logging levels
# set. First, with log level ``warning``:
kit_data_path = os.path.join(os.path.abspath(os.path.dirname(mne.__file__)),
'io', 'kit', 'tests', 'data', 'test.sqd')
raw = mne.io.read_raw_kit(kit_data_path, verbose='warning')
###############################################################################
# No messages were generated, because none of the messages were of severity
# "warning" or worse. Next, we'll load the same file with log level ``info``
# (the default level):
raw = mne.io.read_raw_kit(kit_data_path, verbose='info')
###############################################################################
# This time, we got a few messages about extracting information from the file,
# converting that information into the MNE-Python :class:`~mne.Info` format,
# etc. Finally, if we request ``debug``-level information, we get even more
# detail:
raw = mne.io.read_raw_kit(kit_data_path, verbose='debug')
###############################################################################
# We've been passing string values to the ``verbose`` parameter, but we can see
# from :ref:`the table above <table-log-levels>` that ``verbose=True`` will
# give us the ``info`` messages and ``verbose=False`` will suppress them; this
# is a useful shorthand to use in scripts, so you don't have to remember the
# specific names of the different logging levels. One final note:
# ``verbose=None`` (which is the default for functions that have a ``verbose``
# parameter) will fall back on whatever logging level was most recently set by
# :func:`mne.set_log_level`, or if that hasn't been called during the current
# Python session, it will fall back to the value of
# ``mne.get_config('MNE_LOGGING_LEVEL')``.
#
#
# .. LINKS
#
# .. _json: https://en.wikipedia.org/wiki/JSON
# .. _`environment variables`: https://wikipedia.org/wiki/Environment_variable
| {
"content_hash": "2b61467e2c808802fe89631bf03345b8",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 79,
"avg_line_length": 45.0353982300885,
"alnum_prop": 0.6023776773432894,
"repo_name": "rkmaddox/mne-python",
"id": "89096f46684f932e1d10aa319fd0be4a31c7718f",
"size": "10202",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tutorials/intro/50_configure_mne.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "3114"
},
{
"name": "PowerShell",
"bytes": "2988"
},
{
"name": "Python",
"bytes": "4400215"
},
{
"name": "Shell",
"bytes": "936"
}
],
"symlink_target": ""
} |
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
exports.DB = 'mongodb://localhost/test1';
exports.connect = (callback) => {
if (mongoose.connection.readyState === 0) {
mongoose.connect(exports.DB, callback);
}
};
exports.close = (callback) => {
mongoose.connection.close(callback);
};
exports.getConnection = () => mongoose.connection;
| {
"content_hash": "475e80b4d828768cfaa3b28338925fec",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 50,
"avg_line_length": 23.4375,
"alnum_prop": 0.6933333333333334,
"repo_name": "ShareDataO/ShareData-BackEnd",
"id": "fccba74b4dd5793be08fa4b53f91c546f83acf17",
"size": "375",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/IntegrationTest/test-config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "50586"
}
],
"symlink_target": ""
} |
layout: post
date: 2017-10-12
title: "Antonio Riva CS_232 Sleeveless Floor-Length Sheath/Column"
category: Antonio Riva
tags: [Antonio Riva,Sheath/Column,Sweetheart,Floor-Length,Sleeveless]
---
### Antonio Riva CS_232
Just **$319.99**
### Sleeveless Floor-Length Sheath/Column
<table><tr><td>BRANDS</td><td>Antonio Riva</td></tr><tr><td>Silhouette</td><td>Sheath/Column</td></tr><tr><td>Neckline</td><td>Sweetheart</td></tr><tr><td>Hemline/Train</td><td>Floor-Length</td></tr><tr><td>Sleeve</td><td>Sleeveless</td></tr></table>
<a href="https://www.readybrides.com/en/antonio-riva/6004-antonio-riva-cs232.html"><img src="//img.readybrides.com/13061/antonio-riva-cs232.jpg" alt="Antonio Riva CS_232" style="width:100%;" /></a>
<!-- break -->
Buy it: [https://www.readybrides.com/en/antonio-riva/6004-antonio-riva-cs232.html](https://www.readybrides.com/en/antonio-riva/6004-antonio-riva-cs232.html)
| {
"content_hash": "89bb96fba1c51d1cf763c23278b0a298",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 250,
"avg_line_length": 64.42857142857143,
"alnum_prop": 0.7195121951219512,
"repo_name": "HOLEIN/HOLEIN.github.io",
"id": "febac8d3398715c69d1e2fc4a723013b5d1ecca9",
"size": "906",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2017-10-12-Antonio-Riva-CS232-Sleeveless-FloorLength-SheathColumn.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "83876"
},
{
"name": "HTML",
"bytes": "14547"
},
{
"name": "Ruby",
"bytes": "897"
}
],
"symlink_target": ""
} |
<?php
namespace IronBound\Cache;
/**
* Class Cache
* @package IronBound\Cache
*/
final class Cache {
/**
* Add an item to the cache.
*
* Returns false if item is already in the cache.
*
* @since 1.0
*
* @param Cacheable $object
*
* @return boolean
*/
public static function add( Cacheable $object ) {
return wp_cache_add( $object->get_pk(), $object->get_data_to_cache(), $object::get_cache_group() );
}
/**
* Update an item in the cache.
*
* @since 1.0
*
* @param Cacheable $object
*
* @return bool
*/
public static function update( Cacheable $object ) {
return wp_cache_set( $object->get_pk(), $object->get_data_to_cache(), $object::get_cache_group() );
}
/**
* Get an item from the cache.
*
* Returns false if item does not exist.
*
* @since 1.0
*
* @param int|string $pk Primary key.
* @param string $group Group name. ( default "df-{$table_slug}" )
*
* @return bool|array
*/
public static function get( $pk, $group ) {
return wp_cache_get( $pk, $group );
}
/**
* Delete an item from the cache.
*
* @since 1.0
*
* @param Cacheable $object
*
* @return bool
*/
public static function delete( Cacheable $object ) {
return wp_cache_delete( $object->get_pk(), $object::get_cache_group() );
}
}
| {
"content_hash": "0dbf7296aa859838dd67f2b559fac2aa",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 101,
"avg_line_length": 19.16176470588235,
"alnum_prop": 0.6016884113584037,
"repo_name": "iron-bound-designs/IronBound-Cache",
"id": "df82b1c8c2289ad4147bda8737f191f3215e737b",
"size": "1475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Cache.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "2269"
}
],
"symlink_target": ""
} |
"""Tests for report plugins."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import math
from absl import app
from future.builtins import range
from future.builtins import zip
from grr_response_core import config
from grr_response_core.lib import rdfvalue
from grr_response_core.lib.rdfvalues import events as rdf_events
from grr_response_server import data_store
from grr_response_server.flows.cron import system as cron_system
from grr_response_server.gui.api_plugins import stats as stats_api
from grr_response_server.gui.api_plugins.report_plugins import client_report_plugins
from grr_response_server.gui.api_plugins.report_plugins import rdf_report_plugins
from grr_response_server.gui.api_plugins.report_plugins import report_plugins
from grr_response_server.gui.api_plugins.report_plugins import report_plugins_test_mocks
from grr_response_server.gui.api_plugins.report_plugins import server_report_plugins
from grr_response_server.rdfvalues import flow_objects as rdf_flow_objects
from grr_response_server.rdfvalues import objects as rdf_objects
from grr.test_lib import test_lib
ApiReportDataPoint2D = rdf_report_plugins.ApiReportDataPoint2D
RepresentationType = rdf_report_plugins.ApiReportData.RepresentationType
Action = rdf_events.AuditEvent.Action
class ReportPluginsTest(test_lib.GRRBaseTest):
def testGetAvailableReportPlugins(self):
"""Ensure GetAvailableReportPlugins lists ReportPluginBase's subclasses."""
with report_plugins_test_mocks.MockedReportPlugins():
self.assertIn(report_plugins_test_mocks.FooReportPlugin,
report_plugins.GetAvailableReportPlugins())
self.assertIn(report_plugins_test_mocks.BarReportPlugin,
report_plugins.GetAvailableReportPlugins())
def testGetReportByName(self):
"""Ensure GetReportByName instantiates correct subclasses based on name."""
with report_plugins_test_mocks.MockedReportPlugins():
report_object = report_plugins.GetReportByName("BarReportPlugin")
self.assertTrue(
isinstance(report_object, report_plugins_test_mocks.BarReportPlugin))
def testGetReportDescriptor(self):
"""Ensure GetReportDescriptor returns a correctly filled in proto."""
desc = report_plugins_test_mocks.BarReportPlugin.GetReportDescriptor()
self.assertEqual(desc.type,
rdf_report_plugins.ApiReportDescriptor.ReportType.SERVER)
self.assertEqual(desc.title, "Bar Activity")
self.assertEqual(desc.summary,
"Reports bars' activity in the given time range.")
self.assertEqual(desc.requires_time_range, True)
def AddFakeAuditLog(user=None, router_method_name=None, http_request_path=None):
data_store.REL_DB.WriteAPIAuditEntry(
rdf_objects.APIAuditEntry(
username=user,
router_method_name=router_method_name,
http_request_path=http_request_path,
))
class ClientReportPluginsTest(test_lib.GRRBaseTest):
def MockClients(self):
client_ping_time = rdfvalue.RDFDatetime.Now() - rdfvalue.Duration.From(
8, rdfvalue.DAYS)
self.SetupClients(20, ping=client_ping_time)
def testGRRVersionReportPlugin(self):
self.MockClients()
# Scan for activity to be reported.
cron_system.GRRVersionBreakDownCronJob(None, None).Run()
report = report_plugins.GetReportByName(
client_report_plugins.GRRVersion30ReportPlugin.__name__)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__, client_label="All"),
token=self.token)
self.assertEqual(
api_report_data.representation_type,
rdf_report_plugins.ApiReportData.RepresentationType.LINE_CHART)
self.assertLen(api_report_data.line_chart.data, 1)
self.assertEqual(api_report_data.line_chart.data[0].label,
"GRR Monitor %s" % config.CONFIG["Source.version_numeric"])
self.assertLen(api_report_data.line_chart.data[0].points, 1)
self.assertEqual(api_report_data.line_chart.data[0].points[0].y, 20)
def testGRRVersionReportPluginWithNoActivityToReport(self):
# Scan for activity to be reported.
cron_system.GRRVersionBreakDownCronJob(None, None).Run()
report = report_plugins.GetReportByName(
client_report_plugins.GRRVersion30ReportPlugin.__name__)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__, client_label="All"),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.LINE_CHART,
line_chart=rdf_report_plugins.ApiLineChartReportData(data=[])))
def testLastActiveReportPlugin(self):
self.MockClients()
# Scan for activity to be reported.
cron_system.LastAccessStatsCronJob(None, None).Run()
report = report_plugins.GetReportByName(
client_report_plugins.LastActiveReportPlugin.__name__)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__, client_label="All"),
token=self.token)
self.assertEqual(
api_report_data.representation_type,
rdf_report_plugins.ApiReportData.RepresentationType.LINE_CHART)
self.assertLen(api_report_data.line_chart.data, 5)
labels = [
"60 day active", "30 day active", "7 day active", "3 day active",
"1 day active"
]
ys = [20, 20, 0, 0, 0]
for series, label, y in zip(api_report_data.line_chart.data, labels, ys):
self.assertEqual(series.label, label)
self.assertLen(series.points, 1)
self.assertEqual(series.points[0].y, y)
def testLastActiveReportPluginWithNoActivityToReport(self):
# Scan for activity to be reported.
cron_system.LastAccessStatsCronJob(None, None).Run()
report = report_plugins.GetReportByName(
client_report_plugins.LastActiveReportPlugin.__name__)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__, client_label="All"),
token=self.token)
self.assertEqual(
api_report_data.representation_type,
rdf_report_plugins.ApiReportData.RepresentationType.LINE_CHART)
self.assertLen(api_report_data.line_chart.data, 5)
labels = [
"60 day active", "30 day active", "7 day active", "3 day active",
"1 day active"
]
for series, label in zip(api_report_data.line_chart.data, labels):
self.assertEqual(series.label, label)
self.assertLen(series.points, 1)
self.assertEqual(series.points[0].y, 0)
def testOSBreakdownReportPlugin(self):
# Add a client to be reported.
self.SetupClients(1)
# Scan for clients to be reported (the one we just added).
cron_system.OSBreakDownCronJob(None, None).Run()
report = report_plugins.GetReportByName(
client_report_plugins.OSBreakdown30ReportPlugin.__name__)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__, client_label="All"),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
pie_chart=rdf_report_plugins.ApiPieChartReportData(data=[
rdf_report_plugins.ApiReportDataPoint1D(label="Linux", x=1)
]),
representation_type=RepresentationType.PIE_CHART))
def testOSBreakdownReportPluginWithNoDataToReport(self):
report = report_plugins.GetReportByName(
client_report_plugins.OSBreakdown30ReportPlugin.__name__)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__, client_label="All"),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
pie_chart=rdf_report_plugins.ApiPieChartReportData(data=[]),
representation_type=RepresentationType.PIE_CHART))
def testOSReleaseBreakdownReportPlugin(self):
# Add a client to be reported.
self.SetupClients(1)
# Scan for clients to be reported (the one we just added).
cron_system.OSBreakDownCronJob(None, None).Run()
report = report_plugins.GetReportByName(
client_report_plugins.OSReleaseBreakdown30ReportPlugin.__name__)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__, client_label="All"),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
pie_chart=rdf_report_plugins.ApiPieChartReportData(data=[
rdf_report_plugins.ApiReportDataPoint1D(
label="Linux--buster/sid", x=1)
]),
representation_type=RepresentationType.PIE_CHART))
def testOSReleaseBreakdownReportPluginWithNoDataToReport(self):
report = report_plugins.GetReportByName(
client_report_plugins.OSReleaseBreakdown30ReportPlugin.__name__)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__, client_label="Linux--buster/sid"),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
pie_chart=rdf_report_plugins.ApiPieChartReportData(data=[]),
representation_type=RepresentationType.PIE_CHART))
class FileStoreReportPluginsTest(test_lib.GRRBaseTest):
def checkStaticData(self, api_report_data):
self.assertEqual(api_report_data.representation_type,
RepresentationType.STACK_CHART)
labels = [
"0 B - 2 B", "2 B - 50 B", "50 B - 100 B", "100 B - 1000 B",
"1000 B - 9.8 KiB", "9.8 KiB - 97.7 KiB", "97.7 KiB - 488.3 KiB",
"488.3 KiB - 976.6 KiB", "976.6 KiB - 4.8 MiB", "4.8 MiB - 9.5 MiB",
"9.5 MiB - 47.7 MiB", "47.7 MiB - 95.4 MiB", "95.4 MiB - 476.8 MiB",
"476.8 MiB - 953.7 MiB", "953.7 MiB - 4.7 GiB", "4.7 GiB - 9.3 GiB",
u"9.3 GiB - \u221E"
]
xs = [0.] + [
math.log10(x) for x in [
2, 50, 100, 1e3, 10e3, 100e3, 500e3, 1e6, 5e6, 10e6, 50e6, 100e6,
500e6, 1e9, 5e9, 10e9
]
]
for series, label, x in zip(api_report_data.stack_chart.data, labels, xs):
self.assertEqual(series.label, label)
self.assertAlmostEqual([p.x for p in series.points], [x])
self.assertEqual(api_report_data.stack_chart.bar_width, .2)
self.assertEqual([t.label for t in api_report_data.stack_chart.x_ticks], [
"1 B", "32 B", "1 KiB", "32 KiB", "1 MiB", "32 MiB", "1 GiB", "32 GiB",
"1 TiB", "32 TiB", "1 PiB", "32 PiB", "1024 PiB", "32768 PiB",
"1048576 PiB"
])
self.assertAlmostEqual(api_report_data.stack_chart.x_ticks[0].x, 0.)
for diff in (t2.x - t1.x
for t1, t2 in zip(api_report_data.stack_chart.x_ticks[:-1],
api_report_data.stack_chart.x_ticks[1:])):
self.assertAlmostEqual(math.log10(32), diff)
class ServerReportPluginsTest(test_lib.GRRBaseTest):
def testClientApprovalsReportPlugin(self):
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/14")):
AddFakeAuditLog(user="User123")
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/22"), increment=1):
for i in range(10):
AddFakeAuditLog(
user="user{}".format(i),
router_method_name="CreateClientApproval",
http_request_path="/api/users/me/approvals/client/C.{:016X}".format(
i))
AddFakeAuditLog(
user="usera",
router_method_name="GrantClientApproval",
http_request_path="/api/users/user0/approvals/client/" +
"C.0000000000000000/0/")
report = report_plugins.GetReportByName(
server_report_plugins.ClientApprovalsReportPlugin.__name__)
start = rdfvalue.RDFDatetime.FromHumanReadable("2012/12/15")
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=start,
duration=month_duration),
token=self.token)
self.assertEqual(api_report_data.representation_type,
RepresentationType.AUDIT_CHART)
self.assertCountEqual(api_report_data.audit_chart.used_fields,
["action", "client", "timestamp", "user"])
expected = [
(Action.CLIENT_APPROVAL_GRANT, "usera", "C.0000000000000000"),
(Action.CLIENT_APPROVAL_REQUEST, "user9", "C.0000000000000009"),
(Action.CLIENT_APPROVAL_REQUEST, "user8", "C.0000000000000008"),
(Action.CLIENT_APPROVAL_REQUEST, "user7", "C.0000000000000007"),
(Action.CLIENT_APPROVAL_REQUEST, "user6", "C.0000000000000006"),
(Action.CLIENT_APPROVAL_REQUEST, "user5", "C.0000000000000005"),
(Action.CLIENT_APPROVAL_REQUEST, "user4", "C.0000000000000004"),
(Action.CLIENT_APPROVAL_REQUEST, "user3", "C.0000000000000003"),
(Action.CLIENT_APPROVAL_REQUEST, "user2", "C.0000000000000002"),
(Action.CLIENT_APPROVAL_REQUEST, "user1", "C.0000000000000001"),
(Action.CLIENT_APPROVAL_REQUEST, "user0", "C.0000000000000000"),
]
rows = api_report_data.audit_chart.rows
self.assertEqual([(row.action, row.user, row.client) for row in rows],
expected)
def testClientApprovalsReportPluginWithNoActivityToReport(self):
report = report_plugins.GetReportByName(
server_report_plugins.ClientApprovalsReportPlugin.__name__)
now = rdfvalue.RDFDatetime().Now()
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=now - month_duration,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.AUDIT_CHART,
audit_chart=rdf_report_plugins.ApiAuditChartReportData(
used_fields=["action", "client", "timestamp", "user"],
rows=[])))
def testHuntActionsReportPlugin(self):
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/14")):
AddFakeAuditLog(user="User123", router_method_name="CreateHunt")
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/22"), increment=1):
for i in range(10):
AddFakeAuditLog(
user="User{}".format(i), router_method_name="ModifyHunt")
report = report_plugins.GetReportByName(
server_report_plugins.HuntActionsReportPlugin.__name__)
start = rdfvalue.RDFDatetime.FromHumanReadable("2012/12/15")
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=start,
duration=month_duration),
token=self.token)
self.assertEqual(api_report_data.representation_type,
RepresentationType.AUDIT_CHART)
self.assertCountEqual(api_report_data.audit_chart.used_fields,
["action", "timestamp", "user"])
self.assertEqual([(row.action, row.timestamp.Format("%Y/%m/%d"), row.user)
for row in api_report_data.audit_chart.rows],
[(Action.HUNT_MODIFIED, "2012/12/22", "User9"),
(Action.HUNT_MODIFIED, "2012/12/22", "User8"),
(Action.HUNT_MODIFIED, "2012/12/22", "User7"),
(Action.HUNT_MODIFIED, "2012/12/22", "User6"),
(Action.HUNT_MODIFIED, "2012/12/22", "User5"),
(Action.HUNT_MODIFIED, "2012/12/22", "User4"),
(Action.HUNT_MODIFIED, "2012/12/22", "User3"),
(Action.HUNT_MODIFIED, "2012/12/22", "User2"),
(Action.HUNT_MODIFIED, "2012/12/22", "User1"),
(Action.HUNT_MODIFIED, "2012/12/22", "User0")])
def testHuntActionsReportPluginWithNoActivityToReport(self):
report = report_plugins.GetReportByName(
server_report_plugins.HuntActionsReportPlugin.__name__)
now = rdfvalue.RDFDatetime().Now()
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=now - month_duration,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.AUDIT_CHART,
audit_chart=rdf_report_plugins.ApiAuditChartReportData(
used_fields=["action", "timestamp", "user"], rows=[])))
def testHuntApprovalsReportPlugin(self):
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/14")):
AddFakeAuditLog(
user="User123",
router_method_name="GrantHuntApproval",
http_request_path="/api/users/u0/approvals/hunt/H:000011/0/")
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/22"), increment=1):
for i in range(10):
AddFakeAuditLog(
user="User{}".format(i),
router_method_name="CreateHuntApproval",
http_request_path="/api/users/User{0}/approvals/hunt/H:{0:06d}/0/"
.format(i))
AddFakeAuditLog(
user="User456",
router_method_name="GrantHuntApproval",
http_request_path="/api/users/u0/approvals/hunt/H:000010/0/")
report = report_plugins.GetReportByName(
server_report_plugins.HuntApprovalsReportPlugin.__name__)
start = rdfvalue.RDFDatetime.FromHumanReadable("2012/12/15")
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=start,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data.representation_type,
rdf_report_plugins.ApiReportData.RepresentationType.AUDIT_CHART)
self.assertCountEqual(api_report_data.audit_chart.used_fields,
["action", "timestamp", "user", "urn"])
expected = [
(Action.HUNT_APPROVAL_GRANT, "2012/12/22", "User456",
"aff4:/hunts/H:000010"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User9",
"aff4:/hunts/H:000009"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User8",
"aff4:/hunts/H:000008"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User7",
"aff4:/hunts/H:000007"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User6",
"aff4:/hunts/H:000006"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User5",
"aff4:/hunts/H:000005"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User4",
"aff4:/hunts/H:000004"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User3",
"aff4:/hunts/H:000003"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User2",
"aff4:/hunts/H:000002"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User1",
"aff4:/hunts/H:000001"),
(Action.HUNT_APPROVAL_REQUEST, "2012/12/22", "User0",
"aff4:/hunts/H:000000"),
]
self.assertEqual(
[(row.action, row.timestamp.Format("%Y/%m/%d"), row.user, str(row.urn))
for row in api_report_data.audit_chart.rows], expected)
def testHuntApprovalsReportPluginWithNoActivityToReport(self):
report = report_plugins.GetReportByName(
server_report_plugins.HuntApprovalsReportPlugin.__name__)
now = rdfvalue.RDFDatetime().Now()
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=now - month_duration,
duration=month_duration),
token=self.token)
self.assertEqual(api_report_data.representation_type,
RepresentationType.AUDIT_CHART)
self.assertCountEqual(api_report_data.audit_chart.used_fields,
["action", "timestamp", "user", "urn"])
self.assertEmpty(api_report_data.audit_chart.rows)
def testCronApprovalsReportPlugin(self):
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/14")):
AddFakeAuditLog(
user="User123",
router_method_name="GrantCronJobApproval",
http_request_path="/api/users/u/approvals/cron-job/a/0/")
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/22"), increment=1):
for i in range(10):
AddFakeAuditLog(
user="User{}".format(i),
router_method_name="CreateCronJobApproval",
http_request_path="/api/users/u{0}/approvals/cron-job/a{0}/0/"
.format(i))
AddFakeAuditLog(
user="User456",
router_method_name="GrantCronJobApproval",
http_request_path="/api/users/u0/approvals/cron-job/a0/0/")
report = report_plugins.GetReportByName(
server_report_plugins.CronApprovalsReportPlugin.__name__)
start = rdfvalue.RDFDatetime.FromHumanReadable("2012/12/15")
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=start,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data.representation_type,
rdf_report_plugins.ApiReportData.RepresentationType.AUDIT_CHART)
self.assertCountEqual(api_report_data.audit_chart.used_fields,
["action", "timestamp", "user", "urn"])
expected = [
(Action.CRON_APPROVAL_GRANT, "2012/12/22", "User456", "aff4:/cron/a0"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User9", "aff4:/cron/a9"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User8", "aff4:/cron/a8"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User7", "aff4:/cron/a7"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User6", "aff4:/cron/a6"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User5", "aff4:/cron/a5"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User4", "aff4:/cron/a4"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User3", "aff4:/cron/a3"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User2", "aff4:/cron/a2"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User1", "aff4:/cron/a1"),
(Action.CRON_APPROVAL_REQUEST, "2012/12/22", "User0", "aff4:/cron/a0"),
]
self.assertEqual(
[(row.action, row.timestamp.Format("%Y/%m/%d"), row.user, str(row.urn))
for row in api_report_data.audit_chart.rows], expected)
def testCronApprovalsReportPluginWithNoActivityToReport(self):
report = report_plugins.GetReportByName(
server_report_plugins.CronApprovalsReportPlugin.__name__)
now = rdfvalue.RDFDatetime().Now()
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=now - month_duration,
duration=month_duration),
token=self.token)
self.assertEqual(api_report_data.representation_type,
RepresentationType.AUDIT_CHART)
self.assertCountEqual(api_report_data.audit_chart.used_fields,
["action", "timestamp", "user", "urn"])
self.assertEmpty(api_report_data.audit_chart.rows)
def testMostActiveUsersReportPlugin(self):
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/14")):
AddFakeAuditLog(user="User123")
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/22")):
for _ in range(10):
AddFakeAuditLog(user="User123")
AddFakeAuditLog(user="User456")
report = report_plugins.GetReportByName(
server_report_plugins.MostActiveUsersReportPlugin.__name__)
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/31")):
now = rdfvalue.RDFDatetime().Now()
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=now - month_duration,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.PIE_CHART,
pie_chart=rdf_report_plugins.ApiPieChartReportData(data=[
rdf_report_plugins.ApiReportDataPoint1D(
label="User123", x=11),
rdf_report_plugins.ApiReportDataPoint1D(label="User456", x=1)
])))
def testMostActiveUsersReportPluginWithNoActivityToReport(self):
report = report_plugins.GetReportByName(
server_report_plugins.MostActiveUsersReportPlugin.__name__)
now = rdfvalue.RDFDatetime().Now()
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=now - month_duration,
duration=month_duration),
token=self.token)
self.assertEqual(api_report_data.representation_type,
RepresentationType.PIE_CHART)
self.assertEmpty(api_report_data.pie_chart.data)
def testSystemFlowsReportPlugin(self):
client_id = self.SetupClient(1)
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/14")):
data_store.REL_DB.WriteFlowObject(
rdf_flow_objects.Flow(
flow_class_name="GetClientStats",
creator="GRR",
client_id=client_id,
flow_id="0000000B",
create_time=rdfvalue.RDFDatetime.Now()))
AddFakeAuditLog(user="GRR")
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/22")):
for i in range(10):
data_store.REL_DB.WriteFlowObject(
rdf_flow_objects.Flow(
flow_class_name="GetClientStats",
creator="GRR",
client_id=client_id,
flow_id="{:08X}".format(i),
create_time=rdfvalue.RDFDatetime.Now()))
AddFakeAuditLog(user="GRR",)
data_store.REL_DB.WriteFlowObject(
rdf_flow_objects.Flow(
flow_class_name="ArtifactCollectorFlow",
creator="GRR",
client_id=client_id,
flow_id="0000000A",
create_time=rdfvalue.RDFDatetime.Now()))
AddFakeAuditLog(user="GRR")
report = report_plugins.GetReportByName(
server_report_plugins.SystemFlowsReportPlugin.__name__)
start = rdfvalue.RDFDatetime.FromHumanReadable("2012/12/15")
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=start,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.STACK_CHART,
stack_chart=rdf_report_plugins.ApiStackChartReportData(
x_ticks=[],
data=[
rdf_report_plugins.ApiReportDataSeries2D(
label=u"GetClientStats\u2003Run By: GRR (10)",
points=[ApiReportDataPoint2D(x=0, y=10)]),
rdf_report_plugins.ApiReportDataSeries2D(
label=u"ArtifactCollectorFlow\u2003Run By: GRR (1)",
points=[ApiReportDataPoint2D(x=1, y=1)])
])))
def testSystemFlowsReportPluginWithNoActivityToReport(self):
report = report_plugins.GetReportByName(
server_report_plugins.SystemFlowsReportPlugin.__name__)
now = rdfvalue.RDFDatetime().Now()
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=now - month_duration,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.STACK_CHART,
stack_chart=rdf_report_plugins.ApiStackChartReportData(x_ticks=[])))
def testUserActivityReportPlugin(self):
entries = {
"2012/12/02": ["User123"],
"2012/12/07": ["User123"],
"2012/12/15": ["User123"] * 2 + ["User456"],
"2012/12/23": ["User123"] * 10,
"2012/12/28": ["User123"],
}
for date_string, usernames in entries.items():
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable(date_string)):
for username in usernames:
AddFakeAuditLog(user=username)
report = report_plugins.GetReportByName(
server_report_plugins.UserActivityReportPlugin.__name__)
# Use 15 days which will be rounded up to 3 full weeks.
duration = rdfvalue.Duration.From(15, rdfvalue.DAYS)
start_time = rdfvalue.RDFDatetime.FromHumanReadable("2012/12/07")
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=start_time,
duration=duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.STACK_CHART,
stack_chart=rdf_report_plugins.ApiStackChartReportData(data=[
rdf_report_plugins.ApiReportDataSeries2D(
label=u"User123",
points=[
ApiReportDataPoint2D(x=0, y=1),
ApiReportDataPoint2D(x=1, y=2),
ApiReportDataPoint2D(x=2, y=10),
]),
rdf_report_plugins.ApiReportDataSeries2D(
label=u"User456",
points=[
ApiReportDataPoint2D(x=0, y=0),
ApiReportDataPoint2D(x=1, y=1),
ApiReportDataPoint2D(x=2, y=0),
])
])))
def testUserActivityReportPluginWithNoActivityToReport(self):
report = report_plugins.GetReportByName(
server_report_plugins.UserActivityReportPlugin.__name__)
duration = rdfvalue.Duration.From(14, rdfvalue.DAYS)
start_time = rdfvalue.RDFDatetime.Now() - duration
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=start_time,
duration=duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.STACK_CHART,
stack_chart=rdf_report_plugins.ApiStackChartReportData(data=[])))
def testUserFlowsReportPlugin(self):
client_id = self.SetupClient(1)
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/14")):
AddFakeAuditLog(user="User123")
data_store.REL_DB.WriteFlowObject(
rdf_flow_objects.Flow(
flow_class_name="GetClientStats",
creator="User123",
client_id=client_id,
flow_id="E0000000",
create_time=rdfvalue.RDFDatetime.Now()))
with test_lib.FakeTime(
rdfvalue.RDFDatetime.FromHumanReadable("2012/12/22")):
for i in range(10):
data_store.REL_DB.WriteFlowObject(
rdf_flow_objects.Flow(
flow_class_name="GetClientStats",
creator="User123",
client_id=client_id,
flow_id="{:08X}".format(i),
create_time=rdfvalue.RDFDatetime.Now()))
AddFakeAuditLog(user="User123")
data_store.REL_DB.WriteFlowObject(
rdf_flow_objects.Flow(
flow_class_name="ArtifactCollectorFlow",
creator="User456",
client_id=client_id,
flow_id="F0000000",
create_time=rdfvalue.RDFDatetime.Now()))
AddFakeAuditLog(user="User456")
report = report_plugins.GetReportByName(
server_report_plugins.UserFlowsReportPlugin.__name__)
start = rdfvalue.RDFDatetime.FromHumanReadable("2012/12/15")
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=start,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.STACK_CHART,
stack_chart=rdf_report_plugins.ApiStackChartReportData(
x_ticks=[],
data=[
rdf_report_plugins.ApiReportDataSeries2D(
label=u"GetClientStats\u2003Run By: User123 (10)",
points=[ApiReportDataPoint2D(x=0, y=10)]),
rdf_report_plugins.ApiReportDataSeries2D(
label=u"ArtifactCollectorFlow\u2003Run By: User456 (1)",
points=[ApiReportDataPoint2D(x=1, y=1)])
])))
def testUserFlowsReportPluginWithNoActivityToReport(self):
report = report_plugins.GetReportByName(
server_report_plugins.UserFlowsReportPlugin.__name__)
now = rdfvalue.RDFDatetime().Now()
month_duration = rdfvalue.Duration.From(30, rdfvalue.DAYS)
api_report_data = report.GetReportData(
stats_api.ApiGetReportArgs(
name=report.__class__.__name__,
start_time=now - month_duration,
duration=month_duration),
token=self.token)
self.assertEqual(
api_report_data,
rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.STACK_CHART,
stack_chart=rdf_report_plugins.ApiStackChartReportData(x_ticks=[])))
def main(argv):
test_lib.main(argv)
if __name__ == "__main__":
app.run(main)
| {
"content_hash": "03d99cfdf16ebf31764a9f741ff7e5a5",
"timestamp": "",
"source": "github",
"line_count": 907,
"max_line_length": 88,
"avg_line_length": 39.08599779492833,
"alnum_prop": 0.6355250909706355,
"repo_name": "demonchild2112/travis-test",
"id": "f92029758e3870730b5c86a37d86dfaeeae1241f",
"size": "35473",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "grr/server/grr_response_server/gui/api_plugins/report_plugins/report_plugins_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "227"
},
{
"name": "Batchfile",
"bytes": "3446"
},
{
"name": "C",
"bytes": "11321"
},
{
"name": "C++",
"bytes": "54535"
},
{
"name": "CSS",
"bytes": "35549"
},
{
"name": "Dockerfile",
"bytes": "1819"
},
{
"name": "HCL",
"bytes": "7208"
},
{
"name": "HTML",
"bytes": "190212"
},
{
"name": "JavaScript",
"bytes": "11691"
},
{
"name": "Jupyter Notebook",
"bytes": "199190"
},
{
"name": "Makefile",
"bytes": "3139"
},
{
"name": "PowerShell",
"bytes": "1984"
},
{
"name": "Python",
"bytes": "7213255"
},
{
"name": "Roff",
"bytes": "444"
},
{
"name": "Shell",
"bytes": "48882"
},
{
"name": "Standard ML",
"bytes": "8172"
},
{
"name": "TSQL",
"bytes": "51"
}
],
"symlink_target": ""
} |
[](https://www.npmjs.org/package/bitcore-wallet-service)
[](https://travis-ci.org/bitpay/bitcore-wallet-service)
[](https://coveralls.io/r/bitpay/bitcore-wallet-service?branch=master)
A Multisig HD Bitcore Wallet Service.
# Description
Bitcore Wallet Service facilitates multisig HD wallets creation and operation through a (hopefully) simple and intuitive REST API.
BWS can usually be installed within minutes and accommodates all the needed infrastructure for peers in a multisig wallet to communicate and operate – with minimum server trust.
See [Bitcore-wallet-client](https://github.com/bitpay/bitcore-wallet-client) for the *official* client library that communicates to BWS and verifies its response. Also check [Bitcore-wallet](https://github.com/bitpay/bitcore-wallet) for a simple CLI wallet implementation that relies on BWS.
BWS is been used in production enviroments for [Copay Wallet](https://copay.io), [Bitpay App wallet](https://bitpay.com/wallet) and others.
More about BWS at https://blog.bitpay.com/announcing-the-bitcore-wallet-suite/
# Getting Started
```
git clone https://github.com/bitpay/bitcore-wallet-service.git
cd bitcore-wallet-service
npm install
npm start
```
This will launch the BWS service (with default settings) at `http://localhost:3232/bws/api`.
BWS needs mongoDB. You can configure the connection at `config.js`
BWS supports SSL and Clustering. For a detailed guide on installing BWS with extra features see [Installing BWS](https://github.com/bitpay/bitcore-wallet-service/blob/master/installation.md).
BWS uses by default a Request Rate Limitation to CreateWallet endpoint. If you need to modify it, check defaults.js' `Defaults.RateLimit`
# Using BWS with PM2
BWS can be used with PM2 with the provided `app.js` script:
```
pm2 start app.js --name "bitcoin-wallet-service"
```
# Security Considerations
* Private keys are never sent to BWS. Copayers store them locally.
* Extended public keys are stored on BWS. This allows BWS to easily check wallet balance, send offline notifications to copayers, etc.
* During wallet creation, the initial copayer creates a wallet secret that contains a private key. All copayers need to prove they have the secret by signing their information with this private key when joining the wallet. The secret should be shared using secured channels.
* A copayer could join the wallet more than once, and there is no mechanism to prevent this. See [wallet](https://github.com/bitpay/bitcore-wallet)'s confirm command, for a method for confirming copayers.
* All BWS responses are verified:
* Addresses and change addresses are derived independently and locally by the copayers from their local data.
* TX Proposals templates are signed by copayers and verified by others, so the BWS cannot create or tamper with them.
# Using SSL
You can add your certificates at the config.js using:
``` json
https: true,
privateKeyFile: 'private.pem',
certificateFile: 'cert.pem',
////// The following is only for certs which are not
////// trusted by nodejs 'https' by default
////// CAs like Verisign do not require this
// CAinter1: '', // ex. 'COMODORSADomainValidationSecureServerCA.crt'
// CAinter2: '', // ex. 'COMODORSAAddTrustCA.crt'
// CAroot: '', // ex. 'AddTrustExternalCARoot.crt'
```
@dabura667 made a report about how to use letsencrypt with BWS: https://github.com/bitpay/bitcore-wallet-service/issues/423
# REST API
Note: all currency amounts are in units of satoshis (1/100,000,000 of a bitcoin).
## Authentication
In order to access a wallet, clients are required to send the headers:
```
x-identity
x-signature
```
Identity is the Peer-ID, this will identify the peer and its wallet. Signature is the current request signature, using `requestSigningKey`, the `m/1/1` derivative of the Extended Private Key.
See [Bitcore Wallet Client](https://github.com/bitpay/bitcore-wallet-client/blob/master/lib/api.js#L73) for implementation details.
## GET Endpoints
`/v1/wallets/`: Get wallet information
Returns:
* Wallet object. (see [fields on the source code](https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/wallet.js)).
`/v1/txhistory/`: Get Wallet's transaction history
Optional Arguments:
* skip: Records to skip from the result (defaults to 0)
* limit: Total number of records to return (return all available records if not specified).
Returns:
* History of incoming and outgoing transactions of the wallet. The list is paginated using the `skip` & `limit` params. Each item has the following fields:
* action ('sent', 'received', 'moved')
* amount
* fees
* time
* addressTo
* confirmations
* proposalId
* creatorName
* message
* actions array ['createdOn', 'type', 'copayerId', 'copayerName', 'comment']
`/v1/txproposals/`: Get Wallet's pending transaction proposals and their status
Returns:
* List of pending TX Proposals. (see [fields on the source code](https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/txproposal.js))
`/v1/addresses/`: Get Wallet's main addresses (does not include change addresses)
Returns:
* List of Addresses object: (https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/address.js)). This call is mainly provided so the client check this addresses for incoming transactions (using a service like [Insight](https://insight.is)
`/v1/balance/`: Get Wallet's balance
Returns:
* totalAmount: Wallet's total balance
* lockedAmount: Current balance of outstanding transaction proposals, that cannot be used on new transactions.
* availableAmount: Funds available for new proposals.
* totalConfirmedAmount: Same as totalAmount for confirmed UTXOs only.
* lockedConfirmedAmount: Same as lockedAmount for confirmed UTXOs only.
* availableConfirmedAmount: Same as availableAmount for confirmed UTXOs only.
* byAddress array ['address', 'path', 'amount']: A list of addresses holding funds.
* totalKbToSendMax: An estimation of the number of KiB required to include all available UTXOs in a tx (including unconfirmed).
`/v1/txnotes/:txid`: Get user notes associated to the specified transaction.
Returns:
* The note associated to the `txid` as a string.
`/v1/fiatrates/:code`: Get the fiat rate for the specified ISO 4217 code.
Optional Arguments:
* provider: An identifier representing the source of the rates.
* ts: The timestamp for the fiat rate (defaults to now).
Returns:
* The fiat exchange rate.
## POST Endpoints
`/v1/wallets/`: Create a new Wallet
Required Arguments:
* name: Name of the wallet
* m: Number of required peers to sign transactions
* n: Number of total peers on the wallet
* pubKey: Wallet Creation Public key to check joining copayer's signatures (the private key is unknown by BWS and must be communicated
by the creator peer to other peers).
Returns:
* walletId: Id of the new created wallet
`/v1/wallets/:id/copayers/`: Join a Wallet in creation
Required Arguments:
* walletId: Id of the wallet to join
* name: Copayer Name
* xPubKey - Extended Public Key for this copayer.
* requestPubKey - Public Key used to check requests from this copayer.
* copayerSignature - Signature used by other copayers to verify that the copayer joining knows the wallet secret.
Returns:
* copayerId: Assigned ID of the copayer (to be used on x-identity header)
* wallet: Object with wallet's information
`/v1/txproposals/`: Add a new transaction proposal
Required Arguments:
* toAddress: RCPT Bitcoin address.
* amount: amount (in satoshis) of the mount proposed to be transfered
* proposalsSignature: Signature of the proposal by the creator peer, using proposalSigningKey.
* (opt) message: Encrypted private message to peers.
* (opt) payProUrl: Paypro URL for peers to verify TX
* (opt) feePerKb: Use an alternative fee per KB for this TX.
* (opt) excludeUnconfirmedUtxos: Do not use UTXOs of unconfirmed transactions as inputs for this TX.
Returns:
* TX Proposal object. (see [fields on the source code](https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/txproposal.js)). `.id` is probably needed in this case.
`/v3/addresses/`: Request a new main address from wallet . (creates an address on normal conditions)
Returns:
* Address object: (https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/address.js)). Note that `path` is returned so client can derive the address independently and check server's response.
`/v1/txproposals/:id/signatures/`: Sign a transaction proposal
Required Arguments:
* signatures: All Transaction's input signatures, in order of appearance.
Returns:
* TX Proposal object. (see [fields on the source code](https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/txproposal.js)). `.status` is probably needed in this case.
`/v1/txproposals/:id/broadcast/`: Broadcast a transaction proposal
Returns:
* TX Proposal object. (see [fields on the source code](https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/txproposal.js)). `.status` is probably needed in this case.
`/v1/txproposals/:id/rejections`: Reject a transaction proposal
Returns:
* TX Proposal object. (see [fields on the source code](https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/txproposal.js)). `.status` is probably needed in this case.
`/v1/addresses/scan`: Start an address scan process looking for activity.
Optional Arguments:
* includeCopayerBranches: Scan all copayer branches following BIP45 recommendation (defaults to false).
`/v1/txconfirmations/`: Subscribe to receive push notifications when the specified transaction gets confirmed.
Required Arguments:
* txid: The transaction to subscribe to.
## PUT Endpoints
`/v1/txnotes/:txid/`: Modify a note for a tx.
## DELETE Endpoints
`/v1/txproposals/:id/`: Deletes a transaction proposal. Only the creator can delete a TX Proposal, and only if it has no other signatures or rejections
Returns:
* TX Proposal object. (see [fields on the source code](https://github.com/bitpay/bitcore-wallet-service/blob/master/lib/model/txproposal.js)). `.id` is probably needed in this case.
`/v1/txconfirmations/:txid`: Unsubscribe from transaction `txid` and no longer listen to its confirmation.
# Push Notifications
Recomended to complete config.js file:
* [GCM documentation to get your API key](https://developers.google.com/cloud-messaging/gcm)
* [Apple's Notification guide to know how to get your certificates for APN](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/Introduction.html)
## POST Endpoints
`/v1/pushnotifications/subscriptions/`: Adds subscriptions for push notifications service at database.
## DELETE Endpoints
`/v2/pushnotifications/subscriptions/`: Remove subscriptions for push notifications service from database.
| {
"content_hash": "d1e509b82f4a0383f7f70a06a9e9be4a",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 291,
"avg_line_length": 44.76892430278885,
"alnum_prop": 0.7635489899439352,
"repo_name": "matiu/bitcore-wallet-service",
"id": "b3b6723fc4f9d9e9544b644d36b1561c5860ca00",
"size": "11266",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1048047"
},
{
"name": "Makefile",
"bytes": "147"
},
{
"name": "Shell",
"bytes": "1525"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_34) on Thu Jan 07 14:13:59 GMT 2016 -->
<TITLE>
Uses of Class org.apache.fop.layoutmgr.Page (Apache FOP 2.1 API)
</TITLE>
<META NAME="date" CONTENT="2016-01-07">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.fop.layoutmgr.Page (Apache FOP 2.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/fop/layoutmgr//class-usePage.html" target="_top"><B>FRAMES</B></A>
<A HREF="Page.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.fop.layoutmgr.Page</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.fop.layoutmgr"><B>org.apache.fop.layoutmgr</B></A></TD>
<TD>FOP's layout engine. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.fop.layoutmgr"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A> in <A HREF="../../../../../org/apache/fop/layoutmgr/package-summary.html">org.apache.fop.layoutmgr</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../org/apache/fop/layoutmgr/package-summary.html">org.apache.fop.layoutmgr</A> declared as <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPageSequenceLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.html#curPage">curPage</A></B></CODE>
<BR>
Current page with page-viewport-area being filled by the PSLM.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/apache/fop/layoutmgr/package-summary.html">org.apache.fop.layoutmgr</A> that return <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPageSequenceLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.html#createPage(int, boolean)">createPage</A></B>(int pageNumber,
boolean isBlank)</CODE>
<BR>
Creates and returns a new page.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>PageSequenceLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/PageSequenceLayoutManager.html#createPage(int, boolean)">createPage</A></B>(int pageNumber,
boolean isBlank)</CODE>
<BR>
Creates and returns a new page.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>ExternalDocumentLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.html#createPage(int, boolean)">createPage</A></B>(int pageNumber,
boolean isBlank)</CODE>
<BR>
Creates and returns a new page.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPageSequenceLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.html#getCurrentPage()">getCurrentPage</A></B>()</CODE>
<BR>
Provides access to the current page.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>AbstractLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/AbstractLayoutManager.html#getCurrentPage()">getCurrentPage</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>PageProvider.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/PageProvider.html#getPage(boolean, int)">getPage</A></B>(boolean isBlank,
int index)</CODE>
<BR>
Returns a Page.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>PageProvider.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/PageProvider.html#getPage(boolean, int, int)">getPage</A></B>(boolean isBlank,
int index,
int relativeTo)</CODE>
<BR>
Returns a Page.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>AbstractPageSequenceLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.html#makeNewPage(boolean)">makeNewPage</A></B>(boolean isBlank)</CODE>
<BR>
Makes a new page</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></CODE></FONT></TD>
<TD><CODE><B>PageSequenceLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/PageSequenceLayoutManager.html#makeNewPage(boolean)">makeNewPage</A></B>(boolean isBlank)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/apache/fop/layoutmgr/package-summary.html">org.apache.fop.layoutmgr</A> with parameters of type <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B>AbstractPageSequenceLayoutManager.</B><B><A HREF="../../../../../org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.html#setCurrentPage(org.apache.fop.layoutmgr.Page)">setCurrentPage</A></B>(<A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr">Page</A> currentPage)</CODE>
<BR>
Provides access for setting the current page.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/fop/layoutmgr/Page.html" title="class in org.apache.fop.layoutmgr"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/fop/layoutmgr//class-usePage.html" target="_top"><B>FRAMES</B></A>
<A HREF="Page.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "acf47efa2ec5987e2c249adb4440c7d0",
"timestamp": "",
"source": "github",
"line_count": 282,
"max_line_length": 347,
"avg_line_length": 51.152482269503544,
"alnum_prop": 0.6447140381282496,
"repo_name": "JollyApplez/SeCuenti",
"id": "3fbd0fd37d668993efea0697cc455f721f8681e7",
"size": "14425",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Resources/fop-2.1/javadocs/org/apache/fop/layoutmgr/class-use/Page.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "4336"
},
{
"name": "CSS",
"bytes": "1391"
},
{
"name": "HTML",
"bytes": "82926483"
},
{
"name": "Java",
"bytes": "8120"
},
{
"name": "JavaScript",
"bytes": "10503"
},
{
"name": "Shell",
"bytes": "7681"
},
{
"name": "XSLT",
"bytes": "1951"
}
],
"symlink_target": ""
} |
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.TransactionalMap;
import com.hazelcast.transaction.TransactionException;
import com.hazelcast.transaction.TransactionalTask;
import com.hazelcast.transaction.TransactionalTaskContext;
public class TransactionalTaskMember {
public static void main(String[] args) throws Throwable {
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
hz.executeTransaction(new TransactionalTask() {
@Override
public Object execute(TransactionalTaskContext context) throws TransactionException {
TransactionalMap<String, String> map = context.getMap("map");
map.put("1", "1");
map.put("2", "2");
return null;
}
});
System.out.println("Finished");
System.exit(0);
}
}
| {
"content_hash": "f35821e57144f08c4fc79a14810e2278",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 97,
"avg_line_length": 37.958333333333336,
"alnum_prop": 0.6750823271130626,
"repo_name": "SoCe/SoCe",
"id": "4b0588db4e0b601c5aadda67d1154a00863b8597",
"size": "911",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Server/thirdparty/hazelcast/hazelcast-3.3.3/code-samples/transactions/transactional-task/src/main/java/TransactionalTaskMember.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "87092"
}
],
"symlink_target": ""
} |
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
/**
* Methods supporting a list of Akrecipes records.
*
* @since 1.6
*/
class AkrecipesModelContests extends JModelList
{
/**
* Constructor.
*
* @param array $config An optional associative array of configuration settings.
*
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'ordering', 'a.ordering',
'state', 'a.state',
'created_by', 'a.created_by',
'modified_by', 'a.modified_by',
'publish_up', 'a.publish_up',
'publish_down', 'a.publish_down',
'language', 'a.language',
'contest_name', 'a.contest_name',
'contest_description', 'a.contest_description',
'alias', 'a.alias',
);
}
parent::__construct($config);
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @param string $ordering Elements order
* @param string $direction Order direction
*
* @return void
*
* @throws Exception
*
* @since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication();
// List state information
$limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->get('list_limit'));
$this->setState('list.limit', $limit);
$limitstart = $app->getUserStateFromRequest('limitstart', 'limitstart', 0);
$this->setState('list.start', $limitstart);
if ($list = $app->getUserStateFromRequest($this->context . '.list', 'list', array(), 'array'))
{
foreach ($list as $name => $value)
{
// Extra validations
switch ($name)
{
case 'fullordering':
$orderingParts = explode(' ', $value);
if (count($orderingParts) >= 2)
{
// Latest part will be considered the direction
$fullDirection = end($orderingParts);
if (in_array(strtoupper($fullDirection), array('ASC', 'DESC', '')))
{
$this->setState('list.direction', $fullDirection);
}
unset($orderingParts[count($orderingParts) - 1]);
// The rest will be the ordering
$fullOrdering = implode(' ', $orderingParts);
if (in_array($fullOrdering, $this->filter_fields))
{
$this->setState('list.ordering', $fullOrdering);
}
}
else
{
$this->setState('list.ordering', $ordering);
$this->setState('list.direction', $direction);
}
break;
case 'ordering':
if (!in_array($value, $this->filter_fields))
{
$value = $ordering;
}
break;
case 'direction':
if (!in_array(strtoupper($value), array('ASC', 'DESC', '')))
{
$value = $direction;
}
break;
case 'limit':
$limit = $value;
break;
// Just to keep the default case
default:
$value = $value;
break;
}
$this->setState('list.' . $name, $value);
}
}
// Receive & set filters
if ($filters = $app->getUserStateFromRequest($this->context . '.filter', 'filter', array(), 'array'))
{
foreach ($filters as $name => $value)
{
$this->setState('filter.' . $name, $value);
}
}
$ordering = $app->input->get('filter_order');
if (!empty($ordering))
{
$list = $app->getUserState($this->context . '.list');
$list['ordering'] = $app->input->get('filter_order');
$app->setUserState($this->context . '.list', $list);
}
$orderingDirection = $app->input->get('filter_order_Dir');
if (!empty($orderingDirection))
{
$list = $app->getUserState($this->context . '.list');
$list['direction'] = $app->input->get('filter_order_Dir');
$app->setUserState($this->context . '.list', $list);
}
$list = $app->getUserState($this->context . '.list');
if (empty($list['ordering']))
{
$list['ordering'] = 'ordering';
}
if (empty($list['direction']))
{
$list['direction'] = 'asc';
}
if (isset($list['ordering']))
{
$this->setState('list.ordering', $list['ordering']);
}
if (isset($list['direction']))
{
$this->setState('list.direction', $list['direction']);
}
}
/**
* Build an SQL query to load the list data.
*
* @return JDatabaseQuery
*
* @since 1.6
*/
protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query
->select(
$this->getState(
'list.select', 'DISTINCT a.*'
)
);
$query->from('`#__akrecipes_contests` AS a');
// Join over the users for the checked out user.
$query->select('uc.name AS editor');
$query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');
// Join over the created by field 'created_by'
$query->join('LEFT', '#__users AS created_by ON created_by.id = a.created_by');
// Join over the created by field 'modified_by'
$query->join('LEFT', '#__users AS modified_by ON modified_by.id = a.modified_by');
if (!JFactory::getUser()->authorise('core.edit', 'com_akrecipes'))
{
$query->where('a.state = 1');
}
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0)
{
$query->where('a.id = ' . (int) substr($search, 3));
}
else
{
$search = $db->Quote('%' . $db->escape($search, true) . '%');
$query->where('( a.contest_name LIKE ' . $search . ' )');
}
}
// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering');
$orderDirn = $this->state->get('list.direction');
if ($orderCol && $orderDirn)
{
$query->order($db->escape($orderCol . ' ' . $orderDirn));
}
return $query;
}
/**
* Method to get an array of data items
*
* @return mixed An array of data on success, false on failure.
*/
public function getItems()
{
$items = parent::getItems();
return $items;
}
/**
* Overrides the default function to check Date fields format, identified by
* "_dateformat" suffix, and erases the field if it's not correct.
*
* @return void
*/
protected function loadFormData()
{
$app = JFactory::getApplication();
$filters = $app->getUserState($this->context . '.filter', array());
$error_dateformat = false;
foreach ($filters as $key => $value)
{
if (strpos($key, '_dateformat') && !empty($value) && $this->isValidDate($value) == null)
{
$filters[$key] = '';
$error_dateformat = true;
}
}
if ($error_dateformat)
{
$app->enqueueMessage(JText::_("COM_AKCONTESTS_SEARCH_FILTER_DATE_FORMAT"), "warning");
$app->setUserState($this->context . '.filter', $filters);
}
return parent::loadFormData();
}
/**
* Checks if a given date is valid and in a specified format (YYYY-MM-DD)
*
* @param string $date Date to be checked
*
* @return bool
*/
private function isValidDate($date)
{
$date = str_replace('/', '-', $date);
return (date_create($date)) ? JFactory::getDate($date)->format("Y-m-d") : null;
}
}
| {
"content_hash": "d3742424f57faa13003c415fed865804",
"timestamp": "",
"source": "github",
"line_count": 308,
"max_line_length": 103,
"avg_line_length": 23.56168831168831,
"alnum_prop": 0.5828854898718479,
"repo_name": "rutvikd/ak-recipes",
"id": "9e94acb4d8f620b949522423bdf85fe1da14f2b9",
"size": "7485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com_akrecipes-1.0.1/site/models/contests.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "300248"
},
{
"name": "HTML",
"bytes": "10562"
},
{
"name": "JavaScript",
"bytes": "177835"
},
{
"name": "PHP",
"bytes": "6358610"
},
{
"name": "Shell",
"bytes": "257"
}
],
"symlink_target": ""
} |
A simple pattern for managing flash messages in your Ruby on Rails application.
## Installation
***This branch is only used for Rails 3. Still using Rails 2? Use [https://github.com/planetargon/flash-message-conductor/tree/rails2](https://github.com/planetargon/flash-message-conductor/tree/rails2) instead.***
Add this line to your application's Gemfile:
gem "flash-message-conductor", "~> 2.0.1"
And then execute:
$ bundle
Or install it yourself as:
gem install flash-message-conductor
## Usage
### Controller helpers
```
add_message('foo')
```
**Is the equivalent of:**
```
flash[:message] = 'foo'
```
**Flash methods Keep, discard, and now are also supported**
```
add_message('foo', :state => :keep)
```
**Is the equivalent of:**
```
flash[:message] = 'foo'
flash.keep(:message)
```
**Rails Controller helpers included:**
```
add_message(message)
add_notice(message)
add_error(message)
add_alert(message)
```
### View helpers
```
<%= render_flash_messages %>
```
**Produces:**
```
<div id="flash_messages">
<p class="message">You have successfully done XYZ...</p>
</div>
```
**Or... if you set an error:**
```
<div id="flash_messages">
<p class="error">Oops! Something went bonkers!<p>
</div>
```
**Or:**
```
<% if flash_message_set? -%>
# do something
<% end -%>
```
Copyright (c) 2008-2013 Planet Argon, released under the MIT license
### Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {
"content_hash": "923b2b272a7ac31a8c8d311e484f02e8",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 214,
"avg_line_length": 18.141304347826086,
"alnum_prop": 0.6518873576992211,
"repo_name": "muthhus/flash-message-conductor",
"id": "d50fbd537a8472c554460297c1b1fe0661392594",
"size": "1696",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
set -o errexit
set -o nounset
set -o pipefail
KUBE_ROOT=$(dirname "${BASH_SOURCE}")/..
source "${KUBE_ROOT}/hack/lib/init.sh"
source "${KUBE_ROOT}/hack/lib/test.sh"
# Stops the running kubectl proxy, if there is one.
function stop-proxy()
{
[[ -n "${PROXY_PORT-}" ]] && kube::log::status "Stopping proxy on port ${PROXY_PORT}"
[[ -n "${PROXY_PID-}" ]] && kill "${PROXY_PID}" 1>&2 2>/dev/null
[[ -n "${PROXY_PORT_FILE-}" ]] && rm -f ${PROXY_PORT_FILE}
PROXY_PID=
PROXY_PORT=
PROXY_PORT_FILE=
}
# Starts "kubect proxy" to test the client proxy. $1: api_prefix
function start-proxy()
{
stop-proxy
PROXY_PORT_FILE=$(mktemp proxy-port.out.XXXXX)
kube::log::status "Starting kubectl proxy on random port; output file in ${PROXY_PORT_FILE}; args: ${1-}"
if [ $# -eq 0 ]; then
kubectl proxy --port=0 --www=. 1>${PROXY_PORT_FILE} 2>&1 &
else
kubectl proxy --port=0 --www=. --api-prefix="$1" 1>${PROXY_PORT_FILE} 2>&1 &
fi
PROXY_PID=$!
PROXY_PORT=
local attempts=0
while [[ -z ${PROXY_PORT} ]]; do
if (( ${attempts} > 9 )); then
kill "${PROXY_PID}"
kube::log::error_exit "Couldn't start proxy. Failed to read port after ${attempts} tries. Got: $(cat ${PROXY_PORT_FILE})"
fi
sleep .5
kube::log::status "Attempt ${attempts} to read ${PROXY_PORT_FILE}..."
PROXY_PORT=$(sed 's/.*Starting to serve on 127.0.0.1:\([0-9]*\)$/\1/'< ${PROXY_PORT_FILE})
attempts=$((attempts+1))
done
kube::log::status "kubectl proxy running on port ${PROXY_PORT}"
# We try checking kubectl proxy 30 times with 1s delays to avoid occasional
# failures.
if [ $# -eq 0 ]; then
kube::util::wait_for_url "http://127.0.0.1:${PROXY_PORT}/healthz" "kubectl proxy" 1 30
else
kube::util::wait_for_url "http://127.0.0.1:${PROXY_PORT}/$1/healthz" "kubectl proxy --api-prefix=$1" 1 30
fi
}
function cleanup()
{
[[ -n "${APISERVER_PID-}" ]] && kill "${APISERVER_PID}" 1>&2 2>/dev/null
[[ -n "${CTLRMGR_PID-}" ]] && kill "${CTLRMGR_PID}" 1>&2 2>/dev/null
[[ -n "${KUBELET_PID-}" ]] && kill "${KUBELET_PID}" 1>&2 2>/dev/null
stop-proxy
kube::etcd::cleanup
rm -rf "${KUBE_TEMP}"
kube::log::status "Clean up complete"
}
# Executes curl against the proxy. $1 is the path to use, $2 is the desired
# return code. Prints a helpful message on failure.
function check-curl-proxy-code()
{
local status
local -r address=$1
local -r desired=$2
local -r full_address="${PROXY_HOST}:${PROXY_PORT}${address}"
status=$(curl -w "%{http_code}" --silent --output /dev/null "${full_address}")
if [ "${status}" == "${desired}" ]; then
return 0
fi
echo "For address ${full_address}, got ${status} but wanted ${desired}"
return 1
}
# TODO: Remove this function when we do the retry inside the kubectl commands. See #15333.
function kubectl-with-retry()
{
ERROR_FILE="${KUBE_TEMP}/kubectl-error"
for count in $(seq 0 3); do
kubectl "$@" 2> ${ERROR_FILE} || true
if grep -q "the object has been modified" "${ERROR_FILE}"; then
kube::log::status "retry $1, error: $(cat ${ERROR_FILE})"
rm "${ERROR_FILE}"
sleep $((2**count))
else
rm "${ERROR_FILE}"
break
fi
done
}
kube::util::trap_add cleanup EXIT SIGINT
kube::util::ensure-temp-dir
kube::etcd::start
ETCD_HOST=${ETCD_HOST:-127.0.0.1}
ETCD_PORT=${ETCD_PORT:-4001}
API_PORT=${API_PORT:-8080}
API_HOST=${API_HOST:-127.0.0.1}
KUBELET_PORT=${KUBELET_PORT:-10250}
KUBELET_HEALTHZ_PORT=${KUBELET_HEALTHZ_PORT:-10248}
CTLRMGR_PORT=${CTLRMGR_PORT:-10252}
PROXY_HOST=127.0.0.1 # kubectl only serves on localhost.
# ensure ~/.kube/config isn't loaded by tests
HOME="${KUBE_TEMP}"
# Check kubectl
kube::log::status "Running kubectl with no options"
"${KUBE_OUTPUT_HOSTBIN}/kubectl"
kube::log::status "Starting kubelet in masterless mode"
"${KUBE_OUTPUT_HOSTBIN}/kubelet" \
--really-crash-for-testing=true \
--root-dir=/tmp/kubelet.$$ \
--cert-dir="${TMPDIR:-/tmp/}" \
--docker-endpoint="fake://" \
--hostname-override="127.0.0.1" \
--address="127.0.0.1" \
--port="$KUBELET_PORT" \
--healthz-port="${KUBELET_HEALTHZ_PORT}" 1>&2 &
KUBELET_PID=$!
kube::util::wait_for_url "http://127.0.0.1:${KUBELET_HEALTHZ_PORT}/healthz" "kubelet(masterless)"
kill ${KUBELET_PID} 1>&2 2>/dev/null
kube::log::status "Starting kubelet in masterful mode"
"${KUBE_OUTPUT_HOSTBIN}/kubelet" \
--really-crash-for-testing=true \
--root-dir=/tmp/kubelet.$$ \
--cert-dir="${TMPDIR:-/tmp/}" \
--docker-endpoint="fake://" \
--hostname-override="127.0.0.1" \
--address="127.0.0.1" \
--api-servers="${API_HOST}:${API_PORT}" \
--port="$KUBELET_PORT" \
--healthz-port="${KUBELET_HEALTHZ_PORT}" 1>&2 &
KUBELET_PID=$!
kube::util::wait_for_url "http://127.0.0.1:${KUBELET_HEALTHZ_PORT}/healthz" "kubelet"
# Start kube-apiserver
kube::log::status "Starting kube-apiserver"
# Admission Controllers to invoke prior to persisting objects in cluster
ADMISSION_CONTROL="NamespaceLifecycle,LimitRanger,ResourceQuota"
KUBE_API_VERSIONS="v1,autoscaling/v1,batch/v1,extensions/v1beta1" "${KUBE_OUTPUT_HOSTBIN}/kube-apiserver" \
--address="127.0.0.1" \
--public-address-override="127.0.0.1" \
--port="${API_PORT}" \
--admission-control="${ADMISSION_CONTROL}" \
--etcd-servers="http://${ETCD_HOST}:${ETCD_PORT}" \
--public-address-override="127.0.0.1" \
--kubelet-port=${KUBELET_PORT} \
--runtime-config=api/v1 \
--cert-dir="${TMPDIR:-/tmp/}" \
--service-cluster-ip-range="10.0.0.0/24" 1>&2 &
APISERVER_PID=$!
kube::util::wait_for_url "http://127.0.0.1:${API_PORT}/healthz" "apiserver"
# Start controller manager
kube::log::status "Starting controller-manager"
"${KUBE_OUTPUT_HOSTBIN}/kube-controller-manager" \
--port="${CTLRMGR_PORT}" \
--master="127.0.0.1:${API_PORT}" 1>&2 &
CTLRMGR_PID=$!
kube::util::wait_for_url "http://127.0.0.1:${CTLRMGR_PORT}/healthz" "controller-manager"
kube::util::wait_for_url "http://127.0.0.1:${API_PORT}/api/v1/nodes/127.0.0.1" "apiserver(nodes)"
# Expose kubectl directly for readability
PATH="${KUBE_OUTPUT_HOSTBIN}":$PATH
kube::log::status "Checking kubectl version"
kubectl version
runTests() {
version="$1"
echo "Testing api version: $1"
if [[ -z "${version}" ]]; then
kube_flags=(
-s "http://127.0.0.1:${API_PORT}"
--match-server-version
)
[ "$(kubectl get nodes -o go-template='{{ .apiVersion }}' "${kube_flags[@]}")" == "v1" ]
else
kube_flags=(
-s "http://127.0.0.1:${API_PORT}"
--match-server-version
--api-version="${version}"
)
[ "$(kubectl get nodes -o go-template='{{ .apiVersion }}' "${kube_flags[@]}")" == "${version}" ]
fi
id_field=".metadata.name"
labels_field=".metadata.labels"
annotations_field=".metadata.annotations"
service_selector_field=".spec.selector"
rc_replicas_field=".spec.replicas"
rc_status_replicas_field=".status.replicas"
rc_container_image_field=".spec.template.spec.containers"
rs_replicas_field=".spec.replicas"
port_field="(index .spec.ports 0).port"
port_name="(index .spec.ports 0).name"
second_port_field="(index .spec.ports 1).port"
second_port_name="(index .spec.ports 1).name"
image_field="(index .spec.containers 0).image"
hpa_min_field=".spec.minReplicas"
hpa_max_field=".spec.maxReplicas"
hpa_cpu_field=".spec.cpuUtilization.targetPercentage"
job_parallelism_field=".spec.parallelism"
deployment_replicas=".spec.replicas"
secret_data=".data"
secret_type=".type"
deployment_image_field="(index .spec.template.spec.containers 0).image"
change_cause_annotation='.*kubernetes.io/change-cause.*'
# Passing no arguments to create is an error
! kubectl create
#######################
# kubectl local proxy #
#######################
# Make sure the UI can be proxied
start-proxy
check-curl-proxy-code /ui 301
check-curl-proxy-code /metrics 200
check-curl-proxy-code /api/ui 404
if [[ -n "${version}" ]]; then
check-curl-proxy-code /api/${version}/namespaces 200
fi
check-curl-proxy-code /static/ 200
stop-proxy
# Make sure the in-development api is accessible by default
start-proxy
check-curl-proxy-code /apis 200
check-curl-proxy-code /apis/extensions/ 200
stop-proxy
# Custom paths let you see everything.
start-proxy /custom
check-curl-proxy-code /custom/ui 301
check-curl-proxy-code /custom/metrics 200
if [[ -n "${version}" ]]; then
check-curl-proxy-code /custom/api/${version}/namespaces 200
fi
stop-proxy
#########################
# RESTMapper evaluation #
#########################
kube::log::status "Testing RESTMapper"
RESTMAPPER_ERROR_FILE="${KUBE_TEMP}/restmapper-error"
### Non-existent resource type should give a recognizeable error
# Pre-condition: None
# Command
kubectl get "${kube_flags[@]}" unknownresourcetype 2>${RESTMAPPER_ERROR_FILE} || true
if grep -q "the server doesn't have a resource type" "${RESTMAPPER_ERROR_FILE}"; then
kube::log::status "\"kubectl get unknownresourcetype\" returns error as expected: $(cat ${RESTMAPPER_ERROR_FILE})"
else
kube::log::status "\"kubectl get unknownresourcetype\" returns unexpected error or non-error: $(cat ${RESTMAPPER_ERROR_FILE})"
exit 1
fi
rm "${RESTMAPPER_ERROR_FILE}"
# Post-condition: None
###########################
# POD creation / deletion #
###########################
kube::log::status "Testing kubectl(${version}:pods)"
### Create POD valid-pod from JSON
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create "${kube_flags[@]}" -f docs/admin/limitrange/valid-pod.yaml
# Post-condition: valid-pod POD is created
kubectl get "${kube_flags[@]}" pods -o json
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
kube::test::get_object_assert 'pod valid-pod' "{{$id_field}}" 'valid-pod'
kube::test::get_object_assert 'pod/valid-pod' "{{$id_field}}" 'valid-pod'
kube::test::get_object_assert 'pods/valid-pod' "{{$id_field}}" 'valid-pod'
# Repeat above test using jsonpath template
kube::test::get_object_jsonpath_assert pods "{.items[*]$id_field}" 'valid-pod'
kube::test::get_object_jsonpath_assert 'pod valid-pod' "{$id_field}" 'valid-pod'
kube::test::get_object_jsonpath_assert 'pod/valid-pod' "{$id_field}" 'valid-pod'
kube::test::get_object_jsonpath_assert 'pods/valid-pod' "{$id_field}" 'valid-pod'
# Describe command should print detailed information
kube::test::describe_object_assert pods 'valid-pod' "Name:" "Image:" "Node:" "Labels:" "Status:" "Controllers"
# Describe command (resource only) should print detailed information
kube::test::describe_resource_assert pods "Name:" "Image:" "Node:" "Labels:" "Status:" "Controllers"
### Validate Export ###
kube::test::get_object_assert 'pods/valid-pod' "{{.metadata.namespace}} {{.metadata.name}}" '<no value> valid-pod' "--export=true"
### Dump current valid-pod POD
output_pod=$(kubectl get pod valid-pod -o yaml --output-version=v1 "${kube_flags[@]}")
### Delete POD valid-pod by id
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
kubectl delete pod valid-pod "${kube_flags[@]}" --grace-period=0
# Post-condition: valid-pod POD doesn't exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
### Create POD valid-pod from dumped YAML
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
echo "${output_pod}" | kubectl create -f - "${kube_flags[@]}"
# Post-condition: valid-pod POD is created
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
### Delete POD valid-pod from JSON
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
kubectl delete -f docs/admin/limitrange/valid-pod.yaml "${kube_flags[@]}" --grace-period=0
# Post-condition: valid-pod POD doesn't exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
### Create POD redis-master from JSON
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/admin/limitrange/valid-pod.yaml "${kube_flags[@]}"
# Post-condition: valid-pod POD is created
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
### Delete POD valid-pod with label
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert "pods -l'name in (valid-pod)'" '{{range.items}}{{$id_field}}:{{end}}' 'valid-pod:'
# Command
kubectl delete pods -l'name in (valid-pod)' "${kube_flags[@]}" --grace-period=0
# Post-condition: valid-pod POD doesn't exist
kube::test::get_object_assert "pods -l'name in (valid-pod)'" '{{range.items}}{{$id_field}}:{{end}}' ''
### Create POD valid-pod from JSON
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/admin/limitrange/valid-pod.yaml "${kube_flags[@]}"
# Post-condition: valid-pod POD is created
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
### Delete PODs with no parameter mustn't kill everything
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
! kubectl delete pods "${kube_flags[@]}"
# Post-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
### Delete PODs with --all and a label selector is not permitted
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
! kubectl delete --all pods -l'name in (valid-pod)' "${kube_flags[@]}"
# Post-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
### Delete all PODs
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
kubectl delete --all pods "${kube_flags[@]}" --grace-period=0 # --all remove all the pods
# Post-condition: no POD exists
kube::test::get_object_assert "pods -l'name in (valid-pod)'" '{{range.items}}{{$id_field}}:{{end}}' ''
### Create two PODs
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/admin/limitrange/valid-pod.yaml "${kube_flags[@]}"
kubectl create -f examples/redis/redis-proxy.yaml "${kube_flags[@]}"
# Post-condition: valid-pod and redis-proxy PODs are created
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'redis-proxy:valid-pod:'
### Delete multiple PODs at once
# Pre-condition: valid-pod and redis-proxy PODs exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'redis-proxy:valid-pod:'
# Command
kubectl delete pods valid-pod redis-proxy "${kube_flags[@]}" --grace-period=0 # delete multiple pods at once
# Post-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
### Create valid-pod POD
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/admin/limitrange/valid-pod.yaml "${kube_flags[@]}"
# Post-condition: valid-pod POD is created
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
### Label the valid-pod POD
# Pre-condition: valid-pod is not labelled
kube::test::get_object_assert 'pod valid-pod' "{{range$labels_field}}{{.}}:{{end}}" 'valid-pod:'
# Command
kubectl label pods valid-pod new-name=new-valid-pod "${kube_flags[@]}"
# Post-condition: valid-pod is labelled
kube::test::get_object_assert 'pod valid-pod' "{{range$labels_field}}{{.}}:{{end}}" 'valid-pod:new-valid-pod:'
### Delete POD by label
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
kubectl delete pods -lnew-name=new-valid-pod --grace-period=0 "${kube_flags[@]}"
# Post-condition: valid-pod POD doesn't exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
### Create valid-pod POD
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/admin/limitrange/valid-pod.yaml "${kube_flags[@]}"
# Post-condition: valid-pod POD is created
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
## Patch pod can change image
# Command
kubectl patch "${kube_flags[@]}" pod valid-pod --record -p='{"spec":{"containers":[{"name": "kubernetes-serve-hostname", "image": "nginx"}]}}'
# Post-condition: valid-pod POD has image nginx
kube::test::get_object_assert pods "{{range.items}}{{$image_field}}:{{end}}" 'nginx:'
# Post-condition: valid-pod has the record annotation
kube::test::get_object_assert pods "{{range.items}}{{$annotations_field}}:{{end}}" "${change_cause_annotation}"
# prove that patch can use different types
kubectl patch "${kube_flags[@]}" pod valid-pod --type="json" -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"nginx2"}]'
# Post-condition: valid-pod POD has image nginx
kube::test::get_object_assert pods "{{range.items}}{{$image_field}}:{{end}}" 'nginx2:'
# prove that patch can use different types
kubectl patch "${kube_flags[@]}" pod valid-pod --type="json" -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"nginx"}]'
# Post-condition: valid-pod POD has image nginx
kube::test::get_object_assert pods "{{range.items}}{{$image_field}}:{{end}}" 'nginx:'
# prove that yaml input works too
YAML_PATCH=$'spec:\n containers:\n - name: kubernetes-serve-hostname\n image: changed-with-yaml\n'
kubectl patch "${kube_flags[@]}" pod valid-pod -p="${YAML_PATCH}"
# Post-condition: valid-pod POD has image nginx
kube::test::get_object_assert pods "{{range.items}}{{$image_field}}:{{end}}" 'changed-with-yaml:'
## Patch pod from JSON can change image
# Command
kubectl patch "${kube_flags[@]}" -f docs/admin/limitrange/valid-pod.yaml -p='{"spec":{"containers":[{"name": "kubernetes-serve-hostname", "image": "kubernetes/pause"}]}}'
# Post-condition: valid-pod POD has image kubernetes/pause
kube::test::get_object_assert pods "{{range.items}}{{$image_field}}:{{end}}" 'kubernetes/pause:'
## If resourceVersion is specified in the patch, it will be treated as a precondition, i.e., if the resourceVersion is different from that is stored in the server, the Patch should be rejected
ERROR_FILE="${KUBE_TEMP}/conflict-error"
## If the resourceVersion is the same as the one stored in the server, the patch will be applied.
# Command
# Needs to retry because other party may change the resource.
for count in $(seq 0 3); do
resourceVersion=$(kubectl get "${kube_flags[@]}" pod valid-pod -o go-template='{{ .metadata.resourceVersion }}')
kubectl patch "${kube_flags[@]}" pod valid-pod -p='{"spec":{"containers":[{"name": "kubernetes-serve-hostname", "image": "nginx"}]},"metadata":{"resourceVersion":"'$resourceVersion'"}}' 2> "${ERROR_FILE}" || true
if grep -q "the object has been modified" "${ERROR_FILE}"; then
kube::log::status "retry $1, error: $(cat ${ERROR_FILE})"
rm "${ERROR_FILE}"
sleep $((2**count))
else
rm "${ERROR_FILE}"
kube::test::get_object_assert pods "{{range.items}}{{$image_field}}:{{end}}" 'nginx:'
break
fi
done
## If the resourceVersion is the different from the one stored in the server, the patch will be rejected.
resourceVersion=$(kubectl get "${kube_flags[@]}" pod valid-pod -o go-template='{{ .metadata.resourceVersion }}')
((resourceVersion+=100))
# Command
kubectl patch "${kube_flags[@]}" pod valid-pod -p='{"spec":{"containers":[{"name": "kubernetes-serve-hostname", "image": "nginx"}]},"metadata":{"resourceVersion":"'$resourceVersion'"}}' 2> "${ERROR_FILE}" || true
# Post-condition: should get an error reporting the conflict
if grep -q "please apply your changes to the latest version and try again" "${ERROR_FILE}"; then
kube::log::status "\"kubectl patch with resourceVersion $resourceVersion\" returns error as expected: $(cat ${ERROR_FILE})"
else
kube::log::status "\"kubectl patch with resourceVersion $resourceVersion\" returns unexpected error or non-error: $(cat ${ERROR_FILE})"
exit 1
fi
rm "${ERROR_FILE}"
## --force replace pod can change other field, e.g., spec.container.name
# Command
kubectl get "${kube_flags[@]}" pod valid-pod -o json | sed 's/"kubernetes-serve-hostname"/"replaced-k8s-serve-hostname"/g' > /tmp/tmp-valid-pod.json
kubectl replace "${kube_flags[@]}" --force -f /tmp/tmp-valid-pod.json
# Post-condition: spec.container.name = "replaced-k8s-serve-hostname"
kube::test::get_object_assert 'pod valid-pod' "{{(index .spec.containers 0).name}}" 'replaced-k8s-serve-hostname'
#cleaning
rm /tmp/tmp-valid-pod.json
## replace of a cluster scoped resource can succeed
# Pre-condition: a node exists
kubectl create -f - "${kube_flags[@]}" << __EOF__
{
"kind": "Node",
"apiVersion": "v1",
"metadata": {
"name": "node-${version}-test"
}
}
__EOF__
kubectl replace -f - "${kube_flags[@]}" << __EOF__
{
"kind": "Node",
"apiVersion": "v1",
"metadata": {
"name": "node-${version}-test",
"annotations": {"a":"b"}
}
}
__EOF__
# Post-condition: the node command succeeds
kube::test::get_object_assert "node node-${version}-test" "{{.metadata.annotations.a}}" 'b'
kubectl delete node node-${version}-test
## kubectl edit can update the image field of a POD. tmp-editor.sh is a fake editor
echo -e '#!/bin/bash\nsed -i "s/nginx/gcr.io\/google_containers\/serve_hostname/g" $1' > /tmp/tmp-editor.sh
chmod +x /tmp/tmp-editor.sh
EDITOR=/tmp/tmp-editor.sh kubectl edit "${kube_flags[@]}" pods/valid-pod
# Post-condition: valid-pod POD has image gcr.io/google_containers/serve_hostname
kube::test::get_object_assert pods "{{range.items}}{{$image_field}}:{{end}}" 'gcr.io/google_containers/serve_hostname:'
# cleaning
rm /tmp/tmp-editor.sh
[ "$(EDITOR=cat kubectl edit pod/valid-pod 2>&1 | grep 'Edit cancelled')" ]
[ "$(EDITOR=cat kubectl edit pod/valid-pod | grep 'name: valid-pod')" ]
[ "$(EDITOR=cat kubectl edit --windows-line-endings pod/valid-pod | file - | grep CRLF)" ]
[ ! "$(EDITOR=cat kubectl edit --windows-line-endings=false pod/valid-pod | file - | grep CRLF)" ]
### Overwriting an existing label is not permitted
# Pre-condition: name is valid-pod
kube::test::get_object_assert 'pod valid-pod' "{{${labels_field}.name}}" 'valid-pod'
# Command
! kubectl label pods valid-pod name=valid-pod-super-sayan "${kube_flags[@]}"
# Post-condition: name is still valid-pod
kube::test::get_object_assert 'pod valid-pod' "{{${labels_field}.name}}" 'valid-pod'
### --overwrite must be used to overwrite existing label, can be applied to all resources
# Pre-condition: name is valid-pod
kube::test::get_object_assert 'pod valid-pod' "{{${labels_field}.name}}" 'valid-pod'
# Command
kubectl label --overwrite pods --all name=valid-pod-super-sayan "${kube_flags[@]}"
# Post-condition: name is valid-pod-super-sayan
kube::test::get_object_assert 'pod valid-pod' "{{${labels_field}.name}}" 'valid-pod-super-sayan'
### Delete POD by label
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
kubectl delete pods -l'name in (valid-pod-super-sayan)' --grace-period=0 "${kube_flags[@]}"
# Post-condition: valid-pod POD doesn't exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
### Create two PODs from 1 yaml file
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/user-guide/multi-pod.yaml "${kube_flags[@]}"
# Post-condition: valid-pod and redis-proxy PODs exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'redis-master:redis-proxy:'
### Delete two PODs from 1 yaml file
# Pre-condition: redis-master and redis-proxy PODs exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'redis-master:redis-proxy:'
# Command
kubectl delete -f docs/user-guide/multi-pod.yaml "${kube_flags[@]}"
# Post-condition: no PODs exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
## kubectl apply should update configuration annotations only if apply is already called
## 1. kubectl create doesn't set the annotation
# Pre-Condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command: create a pod "test-pod"
kubectl create -f hack/testdata/pod.yaml "${kube_flags[@]}"
# Post-Condition: pod "test-pod" is created
kube::test::get_object_assert 'pods test-pod' "{{${labels_field}.name}}" 'test-pod-label'
# Post-Condition: pod "test-pod" doesn't have configuration annotation
! [[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
## 2. kubectl replace doesn't set the annotation
kubectl get pods test-pod -o yaml "${kube_flags[@]}" | sed 's/test-pod-label/test-pod-replaced/g' > "${KUBE_TEMP}"/test-pod-replace.yaml
# Command: replace the pod "test-pod"
kubectl replace -f "${KUBE_TEMP}"/test-pod-replace.yaml "${kube_flags[@]}"
# Post-Condition: pod "test-pod" is replaced
kube::test::get_object_assert 'pods test-pod' "{{${labels_field}.name}}" 'test-pod-replaced'
# Post-Condition: pod "test-pod" doesn't have configuration annotation
! [[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
## 3. kubectl apply does set the annotation
# Command: apply the pod "test-pod"
kubectl apply -f hack/testdata/pod-apply.yaml "${kube_flags[@]}"
# Post-Condition: pod "test-pod" is applied
kube::test::get_object_assert 'pods test-pod' "{{${labels_field}.name}}" 'test-pod-applied'
# Post-Condition: pod "test-pod" has configuration annotation
[[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration > "${KUBE_TEMP}"/annotation-configuration
## 4. kubectl replace updates an existing annotation
kubectl get pods test-pod -o yaml "${kube_flags[@]}" | sed 's/test-pod-applied/test-pod-replaced/g' > "${KUBE_TEMP}"/test-pod-replace.yaml
# Command: replace the pod "test-pod"
kubectl replace -f "${KUBE_TEMP}"/test-pod-replace.yaml "${kube_flags[@]}"
# Post-Condition: pod "test-pod" is replaced
kube::test::get_object_assert 'pods test-pod' "{{${labels_field}.name}}" 'test-pod-replaced'
# Post-Condition: pod "test-pod" has configuration annotation, and it's updated (different from the annotation when it's applied)
[[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration > "${KUBE_TEMP}"/annotation-configuration-replaced
! [[ $(diff -q "${KUBE_TEMP}"/annotation-configuration "${KUBE_TEMP}"/annotation-configuration-replaced > /dev/null) ]]
# Clean up
rm "${KUBE_TEMP}"/test-pod-replace.yaml "${KUBE_TEMP}"/annotation-configuration "${KUBE_TEMP}"/annotation-configuration-replaced
kubectl delete pods test-pod "${kube_flags[@]}"
## Configuration annotations should be set when --save-config is enabled
## 1. kubectl create --save-config should generate configuration annotation
# Pre-Condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command: create a pod "test-pod"
kubectl create -f hack/testdata/pod.yaml --save-config "${kube_flags[@]}"
# Post-Condition: pod "test-pod" has configuration annotation
[[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Clean up
kubectl delete -f hack/testdata/pod.yaml "${kube_flags[@]}"
## 2. kubectl edit --save-config should generate configuration annotation
# Pre-Condition: no POD exists, then create pod "test-pod", which shouldn't have configuration annotation
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
kubectl create -f hack/testdata/pod.yaml "${kube_flags[@]}"
! [[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Command: edit the pod "test-pod"
temp_editor="${KUBE_TEMP}/tmp-editor.sh"
echo -e '#!/bin/bash\nsed -i "s/test-pod-label/test-pod-label-edited/g" $@' > "${temp_editor}"
chmod +x "${temp_editor}"
EDITOR=${temp_editor} kubectl edit pod test-pod --save-config "${kube_flags[@]}"
# Post-Condition: pod "test-pod" has configuration annotation
[[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Clean up
kubectl delete -f hack/testdata/pod.yaml "${kube_flags[@]}"
## 3. kubectl replace --save-config should generate configuration annotation
# Pre-Condition: no POD exists, then create pod "test-pod", which shouldn't have configuration annotation
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
kubectl create -f hack/testdata/pod.yaml "${kube_flags[@]}"
! [[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Command: replace the pod "test-pod"
kubectl replace -f hack/testdata/pod.yaml --save-config "${kube_flags[@]}"
# Post-Condition: pod "test-pod" has configuration annotation
[[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Clean up
kubectl delete -f hack/testdata/pod.yaml "${kube_flags[@]}"
## 4. kubectl run --save-config should generate configuration annotation
# Pre-Condition: no RC exists
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
# Command: create the rc "nginx" with image nginx
kubectl run nginx --image=nginx --save-config --generator=run/v1 "${kube_flags[@]}"
# Post-Condition: rc "nginx" has configuration annotation
[[ "$(kubectl get rc nginx -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
## 5. kubectl expose --save-config should generate configuration annotation
# Pre-Condition: no service exists
kube::test::get_object_assert svc "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:'
# Command: expose the rc "nginx"
kubectl expose rc nginx --save-config --port=80 --target-port=8000 "${kube_flags[@]}"
# Post-Condition: service "nginx" has configuration annotation
[[ "$(kubectl get svc nginx -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Clean up
kubectl delete rc,svc nginx
## 6. kubectl autoscale --save-config should generate configuration annotation
# Pre-Condition: no RC exists, then create the rc "frontend", which shouldn't have configuration annotation
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
kubectl create -f examples/guestbook/frontend-controller.yaml "${kube_flags[@]}"
! [[ "$(kubectl get rc frontend -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Command: autoscale rc "frontend"
kubectl autoscale -f examples/guestbook/frontend-controller.yaml --save-config "${kube_flags[@]}" --max=2
# Post-Condition: hpa "frontend" has configuration annotation
[[ "$(kubectl get hpa frontend -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Clean up
kubectl delete rc,hpa frontend "${kube_flags[@]}"
## kubectl apply should create the resource that doesn't exist yet
# Pre-Condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command: apply a pod "test-pod" (doesn't exist) should create this pod
kubectl apply -f hack/testdata/pod.yaml "${kube_flags[@]}"
# Post-Condition: pod "test-pod" is created
kube::test::get_object_assert 'pods test-pod' "{{${labels_field}.name}}" 'test-pod-label'
# Post-Condition: pod "test-pod" has configuration annotation
[[ "$(kubectl get pods test-pod -o yaml "${kube_flags[@]}" | grep kubectl.kubernetes.io/last-applied-configuration)" ]]
# Clean up
kubectl delete pods test-pod "${kube_flags[@]}"
## kubectl run should create deployments or jobs
# Pre-Condition: no Job exists
kube::test::get_object_assert jobs "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl run pi --generator=job/v1beta1 --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(20)' "${kube_flags[@]}"
# Post-Condition: Job "pi" is created
kube::test::get_object_assert jobs "{{range.items}}{{$id_field}}:{{end}}" 'pi:'
# Clean up
kubectl delete jobs pi "${kube_flags[@]}"
# Post-condition: no pods exist.
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Pre-Condition: no Deployment exists
kube::test::get_object_assert deployment "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl run nginx --image=nginx --generator=deployment/v1beta1 "${kube_flags[@]}"
# Post-Condition: Deployment "nginx" is created
kube::test::get_object_assert deployment "{{range.items}}{{$id_field}}:{{end}}" 'nginx:'
# Clean up
kubectl delete deployment nginx "${kube_flags[@]}"
##############
# Namespaces #
##############
### Create a new namespace
# Pre-condition: only the "default" namespace exists
kube::test::get_object_assert namespaces "{{range.items}}{{$id_field}}:{{end}}" 'default:'
# Command
kubectl create namespace my-namespace
# Post-condition: namespace 'my-namespace' is created.
kube::test::get_object_assert 'namespaces/my-namespace' "{{$id_field}}" 'my-namespace'
# Clean up
kubectl delete namespace my-namespace
##############
# Pods in Namespaces #
##############
### Create a new namespace
# Pre-condition: the other namespace does not exist
kube::test::get_object_assert 'namespaces' '{{range.items}}{{ if eq $id_field \"other\" }}found{{end}}{{end}}:' ':'
# Command
kubectl create namespace other
# Post-condition: namespace 'other' is created.
kube::test::get_object_assert 'namespaces/other' "{{$id_field}}" 'other'
### Create POD valid-pod in specific namespace
# Pre-condition: no POD exists
kube::test::get_object_assert 'pods --namespace=other' "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create "${kube_flags[@]}" --namespace=other -f docs/admin/limitrange/valid-pod.yaml
# Post-condition: valid-pod POD is created
kube::test::get_object_assert 'pods --namespace=other' "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
### Delete POD valid-pod in specific namespace
# Pre-condition: valid-pod POD exists
kube::test::get_object_assert 'pods --namespace=other' "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
kubectl delete "${kube_flags[@]}" pod --namespace=other valid-pod --grace-period=0
# Post-condition: valid-pod POD doesn't exist
kube::test::get_object_assert 'pods --namespace=other' "{{range.items}}{{$id_field}}:{{end}}" ''
# Clean up
kubectl delete namespace other
##############
# Secrets #
##############
### Create a new namespace
# Pre-condition: the test-secrets namespace does not exist
kube::test::get_object_assert 'namespaces' '{{range.items}}{{ if eq $id_field \"test-secrets\" }}found{{end}}{{end}}:' ':'
# Command
kubectl create namespace test-secrets
# Post-condition: namespace 'test-secrets' is created.
kube::test::get_object_assert 'namespaces/test-secrets' "{{$id_field}}" 'test-secrets'
### Create a generic secret in a specific namespace
# Pre-condition: no SECRET exists
kube::test::get_object_assert 'secrets --namespace=test-secrets' "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create secret generic test-secret --from-literal=key1=value1 --type=test-type --namespace=test-secrets
# Post-condition: secret exists and has expected values
kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' "{{$id_field}}" 'test-secret'
kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' "{{$secret_type}}" 'test-type'
[[ "$(kubectl get secret/test-secret --namespace=test-secrets -o yaml "${kube_flags[@]}" | grep 'key1: dmFsdWUx')" ]]
# Clean-up
kubectl delete secret test-secret --namespace=test-secrets
### Create a docker-registry secret in a specific namespace
# Pre-condition: no SECRET exists
kube::test::get_object_assert 'secrets --namespace=test-secrets' "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create secret docker-registry test-secret --docker-username=test-user --docker-password=test-password --docker-email='test-user@test.com' --namespace=test-secrets
# Post-condition: secret exists and has expected values
kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' "{{$id_field}}" 'test-secret'
kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' "{{$secret_type}}" 'kubernetes.io/dockercfg'
[[ "$(kubectl get secret/test-secret --namespace=test-secrets -o yaml "${kube_flags[@]}" | grep '.dockercfg:')" ]]
# Clean-up
kubectl delete secret test-secret --namespace=test-secrets
### Create a secret using output flags
# Pre-condition: no secret exists
kube::test::get_object_assert 'secrets --namespace=test-secrets' "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
[[ "$(kubectl create secret generic test-secret --namespace=test-secrets --from-literal=key1=value1 --output=go-template --template=\"{{.metadata.name}}:\" | grep 'test-secret:')" ]]
## Clean-up
kubectl delete secret test-secret --namespace=test-secrets
# Clean up
kubectl delete namespace test-secrets
######################
# ConfigMap #
######################
kubectl create -f docs/user-guide/configmap/config-map.yaml
kube::test::get_object_assert configmap "{{range.items}}{{$id_field}}{{end}}" 'test-configmap'
kubectl delete configmap test-configmap "${kube_flags[@]}"
### Create a new namespace
# Pre-condition: the test-configmaps namespace does not exist
kube::test::get_object_assert 'namespaces' '{{range.items}}{{ if eq $id_field \"test-configmaps\" }}found{{end}}{{end}}:' ':'
# Command
kubectl create namespace test-configmaps
# Post-condition: namespace 'test-configmaps' is created.
kube::test::get_object_assert 'namespaces/test-configmaps' "{{$id_field}}" 'test-configmaps'
### Create a generic configmap in a specific namespace
# Pre-condition: no configmaps namespace exists
kube::test::get_object_assert 'configmaps --namespace=test-configmaps' "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create configmap test-configmap --from-literal=key1=value1 --namespace=test-configmaps
# Post-condition: configmap exists and has expected values
kube::test::get_object_assert 'configmap/test-configmap --namespace=test-configmaps' "{{$id_field}}" 'test-configmap'
[[ "$(kubectl get configmap/test-configmap --namespace=test-configmaps -o yaml "${kube_flags[@]}" | grep 'key1: value1')" ]]
# Clean-up
kubectl delete configmap test-configmap --namespace=test-configmaps
kubectl delete namespace test-configmaps
#################
# Pod templates #
#################
### Create PODTEMPLATE
# Pre-condition: no PODTEMPLATE
kube::test::get_object_assert podtemplates "{{range.items}}{{.metadata.name}}:{{end}}" ''
# Command
kubectl create -f docs/user-guide/walkthrough/podtemplate.json "${kube_flags[@]}"
# Post-condition: nginx PODTEMPLATE is available
kube::test::get_object_assert podtemplates "{{range.items}}{{.metadata.name}}:{{end}}" 'nginx:'
### Printing pod templates works
kubectl get podtemplates "${kube_flags[@]}"
[[ "$(kubectl get podtemplates -o yaml "${kube_flags[@]}" | grep nginx)" ]]
### Delete nginx pod template by name
# Pre-condition: nginx pod template is available
kube::test::get_object_assert podtemplates "{{range.items}}{{.metadata.name}}:{{end}}" 'nginx:'
# Command
kubectl delete podtemplate nginx "${kube_flags[@]}"
# Post-condition: No templates exist
kube::test::get_object_assert podtemplate "{{range.items}}{{.metadata.name}}:{{end}}" ''
############
# Services #
############
kube::log::status "Testing kubectl(${version}:services)"
### Create redis-master service from JSON
# Pre-condition: Only the default kubernetes services exist
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:'
# Command
kubectl create -f examples/guestbook/redis-master-service.yaml "${kube_flags[@]}"
# Post-condition: redis-master service exists
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:redis-master:'
# Describe command should print detailed information
kube::test::describe_object_assert services 'redis-master' "Name:" "Labels:" "Selector:" "IP:" "Port:" "Endpoints:" "Session Affinity:"
# Describe command (resource only) should print detailed information
kube::test::describe_resource_assert services "Name:" "Labels:" "Selector:" "IP:" "Port:" "Endpoints:" "Session Affinity:"
### Dump current redis-master service
output_service=$(kubectl get service redis-master -o json --output-version=v1 "${kube_flags[@]}")
### Delete redis-master-service by id
# Pre-condition: redis-master service exists
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:redis-master:'
# Command
kubectl delete service redis-master "${kube_flags[@]}"
# Post-condition: Only the default kubernetes services exist
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:'
### Create redis-master-service from dumped JSON
# Pre-condition: Only the default kubernetes services exist
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:'
# Command
echo "${output_service}" | kubectl create -f - "${kube_flags[@]}"
# Post-condition: redis-master service is created
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:redis-master:'
### Create redis-master-${version}-test service
# Pre-condition: redis-master-service service exists
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:redis-master:'
# Command
kubectl create -f - "${kube_flags[@]}" << __EOF__
{
"kind": "Service",
"apiVersion": "v1",
"metadata": {
"name": "service-${version}-test"
},
"spec": {
"ports": [
{
"protocol": "TCP",
"port": 80,
"targetPort": 80
}
]
}
}
__EOF__
# Post-condition: service-${version}-test service is created
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:redis-master:service-.*-test:'
### Identity
kubectl get service "${kube_flags[@]}" service-${version}-test -o json | kubectl replace "${kube_flags[@]}" -f -
### Delete services by id
# Pre-condition: service-${version}-test exists
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:redis-master:service-.*-test:'
# Command
kubectl delete service redis-master "${kube_flags[@]}"
kubectl delete service "service-${version}-test" "${kube_flags[@]}"
# Post-condition: Only the default kubernetes services exist
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:'
### Create two services
# Pre-condition: Only the default kubernetes services exist
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:'
# Command
kubectl create -f examples/guestbook/redis-master-service.yaml "${kube_flags[@]}"
kubectl create -f examples/guestbook/redis-slave-service.yaml "${kube_flags[@]}"
# Post-condition: redis-master and redis-slave services are created
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:redis-master:redis-slave:'
### Custom columns can be specified
# Pre-condition: generate output using custom columns
output_message=$(kubectl get services -o=custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion 2>&1 "${kube_flags[@]}")
# Post-condition: should contain name column
kube::test::if_has_string "${output_message}" 'redis-master'
### Delete multiple services at once
# Pre-condition: redis-master and redis-slave services exist
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:redis-master:redis-slave:'
# Command
kubectl delete services redis-master redis-slave "${kube_flags[@]}" # delete multiple services at once
# Post-condition: Only the default kubernetes services exist
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:'
###########################
# Replication controllers #
###########################
kube::log::status "Testing kubectl(${version}:replicationcontrollers)"
### Create and stop controller, make sure it doesn't leak pods
# Pre-condition: no replication controller exists
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f examples/guestbook/frontend-controller.yaml "${kube_flags[@]}"
kubectl delete rc frontend "${kube_flags[@]}"
# Post-condition: no pods from frontend controller
kube::test::get_object_assert 'pods -l "name=frontend"' "{{range.items}}{{$id_field}}:{{end}}" ''
### Create replication controller frontend from JSON
# Pre-condition: no replication controller exists
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f examples/guestbook/frontend-controller.yaml "${kube_flags[@]}"
# Post-condition: frontend replication controller is created
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:'
# Describe command should print detailed information
kube::test::describe_object_assert rc 'frontend' "Name:" "Image(s):" "Labels:" "Selector:" "Replicas:" "Pods Status:"
# Describe command (resource only) should print detailed information
kube::test::describe_resource_assert rc "Name:" "Name:" "Image(s):" "Labels:" "Selector:" "Replicas:" "Pods Status:"
### Scale replication controller frontend with current-replicas and replicas
# Pre-condition: 3 replicas
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '3'
# Command
kubectl scale --current-replicas=3 --replicas=2 replicationcontrollers frontend "${kube_flags[@]}"
# Post-condition: 2 replicas
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'
### Scale replication controller frontend with (wrong) current-replicas and replicas
# Pre-condition: 2 replicas
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'
# Command
! kubectl scale --current-replicas=3 --replicas=2 replicationcontrollers frontend "${kube_flags[@]}"
# Post-condition: nothing changed
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'
### Scale replication controller frontend with replicas only
# Pre-condition: 2 replicas
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'
# Command
kubectl scale --replicas=3 replicationcontrollers frontend "${kube_flags[@]}"
# Post-condition: 3 replicas
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '3'
### Scale replication controller from JSON with replicas only
# Pre-condition: 3 replicas
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '3'
# Command
kubectl scale --replicas=2 -f examples/guestbook/frontend-controller.yaml "${kube_flags[@]}"
# Post-condition: 2 replicas
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'
# Clean-up
kubectl delete rc frontend "${kube_flags[@]}"
### Scale multiple replication controllers
kubectl create -f examples/guestbook/redis-master-controller.yaml "${kube_flags[@]}"
kubectl create -f examples/guestbook/redis-slave-controller.yaml "${kube_flags[@]}"
# Command
kubectl scale rc/redis-master rc/redis-slave --replicas=4 "${kube_flags[@]}"
# Post-condition: 4 replicas each
kube::test::get_object_assert 'rc redis-master' "{{$rc_replicas_field}}" '4'
kube::test::get_object_assert 'rc redis-slave' "{{$rc_replicas_field}}" '4'
# Clean-up
kubectl delete rc redis-{master,slave} "${kube_flags[@]}"
### Scale a job
kubectl create -f docs/user-guide/job.yaml "${kube_flags[@]}"
# Command
kubectl scale --replicas=2 job/pi
# Post-condition: 2 replicas for pi
kube::test::get_object_assert 'job pi' "{{$job_parallelism_field}}" '2'
# Clean-up
kubectl delete job/pi "${kube_flags[@]}"
### Scale a deployment
kubectl create -f docs/user-guide/deployment.yaml "${kube_flags[@]}"
# Command
kubectl scale --current-replicas=3 --replicas=1 deployment/nginx-deployment
# Post-condition: 1 replica for nginx-deployment
kube::test::get_object_assert 'deployment nginx-deployment' "{{$deployment_replicas}}" '1'
# Clean-up
kubectl delete deployment/nginx-deployment "${kube_flags[@]}"
### Expose a deployment as a service
kubectl create -f docs/user-guide/deployment.yaml "${kube_flags[@]}"
# Pre-condition: 3 replicas
kube::test::get_object_assert 'deployment nginx-deployment' "{{$deployment_replicas}}" '3'
# Command
kubectl expose deployment/nginx-deployment
# Post-condition: service exists and exposes deployment port (80)
kube::test::get_object_assert 'service nginx-deployment' "{{$port_field}}" '80'
# Clean-up
kubectl delete deployment/nginx-deployment service/nginx-deployment "${kube_flags[@]}"
### Expose replication controller as service
kubectl create -f examples/guestbook/frontend-controller.yaml "${kube_flags[@]}"
# Pre-condition: 3 replicas
kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '3'
# Command
kubectl expose rc frontend --port=80 "${kube_flags[@]}"
# Post-condition: service exists and the port is unnamed
kube::test::get_object_assert 'service frontend' "{{$port_name}} {{$port_field}}" '<no value> 80'
# Command
kubectl expose service frontend --port=443 --name=frontend-2 "${kube_flags[@]}"
# Post-condition: service exists and the port is unnamed
kube::test::get_object_assert 'service frontend-2' "{{$port_name}} {{$port_field}}" '<no value> 443'
# Command
kubectl create -f docs/admin/limitrange/valid-pod.yaml "${kube_flags[@]}"
kubectl expose pod valid-pod --port=444 --name=frontend-3 "${kube_flags[@]}"
# Post-condition: service exists and the port is unnamed
kube::test::get_object_assert 'service frontend-3' "{{$port_name}} {{$port_field}}" '<no value> 444'
# Create a service using service/v1 generator
kubectl expose rc frontend --port=80 --name=frontend-4 --generator=service/v1 "${kube_flags[@]}"
# Post-condition: service exists and the port is named default.
kube::test::get_object_assert 'service frontend-4' "{{$port_name}} {{$port_field}}" 'default 80'
# Verify that expose service works without specifying a port.
kubectl expose service frontend --name=frontend-5 "${kube_flags[@]}"
# Post-condition: service exists with the same port as the original service.
kube::test::get_object_assert 'service frontend-5' "{{$port_field}}" '80'
# Cleanup services
kubectl delete pod valid-pod "${kube_flags[@]}"
kubectl delete service frontend{,-2,-3,-4,-5} "${kube_flags[@]}"
### Expose negative invalid resource test
# Pre-condition: don't need
# Command
output_message=$(! kubectl expose nodes 127.0.0.1 2>&1 "${kube_flags[@]}")
# Post-condition: the error message has "cannot expose" string
kube::test::if_has_string "${output_message}" 'cannot expose'
### Try to generate a service with invalid name (exceeding maximum valid size)
# Pre-condition: use --name flag
output_message=$(! kubectl expose -f hack/testdata/pod-with-large-name.yaml --name=invalid-large-service-name --port=8081 2>&1 "${kube_flags[@]}")
# Post-condition: should fail due to invalid name
kube::test::if_has_string "${output_message}" 'metadata.name: Invalid value'
# Pre-condition: default run without --name flag; should succeed by truncating the inherited name
output_message=$(kubectl expose -f hack/testdata/pod-with-large-name.yaml --port=8081 2>&1 "${kube_flags[@]}")
# Post-condition: inherited name from pod has been truncated
kube::test::if_has_string "${output_message}" '\"kubernetes-serve-hostnam\" exposed'
# Clean-up
kubectl delete svc kubernetes-serve-hostnam "${kube_flags[@]}"
### Expose multiport object as a new service
# Pre-condition: don't use --port flag
output_message=$(kubectl expose -f docs/admin/high-availability/etcd.yaml --selector=test=etcd 2>&1 "${kube_flags[@]}")
# Post-condition: expose succeeded
kube::test::if_has_string "${output_message}" '\"etcd-server\" exposed'
# Post-condition: generated service has both ports from the exposed pod
kube::test::get_object_assert 'service etcd-server' "{{$port_name}} {{$port_field}}" 'port-1 2380'
kube::test::get_object_assert 'service etcd-server' "{{$second_port_name}} {{$second_port_field}}" 'port-2 4001'
# Clean-up
kubectl delete svc etcd-server "${kube_flags[@]}"
### Delete replication controller with id
# Pre-condition: frontend replication controller exists
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:'
# Command
kubectl delete rc frontend "${kube_flags[@]}"
# Post-condition: no replication controller exists
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
### Create two replication controllers
# Pre-condition: no replication controller exists
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f examples/guestbook/frontend-controller.yaml "${kube_flags[@]}"
kubectl create -f examples/guestbook/redis-slave-controller.yaml "${kube_flags[@]}"
# Post-condition: frontend and redis-slave
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:redis-slave:'
### Delete multiple controllers at once
# Pre-condition: frontend and redis-slave
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:redis-slave:'
# Command
kubectl delete rc frontend redis-slave "${kube_flags[@]}" # delete multiple controllers at once
# Post-condition: no replication controller exists
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
### Auto scale replication controller
# Pre-condition: no replication controller exists
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f examples/guestbook/frontend-controller.yaml "${kube_flags[@]}"
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:'
# autoscale 1~2 pods, CPU utilization 70%, rc specified by file
kubectl autoscale -f examples/guestbook/frontend-controller.yaml "${kube_flags[@]}" --max=2 --cpu-percent=70
kube::test::get_object_assert 'hpa frontend' "{{$hpa_min_field}} {{$hpa_max_field}} {{$hpa_cpu_field}}" '1 2 70'
kubectl delete hpa frontend "${kube_flags[@]}"
# autoscale 2~3 pods, default CPU utilization (80%), rc specified by name
kubectl autoscale rc frontend "${kube_flags[@]}" --min=2 --max=3
kube::test::get_object_assert 'hpa frontend' "{{$hpa_min_field}} {{$hpa_max_field}} {{$hpa_cpu_field}}" '2 3 80'
kubectl delete hpa frontend "${kube_flags[@]}"
# autoscale without specifying --max should fail
! kubectl autoscale rc frontend "${kube_flags[@]}"
# Clean up
kubectl delete rc frontend "${kube_flags[@]}"
### Auto scale deployment
# Pre-condition: no deployment exists
kube::test::get_object_assert deployment "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/user-guide/deployment.yaml "${kube_flags[@]}"
kube::test::get_object_assert deployment "{{range.items}}{{$id_field}}:{{end}}" 'nginx-deployment:'
# autoscale 2~3 pods, default CPU utilization (80%)
kubectl-with-retry autoscale deployment nginx-deployment "${kube_flags[@]}" --min=2 --max=3
kube::test::get_object_assert 'hpa nginx-deployment' "{{$hpa_min_field}} {{$hpa_max_field}} {{$hpa_cpu_field}}" '2 3 80'
# Clean up
kubectl delete hpa nginx-deployment "${kube_flags[@]}"
kubectl delete deployment nginx-deployment "${kube_flags[@]}"
### Rollback a deployment
# Pre-condition: no deployment exists
kube::test::get_object_assert deployment "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
# Create a deployment (revision 1)
kubectl create -f docs/user-guide/deployment.yaml "${kube_flags[@]}"
kube::test::get_object_assert deployment "{{range.items}}{{$id_field}}:{{end}}" 'nginx-deployment:'
kube::test::get_object_assert deployment "{{range.items}}{{$deployment_image_field}}:{{end}}" 'nginx:'
# Rollback to revision 1 - should be no-op
kubectl rollout undo deployment nginx-deployment --to-revision=1 "${kube_flags[@]}"
kube::test::get_object_assert deployment "{{range.items}}{{$deployment_image_field}}:{{end}}" 'nginx:'
# Update the deployment (revision 2)
kubectl apply -f hack/testdata/deployment-revision2.yaml "${kube_flags[@]}"
kube::test::get_object_assert deployment "{{range.items}}{{$deployment_image_field}}:{{end}}" 'nginx:latest:'
# Rollback to revision 1
kubectl rollout undo deployment nginx-deployment --to-revision=1 "${kube_flags[@]}"
sleep 1
kube::test::get_object_assert deployment "{{range.items}}{{$deployment_image_field}}:{{end}}" 'nginx:'
# Rollback to revision 1000000 - should be no-op
kubectl rollout undo deployment nginx-deployment --to-revision=1000000 "${kube_flags[@]}"
kube::test::get_object_assert deployment "{{range.items}}{{$deployment_image_field}}:{{end}}" 'nginx:'
# Rollback to last revision
kubectl rollout undo deployment nginx-deployment "${kube_flags[@]}"
sleep 1
kube::test::get_object_assert deployment "{{range.items}}{{$deployment_image_field}}:{{end}}" 'nginx:latest:'
# Clean up
kubectl delete deployment nginx-deployment "${kube_flags[@]}"
kubectl delete rs -l pod-template-hash "${kube_flags[@]}"
######################
# Replica Sets #
######################
kube::log::status "Testing kubectl(${version}:replicasets)"
### Create and stop a replica set, make sure it doesn't leak pods
# Pre-condition: no replica set exists
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/user-guide/replicaset/frontend.yaml "${kube_flags[@]}"
kubectl delete rs frontend "${kube_flags[@]}"
# Post-condition: no pods from frontend replica set
kube::test::get_object_assert 'pods -l "tier=frontend"' "{{range.items}}{{$id_field}}:{{end}}" ''
### Create replica set frontend from YAML
# Pre-condition: no replica set exists
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/user-guide/replicaset/frontend.yaml "${kube_flags[@]}"
# Post-condition: frontend replica set is created
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" 'frontend:'
# TODO(madhusudancs): Add describe tests once PR #20886 that implements describe for ReplicaSet is merged.
### Scale replica set frontend with current-replicas and replicas
# Pre-condition: 3 replicas
kube::test::get_object_assert 'rs frontend' "{{$rs_replicas_field}}" '3'
# Command
kubectl scale --current-replicas=3 --replicas=2 replicasets frontend "${kube_flags[@]}"
# Post-condition: 2 replicas
kube::test::get_object_assert 'rs frontend' "{{$rs_replicas_field}}" '2'
# Clean-up
kubectl delete rs frontend "${kube_flags[@]}"
# TODO(madhusudancs): Fix this when Scale group issues are resolved (see issue #18528).
### Expose replica set as service
kubectl create -f docs/user-guide/replicaset/frontend.yaml "${kube_flags[@]}"
# Pre-condition: 3 replicas
kube::test::get_object_assert 'rs frontend' "{{$rs_replicas_field}}" '3'
# Command
kubectl expose rs frontend --port=80 "${kube_flags[@]}"
# Post-condition: service exists and the port is unnamed
kube::test::get_object_assert 'service frontend' "{{$port_name}} {{$port_field}}" '<no value> 80'
# Create a service using service/v1 generator
kubectl expose rs frontend --port=80 --name=frontend-2 --generator=service/v1 "${kube_flags[@]}"
# Post-condition: service exists and the port is named default.
kube::test::get_object_assert 'service frontend-2' "{{$port_name}} {{$port_field}}" 'default 80'
# Cleanup services
kubectl delete service frontend{,-2} "${kube_flags[@]}"
### Delete replica set with id
# Pre-condition: frontend replica set exists
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" 'frontend:'
# Command
kubectl delete rs frontend "${kube_flags[@]}"
# Post-condition: no replica set exists
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" ''
### Create two replica sets
# Pre-condition: no replica set exists
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/user-guide/replicaset/frontend.yaml "${kube_flags[@]}"
kubectl create -f docs/user-guide/replicaset/redis-slave.yaml "${kube_flags[@]}"
# Post-condition: frontend and redis-slave
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" 'frontend:redis-slave:'
### Delete multiple replica sets at once
# Pre-condition: frontend and redis-slave
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" 'frontend:redis-slave:'
# Command
kubectl delete rs frontend redis-slave "${kube_flags[@]}" # delete multiple replica sets at once
# Post-condition: no replica set exists
kube::test::get_object_assert rs "{{range.items}}{{$id_field}}:{{end}}" ''
######################
# Multiple Resources #
######################
kube::log::status "Testing kubectl(${version}:multiple resources)"
FILES="hack/testdata/multi-resource-yaml
hack/testdata/multi-resource-list
hack/testdata/multi-resource-json
hack/testdata/multi-resource-rclist
hack/testdata/multi-resource-svclist"
YAML=".yaml"
JSON=".json"
for file in $FILES; do
if [ -f $file$YAML ]
then
file=$file$YAML
replace_file="${file%.yaml}-modify.yaml"
else
file=$file$JSON
replace_file="${file%.json}-modify.json"
fi
has_svc=true
has_rc=true
two_rcs=false
two_svcs=false
if [[ "${file}" == *rclist* ]]; then
has_svc=false
two_rcs=true
fi
if [[ "${file}" == *svclist* ]]; then
has_rc=false
two_svcs=true
fi
### Create, get, describe, replace, label, annotate, and then delete service nginxsvc and replication controller my-nginx from 5 types of files:
### 1) YAML, separated by ---; 2) JSON, with a List type; 3) JSON, with JSON object concatenation
### 4) JSON, with a ReplicationControllerList type; 5) JSON, with a ServiceList type
echo "Testing with file ${file} and replace with file ${replace_file}"
# Pre-condition: no service (other than default kubernetes services) or replication controller exists
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:'
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f "${file}" "${kube_flags[@]}"
# Post-condition: mock service (and mock2) exists
if [ "$has_svc" = true ]; then
if [ "$two_svcs" = true ]; then
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:mock:mock2:'
else
kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:mock:'
fi
fi
# Post-condition: mock rc (and mock2) exists
if [ "$has_rc" = true ]; then
if [ "$two_rcs" = true ]; then
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'mock:mock2:'
else
kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'mock:'
fi
fi
# Command
kubectl get -f "${file}" "${kube_flags[@]}"
# Command: watching multiple resources should return "not supported" error
WATCH_ERROR_FILE="${KUBE_TEMP}/kubectl-watch-error"
kubectl get -f "${file}" "${kube_flags[@]}" "--watch" 2> ${WATCH_ERROR_FILE} || true
if ! grep -q "watch is only supported on individual resources and resource collections" "${WATCH_ERROR_FILE}"; then
kube::log::error_exit "kubectl watch multiple resource returns unexpected error or non-error: $(cat ${WATCH_ERROR_FILE})" "1"
fi
kubectl describe -f "${file}" "${kube_flags[@]}"
# Command
kubectl replace -f $replace_file --force "${kube_flags[@]}"
# Post-condition: mock service (and mock2) and mock rc (and mock2) are replaced
if [ "$has_svc" = true ]; then
kube::test::get_object_assert 'services mock' "{{${labels_field}.status}}" 'replaced'
if [ "$two_svcs" = true ]; then
kube::test::get_object_assert 'services mock2' "{{${labels_field}.status}}" 'replaced'
fi
fi
if [ "$has_rc" = true ]; then
kube::test::get_object_assert 'rc mock' "{{${labels_field}.status}}" 'replaced'
if [ "$two_rcs" = true ]; then
kube::test::get_object_assert 'rc mock2' "{{${labels_field}.status}}" 'replaced'
fi
fi
# Command: kubectl edit multiple resources
temp_editor="${KUBE_TEMP}/tmp-editor.sh"
echo -e '#!/bin/bash\nsed -i "s/status\:\ replaced/status\:\ edited/g" $@' > "${temp_editor}"
chmod +x "${temp_editor}"
EDITOR="${temp_editor}" kubectl edit "${kube_flags[@]}" -f "${file}"
# Post-condition: mock service (and mock2) and mock rc (and mock2) are edited
if [ "$has_svc" = true ]; then
kube::test::get_object_assert 'services mock' "{{${labels_field}.status}}" 'edited'
if [ "$two_svcs" = true ]; then
kube::test::get_object_assert 'services mock2' "{{${labels_field}.status}}" 'edited'
fi
fi
if [ "$has_rc" = true ]; then
kube::test::get_object_assert 'rc mock' "{{${labels_field}.status}}" 'edited'
if [ "$two_rcs" = true ]; then
kube::test::get_object_assert 'rc mock2' "{{${labels_field}.status}}" 'edited'
fi
fi
# cleaning
rm "${temp_editor}"
# Command
# We need to set --overwrite, because otherwise, if the first attempt to run "kubectl label"
# fails on some, but not all, of the resources, retries will fail because it tries to modify
# existing labels.
kubectl-with-retry label -f $file labeled=true --overwrite "${kube_flags[@]}"
# Post-condition: mock service and mock rc (and mock2) are labeled
if [ "$has_svc" = true ]; then
kube::test::get_object_assert 'services mock' "{{${labels_field}.labeled}}" 'true'
if [ "$two_svcs" = true ]; then
kube::test::get_object_assert 'services mock2' "{{${labels_field}.labeled}}" 'true'
fi
fi
if [ "$has_rc" = true ]; then
kube::test::get_object_assert 'rc mock' "{{${labels_field}.labeled}}" 'true'
if [ "$two_rcs" = true ]; then
kube::test::get_object_assert 'rc mock2' "{{${labels_field}.labeled}}" 'true'
fi
fi
# Command
# Command
# We need to set --overwrite, because otherwise, if the first attempt to run "kubectl annotate"
# fails on some, but not all, of the resources, retries will fail because it tries to modify
# existing annotations.
kubectl-with-retry annotate -f $file annotated=true --overwrite "${kube_flags[@]}"
# Post-condition: mock service (and mock2) and mock rc (and mock2) are annotated
if [ "$has_svc" = true ]; then
kube::test::get_object_assert 'services mock' "{{${annotations_field}.annotated}}" 'true'
if [ "$two_svcs" = true ]; then
kube::test::get_object_assert 'services mock2' "{{${annotations_field}.annotated}}" 'true'
fi
fi
if [ "$has_rc" = true ]; then
kube::test::get_object_assert 'rc mock' "{{${annotations_field}.annotated}}" 'true'
if [ "$two_rcs" = true ]; then
kube::test::get_object_assert 'rc mock2' "{{${annotations_field}.annotated}}" 'true'
fi
fi
# Cleanup resources created
kubectl delete -f "${file}" "${kube_flags[@]}"
done
######################
# Persistent Volumes #
######################
### Create and delete persistent volume examples
# Pre-condition: no persistent volumes currently exist
kube::test::get_object_assert pv "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/user-guide/persistent-volumes/volumes/local-01.yaml "${kube_flags[@]}"
kube::test::get_object_assert pv "{{range.items}}{{$id_field}}:{{end}}" 'pv0001:'
kubectl delete pv pv0001 "${kube_flags[@]}"
kubectl create -f docs/user-guide/persistent-volumes/volumes/local-02.yaml "${kube_flags[@]}"
kube::test::get_object_assert pv "{{range.items}}{{$id_field}}:{{end}}" 'pv0002:'
kubectl delete pv pv0002 "${kube_flags[@]}"
kubectl create -f docs/user-guide/persistent-volumes/volumes/gce.yaml "${kube_flags[@]}"
kube::test::get_object_assert pv "{{range.items}}{{$id_field}}:{{end}}" 'pv0003:'
kubectl delete pv pv0003 "${kube_flags[@]}"
# Post-condition: no PVs
kube::test::get_object_assert pv "{{range.items}}{{$id_field}}:{{end}}" ''
############################
# Persistent Volume Claims #
############################
### Create and delete persistent volume claim examples
# Pre-condition: no persistent volume claims currently exist
kube::test::get_object_assert pvc "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create -f docs/user-guide/persistent-volumes/claims/claim-01.yaml "${kube_flags[@]}"
kube::test::get_object_assert pvc "{{range.items}}{{$id_field}}:{{end}}" 'myclaim-1:'
kubectl delete pvc myclaim-1 "${kube_flags[@]}"
kubectl create -f docs/user-guide/persistent-volumes/claims/claim-02.yaml "${kube_flags[@]}"
kube::test::get_object_assert pvc "{{range.items}}{{$id_field}}:{{end}}" 'myclaim-2:'
kubectl delete pvc myclaim-2 "${kube_flags[@]}"
kubectl create -f docs/user-guide/persistent-volumes/claims/claim-03.json "${kube_flags[@]}"
kube::test::get_object_assert pvc "{{range.items}}{{$id_field}}:{{end}}" 'myclaim-3:'
kubectl delete pvc myclaim-3 "${kube_flags[@]}"
# Post-condition: no PVCs
kube::test::get_object_assert pvc "{{range.items}}{{$id_field}}:{{end}}" ''
#########
# Nodes #
#########
kube::log::status "Testing kubectl(${version}:nodes)"
kube::test::get_object_assert nodes "{{range.items}}{{$id_field}}:{{end}}" '127.0.0.1:'
kube::test::describe_object_assert nodes "127.0.0.1" "Name:" "Labels:" "CreationTimestamp:" "Conditions:" "Addresses:" "Capacity:" "Pods:"
# Describe command (resource only) should print detailed information
kube::test::describe_resource_assert nodes "Name:" "Labels:" "CreationTimestamp:" "Conditions:" "Addresses:" "Capacity:" "Pods:"
### kubectl patch update can mark node unschedulable
# Pre-condition: node is schedulable
kube::test::get_object_assert "nodes 127.0.0.1" "{{.spec.unschedulable}}" '<no value>'
kubectl patch "${kube_flags[@]}" nodes "127.0.0.1" -p='{"spec":{"unschedulable":true}}'
# Post-condition: node is unschedulable
kube::test::get_object_assert "nodes 127.0.0.1" "{{.spec.unschedulable}}" 'true'
kubectl patch "${kube_flags[@]}" nodes "127.0.0.1" -p='{"spec":{"unschedulable":null}}'
# Post-condition: node is schedulable
kube::test::get_object_assert "nodes 127.0.0.1" "{{.spec.unschedulable}}" '<no value>'
#####################
# Retrieve multiple #
#####################
kube::log::status "Testing kubectl(${version}:multiget)"
kube::test::get_object_assert 'nodes/127.0.0.1 service/kubernetes' "{{range.items}}{{$id_field}}:{{end}}" '127.0.0.1:kubernetes:'
#####################
# Resource aliasing #
#####################
kube::log::status "Testing resource aliasing"
kubectl create -f examples/cassandra/cassandra-controller.yaml "${kube_flags[@]}"
kubectl scale rc cassandra --replicas=1 "${kube_flags[@]}"
kubectl create -f examples/cassandra/cassandra-service.yaml "${kube_flags[@]}"
kube::test::get_object_assert "all -l'app=cassandra'" "{{range.items}}{{range .metadata.labels}}{{.}}:{{end}}{{end}}" 'cassandra:cassandra:cassandra:'
kubectl delete all -l app=cassandra "${kube_flags[@]}"
###########
# Explain #
###########
kube::log::status "Testing kubectl(${version}:explain)"
kubectl explain pods
# shortcuts work
kubectl explain po
kubectl explain po.status.message
###########
# Swagger #
###########
if [[ -n "${version}" ]]; then
# Verify schema
file="${KUBE_TEMP}/schema-${version}.json"
curl -s "http://127.0.0.1:${API_PORT}/swaggerapi/api/${version}" > "${file}"
[[ "$(grep "list of returned" "${file}")" ]]
[[ "$(grep "List of pods" "${file}")" ]]
[[ "$(grep "Watch for changes to the described resources" "${file}")" ]]
fi
#####################
# Kubectl --sort-by #
#####################
### sort-by should not panic if no pod exists
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl get pods --sort-by="{metadata.name}"
############################
# Kubectl --all-namespaces #
############################
# Pre-condition: the "default" namespace exists
kube::test::get_object_assert namespaces "{{range.items}}{{$id_field}}:{{end}}" 'default:'
### Create POD
# Pre-condition: no POD exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
# Command
kubectl create "${kube_flags[@]}" -f docs/admin/limitrange/valid-pod.yaml
# Post-condition: valid-pod is created
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
### Verify a specific namespace is ignored when all-namespaces is provided
# Command
kubectl get pods --all-namespaces --namespace=default
### Clean up
# Pre-condition: valid-pod exists
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
# Command
kubectl delete "${kube_flags[@]}" pod valid-pod --grace-period=0
# Post-condition: valid-pod doesn't exist
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
kube::test::clear_all
}
kube_api_versions=(
""
v1
)
for version in "${kube_api_versions[@]}"; do
KUBE_API_VERSIONS="v1,autoscaling/v1,batch/v1,extensions/v1beta1" runTests "${version}"
done
kube::log::status "TEST PASSED"
| {
"content_hash": "5f79018a2e3694129aa104f0d60fdaab",
"timestamp": "",
"source": "github",
"line_count": 1593,
"max_line_length": 216,
"avg_line_length": 47.728813559322035,
"alnum_prop": 0.6637863005050505,
"repo_name": "swagiaal/kubernetes",
"id": "7b5ec0ec2411e3c9a479d3bc3739a81edaabdbd3",
"size": "76799",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hack/test-cmd.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "19918833"
},
{
"name": "HTML",
"bytes": "1193990"
},
{
"name": "Makefile",
"bytes": "47266"
},
{
"name": "Nginx",
"bytes": "1013"
},
{
"name": "Python",
"bytes": "68276"
},
{
"name": "SaltStack",
"bytes": "46138"
},
{
"name": "Shell",
"bytes": "1168934"
}
],
"symlink_target": ""
} |
require 's3_assets_uploader/config'
RSpec.describe S3AssetsUploader::Config do
let(:config) { described_class.new }
before do
# Avoid slow test
allow(config).to receive(:create_default_client)
end
describe '#validate!' do
it 'requires bucket' do
expect { config.validate! }.to raise_error(S3AssetsUploader::Config::ValidationError, /bucket/)
end
context 'with bucket' do
before do
config.bucket = 'some-bucket'
end
it 'passes' do
expect { config.validate! }.to_not raise_error
end
context 'with invalid additional_paths' do
before do
config.assets_path = File.expand_path('../../fixtures/public/assets', __FILE__)
config.additional_paths << __FILE__
end
it 'rejects additional_paths which is not under public_path' do
expect { config.validate! }.to raise_error(S3AssetsUploader::Config::ValidationError, /must be under/)
end
end
end
end
end
| {
"content_hash": "d3e619644e2179436365a248c1abf496",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 112,
"avg_line_length": 27.08108108108108,
"alnum_prop": 0.6387225548902196,
"repo_name": "sorah/s3_assets_uploader",
"id": "6fe0bed0083d729973ce0642cb2488f242ce31ab",
"size": "1002",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/s3_assets_uploader/config_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "7779"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
#ifndef INC_DEFS_H
#define INC_DEFS_H 1
#if !defined(ALREADY_INCLUDED_CONFIG_H)
/*
* Savannah bug #20128: if we include some system header and it
* includes some othersecond system header, the second system header
* may in fact turn out to be a file provided by gnulib. For that
* situation, we need to have already included <config.h> so that the
* Gnulib files have access to the information probed by their
* configure script fragments. So <config.h> should be the first
* thing included.
*/
#error "<config.h> should be #included before defs.h, and indeed before any other header"
Please stop compiling the program now
#endif
#include <sys/types.h>
/* XXX: some of these includes probably don't belong in a common header file */
#include <sys/stat.h>
#include <stdio.h> /* for FILE* */
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <limits.h> /* for CHAR_BIT */
#include <stdbool.h> /* for bool/boolean */
#include <stdint.h> /* for uintmax_t */
#include <sys/stat.h> /* S_ISUID etc. */
#ifndef CHAR_BIT
# define CHAR_BIT 8
#endif
#if HAVE_INTTYPES_H
# include <inttypes.h>
#endif
typedef bool boolean;
#include "regex.h"
#include "timespec.h"
#include "buildcmd.h"
#include "quotearg.h"
/* These days we will assume ANSI/ISO C protootypes work on our compiler. */
#define PARAMS(Args) Args
#ifndef ATTRIBUTE_NORETURN
# if HAVE_ATTRIBUTE_NORETURN
# define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
# else
# define ATTRIBUTE_NORETURN /* nothing */
# endif
#endif
int optionl_stat PARAMS((const char *name, struct stat *p));
int optionp_stat PARAMS((const char *name, struct stat *p));
int optionh_stat PARAMS((const char *name, struct stat *p));
int debug_stat PARAMS((const char *file, struct stat *bufp));
void set_stat_placeholders PARAMS((struct stat *p));
int get_statinfo PARAMS((const char *pathname, const char *name, struct stat *p));
#define MODE_WXUSR (S_IWUSR | S_IXUSR)
#define MODE_R (S_IRUSR | S_IRGRP | S_IROTH)
#define MODE_RW (S_IWUSR | S_IWGRP | S_IWOTH | MODE_R)
#define MODE_RWX (S_IXUSR | S_IXGRP | S_IXOTH | MODE_RW)
#define MODE_ALL (S_ISUID | S_ISGID | S_ISVTX | MODE_RWX)
struct predicate;
struct options;
/* Pointer to a predicate function. */
typedef boolean (*PRED_FUNC)(const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr);
/* The number of seconds in a day. */
#define DAYSECS 86400
/* Argument structures for predicates. */
enum comparison_type
{
COMP_GT,
COMP_LT,
COMP_EQ
};
enum permissions_type
{
PERM_AT_LEAST,
PERM_ANY,
PERM_EXACT
};
enum predicate_type
{
NO_TYPE,
PRIMARY_TYPE,
UNI_OP,
BI_OP,
OPEN_PAREN,
CLOSE_PAREN
};
enum predicate_precedence
{
NO_PREC,
COMMA_PREC,
OR_PREC,
AND_PREC,
NEGATE_PREC,
MAX_PREC
};
struct long_val
{
enum comparison_type kind;
boolean negative; /* Defined only when representing time_t. */
uintmax_t l_val;
};
struct perm_val
{
enum permissions_type kind;
mode_t val[2];
};
/* dir_id is used to support loop detection in find.c
*/
struct dir_id
{
ino_t ino;
dev_t dev;
};
/* samefile_file_id is used to support the -samefile test.
*/
struct samefile_file_id
{
ino_t ino;
dev_t dev;
int fd;
};
struct size_val
{
enum comparison_type kind;
int blocksize;
uintmax_t size;
};
enum xval
{
XVAL_ATIME, XVAL_BIRTHTIME, XVAL_CTIME, XVAL_MTIME, XVAL_TIME
};
struct time_val
{
enum xval xval;
enum comparison_type kind;
struct timespec ts;
};
struct exec_val
{
boolean multiple; /* -exec {} \+ denotes multiple argument. */
struct buildcmd_control ctl;
struct buildcmd_state state;
char **replace_vec; /* Command arguments (for ";" style) */
int num_args;
boolean use_current_dir; /* If nonzero, don't chdir to start dir */
boolean close_stdin; /* If true, close stdin in the child. */
int dir_fd; /* The directory to do the exec in. */
};
/* The format string for a -printf or -fprintf is chopped into one or
more `struct segment', linked together into a list.
Each stretch of plain text is a segment, and
each \c and `%' conversion is a segment. */
/* Special values for the `kind' field of `struct segment'. */
enum SegmentKind
{
KIND_PLAIN=0, /* Segment containing just plain text. */
KIND_STOP=1, /* \c -- stop printing and flush output. */
KIND_FORMAT, /* Regular format */
};
struct segment
{
enum SegmentKind segkind; /* KIND_FORMAT, KIND_PLAIN, KIND_STOP */
char format_char[2]; /* Format chars if kind is KIND_FORMAT */
char *text; /* Plain text or `%' format string. */
int text_len; /* Length of `text'. */
struct segment *next; /* Next segment for this predicate. */
};
struct format_val
{
struct segment *segment; /* Linked list of segments. */
FILE *stream; /* Output stream to print on. */
const char *filename; /* We need the filename for error messages. */
boolean dest_is_tty; /* True if the destination is a terminal. */
struct quoting_options *quote_opts;
};
/* Profiling information for a predicate */
struct predicate_performance_info
{
unsigned long visits;
unsigned long successes;
};
/* evaluation cost of a predicate */
enum EvaluationCost
{
NeedsNothing,
NeedsType,
NeedsStatInfo,
NeedsLinkName,
NeedsAccessInfo,
NeedsSyncDiskHit,
NeedsEventualExec,
NeedsImmediateExec,
NeedsUserInteraction,
NeedsUnknown,
NumEvaluationCosts
};
struct predicate
{
/* Pointer to the function that implements this predicate. */
PRED_FUNC pred_func;
/* Only used for debugging, but defined unconditionally so individual
modules can be compiled with -DDEBUG. */
char *p_name;
/* The type of this node. There are two kinds. The first is real
predicates ("primaries") such as -perm, -print, or -exec. The
other kind is operators for combining predicates. */
enum predicate_type p_type;
/* The precedence of this node. Only has meaning for operators. */
enum predicate_precedence p_prec;
/* True if this predicate node produces side effects.
If side_effects are produced
then optimization will not be performed */
boolean side_effects;
/* True if this predicate node requires default print be turned off. */
boolean no_default_print;
/* True if this predicate node requires a stat system call to execute. */
boolean need_stat;
/* True if this predicate node requires knowledge of the file type. */
boolean need_type;
enum EvaluationCost p_cost;
/* est_success_rate is a number between 0.0 and 1.0 */
float est_success_rate;
/* True if this predicate should display control characters literally */
boolean literal_control_chars;
/* True if this predicate didn't originate from the user. */
boolean artificial;
/* The raw text of the argument of this predicate. */
char *arg_text;
/* Information needed by the predicate processor.
Next to each member are listed the predicates that use it. */
union
{
const char *str; /* fstype [i]lname [i]name [i]path */
struct re_pattern_buffer *regex; /* regex */
struct exec_val exec_vec; /* exec ok */
struct long_val numinfo; /* gid inum links uid */
struct size_val size; /* size */
uid_t uid; /* user */
gid_t gid; /* group */
struct time_val reftime; /* newer newerXY anewer cnewer mtime atime ctime mmin amin cmin */
struct perm_val perm; /* perm */
struct samefile_file_id samefileid; /* samefile */
mode_t type; /* type */
struct format_val printf_vec; /* printf fprintf fprint ls fls print0 fprint0 print */
} args;
/* The next predicate in the user input sequence,
which represents the order in which the user supplied the
predicates on the command line. */
struct predicate *pred_next;
/* The right and left branches from this node in the expression
tree, which represents the order in which the nodes should be
processed. */
struct predicate *pred_left;
struct predicate *pred_right;
struct predicate_performance_info perf;
const struct parser_table* parser_entry;
};
/* find.c, ftsfind.c */
boolean is_fts_enabled(int *ftsoptions);
int get_start_dirfd(void);
int get_current_dirfd(void);
/* find library function declarations. */
/* find global function declarations. */
/* find.c */
/* SymlinkOption represents the choice of
* -P, -L or -P (default) on the command line.
*/
enum SymlinkOption
{
SYMLINK_NEVER_DEREF, /* Option -P */
SYMLINK_ALWAYS_DEREF, /* Option -L */
SYMLINK_DEREF_ARGSONLY /* Option -H */
};
extern enum SymlinkOption symlink_handling; /* defined in find.c. */
void set_follow_state PARAMS((enum SymlinkOption opt));
void cleanup(void);
/* fstype.c */
char *filesystem_type PARAMS((const struct stat *statp, const char *path));
char * get_mounted_filesystems (void);
dev_t * get_mounted_devices PARAMS((size_t *));
enum arg_type
{
ARG_OPTION, /* regular options like -maxdepth */
ARG_NOOP, /* does nothing, returns true, internal use only */
ARG_POSITIONAL_OPTION, /* options whose position is important (-follow) */
ARG_TEST, /* a like -name */
ARG_SPECIAL_PARSE, /* complex to parse, don't eat the test name before calling parse_xx(). */
ARG_PUNCTUATION, /* like -o or ( */
ARG_ACTION /* like -print */
};
struct parser_table;
/* Pointer to a parser function. */
typedef boolean (*PARSE_FUNC)(const struct parser_table *p,
char *argv[], int *arg_ptr);
struct parser_table
{
enum arg_type type;
char *parser_name;
PARSE_FUNC parser_func;
PRED_FUNC pred_func;
};
/* parser.c */
const struct parser_table* find_parser PARAMS((char *search_name));
boolean parse_print PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
void pred_sanity_check PARAMS((const struct predicate *predicates));
void check_option_combinations (const struct predicate *p);
void parse_begin_user_args PARAMS((char **args, int argno, const struct predicate *last, const struct predicate *predicates));
void parse_end_user_args PARAMS((char **args, int argno, const struct predicate *last, const struct predicate *predicates));
boolean parse_openparen PARAMS((const struct parser_table* entry, char *argv[], int *arg_ptr));
boolean parse_closeparen PARAMS((const struct parser_table* entry, char *argv[], int *arg_ptr));
/* pred.c */
typedef boolean PREDICATEFUNCTION(const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr);
PREDICATEFUNCTION pred_amin;
PREDICATEFUNCTION pred_and;
PREDICATEFUNCTION pred_anewer;
PREDICATEFUNCTION pred_atime;
PREDICATEFUNCTION pred_closeparen;
PREDICATEFUNCTION pred_cmin;
PREDICATEFUNCTION pred_cnewer;
PREDICATEFUNCTION pred_comma;
PREDICATEFUNCTION pred_ctime;
PREDICATEFUNCTION pred_delete;
PREDICATEFUNCTION pred_empty;
PREDICATEFUNCTION pred_exec;
PREDICATEFUNCTION pred_execdir;
PREDICATEFUNCTION pred_executable;
PREDICATEFUNCTION pred_false;
PREDICATEFUNCTION pred_fls;
PREDICATEFUNCTION pred_fprint;
PREDICATEFUNCTION pred_fprint0;
PREDICATEFUNCTION pred_fprintf;
PREDICATEFUNCTION pred_fstype;
PREDICATEFUNCTION pred_gid;
PREDICATEFUNCTION pred_group;
PREDICATEFUNCTION pred_ilname;
PREDICATEFUNCTION pred_iname;
PREDICATEFUNCTION pred_inum;
PREDICATEFUNCTION pred_ipath;
PREDICATEFUNCTION pred_links;
PREDICATEFUNCTION pred_lname;
PREDICATEFUNCTION pred_ls;
PREDICATEFUNCTION pred_mmin;
PREDICATEFUNCTION pred_mtime;
PREDICATEFUNCTION pred_name;
PREDICATEFUNCTION pred_negate;
PREDICATEFUNCTION pred_newer;
PREDICATEFUNCTION pred_newerXY;
PREDICATEFUNCTION pred_nogroup;
PREDICATEFUNCTION pred_nouser;
PREDICATEFUNCTION pred_ok;
PREDICATEFUNCTION pred_okdir;
PREDICATEFUNCTION pred_openparen;
PREDICATEFUNCTION pred_or;
PREDICATEFUNCTION pred_path;
PREDICATEFUNCTION pred_perm;
PREDICATEFUNCTION pred_print;
PREDICATEFUNCTION pred_print0;
PREDICATEFUNCTION pred_prune;
PREDICATEFUNCTION pred_quit;
PREDICATEFUNCTION pred_readable;
PREDICATEFUNCTION pred_regex;
PREDICATEFUNCTION pred_samefile;
PREDICATEFUNCTION pred_size;
PREDICATEFUNCTION pred_true;
PREDICATEFUNCTION pred_type;
PREDICATEFUNCTION pred_uid;
PREDICATEFUNCTION pred_used;
PREDICATEFUNCTION pred_user;
PREDICATEFUNCTION pred_writable;
PREDICATEFUNCTION pred_xtype;
int launch PARAMS((const struct buildcmd_control *ctl,
struct buildcmd_state *buildstate));
char *find_pred_name PARAMS((PRED_FUNC pred_func));
void print_predicate PARAMS((FILE *fp, const struct predicate *p));
void print_tree PARAMS((FILE*, struct predicate *node, int indent));
void print_list PARAMS((FILE*, struct predicate *node));
void print_optlist PARAMS((FILE *fp, const struct predicate *node));
void show_success_rates(const struct predicate *node);
/* tree.c */
struct predicate * build_expression_tree PARAMS((int argc, char *argv[], int end_of_leading_options));
struct predicate * get_eval_tree PARAMS((void));
struct predicate *get_new_pred PARAMS((const struct parser_table *entry));
struct predicate *get_new_pred_chk_op PARAMS((const struct parser_table *entry));
float calculate_derived_rates PARAMS((struct predicate *p));
/* util.c */
struct predicate *insert_primary PARAMS((const struct parser_table *entry));
struct predicate *insert_primary_withpred PARAMS((const struct parser_table *entry, PRED_FUNC fptr));
void usage PARAMS((FILE *fp, int status, char *msg));
extern boolean check_nofollow(void);
void complete_pending_execs(struct predicate *p);
void complete_pending_execdirs(int dir_fd); /* Passing dir_fd is an unpleasant CodeSmell. */
const char *safely_quote_err_filename (int n, char const *arg);
void fatal_file_error(const char *name) ATTRIBUTE_NORETURN;
void nonfatal_file_error(const char *name);
int process_leading_options PARAMS((int argc, char *argv[]));
void set_option_defaults PARAMS((struct options *p));
#if 0
#define apply_predicate(pathname, stat_buf_ptr, node) \
(*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
#else
boolean apply_predicate(const char *pathname, struct stat *stat_buf, struct predicate *p);
#endif
#define pred_is(node, fn) ( ((node)->pred_func) == (fn) )
/* find.c. */
int get_info PARAMS((const char *pathname, struct stat *p, struct predicate *pred_ptr));
int following_links PARAMS((void));
int digest_mode PARAMS((mode_t mode, const char *pathname, const char *name, struct stat *pstat, boolean leaf));
boolean default_prints PARAMS((struct predicate *pred));
boolean looks_like_expression PARAMS((const char *arg, boolean leading));
enum DebugOption
{
DebugNone = 0,
DebugExpressionTree = 1,
DebugStat = 2,
DebugSearch = 4,
DebugTreeOpt = 8,
DebugHelp = 16,
DebugExec = 32,
DebugSuccessRates = 64
};
struct options
{
/* If true, process directory before contents. True unless -depth given. */
boolean do_dir_first;
/* If true, -depth was EXPLICITLY set (as opposed to having been turned
* on by -delete, for example).
*/
boolean explicit_depth;
/* If >=0, don't descend more than this many levels of subdirectories. */
int maxdepth;
/* If >=0, don't process files above this level. */
int mindepth;
/* If true, do not assume that files in directories with nlink == 2
are non-directories. */
boolean no_leaf_check;
/* If true, don't cross filesystem boundaries. */
boolean stay_on_filesystem;
/* If true, we ignore the problem where we find that a directory entry
* no longer exists by the time we get around to processing it.
*/
boolean ignore_readdir_race;
/* If true, pass control characters through. If false, escape them
* or turn them into harmless things.
*/
boolean literal_control_chars;
/* If true, we issue warning messages
*/
boolean warnings;
/* If true, avoid POSIX-incompatible behaviours
* (this functionality is currently incomplete
* and at the moment affects mainly warning messages).
*/
boolean posixly_correct;
struct timespec start_time; /* Time at start of execution. */
/* Either one day before now (the default), or the start of today (if -daystart is given). */
struct timespec cur_day_start;
/* If true, cur_day_start has been adjusted to the start of the day. */
boolean full_days;
int output_block_size; /* Output block size. */
/* bitmask for debug options */
unsigned long debug_options;
enum SymlinkOption symlink_handling;
/* Pointer to the function used to stat files. */
int (*xstat) (const char *name, struct stat *statbuf);
/* Indicate if we can implement safely_chdir() using the O_NOFOLLOW
* flag to open(2).
*/
boolean open_nofollow_available;
/* The variety of regular expression that we support.
* The default is POSIX Basic Regular Expressions, but this
* can be changed with the positional option, -regextype.
*/
int regex_options;
/* Optimisation level. One is the default.
*/
unsigned short optimisation_level;
/* How should we quote filenames in error messages and so forth?
*/
enum quoting_style err_quoting_style;
};
extern struct options options;
struct state
{
/* Current depth; 0 means current path is a command line arg. */
int curdepth;
/* If true, we have called stat on the current path. */
boolean have_stat;
/* If true, we know the type of the current path. */
boolean have_type;
mode_t type; /* this is the actual type */
/* The file being operated on, relative to the current directory.
Used for stat, readlink, remove, and opendir. */
char *rel_pathname;
/* The directory fd to which rel_pathname is relative. Thsi is relevant
* when we're navigating the hierarchy with fts() and using FTS_CWDFD.
*/
int cwd_dir_fd;
/* Length of starting path. */
int starting_path_length;
/* If true, don't descend past current directory.
Can be set by -prune, -maxdepth, and -xdev/-mount. */
boolean stop_at_current_level;
/* Status value to return to system. */
int exit_status;
/* True if there are any execdirs. This saves us a pair of fchdir()
* calls for every directory we leave if it is false. This is just
* an optimisation. Set to true if you want to be conservative.
*/
boolean execdirs_outstanding;
};
/* finddata.c */
extern struct state state;
extern char const *starting_dir;
extern int starting_desc;
extern char *program_name;
#endif
| {
"content_hash": "75dd9fd67e23d1b554f8b2818f1a5f66",
"timestamp": "",
"source": "github",
"line_count": 644,
"max_line_length": 126,
"avg_line_length": 28.76086956521739,
"alnum_prop": 0.7036497138537955,
"repo_name": "google/qpp",
"id": "1708d839be1777202543c3c3f23818b030711916",
"size": "19337",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "http/node_modules/jsDAV/node_modules/gnu-tools/findutils-src/find/defs.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "123044"
},
{
"name": "JavaScript",
"bytes": "4477456"
},
{
"name": "LiveScript",
"bytes": "6103"
}
],
"symlink_target": ""
} |
using System;
namespace Braintree.TestUtil
{
public class ModificationRequestForTests : Request
{
public decimal? Amount { get; set; }
public DateTime? CreatedAt { get; set; }
public string Description { get; set; }
public string Id { get; set; }
new public string Kind { get; set; }
public string MerchantId { get; set; }
public string Name { get; set; }
public bool? NeverExpires { get; set; }
public int? NumberOfBillingCycles { get; set; }
public string PlanId { get; set; }
public int? Quantity { get; set; }
public DateTime? UpdatedAt { get; set; }
public override string ToXml()
{
return ToXml("modification");
}
public override string ToXml(string root)
{
return BuildRequest(root).ToXml();
}
public RequestBuilder BuildRequest(string root)
{
return new RequestBuilder(root).
AddElement("amount", Amount).
AddElement("created-at", CreatedAt).
AddElement("description", Description).
AddElement("id", Id).
AddElement("kind", Kind).
AddElement("merchant-id", MerchantId).
AddElement("name", Name).
AddElement("never-expires", NeverExpires).
AddElement("number-of-billing-cycles", NumberOfBillingCycles).
AddElement("plan-id", PlanId).
AddElement("quantity", Quantity).
AddElement("updated-at", UpdatedAt);
}
}
}
| {
"content_hash": "632b891e1cfd49c5bdc383cea2023f8c",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 78,
"avg_line_length": 34.680851063829785,
"alnum_prop": 0.5539877300613497,
"repo_name": "braintree/braintree_dotnet",
"id": "358d580abc9ca86bf26b64e90062062e72066e04",
"size": "1630",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/Braintree.TestUtil/ModificationRequestForTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2089391"
},
{
"name": "Makefile",
"bytes": "526"
},
{
"name": "Ruby",
"bytes": "5822"
}
],
"symlink_target": ""
} |
<?php
namespace Restorando\HttpClient\Message;
use Buzz\Message\Request as BaseRequest;
class Request extends BaseRequest
{
}
| {
"content_hash": "c459b98925b6bedf2545ff72067a87f6",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 40,
"avg_line_length": 13,
"alnum_prop": 0.7923076923076923,
"repo_name": "restorando/php-api-client",
"id": "47cd53999bd369ebc307d27cbdec24b94f2773a1",
"size": "130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/Restorando/HttpClient/Message/Request.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "26336"
}
],
"symlink_target": ""
} |
module Project::BaseValidator
extend ActiveSupport::Concern
included do
# All valid states for projects in_analysis to end of publication
ON_ANALYSIS_TO_END_STATES = %w(in_analysis approved online successful waiting_funds failed).freeze
# All valid states for projects approved to end of publication
ON_ONLINE_TO_END_STATES = %w(online successful waiting_funds failed).freeze
# Start validations when project state
# is included on ON_ANALYSIS_TO_END_STATE
with_options if: -> (x) { ON_ANALYSIS_TO_END_STATES.include? x.state } do |wo|
wo.validates_presence_of :about_html, :headline, :goal
wo.validates_presence_of :uploaded_image,
unless: ->(project) { project.video_thumbnail.present? }
wo.validate do
[:uploaded_image, :about_html, :name].each do |attr|
self.user.errors.add_on_blank(attr)
end
self.user.errors.each do |error, error_message|
self.errors.add('user.' + error.to_s, error_message)
end
end
end
with_options if: -> (x) { ON_ONLINE_TO_END_STATES.include? x.state } do |wo|
#wo.validates_presence_of :budget
wo.validates_presence_of :account, message: 'Dados Bancários não podem ficar em branco'
wo.validate do
if self.account && (self.account.agency.try(:size) || 0) < 4
self.errors['account.agency_size'] << "Agência deve ter pelo menos 4 dígitos"
end
end
end
end
end
| {
"content_hash": "fc24acaf237db66bd389cf8303b4e1de",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 102,
"avg_line_length": 35.166666666666664,
"alnum_prop": 0.6580907244414353,
"repo_name": "umeshduggal/flockaway",
"id": "79185e327125e04a6a4d02a5e4eb896ef31f9b0e",
"size": "1565",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/concerns/project/base_validator.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "144322"
},
{
"name": "CoffeeScript",
"bytes": "11495"
},
{
"name": "HTML",
"bytes": "289329"
},
{
"name": "JavaScript",
"bytes": "123974"
},
{
"name": "Ruby",
"bytes": "1366862"
}
],
"symlink_target": ""
} |
package eu.drus.jpa.unit.sql.dbunit.dataset;
import static eu.drus.jpa.unit.sql.dbunit.dataset.ColumnNameMatcher.columnWithName;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dbunit.dataset.Column;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.ITableMetaData;
import org.dbunit.dataset.stream.IDataSetConsumer;
import org.dbunit.dataset.stream.IDataSetProducer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.google.gson.JsonSyntaxException;
import eu.drus.jpa.unit.sql.dbunit.dataset.JsonDataSetProducer;
public class JsonDataSetProducerTest {
private InputStream jsonStream;
private InputStream yamlStream;
@Before
public void openResourceStream() {
jsonStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("test-data.json");
yamlStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("test-data.yaml");
}
@After
public void closeResourceStream() throws IOException {
jsonStream.close();
yamlStream.close();
}
@SuppressWarnings("unchecked")
@Test
public void testProduceDataSetUsingValidStream() throws DataSetException {
// GIVEN
final IDataSetConsumer consumer = mock(IDataSetConsumer.class);
final IDataSetProducer producer = new JsonDataSetProducer(jsonStream);
producer.setConsumer(consumer);
// WHEN
producer.produce();
// THEN
verify(consumer).startDataSet();
final ArgumentCaptor<ITableMetaData> tmdCaptor = ArgumentCaptor.forClass(ITableMetaData.class);
verify(consumer, times(2)).startTable(tmdCaptor.capture());
final List<ITableMetaData> tmdList = tmdCaptor.getAllValues();
final ITableMetaData tmd1 = tmdList.get(0);
final List<Column> table1Columns = Arrays.asList(tmd1.getColumns());
final ITableMetaData tmd2 = tmdList.get(1);
final List<Column> table2Columns = Arrays.asList(tmd2.getColumns());
assertThat(tmd1.getTableName(), equalTo("JSON_TABLE_1"));
assertThat(table1Columns.size(), equalTo(7));
assertThat(table1Columns, hasItems(columnWithName("id"), columnWithName("version"), columnWithName("value_1"),
columnWithName("value_2"), columnWithName("value_3"), columnWithName("value_4"), columnWithName("value_5")));
assertThat(tmd2.getTableName(), equalTo("JSON_TABLE_2"));
assertThat(table2Columns.size(), equalTo(4));
assertThat(table2Columns,
hasItems(columnWithName("id"), columnWithName("version"), columnWithName("value_6"), columnWithName("value_7")));
final ArgumentCaptor<Object[]> rowCaptor = ArgumentCaptor.forClass(Object[].class);
verify(consumer, times(4)).row(rowCaptor.capture());
final List<Object[]> allRows = rowCaptor.getAllValues();
final Map<String, String> record1 = rebuildRecord(table1Columns, allRows.get(0));
assertThat(record1.size(), equalTo(7));
assertThat(record1.get("id"), equalTo("1"));
assertThat(record1.get("version"), equalTo("Record 1 version"));
assertThat(record1.get("value_1"), equalTo("Record 1 Value 1"));
assertThat(record1.get("value_2"), equalTo("Record 1 Value 2"));
assertThat(record1.get("value_3"), nullValue());
assertThat(record1.get("value_4"), equalTo("Record 1 Value 4"));
assertThat(record1.get("value_5"), nullValue());
final Map<String, String> record2 = rebuildRecord(table1Columns, allRows.get(1));
assertThat(record2.size(), equalTo(7));
assertThat(record2.get("id"), equalTo("2"));
assertThat(record2.get("version"), equalTo("Record 2 version"));
assertThat(record2.get("value_1"), equalTo("Record 2 Value 1"));
assertThat(record2.get("value_2"), equalTo("Record 2 Value 2"));
assertThat(record2.get("value_3"), equalTo("Record 2 Value 3"));
assertThat(record2.get("value_4"), nullValue());
assertThat(record2.get("value_5"), nullValue());
final Map<String, String> record3 = rebuildRecord(table1Columns, allRows.get(2));
assertThat(record3.size(), equalTo(7));
assertThat(record3.get("id"), equalTo("3"));
assertThat(record3.get("version"), equalTo("Record 3 version"));
assertThat(record3.get("value_1"), nullValue());
assertThat(record3.get("value_2"), nullValue());
assertThat(record3.get("value_3"), nullValue());
assertThat(record3.get("value_4"), nullValue());
assertThat(record3.get("value_5"), equalTo("Record 3 Value 5"));
final Map<String, String> record4 = rebuildRecord(table2Columns, allRows.get(3));
assertThat(record4.size(), equalTo(4));
assertThat(record4.get("id"), equalTo("4"));
assertThat(record4.get("version"), equalTo("Record 4 version"));
assertThat(record4.get("value_6"), equalTo("Record 4 Value 6"));
assertThat(record4.get("value_7"), equalTo("Record 4 Value 7"));
verify(consumer, times(2)).endTable();
verify(consumer).endDataSet();
}
@Test(expected = NullPointerException.class)
public void testProduceDataSetUsingNullStream() throws DataSetException {
// WHEN
new JsonDataSetProducer(null);
}
@Test
public void testProduceDataSetUsingNotJsonStream() throws DataSetException {
// GIVEN
final IDataSetConsumer consumer = mock(IDataSetConsumer.class);
final IDataSetProducer producer = new JsonDataSetProducer(yamlStream);
producer.setConsumer(consumer);
// WHEN
try {
producer.produce();
fail("DataSetException expected");
} catch (final DataSetException e) {
// THEN
assertThat(e.getCause(), instanceOf(JsonSyntaxException.class));
}
}
private Map<String, String> rebuildRecord(final List<Column> columns, final Object[] entries) {
final Map<String, String> record = new HashMap<>();
for (int i = 0; i < columns.size(); i++) {
record.put(columns.get(i).getColumnName(), (String) entries[i]);
}
return record;
}
}
| {
"content_hash": "76a63c4aef348a069312d73e700fe327",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 129,
"avg_line_length": 42.03703703703704,
"alnum_prop": 0.6816446402349486,
"repo_name": "dadrus/jpa-unit",
"id": "49d105c664b0bfcf6ec5c9b126fb935d2b2ac395",
"size": "6810",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "rdbms/src/test/java/eu/drus/jpa/unit/sql/dbunit/dataset/JsonDataSetProducerTest.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Gherkin",
"bytes": "1690"
},
{
"name": "Java",
"bytes": "1237669"
},
{
"name": "Shell",
"bytes": "1438"
}
],
"symlink_target": ""
} |
package io.datarouter.nodewatch.job;
import javax.inject.Inject;
import io.datarouter.instrumentation.tablecount.TableCountBatchDto;
import io.datarouter.instrumentation.tablecount.TableCountDto;
import io.datarouter.instrumentation.tablecount.TableCountPublisher;
import io.datarouter.instrumentation.task.TaskTracker;
import io.datarouter.job.BaseJob;
import io.datarouter.nodewatch.storage.latesttablecount.DatarouterLatestTableCountDao;
import io.datarouter.nodewatch.storage.latesttablecount.LatestTableCount;
import io.datarouter.storage.config.properties.ServiceName;
public class LatestTableCountPublisherJob extends BaseJob{
@Inject
private TableCountPublisher publisher;
@Inject
private DatarouterLatestTableCountDao dao;
@Inject
private ServiceName serviceName;
@Override
public void run(TaskTracker tracker){
dao.scan()
.map(this::toDto)
.batch(50)
.map(TableCountBatchDto::new)
.forEach(publisher::add);
}
private TableCountDto toDto(LatestTableCount count){
return new TableCountDto(
serviceName.get(),
count.getKey().getClientName(),
count.getKey().getTableName(),
count.getNumRows(),
count.getDateUpdated(),
count.getCountTimeMs(),
count.getNumSpans(),
count.getNumSlowSpans());
}
}
| {
"content_hash": "a60f6464c10d062abcf92b9bd013ee10",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 86,
"avg_line_length": 28.22222222222222,
"alnum_prop": 0.7921259842519685,
"repo_name": "hotpads/datarouter",
"id": "246cb13c1557cd1029200c5826c2675c306f242b",
"size": "1883",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "datarouter-nodewatch/src/main/java/io/datarouter/nodewatch/job/LatestTableCountPublisherJob.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "9438"
},
{
"name": "Java",
"bytes": "8616487"
},
{
"name": "JavaScript",
"bytes": "639471"
}
],
"symlink_target": ""
} |
(function(){
'use strict'
angular
.module('legislately')
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/home.html',
controller: 'HomeController as home'
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'AuthController as auth',
onEnter: function(Auth, $state) {
Auth.currentUser().then(function() {
$state.go('newsfeed');
})
}
})
.state('register', {
url: '/register',
templateUrl: 'views/register.html',
controller: 'AuthController as auth',
onEnter: function(Auth, $state) {
Auth.currentUser().then(function() {
$state.go('newsfeed')
})
}
})
.state('newsfeed', {
url: '/feed',
templateUrl: 'views/newsfeed.html',
controller: 'NewsfeedController as feed',
resolve: {
following: function(UserFactory) {
return UserFactory.following();
}
}
})
.state('show', {
url: '/legislators/:id',
templateUrl: 'views/show.html',
controller: 'ShowController as show',
resolve: {
info: function(LegislatorFactory, $stateParams) {
return LegislatorFactory.info($stateParams.id);
},
votes: function(LegislatorFactory, $stateParams) {
return LegislatorFactory.votes($stateParams.id);
},
following: function(UserFactory, $rootScope) {
if ($rootScope.user) {
return UserFactory.following();
}
}
}
})
.state('show.info', {
url: '/info',
templateUrl: 'views/show.info.html'
})
.state('show.activity', {
url: '/activity',
templateUrl: 'views/show.activity.html'
})
.state('coming-soon', {
url: '/coming-soon',
templateUrl: 'views/coming-soon.html',
controller: 'ComingSoonController as soon',
resolve: {
comingSoon: function(SCAPIFactory) {
return SCAPIFactory.getComingSoon();
}
}
})
.state('about', {
url: '/about',
templateUrl: 'views/about.html'
});
$urlRouterProvider.otherwise('/');
})
}());
| {
"content_hash": "2939508763cba90f3e5f04c0fdd285de",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 62,
"avg_line_length": 30.093023255813954,
"alnum_prop": 0.4864760432766615,
"repo_name": "radditude/legislately",
"id": "fec0778da749eab7a46f496dab652fe24bd160fa",
"size": "2588",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "app/assets/javascripts/routes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3052"
},
{
"name": "HTML",
"bytes": "26601"
},
{
"name": "JavaScript",
"bytes": "12308"
},
{
"name": "Ruby",
"bytes": "51140"
}
],
"symlink_target": ""
} |
package com.pygmalios.rawKafkaCassandra.akka24
import java.util.concurrent.ThreadLocalRandom
import akka.actor.{Actor, ActorRef, DeadLetterSuppression, Props, SupervisorStrategy, Terminated}
import scala.concurrent.duration.{Duration, FiniteDuration}
object BackoffSupervisor {
/**
* Props for creating an [[BackoffSupervisor]] actor.
*
* Exceptions in the child are handled with the default supervision strategy, i.e.
* most exceptions will immediately restart the child. You can define another
* supervision strategy by using [[propsWithSupervisorStrategy]].
*
* @param childProps the [[akka.actor.Props]] of the child actor that
* will be started and supervised
* @param childName name of the child actor
* @param minBackoff minimum (initial) duration until the child actor will
* started again, if it is terminated
* @param maxBackoff the exponential back-off is capped to this duration
* @param randomFactor after calculation of the exponential back-off an additional
* random delay based on this factor is added, e.g. `0.2` adds up to `20%` delay.
* In order to skip this additional delay pass in `0`.
*/
def props(
childProps: Props,
childName: String,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double): Props = {
propsWithSupervisorStrategy(childProps, childName, minBackoff, maxBackoff, randomFactor, SupervisorStrategy.defaultStrategy)
}
/**
* Props for creating an [[BackoffSupervisor]] actor with a custom
* supervision strategy.
*
* Exceptions in the child are handled with the given `supervisionStrategy`. A
* `Restart` will perform a normal immediate restart of the child. A `Stop` will
* stop the child, but it will be started again after the back-off duration.
*
* @param childProps the [[akka.actor.Props]] of the child actor that
* will be started and supervised
* @param childName name of the child actor
* @param minBackoff minimum (initial) duration until the child actor will
* started again, if it is terminated
* @param maxBackoff the exponential back-off is capped to this duration
* @param randomFactor after calculation of the exponential back-off an additional
* random delay based on this factor is added, e.g. `0.2` adds up to `20%` delay.
* In order to skip this additional delay pass in `0`.
* @param strategy the supervision strategy to use for handling exceptions
* in the child
*/
def propsWithSupervisorStrategy(
childProps: Props,
childName: String,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double,
strategy: SupervisorStrategy): Props = {
require(minBackoff > Duration.Zero, "minBackoff must be > 0")
require(maxBackoff >= minBackoff, "maxBackoff must be >= minBackoff")
require(0.0 <= randomFactor && randomFactor <= 1.0, "randomFactor must be between 0.0 and 1.0")
Props(new BackoffSupervisor(childProps, childName, minBackoff, maxBackoff, randomFactor, strategy))
}
/**
* Send this message to the [[BackoffSupervisor]] and it will reply with
* [[BackoffSupervisor.CurrentChild]] containing the `ActorRef` of the current child, if any.
*/
case object GetCurrentChild
/**
* Java API: Send this message to the [[BackoffSupervisor]] and it will reply with
* [[BackoffSupervisor.CurrentChild]] containing the `ActorRef` of the current child, if any.
*/
def getCurrentChild = GetCurrentChild
final case class CurrentChild(ref: Option[ActorRef]) {
/**
* Java API: The `ActorRef` of the current child, if any
*/
def getRef: Option[ActorRef] = ref
}
private case object StartChild extends DeadLetterSuppression
private case class ResetRestartCount(current: Int) extends DeadLetterSuppression
/**
* INTERNAL API
*
* Calculates an exponential back off delay.
*/
private[akka24] def calculateDelay(
restartCount: Int,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double): FiniteDuration = {
val rnd = 1.0 + ThreadLocalRandom.current().nextDouble() * randomFactor
if (restartCount >= 30) // Duration overflow protection (> 100 years)
maxBackoff
else
maxBackoff.min(minBackoff * math.pow(2, restartCount)) * rnd match {
case f: FiniteDuration => f
case _ => maxBackoff
}
}
}
/**
* This actor can be used to supervise a child actor and start it again
* after a back-off duration if the child actor is stopped.
*
* This is useful in situations where the re-start of the child actor should be
* delayed e.g. in order to give an external resource time to recover before the
* child actor tries contacting it again (after being restarted).
*
* Specifically this pattern is useful for for persistent actors,
* which are stopped in case of persistence failures.
* Just restarting them immediately would probably fail again (since the data
* store is probably unavailable). It is better to try again after a delay.
*
* It supports exponential back-off between the given `minBackoff` and
* `maxBackoff` durations. For example, if `minBackoff` is 3 seconds and
* `maxBackoff` 30 seconds the start attempts will be delayed with
* 3, 6, 12, 24, 30, 30 seconds. The exponential back-off counter is reset
* if the actor is not terminated within the `minBackoff` duration.
*
* In addition to the calculated exponential back-off an additional
* random delay based the given `randomFactor` is added, e.g. 0.2 adds up to 20%
* delay. The reason for adding a random delay is to avoid that all failing
* actors hit the backend resource at the same time.
*
* You can retrieve the current child `ActorRef` by sending `BackoffSupervisor.GetCurrentChild`
* message to this actor and it will reply with akka.pattern.BackoffSupervisor.CurrentChild
* containing the `ActorRef` of the current child, if any.
*
* The `BackoffSupervisor`delegates all messages from the child to the parent of the
* `BackoffSupervisor`, with the supervisor as sender.
*
* The `BackoffSupervisor` forwards all other messages to the child, if it is currently running.
*
* The child can stop itself and send a [[akka.actor.PoisonPill]] to the parent supervisor
* if it wants to do an intentional stop.
*
* Exceptions in the child are handled with the given `supervisionStrategy`. A
* `Restart` will perform a normal immediate restart of the child. A `Stop` will
* stop the child, but it will be started again after the back-off duration.
*/
final class BackoffSupervisor(
childProps: Props,
childName: String,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double,
override val supervisorStrategy: SupervisorStrategy)
extends Actor {
import BackoffSupervisor._
import context.dispatcher
private var child: Option[ActorRef] = None
private var restartCount = 0
// for binary compatibility with 2.4.0
def this(
childProps: Props,
childName: String,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double) =
this(childProps, childName, minBackoff, maxBackoff, randomFactor, SupervisorStrategy.defaultStrategy)
override def preStart(): Unit =
startChild()
def startChild(): Unit =
if (child.isEmpty) {
child = Some(context.watch(context.actorOf(childProps, childName)))
}
def receive = {
case Terminated(ref) if child.exists(_ == ref) =>
child = None
val restartDelay = calculateDelay(restartCount, minBackoff, maxBackoff, randomFactor)
context.system.scheduler.scheduleOnce(restartDelay, self, StartChild)
restartCount += 1
case StartChild =>
startChild()
context.system.scheduler.scheduleOnce(minBackoff, self, ResetRestartCount(restartCount))
case ResetRestartCount(current) =>
if (current == restartCount)
restartCount = 0
case GetCurrentChild =>
sender() ! CurrentChild(child)
case msg if child.exists(_ == sender()) =>
// use the BackoffSupervisor as sender
context.parent ! msg
case msg => child match {
case Some(c) => c.forward(msg)
case None => context.system.deadLetters.forward(msg)
}
}
}
| {
"content_hash": "ab981121547b59fb7a8edd4c2a4e3c17",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 128,
"avg_line_length": 42.240566037735846,
"alnum_prop": 0.667001675041876,
"repo_name": "pygmalios/raw-kafka-cassandra",
"id": "c182ae39ecf9f0b716b1c06cab9ca4633b57f3ee",
"size": "8955",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/pygmalios/rawKafkaCassandra/akka24/BackoffSupervisor.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "30284"
}
],
"symlink_target": ""
} |
Sandbox for [Polymer](https://www.polymer-project.org/) experiments.
I use [tapio/live-server](https://github.com/tapio/live-server) for all of my quick development projects. To get started:
```bash
npm install -g live-server
cd my-project
live-server .
```
The project will open in your default browser, and reload when changes are detected.
| {
"content_hash": "f85c2f2c029248d9d561bdc68269fd4e",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 121,
"avg_line_length": 31.454545454545453,
"alnum_prop": 0.7572254335260116,
"repo_name": "donmccurdy/sandbox-polymer",
"id": "b3b265612465a39a005c1ea7831033fa0762f7ab",
"size": "365",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12334"
},
{
"name": "HTML",
"bytes": "664686"
},
{
"name": "JavaScript",
"bytes": "852376"
}
],
"symlink_target": ""
} |
FROM balenalib/fincm3-ubuntu:disco-run
ENV GO_VERSION 1.16.3
# gcc for cgo
RUN apt-get update && apt-get install -y --no-install-recommends \
g++ \
gcc \
libc6-dev \
make \
pkg-config \
git \
&& rm -rf /var/lib/apt/lists/*
RUN set -x \
&& fetchDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $fetchDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-armv7hf.tar.gz" \
&& echo "0cfbfa848a1ab81e2aa2dd257c2b3572c3637d32562b1eaa6aeadb2909911606 go$GO_VERSION.linux-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-armv7hf.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu disco \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.3 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "1e796ed4faa7bf64bc919927cda6a227",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 671,
"avg_line_length": 50.58695652173913,
"alnum_prop": 0.706059303824667,
"repo_name": "nghiant2710/base-images",
"id": "d24f42efc8ff90a72a51ece8772f41d2d54711b8",
"size": "2348",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/golang/fincm3/ubuntu/disco/1.16.3/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
<?php
namespace TuxCoffeeCorner\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
class Charity
{
private $id_charity;
private $barcode;
private $organisation;
private $beginn;
private $ende;
private $spendenstand;
private $image = 'NoImage.jpg';
public function getId()
{
return $this->id_charity;
}
public function setBarcode($barcode)
{
$this->barcode = $barcode;
return $this;
}
public function getBarcode()
{
return $this->barcode;
}
public function setOrganisation($organisation)
{
$this->organisation = $organisation;
return $this;
}
public function getOrganisation()
{
return $this->organisation;
}
public function setBeginn($beginn)
{
$this->beginn = $beginn;
return $this;
}
public function getBeginn()
{
return $this->beginn;
}
public function setEnde($ende)
{
$this->ende = $ende;
return $this;
}
public function getEnde()
{
return $this->ende;
}
public function setSpendenstand($spendenstand)
{
$this->spendenstand = $spendenstand;
return $this;
}
public function getSpendenstand()
{
return $this->spendenstand;
}
public function setImage($image)
{
$this->image = $image;
return $this;
}
public function getImage()
{
return $this->image;
}
public function donate()
{
$this->spendenstand += 1;
return $this;
}
public function reset()
{
$this->spendenstand = 0;
return $this;
}
}
| {
"content_hash": "debbd270b61c9c34c09a6758c292950a",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 47,
"avg_line_length": 14.232323232323232,
"alnum_prop": 0.674237047551455,
"repo_name": "TuxCoffeeCorner/tcc",
"id": "55b66f4a9c7d788f6ecf53f6ac507d5fb4eb575f",
"size": "1409",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "symfony/src/TuxCoffeeCorner/CoreBundle/Entity/Charity.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "286"
},
{
"name": "CSS",
"bytes": "15193"
},
{
"name": "JavaScript",
"bytes": "18823"
},
{
"name": "PHP",
"bytes": "161843"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: kristjan
* Date: 9/18/14
* Time: 11:37 AM
*/
namespace Application\Controller\Plugin;
use Application\Common\Message\ErrorMessage;
use Application\View\Helper\Messages;
use Application\Common\Message;
class FlashMessenger extends \Zend\Mvc\Controller\Plugin\FlashMessenger {
const DEFAULT_MESSAGE_TYPE_ERROR = 'error';
const DEFAULT_MESSAGE_TYPE_INFO = 'info';
const DEFAULT_MESSAGE_TYPE_SUCCESS = 'success';
const DEFAULT_MESSAGE_TYPE_WARNING = 'warning';
public function addError($title, $description = null, array $messages = null) {
return $this->addSpecificMessage(self::DEFAULT_MESSAGE_TYPE_ERROR, $title, $description, $messages);
}
public function addInfo($title, $description = null, array $messages = null) {
return $this->addSpecificMessage(self::DEFAULT_MESSAGE_TYPE_INFO, $title, $description, $messages);
}
public function addSuccess($title, $description = null, array $messages = null) {
return $this->addSpecificMessage(self::DEFAULT_MESSAGE_TYPE_SUCCESS, $title, $description, $messages);
}
public function addWarning($title, $description = null, array $messages = null) {
return $this->addSpecificMessage(self::DEFAULT_MESSAGE_TYPE_WARNING, $title, $description, $messages);
}
public function addMessage($message) {
return $this->addSpecificMessage(self::DEFAULT_MESSAGE_TYPE_SUCCESS, $message);
}
public function addMessages($type, array $messages) {
foreach ($messages as $message) {
$this->addSpecificMessage(self::DEFAULT_MESSAGE_TYPE_SUCCESS, $message);
}
}
protected function addSpecificMessage($type, $title, $description = null, array $messages = null) {
$className = '\Application\Common\Message\\' . ucfirst($type) . 'Message';
if (!class_exists($className)) {
throw new \InvalidArgumentException('Class "' . $className . '" is undefined.');
}
$message = new $className($title, $description, $messages);
return parent::addMessage($message);
}
} | {
"content_hash": "a57962162a261b989f65d6a795ec3590",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 110,
"avg_line_length": 32.76923076923077,
"alnum_prop": 0.6765258215962441,
"repo_name": "kristjanAnd/SimpleIV",
"id": "eb26c768cb366418825a356bce6ee2583f60c086",
"size": "2130",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "module/Application/src/Application/Controller/Plugin/FlashMessenger.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1421"
},
{
"name": "JavaScript",
"bytes": "58984"
},
{
"name": "PHP",
"bytes": "421292"
}
],
"symlink_target": ""
} |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/monitoring/v3/group_service.proto
namespace Google\Cloud\Monitoring\V3;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The `CreateGroup` request.
*
* Generated from protobuf message <code>google.monitoring.v3.CreateGroupRequest</code>
*/
class CreateGroupRequest extends \Google\Protobuf\Internal\Message
{
/**
* Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) in
* which to create the group. The format is:
* projects/[PROJECT_ID_OR_NUMBER]
*
* Generated from protobuf field <code>string name = 4 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
*/
private $name = '';
/**
* Required. A group definition. It is an error to define the `name` field because
* the system assigns the name.
*
* Generated from protobuf field <code>.google.monitoring.v3.Group group = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private $group = null;
/**
* If true, validate this request but do not create the group.
*
* Generated from protobuf field <code>bool validate_only = 3;</code>
*/
private $validate_only = false;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $name
* Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) in
* which to create the group. The format is:
* projects/[PROJECT_ID_OR_NUMBER]
* @type \Google\Cloud\Monitoring\V3\Group $group
* Required. A group definition. It is an error to define the `name` field because
* the system assigns the name.
* @type bool $validate_only
* If true, validate this request but do not create the group.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Monitoring\V3\GroupService::initOnce();
parent::__construct($data);
}
/**
* Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) in
* which to create the group. The format is:
* projects/[PROJECT_ID_OR_NUMBER]
*
* Generated from protobuf field <code>string name = 4 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) in
* which to create the group. The format is:
* projects/[PROJECT_ID_OR_NUMBER]
*
* Generated from protobuf field <code>string name = 4 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {</code>
* @param string $var
* @return $this
*/
public function setName($var)
{
GPBUtil::checkString($var, True);
$this->name = $var;
return $this;
}
/**
* Required. A group definition. It is an error to define the `name` field because
* the system assigns the name.
*
* Generated from protobuf field <code>.google.monitoring.v3.Group group = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return \Google\Cloud\Monitoring\V3\Group|null
*/
public function getGroup()
{
return $this->group;
}
public function hasGroup()
{
return isset($this->group);
}
public function clearGroup()
{
unset($this->group);
}
/**
* Required. A group definition. It is an error to define the `name` field because
* the system assigns the name.
*
* Generated from protobuf field <code>.google.monitoring.v3.Group group = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @param \Google\Cloud\Monitoring\V3\Group $var
* @return $this
*/
public function setGroup($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Monitoring\V3\Group::class);
$this->group = $var;
return $this;
}
/**
* If true, validate this request but do not create the group.
*
* Generated from protobuf field <code>bool validate_only = 3;</code>
* @return bool
*/
public function getValidateOnly()
{
return $this->validate_only;
}
/**
* If true, validate this request but do not create the group.
*
* Generated from protobuf field <code>bool validate_only = 3;</code>
* @param bool $var
* @return $this
*/
public function setValidateOnly($var)
{
GPBUtil::checkBool($var);
$this->validate_only = $var;
return $this;
}
}
| {
"content_hash": "27654c7bcb952b0862e60a4f80f6733d",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 144,
"avg_line_length": 31.363057324840764,
"alnum_prop": 0.6133225020308692,
"repo_name": "googleapis/google-cloud-php",
"id": "91e79f540cba7d668c2e14a68cb53004beba41bb",
"size": "4924",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "Monitoring/src/V3/CreateGroupRequest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3333"
},
{
"name": "PHP",
"bytes": "47981731"
},
{
"name": "Python",
"bytes": "413107"
},
{
"name": "Shell",
"bytes": "8171"
}
],
"symlink_target": ""
} |
package com.lufs.java.cron;
import java.text.ParseException;
public class CronExpressTest {
public static void main(String [] args) throws ParseException {
String cron = "0 0 8-16 * * ?";
String cron1 = "0 0 8-16 * 1-5 ?";
String cron2 = "0 0 8-16 ? * 1-5";
CronExpression cronExpression = new CronExpression(cron2);
System.out.println(cronExpression);
}
}
| {
"content_hash": "31b265e896b26f611e70eed52c1723d5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 67,
"avg_line_length": 31.307692307692307,
"alnum_prop": 0.6314496314496314,
"repo_name": "pink-lucifer/preresearch",
"id": "293dd78f3f3d1a72362a72ee79030c49cb89b9ed",
"size": "407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core-java/src/main/java/com/lufs/java/cron/CronExpressTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "816"
},
{
"name": "CMake",
"bytes": "1715"
},
{
"name": "CSS",
"bytes": "111"
},
{
"name": "Go",
"bytes": "18461"
},
{
"name": "HTML",
"bytes": "275"
},
{
"name": "Java",
"bytes": "668209"
},
{
"name": "JavaScript",
"bytes": "31723"
},
{
"name": "Python",
"bytes": "444"
}
],
"symlink_target": ""
} |
import React, {Component} from 'react';
import {View, Text, Image, StyleSheet, TouchableOpacity, Linking} from 'react-native';
import {testHook} from './helpers/cavy.js';
import GLOBAL from './helpers/globals.js';
class ActionBar extends Component {
callNumber() {
this.openURL('tel:' + this.props.mobilePhone);
}
sendMessage() {
this.openURL('sms:' + this.props.mobilePhone);
}
sendMail() {
this.openURL('mailto:' + this.props.email);
}
openURL(url) {
Linking.canOpenURL(url).then(supported => {
if (!supported) {
console.log('Can\'t handle url: ' + url);
} else {
return Linking.openURL(url);
}
}).catch(err => console.error('An error occurred', err));
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity ref={GLOBAL.TEST_ENABLED ? this.props.generateTestHook('ActionBar.EmailButton') : 'EmailButton'} onPress={this.sendMail.bind(this)} style={styles.action}>
<Image source={require('./assets/email.png')} style={styles.icon} />
<Text style={styles.actionText}>email</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.callNumber.bind(this)} style={styles.action}>
<Image source={require('./assets/call.png')} style={styles.icon} />
<Text style={styles.actionText}>call</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.sendMessage.bind(this)} style={styles.action}>
<Image source={require('./assets/sms.png')} style={styles.icon} />
<Text style={styles.actionText}>message</Text>
</TouchableOpacity>
</View>
);
}
}
export default testHook(ActionBar);
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
justifyContent: 'space-around',
backgroundColor: '#FAFAFF',
paddingVertical: 8
},
action: {
flex: 1,
alignItems: 'center'
},
actionText: {
color: '#007AFF'
},
icon: {
height: 20,
width: 20
}
});
| {
"content_hash": "b9229a1f909e8dcec844de6d0c59ad31",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 180,
"avg_line_length": 28.422535211267604,
"alnum_prop": 0.6258671952428146,
"repo_name": "TGPSKI/cavy",
"id": "2505d56c5c28141015bcf9b5e32a405bd2c67b22",
"size": "2018",
"binary": false,
"copies": "1",
"ref": "refs/heads/cavy-suites",
"path": "sample-app/EmployeeDirectory/app/ActionBar.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1417"
},
{
"name": "JavaScript",
"bytes": "49908"
},
{
"name": "Objective-C",
"bytes": "4449"
},
{
"name": "Python",
"bytes": "1659"
}
],
"symlink_target": ""
} |
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
};
#endif
| {
"content_hash": "2d50ec3bb448875e53802016fc7960d1",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 37,
"avg_line_length": 11.1875,
"alnum_prop": 0.7039106145251397,
"repo_name": "stephaneAG/PengPod700",
"id": "2600e9a05e0ad04cbc709dc3b7c450778c16d5fc",
"size": "2172",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "QtEsrc/qt-everywhere-opensource-src-4.8.5/examples/webkit/simplewebplugin/mainwindow.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "167426"
},
{
"name": "Batchfile",
"bytes": "25368"
},
{
"name": "C",
"bytes": "3755463"
},
{
"name": "C#",
"bytes": "9282"
},
{
"name": "C++",
"bytes": "177871700"
},
{
"name": "CSS",
"bytes": "600936"
},
{
"name": "GAP",
"bytes": "758872"
},
{
"name": "GLSL",
"bytes": "32226"
},
{
"name": "Groff",
"bytes": "106542"
},
{
"name": "HTML",
"bytes": "273585110"
},
{
"name": "IDL",
"bytes": "1194"
},
{
"name": "JavaScript",
"bytes": "435912"
},
{
"name": "Makefile",
"bytes": "289373"
},
{
"name": "Objective-C",
"bytes": "1898658"
},
{
"name": "Objective-C++",
"bytes": "3222428"
},
{
"name": "PHP",
"bytes": "6074"
},
{
"name": "Perl",
"bytes": "291672"
},
{
"name": "Prolog",
"bytes": "102468"
},
{
"name": "Python",
"bytes": "22546"
},
{
"name": "QML",
"bytes": "3580408"
},
{
"name": "QMake",
"bytes": "2191574"
},
{
"name": "Scilab",
"bytes": "2390"
},
{
"name": "Shell",
"bytes": "116533"
},
{
"name": "TypeScript",
"bytes": "42452"
},
{
"name": "Visual Basic",
"bytes": "8370"
},
{
"name": "XQuery",
"bytes": "25094"
},
{
"name": "XSLT",
"bytes": "252382"
}
],
"symlink_target": ""
} |
/**
* Creates an anguilla command using a wrapper shorthand. The command will communicate with the web service
* to return a message.
*
* Note the ${PluginName} will get replaced by the actual plugin name.
*/
Alchemy.command("${PluginName}", "HelloWorld", {
/**
* Whether or not the command is enabled for the user (will usually have extensions displayed but disabled).
* @returns {boolean}
*/
isEnabled: function () {
return true;
},
/**
* Whether or not the command is available to the user.
* @returns {boolean}
*/
isAvailable: function () {
return true;
},
/**
* Executes your command. You can use _execute or execute as the property name.
*/
execute: function () {
var progress = $messages.registerProgress("Getting api version...", null),
userName = "AlchemyTester";d
// This is the error first callback pattern that the webapi proxy js exposes. Look at another example to
// see how the promise pattern can also be used.
// The call back must go as last parameter of action method.
Alchemy.Plugins["${PluginName}"].Api.Service.helloWorld(userName, function (error, message) {
progress.finish({ success: true });
if (error) {
// error will only exist if there was an error, otherwise it'll be null.
$messages.registerError("There was an error", error.message);
}
$messages.registerGoal(message, null);
});
}
}); | {
"content_hash": "5f690c3343f6e78c42b3e96c54c0312f",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 112,
"avg_line_length": 34.666666666666664,
"alnum_prop": 0.6147435897435898,
"repo_name": "Alchemy4Tridion/Alchemy4Tridion.Plugins.Sample.HelloWorld",
"id": "039d63ada8f35f3dacf38c27a6960f5e84759d93",
"size": "1562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Alchemy4Tridion.Plugins.Sample.HelloWorld/Static/Scripts/HelloWorldCommand.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "821"
},
{
"name": "C#",
"bytes": "13326"
},
{
"name": "CSS",
"bytes": "236"
},
{
"name": "JavaScript",
"bytes": "8452"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d6a6bf1b887f78d1882f9351eebf97b8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "bdaf506659f9e295c13b5883c5b49b33c3ac7931",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Aizoaceae/Papularia/Papularia crystallina/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef _SUNDIALS_TPETRA_INTERFACE_HPP_
#define _SUNDIALS_TPETRA_INTERFACE_HPP_
#include <Tpetra_Vector.hpp>
#include <nvector/nvector_trilinos.h>
namespace sundials
{
namespace trilinos
{
namespace nvector_tpetra
{
struct TpetraVectorInterface : public _N_VectorContent_Trilinos
{
// Typedef of Tpetra vector class to be used with SUNDIALS
typedef Tpetra::Vector<realtype, int, sunindextype> vector_type;
TpetraVectorInterface(Teuchos::RCP<vector_type> rcpvec)
{
rcpvec_ = rcpvec;
}
~TpetraVectorInterface() = default;
Teuchos::RCP<vector_type> rcpvec_;
};
} // namespace nvector_tpetra
} // namespace trilinos
} // namespace sundials
inline Teuchos::RCP<sundials::trilinos::nvector_tpetra::TpetraVectorInterface::vector_type> N_VGetVector_Trilinos(N_Vector v)
{
sundials::trilinos::nvector_tpetra::TpetraVectorInterface* iface =
reinterpret_cast<sundials::trilinos::nvector_tpetra::TpetraVectorInterface*>(v->content);
return iface->rcpvec_;
}
/*
* -----------------------------------------------------------------
* Function : N_VMake_Trilinos
* -----------------------------------------------------------------
* This function attaches N_Vector functions to a Tpetra vector.
* -----------------------------------------------------------------
*/
SUNDIALS_EXPORT N_Vector
N_VMake_Trilinos(Teuchos::RCP<sundials::trilinos::nvector_tpetra::TpetraVectorInterface::vector_type> v,
SUNContext sunctx);
#endif // _TPETRA_SUNDIALS_INTERFACE_HPP_
| {
"content_hash": "53a1bbf89328c0cc5a6be785c9af8616",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 125,
"avg_line_length": 26.344827586206897,
"alnum_prop": 0.6335078534031413,
"repo_name": "stan-dev/math",
"id": "7bfb2e55624c9ca57876eb7f68a4877b4260995d",
"size": "2061",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "lib/sundials_6.1.1/include/nvector/trilinos/SundialsTpetraVectorInterface.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "89079"
},
{
"name": "Assembly",
"bytes": "566183"
},
{
"name": "Batchfile",
"bytes": "33076"
},
{
"name": "C",
"bytes": "7093229"
},
{
"name": "C#",
"bytes": "54013"
},
{
"name": "C++",
"bytes": "166268432"
},
{
"name": "CMake",
"bytes": "820167"
},
{
"name": "CSS",
"bytes": "11283"
},
{
"name": "Cuda",
"bytes": "342187"
},
{
"name": "DIGITAL Command Language",
"bytes": "32438"
},
{
"name": "Dockerfile",
"bytes": "118"
},
{
"name": "Fortran",
"bytes": "2299405"
},
{
"name": "HTML",
"bytes": "8320473"
},
{
"name": "JavaScript",
"bytes": "38507"
},
{
"name": "M4",
"bytes": "10525"
},
{
"name": "Makefile",
"bytes": "74538"
},
{
"name": "Meson",
"bytes": "4233"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NASL",
"bytes": "106079"
},
{
"name": "Objective-C",
"bytes": "420"
},
{
"name": "Objective-C++",
"bytes": "420"
},
{
"name": "Pascal",
"bytes": "75208"
},
{
"name": "Perl",
"bytes": "47080"
},
{
"name": "Python",
"bytes": "1958975"
},
{
"name": "QMake",
"bytes": "18714"
},
{
"name": "Roff",
"bytes": "30570"
},
{
"name": "Ruby",
"bytes": "5532"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "SWIG",
"bytes": "5501"
},
{
"name": "Shell",
"bytes": "187001"
},
{
"name": "Starlark",
"bytes": "29435"
},
{
"name": "XSLT",
"bytes": "567938"
},
{
"name": "Yacc",
"bytes": "22343"
}
],
"symlink_target": ""
} |
package com.google.javascript.jscomp.parsing;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
/**
* All natively recognized JSDoc annotations.
*/
enum Annotation {
NG_INJECT,
ABSTRACT,
ALTERNATE_MESSAGE_ID,
AUTHOR,
CLOSURE_PRIMITIVE,
CONSTANT,
CONSTRUCTOR,
CUSTOM_ELEMENT,
RECORD,
DEFINE,
DEPRECATED,
DESC,
DICT,
ENUM,
EXTENDS,
EXTERNS,
EXPORT,
EXPOSE,
FILE_OVERVIEW,
FINAL,
HIDDEN,
IDGENERATOR,
IMPLEMENTS,
IMPLICIT_CAST,
INHERIT_DOC,
INTERFACE,
LENDS,
LICENSE, // same as preserve
MEANING,
MIXIN_CLASS,
MIXIN_FUNCTION,
MODIFIES,
NO_COLLAPSE,
NO_COMPILE,
NO_INLINE,
NO_SIDE_EFFECTS,
NOT_IMPLEMENTED,
OVERRIDE,
PACKAGE,
PARAM,
POLYMER,
POLYMER_BEHAVIOR,
PRESERVE, // same as license
PRIVATE,
PROTECTED,
PUBLIC,
RETURN,
SEE,
STRUCT,
SUPPRESS,
TEMPLATE,
THIS,
THROWS,
TYPE,
TYPEDEF,
TYPE_SUMMARY,
UNRESTRICTED,
VERSION,
WIZACTION;
static final Map<String, Annotation> recognizedAnnotations =
new ImmutableMap.Builder<String, Annotation>()
.put("ngInject", Annotation.NG_INJECT)
.put("abstract", Annotation.ABSTRACT)
.put("alternateMessageId", Annotation.ALTERNATE_MESSAGE_ID)
.put("argument", Annotation.PARAM)
.put("author", Annotation.AUTHOR)
.put("closurePrimitive", Annotation.CLOSURE_PRIMITIVE)
.put("const", Annotation.CONSTANT)
.put("constant", Annotation.CONSTANT)
.put("constructor", Annotation.CONSTRUCTOR)
.put("customElement", Annotation.CUSTOM_ELEMENT)
.put("copyright", Annotation.LICENSE)
.put("define", Annotation.DEFINE)
.put("deprecated", Annotation.DEPRECATED)
.put("desc", Annotation.DESC)
.put("dict", Annotation.DICT)
.put("enum", Annotation.ENUM)
.put("export", Annotation.EXPORT)
.put("expose", Annotation.EXPOSE)
.put("extends", Annotation.EXTENDS)
.put("externs", Annotation.EXTERNS)
.put("fileoverview", Annotation.FILE_OVERVIEW)
.put("final", Annotation.FINAL)
.put("hidden", Annotation.HIDDEN)
.put("idGenerator", Annotation.IDGENERATOR)
.put("implements", Annotation.IMPLEMENTS)
.put("implicitCast", Annotation.IMPLICIT_CAST)
.put("inheritDoc", Annotation.INHERIT_DOC)
.put("interface", Annotation.INTERFACE)
.put("record", Annotation.RECORD)
.put("lends", Annotation.LENDS)
.put("license", Annotation.LICENSE)
.put("meaning", Annotation.MEANING)
.put("mixinClass", Annotation.MIXIN_CLASS)
.put("mixinFunction", Annotation.MIXIN_FUNCTION)
.put("modifies", Annotation.MODIFIES)
.put("nocollapse", Annotation.NO_COLLAPSE)
.put("nocompile", Annotation.NO_COMPILE)
.put("noinline", Annotation.NO_INLINE)
.put("nosideeffects", Annotation.NO_SIDE_EFFECTS)
.put("override", Annotation.OVERRIDE)
.put("owner", Annotation.AUTHOR)
.put("package", Annotation.PACKAGE)
.put("param", Annotation.PARAM)
.put("polymer", Annotation.POLYMER)
.put("polymerBehavior", Annotation.POLYMER_BEHAVIOR)
.put("preserve", Annotation.PRESERVE)
.put("private", Annotation.PRIVATE)
.put("protected", Annotation.PROTECTED)
.put("public", Annotation.PUBLIC)
.put("return", Annotation.RETURN)
.put("returns", Annotation.RETURN)
.put("see", Annotation.SEE)
.put("struct", Annotation.STRUCT)
.put("suppress", Annotation.SUPPRESS)
.put("template", Annotation.TEMPLATE)
.put("this", Annotation.THIS)
.put("throws", Annotation.THROWS)
.put("type", Annotation.TYPE)
.put("typedef", Annotation.TYPEDEF)
.put("typeSummary", Annotation.TYPE_SUMMARY)
.put("unrestricted", Annotation.UNRESTRICTED)
.put("version", Annotation.VERSION)
.put("wizaction", Annotation.WIZACTION)
.build();
}
| {
"content_hash": "b4b6c87d9dd1be97d71fcaa9ddca3e1b",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 69,
"avg_line_length": 30.17391304347826,
"alnum_prop": 0.6231988472622478,
"repo_name": "vobruba-martin/closure-compiler",
"id": "2edf642d215b211cfede222ec8bdab4ef732892a",
"size": "4776",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/com/google/javascript/jscomp/parsing/Annotation.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2098"
},
{
"name": "Java",
"bytes": "16555335"
},
{
"name": "JavaScript",
"bytes": "7281930"
},
{
"name": "Shell",
"bytes": "724"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
public partial class XeroLinkedService : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
if (ConnectVia != null)
{
writer.WritePropertyName("connectVia");
writer.WriteObjectValue(ConnectVia);
}
if (Description != null)
{
writer.WritePropertyName("description");
writer.WriteStringValue(Description);
}
if (Parameters != null)
{
writer.WritePropertyName("parameters");
writer.WriteStartObject();
foreach (var item in Parameters)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
if (Annotations != null)
{
writer.WritePropertyName("annotations");
writer.WriteStartArray();
foreach (var item in Annotations)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
writer.WritePropertyName("typeProperties");
writer.WriteStartObject();
writer.WritePropertyName("host");
writer.WriteObjectValue(Host);
if (ConsumerKey != null)
{
writer.WritePropertyName("consumerKey");
writer.WriteObjectValue(ConsumerKey);
}
if (PrivateKey != null)
{
writer.WritePropertyName("privateKey");
writer.WriteObjectValue(PrivateKey);
}
if (UseEncryptedEndpoints != null)
{
writer.WritePropertyName("useEncryptedEndpoints");
writer.WriteObjectValue(UseEncryptedEndpoints);
}
if (UseHostVerification != null)
{
writer.WritePropertyName("useHostVerification");
writer.WriteObjectValue(UseHostVerification);
}
if (UsePeerVerification != null)
{
writer.WritePropertyName("usePeerVerification");
writer.WriteObjectValue(UsePeerVerification);
}
if (EncryptedCredential != null)
{
writer.WritePropertyName("encryptedCredential");
writer.WriteObjectValue(EncryptedCredential);
}
writer.WriteEndObject();
foreach (var item in AdditionalProperties)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
internal static XeroLinkedService DeserializeXeroLinkedService(JsonElement element)
{
string type = default;
IntegrationRuntimeReference connectVia = default;
string description = default;
IDictionary<string, ParameterSpecification> parameters = default;
IList<object> annotations = default;
object host = default;
SecretBase consumerKey = default;
SecretBase privateKey = default;
object useEncryptedEndpoints = default;
object useHostVerification = default;
object usePeerVerification = default;
object encryptedCredential = default;
IDictionary<string, object> additionalProperties = default;
Dictionary<string, object> additionalPropertiesDictionary = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("connectVia"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
connectVia = IntegrationRuntimeReference.DeserializeIntegrationRuntimeReference(property.Value);
continue;
}
if (property.NameEquals("description"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
description = property.Value.GetString();
continue;
}
if (property.NameEquals("parameters"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
Dictionary<string, ParameterSpecification> dictionary = new Dictionary<string, ParameterSpecification>();
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
dictionary.Add(property0.Name, null);
}
else
{
dictionary.Add(property0.Name, ParameterSpecification.DeserializeParameterSpecification(property0.Value));
}
}
parameters = dictionary;
continue;
}
if (property.NameEquals("annotations"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
List<object> array = new List<object>();
foreach (var item in property.Value.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.Null)
{
array.Add(null);
}
else
{
array.Add(item.GetObject());
}
}
annotations = array;
continue;
}
if (property.NameEquals("typeProperties"))
{
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("host"))
{
host = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("consumerKey"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
consumerKey = SecretBase.DeserializeSecretBase(property0.Value);
continue;
}
if (property0.NameEquals("privateKey"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
privateKey = SecretBase.DeserializeSecretBase(property0.Value);
continue;
}
if (property0.NameEquals("useEncryptedEndpoints"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
useEncryptedEndpoints = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("useHostVerification"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
useHostVerification = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("usePeerVerification"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
usePeerVerification = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("encryptedCredential"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
encryptedCredential = property0.Value.GetObject();
continue;
}
}
continue;
}
additionalPropertiesDictionary ??= new Dictionary<string, object>();
if (property.Value.ValueKind == JsonValueKind.Null)
{
additionalPropertiesDictionary.Add(property.Name, null);
}
else
{
additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject());
}
}
additionalProperties = additionalPropertiesDictionary;
return new XeroLinkedService(type, connectVia, description, parameters, annotations, additionalProperties, host, consumerKey, privateKey, useEncryptedEndpoints, useHostVerification, usePeerVerification, encryptedCredential);
}
}
}
| {
"content_hash": "32c3b4bee20919d22580b475810cbd6d",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 236,
"avg_line_length": 41.756972111553786,
"alnum_prop": 0.4490983684762904,
"repo_name": "stankovski/azure-sdk-for-net",
"id": "33a07938a4cbac30de0b84b433a41aaf7f7e0f85",
"size": "10619",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/XeroLinkedService.Serialization.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "33972632"
},
{
"name": "Cucumber",
"bytes": "89597"
},
{
"name": "Shell",
"bytes": "675"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<title>Parallel capture requests</title>
</head>
<body>
<button id="button">User gesture</button>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/resources/testdriver.js"></script>
<script src="/resources/testdriver-vendor.js"></script>
<script>
async function getDisplayMedia(constraints) {
const p = new Promise(r => button.onclick = r);
await test_driver.click(button);
await p;
return navigator.mediaDevices.getDisplayMedia(constraints);
}
promise_test(function() {
const getUserMediaPromise =
navigator.mediaDevices.getUserMedia({audio: true, video:true});
const getDisplayMediaPromise =
getDisplayMedia({video: true, audio: true});
return Promise.all([getUserMediaPromise, getDisplayMediaPromise])
.then(function(s) {
assert_greater_than_equal(s[0].getTracks().length, 1);
assert_less_than_equal(s[0].getTracks().length, 2);
assert_equals(s[0].getVideoTracks().length, 1);
assert_less_than_equal(s[0].getAudioTracks().length, 1);
assert_greater_than_equal(s[1].getTracks().length, 1);
assert_less_than_equal(s[1].getTracks().length, 2);
assert_equals(s[1].getVideoTracks().length, 1);
assert_less_than_equal(s[1].getAudioTracks().length, 1);
});
}, 'getDisplayMedia() and parallel getUserMedia()');
promise_test(function() {
const getDisplayMediaPromise =
getDisplayMedia({video: true, audio: true});
const getUserMediaPromise =
navigator.mediaDevices.getUserMedia({audio: true, video:true});
return Promise.all([getDisplayMediaPromise, getUserMediaPromise])
.then(function(s) {
assert_greater_than_equal(s[0].getTracks().length, 1);
assert_less_than_equal(s[0].getTracks().length, 2);
assert_equals(s[0].getVideoTracks().length, 1);
assert_less_than_equal(s[0].getAudioTracks().length, 1);
assert_greater_than_equal(s[1].getTracks().length, 1);
assert_less_than_equal(s[1].getTracks().length, 2);
assert_equals(s[1].getVideoTracks().length, 1);
assert_less_than_equal(s[1].getAudioTracks().length, 1);
});
}, 'getUserMedia() and parallel getDisplayMedia()');
</script>
</body>
</html>
| {
"content_hash": "a88d8a06473ed41f20aa23cbec34f1d6",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 71,
"avg_line_length": 40.35087719298246,
"alnum_prop": 0.68,
"repo_name": "chromium/chromium",
"id": "301515d1bd36ac294299f0a41e92b3abf01f1eb2",
"size": "2300",
"binary": false,
"copies": "12",
"ref": "refs/heads/main",
"path": "third_party/blink/web_tests/external/wpt/mediacapture-streams/parallel-capture-requests.https.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<resources>
<string name="app_name">ImitKakaotalk</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>
| {
"content_hash": "4944f5fa8a472c2f2f94ce5a54831cb1",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 52,
"avg_line_length": 30.5,
"alnum_prop": 0.6994535519125683,
"repo_name": "LJAYMORI/androidImitationKakaotalk",
"id": "767ac90b6c8e151917897e762d2fbc47a6b80d48",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/values/strings.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "5320"
}
],
"symlink_target": ""
} |
//
// SCListener 1.0.1
// http://github.com/stephencelis/sc_listener
//
// (c) 2009-* Stephen Celis, <stephen@stephencelis.com>.
// Released under the MIT License.
//
#ifdef USE_TI_MEDIA
#import "SCListener.h"
#import <AVFoundation/AVAudioSession.h>
@interface SCListener (Private)
- (void)updateLevels;
- (void)setupQueue;
- (void)setupFormat;
- (void)setupBuffers;
- (void)setupMetering;
@end
static SCListener *sharedListener = nil;
static void listeningCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp *inStartTime, UInt32 inNumberPacketsDescriptions, const AudioStreamPacketDescription *inPacketDescs) {
SCListener *listener = (SCListener *)inUserData;
if ([listener isListening])
AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, NULL);
}
@implementation SCListener
+ (SCListener *)sharedListener {
@synchronized(self) {
if (sharedListener == nil)
{
sharedListener = [[self alloc] init];
}
}
return sharedListener;
}
- (void)dealloc {
[sharedListener stop];
[super dealloc];
}
#pragma mark -
#pragma mark Listening
- (void)listen {
if (queue == nil)
[self setupQueue];
AudioQueueStart(queue, NULL);
}
- (void)pause {
if (![self isListening])
return;
AudioQueueStop(queue, true);
}
- (void)stop {
if (queue == nil)
return;
AudioQueueDispose(queue, true);
queue = nil;
}
- (BOOL)isListening {
if (queue == nil)
return NO;
UInt32 isListening, ioDataSize = sizeof(UInt32);
OSStatus result = AudioQueueGetProperty(queue, kAudioQueueProperty_IsRunning, &isListening, &ioDataSize);
return (result != noErr) ? NO : isListening;
}
#pragma mark -
#pragma mark Levels getters
- (Float32)averagePower {
if (![self isListening])
return 0.0;
return [self levels][0].mAveragePower;
}
- (Float32)peakPower {
if (![self isListening])
return 0.0;
return [self levels][0].mPeakPower;
}
- (AudioQueueLevelMeterState *)levels {
if (![self isListening])
return nil;
[self updateLevels];
return levels;
}
- (void)updateLevels {
UInt32 ioDataSize = format.mChannelsPerFrame * sizeof(AudioQueueLevelMeterState);
AudioQueueGetProperty(queue, (AudioQueuePropertyID)kAudioQueueProperty_CurrentLevelMeter, levels, &ioDataSize);
}
#pragma mark -
#pragma mark Setup
- (void)setupQueue {
if (queue)
return;
[self setupFormat];
[self setupBuffers];
AudioQueueNewInput(&format, listeningCallback, self, NULL, NULL, 0, &queue);
[self setupMetering];
}
- (void)setupFormat {
#if TARGET_IPHONE_SIMULATOR
format.mSampleRate = 44100.0;
#else
/*DrawerDemo Modification begin*/
// UInt32 ioDataSize = sizeof(sampleRate);
// AudioSessionGetProperty(kAudioSessionProperty_CurrentHardwareSampleRate, &ioDataSize, &sampleRate);
// format.mSampleRate = sampleRate;
sampleRate = [[AVAudioSession sharedInstance] sampleRate];
format.mSampleRate = sampleRate;
/*DrawerDemo Modifications End*/
#endif
format.mFormatID = kAudioFormatLinearPCM;
format.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
format.mFramesPerPacket = format.mChannelsPerFrame = 1;
format.mBitsPerChannel = 16;
format.mBytesPerPacket = format.mBytesPerFrame = 2;
}
- (void)setupBuffers {
AudioQueueBufferRef buffers[3];
for (NSInteger i = 0; i < 3; ++i) {
AudioQueueAllocateBuffer(queue, 735, &buffers[i]);
AudioQueueEnqueueBuffer(queue, buffers[i], 0, NULL);
}
}
- (void)setupMetering {
levels = (AudioQueueLevelMeterState *)calloc(sizeof(AudioQueueLevelMeterState), format.mChannelsPerFrame);
UInt32 trueValue = true;
AudioQueueSetProperty(queue, kAudioQueueProperty_EnableLevelMetering, &trueValue, sizeof(UInt32));
}
#pragma mark -
#pragma mark Singleton Pattern
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (sharedListener == nil) {
sharedListener = [super allocWithZone:zone];
return sharedListener;
}
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)init {
self = [super init];
return self;
}
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return UINT_MAX;
}
- (oneway void)release {
// Do nothing.
}
- (id)autorelease {
return self;
}
@end
#endif | {
"content_hash": "438a7ce0d72c6f8869dfa898a4c4bca3",
"timestamp": "",
"source": "github",
"line_count": 199,
"max_line_length": 221,
"avg_line_length": 20.959798994974875,
"alnum_prop": 0.7259649964037401,
"repo_name": "ma2016/AndroidIOSAlloyDrawerWidget",
"id": "7d192fbf611148d6836596cc2626a3fa93ce680c",
"size": "4171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/iphone/Classes/SCListener.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "120339"
},
{
"name": "C++",
"bytes": "13059"
},
{
"name": "CSS",
"bytes": "1276"
},
{
"name": "JavaScript",
"bytes": "316029"
},
{
"name": "Makefile",
"bytes": "1725590"
},
{
"name": "Objective-C",
"bytes": "3409373"
},
{
"name": "Objective-C++",
"bytes": "8645"
},
{
"name": "Perl",
"bytes": "188"
},
{
"name": "Python",
"bytes": "5251"
},
{
"name": "Shell",
"bytes": "1272"
}
],
"symlink_target": ""
} |
package cl.io.gateway.example.authservice;
import cl.io.gateway.IGateway;
import cl.io.gateway.auth.AuthenticationService;
import cl.io.gateway.auth.AuthenticationStatus;
import cl.io.gateway.auth.IAuthenticationGatewayNetworkService;
import cl.io.gateway.auth.IAuthenticationService;
import cl.io.gateway.messaging.NetworkServiceSource;
import cl.io.gateway.network.NetworkEvent;
import cl.io.gateway.network.NetworkEventType;
import cl.io.gateway.network.handler.INetworkEventListener;
import cl.io.gateway.vo.GatewayClient;
/**
* Sample class of authentication service. The @AuthenticationService annotation
* and the IAuthenticationService interface must be used for the framework to
* detect and initialize.
*
* This example service does not perform any authentication type, it only
* listens to network events and when a client connects it marks it as
* 'authenticated' and when it is disconnected it marks it as 'disconnected'.
*
* @author egacl
*
*/
@AuthenticationService(authProtocolEvents = { "LOGIN, LOGOUT" }, value = NetworkServiceSource.ADMIN)
public class ExampleAuthenticationService implements IAuthenticationService {
@Override
public void initialize(final IGateway gateway, final IAuthenticationGatewayNetworkService netService)
throws Exception {
System.out.println("Hello! I'm an authentication service!");
// a listener is added to capture client connection and disconnection network
// events
netService.addNetworkEventListener(new INetworkEventListener() {
@Override
public void onEvent(NetworkEvent event) {
if (event.getEventType() == NetworkEventType.ACTIVE) {
// when the network driver notifies a connected client, it is marked as
// 'authenticated' at the gateway
netService.clientAuthenticated(new GatewayClient(event.getChannelId()),
AuthenticationStatus.LOGGED_IN);
} else if (event.getEventType() == NetworkEventType.INACTIVE) {
// when the network driver notifies a client it is disconnected, then it is
// marked as 'disconnected' at the gateway
netService.clientAuthenticated(new GatewayClient(event.getChannelId()),
AuthenticationStatus.LOGGED_OUT);
}
}
});
}
}
| {
"content_hash": "6f47dcefd55ca67bf0062b96b9655bf4",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 105,
"avg_line_length": 45.2037037037037,
"alnum_prop": 0.6988938959442851,
"repo_name": "egacl/gatewayio",
"id": "0dc2c6fa430e4d2ce7af1b7e9810b3983c6a8ca4",
"size": "3063",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GatewayExample/src/main/java/cl/io/gateway/example/authservice/ExampleAuthenticationService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "127"
},
{
"name": "Java",
"bytes": "328998"
}
],
"symlink_target": ""
} |
package net.sf.kerner.utils.math;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestMathUtils3 {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public final void testGetClosest01() {
double c = UtilMath.getClosest(2.1, 3, 2, 1);
assertEquals(2, c, 0);
}
@Test
public final void testGetClosest02() {
double c = UtilMath.getClosest(0.9, 3, 2, 1);
assertEquals(1, c, 0);
}
@Test
public final void testGetClosest03() {
double c = UtilMath.getClosest(0.9, 3, 1, 2, 1);
assertEquals(1, c, 0);
}
@Test
public final void testGetClosest04() {
double c = UtilMath.getClosest(0.9, 3, 3, 1, 2, 1);
assertEquals(1, c, 0);
}
@Test
public final void testGetClosest05() {
double c = UtilMath.getClosest(1.9, 0, 1, 2, 3);
assertEquals(2, c, 0);
}
}
| {
"content_hash": "df2ea0e66b69b9a1ae962d0ff1466c11",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 62,
"avg_line_length": 21.694915254237287,
"alnum_prop": 0.61796875,
"repo_name": "SilicoSciences/net.sf.kerner.utils",
"id": "35b9eec18cb594f8ccc42a686ed8548c3536b166",
"size": "2066",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/net/sf/kerner/utils/math/TestMathUtils3.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "11156"
},
{
"name": "Java",
"bytes": "435842"
}
],
"symlink_target": ""
} |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Polymer('device-list', {
publish: {
/**
* The label of the list to be displayed.
* @type {string}
*/
label: 'Device List',
/**
* Info of the devices contained in the list.
* @type {Array.<DeviceInfo>}
*/
devices: null
},
/**
* Called when an instance is created.
*/
created: function() {
this.devices = [];
},
/**
* @param {string} reason The device ineligibility reason.
* @return {string} The prettified ineligibility reason.
* @private
*/
prettifyReason_: function(reason) {
if (reason == null)
return '';
var reasonWithSpaces = reason.replace(/([A-Z])/g, ' $1');
return reasonWithSpaces[0].toUpperCase() + reasonWithSpaces.slice(1);
},
/**
* @param {string} connectionStatus The Bluetooth connection status.
* @return {string} The icon id to be shown for the connection state.
* @private
*/
getIconForConnection_: function(connectionStatus) {
switch (connectionStatus) {
case 'connected':
return 'device:bluetooth-connected';
case 'disconnected':
return 'device:bluetooth';
case 'connecting':
return 'device:bluetooth-searching';
default:
return 'device:bluetooth-disabled';
}
},
/**
* @param {string} reason The device ineligibility reason.
* @return {string} The icon id to be shown for the ineligibility reason.
* @private
*/
getIconForIneligibilityReason_: function(reason) {
switch (reason) {
case 'badOsVersion':
return 'notification:system-update';
case 'bluetoothNotSupported':
return 'device:bluetooth-disabled';
case 'deviceOffline':
return 'device:signal-cellular-off';
case 'invalidCredentials':
return 'notification:sync-problem';
default:
return 'error';
};
}
});
| {
"content_hash": "b24ef4112cfecdf73c2558e75207cb8a",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 75,
"avg_line_length": 26.75,
"alnum_prop": 0.6261682242990654,
"repo_name": "guorendong/iridium-browser-ubuntu",
"id": "23e79183b483f6508f2bbb9ca93b03088b5ebd4c",
"size": "2033",
"binary": false,
"copies": "3",
"ref": "refs/heads/ubuntu/precise",
"path": "components/proximity_auth/webui/resources/device-list.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "8402"
},
{
"name": "Assembly",
"bytes": "256197"
},
{
"name": "Batchfile",
"bytes": "34966"
},
{
"name": "C",
"bytes": "15445429"
},
{
"name": "C++",
"bytes": "276628399"
},
{
"name": "CMake",
"bytes": "27829"
},
{
"name": "CSS",
"bytes": "867238"
},
{
"name": "Emacs Lisp",
"bytes": "3348"
},
{
"name": "Go",
"bytes": "13628"
},
{
"name": "Groff",
"bytes": "7777"
},
{
"name": "HTML",
"bytes": "20250399"
},
{
"name": "Java",
"bytes": "9950308"
},
{
"name": "JavaScript",
"bytes": "13873772"
},
{
"name": "LLVM",
"bytes": "1169"
},
{
"name": "Logos",
"bytes": "6893"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "Makefile",
"bytes": "179129"
},
{
"name": "Objective-C",
"bytes": "1871766"
},
{
"name": "Objective-C++",
"bytes": "9674498"
},
{
"name": "PHP",
"bytes": "42038"
},
{
"name": "PLpgSQL",
"bytes": "163248"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "474121"
},
{
"name": "Python",
"bytes": "11646662"
},
{
"name": "Ragel in Ruby Host",
"bytes": "104923"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "1151673"
},
{
"name": "Standard ML",
"bytes": "5034"
},
{
"name": "VimL",
"bytes": "4075"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
using NDiagnostics.Metering.Extensions;
using NDiagnostics.Metering.Samples;
using NDiagnostics.Metering.Types;
namespace NDiagnostics.Metering.Meters
{
internal sealed class MultiTimer100NsInverseMeter : Meter<MultiTimer100NsInverseSample>, IMultiTimer100NsInverse
{
#region Constructors and Destructors
public MultiTimer100NsInverseMeter(string categoryName, MeterCategoryType categoryType, string meterName, MeterType meterType, string instanceName, InstanceLifetime instanceLifetime, bool isReadOnly)
: base(categoryName, categoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly, true)
{
}
#endregion
#region IMeter
public override MultiTimer100NsInverseSample Current => this.GetCurrentSample();
public override void Reset()
{
this.ThrowIfDisposed();
this.ValueCounter.RawValue = 0L;
this.BaseCounter.RawValue = 0L;
}
#endregion
#region IMultiTimer100NsInverse
public void Sample(Time100Ns time)
{
this.ThrowIfDisposed();
this.ValueCounter.IncrementBy(time.Ticks);
this.BaseCounter.Increment();
}
#endregion
#region Methods
private MultiTimer100NsInverseSample GetCurrentSample()
{
var sample = this.ValueCounter.RawSample;
return new MultiTimer100NsInverseSample(new Time100Ns(sample.Value), sample.BaseValue, sample.TimeStamp, sample.TimeStamp100Ns);
}
#endregion
}
}
| {
"content_hash": "7c89e473054b88aadfa043ad7c4473db",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 207,
"avg_line_length": 30.75,
"alnum_prop": 0.6791744840525328,
"repo_name": "svolmer/NDiagnostics",
"id": "54382f889227eb013134e3015ef93e6785a1f98d",
"size": "1601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Metering/Meters/MultiTimer100NsInverseMeter.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "746"
},
{
"name": "C#",
"bytes": "174502"
},
{
"name": "PowerShell",
"bytes": "90975"
}
],
"symlink_target": ""
} |
<?php
require_once dirname(dirname(__FILE__)) . '/getTree.class.php';
class tpGetChunkTreeProcessor extends tpGetTreeProcessor {
public $classKey = 'modChunk';
public $categoryAlias = 'Chunks';
public $elementNodeId = 'chunk';
public $defaultSortField = 'name';
public $elementNameField = 'name';
}
return 'tpGetChunkTreeProcessor';
| {
"content_hash": "c3f9306c2c794b1a55d4dd183128ca96",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 63,
"avg_line_length": 35.3,
"alnum_prop": 0.7138810198300283,
"repo_name": "modxcms/ThemePackagerComponent",
"id": "b51050726eb6e48ece675a807a0951a6f8b87cba",
"size": "353",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "core/components/themepackagercomponent/processors/chunk/gettree.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "194"
},
{
"name": "JavaScript",
"bytes": "51568"
},
{
"name": "PHP",
"bytes": "166158"
}
],
"symlink_target": ""
} |
<!-- overview page content content -->
<div class="mdl-layout__tab-panel is-active" id="home">
<!-- installation card -->
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--2dp">
<!-- video may go here? -->
<header class="section__play-btn mdl-cell mdl-cell--3-col-desktop mdl-cell--2-col-tablet mdl-cell--4-col-phone mdl-color--teal-100 mdl-color-text--white">
<i class="material-icons">build</i>
</header>
<!-- features blurbr -->
<div class="mdl-card mdl-cell mdl-cell--9-col-desktop mdl-cell--6-col-tablet mdl-cell--4-col-phone">
<div class="mdl-card__supporting-text">
<h4>Install</h4>
There are two main methods of installation... either via:
<br><b>curl “way-cooler.org/releases/latest/install.sh” -sSf | sh</b><br><br>
...or via downloading a tarred version of Way Cooler and its client programs found
<a href="https://github.com/way-cooler/way-cooler#user-content-installation">here</a>
<br>(this will contain an install script that the user can run)
</div>
<div class="mdl-card__actions">
<a href="#" class="mdl-button">More install info here</a>
</div>
</div>
</section>
<!-- features card -->
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--2dp">
<!-- carousel placeholder pic -->
<header class="section__play-btn mdl-cell mdl-cell--3-col-desktop mdl-cell--2-col-tablet mdl-cell--4-col-phone mdl-color--teal-100 mdl-color-text--white">
<i class="material-icons">play_circle_filled</i>
</header>
<!-- features blurbr -->
<div class="mdl-card mdl-cell mdl-cell--9-col-desktop mdl-cell--6-col-tablet mdl-cell--4-col-phone">
<div class="mdl-card__supporting-text">
<h4>Features</h4>
<---- this is going to be a video. Dolore ex deserunt aute fugiat aute nulla ea sunt aliqua nisi cupidatat eu. Nostrud in laboris labore nisi amet do dolor eu fugiat consectetur elit cillum esse.
</div>
<div class="mdl-card__actions">
<a href="#features" class="mdl-button">Read our features</a>
</div>
</div>
</section>
<!-- details card -->
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--2dp">
<div class="mdl-card mdl-cell mdl-cell--12-col">
<div class="mdl-card__supporting-text mdl-grid mdl-grid--no-spacing">
<h4 class="mdl-cell mdl-cell--12-col">Details</h4>
<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">
<div class="section__circle-container__circle mdl-color--primary"></div>
</div>
<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">
<h5>Extensibility</h5>
Dolore ex deserunt aute fugiat aute nulla ea sunt aliqua nisi cupidatat eu. Duis nulla tempor do aute et eiusmod velit exercitation nostrud quis <a href="#install">proident minim</a>.
</div>
<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">
<div class="section__circle-container__circle mdl-color--primary"></div>
</div>
<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">
<h5>Configurability</h5>
Dolore ex deserunt aute fugiat aute nulla ea sunt aliqua nisi cupidatat eu. Duis nulla tempor do aute et eiusmod velit exercitation nostrud quis <a href="#">proident minim</a>.
</div>
<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">
<div class="section__circle-container__circle mdl-color--primary"></div>
</div>
<div class="section__text mdl-cell mdl-cell--10-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">
<h5>Security</h5>
Dolore ex deserunt aute fugiat aute nulla ea sunt aliqua nisi cupidatat eu. Duis nulla tempor do aute et eiusmod velit exercitation nostrud quis <a href="#">proident minim</a>.
</div>
</div>
<div class="mdl-card__actions">
<a href="#features" class="mdl-button">Read more...</a>
</div>
</div>
</section>
<br />
<!--<section class="section--footer mdl-color--white mdl-grid">
<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">
<div class="section__circle-container__circle mdl-color--accent section__circle--big"></div>
</div>
<div class="section__text mdl-cell mdl-cell--4-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">
<h5>Lorem ipsum dolor sit amet</h5>
Qui sint ut et qui nisi cupidatat. Reprehenderit nostrud proident officia exercitation anim et pariatur ex.
</div>
<div class="section__circle-container mdl-cell mdl-cell--2-col mdl-cell--1-col-phone">
<div class="section__circle-container__circle mdl-color--accent section__circle--big"></div>
</div>
<div class="section__text mdl-cell mdl-cell--4-col-desktop mdl-cell--6-col-tablet mdl-cell--3-col-phone">
<h5>Lorem ipsum dolor sit amet</h5>
Qui sint ut et qui nisi cupidatat. Reprehenderit nostrud proident officia exercitation anim et pariatur ex.
</div>
</section>-->
</div> | {
"content_hash": "e62be2dcb829e8bbb6f89541e583d227",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 203,
"avg_line_length": 54.12244897959184,
"alnum_prop": 0.6523378582202112,
"repo_name": "DCElemeno/Way-Cooler-mdlite",
"id": "e3106508ad699e880a9fde314d426f2779f1ba55",
"size": "5308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pages/home.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5691"
},
{
"name": "HTML",
"bytes": "26613"
},
{
"name": "JavaScript",
"bytes": "589"
},
{
"name": "PHP",
"bytes": "4170"
}
],
"symlink_target": ""
} |
from typing import Callable, List
import numpy as np
import pytest
import scipy.special
import tvm
from tvm import relay
def dequantize(data, scale, zp):
return scale * (np.asarray(data) - zp)
def generate_golden_output(
floating_point_golden_func, dequantized_x, output_scale, output_zero_point, dtype
):
output = floating_point_golden_func(dequantized_x)
output = np.around(output / output_scale + output_zero_point)
np_dtype = {"int8": np.int8, "uint8": np.uint8}[dtype]
q_min = np.iinfo(np_dtype).min
q_max = np.iinfo(np_dtype).max
return np.clip(output, q_min, q_max)
def run_qnn_func(func: relay.Function, args: List[relay.Expr]):
mod = tvm.IRModule.from_expr(func)
mod = relay.transform.InferType()(mod)
mod = relay.qnn.transform.Legalize()(mod)
mod = relay.qnn.transform.CanonicalizeOps()(mod)
func = mod["main"]
op_res = relay.create_executor("graph", device=tvm.cpu(0), target="llvm").evaluate(func)(*args)
return op_res.numpy()
def create_qnn_func(
qnn_op: Callable[[relay.Expr, relay.Expr, relay.Expr, relay.Expr, relay.Expr], relay.Call],
x_data: np.ndarray,
input_scale: float,
input_zero_point: int,
output_scale: float,
output_zero_point: int,
input_dtype: str = "uint8",
):
x = relay.var("x", shape=x_data.shape, dtype=input_dtype)
y = qnn_op(
x=x,
scale=relay.const(input_scale, "float32"),
zero_point=relay.const(input_zero_point, "int32"),
output_scale=relay.const(output_scale, "float32"),
output_zero_point=relay.const(output_zero_point, "int32"),
)
return relay.Function([x], y)
def run_condition(
qnn_op: Callable[[relay.Expr, relay.Expr, relay.Expr, relay.Expr, relay.Expr], relay.Call],
floating_point_golden_func: Callable[[np.ndarray], np.ndarray],
x_data: np.ndarray,
input_scale: float,
input_zero_point: int,
output_scale: float,
output_zero_point: int,
input_dtype: str = "uint8",
):
func = create_qnn_func(
qnn_op,
x_data,
input_scale=input_scale,
input_zero_point=input_zero_point,
output_scale=output_scale,
output_zero_point=output_zero_point,
input_dtype=input_dtype,
)
x_dequantized = dequantize(x_data, input_scale, input_zero_point)
golden_output = generate_golden_output(
floating_point_golden_func,
x_dequantized,
output_scale,
output_zero_point,
dtype=input_dtype,
)
op_res = run_qnn_func(func, [x_data])
np.testing.assert_equal(op_res, golden_output.astype(input_dtype))
def generic_test(
qnn_op: Callable[[relay.Expr, relay.Expr, relay.Expr, relay.Expr, relay.Expr], relay.Call],
floating_point_golden_func: Callable[[np.ndarray], np.ndarray],
input_dtype: str = "uint8",
x_data: np.ndarray = np.arange(0, 256, dtype="uint8"),
):
x_data = x_data.view(input_dtype)
return run_condition(
qnn_op,
floating_point_golden_func,
x_data,
input_scale=0.125,
input_zero_point=0,
output_scale=0.125,
output_zero_point=0,
input_dtype=input_dtype,
)
class TestRSqrt:
def test_saturation(self):
# Same qparams in and out
x_data = np.array((255, 133, 0, 9)).reshape((1, 4))
run_condition(
relay.qnn.op.rsqrt,
lambda x: 1 / np.sqrt(x),
x_data,
input_scale=0.125,
input_zero_point=0,
output_scale=0.125,
output_zero_point=0,
input_dtype="uint8",
)
# Different scale
run_condition(
relay.qnn.op.rsqrt,
lambda x: 1 / np.sqrt(x),
x_data,
input_scale=0.125,
input_zero_point=0,
output_scale=0.25,
output_zero_point=0,
input_dtype="uint8",
)
def test_all_numbers_uint8(self):
generic_test(relay.qnn.op.rsqrt, lambda x: 1 / np.sqrt(x), input_dtype="uint8")
def test_all_numbers_int8(self):
generic_test(
relay.qnn.op.rsqrt,
lambda x: 1 / np.sqrt(x),
input_dtype="int8",
x_data=np.arange(1, 128, dtype="int8"),
)
class Sqrt:
def test_all_numbers_uint8(self):
generic_test(relay.qnn.op.sqrt, np.sqrt, input_dtype="uint8")
def test_all_numbers_int8(self):
generic_test(
relay.qnn.op.sqrt,
np.sqrt,
input_dtype="int8",
x_data=np.arange(1, 128, dtype="int8"),
)
class TestExp:
def test_all_numbers_uint8(self):
generic_test(relay.qnn.op.exp, np.exp, input_dtype="uint8")
def test_all_numbers_int8(self):
generic_test(relay.qnn.op.exp, np.exp, input_dtype="int8")
class TestTanh:
def test_all_numbers_uint8(self):
generic_test(relay.qnn.op.tanh, np.tanh, input_dtype="uint8")
def test_all_numbers_int8(self):
generic_test(relay.qnn.op.tanh, np.tanh, input_dtype="int8")
class TestErf:
def test_all_numbers_uint8(self):
generic_test(relay.qnn.op.erf, scipy.special.erf, input_dtype="uint8")
def test_all_numbers_int8(self):
generic_test(relay.qnn.op.erf, scipy.special.erf, input_dtype="int8")
class TestSigmoid:
def test_all_numbers_uint8(self):
generic_test(relay.qnn.op.sigmoid, lambda x: 1 / (1 + np.exp(-x)), input_dtype="uint8")
def test_all_numbers_int8(self):
generic_test(relay.qnn.op.sigmoid, lambda x: 1 / (1 + np.exp(-x)), input_dtype="int8")
if __name__ == "__main__":
import sys
sys.exit(pytest.main([__file__]))
| {
"content_hash": "970a599bfff660e90730dca44c540fb5",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 99,
"avg_line_length": 28.888324873096447,
"alnum_prop": 0.6063960639606396,
"repo_name": "dmlc/tvm",
"id": "18acc119a9478b0c3eaa0196945dc8a6ef848cea",
"size": "6477",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tests/python/relay/test_op_qnn_unary_elementwise.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "6112"
},
{
"name": "C",
"bytes": "92947"
},
{
"name": "C++",
"bytes": "5765945"
},
{
"name": "CMake",
"bytes": "74045"
},
{
"name": "Go",
"bytes": "112384"
},
{
"name": "HTML",
"bytes": "8625"
},
{
"name": "Java",
"bytes": "171101"
},
{
"name": "JavaScript",
"bytes": "49803"
},
{
"name": "Makefile",
"bytes": "55807"
},
{
"name": "Objective-C",
"bytes": "15241"
},
{
"name": "Objective-C++",
"bytes": "46673"
},
{
"name": "Python",
"bytes": "7183810"
},
{
"name": "Rust",
"bytes": "181961"
},
{
"name": "Scala",
"bytes": "202148"
},
{
"name": "Shell",
"bytes": "97271"
},
{
"name": "Tcl",
"bytes": "53645"
},
{
"name": "Verilog",
"bytes": "30605"
}
],
"symlink_target": ""
} |
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/unistd.h>
#include <errno.h>
__syscall3(int, execve, const char*, path, char **, argv, char **, envp) ;
| {
"content_hash": "5f722fc398fc247364f9d0bdb62308d2",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 74,
"avg_line_length": 21.125,
"alnum_prop": 0.650887573964497,
"repo_name": "NEWPLAN/AIOS",
"id": "6ced98fc69ea2a3a4d4fbcbea037f23dce566eff",
"size": "830",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/libc/unistd/execve.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "22993"
},
{
"name": "C",
"bytes": "593672"
},
{
"name": "Lua",
"bytes": "24"
},
{
"name": "Makefile",
"bytes": "24479"
},
{
"name": "Shell",
"bytes": "8064"
}
],
"symlink_target": ""
} |
package ru.job4j.array;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Anton Rodionov
* @version $Id$
*/
public class TurnTest {
/**
* Test нечетное количество элементов в массиве.
*/
@Test
public void nechetMass() {
Turn trn = new Turn();
int[] mass = {1, 2, 3, 4, 5};
int[] resultArray = trn.back(mass);
int[] expectedArray = {5, 4, 3, 2, 1};
assertThat(resultArray, is(expectedArray));
}
/**
* Test четное количество элементов в массиве.
*/
@Test
public void chetMass() {
Turn trn = new Turn();
int[] masss = {1, 2, 3, 4};
int[] resultArray = trn.back(masss);
int[] expectedArray = {4, 3, 2, 1};
assertThat(resultArray, is(expectedArray));
}
} | {
"content_hash": "80175608ffe3dad410d13cc8ef6ee730",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 47,
"avg_line_length": 21.833333333333332,
"alnum_prop": 0.6272264631043257,
"repo_name": "AntonRodionov/arodionov",
"id": "2f4772045c1515dbe28d3355c9cf76ea43ae36af",
"size": "854",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_001/src/test/java/ru/job4j/array/TurnTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "40240"
}
],
"symlink_target": ""
} |
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/particle/shared_pt_buzzing_insects_small.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | {
"content_hash": "199fd1e554ae443ac6378cc4ec43fefe",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 79,
"avg_line_length": 23.692307692307693,
"alnum_prop": 0.6948051948051948,
"repo_name": "obi-two/Rebelion",
"id": "b854388c0625558e7ffbd796b3b8dccf8c9f1d77",
"size": "453",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "data/scripts/templates/object/static/particle/shared_pt_buzzing_insects_small.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "11818"
},
{
"name": "C",
"bytes": "7699"
},
{
"name": "C++",
"bytes": "2293610"
},
{
"name": "CMake",
"bytes": "39727"
},
{
"name": "PLSQL",
"bytes": "42065"
},
{
"name": "Python",
"bytes": "7499185"
},
{
"name": "SQLPL",
"bytes": "41864"
}
],
"symlink_target": ""
} |
#ifndef H_LUCY_TEST_UTIL_TESTNUMBERUTILS
#define H_LUCY_TEST_UTIL_TESTNUMBERUTILS 1
#ifdef __cplusplus
extern "C" {
#endif
#include "testlucy_parcel.h"
/* Include the header for this class's parent.
*/
#include "Clownfish/TestHarness/TestBatch.h"
/* Define the struct layout for instances of this class.
*/
#ifdef C_TESTLUCY_TESTNUMBERUTILS
extern uint32_t testlucy_TestNumUtil_IVARS_OFFSET;
typedef struct testlucy_TestNumberUtilsIVARS testlucy_TestNumberUtilsIVARS;
static CFISH_INLINE testlucy_TestNumberUtilsIVARS*
testlucy_TestNumUtil_IVARS(testlucy_TestNumberUtils *self) {
char *ptr = (char*)self + testlucy_TestNumUtil_IVARS_OFFSET;
return (testlucy_TestNumberUtilsIVARS*)ptr;
}
#ifdef TESTLUCY_USE_SHORT_NAMES
#define TestNumberUtilsIVARS testlucy_TestNumberUtilsIVARS
#define TestNumUtil_IVARS testlucy_TestNumUtil_IVARS
#endif
#endif /* C_TESTLUCY_TESTNUMBERUTILS */
/* Declare this class's inert variables.
*/
/* Declare both this class's inert functions and the C functions which
* implement this class's dynamic methods.
*/
TESTLUCY_VISIBLE testlucy_TestNumberUtils*
testlucy_TestNumUtil_new(void);
void
TESTLUCY_TestNumUtil_Run_IMP(testlucy_TestNumberUtils* self, cfish_TestBatchRunner* runner);
/* Define typedefs for each dynamic method, allowing us to cast generic
* pointers to the appropriate function pointer type more cleanly.
*/
typedef void*
(*TESTLUCY_TestNumUtil_To_Host_t)(testlucy_TestNumberUtils* self, void* vcache);
typedef cfish_Obj*
(*TESTLUCY_TestNumUtil_Clone_t)(testlucy_TestNumberUtils* self);
typedef bool
(*TESTLUCY_TestNumUtil_Equals_t)(testlucy_TestNumberUtils* self, cfish_Obj* other);
typedef int32_t
(*TESTLUCY_TestNumUtil_Compare_To_t)(testlucy_TestNumberUtils* self, cfish_Obj* other);
typedef void
(*TESTLUCY_TestNumUtil_Destroy_t)(testlucy_TestNumberUtils* self);
typedef cfish_String*
(*TESTLUCY_TestNumUtil_To_String_t)(testlucy_TestNumberUtils* self);
typedef void
(*TESTLUCY_TestNumUtil_Run_t)(testlucy_TestNumberUtils* self, cfish_TestBatchRunner* runner);
/* Define type-safe wrappers for inert functions of Obj.
*/
static CFISH_INLINE cfish_Class*
testlucy_TestNumUtil_get_class(testlucy_TestNumberUtils *self) {
return cfish_Obj_get_class((cfish_Obj*)self);
}
static CFISH_INLINE cfish_String*
testlucy_TestNumUtil_get_class_name(testlucy_TestNumberUtils *self) {
return cfish_Obj_get_class_name((cfish_Obj*)self);
}
static CFISH_INLINE bool
testlucy_TestNumUtil_is_a(testlucy_TestNumberUtils *self, cfish_Class *ancestor) {
return cfish_Obj_is_a((cfish_Obj*)self, ancestor);
}
/* Define the inline functions which implement this class's virtual methods.
*/
extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestNumUtil_To_Host_OFFSET;
static CFISH_INLINE void*
TESTLUCY_TestNumUtil_To_Host(testlucy_TestNumberUtils* self, void* vcache) {
const TESTLUCY_TestNumUtil_To_Host_t method = (TESTLUCY_TestNumUtil_To_Host_t)cfish_obj_method(self, TESTLUCY_TestNumUtil_To_Host_OFFSET);
return method(self, vcache);
}
extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestNumUtil_Clone_OFFSET;
static CFISH_INLINE cfish_Obj*
TESTLUCY_TestNumUtil_Clone(testlucy_TestNumberUtils* self) {
const TESTLUCY_TestNumUtil_Clone_t method = (TESTLUCY_TestNumUtil_Clone_t)cfish_obj_method(self, TESTLUCY_TestNumUtil_Clone_OFFSET);
return method(self);
}
extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestNumUtil_Equals_OFFSET;
static CFISH_INLINE bool
TESTLUCY_TestNumUtil_Equals(testlucy_TestNumberUtils* self, cfish_Obj* other) {
const TESTLUCY_TestNumUtil_Equals_t method = (TESTLUCY_TestNumUtil_Equals_t)cfish_obj_method(self, TESTLUCY_TestNumUtil_Equals_OFFSET);
return method(self, other);
}
extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestNumUtil_Compare_To_OFFSET;
static CFISH_INLINE int32_t
TESTLUCY_TestNumUtil_Compare_To(testlucy_TestNumberUtils* self, cfish_Obj* other) {
const TESTLUCY_TestNumUtil_Compare_To_t method = (TESTLUCY_TestNumUtil_Compare_To_t)cfish_obj_method(self, TESTLUCY_TestNumUtil_Compare_To_OFFSET);
return method(self, other);
}
extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestNumUtil_Destroy_OFFSET;
static CFISH_INLINE void
TESTLUCY_TestNumUtil_Destroy(testlucy_TestNumberUtils* self) {
const TESTLUCY_TestNumUtil_Destroy_t method = (TESTLUCY_TestNumUtil_Destroy_t)cfish_obj_method(self, TESTLUCY_TestNumUtil_Destroy_OFFSET);
method(self);
}
extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestNumUtil_To_String_OFFSET;
static CFISH_INLINE cfish_String*
TESTLUCY_TestNumUtil_To_String(testlucy_TestNumberUtils* self) {
const TESTLUCY_TestNumUtil_To_String_t method = (TESTLUCY_TestNumUtil_To_String_t)cfish_obj_method(self, TESTLUCY_TestNumUtil_To_String_OFFSET);
return method(self);
}
extern TESTLUCY_VISIBLE uint32_t TESTLUCY_TestNumUtil_Run_OFFSET;
static CFISH_INLINE void
TESTLUCY_TestNumUtil_Run(testlucy_TestNumberUtils* self, cfish_TestBatchRunner* runner) {
const TESTLUCY_TestNumUtil_Run_t method = (TESTLUCY_TestNumUtil_Run_t)cfish_obj_method(self, TESTLUCY_TestNumUtil_Run_OFFSET);
method(self, runner);
}
/* Declare callbacks for wrapping host overrides.
*/
#ifdef CFISH_NO_DYNAMIC_OVERRIDES
#else
#endif
/* Define "short names" for this class's symbols.
*/
#ifdef TESTLUCY_USE_SHORT_NAMES
#define TestNumberUtils testlucy_TestNumberUtils
#define TESTNUMBERUTILS TESTLUCY_TESTNUMBERUTILS
#define TestNumUtil_new testlucy_TestNumUtil_new
#define TestNumUtil_get_class testlucy_TestNumUtil_get_class
#define TestNumUtil_get_class_name testlucy_TestNumUtil_get_class_name
#define TestNumUtil_is_a testlucy_TestNumUtil_is_a
#define TestNumUtil_Run_IMP TESTLUCY_TestNumUtil_Run_IMP
#define TestNumUtil_To_Host TESTLUCY_TestNumUtil_To_Host
#define TestNumUtil_To_Host_t TESTLUCY_TestNumUtil_To_Host_t
#define TestNumUtil_Clone TESTLUCY_TestNumUtil_Clone
#define TestNumUtil_Clone_t TESTLUCY_TestNumUtil_Clone_t
#define TestNumUtil_Equals TESTLUCY_TestNumUtil_Equals
#define TestNumUtil_Equals_t TESTLUCY_TestNumUtil_Equals_t
#define TestNumUtil_Compare_To TESTLUCY_TestNumUtil_Compare_To
#define TestNumUtil_Compare_To_t TESTLUCY_TestNumUtil_Compare_To_t
#define TestNumUtil_Destroy TESTLUCY_TestNumUtil_Destroy
#define TestNumUtil_Destroy_t TESTLUCY_TestNumUtil_Destroy_t
#define TestNumUtil_To_String TESTLUCY_TestNumUtil_To_String
#define TestNumUtil_To_String_t TESTLUCY_TestNumUtil_To_String_t
#define TestNumUtil_Run TESTLUCY_TestNumUtil_Run
#define TestNumUtil_Run_t TESTLUCY_TestNumUtil_Run_t
#endif /* TESTLUCY_USE_SHORT_NAMES */
#ifdef __cplusplus
}
#endif
#endif /* H_LUCY_TEST_UTIL_TESTNUMBERUTILS */
| {
"content_hash": "dca790d13a4fa76cd01795e9a9030032",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 151,
"avg_line_length": 32.94059405940594,
"alnum_prop": 0.7877968139464984,
"repo_name": "QuantamHD/LucyJS",
"id": "6cb19cf756553ca07cc5f492e9c7d40a06a8d5f2",
"size": "7640",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "external/includes/unix/Lucy/Test/Util/TestNumberUtils.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4338"
},
{
"name": "C++",
"bytes": "19887"
},
{
"name": "JavaScript",
"bytes": "7412"
},
{
"name": "Python",
"bytes": "1575"
}
],
"symlink_target": ""
} |
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="hackhou.fencehouston.fencehouston.DrawerMainActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="@+id/navigation_drawer"
android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="hackhou.fencehouston.fencehouston.NavigationDrawerFragment"
tools:layout="@layout/fragment_navigation_main_drawer" />
</android.support.v4.widget.DrawerLayout>
| {
"content_hash": "8c087c53c48b3f6428ac08d7488b92cc",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 158,
"avg_line_length": 62.76,
"alnum_prop": 0.7202039515615042,
"repo_name": "aaron7pm/FenceHouston",
"id": "909acd94cb44331bd7caf14c4b5a76b3b48c6e98",
"size": "1569",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_drawer_main.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "90739"
}
],
"symlink_target": ""
} |
# -*- coding: iso-8859-1 -*-
"""Testcases for cssutils.stylesheets.MediaList"""
import xml.dom
import basetest
import cssutils.stylesheets
class MediaQueryTestCase(basetest.BaseTestCase):
def setUp(self):
super(MediaQueryTestCase, self).setUp()
self.r = cssutils.stylesheets.MediaQuery()
def test_mediaText(self):
"MediaQuery.mediaText"
tests = {
u'all': None,
u'braille': None,
u'embossed': None,
u'handheld': None,
u'print': None,
u'projection': None,
u'screen': None,
u'speech': None,
u'tty': None,
u'tv': None,
u'ALL': None,
u'a\\ll': None,
u'not tv': None,
u'n\\ot t\\v': None,
u'only tv': None,
u'\\only \\tv': None,
u'PRINT': None,
u'NOT PRINT': None,
u'ONLY PRINT': None,
u'tv and (color)': None,
u'not tv and (color)': None,
u'only tv and (color)': None,
}
self.do_equal_r(tests, att='mediaText')
tests = {
u'': xml.dom.SyntaxErr,
u'two values': xml.dom.SyntaxErr,
u'or even three': xml.dom.SyntaxErr,
u'print and(color)': xml.dom.SyntaxErr, # a function
u'aural': xml.dom.InvalidCharacterErr, # a dimension
u'3d': xml.dom.InvalidCharacterErr, # a dimension
}
self.do_raise_r(tests, att='_setMediaText')
def test_mediaType(self):
"MediaQuery.mediaType"
mq = cssutils.stylesheets.MediaQuery()
self.assertEqual(u'', mq.mediaText)
for mt in cssutils.stylesheets.MediaQuery.MEDIA_TYPES:
mq.mediaType = mt
self.assertEqual(mq.mediaType, mt)
mq.mediaType = mt.upper()
self.assertEqual(mq.mediaType, mt.upper())
mt = u'3D-UNKOwn-MEDIAtype0123'
#mq.mediaType = mt
self.assertRaises(xml.dom.InvalidCharacterErr, mq._setMediaType, mt)
def test_comments(self):
"MediaQuery.mediaText comments"
tests = {
u'all': None,
u'print': None,
u'not print': None,
u'only print': None,
u'print and (color)': None,
u'print and (color) and (width)': None,
u'print and (color: 2)': None,
u'print and (min-width: 100px)': None,
u'print and (min-width: 100px) and (color: red)': None,
u'not print and (min-width: 100px)': None,
u'only print and (min-width: 100px)': None,
u'/*1*/ tv /*2*/': None,
u'/*0*/ only /*1*/ tv /*2*/': None,
u'/*0* /not /*1*/ tv /*2*/': None,
u'/*x*/ only /*x*/ print /*x*/ and /*x*/ (/*x*/min-width/*x*/: /*x*/ 100px /*x*/)': None,
u'print and/*1*/(color)': u'print and /*1*/ (color)'
}
self.do_equal_r(tests, att='mediaText')
def test_reprANDstr(self):
"MediaQuery.__repr__(), .__str__()"
mediaText='tv and (color)'
s = cssutils.stylesheets.MediaQuery(mediaText=mediaText)
self.assert_(mediaText in str(s))
s2 = eval(repr(s))
self.assertEqual(mediaText, s2.mediaText)
self.assert_(isinstance(s2, s.__class__))
if __name__ == '__main__':
import unittest
unittest.main()
| {
"content_hash": "12b9dd042e473f6247820f4fc2df1577",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 101,
"avg_line_length": 34.627450980392155,
"alnum_prop": 0.4980181200453001,
"repo_name": "bslatkin/8-bits",
"id": "83ff6cfbfabbaf3efb3330d149d8d64590d70632",
"size": "3532",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tools/cssutils/src/cssutils/tests/test_mediaquery.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "673198"
},
{
"name": "JavaScript",
"bytes": "235999"
},
{
"name": "Python",
"bytes": "2125221"
},
{
"name": "Shell",
"bytes": "13761"
}
],
"symlink_target": ""
} |
import { Command } from 'commander';
import bootstrap from './cmds/bootstrap';
import configure from './cmds/configure';
import backup from './cmds/backup';
import restore from './cmds/restore';
import upload from './cmds/upload';
import chalk from 'chalk';
const program = new Command();
// TODO
// bootstrap:
// Check whether config.json exists
// If config.json exists, import it
// Ask which categories in .runtimeconfig.json should be imported
// - Ask which new categories (names) should be created
// - Ask for the slug for each category
// - Add name/slug objects to .runtimeconfig.json
// Save .runtimeconfig.json
console.log(`Gettin' spooky 👻 with ${chalk.hex('#fedc5d').bold('poltergeist')}`);
program.version('0.0.0', '-v, --version');
program
.command('bootstrap [destination]')
.description('bootstrap project')
.action(bootstrap);
program
.command('configure')
.description('configure project')
.action(configure);
program
.command('backup [destination]')
.option('--configuration', 'backup configuration')
.option('--firestore', 'backup Firestore')
.option('--storage', 'backup storage')
.option('--accounts', 'backup accounts')
.description('backup project data')
.action(backup);
program
.command('restore [source]')
.option('--configuration', 'restore configuration')
.option('--firestore', 'restore Firestore')
.option('--storage', 'restore storage')
.option('--accounts', 'restore accounts')
.description('restore backup folder to project')
.action(restore);
program
.command('upload')
.description('upload file or directory content')
.action(upload);
program.parse(process.argv);
| {
"content_hash": "18f7b6d98c5e0f09181762f88c94202a",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 82,
"avg_line_length": 28.70689655172414,
"alnum_prop": 0.7039039039039039,
"repo_name": "accosine/poltergeist",
"id": "74255c92f052a221dc31f7d5c2a288d940398100",
"size": "1688",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/cli/src/cli.ts",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "3105"
},
{
"name": "JavaScript",
"bytes": "384610"
},
{
"name": "TypeScript",
"bytes": "16131"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Sep 05 03:08:45 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.microprofile.jwtauth.deployment.auth.jaas (BOM: * : All 2.2.0.Final API)</title>
<meta name="date" content="2018-09-05">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../../../../org/wildfly/swarm/microprofile/jwtauth/deployment/auth/jaas/package-summary.html" target="classFrame">org.wildfly.swarm.microprofile.jwtauth.deployment.auth.jaas</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="JWTCredential.html" title="class in org.wildfly.swarm.microprofile.jwtauth.deployment.auth.jaas" target="classFrame">JWTCredential</a></li>
<li><a href="JWTLoginModule.html" title="class in org.wildfly.swarm.microprofile.jwtauth.deployment.auth.jaas" target="classFrame">JWTLoginModule</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "1adbf335d01a6d95440ca2b24f60ea17",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 219,
"avg_line_length": 57.68181818181818,
"alnum_prop": 0.6847911741528763,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "a42cd95de3ac3c05e43c0d4aa7033a19a1c46d74",
"size": "1269",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.2.0.Final/apidocs/org/wildfly/swarm/microprofile/jwtauth/deployment/auth/jaas/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace hawkeye.Core.Presentation.ViewModel
{
public interface ISupportBusy
{
BusyViewModel BusyViewModel { get; }
}
} | {
"content_hash": "6d47f7a68b036a4649bca19cfa7a2141",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 45,
"avg_line_length": 20,
"alnum_prop": 0.6928571428571428,
"repo_name": "xjpeter/hawkeye",
"id": "9709946620a8e15b8d61e3aec3fc29140d1377af",
"size": "140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hawkeye/Core/Presentation/ViewModel/ISupportBusy.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "49206"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "8eb9678d099e849aba251ebb79cb08e2",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "88ab93f3a65fbb0b9d7c500b51866068d56954c0",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Acanthaceae/Hemigraphis/Hemigraphis szechuanica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import {
DirectionalLight,
Group,
LightProbe,
WebGLCubeRenderTarget
} from "../../../build/three.module.js";
class SessionLightProbe {
constructor( xrLight, renderer, lightProbe, environmentEstimation, estimationStartCallback ) {
this.xrLight = xrLight;
this.renderer = renderer;
this.lightProbe = lightProbe;
this.xrWebGLBinding = null;
this.estimationStartCallback = estimationStartCallback;
this.frameCallback = this.onXRFrame.bind( this );
const session = renderer.xr.getSession();
// If the XRWebGLBinding class is available then we can also query an
// estimated reflection cube map.
if ( environmentEstimation && 'XRWebGLBinding' in window ) {
// This is the simplest way I know of to initialize a WebGL cubemap in Three.
const cubeRenderTarget = new WebGLCubeRenderTarget( 16 );
xrLight.environment = cubeRenderTarget.texture;
const gl = renderer.getContext();
// Ensure that we have any extensions needed to use the preferred cube map format.
switch ( session.preferredReflectionFormat ) {
case 'srgba8':
gl.getExtension( 'EXT_sRGB' );
break;
case 'rgba16f':
gl.getExtension( 'OES_texture_half_float' );
break;
}
this.xrWebGLBinding = new XRWebGLBinding( session, gl );
this.lightProbe.addEventListener('reflectionchange', () => {
this.updateReflection();
});
}
// Start monitoring the XR animation frame loop to look for lighting
// estimation changes.
session.requestAnimationFrame( this.frameCallback );
}
updateReflection() {
const textureProperties = this.renderer.properties.get( this.xrLight.environment );
if ( textureProperties ) {
const cubeMap = this.xrWebGLBinding.getReflectionCubeMap( this.lightProbe );
if ( cubeMap ) {
textureProperties.__webglTexture = cubeMap;
}
}
}
onXRFrame( time, xrFrame ) {
// If either this obejct or the XREstimatedLight has been destroyed, stop
// running the frame loop.
if ( ! this.xrLight ) {
return;
}
const session = xrFrame.session;
session.requestAnimationFrame( this.frameCallback );
const lightEstimate = xrFrame.getLightEstimate( this.lightProbe );
if ( lightEstimate ) {
// We can copy the estimate's spherical harmonics array directly into the light probe.
this.xrLight.lightProbe.sh.fromArray( lightEstimate.sphericalHarmonicsCoefficients );
this.xrLight.lightProbe.intensity = 1.0;
// For the directional light we have to normalize the color and set the scalar as the
// intensity, since WebXR can return color values that exceed 1.0.
const intensityScalar = Math.max( 1.0,
Math.max( lightEstimate.primaryLightIntensity.x,
Math.max( lightEstimate.primaryLightIntensity.y,
lightEstimate.primaryLightIntensity.z ) ) );
this.xrLight.directionalLight.color.setRGB(
lightEstimate.primaryLightIntensity.x / intensityScalar,
lightEstimate.primaryLightIntensity.y / intensityScalar,
lightEstimate.primaryLightIntensity.z / intensityScalar );
this.xrLight.directionalLight.intensity = intensityScalar;
this.xrLight.directionalLight.position.copy( lightEstimate.primaryLightDirection );
if ( this.estimationStartCallback ) {
this.estimationStartCallback();
this.estimationStartCallback = null;
}
}
}
dispose() {
this.xrLight = null;
this.renderer = null;
this.lightProbe = null;
this.xrWebGLBinding = null;
}
}
export class XREstimatedLight extends Group {
constructor( renderer, environmentEstimation = true ) {
super();
this.lightProbe = new LightProbe();
this.lightProbe.intensity = 0;
this.add( this.lightProbe );
this.directionalLight = new DirectionalLight();
this.directionalLight.intensity = 0;
this.add( this.directionalLight );
// Will be set to a cube map in the SessionLightProbe is environment estimation is
// available and requested.
this.environment = null;
let sessionLightProbe = null;
let estimationStarted = false;
renderer.xr.addEventListener( 'sessionstart', () => {
const session = renderer.xr.getSession();
if ( 'requestLightProbe' in session ) {
session.requestLightProbe( {
reflectionFormat: session.preferredReflectionFormat
} ).then( ( probe ) => {
sessionLightProbe = new SessionLightProbe( this, renderer, probe, environmentEstimation, () => {
estimationStarted = true;
// Fired to indicate that the estimated lighting values are now being updated.
this.dispatchEvent( { type: 'estimationstart' } );
} );
} );
}
} );
renderer.xr.addEventListener( 'sessionend', () => {
if ( sessionLightProbe ) {
sessionLightProbe.dispose();
sessionLightProbe = null;
}
if ( estimationStarted ) {
// Fired to indicate that the estimated lighting values are no longer being updated.
this.dispatchEvent( { type: 'estimationend' } );
}
} );
// Done inline to provide access to sessionLightProbe.
this.dispose = () => {
if ( sessionLightProbe ) {
sessionLightProbe.dispose();
sessionLightProbe = null;
}
this.remove( this.lightProbe );
this.lightProbe = null;
this.remove( this.directionalLight );
this.directionalLight = null;
this.environment = null;
};
}
}
| {
"content_hash": "91b0300fbc4660c9cb5109bcac0bd544",
"timestamp": "",
"source": "github",
"line_count": 221,
"max_line_length": 101,
"avg_line_length": 23.873303167420815,
"alnum_prop": 0.7067854435178166,
"repo_name": "opensim-org/three.js",
"id": "60c27f0b2d65d5b91dbc12046dd8445e69daa171",
"size": "5276",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/jsm/webxr/XREstimatedLight.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "36195"
},
{
"name": "GLSL",
"bytes": "2572"
},
{
"name": "HTML",
"bytes": "22677"
},
{
"name": "JavaScript",
"bytes": "6171747"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.php.project</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/php-project/1">
<name>encyclopedia-cthulhiana.dev</name>
</data>
</configuration>
</project>
| {
"content_hash": "edad2f9024d2d22868f14b26e359935f",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 63,
"avg_line_length": 36.55555555555556,
"alnum_prop": 0.6382978723404256,
"repo_name": "muirgen/encyclopedia-cthulhiana.dev",
"id": "62950e5a9ad56e6b5ce0b90ab4020a230fd780ff",
"size": "329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nbproject/project.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "4370"
},
{
"name": "CSS",
"bytes": "186990"
},
{
"name": "HTML",
"bytes": "32754"
},
{
"name": "JavaScript",
"bytes": "37601"
},
{
"name": "PHP",
"bytes": "325137"
}
],
"symlink_target": ""
} |
package com.microsoft.azure.management.network.v2020_06_01.implementation;
import java.util.List;
import com.microsoft.azure.management.network.v2020_06_01.ProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.rest.SkipParentValidation;
import com.microsoft.azure.Resource;
/**
* Virtual Network Tap resource.
*/
@JsonFlatten
@SkipParentValidation
public class VirtualNetworkTapInner extends Resource {
/**
* Specifies the list of resource IDs for the network interface IP
* configuration that needs to be tapped.
*/
@JsonProperty(value = "properties.networkInterfaceTapConfigurations", access = JsonProperty.Access.WRITE_ONLY)
private List<NetworkInterfaceTapConfigurationInner> networkInterfaceTapConfigurations;
/**
* The resource GUID property of the virtual network tap resource.
*/
@JsonProperty(value = "properties.resourceGuid", access = JsonProperty.Access.WRITE_ONLY)
private String resourceGuid;
/**
* The provisioning state of the virtual network tap resource. Possible
* values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*/
@JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/**
* The reference to the private IP Address of the collector nic that will
* receive the tap.
*/
@JsonProperty(value = "properties.destinationNetworkInterfaceIPConfiguration")
private NetworkInterfaceIPConfigurationInner destinationNetworkInterfaceIPConfiguration;
/**
* The reference to the private IP address on the internal Load Balancer
* that will receive the tap.
*/
@JsonProperty(value = "properties.destinationLoadBalancerFrontEndIPConfiguration")
private FrontendIPConfigurationInner destinationLoadBalancerFrontEndIPConfiguration;
/**
* The VXLAN destination port that will receive the tapped traffic.
*/
@JsonProperty(value = "properties.destinationPort")
private Integer destinationPort;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
@JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
private String etag;
/**
* Resource ID.
*/
@JsonProperty(value = "id")
private String id;
/**
* Get specifies the list of resource IDs for the network interface IP configuration that needs to be tapped.
*
* @return the networkInterfaceTapConfigurations value
*/
public List<NetworkInterfaceTapConfigurationInner> networkInterfaceTapConfigurations() {
return this.networkInterfaceTapConfigurations;
}
/**
* Get the resource GUID property of the virtual network tap resource.
*
* @return the resourceGuid value
*/
public String resourceGuid() {
return this.resourceGuid;
}
/**
* Get the provisioning state of the virtual network tap resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*
* @return the provisioningState value
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Get the reference to the private IP Address of the collector nic that will receive the tap.
*
* @return the destinationNetworkInterfaceIPConfiguration value
*/
public NetworkInterfaceIPConfigurationInner destinationNetworkInterfaceIPConfiguration() {
return this.destinationNetworkInterfaceIPConfiguration;
}
/**
* Set the reference to the private IP Address of the collector nic that will receive the tap.
*
* @param destinationNetworkInterfaceIPConfiguration the destinationNetworkInterfaceIPConfiguration value to set
* @return the VirtualNetworkTapInner object itself.
*/
public VirtualNetworkTapInner withDestinationNetworkInterfaceIPConfiguration(NetworkInterfaceIPConfigurationInner destinationNetworkInterfaceIPConfiguration) {
this.destinationNetworkInterfaceIPConfiguration = destinationNetworkInterfaceIPConfiguration;
return this;
}
/**
* Get the reference to the private IP address on the internal Load Balancer that will receive the tap.
*
* @return the destinationLoadBalancerFrontEndIPConfiguration value
*/
public FrontendIPConfigurationInner destinationLoadBalancerFrontEndIPConfiguration() {
return this.destinationLoadBalancerFrontEndIPConfiguration;
}
/**
* Set the reference to the private IP address on the internal Load Balancer that will receive the tap.
*
* @param destinationLoadBalancerFrontEndIPConfiguration the destinationLoadBalancerFrontEndIPConfiguration value to set
* @return the VirtualNetworkTapInner object itself.
*/
public VirtualNetworkTapInner withDestinationLoadBalancerFrontEndIPConfiguration(FrontendIPConfigurationInner destinationLoadBalancerFrontEndIPConfiguration) {
this.destinationLoadBalancerFrontEndIPConfiguration = destinationLoadBalancerFrontEndIPConfiguration;
return this;
}
/**
* Get the VXLAN destination port that will receive the tapped traffic.
*
* @return the destinationPort value
*/
public Integer destinationPort() {
return this.destinationPort;
}
/**
* Set the VXLAN destination port that will receive the tapped traffic.
*
* @param destinationPort the destinationPort value to set
* @return the VirtualNetworkTapInner object itself.
*/
public VirtualNetworkTapInner withDestinationPort(Integer destinationPort) {
this.destinationPort = destinationPort;
return this;
}
/**
* Get a unique read-only string that changes whenever the resource is updated.
*
* @return the etag value
*/
public String etag() {
return this.etag;
}
/**
* Get resource ID.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Set resource ID.
*
* @param id the id value to set
* @return the VirtualNetworkTapInner object itself.
*/
public VirtualNetworkTapInner withId(String id) {
this.id = id;
return this;
}
}
| {
"content_hash": "25ec8949aad8f11f8ed4679c443d0942",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 163,
"avg_line_length": 34.45161290322581,
"alnum_prop": 0.7180087390761548,
"repo_name": "selvasingh/azure-sdk-for-java",
"id": "ba3e9860d75d3dd9c45e238eae4c8c0b6507fb48",
"size": "6638",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/implementation/VirtualNetworkTapInner.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "29891970"
},
{
"name": "JavaScript",
"bytes": "6198"
},
{
"name": "PowerShell",
"bytes": "160"
},
{
"name": "Shell",
"bytes": "609"
}
],
"symlink_target": ""
} |
package city.animationPanels;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import city.gui.BuildingIcon;
import city.gui.SimCityGui;
public class InsideBuildingPanel extends JPanel{
private static final long serialVersionUID = 1L;
public boolean isVisible = false;
SimCityGui myCity;
String myName;
BuildingIcon buildingIcon;
public InsideAnimationPanel insideAnimationPanel;
public JPanel guiInteractionPanel;
static final int FRAMEX = 1100;
static final int FRAMEY = 430;
static final int INSIDE_BUILDING_FRAME_Y = 517;
public InsideBuildingPanel(BuildingIcon b, int i, SimCityGui s, InsideAnimationPanel iap, JPanel gip) {
buildingIcon = b;
myName = "" + i;
myCity = s;
insideAnimationPanel = iap;
guiInteractionPanel = gip;
setBackground(Color.LIGHT_GRAY);
setLayout(new BorderLayout());
Dimension dim = new Dimension(FRAMEX, INSIDE_BUILDING_FRAME_Y);
this.setMinimumSize(dim);
this.setMaximumSize(dim);
this.setPreferredSize(dim);
add(insideAnimationPanel,BorderLayout.CENTER);
add(guiInteractionPanel, BorderLayout.WEST);
}
public String getName(){
return myName;
}
public void displayBuildngPanel() {
myCity.displayBuildingPanel(this);
}
}
| {
"content_hash": "a201ea4c7018b13c0e90a6fea53bfd21",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 104,
"avg_line_length": 25.6,
"alnum_prop": 0.7625,
"repo_name": "gabelew/SimCity201",
"id": "bd73c558ae02108116541a2675b7a1641055e5d7",
"size": "1280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/city/animationPanels/InsideBuildingPanel.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1232453"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;
namespace UnicornStore.Migrations.UnicornStore
{
public partial class InitialSchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
CategoryId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
DisplayName = table.Column<string>(nullable: true),
ParentCategoryId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.CategoryId);
table.ForeignKey(
name: "FK_Categories_Categories_ParentCategoryId",
column: x => x.ParentCategoryId,
principalTable: "Categories",
principalColumn: "CategoryId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
OrderId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CheckoutBegan = table.Column<DateTime>(nullable: false),
OrderPlaced = table.Column<DateTime>(nullable: true),
State = table.Column<int>(nullable: false),
Total = table.Column<decimal>(nullable: false),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.OrderId);
});
migrationBuilder.CreateTable(
name: "WebsiteAds",
columns: table => new
{
WebsiteAdId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Details = table.Column<string>(nullable: true),
End = table.Column<DateTime>(nullable: true),
ImageUrl = table.Column<string>(nullable: true),
Start = table.Column<DateTime>(nullable: true),
TagLine = table.Column<string>(nullable: true),
Url = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_WebsiteAds", x => x.WebsiteAdId);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
ProductId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CategoryId = table.Column<int>(nullable: false),
CurrentPrice = table.Column<decimal>(nullable: false),
Description = table.Column<string>(nullable: true),
DisplayName = table.Column<string>(nullable: true),
ImageUrl = table.Column<string>(nullable: true),
MSRP = table.Column<decimal>(nullable: false),
SKU = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.ProductId);
table.UniqueConstraint("AK_Products_SKU", x => x.SKU);
table.ForeignKey(
name: "FK_Products_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "CategoryId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "OrderShippingDetails",
columns: table => new
{
OrderId = table.Column<int>(nullable: false),
Addressee = table.Column<string>(nullable: false),
CityOrTown = table.Column<string>(nullable: false),
Country = table.Column<string>(nullable: false),
LineOne = table.Column<string>(nullable: false),
LineTwo = table.Column<string>(nullable: true),
StateOrProvince = table.Column<string>(nullable: false),
ZipOrPostalCode = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderShippingDetails", x => x.OrderId);
table.ForeignKey(
name: "FK_OrderShippingDetails_Orders_OrderId",
column: x => x.OrderId,
principalTable: "Orders",
principalColumn: "OrderId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "CartItems",
columns: table => new
{
CartItemId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
LastUpdated = table.Column<DateTime>(nullable: false),
PriceCalculated = table.Column<DateTime>(nullable: false),
PricePerUnit = table.Column<decimal>(nullable: false),
ProductId = table.Column<int>(nullable: false),
Quantity = table.Column<int>(nullable: false),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_CartItems", x => x.CartItemId);
table.ForeignKey(
name: "FK_CartItems_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "ProductId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "OrderLine",
columns: table => new
{
OrderId = table.Column<int>(nullable: false),
ProductId = table.Column<int>(nullable: false),
PricePerUnit = table.Column<decimal>(nullable: false),
Quantity = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderLine", x => new { x.OrderId, x.ProductId });
table.ForeignKey(
name: "FK_OrderLine_Orders_OrderId",
column: x => x.OrderId,
principalTable: "Orders",
principalColumn: "OrderId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_OrderLine_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "ProductId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Recalls",
columns: table => new
{
RecallId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Details = table.Column<string>(nullable: true),
ProductSKU = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Recalls", x => x.RecallId);
table.ForeignKey(
name: "FK_Recalls_Products_ProductSKU",
column: x => x.ProductSKU,
principalTable: "Products",
principalColumn: "SKU",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_CartItems_ProductId",
table: "CartItems",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Categories_ParentCategoryId",
table: "Categories",
column: "ParentCategoryId");
migrationBuilder.CreateIndex(
name: "IX_OrderLine_OrderId",
table: "OrderLine",
column: "OrderId");
migrationBuilder.CreateIndex(
name: "IX_OrderLine_ProductId",
table: "OrderLine",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_OrderShippingDetails_OrderId",
table: "OrderShippingDetails",
column: "OrderId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Products_CategoryId",
table: "Products",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Recalls_ProductSKU",
table: "Recalls",
column: "ProductSKU");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CartItems");
migrationBuilder.DropTable(
name: "OrderLine");
migrationBuilder.DropTable(
name: "OrderShippingDetails");
migrationBuilder.DropTable(
name: "Recalls");
migrationBuilder.DropTable(
name: "WebsiteAds");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "Products");
migrationBuilder.DropTable(
name: "Categories");
}
}
}
| {
"content_hash": "19256c52344b7e11a42b457a22627474",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 122,
"avg_line_length": 43.76892430278885,
"alnum_prop": 0.4942654287274713,
"repo_name": "rowanmiller/UnicornStore",
"id": "157d93cd97ad0975778fd2df759cce8ced0f7f66",
"size": "10988",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UnicornStore/src/UnicornStore/Migrations/UnicornStore/20160915231430_InitialSchema.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "266782"
},
{
"name": "CSS",
"bytes": "964"
},
{
"name": "HTML",
"bytes": "6663"
},
{
"name": "JavaScript",
"bytes": "377"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "c657617ba19055ba7fcab6f0d08c3443",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "5d240a869d886dbe6dcf98156d2da93a2ecb6ef4",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Myrcia/Myrcia vestita/ Syn. Aulomyrcia pachyclada prolifera/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
layout: post
title: "Child Care Grant Extended Deadline"
modified:
categories: news
excerpt:
tags: []
date: 2019-06-04
author: steve_richardson
---
The deadline for the NPSS Child Care Grant has been extended until June 28. Funds for these grants are still available, so apply now!
The Nuclear & Plasma Sciences Society is offering child care reimbursement of up to $400 per family to assist conference attendees who incur additional childcare expenses by attending an NPSS conference. Limited funds are available and preference will be given to applicants in the early stages of their careers who are IEEE NPSS members. To apply for Child Care Assistance, fill out [this form](/assets/PPPS2019_CCA_Application.docx) and return it no later than **June 28, 2019** by email to: [treasurer@ppps2019.org](mailto:treasurer@ppps2019.org)
| {
"content_hash": "34de16b2bccaa3a8bb3d96c884666223",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 549,
"avg_line_length": 59.642857142857146,
"alnum_prop": 0.792814371257485,
"repo_name": "ppps2019/ppps2019.github.io",
"id": "1cc6cd5b0029d1c9bac4fbd0eee92d5c42d12a0c",
"size": "839",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/news/2019-06-04-childcare.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2396"
},
{
"name": "HTML",
"bytes": "34011"
},
{
"name": "JavaScript",
"bytes": "3319"
},
{
"name": "Ruby",
"bytes": "4895"
},
{
"name": "SCSS",
"bytes": "54308"
}
],
"symlink_target": ""
} |
fork from https://github.com/jaumard/ngx-dashboard/
Dashboard library for angular 4 and more
Demo at: https://jaumard.github.io/ngx-dashboard/demo/demoDist/index.html
## Usage
See demo source code here: https://github.com/jaumard/ngx-dashboard/tree/master/demo
### Create my own widget
To do this you need to extend the WidgetComponent like this:
```js
import {Component, Renderer2, ElementRef, forwardRef} from "@angular/core";
import {WidgetComponent} from "ngx-dashboard";
@Component({
selector: 'app-my-widget',
templateUrl: './my-widget.component.html',
styleUrls: ['./my-widget.component.css'],
providers: [{provide: WidgetComponent, useExisting: forwardRef(() => MyWidgetComponent) }]
})
export class MyWidgetComponent extends WidgetComponent {
@Input() public widgetId: string;
constructor(ngEl: ElementRef, renderer: Renderer2) {
super(ngEl, renderer);
}
}
```
The `providers` part is mandatory, if you miss it your widget will not be see as a widget.
The `@Input()` is also mandatory if you want to use `removeById` because angular 4 doesn't inherit annotations yet.
To dynamically add your widget you also need to declare it under "entryComponents" on your app module like this:
```js
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {NgDashboardModule} from 'ngx-dashboard';
import { AppComponent } from './app.component';
import {MyWidgetComponent} from './my-widget/my-widget.component';
@NgModule({
declarations: [
AppComponent,
MyWidgetComponent
],
entryComponents: [
MyWidgetComponent
],
imports: [
BrowserModule,
NgDashboardModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
### Use custom drag handle
To do this, you can use the `widgetHandle` directive to select witch handle you want from your template. Example:
```html
<widget [size]="[2, 1]" widgetId="large">
<div widgetHandle class="head handle">Large widget [2, 1] handle only on this text</div>
<div>All other stuff...</div>
</widget>
```
# Development
To run the demo locally, you need to do:
```
cd ngx-dashboard
npm i
npm run build
cd demo
npm i
cd src
ln -s ../../src/dist/ .
cd ..
npm start
```
| {
"content_hash": "a51413b302c3f5c53fae6a4865ee6b58",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 115,
"avg_line_length": 24.89010989010989,
"alnum_prop": 0.7130242825607064,
"repo_name": "shadeeka/ngz-dashboard",
"id": "54f432a5ffcf4f8665a2b6aaa09fc8b57df8c2aa",
"size": "2281",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "28848"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.