file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
IPaddValidity_hex_bin.py | #!/usr/bin/env python
import fileinput
class NotValidIP(Exception):
pass
class NotValidIPLength(Exception):
pass
while True:
try:
ip_addr = input("Enter a network IP address: ")
ip_addr_split = ip_addr.split('.')
len1 = len(ip_addr_split)
ip_addr_split = ip_addr_split[:3]
ip_addr_split.append('0')
i=0
for element in ip_addr_split:
ip_addr_split[i] = int(element)
i = i+1
i = 0
for element in ip_addr_split:
|
if (len1!=3 and len1!=4):
raise NotValidIPLength
print("The network IP address now is: %s" % ip_addr_split)
break
except ValueError:
print('Not a good value')
except NotValidIP:
print('this is not a valid IP address')
except NotValidIPLength:
print('this is not an IP address size')
print('%20s %20s %20s' % ('NETWORK_NUMBER', 'FIRST_OCTET_BINARY', 'FIRST_OCTET_HEX') )
a = '.'.join(str(q) for q in ip_addr_split)
b = bin(ip_addr_split[0])
c = hex(ip_addr_split[0])
print('%20s %20s %20s' % (a, b, c)) | if (element > 255 or element < 0):
raise NotValidIP | conditional_block |
AdminActions.js | import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
SET_ADMIN_SEARCH: 'SET_ADMIN_SEARCH',
SET_ADMIN_CURRENT_PAGE: 'SET_ADMIN_CURRENT_PAGE',
SET_ADMIN_MAX_PAGE: 'SET_ADMIN_MAX_PAGE',
SET_ADMIN: 'SET_ADMIN', | };
export function setSearch(search) {
return {
type: ACTIONS.SET_ADMIN_SEARCH,
search
};
}
export function setCurrentPage(page) {
return {
type: ACTIONS.SET_ADMIN_CURRENT_PAGE,
page
};
}
export function setMaxPage(page) {
return {
type: ACTIONS.SET_ADMIN_MAX_PAGE,
page
};
}
export function setAdmin(admin) {
return {
type: ACTIONS.SET_ADMIN,
admin
};
}
export function getAdminSearch(search, page) {
return (dispatch) => {
return callApi(`admin?search=${search}&page=${page}`, 'get', '' ).then(res => {
dispatch(setAdmin(res.admin));
});
};
}
export function deleteAdmin(del) {
return () => {
return callApi('admin/delete', 'post', '', {del}).then(res => {
return res;
});
};
}
export function recoverAdmin(recover) {
return () => {
return callApi('admin/recover', 'post', '', {recover}).then(res => {
return res;
});
};
}
export function createAdmin(admin) {
return () => {
return callApi('admin', 'post', '', {admin}).then(res => {
return res.admin;
});
};
} | random_line_split | |
AdminActions.js | import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
SET_ADMIN_SEARCH: 'SET_ADMIN_SEARCH',
SET_ADMIN_CURRENT_PAGE: 'SET_ADMIN_CURRENT_PAGE',
SET_ADMIN_MAX_PAGE: 'SET_ADMIN_MAX_PAGE',
SET_ADMIN: 'SET_ADMIN',
};
export function setSearch(search) {
return {
type: ACTIONS.SET_ADMIN_SEARCH,
search
};
}
export function setCurrentPage(page) {
return {
type: ACTIONS.SET_ADMIN_CURRENT_PAGE,
page
};
}
export function setMaxPage(page) {
return {
type: ACTIONS.SET_ADMIN_MAX_PAGE,
page
};
}
export function setAdmin(admin) {
return {
type: ACTIONS.SET_ADMIN,
admin
};
}
export function | (search, page) {
return (dispatch) => {
return callApi(`admin?search=${search}&page=${page}`, 'get', '' ).then(res => {
dispatch(setAdmin(res.admin));
});
};
}
export function deleteAdmin(del) {
return () => {
return callApi('admin/delete', 'post', '', {del}).then(res => {
return res;
});
};
}
export function recoverAdmin(recover) {
return () => {
return callApi('admin/recover', 'post', '', {recover}).then(res => {
return res;
});
};
}
export function createAdmin(admin) {
return () => {
return callApi('admin', 'post', '', {admin}).then(res => {
return res.admin;
});
};
}
| getAdminSearch | identifier_name |
AdminActions.js | import callApi from '../../util/apiCaller';
// Export Constants
export const ACTIONS = {
SET_ADMIN_SEARCH: 'SET_ADMIN_SEARCH',
SET_ADMIN_CURRENT_PAGE: 'SET_ADMIN_CURRENT_PAGE',
SET_ADMIN_MAX_PAGE: 'SET_ADMIN_MAX_PAGE',
SET_ADMIN: 'SET_ADMIN',
};
export function setSearch(search) |
export function setCurrentPage(page) {
return {
type: ACTIONS.SET_ADMIN_CURRENT_PAGE,
page
};
}
export function setMaxPage(page) {
return {
type: ACTIONS.SET_ADMIN_MAX_PAGE,
page
};
}
export function setAdmin(admin) {
return {
type: ACTIONS.SET_ADMIN,
admin
};
}
export function getAdminSearch(search, page) {
return (dispatch) => {
return callApi(`admin?search=${search}&page=${page}`, 'get', '' ).then(res => {
dispatch(setAdmin(res.admin));
});
};
}
export function deleteAdmin(del) {
return () => {
return callApi('admin/delete', 'post', '', {del}).then(res => {
return res;
});
};
}
export function recoverAdmin(recover) {
return () => {
return callApi('admin/recover', 'post', '', {recover}).then(res => {
return res;
});
};
}
export function createAdmin(admin) {
return () => {
return callApi('admin', 'post', '', {admin}).then(res => {
return res.admin;
});
};
}
| {
return {
type: ACTIONS.SET_ADMIN_SEARCH,
search
};
} | identifier_body |
check-boundary.py | #!/usr/bin/python
from sensu_plugin import SensuPluginMetricJSON
import requests
#import os
import json
from sh import curl
from walrus import *
#from redis import *
import math
#from requests.auth import HTTPBasicAuth
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='localhost', port=6379, db=0)
c = statsd.StatsClient('grafana', 8125)
class FooBarBazMetricJSON(SensuPluginMetricJSON):
|
if __name__ == "__main__":
f = FooBarBazMetricJSON()
| def run(self):
endpoints = ['topology', 'remediations']
positions = [30, 50, 99]
api = 'ecepeda-api.route105.net'
token_curl = curl('https://{0}/aims/v1/authenticate'.format(api), '-s', '-k', '-X', 'POST', '-H', 'Accept: application/json', '--user', '2A6B0U16535H6X0D5822:$2a$12$WB8KmRcUnGpf1M6oEdLBe.GrfBEaa94U4QMBTPMuVWktWZf91AJk')
headers = {'X-Iam-Auth-Token': json.loads(str(token_curl))['authentication']['token'], 'X-Request-Id': 'DEADBEEF'}
for endpoint in endpoints:
a = db.ZSet('measures_{0}'.format(endpoint))
percentiles = db.Hash('percentiles_{0}'.format(endpoint))
current = percentiles['current']
if current is None or int(current) > 99:
current = 1
url = 'https://{0}/assets/v1/67000001/environments/814C2911-09BB-1005-9916-7831C1BAC182/{1}'.format(api, endpoint)
with warnings.catch_warnings():
warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
r = requests.get(url, headers=headers, verify=False)
a.remove(current)
a.add(current, r.elapsed.microseconds)
c.timing(endpoint, int(r.elapsed.microseconds)/1000)
iterate = True
elements = []
iterator = a.__iter__()
while iterate:
try:
elem = iterator.next()
elements.append({'position': elem[0], 'time': elem[1]})
except:
iterate = False
if len(elements) > 0:
for percentile in positions:
position = (percentile*.01) * len(elements) - 1
percentiles[percentile] = elements[int(math.ceil(position))]
percentiles['current'] = int(current) + 1
self.output(str(percentiles))
self.warning(str(endpoints)) | identifier_body |
check-boundary.py | #!/usr/bin/python
from sensu_plugin import SensuPluginMetricJSON
import requests
#import os
import json
from sh import curl
from walrus import *
#from redis import *
import math
#from requests.auth import HTTPBasicAuth
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='localhost', port=6379, db=0)
c = statsd.StatsClient('grafana', 8125)
class FooBarBazMetricJSON(SensuPluginMetricJSON):
def | (self):
endpoints = ['topology', 'remediations']
positions = [30, 50, 99]
api = 'ecepeda-api.route105.net'
token_curl = curl('https://{0}/aims/v1/authenticate'.format(api), '-s', '-k', '-X', 'POST', '-H', 'Accept: application/json', '--user', '2A6B0U16535H6X0D5822:$2a$12$WB8KmRcUnGpf1M6oEdLBe.GrfBEaa94U4QMBTPMuVWktWZf91AJk')
headers = {'X-Iam-Auth-Token': json.loads(str(token_curl))['authentication']['token'], 'X-Request-Id': 'DEADBEEF'}
for endpoint in endpoints:
a = db.ZSet('measures_{0}'.format(endpoint))
percentiles = db.Hash('percentiles_{0}'.format(endpoint))
current = percentiles['current']
if current is None or int(current) > 99:
current = 1
url = 'https://{0}/assets/v1/67000001/environments/814C2911-09BB-1005-9916-7831C1BAC182/{1}'.format(api, endpoint)
with warnings.catch_warnings():
warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
r = requests.get(url, headers=headers, verify=False)
a.remove(current)
a.add(current, r.elapsed.microseconds)
c.timing(endpoint, int(r.elapsed.microseconds)/1000)
iterate = True
elements = []
iterator = a.__iter__()
while iterate:
try:
elem = iterator.next()
elements.append({'position': elem[0], 'time': elem[1]})
except:
iterate = False
if len(elements) > 0:
for percentile in positions:
position = (percentile*.01) * len(elements) - 1
percentiles[percentile] = elements[int(math.ceil(position))]
percentiles['current'] = int(current) + 1
self.output(str(percentiles))
self.warning(str(endpoints))
if __name__ == "__main__":
f = FooBarBazMetricJSON()
| run | identifier_name |
check-boundary.py | #!/usr/bin/python
from sensu_plugin import SensuPluginMetricJSON
import requests
#import os
import json
from sh import curl
from walrus import *
#from redis import *
import math
#from requests.auth import HTTPBasicAuth
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='localhost', port=6379, db=0)
c = statsd.StatsClient('grafana', 8125)
class FooBarBazMetricJSON(SensuPluginMetricJSON):
def run(self):
endpoints = ['topology', 'remediations']
positions = [30, 50, 99]
api = 'ecepeda-api.route105.net'
token_curl = curl('https://{0}/aims/v1/authenticate'.format(api), '-s', '-k', '-X', 'POST', '-H', 'Accept: application/json', '--user', '2A6B0U16535H6X0D5822:$2a$12$WB8KmRcUnGpf1M6oEdLBe.GrfBEaa94U4QMBTPMuVWktWZf91AJk')
headers = {'X-Iam-Auth-Token': json.loads(str(token_curl))['authentication']['token'], 'X-Request-Id': 'DEADBEEF'}
for endpoint in endpoints:
a = db.ZSet('measures_{0}'.format(endpoint))
percentiles = db.Hash('percentiles_{0}'.format(endpoint))
current = percentiles['current']
if current is None or int(current) > 99:
current = 1
url = 'https://{0}/assets/v1/67000001/environments/814C2911-09BB-1005-9916-7831C1BAC182/{1}'.format(api, endpoint)
with warnings.catch_warnings():
warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
r = requests.get(url, headers=headers, verify=False)
a.remove(current)
a.add(current, r.elapsed.microseconds)
c.timing(endpoint, int(r.elapsed.microseconds)/1000)
iterate = True
elements = []
iterator = a.__iter__()
while iterate:
try:
elem = iterator.next()
elements.append({'position': elem[0], 'time': elem[1]})
except:
iterate = False
if len(elements) > 0:
for percentile in positions:
position = (percentile*.01) * len(elements) - 1
percentiles[percentile] = elements[int(math.ceil(position))]
percentiles['current'] = int(current) + 1
self.output(str(percentiles))
self.warning(str(endpoints))
if __name__ == "__main__":
| f = FooBarBazMetricJSON() | conditional_block | |
check-boundary.py | #!/usr/bin/python
from sensu_plugin import SensuPluginMetricJSON
import requests
#import os
import json
from sh import curl
from walrus import *
#from redis import *
import math
#from requests.auth import HTTPBasicAuth
import statsd
import warnings
from requests.packages.urllib3 import exceptions
db = Database(host='localhost', port=6379, db=0)
c = statsd.StatsClient('grafana', 8125)
class FooBarBazMetricJSON(SensuPluginMetricJSON):
def run(self):
endpoints = ['topology', 'remediations']
positions = [30, 50, 99]
api = 'ecepeda-api.route105.net'
token_curl = curl('https://{0}/aims/v1/authenticate'.format(api), '-s', '-k', '-X', 'POST', '-H', 'Accept: application/json', '--user', '2A6B0U16535H6X0D5822:$2a$12$WB8KmRcUnGpf1M6oEdLBe.GrfBEaa94U4QMBTPMuVWktWZf91AJk')
headers = {'X-Iam-Auth-Token': json.loads(str(token_curl))['authentication']['token'], 'X-Request-Id': 'DEADBEEF'}
for endpoint in endpoints:
a = db.ZSet('measures_{0}'.format(endpoint))
percentiles = db.Hash('percentiles_{0}'.format(endpoint))
current = percentiles['current']
if current is None or int(current) > 99:
current = 1
url = 'https://{0}/assets/v1/67000001/environments/814C2911-09BB-1005-9916-7831C1BAC182/{1}'.format(api, endpoint)
with warnings.catch_warnings():
warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
r = requests.get(url, headers=headers, verify=False)
a.remove(current)
a.add(current, r.elapsed.microseconds)
c.timing(endpoint, int(r.elapsed.microseconds)/1000)
iterate = True
elements = []
iterator = a.__iter__()
while iterate:
try:
elem = iterator.next()
elements.append({'position': elem[0], 'time': elem[1]})
except:
iterate = False
if len(elements) > 0: | percentiles[percentile] = elements[int(math.ceil(position))]
percentiles['current'] = int(current) + 1
self.output(str(percentiles))
self.warning(str(endpoints))
if __name__ == "__main__":
f = FooBarBazMetricJSON() | for percentile in positions:
position = (percentile*.01) * len(elements) - 1 | random_line_split |
shell.py | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status', |
if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
else:
subcommand = 'daemon'
parser = OptionParser()
parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true',
help = "Don't daemonize by forking into the background.")
parser.add_option('-l', '--level', dest='log_level', default='warn',
help = "Set logging level (debug, info, warn, error) Default: warn")
parser.add_option('-c', '--config', dest='config', default='/etc/happy.conf',
help = "Path to HAppy configuration file. Default: /etc/happy.conf")
options, args = parser.parse_args()
options.subcommand = subcommand
return options
def main():
options = parse_args(sys.argv[1:])
import happy
prog = happy.HAppy(options)
getattr(prog, options.subcommand)()
if __name__ == '__main__':
main() | ]
def parse_args(argv): | random_line_split |
shell.py | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status',
]
def parse_args(argv):
if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
else:
subcommand = 'daemon'
parser = OptionParser()
parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true',
help = "Don't daemonize by forking into the background.")
parser.add_option('-l', '--level', dest='log_level', default='warn',
help = "Set logging level (debug, info, warn, error) Default: warn")
parser.add_option('-c', '--config', dest='config', default='/etc/happy.conf',
help = "Path to HAppy configuration file. Default: /etc/happy.conf")
options, args = parser.parse_args()
options.subcommand = subcommand
return options
def main():
options = parse_args(sys.argv[1:])
import happy
prog = happy.HAppy(options)
getattr(prog, options.subcommand)()
if __name__ == '__main__':
| main() | conditional_block | |
shell.py | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status',
]
def parse_args(argv):
|
def main():
options = parse_args(sys.argv[1:])
import happy
prog = happy.HAppy(options)
getattr(prog, options.subcommand)()
if __name__ == '__main__':
main()
| if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
else:
subcommand = 'daemon'
parser = OptionParser()
parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true',
help = "Don't daemonize by forking into the background.")
parser.add_option('-l', '--level', dest='log_level', default='warn',
help = "Set logging level (debug, info, warn, error) Default: warn")
parser.add_option('-c', '--config', dest='config', default='/etc/happy.conf',
help = "Path to HAppy configuration file. Default: /etc/happy.conf")
options, args = parser.parse_args()
options.subcommand = subcommand
return options | identifier_body |
shell.py | # HAppy
import sys
import logging
from optparse import OptionParser
logger = logging.getLogger(__name__)
SUB_COMMANDS = [
'daemon',
'takeover',
'release',
'status',
]
def | (argv):
if len(argv) > 0 and argv[0] in SUB_COMMANDS:
subcommand = argv.pop(0)
else:
subcommand = 'daemon'
parser = OptionParser()
parser.add_option('-f', '--foreground', dest='foreground', default=False, action='store_true',
help = "Don't daemonize by forking into the background.")
parser.add_option('-l', '--level', dest='log_level', default='warn',
help = "Set logging level (debug, info, warn, error) Default: warn")
parser.add_option('-c', '--config', dest='config', default='/etc/happy.conf',
help = "Path to HAppy configuration file. Default: /etc/happy.conf")
options, args = parser.parse_args()
options.subcommand = subcommand
return options
def main():
options = parse_args(sys.argv[1:])
import happy
prog = happy.HAppy(options)
getattr(prog, options.subcommand)()
if __name__ == '__main__':
main()
| parse_args | identifier_name |
responsive-scripts.js | /*! Responsive JS Library v1.2.2 */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = '­<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function( win ){
//exposed namespace
win.respond = {};
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//expose media query support flag for external use
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){ return; }
//define vars
var doc = win.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
requestQueue = [],
//loop stylesheets, send text content to translate
ripCSS = function(){
var sheets = links,
sl = sheets.length,
i = 0,
//vars for loop:
sheet, href, media, isCSS;
for( ; i < sl; i++ ){
sheet = sheets[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
makeRequests();
} );
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
ql = qs && qs.length || 0,
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( ; i < ql; i++ ){
j = 0;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( ; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
lastCall,
resizeDefer,
// returns the value of 1em in pixels
getEmValue = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
clearTimeout( resizeDefer );
resizeDefer = setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles ){
var thisstyle = mediastyles[ i ],
min = thisstyle.minw,
max = thisstyle.maxw,
minnull = min === null,
maxnull = max === null,
em = "em";
if( !!min ){
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
if( !!max ){
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
//remove any existing respond style element(s)
for( var i in appendedEls ){
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
head.removeChild( appendedEls[ i ] );
}
}
//inject active styles, grouped by media type
for( var i in styleBlocks ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ i ].join( "\n" );
ss.type = "text/css";
ss.media = i;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
},
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
return;
}
callback( req.responseText );
}
if ( req.readyState == 4 ){
return;
}
req.send( null );
},
//define ajax obj
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})();
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( win.addEventListener ){
win.addEventListener( "resize", callMedia, false );
}
else if( win.attachEvent ){
win.attachEvent( "onresize", callMedia );
}
})(this);
/**
* jQuery Scroll Top Plugin 1.0.0
*/
jQuery(document).ready(function ($) {
$('a[href=#scroll-top]').click(function () {
$('html, body').animate({
scrollTop: 0
}, 'slow');
return false;
});
});
/*! http://mths.be/placeholder v2.0.7 by @mathias */
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea'),
prototype = $.fn,
valHooks = $.valHooks,
hooks,
placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != document.activeElement) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
isInputSupported || (valHooks.input = hooks);
isTextareaSupported || (valHooks.textarea = hooks);
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this,
$input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == document.activeElement && input.select();
}
}
}
function setPlaceholder() |
}(this, document, jQuery));
/*global jQuery */
/*jshint multistr:true browser:true */
/*!
* FitVids 1.0
*
* Copyright 2011, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
* Date: Thu Sept 01 18:00:00 2011 -0500
*/
(function( $ ){
"use strict";
$.fn.fitVids = function( options ) {
var settings = {
customSelector: null
};
var div = document.createElement('div'),
ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0];
div.className = 'fit-vids-style';
div.innerHTML = '­<style> \
.fluid-width-video-wrapper { \
width: 100%; \
position: relative; \
padding: 0; \
} \
\
.fluid-width-video-wrapper iframe, \
.fluid-width-video-wrapper object, \
.fluid-width-video-wrapper embed { \
position: absolute; \
top: 0; \
left: 0; \
width: 100%; \
height: 100%; \
} \
</style>';
ref.parentNode.insertBefore(div,ref);
if ( options ) {
$.extend( settings, options );
}
return this.each(function(){
var selectors = [
"iframe[src*='player.vimeo.com']",
"iframe[src*='www.youtube.com']",
"iframe[src*='www.youtube-nocookie.com']",
"iframe[src*='fast.wistia.com']",
"embed"
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos.each(function(){
var $this = $(this);
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if(!$this.attr('id')){
var videoID = 'fitvid' + Math.floor(Math.random()*999999);
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%");
$this.removeAttr('height').removeAttr('width');
});
});
};
})( jQuery );
/*!
* Mobile Menu
*/
(function($) {
var current = $('.main-nav li.current-menu-item a').html();
current = $('.main-nav li.current_page_item a').html();
if( $('span').hasClass('custom-mobile-menu-title') ) {
current = $('span.custom-mobile-menu-title').html();
}
else if( typeof current == 'undefined' || current === null ) {
if( $('body').hasClass('home') ) {
if( $('#logo span').hasClass('site-name') ) {
current = $('#logo .site-name a').html();
}
else {
current = $('#logo img').attr('alt');
}
}
else {
if( $('body').hasClass('woocommerce') ) {
current = $('h1.page-title').html();
}
else if( $('body').hasClass('archive') ) {
current = $('h6.title-archive').html();
}
else if( $('body').hasClass('search-results') ) {
current = $('h6.title-search-results').html();
}
else if( $('body').hasClass('page-template-blog-excerpt-php') ) {
current = $('.current_page_item').text();
}
else if( $('body').hasClass('page-template-blog-php') ) {
current = $('.current_page_item').text();
}
else {
current = $('h1.post-title').html();
}
}
};
$('.main-nav').append('<a id="responsive_menu_button"></a>');
$('.main-nav').prepend('<div id="responsive_current_menu_item">Menu</div>');
$('a#responsive_menu_button, #responsive_current_menu_item').click(function(){
$('.js .main-nav .menu').slideToggle( function() {
if( $(this).is(':visible') ) {
$('a#responsive_menu_button').addClass('responsive-toggle-open');
}
else {
$('a#responsive_menu_button').removeClass('responsive-toggle-open');
$('.js .main-nav .menu').removeAttr('style');
}
});
});
})(jQuery);
// Close the mobile menu when clicked outside of it.
(function($) {
$('html').click(function() {
// Check if the menu is open, close in that case.
if( $('a#responsive_menu_button').hasClass('responsive-toggle-open') ){
$('.js .main-nav .menu').slideToggle( function() {
$('a#responsive_menu_button').removeClass('responsive-toggle-open');
$('.js .main-nav .menu').removeAttr('style');
});
}
})
})(jQuery);
// Stop propagation on click on menu.
jQuery('.main-nav').click(function(event){
var pathname = window.location.pathname;
if( pathname != '/wp-admin/customize.php' ){
event.stopPropagation();
}
});
// Placeholder
jQuery(function(){
jQuery('input[placeholder], textarea[placeholder]').placeholder();
});
// FitVids
jQuery(document).ready(function(){
// Target your #container, #wrapper etc.
jQuery("#wrapper").fitVids();
});
// Have a custom video player? We now have a customSelector option where you can add your own specific video vendor selector (mileage may vary depending on vendor and fluidity of player):
// jQuery("#thing-with-videos").fitVids({ customSelector: "iframe[src^='http://example.com'], iframe[src^='http://example.org']"});
// Selectors are comma separated, just like CSS
// Note: This will be the quickest way to add your own custom vendor as well as test your player's compatibility with FitVids. | {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': true,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
} | identifier_body |
responsive-scripts.js | /*! Responsive JS Library v1.2.2 */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = '­<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function( win ){
//exposed namespace
win.respond = {};
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//expose media query support flag for external use
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){ return; }
//define vars
var doc = win.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
requestQueue = [],
//loop stylesheets, send text content to translate
ripCSS = function(){
var sheets = links,
sl = sheets.length,
i = 0,
//vars for loop:
sheet, href, media, isCSS;
for( ; i < sl; i++ ){
sheet = sheets[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
makeRequests();
} );
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
ql = qs && qs.length || 0,
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( ; i < ql; i++ ){
j = 0;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( ; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
lastCall,
resizeDefer,
// returns the value of 1em in pixels
getEmValue = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
clearTimeout( resizeDefer );
resizeDefer = setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles ){
var thisstyle = mediastyles[ i ],
min = thisstyle.minw,
max = thisstyle.maxw,
minnull = min === null,
maxnull = max === null,
em = "em";
if( !!min ){
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
if( !!max ){
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
//remove any existing respond style element(s)
for( var i in appendedEls ){
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
head.removeChild( appendedEls[ i ] );
}
}
//inject active styles, grouped by media type
for( var i in styleBlocks ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ i ].join( "\n" );
ss.type = "text/css";
ss.media = i;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
},
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
return;
}
callback( req.responseText );
}
if ( req.readyState == 4 ){
return;
}
req.send( null );
},
//define ajax obj
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})();
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( win.addEventListener ){
win.addEventListener( "resize", callMedia, false );
}
else if( win.attachEvent ){
win.attachEvent( "onresize", callMedia );
}
})(this);
/**
* jQuery Scroll Top Plugin 1.0.0
*/
jQuery(document).ready(function ($) {
$('a[href=#scroll-top]').click(function () {
$('html, body').animate({
scrollTop: 0
}, 'slow');
return false;
});
});
/*! http://mths.be/placeholder v2.0.7 by @mathias */
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea'),
prototype = $.fn,
valHooks = $.valHooks,
hooks,
placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
if (!$element.data('placeholder-enabled')) |
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != document.activeElement) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
isInputSupported || (valHooks.input = hooks);
isTextareaSupported || (valHooks.textarea = hooks);
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this,
$input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == document.activeElement && input.select();
}
}
}
function setPlaceholder() {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': true,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
}
}(this, document, jQuery));
/*global jQuery */
/*jshint multistr:true browser:true */
/*!
* FitVids 1.0
*
* Copyright 2011, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
* Date: Thu Sept 01 18:00:00 2011 -0500
*/
(function( $ ){
"use strict";
$.fn.fitVids = function( options ) {
var settings = {
customSelector: null
};
var div = document.createElement('div'),
ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0];
div.className = 'fit-vids-style';
div.innerHTML = '­<style> \
.fluid-width-video-wrapper { \
width: 100%; \
position: relative; \
padding: 0; \
} \
\
.fluid-width-video-wrapper iframe, \
.fluid-width-video-wrapper object, \
.fluid-width-video-wrapper embed { \
position: absolute; \
top: 0; \
left: 0; \
width: 100%; \
height: 100%; \
} \
</style>';
ref.parentNode.insertBefore(div,ref);
if ( options ) {
$.extend( settings, options );
}
return this.each(function(){
var selectors = [
"iframe[src*='player.vimeo.com']",
"iframe[src*='www.youtube.com']",
"iframe[src*='www.youtube-nocookie.com']",
"iframe[src*='fast.wistia.com']",
"embed"
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos.each(function(){
var $this = $(this);
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if(!$this.attr('id')){
var videoID = 'fitvid' + Math.floor(Math.random()*999999);
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%");
$this.removeAttr('height').removeAttr('width');
});
});
};
})( jQuery );
/*!
* Mobile Menu
*/
(function($) {
var current = $('.main-nav li.current-menu-item a').html();
current = $('.main-nav li.current_page_item a').html();
if( $('span').hasClass('custom-mobile-menu-title') ) {
current = $('span.custom-mobile-menu-title').html();
}
else if( typeof current == 'undefined' || current === null ) {
if( $('body').hasClass('home') ) {
if( $('#logo span').hasClass('site-name') ) {
current = $('#logo .site-name a').html();
}
else {
current = $('#logo img').attr('alt');
}
}
else {
if( $('body').hasClass('woocommerce') ) {
current = $('h1.page-title').html();
}
else if( $('body').hasClass('archive') ) {
current = $('h6.title-archive').html();
}
else if( $('body').hasClass('search-results') ) {
current = $('h6.title-search-results').html();
}
else if( $('body').hasClass('page-template-blog-excerpt-php') ) {
current = $('.current_page_item').text();
}
else if( $('body').hasClass('page-template-blog-php') ) {
current = $('.current_page_item').text();
}
else {
current = $('h1.post-title').html();
}
}
};
$('.main-nav').append('<a id="responsive_menu_button"></a>');
$('.main-nav').prepend('<div id="responsive_current_menu_item">Menu</div>');
$('a#responsive_menu_button, #responsive_current_menu_item').click(function(){
$('.js .main-nav .menu').slideToggle( function() {
if( $(this).is(':visible') ) {
$('a#responsive_menu_button').addClass('responsive-toggle-open');
}
else {
$('a#responsive_menu_button').removeClass('responsive-toggle-open');
$('.js .main-nav .menu').removeAttr('style');
}
});
});
})(jQuery);
// Close the mobile menu when clicked outside of it.
(function($) {
$('html').click(function() {
// Check if the menu is open, close in that case.
if( $('a#responsive_menu_button').hasClass('responsive-toggle-open') ){
$('.js .main-nav .menu').slideToggle( function() {
$('a#responsive_menu_button').removeClass('responsive-toggle-open');
$('.js .main-nav .menu').removeAttr('style');
});
}
})
})(jQuery);
// Stop propagation on click on menu.
jQuery('.main-nav').click(function(event){
var pathname = window.location.pathname;
if( pathname != '/wp-admin/customize.php' ){
event.stopPropagation();
}
});
// Placeholder
jQuery(function(){
jQuery('input[placeholder], textarea[placeholder]').placeholder();
});
// FitVids
jQuery(document).ready(function(){
// Target your #container, #wrapper etc.
jQuery("#wrapper").fitVids();
});
// Have a custom video player? We now have a customSelector option where you can add your own specific video vendor selector (mileage may vary depending on vendor and fluidity of player):
// jQuery("#thing-with-videos").fitVids({ customSelector: "iframe[src^='http://example.com'], iframe[src^='http://example.org']"});
// Selectors are comma separated, just like CSS
// Note: This will be the quickest way to add your own custom vendor as well as test your player's compatibility with FitVids. | {
return element.value = value;
} | conditional_block |
responsive-scripts.js | /*! Responsive JS Library v1.2.2 */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = '­<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function( win ){
//exposed namespace
win.respond = {};
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//expose media query support flag for external use
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){ return; }
//define vars
var doc = win.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
requestQueue = [],
//loop stylesheets, send text content to translate
ripCSS = function(){
var sheets = links,
sl = sheets.length,
i = 0,
//vars for loop:
sheet, href, media, isCSS;
for( ; i < sl; i++ ){
sheet = sheets[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
makeRequests();
} );
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
ql = qs && qs.length || 0,
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( ; i < ql; i++ ){
j = 0;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( ; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
lastCall,
resizeDefer,
// returns the value of 1em in pixels
getEmValue = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
clearTimeout( resizeDefer );
resizeDefer = setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles ){
var thisstyle = mediastyles[ i ],
min = thisstyle.minw,
max = thisstyle.maxw,
minnull = min === null,
maxnull = max === null,
em = "em";
if( !!min ){
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
if( !!max ){
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
//remove any existing respond style element(s)
for( var i in appendedEls ){
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
head.removeChild( appendedEls[ i ] );
}
}
//inject active styles, grouped by media type
for( var i in styleBlocks ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ i ].join( "\n" );
ss.type = "text/css";
ss.media = i;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
},
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
return;
}
callback( req.responseText );
}
if ( req.readyState == 4 ){
return;
}
req.send( null );
},
//define ajax obj
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})();
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( win.addEventListener ){
win.addEventListener( "resize", callMedia, false );
}
else if( win.attachEvent ){
win.attachEvent( "onresize", callMedia );
}
})(this);
/**
* jQuery Scroll Top Plugin 1.0.0
*/
jQuery(document).ready(function ($) {
$('a[href=#scroll-top]').click(function () {
$('html, body').animate({
scrollTop: 0
}, 'slow');
return false;
});
});
/*! http://mths.be/placeholder v2.0.7 by @mathias */
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea'),
prototype = $.fn,
valHooks = $.valHooks,
hooks,
placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != document.activeElement) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
isInputSupported || (valHooks.input = hooks);
isTextareaSupported || (valHooks.textarea = hooks);
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this,
$input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == document.activeElement && input.select();
}
}
}
function | () {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': true,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
}
}(this, document, jQuery));
/*global jQuery */
/*jshint multistr:true browser:true */
/*!
* FitVids 1.0
*
* Copyright 2011, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
* Date: Thu Sept 01 18:00:00 2011 -0500
*/
(function( $ ){
"use strict";
$.fn.fitVids = function( options ) {
var settings = {
customSelector: null
};
var div = document.createElement('div'),
ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0];
div.className = 'fit-vids-style';
div.innerHTML = '­<style> \
.fluid-width-video-wrapper { \
width: 100%; \
position: relative; \
padding: 0; \
} \
\
.fluid-width-video-wrapper iframe, \
.fluid-width-video-wrapper object, \
.fluid-width-video-wrapper embed { \
position: absolute; \
top: 0; \
left: 0; \
width: 100%; \
height: 100%; \
} \
</style>';
ref.parentNode.insertBefore(div,ref);
if ( options ) {
$.extend( settings, options );
}
return this.each(function(){
var selectors = [
"iframe[src*='player.vimeo.com']",
"iframe[src*='www.youtube.com']",
"iframe[src*='www.youtube-nocookie.com']",
"iframe[src*='fast.wistia.com']",
"embed"
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos.each(function(){
var $this = $(this);
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if(!$this.attr('id')){
var videoID = 'fitvid' + Math.floor(Math.random()*999999);
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%");
$this.removeAttr('height').removeAttr('width');
});
});
};
})( jQuery );
/*!
* Mobile Menu
*/
(function($) {
var current = $('.main-nav li.current-menu-item a').html();
current = $('.main-nav li.current_page_item a').html();
if( $('span').hasClass('custom-mobile-menu-title') ) {
current = $('span.custom-mobile-menu-title').html();
}
else if( typeof current == 'undefined' || current === null ) {
if( $('body').hasClass('home') ) {
if( $('#logo span').hasClass('site-name') ) {
current = $('#logo .site-name a').html();
}
else {
current = $('#logo img').attr('alt');
}
}
else {
if( $('body').hasClass('woocommerce') ) {
current = $('h1.page-title').html();
}
else if( $('body').hasClass('archive') ) {
current = $('h6.title-archive').html();
}
else if( $('body').hasClass('search-results') ) {
current = $('h6.title-search-results').html();
}
else if( $('body').hasClass('page-template-blog-excerpt-php') ) {
current = $('.current_page_item').text();
}
else if( $('body').hasClass('page-template-blog-php') ) {
current = $('.current_page_item').text();
}
else {
current = $('h1.post-title').html();
}
}
};
$('.main-nav').append('<a id="responsive_menu_button"></a>');
$('.main-nav').prepend('<div id="responsive_current_menu_item">Menu</div>');
$('a#responsive_menu_button, #responsive_current_menu_item').click(function(){
$('.js .main-nav .menu').slideToggle( function() {
if( $(this).is(':visible') ) {
$('a#responsive_menu_button').addClass('responsive-toggle-open');
}
else {
$('a#responsive_menu_button').removeClass('responsive-toggle-open');
$('.js .main-nav .menu').removeAttr('style');
}
});
});
})(jQuery);
// Close the mobile menu when clicked outside of it.
(function($) {
$('html').click(function() {
// Check if the menu is open, close in that case.
if( $('a#responsive_menu_button').hasClass('responsive-toggle-open') ){
$('.js .main-nav .menu').slideToggle( function() {
$('a#responsive_menu_button').removeClass('responsive-toggle-open');
$('.js .main-nav .menu').removeAttr('style');
});
}
})
})(jQuery);
// Stop propagation on click on menu.
jQuery('.main-nav').click(function(event){
var pathname = window.location.pathname;
if( pathname != '/wp-admin/customize.php' ){
event.stopPropagation();
}
});
// Placeholder
jQuery(function(){
jQuery('input[placeholder], textarea[placeholder]').placeholder();
});
// FitVids
jQuery(document).ready(function(){
// Target your #container, #wrapper etc.
jQuery("#wrapper").fitVids();
});
// Have a custom video player? We now have a customSelector option where you can add your own specific video vendor selector (mileage may vary depending on vendor and fluidity of player):
// jQuery("#thing-with-videos").fitVids({ customSelector: "iframe[src^='http://example.com'], iframe[src^='http://example.org']"});
// Selectors are comma separated, just like CSS
// Note: This will be the quickest way to add your own custom vendor as well as test your player's compatibility with FitVids. | setPlaceholder | identifier_name |
responsive-scripts.js | /*! Responsive JS Library v1.2.2 */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = '­<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function( win ){
//exposed namespace
win.respond = {};
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//expose media query support flag for external use
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){ return; }
//define vars
var doc = win.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
requestQueue = [],
//loop stylesheets, send text content to translate
ripCSS = function(){
var sheets = links,
sl = sheets.length,
i = 0,
//vars for loop:
sheet, href, media, isCSS;
for( ; i < sl; i++ ){
sheet = sheets[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
makeRequests();
} );
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
ql = qs && qs.length || 0,
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( ; i < ql; i++ ){
j = 0;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( ; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
lastCall,
resizeDefer,
// returns the value of 1em in pixels
getEmValue = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
} |
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
clearTimeout( resizeDefer );
resizeDefer = setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles ){
var thisstyle = mediastyles[ i ],
min = thisstyle.minw,
max = thisstyle.maxw,
minnull = min === null,
maxnull = max === null,
em = "em";
if( !!min ){
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
if( !!max ){
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
//remove any existing respond style element(s)
for( var i in appendedEls ){
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
head.removeChild( appendedEls[ i ] );
}
}
//inject active styles, grouped by media type
for( var i in styleBlocks ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ i ].join( "\n" );
ss.type = "text/css";
ss.media = i;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
},
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
return;
}
callback( req.responseText );
}
if ( req.readyState == 4 ){
return;
}
req.send( null );
},
//define ajax obj
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})();
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( win.addEventListener ){
win.addEventListener( "resize", callMedia, false );
}
else if( win.attachEvent ){
win.attachEvent( "onresize", callMedia );
}
})(this);
/**
* jQuery Scroll Top Plugin 1.0.0
*/
jQuery(document).ready(function ($) {
$('a[href=#scroll-top]').click(function () {
$('html, body').animate({
scrollTop: 0
}, 'slow');
return false;
});
});
/*! http://mths.be/placeholder v2.0.7 by @mathias */
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea'),
prototype = $.fn,
valHooks = $.valHooks,
hooks,
placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != document.activeElement) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
isInputSupported || (valHooks.input = hooks);
isTextareaSupported || (valHooks.textarea = hooks);
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this,
$input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == document.activeElement && input.select();
}
}
}
function setPlaceholder() {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': true,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
}
}(this, document, jQuery));
/*global jQuery */
/*jshint multistr:true browser:true */
/*!
* FitVids 1.0
*
* Copyright 2011, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
* Date: Thu Sept 01 18:00:00 2011 -0500
*/
(function( $ ){
"use strict";
$.fn.fitVids = function( options ) {
var settings = {
customSelector: null
};
var div = document.createElement('div'),
ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0];
div.className = 'fit-vids-style';
div.innerHTML = '­<style> \
.fluid-width-video-wrapper { \
width: 100%; \
position: relative; \
padding: 0; \
} \
\
.fluid-width-video-wrapper iframe, \
.fluid-width-video-wrapper object, \
.fluid-width-video-wrapper embed { \
position: absolute; \
top: 0; \
left: 0; \
width: 100%; \
height: 100%; \
} \
</style>';
ref.parentNode.insertBefore(div,ref);
if ( options ) {
$.extend( settings, options );
}
return this.each(function(){
var selectors = [
"iframe[src*='player.vimeo.com']",
"iframe[src*='www.youtube.com']",
"iframe[src*='www.youtube-nocookie.com']",
"iframe[src*='fast.wistia.com']",
"embed"
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos.each(function(){
var $this = $(this);
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if(!$this.attr('id')){
var videoID = 'fitvid' + Math.floor(Math.random()*999999);
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%");
$this.removeAttr('height').removeAttr('width');
});
});
};
})( jQuery );
/*!
* Mobile Menu
*/
(function($) {
var current = $('.main-nav li.current-menu-item a').html();
current = $('.main-nav li.current_page_item a').html();
if( $('span').hasClass('custom-mobile-menu-title') ) {
current = $('span.custom-mobile-menu-title').html();
}
else if( typeof current == 'undefined' || current === null ) {
if( $('body').hasClass('home') ) {
if( $('#logo span').hasClass('site-name') ) {
current = $('#logo .site-name a').html();
}
else {
current = $('#logo img').attr('alt');
}
}
else {
if( $('body').hasClass('woocommerce') ) {
current = $('h1.page-title').html();
}
else if( $('body').hasClass('archive') ) {
current = $('h6.title-archive').html();
}
else if( $('body').hasClass('search-results') ) {
current = $('h6.title-search-results').html();
}
else if( $('body').hasClass('page-template-blog-excerpt-php') ) {
current = $('.current_page_item').text();
}
else if( $('body').hasClass('page-template-blog-php') ) {
current = $('.current_page_item').text();
}
else {
current = $('h1.post-title').html();
}
}
};
$('.main-nav').append('<a id="responsive_menu_button"></a>');
$('.main-nav').prepend('<div id="responsive_current_menu_item">Menu</div>');
$('a#responsive_menu_button, #responsive_current_menu_item').click(function(){
$('.js .main-nav .menu').slideToggle( function() {
if( $(this).is(':visible') ) {
$('a#responsive_menu_button').addClass('responsive-toggle-open');
}
else {
$('a#responsive_menu_button').removeClass('responsive-toggle-open');
$('.js .main-nav .menu').removeAttr('style');
}
});
});
})(jQuery);
// Close the mobile menu when clicked outside of it.
(function($) {
$('html').click(function() {
// Check if the menu is open, close in that case.
if( $('a#responsive_menu_button').hasClass('responsive-toggle-open') ){
$('.js .main-nav .menu').slideToggle( function() {
$('a#responsive_menu_button').removeClass('responsive-toggle-open');
$('.js .main-nav .menu').removeAttr('style');
});
}
})
})(jQuery);
// Stop propagation on click on menu.
jQuery('.main-nav').click(function(event){
var pathname = window.location.pathname;
if( pathname != '/wp-admin/customize.php' ){
event.stopPropagation();
}
});
// Placeholder
jQuery(function(){
jQuery('input[placeholder], textarea[placeholder]').placeholder();
});
// FitVids
jQuery(document).ready(function(){
// Target your #container, #wrapper etc.
jQuery("#wrapper").fitVids();
});
// Have a custom video player? We now have a customSelector option where you can add your own specific video vendor selector (mileage may vary depending on vendor and fluidity of player):
// jQuery("#thing-with-videos").fitVids({ customSelector: "iframe[src^='http://example.com'], iframe[src^='http://example.org']"});
// Selectors are comma separated, just like CSS
// Note: This will be the quickest way to add your own custom vendor as well as test your player's compatibility with FitVids. | else {
body.removeChild( div );
} | random_line_split |
vmware_dvswitch.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_dvswitch
short_description: Create or remove a distributed vSwitch
description:
- Create or remove a distributed vSwitch
version_added: 2.0
author: "Joseph Callen (@jcpowermac)"
notes:
- Tested on vSphere 5.5
requirements:
- "python >= 2.6"
- PyVmomi
options:
datacenter_name:
description:
- The name of the datacenter that will contain the dvSwitch
required: True
switch_name:
description:
- The name of the switch to create or remove
required: True
mtu:
description:
- The switch maximum transmission unit
required: True
uplink_quantity:
description:
- Quantity of uplink per ESXi host added to the switch
required: True
discovery_proto:
description:
- Link discovery protocol between Cisco and Link Layer discovery
choices:
- 'cdp'
- 'lldp'
required: True
discovery_operation:
description:
- Select the discovery operation
choices:
- 'both'
- 'none'
- 'advertise'
- 'listen'
state:
description:
- Create or remove dvSwitch
default: 'present'
choices:
- 'present'
- 'absent'
required: False
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Create dvswitch
local_action:
module: vmware_dvswitch
hostname: vcenter_ip_or_hostname
username: vcenter_username
password: vcenter_password
datacenter_name: datacenter
switch_name: dvSwitch
mtu: 9000
uplink_quantity: 2
discovery_proto: lldp
discovery_operation: both
state: present
'''
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import (HAS_PYVMOMI,
connect_to_api,
find_datacenter_by_name,
find_dvs_by_name,
vmware_argument_spec,
wait_for_task
)
class VMwareDVSwitch(object):
def __init__(self, module):
self.module = module
self.dvs = None
self.switch_name = self.module.params['switch_name']
self.datacenter_name = self.module.params['datacenter_name']
self.mtu = self.module.params['mtu']
self.uplink_quantity = self.module.params['uplink_quantity']
self.discovery_proto = self.module.params['discovery_proto']
self.discovery_operation = self.module.params['discovery_operation']
self.state = self.module.params['state']
self.content = connect_to_api(module)
def process_state(self):
try:
dvs_states = {
'absent': {
'present': self.state_destroy_dvs,
'absent': self.state_exit_unchanged,
},
'present': {
'update': self.state_update_dvs,
'present': self.state_exit_unchanged,
'absent': self.state_create_dvs,
}
}
dvs_states[self.state][self.check_dvs_configuration()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def create_dvswitch(self, network_folder):
result = None
changed = False
spec = vim.DistributedVirtualSwitch.CreateSpec()
spec.configSpec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
spec.configSpec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy()
spec.configSpec.linkDiscoveryProtocolConfig = vim.host.LinkDiscoveryProtocolConfig()
spec.configSpec.name = self.switch_name
spec.configSpec.maxMtu = self.mtu
spec.configSpec.linkDiscoveryProtocolConfig.protocol = self.discovery_proto
spec.configSpec.linkDiscoveryProtocolConfig.operation = self.discovery_operation
spec.productInfo = vim.dvs.ProductSpec()
spec.productInfo.name = "DVS"
spec.productInfo.vendor = "VMware"
for count in range(1, self.uplink_quantity+1):
spec.configSpec.uplinkPortPolicy.uplinkPortName.append("uplink%d" % count)
task = network_folder.CreateDVS_Task(spec)
changed, result = wait_for_task(task)
return changed, result
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def state_destroy_dvs(self):
|
def state_update_dvs(self):
self.module.exit_json(changed=False, msg="Currently not implemented.")
def state_create_dvs(self):
changed = True
result = None
if not self.module.check_mode:
dc = find_datacenter_by_name(self.content, self.datacenter_name)
changed, result = self.create_dvswitch(dc.networkFolder)
self.module.exit_json(changed=changed, result=str(result))
def check_dvs_configuration(self):
self.dvs = find_dvs_by_name(self.content, self.switch_name)
if self.dvs is None:
return 'absent'
else:
return 'present'
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(datacenter_name=dict(required=True, type='str'),
switch_name=dict(required=True, type='str'),
mtu=dict(required=True, type='int'),
uplink_quantity=dict(required=True, type='int'),
discovery_proto=dict(required=True, choices=['cdp', 'lldp'], type='str'),
discovery_operation=dict(required=True, choices=['both', 'none', 'advertise', 'listen'], type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_PYVMOMI:
module.fail_json(msg='pyvmomi is required for this module')
vmware_dvswitch = VMwareDVSwitch(module)
vmware_dvswitch.process_state()
if __name__ == '__main__':
main()
| task = self.dvs.Destroy_Task()
changed, result = wait_for_task(task)
self.module.exit_json(changed=changed, result=str(result)) | identifier_body |
vmware_dvswitch.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_dvswitch
short_description: Create or remove a distributed vSwitch
description:
- Create or remove a distributed vSwitch
version_added: 2.0
author: "Joseph Callen (@jcpowermac)"
notes:
- Tested on vSphere 5.5
requirements:
- "python >= 2.6"
- PyVmomi
options:
datacenter_name:
description:
- The name of the datacenter that will contain the dvSwitch
required: True
switch_name:
description:
- The name of the switch to create or remove
required: True
mtu:
description:
- The switch maximum transmission unit
required: True
uplink_quantity:
description:
- Quantity of uplink per ESXi host added to the switch
required: True
discovery_proto:
description:
- Link discovery protocol between Cisco and Link Layer discovery
choices:
- 'cdp'
- 'lldp'
required: True
discovery_operation:
description:
- Select the discovery operation
choices:
- 'both'
- 'none'
- 'advertise'
- 'listen'
state:
description:
- Create or remove dvSwitch
default: 'present'
choices:
- 'present'
- 'absent'
required: False
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Create dvswitch
local_action:
module: vmware_dvswitch
hostname: vcenter_ip_or_hostname
username: vcenter_username
password: vcenter_password
datacenter_name: datacenter
switch_name: dvSwitch
mtu: 9000
uplink_quantity: 2
discovery_proto: lldp
discovery_operation: both
state: present
'''
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import (HAS_PYVMOMI,
connect_to_api,
find_datacenter_by_name,
find_dvs_by_name,
vmware_argument_spec,
wait_for_task
)
class VMwareDVSwitch(object):
def | (self, module):
self.module = module
self.dvs = None
self.switch_name = self.module.params['switch_name']
self.datacenter_name = self.module.params['datacenter_name']
self.mtu = self.module.params['mtu']
self.uplink_quantity = self.module.params['uplink_quantity']
self.discovery_proto = self.module.params['discovery_proto']
self.discovery_operation = self.module.params['discovery_operation']
self.state = self.module.params['state']
self.content = connect_to_api(module)
def process_state(self):
try:
dvs_states = {
'absent': {
'present': self.state_destroy_dvs,
'absent': self.state_exit_unchanged,
},
'present': {
'update': self.state_update_dvs,
'present': self.state_exit_unchanged,
'absent': self.state_create_dvs,
}
}
dvs_states[self.state][self.check_dvs_configuration()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def create_dvswitch(self, network_folder):
result = None
changed = False
spec = vim.DistributedVirtualSwitch.CreateSpec()
spec.configSpec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
spec.configSpec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy()
spec.configSpec.linkDiscoveryProtocolConfig = vim.host.LinkDiscoveryProtocolConfig()
spec.configSpec.name = self.switch_name
spec.configSpec.maxMtu = self.mtu
spec.configSpec.linkDiscoveryProtocolConfig.protocol = self.discovery_proto
spec.configSpec.linkDiscoveryProtocolConfig.operation = self.discovery_operation
spec.productInfo = vim.dvs.ProductSpec()
spec.productInfo.name = "DVS"
spec.productInfo.vendor = "VMware"
for count in range(1, self.uplink_quantity+1):
spec.configSpec.uplinkPortPolicy.uplinkPortName.append("uplink%d" % count)
task = network_folder.CreateDVS_Task(spec)
changed, result = wait_for_task(task)
return changed, result
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def state_destroy_dvs(self):
task = self.dvs.Destroy_Task()
changed, result = wait_for_task(task)
self.module.exit_json(changed=changed, result=str(result))
def state_update_dvs(self):
self.module.exit_json(changed=False, msg="Currently not implemented.")
def state_create_dvs(self):
changed = True
result = None
if not self.module.check_mode:
dc = find_datacenter_by_name(self.content, self.datacenter_name)
changed, result = self.create_dvswitch(dc.networkFolder)
self.module.exit_json(changed=changed, result=str(result))
def check_dvs_configuration(self):
self.dvs = find_dvs_by_name(self.content, self.switch_name)
if self.dvs is None:
return 'absent'
else:
return 'present'
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(datacenter_name=dict(required=True, type='str'),
switch_name=dict(required=True, type='str'),
mtu=dict(required=True, type='int'),
uplink_quantity=dict(required=True, type='int'),
discovery_proto=dict(required=True, choices=['cdp', 'lldp'], type='str'),
discovery_operation=dict(required=True, choices=['both', 'none', 'advertise', 'listen'], type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_PYVMOMI:
module.fail_json(msg='pyvmomi is required for this module')
vmware_dvswitch = VMwareDVSwitch(module)
vmware_dvswitch.process_state()
if __name__ == '__main__':
main()
| __init__ | identifier_name |
vmware_dvswitch.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_dvswitch
short_description: Create or remove a distributed vSwitch
description:
- Create or remove a distributed vSwitch
version_added: 2.0
author: "Joseph Callen (@jcpowermac)"
notes:
- Tested on vSphere 5.5
requirements:
- "python >= 2.6"
- PyVmomi
options:
datacenter_name:
description:
- The name of the datacenter that will contain the dvSwitch
required: True
switch_name:
description:
- The name of the switch to create or remove
required: True
mtu:
description:
- The switch maximum transmission unit
required: True
uplink_quantity:
description:
- Quantity of uplink per ESXi host added to the switch
required: True
discovery_proto:
description:
- Link discovery protocol between Cisco and Link Layer discovery
choices:
- 'cdp'
- 'lldp'
required: True
discovery_operation:
description:
- Select the discovery operation
choices:
- 'both'
- 'none'
- 'advertise'
- 'listen'
state:
description:
- Create or remove dvSwitch
default: 'present'
choices:
- 'present'
- 'absent'
required: False
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Create dvswitch
local_action:
module: vmware_dvswitch
hostname: vcenter_ip_or_hostname
username: vcenter_username
password: vcenter_password
datacenter_name: datacenter
switch_name: dvSwitch
mtu: 9000
uplink_quantity: 2
discovery_proto: lldp
discovery_operation: both
state: present
'''
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import (HAS_PYVMOMI,
connect_to_api,
find_datacenter_by_name,
find_dvs_by_name,
vmware_argument_spec,
wait_for_task
)
class VMwareDVSwitch(object):
def __init__(self, module):
self.module = module
self.dvs = None
self.switch_name = self.module.params['switch_name']
self.datacenter_name = self.module.params['datacenter_name']
self.mtu = self.module.params['mtu']
self.uplink_quantity = self.module.params['uplink_quantity']
self.discovery_proto = self.module.params['discovery_proto']
self.discovery_operation = self.module.params['discovery_operation']
self.state = self.module.params['state']
self.content = connect_to_api(module)
def process_state(self):
try:
dvs_states = {
'absent': {
'present': self.state_destroy_dvs,
'absent': self.state_exit_unchanged,
},
'present': {
'update': self.state_update_dvs,
'present': self.state_exit_unchanged,
'absent': self.state_create_dvs,
}
}
dvs_states[self.state][self.check_dvs_configuration()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def create_dvswitch(self, network_folder):
result = None
changed = False
spec = vim.DistributedVirtualSwitch.CreateSpec()
spec.configSpec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
spec.configSpec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy()
spec.configSpec.linkDiscoveryProtocolConfig = vim.host.LinkDiscoveryProtocolConfig()
spec.configSpec.name = self.switch_name
spec.configSpec.maxMtu = self.mtu
spec.configSpec.linkDiscoveryProtocolConfig.protocol = self.discovery_proto
spec.configSpec.linkDiscoveryProtocolConfig.operation = self.discovery_operation
spec.productInfo = vim.dvs.ProductSpec()
spec.productInfo.name = "DVS"
spec.productInfo.vendor = "VMware"
for count in range(1, self.uplink_quantity+1):
spec.configSpec.uplinkPortPolicy.uplinkPortName.append("uplink%d" % count)
task = network_folder.CreateDVS_Task(spec)
changed, result = wait_for_task(task)
return changed, result
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def state_destroy_dvs(self):
task = self.dvs.Destroy_Task()
changed, result = wait_for_task(task)
self.module.exit_json(changed=changed, result=str(result))
def state_update_dvs(self):
self.module.exit_json(changed=False, msg="Currently not implemented.")
def state_create_dvs(self):
changed = True
result = None
if not self.module.check_mode:
dc = find_datacenter_by_name(self.content, self.datacenter_name)
changed, result = self.create_dvswitch(dc.networkFolder)
self.module.exit_json(changed=changed, result=str(result))
def check_dvs_configuration(self):
self.dvs = find_dvs_by_name(self.content, self.switch_name)
if self.dvs is None:
return 'absent'
else:
return 'present'
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(datacenter_name=dict(required=True, type='str'),
switch_name=dict(required=True, type='str'),
mtu=dict(required=True, type='int'),
uplink_quantity=dict(required=True, type='int'),
discovery_proto=dict(required=True, choices=['cdp', 'lldp'], type='str'),
discovery_operation=dict(required=True, choices=['both', 'none', 'advertise', 'listen'], type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_PYVMOMI:
|
vmware_dvswitch = VMwareDVSwitch(module)
vmware_dvswitch.process_state()
if __name__ == '__main__':
main()
| module.fail_json(msg='pyvmomi is required for this module') | conditional_block |
vmware_dvswitch.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_dvswitch
short_description: Create or remove a distributed vSwitch
description:
- Create or remove a distributed vSwitch
version_added: 2.0
author: "Joseph Callen (@jcpowermac)"
notes:
- Tested on vSphere 5.5
requirements:
- "python >= 2.6"
- PyVmomi
options:
datacenter_name:
description:
- The name of the datacenter that will contain the dvSwitch
required: True
switch_name:
description:
- The name of the switch to create or remove
required: True
mtu:
description:
- The switch maximum transmission unit
required: True
uplink_quantity:
description:
- Quantity of uplink per ESXi host added to the switch
required: True
discovery_proto:
description:
- Link discovery protocol between Cisco and Link Layer discovery
choices:
- 'cdp'
- 'lldp'
required: True
discovery_operation:
description:
- Select the discovery operation
choices:
- 'both'
- 'none'
- 'advertise'
- 'listen'
state:
description:
- Create or remove dvSwitch
default: 'present'
choices:
- 'present'
- 'absent'
required: False
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Create dvswitch
local_action:
module: vmware_dvswitch
hostname: vcenter_ip_or_hostname
username: vcenter_username
password: vcenter_password
datacenter_name: datacenter
switch_name: dvSwitch
mtu: 9000
uplink_quantity: 2
discovery_proto: lldp
discovery_operation: both
state: present
'''
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import (HAS_PYVMOMI,
connect_to_api, | find_dvs_by_name,
vmware_argument_spec,
wait_for_task
)
class VMwareDVSwitch(object):
def __init__(self, module):
self.module = module
self.dvs = None
self.switch_name = self.module.params['switch_name']
self.datacenter_name = self.module.params['datacenter_name']
self.mtu = self.module.params['mtu']
self.uplink_quantity = self.module.params['uplink_quantity']
self.discovery_proto = self.module.params['discovery_proto']
self.discovery_operation = self.module.params['discovery_operation']
self.state = self.module.params['state']
self.content = connect_to_api(module)
def process_state(self):
try:
dvs_states = {
'absent': {
'present': self.state_destroy_dvs,
'absent': self.state_exit_unchanged,
},
'present': {
'update': self.state_update_dvs,
'present': self.state_exit_unchanged,
'absent': self.state_create_dvs,
}
}
dvs_states[self.state][self.check_dvs_configuration()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def create_dvswitch(self, network_folder):
result = None
changed = False
spec = vim.DistributedVirtualSwitch.CreateSpec()
spec.configSpec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
spec.configSpec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy()
spec.configSpec.linkDiscoveryProtocolConfig = vim.host.LinkDiscoveryProtocolConfig()
spec.configSpec.name = self.switch_name
spec.configSpec.maxMtu = self.mtu
spec.configSpec.linkDiscoveryProtocolConfig.protocol = self.discovery_proto
spec.configSpec.linkDiscoveryProtocolConfig.operation = self.discovery_operation
spec.productInfo = vim.dvs.ProductSpec()
spec.productInfo.name = "DVS"
spec.productInfo.vendor = "VMware"
for count in range(1, self.uplink_quantity+1):
spec.configSpec.uplinkPortPolicy.uplinkPortName.append("uplink%d" % count)
task = network_folder.CreateDVS_Task(spec)
changed, result = wait_for_task(task)
return changed, result
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def state_destroy_dvs(self):
task = self.dvs.Destroy_Task()
changed, result = wait_for_task(task)
self.module.exit_json(changed=changed, result=str(result))
def state_update_dvs(self):
self.module.exit_json(changed=False, msg="Currently not implemented.")
def state_create_dvs(self):
changed = True
result = None
if not self.module.check_mode:
dc = find_datacenter_by_name(self.content, self.datacenter_name)
changed, result = self.create_dvswitch(dc.networkFolder)
self.module.exit_json(changed=changed, result=str(result))
def check_dvs_configuration(self):
self.dvs = find_dvs_by_name(self.content, self.switch_name)
if self.dvs is None:
return 'absent'
else:
return 'present'
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(datacenter_name=dict(required=True, type='str'),
switch_name=dict(required=True, type='str'),
mtu=dict(required=True, type='int'),
uplink_quantity=dict(required=True, type='int'),
discovery_proto=dict(required=True, choices=['cdp', 'lldp'], type='str'),
discovery_operation=dict(required=True, choices=['both', 'none', 'advertise', 'listen'], type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_PYVMOMI:
module.fail_json(msg='pyvmomi is required for this module')
vmware_dvswitch = VMwareDVSwitch(module)
vmware_dvswitch.process_state()
if __name__ == '__main__':
main() | find_datacenter_by_name, | random_line_split |
Routine.js | app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Ro | ata) {
if (data) {
this.setData(data);
}
};
// Methods
Routine.prototype = new DataModel(Config.HostServices + "/api/Routine");
Routine.prototype.GetLastRoutine = function () {
var $this = this;
return $http.get($this.url + '/GetLastRoutine/').success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.GetByClientId = function (id) {
var $this = this;
return $http.get($this.url + '/GetByClientId/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.HistoryClient = function (id) {
var $this = this;
return $http.get($this.url + '/HistoryClient/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
return Routine;
}
]); | utine(d | identifier_name |
Routine.js | app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Routine(data) {
|
// Methods
Routine.prototype = new DataModel(Config.HostServices + "/api/Routine");
Routine.prototype.GetLastRoutine = function () {
var $this = this;
return $http.get($this.url + '/GetLastRoutine/').success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.GetByClientId = function (id) {
var $this = this;
return $http.get($this.url + '/GetByClientId/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.HistoryClient = function (id) {
var $this = this;
return $http.get($this.url + '/HistoryClient/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
return Routine;
}
]); | if (data) {
this.setData(data);
}
};
| identifier_body |
Routine.js | app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Routine(data) {
if (data) {
| };
// Methods
Routine.prototype = new DataModel(Config.HostServices + "/api/Routine");
Routine.prototype.GetLastRoutine = function () {
var $this = this;
return $http.get($this.url + '/GetLastRoutine/').success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.GetByClientId = function (id) {
var $this = this;
return $http.get($this.url + '/GetByClientId/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.HistoryClient = function (id) {
var $this = this;
return $http.get($this.url + '/HistoryClient/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
return Routine;
}
]); | this.setData(data);
}
| conditional_block |
Routine.js | app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Routine(data) {
if (data) {
this.setData(data);
}
};
// Methods
Routine.prototype = new DataModel(Config.HostServices + "/api/Routine");
Routine.prototype.GetLastRoutine = function () {
var $this = this;
return $http.get($this.url + '/GetLastRoutine/').success(function (response) { | }
});
};
Routine.prototype.GetByClientId = function (id) {
var $this = this;
return $http.get($this.url + '/GetByClientId/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.HistoryClient = function (id) {
var $this = this;
return $http.get($this.url + '/HistoryClient/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
return Routine;
}
]); | if (response && response.Status == 0) {
angular.extend($this, response.Result); | random_line_split |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use HttpResult;
use client::{Response, get_host_and_port};
/// A client request to a remote server.
pub struct Request<W> {
/// The target URI for this request.
pub url: Url,
/// The HTTP version of this request.
pub version: version::HttpVersion,
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
headers: Headers,
method: method::Method,
_marker: PhantomData<W>,
}
impl<W> Request<W> {
/// Read the Request headers.
#[inline]
pub fn headers(&self) -> &Headers { &self.headers }
/// Read the Request method.
#[inline]
pub fn method(&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> HttpResult<Request<Fresh>> where
C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> {
debug!("{} {}", method, url);
let (host, port) = try!(get_host_and_port(&url));
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
let stream = ThroughWriter(BufWriter::new(stream));
let mut headers = Headers::new();
headers.set(Host {
hostname: host,
port: Some(port),
});
Ok(Request {
method: method,
headers: headers,
url: url,
version: version::HttpVersion::Http11,
body: stream,
_marker: PhantomData,
})
}
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> HttpResult<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test
if let Some(ref q) = self.url.query {
uri.push('?');
uri.push_str(&q[..]);
}
debug!("writing head: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
EmptyWriter(self.body.into_inner())
},
_ => {
let mut chunked = true;
let mut len = 0;
match self.headers.get::<header::ContentLength>() {
Some(cl) => {
chunked = false;
len = **cl;
},
None => ()
};
// cant do in match above, thanks borrowck
if chunked |
debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
}
}
};
Ok(Request {
method: self.method,
headers: self.headers,
url: self.url,
version: self.version,
body: stream,
_marker: PhantomData,
})
}
/// Get a mutable reference to the Request headers.
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> HttpResult<Response> {
let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
Response::new(raw)
}
}
impl Write for Request<Streaming> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConnector};
use super::Request;
#[test]
fn test_get_empty_body() {
let req = Request::with_connector(
Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let req = Request::with_connector(
Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
}
| {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(header::Encoding::Chunked);
false
},
None => true
};
if encodings {
self.headers.set::<header::TransferEncoding>(
header::TransferEncoding(vec![header::Encoding::Chunked]))
}
} | conditional_block |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use HttpResult;
use client::{Response, get_host_and_port};
/// A client request to a remote server.
pub struct Request<W> {
/// The target URI for this request.
pub url: Url,
/// The HTTP version of this request.
pub version: version::HttpVersion,
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
headers: Headers,
method: method::Method,
_marker: PhantomData<W>,
}
impl<W> Request<W> {
/// Read the Request headers.
#[inline]
pub fn headers(&self) -> &Headers { &self.headers }
/// Read the Request method.
#[inline]
pub fn method(&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> HttpResult<Request<Fresh>> where
C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> {
debug!("{} {}", method, url);
let (host, port) = try!(get_host_and_port(&url));
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
let stream = ThroughWriter(BufWriter::new(stream));
let mut headers = Headers::new();
headers.set(Host {
hostname: host,
port: Some(port),
});
Ok(Request {
method: method,
headers: headers,
url: url,
version: version::HttpVersion::Http11,
body: stream,
_marker: PhantomData,
})
}
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> HttpResult<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test
if let Some(ref q) = self.url.query {
uri.push('?');
uri.push_str(&q[..]);
}
debug!("writing head: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
EmptyWriter(self.body.into_inner())
},
_ => {
let mut chunked = true;
let mut len = 0;
match self.headers.get::<header::ContentLength>() {
Some(cl) => {
chunked = false;
len = **cl;
},
None => ()
};
// cant do in match above, thanks borrowck
if chunked {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(header::Encoding::Chunked);
false
},
None => true
};
if encodings {
self.headers.set::<header::TransferEncoding>(
header::TransferEncoding(vec![header::Encoding::Chunked]))
}
}
debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
}
}
};
Ok(Request {
method: self.method,
headers: self.headers,
url: self.url,
version: self.version,
body: stream,
_marker: PhantomData,
})
}
/// Get a mutable reference to the Request headers.
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers |
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> HttpResult<Response> {
let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
Response::new(raw)
}
}
impl Write for Request<Streaming> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConnector};
use super::Request;
#[test]
fn test_get_empty_body() {
let req = Request::with_connector(
Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let req = Request::with_connector(
Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
}
| { &mut self.headers } | identifier_body |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use HttpResult;
use client::{Response, get_host_and_port};
/// A client request to a remote server.
pub struct Request<W> {
/// The target URI for this request.
pub url: Url,
/// The HTTP version of this request.
pub version: version::HttpVersion,
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
headers: Headers,
method: method::Method,
_marker: PhantomData<W>,
}
impl<W> Request<W> {
/// Read the Request headers.
#[inline]
pub fn headers(&self) -> &Headers { &self.headers }
/// Read the Request method.
#[inline]
pub fn method(&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> HttpResult<Request<Fresh>> where
C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> {
debug!("{} {}", method, url);
let (host, port) = try!(get_host_and_port(&url));
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
let stream = ThroughWriter(BufWriter::new(stream));
let mut headers = Headers::new();
headers.set(Host {
hostname: host,
port: Some(port),
});
Ok(Request {
method: method,
headers: headers,
url: url,
version: version::HttpVersion::Http11,
body: stream,
_marker: PhantomData,
})
}
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> HttpResult<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test
if let Some(ref q) = self.url.query {
uri.push('?');
uri.push_str(&q[..]);
}
debug!("writing head: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
EmptyWriter(self.body.into_inner())
},
_ => {
let mut chunked = true;
let mut len = 0;
match self.headers.get::<header::ContentLength>() {
Some(cl) => {
chunked = false;
len = **cl;
},
None => ()
};
// cant do in match above, thanks borrowck
if chunked {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(header::Encoding::Chunked);
false
},
None => true
};
if encodings {
self.headers.set::<header::TransferEncoding>(
header::TransferEncoding(vec![header::Encoding::Chunked]))
}
}
| debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
}
}
};
Ok(Request {
method: self.method,
headers: self.headers,
url: self.url,
version: self.version,
body: stream,
_marker: PhantomData,
})
}
/// Get a mutable reference to the Request headers.
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> HttpResult<Response> {
let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
Response::new(raw)
}
}
impl Write for Request<Streaming> {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConnector};
use super::Request;
#[test]
fn test_get_empty_body() {
let req = Request::with_connector(
Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let req = Request::with_connector(
Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
} | random_line_split | |
request.rs | //! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write, BufWriter};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::{self, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use HttpResult;
use client::{Response, get_host_and_port};
/// A client request to a remote server.
pub struct Request<W> {
/// The target URI for this request.
pub url: Url,
/// The HTTP version of this request.
pub version: version::HttpVersion,
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
headers: Headers,
method: method::Method,
_marker: PhantomData<W>,
}
impl<W> Request<W> {
/// Read the Request headers.
#[inline]
pub fn headers(&self) -> &Headers { &self.headers }
/// Read the Request method.
#[inline]
pub fn method(&self) -> method::Method { self.method.clone() }
}
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &mut C)
-> HttpResult<Request<Fresh>> where
C: NetworkConnector<Stream=S>,
S: Into<Box<NetworkStream + Send>> {
debug!("{} {}", method, url);
let (host, port) = try!(get_host_and_port(&url));
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
let stream = ThroughWriter(BufWriter::new(stream));
let mut headers = Headers::new();
headers.set(Host {
hostname: host,
port: Some(port),
});
Ok(Request {
method: method,
headers: headers,
url: url,
version: version::HttpVersion::Http11,
body: stream,
_marker: PhantomData,
})
}
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> HttpResult<Request<Streaming>> {
let mut uri = self.url.serialize_path().unwrap();
//TODO: this needs a test
if let Some(ref q) = self.url.query {
uri.push('?');
uri.push_str(&q[..]);
}
debug!("writing head: {:?} {:?} {:?}", self.method, uri, self.version);
try!(write!(&mut self.body, "{} {} {}{}",
self.method, uri, self.version, LINE_ENDING));
let stream = match self.method {
Method::Get | Method::Head => {
debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
EmptyWriter(self.body.into_inner())
},
_ => {
let mut chunked = true;
let mut len = 0;
match self.headers.get::<header::ContentLength>() {
Some(cl) => {
chunked = false;
len = **cl;
},
None => ()
};
// cant do in match above, thanks borrowck
if chunked {
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
Some(&mut header::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(header::Encoding::Chunked);
false
},
None => true
};
if encodings {
self.headers.set::<header::TransferEncoding>(
header::TransferEncoding(vec![header::Encoding::Chunked]))
}
}
debug!("headers [\n{:?}]", self.headers);
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
if chunked {
ChunkedWriter(self.body.into_inner())
} else {
SizedWriter(self.body.into_inner(), len)
}
}
};
Ok(Request {
method: self.method,
headers: self.headers,
url: self.url,
version: self.version,
body: stream,
_marker: PhantomData,
})
}
/// Get a mutable reference to the Request headers.
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}
impl Request<Streaming> {
/// Completes writing the request, and returns a response to read from.
///
/// Consumes the Request.
pub fn send(self) -> HttpResult<Response> {
let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
Response::new(raw)
}
}
impl Write for Request<Streaming> {
#[inline]
fn | (&mut self, msg: &[u8]) -> io::Result<usize> {
self.body.write(msg)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.body.flush()
}
}
#[cfg(test)]
mod tests {
use std::str::from_utf8;
use url::Url;
use method::Method::{Get, Head};
use mock::{MockStream, MockConnector};
use super::Request;
#[test]
fn test_get_empty_body() {
let req = Request::with_connector(
Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
#[test]
fn test_head_empty_body() {
let req = Request::with_connector(
Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector
).unwrap();
let req = req.start().unwrap();
let stream = *req.body.end().unwrap()
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
let bytes = stream.write;
let s = from_utf8(&bytes[..]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
}
}
| write | identifier_name |
container.js |
import {connect } from 'react-redux'
import React,{Component} from 'react'
import {Nav, Navbar, NavItem} from 'react-bootstrap'
import {pushState} from 'redux-router'
import Alert from '../components/alert'
import Loader from 'react-loader-advanced';
@connect((state) => ( {loading: state.common.loading}))
export default class App extends Component {
constructor(props){
super(props);
}
render () |
}
| {
let topRoutes = this.props.route.childRoutes;
let activeRoute = topRoutes.filter(route => this.props.history.isActive(route.path))[0]
return (<div>
<Navbar>
<Navbar.Header>
<Navbar.Brand><a href="#">ToolboxSite</a></Navbar.Brand>
</Navbar.Header>
<Nav pullRight>
{topRoutes.map(route =><NavItem key={route.path} href={'#'+ route.path}>{route.name}</NavItem>)}
<NavItem href="https://github.com/Jishun/ToolboxSite" target="_blank">GitHub</NavItem>
</Nav>
</Navbar>
<div id="content_area" className="container">
<Nav bsStyle="tabs">
{activeRoute && activeRoute.childRoutes? activeRoute.childRoutes.map((route, i) => <NavItem key={i} active={this.props.history.isActive(route.path)} href={'#' +route.path}>{route.name}</NavItem>) : null}
</Nav>
<Alert></Alert>
<div>{this.props.children}</div>
</div>
</div>);
} | identifier_body |
container.js |
import {connect } from 'react-redux'
import React,{Component} from 'react'
import {Nav, Navbar, NavItem} from 'react-bootstrap'
import {pushState} from 'redux-router'
import Alert from '../components/alert'
import Loader from 'react-loader-advanced';
@connect((state) => ( {loading: state.common.loading}))
export default class | extends Component {
constructor(props){
super(props);
}
render () {
let topRoutes = this.props.route.childRoutes;
let activeRoute = topRoutes.filter(route => this.props.history.isActive(route.path))[0]
return (<div>
<Navbar>
<Navbar.Header>
<Navbar.Brand><a href="#">ToolboxSite</a></Navbar.Brand>
</Navbar.Header>
<Nav pullRight>
{topRoutes.map(route =><NavItem key={route.path} href={'#'+ route.path}>{route.name}</NavItem>)}
<NavItem href="https://github.com/Jishun/ToolboxSite" target="_blank">GitHub</NavItem>
</Nav>
</Navbar>
<div id="content_area" className="container">
<Nav bsStyle="tabs">
{activeRoute && activeRoute.childRoutes? activeRoute.childRoutes.map((route, i) => <NavItem key={i} active={this.props.history.isActive(route.path)} href={'#' +route.path}>{route.name}</NavItem>) : null}
</Nav>
<Alert></Alert>
<div>{this.props.children}</div>
</div>
</div>);
}
}
| App | identifier_name |
container.js | import {connect } from 'react-redux'
import React,{Component} from 'react'
import {Nav, Navbar, NavItem} from 'react-bootstrap'
import {pushState} from 'redux-router'
import Alert from '../components/alert'
import Loader from 'react-loader-advanced';
@connect((state) => ( {loading: state.common.loading}))
export default class App extends Component {
constructor(props){
super(props);
}
render () {
let topRoutes = this.props.route.childRoutes;
let activeRoute = topRoutes.filter(route => this.props.history.isActive(route.path))[0]
return (<div>
<Navbar>
<Navbar.Header> | <Nav pullRight>
{topRoutes.map(route =><NavItem key={route.path} href={'#'+ route.path}>{route.name}</NavItem>)}
<NavItem href="https://github.com/Jishun/ToolboxSite" target="_blank">GitHub</NavItem>
</Nav>
</Navbar>
<div id="content_area" className="container">
<Nav bsStyle="tabs">
{activeRoute && activeRoute.childRoutes? activeRoute.childRoutes.map((route, i) => <NavItem key={i} active={this.props.history.isActive(route.path)} href={'#' +route.path}>{route.name}</NavItem>) : null}
</Nav>
<Alert></Alert>
<div>{this.props.children}</div>
</div>
</div>);
}
} | <Navbar.Brand><a href="#">ToolboxSite</a></Navbar.Brand>
</Navbar.Header> | random_line_split |
compiled_part_6_AbstractAuthView_1.js | /**
* Class that handles abstract function for register and login views
*
* @amed
*/
window.themingStore.views.AbstractAuthView = window.themingStore.views.AbstractView.extend({
/**
* Holds a flag that says the show function if a message is already
* being displayed.
*/
globalErrorBeingShown: false,
/**
* Holds a flag that says the edited field is correct
* based on the properly validation. see verifyValueCorrectnessInLine()
*/
isFieldValidWhileTyping: false,
/**
* Holds a string that indicates the last action in the form
* that wa performed to trigger the Back icon button event.
*/
lastAction: '',
/**
* Overrides the parent constructor
*/
initialize: function () {
window.themingStore.views.AbstractView.prototype.initialize.call(this);
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* creates a base request to send to backend
* @param url
* @param type
* @param data
* @param successf
* @param errorf
* @private
*/
_reqCreator: function (url, type, data, successf, errorf) {
$.ajax({
url: url,
data: data,
type: type,
success: successf,
error: errorf
});
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* function called to check if the user exists
* @param email
* @returns {boolean}
* @private
*/
_userexists: function (email) {
var self = this;
var resp = false;
$.ajax({
url: Routing.generate("sc_demo_security_rest_get_email_check"),
type: "GET",
async: false,
xhrFields: {
"Accept": "application/json"
},
data: {'_email': email},
success: function (data, textStatus, jqXHR) {
if (data.response != false) {
resp = true;
}
}
});
return resp;
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* checks if user is in session and redirect him to the appropriate location
*/
checkLoggedUser: function () {
if (window.themingStore.currentUser) {
if (window.themingStore.currentUser.get('is_publisher')) {
window.themingStore.currentRouter.navigate('dashboard');
}
else {
window.themingStore.currentRouter.navigate('browse');
}
}
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* method to react to gp error on load
*/
listenErrorsGPlusError: function () {
var self = this;
window.onerror = function (msg, url, linenumber) {
if ("Error: Permission denied to access object" == msg) {
Cookies.setCookie(self.gpluscookieerror,
JSON.stringify({ authenticated: true }), 1);
window.location.reload(true);
}
};
},
/**
* Shows an error message above the main form.
*
* @param msg string The message that will be shown inside the error container
* @param el Object a jQuery object to be used as the element where the message
* will be put after.
* @param timeout int The value in milliseconds that the message lasts being shown.
*/
showGlobalError: function (msg, timeout, el) {
if (!this.globalErrorBeingShown) {
this.globalErrorBeingShown = true;
if (typeof el == 'undefined') {
el = $('.logo-ts');
}
var errorImg = $('<img>');
errorImg.attr('src', '/bundles/syscrunchstore/images/log_warning.png')
.attr('alt', '!')
.attr('Error');
var errorMessage = $('<div></div>');
errorMessage.addClass('message')
.append(errorImg)
.append(msg);
var errorContainer = $('<div></div>');
errorContainer.addClass('error_container')
.append(errorMessage);
// Append message after the main element
el.after(errorContainer);
var self = this;
var _callB = function () {
errorContainer.remove();
self.globalErrorBeingShown = false;
};
if (typeof timeout == 'undefined') {
timeout = 3000;
}
setTimeout(_callB, timeout);
}
},
/**
* Makes a transition by showing the sign in form after
* hiding the form-cont.
*
* @param transitionHideTime int The time in milliseconds to hide the first form.
* @param transitionShowTime int The time in milliseconds to hide the second form.
* @param secondForm string The jQuery selector of the form to be displayed.
* @param firstForm string The jQuery selector of the form to be hiden.
*/
showSecondForm: function (transitionHideTime, transitionShowTime, secondForm, firstForm) {
if (typeof transitionHideTime == 'undefined') {
transitionHideTime = 1000;
}
if (typeof transitionShowTime == 'undefined') {
transitionShowTime = 1000;
}
if (typeof secondForm == 'undefined') {
secondForm = '.sign_in_form_container';
}
if (typeof firstForm == 'undefined') {
firstForm = '.form-cont';
}
$(firstForm).animate({height: "hide"}, transitionHideTime, "easeOutQuad");
$(secondForm).animate({height: "show"}, transitionShowTime, "easeOutQuad");
},
/**
*
*
* @param transitionHideTime
* @param transitionShowTime
* @param secondForm
* @param firstForm
*/
showFirstForm: function (transitionHideTime, transitionShowTime, secondForm, firstForm) {
if (typeof transitionHideTime == 'undefined') {
transitionHideTime = 1000;
}
if (typeof transitionShowTime == 'undefined') {
transitionShowTime = 1000;
}
if (typeof secondForm == 'undefined') {
secondForm = '.sign_in_form_container';
}
if (typeof firstForm == 'undefined') {
firstForm = '.form-cont';
}
$(firstForm).animate({height: "show"}, transitionHideTime, "easeOutQuad");
$(secondForm).animate({height: "hide"}, transitionShowTime, "easeOutQuad");
},
/**
* Captures the typing event in the field based on the selector
* given as parameter, and verifies if it is valid according to a
* validation rule defined by the type. If type is not defined, it takes
* from the type attribute of the field.
*
* @param selector string jQuery string selector
* @param type string
*/
verifyValueCorrectnessInLine: function (selector, type) {
var self = this;
if (typeof type == 'undefined') {
type = $(this).attr('type');
}
switch (type) {
case 'email':
self.validateEmailOnKeyUp(selector);
break;
case 'password':
self.passwordValidation(selector);
break;
default:
throw 'Provide a validation rule first!';
}
},
validateEmailOnKeyUp: function (selector) {
var self = this;
$(selector).on('keyup', function (event) {
var keyCode = event.keyCode; |
var textValue = $(this).val();
var isValid = false;
if (!(/[^\s]+/.test(textValue))) {
isValid = false;
}
else {
var emailPattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if (textValue.match(emailPattern) != null) {
isValid = true;
}
}
$('#verify_icon').remove();
var errImg = $('<img>').attr('style', 'position: relative;top: -78%;left: 55%;width: 15%;')
.attr('id', 'verify_icon');
if (!isValid) {
errImg.attr('src', '/bundles/syscrunchstore/images/log_error.png');
self.isFieldValidWhileTyping = false;
}
else {
errImg.attr('src', '/bundles/syscrunchstore/images/log_ok.png');
self.isFieldValidWhileTyping = true;
}
$(this).after(errImg);
});
},
passwordValidation: function (selector) {
var passwordField = $(selector);
var passwordConfirm = $('#conf_password');
var self = this;
// EMPTY FIELD
var errImg = $('<img>').attr('style', 'position: relative;top: -78%;left: 55%;width: 15%;')
.attr('id', 'verify_icon');
errImg.attr('src', '/bundles/syscrunchstore/images/log_error.png');
passwordField.after(errImg);
$(selector + ', #conf_password').on('keyup', function (event) {
var text1 = passwordField.val();
var text2 = passwordConfirm.val();
var isValid = true;
if (!(/[^\s]+/.test(text1)) && !(/[^\s]+/.test(text2)))
{
isValid = false;
self.isFieldValidWhileTyping = false;
var errImg = $('<img>').attr('style', 'position: relative;top: -78%;left: 55%;width: 15%;')
.attr('id', 'verify_icon');
errImg.attr('src', '/bundles/syscrunchstore/images/log_error.png');
$(this).after(errImg);
}
else
{
$('#verify_icon').remove();
if (text1 !== text2)
{
var divBubble = $('<div></div>').attr('style', 'position: relative;top: -30px;left: 244px;').
attr('id', 'verify_icon');
var errImg = $('<img>')
.attr('src', '/bundles/syscrunchstore/images/log_left_bubble_2.png').attr('style', ' width: 15px; float: left;')
.attr('align', 'top');
divBubble.append(errImg);
var divMsgBubble = $('<div></div>')
.attr('style',
'background-color: #FFFFFF; width: auto; height: 25px;float: left;font-size: 14px;line-height: 24px;border-top-right-radius: 9px;border-bottom-right-radius: 9px;padding-right: 6px;')
.text('Passwords do not match');
divBubble.append(divMsgBubble);
var divClear = $('<div class="clear"></div>');
divBubble.append(divClear);
passwordField.after(divBubble);
self.isFieldValidWhileTyping = false;
}
else
{
$('#verify_icon').remove();
self.isFieldValidWhileTyping = true;
}
}
});
},
/**
* Handles the Back icon button in the pages.
*
* @param event
*/
makeBackRedirection: function (event){
var self = this;
$('.back_container').unbind("click").bind("click", function(event){
if (self.lastAction == '')
{
window.themingStore.currentRouter.navigate('browse');
}
else
{
var action = self.lastAction;
switch (action)
{
case 'twitter': self.showFirstForm(500, 500, '.sign_in_twitter_form_container'); break;
case 'email_form': self.showFirstForm(); break;
}
}
self.lastAction = '';
});
}
}); | random_line_split | |
compiled_part_6_AbstractAuthView_1.js | /**
* Class that handles abstract function for register and login views
*
* @amed
*/
window.themingStore.views.AbstractAuthView = window.themingStore.views.AbstractView.extend({
/**
* Holds a flag that says the show function if a message is already
* being displayed.
*/
globalErrorBeingShown: false,
/**
* Holds a flag that says the edited field is correct
* based on the properly validation. see verifyValueCorrectnessInLine()
*/
isFieldValidWhileTyping: false,
/**
* Holds a string that indicates the last action in the form
* that wa performed to trigger the Back icon button event.
*/
lastAction: '',
/**
* Overrides the parent constructor
*/
initialize: function () {
window.themingStore.views.AbstractView.prototype.initialize.call(this);
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* creates a base request to send to backend
* @param url
* @param type
* @param data
* @param successf
* @param errorf
* @private
*/
_reqCreator: function (url, type, data, successf, errorf) {
$.ajax({
url: url,
data: data,
type: type,
success: successf,
error: errorf
});
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* function called to check if the user exists
* @param email
* @returns {boolean}
* @private
*/
_userexists: function (email) {
var self = this;
var resp = false;
$.ajax({
url: Routing.generate("sc_demo_security_rest_get_email_check"),
type: "GET",
async: false,
xhrFields: {
"Accept": "application/json"
},
data: {'_email': email},
success: function (data, textStatus, jqXHR) {
if (data.response != false) {
resp = true;
}
}
});
return resp;
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* checks if user is in session and redirect him to the appropriate location
*/
checkLoggedUser: function () {
if (window.themingStore.currentUser) {
if (window.themingStore.currentUser.get('is_publisher')) {
window.themingStore.currentRouter.navigate('dashboard');
}
else {
window.themingStore.currentRouter.navigate('browse');
}
}
},
/**
* @author Jonathan Claros <jonathan.claros@syscrunch.com>
* method to react to gp error on load
*/
listenErrorsGPlusError: function () {
var self = this;
window.onerror = function (msg, url, linenumber) {
if ("Error: Permission denied to access object" == msg) {
Cookies.setCookie(self.gpluscookieerror,
JSON.stringify({ authenticated: true }), 1);
window.location.reload(true);
}
};
},
/**
* Shows an error message above the main form.
*
* @param msg string The message that will be shown inside the error container
* @param el Object a jQuery object to be used as the element where the message
* will be put after.
* @param timeout int The value in milliseconds that the message lasts being shown.
*/
showGlobalError: function (msg, timeout, el) {
if (!this.globalErrorBeingShown) {
this.globalErrorBeingShown = true;
if (typeof el == 'undefined') {
el = $('.logo-ts');
}
var errorImg = $('<img>');
errorImg.attr('src', '/bundles/syscrunchstore/images/log_warning.png')
.attr('alt', '!')
.attr('Error');
var errorMessage = $('<div></div>');
errorMessage.addClass('message')
.append(errorImg)
.append(msg);
var errorContainer = $('<div></div>');
errorContainer.addClass('error_container')
.append(errorMessage);
// Append message after the main element
el.after(errorContainer);
var self = this;
var _callB = function () {
errorContainer.remove();
self.globalErrorBeingShown = false;
};
if (typeof timeout == 'undefined') {
timeout = 3000;
}
setTimeout(_callB, timeout);
}
},
/**
* Makes a transition by showing the sign in form after
* hiding the form-cont.
*
* @param transitionHideTime int The time in milliseconds to hide the first form.
* @param transitionShowTime int The time in milliseconds to hide the second form.
* @param secondForm string The jQuery selector of the form to be displayed.
* @param firstForm string The jQuery selector of the form to be hiden.
*/
showSecondForm: function (transitionHideTime, transitionShowTime, secondForm, firstForm) {
if (typeof transitionHideTime == 'undefined') {
transitionHideTime = 1000;
}
if (typeof transitionShowTime == 'undefined') {
transitionShowTime = 1000;
}
if (typeof secondForm == 'undefined') {
secondForm = '.sign_in_form_container';
}
if (typeof firstForm == 'undefined') {
firstForm = '.form-cont';
}
$(firstForm).animate({height: "hide"}, transitionHideTime, "easeOutQuad");
$(secondForm).animate({height: "show"}, transitionShowTime, "easeOutQuad");
},
/**
*
*
* @param transitionHideTime
* @param transitionShowTime
* @param secondForm
* @param firstForm
*/
showFirstForm: function (transitionHideTime, transitionShowTime, secondForm, firstForm) {
if (typeof transitionHideTime == 'undefined') {
transitionHideTime = 1000;
}
if (typeof transitionShowTime == 'undefined') {
transitionShowTime = 1000;
}
if (typeof secondForm == 'undefined') {
secondForm = '.sign_in_form_container';
}
if (typeof firstForm == 'undefined') {
firstForm = '.form-cont';
}
$(firstForm).animate({height: "show"}, transitionHideTime, "easeOutQuad");
$(secondForm).animate({height: "hide"}, transitionShowTime, "easeOutQuad");
},
/**
* Captures the typing event in the field based on the selector
* given as parameter, and verifies if it is valid according to a
* validation rule defined by the type. If type is not defined, it takes
* from the type attribute of the field.
*
* @param selector string jQuery string selector
* @param type string
*/
verifyValueCorrectnessInLine: function (selector, type) {
var self = this;
if (typeof type == 'undefined') {
type = $(this).attr('type');
}
switch (type) {
case 'email':
self.validateEmailOnKeyUp(selector);
break;
case 'password':
self.passwordValidation(selector);
break;
default:
throw 'Provide a validation rule first!';
}
},
validateEmailOnKeyUp: function (selector) {
var self = this;
$(selector).on('keyup', function (event) {
var keyCode = event.keyCode;
var textValue = $(this).val();
var isValid = false;
if (!(/[^\s]+/.test(textValue))) {
isValid = false;
}
else {
var emailPattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if (textValue.match(emailPattern) != null) {
isValid = true;
}
}
$('#verify_icon').remove();
var errImg = $('<img>').attr('style', 'position: relative;top: -78%;left: 55%;width: 15%;')
.attr('id', 'verify_icon');
if (!isValid) {
errImg.attr('src', '/bundles/syscrunchstore/images/log_error.png');
self.isFieldValidWhileTyping = false;
}
else {
errImg.attr('src', '/bundles/syscrunchstore/images/log_ok.png');
self.isFieldValidWhileTyping = true;
}
$(this).after(errImg);
});
},
passwordValidation: function (selector) {
var passwordField = $(selector);
var passwordConfirm = $('#conf_password');
var self = this;
// EMPTY FIELD
var errImg = $('<img>').attr('style', 'position: relative;top: -78%;left: 55%;width: 15%;')
.attr('id', 'verify_icon');
errImg.attr('src', '/bundles/syscrunchstore/images/log_error.png');
passwordField.after(errImg);
$(selector + ', #conf_password').on('keyup', function (event) {
var text1 = passwordField.val();
var text2 = passwordConfirm.val();
var isValid = true;
if (!(/[^\s]+/.test(text1)) && !(/[^\s]+/.test(text2)))
{
isValid = false;
self.isFieldValidWhileTyping = false;
var errImg = $('<img>').attr('style', 'position: relative;top: -78%;left: 55%;width: 15%;')
.attr('id', 'verify_icon');
errImg.attr('src', '/bundles/syscrunchstore/images/log_error.png');
$(this).after(errImg);
}
else
{
$('#verify_icon').remove();
if (text1 !== text2)
{
var divBubble = $('<div></div>').attr('style', 'position: relative;top: -30px;left: 244px;').
attr('id', 'verify_icon');
var errImg = $('<img>')
.attr('src', '/bundles/syscrunchstore/images/log_left_bubble_2.png').attr('style', ' width: 15px; float: left;')
.attr('align', 'top');
divBubble.append(errImg);
var divMsgBubble = $('<div></div>')
.attr('style',
'background-color: #FFFFFF; width: auto; height: 25px;float: left;font-size: 14px;line-height: 24px;border-top-right-radius: 9px;border-bottom-right-radius: 9px;padding-right: 6px;')
.text('Passwords do not match');
divBubble.append(divMsgBubble);
var divClear = $('<div class="clear"></div>');
divBubble.append(divClear);
passwordField.after(divBubble);
self.isFieldValidWhileTyping = false;
}
else
{
$('#verify_icon').remove();
self.isFieldValidWhileTyping = true;
}
}
});
},
/**
* Handles the Back icon button in the pages.
*
* @param event
*/
makeBackRedirection: function (event){
var self = this;
$('.back_container').unbind("click").bind("click", function(event){
if (self.lastAction == '')
{
window.themingStore.currentRouter.navigate('browse');
}
else
|
self.lastAction = '';
});
}
});
| {
var action = self.lastAction;
switch (action)
{
case 'twitter': self.showFirstForm(500, 500, '.sign_in_twitter_form_container'); break;
case 'email_form': self.showFirstForm(); break;
}
} | conditional_block |
asha-workers-details.service_20170224103415.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model';
import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data';
import { AshaWorkerPaymentRulesModel } from '../model/asha-worker-payment-rules-model';
import { JSONMessageModel } from '../model/json-message-model';
@Injectable()
export class AshaWorkersDetailsService{
private url: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/getdetails/get_asha_worker_details";
private updateURL: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/ashaActivityRules/updateActivity"
constructor(private http: Http){}
getAshaWorkersList(): Promise<AshaWorkerBasicDetailsModel[]>{
//return Promise.resolve(AshaWorkersList);
return this.http.get(this.url)
.toPromise()
.then(response => response.json().awAshaDetailsModel as AshaWorkerBasicDetailsModel[])
.catch(this.handleError);
}
getDummyAshaWorkerDetails(): Promise<AshaWorkerBasicDetailsModel>{
return Promise.resolve(DummyAshaWorkerDetails);
}
| .toPromise()
.then(function(response){
return response.json() as JSONMessageModel
)
.catch(this.handleError)
}
private handleError(error: any):Promise<any>{
console.error('An error occured', error);
return Promise.reject(error.message || error);
}
} | //update the payment rules for rural, urban and help text
updateAshaWorkerPaymentRules(ashaWorkerPaymentRulesModel: AshaWorkerPaymentRulesModel): Promise<JSONMessageModel>{
let body = JSON.stringify(ashaWorkerPaymentRulesModel);
console.log("body = "+ body);
return this.http.put(this.updateURL,body) | random_line_split |
asha-workers-details.service_20170224103415.ts | import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model';
import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data';
import { AshaWorkerPaymentRulesModel } from '../model/asha-worker-payment-rules-model';
import { JSONMessageModel } from '../model/json-message-model';
@Injectable()
export class | {
private url: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/getdetails/get_asha_worker_details";
private updateURL: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/ashaActivityRules/updateActivity"
constructor(private http: Http){}
getAshaWorkersList(): Promise<AshaWorkerBasicDetailsModel[]>{
//return Promise.resolve(AshaWorkersList);
return this.http.get(this.url)
.toPromise()
.then(response => response.json().awAshaDetailsModel as AshaWorkerBasicDetailsModel[])
.catch(this.handleError);
}
getDummyAshaWorkerDetails(): Promise<AshaWorkerBasicDetailsModel>{
return Promise.resolve(DummyAshaWorkerDetails);
}
//update the payment rules for rural, urban and help text
updateAshaWorkerPaymentRules(ashaWorkerPaymentRulesModel: AshaWorkerPaymentRulesModel): Promise<JSONMessageModel>{
let body = JSON.stringify(ashaWorkerPaymentRulesModel);
console.log("body = "+ body);
return this.http.put(this.updateURL,body)
.toPromise()
.then(function(response){
return response.json() as JSONMessageModel
)
.catch(this.handleError)
}
private handleError(error: any):Promise<any>{
console.error('An error occured', error);
return Promise.reject(error.message || error);
}
} | AshaWorkersDetailsService | identifier_name |
level.js | 'use strict';
function Level(args) {
if(!(this instanceof Level))
return new Level(args);
this.context = args.context;
this.player = args.player;
this.gameplayObjects = args.gameplayObjects;
this.outcomeListeners = [];
this.finalMessageListeners = [];
this.respawnInfoListeners = [];
this.victoryMessages = args.victoryMessages;
this.failureMessages = args.failureMessages;
this.isPaused = true;
this.isFinished = false;
this.handleRespawnInfo(args.respawnInfo);
this.player.setParentLevel(this);
this.gameplayObjects.forEach(o => o.beginObservingPlayer(this.player));
}
Level.prototype.draw = function() {
this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height);
this.gameplayObjects.forEach(o => o.draw(this.context));
this.player.draw(this.context);
}
Level.prototype.update = function(dt) {
this.player.update(dt);
}
Level.prototype.frame = function(dt) {
this.update(dt);
this.draw();
}
Level.prototype.startGameLoop = function() {
const gameLoopFrame = now => {
if(!this.isPaused) {
const dt = now - this.lastFrameTime;
this.frame(dt);
window.requestAnimationFrame(gameLoopFrame);
}
this.lastFrameTime = now; | }
this.isPaused = false;
this.lastFrameTime = performance.now();
window.requestAnimationFrame(gameLoopFrame);
}
Level.prototype.pauseGameLoop = function() {
this.isPaused = true;
}
Level.prototype.addOutcomeListener = function(listener) {
this.outcomeListeners.push(listener);
}
Level.prototype.addFinalMessageListener = function(listener) {
this.finalMessageListeners.push(listener);
}
Level.prototype.addRespawnInfoListener = function(listener) {
this.respawnInfoListeners.push(listener);
}
Level.prototype.generateRespawnInfo = function() {
return this.player.generateRespawnInfo();
}
Level.prototype.handleRespawnInfo = function(respawnInfo) {
this.player.handleRespawnInfo(respawnInfo);
}
Level.prototype.win = function() {
this.finishWithOutcome(true);
}
Level.prototype.lose = function() {
this.finishWithOutcome(false);
}
Level.prototype.finishWithOutcome = function(outcome) {
if(this.isFinished)
return;
this.isFinished = true;
this.pauseGameLoop();
this.player.stop();
this.outcomeListeners.forEach(listener => listener(outcome));
const finalMessage = this.getMessageForOutcome(outcome);
this.finalMessageListeners.forEach(listener => listener(finalMessage));
if(!outcome) {
const respawnInfo = this.generateRespawnInfo();
Object.freeze(respawnInfo);
this.respawnInfoListeners.forEach(listener => listener(respawnInfo));
}
}
Level.prototype.getMessageForOutcome = function(outcome) {
if(outcome)
return mathUtils.randomArrayElement(this.victoryMessages);
else return mathUtils.randomArrayElement(this.failureMessages);
} | random_line_split | |
level.js | 'use strict';
function | (args) {
if(!(this instanceof Level))
return new Level(args);
this.context = args.context;
this.player = args.player;
this.gameplayObjects = args.gameplayObjects;
this.outcomeListeners = [];
this.finalMessageListeners = [];
this.respawnInfoListeners = [];
this.victoryMessages = args.victoryMessages;
this.failureMessages = args.failureMessages;
this.isPaused = true;
this.isFinished = false;
this.handleRespawnInfo(args.respawnInfo);
this.player.setParentLevel(this);
this.gameplayObjects.forEach(o => o.beginObservingPlayer(this.player));
}
Level.prototype.draw = function() {
this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height);
this.gameplayObjects.forEach(o => o.draw(this.context));
this.player.draw(this.context);
}
Level.prototype.update = function(dt) {
this.player.update(dt);
}
Level.prototype.frame = function(dt) {
this.update(dt);
this.draw();
}
Level.prototype.startGameLoop = function() {
const gameLoopFrame = now => {
if(!this.isPaused) {
const dt = now - this.lastFrameTime;
this.frame(dt);
window.requestAnimationFrame(gameLoopFrame);
}
this.lastFrameTime = now;
}
this.isPaused = false;
this.lastFrameTime = performance.now();
window.requestAnimationFrame(gameLoopFrame);
}
Level.prototype.pauseGameLoop = function() {
this.isPaused = true;
}
Level.prototype.addOutcomeListener = function(listener) {
this.outcomeListeners.push(listener);
}
Level.prototype.addFinalMessageListener = function(listener) {
this.finalMessageListeners.push(listener);
}
Level.prototype.addRespawnInfoListener = function(listener) {
this.respawnInfoListeners.push(listener);
}
Level.prototype.generateRespawnInfo = function() {
return this.player.generateRespawnInfo();
}
Level.prototype.handleRespawnInfo = function(respawnInfo) {
this.player.handleRespawnInfo(respawnInfo);
}
Level.prototype.win = function() {
this.finishWithOutcome(true);
}
Level.prototype.lose = function() {
this.finishWithOutcome(false);
}
Level.prototype.finishWithOutcome = function(outcome) {
if(this.isFinished)
return;
this.isFinished = true;
this.pauseGameLoop();
this.player.stop();
this.outcomeListeners.forEach(listener => listener(outcome));
const finalMessage = this.getMessageForOutcome(outcome);
this.finalMessageListeners.forEach(listener => listener(finalMessage));
if(!outcome) {
const respawnInfo = this.generateRespawnInfo();
Object.freeze(respawnInfo);
this.respawnInfoListeners.forEach(listener => listener(respawnInfo));
}
}
Level.prototype.getMessageForOutcome = function(outcome) {
if(outcome)
return mathUtils.randomArrayElement(this.victoryMessages);
else return mathUtils.randomArrayElement(this.failureMessages);
} | Level | identifier_name |
level.js | 'use strict';
function Level(args) |
Level.prototype.draw = function() {
this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height);
this.gameplayObjects.forEach(o => o.draw(this.context));
this.player.draw(this.context);
}
Level.prototype.update = function(dt) {
this.player.update(dt);
}
Level.prototype.frame = function(dt) {
this.update(dt);
this.draw();
}
Level.prototype.startGameLoop = function() {
const gameLoopFrame = now => {
if(!this.isPaused) {
const dt = now - this.lastFrameTime;
this.frame(dt);
window.requestAnimationFrame(gameLoopFrame);
}
this.lastFrameTime = now;
}
this.isPaused = false;
this.lastFrameTime = performance.now();
window.requestAnimationFrame(gameLoopFrame);
}
Level.prototype.pauseGameLoop = function() {
this.isPaused = true;
}
Level.prototype.addOutcomeListener = function(listener) {
this.outcomeListeners.push(listener);
}
Level.prototype.addFinalMessageListener = function(listener) {
this.finalMessageListeners.push(listener);
}
Level.prototype.addRespawnInfoListener = function(listener) {
this.respawnInfoListeners.push(listener);
}
Level.prototype.generateRespawnInfo = function() {
return this.player.generateRespawnInfo();
}
Level.prototype.handleRespawnInfo = function(respawnInfo) {
this.player.handleRespawnInfo(respawnInfo);
}
Level.prototype.win = function() {
this.finishWithOutcome(true);
}
Level.prototype.lose = function() {
this.finishWithOutcome(false);
}
Level.prototype.finishWithOutcome = function(outcome) {
if(this.isFinished)
return;
this.isFinished = true;
this.pauseGameLoop();
this.player.stop();
this.outcomeListeners.forEach(listener => listener(outcome));
const finalMessage = this.getMessageForOutcome(outcome);
this.finalMessageListeners.forEach(listener => listener(finalMessage));
if(!outcome) {
const respawnInfo = this.generateRespawnInfo();
Object.freeze(respawnInfo);
this.respawnInfoListeners.forEach(listener => listener(respawnInfo));
}
}
Level.prototype.getMessageForOutcome = function(outcome) {
if(outcome)
return mathUtils.randomArrayElement(this.victoryMessages);
else return mathUtils.randomArrayElement(this.failureMessages);
} | {
if(!(this instanceof Level))
return new Level(args);
this.context = args.context;
this.player = args.player;
this.gameplayObjects = args.gameplayObjects;
this.outcomeListeners = [];
this.finalMessageListeners = [];
this.respawnInfoListeners = [];
this.victoryMessages = args.victoryMessages;
this.failureMessages = args.failureMessages;
this.isPaused = true;
this.isFinished = false;
this.handleRespawnInfo(args.respawnInfo);
this.player.setParentLevel(this);
this.gameplayObjects.forEach(o => o.beginObservingPlayer(this.player));
} | identifier_body |
init.ts | /// <reference path="application.ts" />
/// <reference path="pages/IndexPageController.ts" />
/// <reference path="pages/DetailsPageController.ts" />
module ft{
declare var Framework7: any;
interface Framework7View{
}
interface Framework7App{
addView(view:String, callback:Framework7ViewOptions):Framework7View
}
interface Framework7ViewOptions{
dynamicNavbar:boolean;
domCache:boolean;
}
export class Init{
private fw7App:Framework7App;
private mainView:Framework7View;
private fw7ViewOptions:Framework7ViewOptions;
private angApp:application;
constructor(){
this.configApp();
}
private | ():void {
// Initialize app
this.fw7App = new Framework7({
animateNavBackIcon: true
});
this.fw7ViewOptions = {
dynamicNavbar: true,
domCache: true
}
// Add view
this.mainView = this.fw7App.addView('.view-main', this.fw7ViewOptions);
// Init Angular
this.angApp = new application( 'ft', [] );
// Init controllers
this.angApp.addController( 'IndexPageController', ft.pages.IndexPageController);
this.angApp.addController( 'DetailsPageController', ft.pages.DetailsPageController);
}
}
// Everything starts here
new Init();
} | configApp | identifier_name |
init.ts | /// <reference path="application.ts" />
/// <reference path="pages/IndexPageController.ts" />
/// <reference path="pages/DetailsPageController.ts" />
module ft{
declare var Framework7: any;
interface Framework7View{
}
interface Framework7App{
addView(view:String, callback:Framework7ViewOptions):Framework7View
}
interface Framework7ViewOptions{
dynamicNavbar:boolean;
domCache:boolean;
}
export class Init{
private fw7App:Framework7App;
private mainView:Framework7View;
private fw7ViewOptions:Framework7ViewOptions;
private angApp:application;
constructor(){ | this.configApp();
}
private configApp():void {
// Initialize app
this.fw7App = new Framework7({
animateNavBackIcon: true
});
this.fw7ViewOptions = {
dynamicNavbar: true,
domCache: true
}
// Add view
this.mainView = this.fw7App.addView('.view-main', this.fw7ViewOptions);
// Init Angular
this.angApp = new application( 'ft', [] );
// Init controllers
this.angApp.addController( 'IndexPageController', ft.pages.IndexPageController);
this.angApp.addController( 'DetailsPageController', ft.pages.DetailsPageController);
}
}
// Everything starts here
new Init();
} | random_line_split | |
messages.py |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
|
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message_parts[0] != "piratebox":
return None
b64_content_part = message_parts[4]
content = base64.b64decode ( b64_content_part )
return content
def get_sendername (self):
return self.name
def get_message ( self ):
return self.decoded
def set_message ( self , decoded):
self.decoded = decoded
class shoutbox_message(message):
def __init__(self, name="generate" ):
message.__init__( self , name)
self.type="sb"
| if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
self.type="gc"
self.decoded="" | identifier_body |
messages.py | import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
|
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message_parts[0] != "piratebox":
return None
b64_content_part = message_parts[4]
content = base64.b64decode ( b64_content_part )
return content
def get_sendername (self):
return self.name
def get_message ( self ):
return self.decoded
def set_message ( self , decoded):
self.decoded = decoded
class shoutbox_message(message):
def __init__(self, name="generate" ):
message.__init__( self , name)
self.type="sb" | self.type="gc"
self.decoded="" | random_line_split |
messages.py |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
self.type="gc"
self.decoded=""
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def | ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message_parts[0] != "piratebox":
return None
b64_content_part = message_parts[4]
content = base64.b64decode ( b64_content_part )
return content
def get_sendername (self):
return self.name
def get_message ( self ):
return self.decoded
def set_message ( self , decoded):
self.decoded = decoded
class shoutbox_message(message):
def __init__(self, name="generate" ):
message.__init__( self , name)
self.type="sb"
| get | identifier_name |
messages.py |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
|
else:
self.name=name
self.type="gc"
self.decoded=""
def set ( self, content=" " ):
base64content = base64.b64encode ( content )
self.decoded="piratebox;"+ self.type + ";01;" + self.name + ";" + base64content
def get ( self ):
# TODO Split decoded part
message_parts = string.split ( self.decoded , ";" )
if message_parts[0] != "piratebox":
return None
b64_content_part = message_parts[4]
content = base64.b64decode ( b64_content_part )
return content
def get_sendername (self):
return self.name
def get_message ( self ):
return self.decoded
def set_message ( self , decoded):
self.decoded = decoded
class shoutbox_message(message):
def __init__(self, name="generate" ):
message.__init__( self , name)
self.type="sb"
| self.name=socket.gethostname() | conditional_block |
addImgcom.js | if (typeof exports === 'undefined') {
exports = {}; | }
exports.config = {
"name": "addImgcom",
"desc": "新增图片组件",
// 线上地址
"url": "http://xxx/addImgcom",
// 日常地址
"urlDaily": "http://xxxx/addImgcom",
// 预发地址
"urlPrepub": "http://example.com/addImgcom",
// 支持的 Method 集合
"method": ['POST']
};
exports.request ={
pageId:'1332edf', //关联 pageid
imgcom:ImgComSchema //db的imgcom表;
} ;
exports.response = {
"success": true, // 标记成功
"model": ImgComSchema
};
exports.responseError = {
"success": false, // 标记失败
"model": {
"error": "Error message"
}
}; | random_line_split | |
addImgcom.js | if (typeof exports === 'undefined') |
exports.config = {
"name": "addImgcom",
"desc": "新增图片组件",
// 线上地址
"url": "http://xxx/addImgcom",
// 日常地址
"urlDaily": "http://xxxx/addImgcom",
// 预发地址
"urlPrepub": "http://example.com/addImgcom",
// 支持的 Method 集合
"method": ['POST']
};
exports.request ={
pageId:'1332edf', //关联 pageid
imgcom:ImgComSchema //db的imgcom表;
} ;
exports.response = {
"success": true, // 标记成功
"model": ImgComSchema
};
exports.responseError = {
"success": false, // 标记失败
"model": {
"error": "Error message"
}
}; | {
exports = {};
} | conditional_block |
lib.rs | //! Boron is a small and expressive web framework for Rust which aims to give a robust foundation
//! for web applications and APIs.
//!
//! ## Installation
//! Add the following line to your `[dependecies]` section in `Cargo.toml`:
//!
//! ```toml
//! boron = "0.0.2"
//! ```
//!
//! ## Your first app
//!
//! ```rust,no_run
//! extern crate boron;
//!
//! use boron::server::Boron;
//! use boron::request::Request;
//! use boron::response::Response;
//! use boron::router::HttpMethods;
//!
//! fn main() {
//! let mut app = Boron::new();
//! app.get("/", |req: &Request, res: Response| {
//! res.send(b"Hello World! I am Boron.")
//! });
//! app.listen("localhost:3000");
//! }
//! ```
extern crate hyper;
extern crate url; | pub mod server;
pub mod response;
pub mod request;
pub mod middleware;
pub mod router;
mod matcher; | extern crate regex;
extern crate typemap;
| random_line_split |
fun-call-variants.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn ho<F>(f: F) -> isize where F: FnOnce(isize) -> isize { let n: isize = f(3); return n; }
fn direct(x: isize) -> isize { return x + 1; }
| let b: isize = ho(direct); // indirect unbound
assert_eq!(a, b);
} | pub fn main() {
let a: isize = direct(3); // direct | random_line_split |
fun-call-variants.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn ho<F>(f: F) -> isize where F: FnOnce(isize) -> isize { let n: isize = f(3); return n; }
fn direct(x: isize) -> isize |
pub fn main() {
let a: isize = direct(3); // direct
let b: isize = ho(direct); // indirect unbound
assert_eq!(a, b);
}
| { return x + 1; } | identifier_body |
fun-call-variants.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn | <F>(f: F) -> isize where F: FnOnce(isize) -> isize { let n: isize = f(3); return n; }
fn direct(x: isize) -> isize { return x + 1; }
pub fn main() {
let a: isize = direct(3); // direct
let b: isize = ho(direct); // indirect unbound
assert_eq!(a, b);
}
| ho | identifier_name |
imagescale-c.py | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version. It is provided for
# educational purposes and is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
import argparse
import collections
import math
import multiprocessing
import os
import sys
import Image
import Qtrac
Result = collections.namedtuple("Result", "todo copied scaled name")
def main():
size, smooth, source, target, concurrency = handle_commandline()
Qtrac.report("starting...")
canceled = False
try:
scale(size, smooth, source, target, concurrency)
except KeyboardInterrupt:
Qtrac.report("canceling...")
canceled = True
summarize(concurrency, canceled)
def handle_commandline():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--concurrency", type=int,
default=multiprocessing.cpu_count(),
help="specify the concurrency (for debugging and "
"timing) [default: %(default)d]")
parser.add_argument("-s", "--size", default=400, type=int,
help="make a scaled image that fits the given dimension "
"[default: %(default)d]")
parser.add_argument("-S", "--smooth", action="store_true",
help="use smooth scaling (slow but good for text)")
parser.add_argument("source",
help="the directory containing the original .xpm images")
parser.add_argument("target",
help="the directory for the scaled .xpm images")
args = parser.parse_args()
source = os.path.abspath(args.source)
target = os.path.abspath(args.target)
if source == target:
args.error("source and target must be different")
if not os.path.exists(args.target):
os.makedirs(target)
return args.size, args.smooth, source, target, args.concurrency
def scale(size, smooth, source, target, concurrency):
pipeline = create_pipeline(size, smooth, concurrency)
for i, (sourceImage, targetImage) in enumerate(
get_jobs(source, target)):
pipeline.send((sourceImage, targetImage, i % concurrency))
def create_pipeline(size, smooth, concurrency):
pipeline = None
sink = results()
for who in range(concurrency):
pipeline = scaler(pipeline, sink, size, smooth, who)
return pipeline
def get_jobs(source, target):
for name in os.listdir(source):
yield os.path.join(source, name), os.path.join(target, name)
@Qtrac.coroutine
def scaler(receiver, sink, size, smooth, me):
while True:
sourceImage, targetImage, who = (yield)
if who == me:
try:
result = scale_one(size, smooth, sourceImage, targetImage)
sink.send(result)
except Image.Error as err:
Qtrac.report(str(err), True)
elif receiver is not None:
receiver.send((sourceImage, targetImage, who))
@Qtrac.coroutine
def results():
while True:
result = (yield)
results.todo += result.todo
results.copied += result.copied
results.scaled += result.scaled
Qtrac.report("{} {}".format("copied" if result.copied else "scaled",
os.path.basename(result.name)))
results.todo = results.copied = results.scaled = 0
def scale_one(size, smooth, sourceImage, targetImage):
oldImage = Image.from_file(sourceImage)
if oldImage.width <= size and oldImage.height <= size:
oldImage.save(targetImage)
return Result(1, 1, 0, targetImage)
else:
i |
def summarize(concurrency, canceled):
message = "copied {} scaled {} ".format(results.copied, results.scaled)
difference = results.todo - (results.copied + results.scaled)
if difference:
message += "skipped {} ".format(difference)
message += "using {} coroutines".format(concurrency)
if canceled:
message += " [canceled]"
Qtrac.report(message)
print()
if __name__ == "__main__":
main()
| f smooth:
scale = min(size / oldImage.width, size / oldImage.height)
newImage = oldImage.scale(scale)
else:
stride = int(math.ceil(max(oldImage.width / size,
oldImage.height / size)))
newImage = oldImage.subsample(stride)
newImage.save(targetImage)
return Result(1, 0, 1, targetImage)
| conditional_block |
imagescale-c.py | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version. It is provided for
# educational purposes and is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
import argparse
import collections
import math
import multiprocessing
import os
import sys
import Image
import Qtrac
Result = collections.namedtuple("Result", "todo copied scaled name")
def main():
size, smooth, source, target, concurrency = handle_commandline()
Qtrac.report("starting...")
canceled = False
try:
scale(size, smooth, source, target, concurrency)
except KeyboardInterrupt:
Qtrac.report("canceling...")
canceled = True
summarize(concurrency, canceled)
def handle_commandline():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--concurrency", type=int,
default=multiprocessing.cpu_count(),
help="specify the concurrency (for debugging and "
"timing) [default: %(default)d]")
parser.add_argument("-s", "--size", default=400, type=int,
help="make a scaled image that fits the given dimension "
"[default: %(default)d]")
parser.add_argument("-S", "--smooth", action="store_true",
help="use smooth scaling (slow but good for text)")
parser.add_argument("source",
help="the directory containing the original .xpm images")
parser.add_argument("target",
help="the directory for the scaled .xpm images")
args = parser.parse_args()
source = os.path.abspath(args.source)
target = os.path.abspath(args.target)
if source == target:
args.error("source and target must be different")
if not os.path.exists(args.target):
os.makedirs(target)
return args.size, args.smooth, source, target, args.concurrency
def scale(size, smooth, source, target, concurrency):
pipeline = create_pipeline(size, smooth, concurrency)
for i, (sourceImage, targetImage) in enumerate(
get_jobs(source, target)):
pipeline.send((sourceImage, targetImage, i % concurrency))
def create_pipeline(size, smooth, concurrency):
p |
def get_jobs(source, target):
for name in os.listdir(source):
yield os.path.join(source, name), os.path.join(target, name)
@Qtrac.coroutine
def scaler(receiver, sink, size, smooth, me):
while True:
sourceImage, targetImage, who = (yield)
if who == me:
try:
result = scale_one(size, smooth, sourceImage, targetImage)
sink.send(result)
except Image.Error as err:
Qtrac.report(str(err), True)
elif receiver is not None:
receiver.send((sourceImage, targetImage, who))
@Qtrac.coroutine
def results():
while True:
result = (yield)
results.todo += result.todo
results.copied += result.copied
results.scaled += result.scaled
Qtrac.report("{} {}".format("copied" if result.copied else "scaled",
os.path.basename(result.name)))
results.todo = results.copied = results.scaled = 0
def scale_one(size, smooth, sourceImage, targetImage):
oldImage = Image.from_file(sourceImage)
if oldImage.width <= size and oldImage.height <= size:
oldImage.save(targetImage)
return Result(1, 1, 0, targetImage)
else:
if smooth:
scale = min(size / oldImage.width, size / oldImage.height)
newImage = oldImage.scale(scale)
else:
stride = int(math.ceil(max(oldImage.width / size,
oldImage.height / size)))
newImage = oldImage.subsample(stride)
newImage.save(targetImage)
return Result(1, 0, 1, targetImage)
def summarize(concurrency, canceled):
message = "copied {} scaled {} ".format(results.copied, results.scaled)
difference = results.todo - (results.copied + results.scaled)
if difference:
message += "skipped {} ".format(difference)
message += "using {} coroutines".format(concurrency)
if canceled:
message += " [canceled]"
Qtrac.report(message)
print()
if __name__ == "__main__":
main()
| ipeline = None
sink = results()
for who in range(concurrency):
pipeline = scaler(pipeline, sink, size, smooth, who)
return pipeline
| identifier_body |
imagescale-c.py | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version. It is provided for
# educational purposes and is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
import argparse
import collections
import math
import multiprocessing
import os
import sys
import Image
import Qtrac
Result = collections.namedtuple("Result", "todo copied scaled name")
def main():
size, smooth, source, target, concurrency = handle_commandline()
Qtrac.report("starting...")
canceled = False
try:
scale(size, smooth, source, target, concurrency)
except KeyboardInterrupt:
Qtrac.report("canceling...")
canceled = True
summarize(concurrency, canceled)
def handle_commandline():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--concurrency", type=int,
default=multiprocessing.cpu_count(),
help="specify the concurrency (for debugging and "
"timing) [default: %(default)d]")
parser.add_argument("-s", "--size", default=400, type=int,
help="make a scaled image that fits the given dimension "
"[default: %(default)d]")
parser.add_argument("-S", "--smooth", action="store_true",
help="use smooth scaling (slow but good for text)")
parser.add_argument("source",
help="the directory containing the original .xpm images")
parser.add_argument("target",
help="the directory for the scaled .xpm images")
args = parser.parse_args()
source = os.path.abspath(args.source)
target = os.path.abspath(args.target)
if source == target:
args.error("source and target must be different")
if not os.path.exists(args.target):
os.makedirs(target)
return args.size, args.smooth, source, target, args.concurrency
def scale(size, smooth, source, target, concurrency):
pipeline = create_pipeline(size, smooth, concurrency)
for i, (sourceImage, targetImage) in enumerate(
get_jobs(source, target)):
pipeline.send((sourceImage, targetImage, i % concurrency))
def create_pipeline(size, smooth, concurrency):
pipeline = None
sink = results()
for who in range(concurrency):
pipeline = scaler(pipeline, sink, size, smooth, who)
return pipeline
def get_jobs(source, target):
for name in os.listdir(source):
yield os.path.join(source, name), os.path.join(target, name)
@Qtrac.coroutine
def scaler(receiver, sink, size, smooth, me):
while True:
sourceImage, targetImage, who = (yield)
if who == me:
try:
result = scale_one(size, smooth, sourceImage, targetImage)
sink.send(result)
except Image.Error as err:
Qtrac.report(str(err), True)
elif receiver is not None:
receiver.send((sourceImage, targetImage, who))
@Qtrac.coroutine
def r | ):
while True:
result = (yield)
results.todo += result.todo
results.copied += result.copied
results.scaled += result.scaled
Qtrac.report("{} {}".format("copied" if result.copied else "scaled",
os.path.basename(result.name)))
results.todo = results.copied = results.scaled = 0
def scale_one(size, smooth, sourceImage, targetImage):
oldImage = Image.from_file(sourceImage)
if oldImage.width <= size and oldImage.height <= size:
oldImage.save(targetImage)
return Result(1, 1, 0, targetImage)
else:
if smooth:
scale = min(size / oldImage.width, size / oldImage.height)
newImage = oldImage.scale(scale)
else:
stride = int(math.ceil(max(oldImage.width / size,
oldImage.height / size)))
newImage = oldImage.subsample(stride)
newImage.save(targetImage)
return Result(1, 0, 1, targetImage)
def summarize(concurrency, canceled):
message = "copied {} scaled {} ".format(results.copied, results.scaled)
difference = results.todo - (results.copied + results.scaled)
if difference:
message += "skipped {} ".format(difference)
message += "using {} coroutines".format(concurrency)
if canceled:
message += " [canceled]"
Qtrac.report(message)
print()
if __name__ == "__main__":
main()
| esults( | identifier_name |
imagescale-c.py | #!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version. It is provided for
# educational purposes and is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
import argparse
import collections
import math
import multiprocessing
import os
import sys
import Image
import Qtrac
Result = collections.namedtuple("Result", "todo copied scaled name")
def main():
size, smooth, source, target, concurrency = handle_commandline()
Qtrac.report("starting...")
canceled = False
try:
scale(size, smooth, source, target, concurrency)
except KeyboardInterrupt:
Qtrac.report("canceling...")
canceled = True
summarize(concurrency, canceled)
def handle_commandline():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--concurrency", type=int,
| "timing) [default: %(default)d]")
parser.add_argument("-s", "--size", default=400, type=int,
help="make a scaled image that fits the given dimension "
"[default: %(default)d]")
parser.add_argument("-S", "--smooth", action="store_true",
help="use smooth scaling (slow but good for text)")
parser.add_argument("source",
help="the directory containing the original .xpm images")
parser.add_argument("target",
help="the directory for the scaled .xpm images")
args = parser.parse_args()
source = os.path.abspath(args.source)
target = os.path.abspath(args.target)
if source == target:
args.error("source and target must be different")
if not os.path.exists(args.target):
os.makedirs(target)
return args.size, args.smooth, source, target, args.concurrency
def scale(size, smooth, source, target, concurrency):
pipeline = create_pipeline(size, smooth, concurrency)
for i, (sourceImage, targetImage) in enumerate(
get_jobs(source, target)):
pipeline.send((sourceImage, targetImage, i % concurrency))
def create_pipeline(size, smooth, concurrency):
pipeline = None
sink = results()
for who in range(concurrency):
pipeline = scaler(pipeline, sink, size, smooth, who)
return pipeline
def get_jobs(source, target):
for name in os.listdir(source):
yield os.path.join(source, name), os.path.join(target, name)
@Qtrac.coroutine
def scaler(receiver, sink, size, smooth, me):
while True:
sourceImage, targetImage, who = (yield)
if who == me:
try:
result = scale_one(size, smooth, sourceImage, targetImage)
sink.send(result)
except Image.Error as err:
Qtrac.report(str(err), True)
elif receiver is not None:
receiver.send((sourceImage, targetImage, who))
@Qtrac.coroutine
def results():
while True:
result = (yield)
results.todo += result.todo
results.copied += result.copied
results.scaled += result.scaled
Qtrac.report("{} {}".format("copied" if result.copied else "scaled",
os.path.basename(result.name)))
results.todo = results.copied = results.scaled = 0
def scale_one(size, smooth, sourceImage, targetImage):
oldImage = Image.from_file(sourceImage)
if oldImage.width <= size and oldImage.height <= size:
oldImage.save(targetImage)
return Result(1, 1, 0, targetImage)
else:
if smooth:
scale = min(size / oldImage.width, size / oldImage.height)
newImage = oldImage.scale(scale)
else:
stride = int(math.ceil(max(oldImage.width / size,
oldImage.height / size)))
newImage = oldImage.subsample(stride)
newImage.save(targetImage)
return Result(1, 0, 1, targetImage)
def summarize(concurrency, canceled):
message = "copied {} scaled {} ".format(results.copied, results.scaled)
difference = results.todo - (results.copied + results.scaled)
if difference:
message += "skipped {} ".format(difference)
message += "using {} coroutines".format(concurrency)
if canceled:
message += " [canceled]"
Qtrac.report(message)
print()
if __name__ == "__main__":
main() | default=multiprocessing.cpu_count(),
help="specify the concurrency (for debugging and "
| random_line_split |
S11.13.2_A4.7_T1.4.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The production x >>= y is the same as x = x >> y
es5id: 11.13.2_A4.7_T1.4
description: Type(x) and Type(y) vary between Null and Undefined
---*/
//CHECK#1
x = null;
x >>= undefined;
if (x !== 0) {
$ERROR('#1: x = null; x >>= undefined; x === 0. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x >>= null;
if (x !== 0) |
//CHECK#3
x = undefined;
x >>= undefined;
if (x !== 0) {
$ERROR('#3: x = undefined; x >>= undefined; x === 0. Actual: ' + (x));
}
//CHECK#4
x = null;
x >>= null;
if (x !== 0) {
$ERROR('#4: x = null; x >>= null; x === 0. Actual: ' + (x));
}
| {
$ERROR('#2: x = undefined; x >>= null; x === 0. Actual: ' + (x));
} | conditional_block |
S11.13.2_A4.7_T1.4.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The production x >>= y is the same as x = x >> y
es5id: 11.13.2_A4.7_T1.4
description: Type(x) and Type(y) vary between Null and Undefined
---*/
//CHECK#1
x = null;
x >>= undefined;
if (x !== 0) {
$ERROR('#1: x = null; x >>= undefined; x === 0. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x >>= null;
if (x !== 0) {
$ERROR('#2: x = undefined; x >>= null; x === 0. Actual: ' + (x));
}
//CHECK#3
x = undefined;
x >>= undefined;
if (x !== 0) {
$ERROR('#3: x = undefined; x >>= undefined; x === 0. Actual: ' + (x)); | x = null;
x >>= null;
if (x !== 0) {
$ERROR('#4: x = null; x >>= null; x === 0. Actual: ' + (x));
} | }
//CHECK#4 | random_line_split |
P13nSelectionItem.js | /*
* ! ${copyright}
*/
// Provides control sap.m.P13nSelectionItem.
sap.ui.define([
'jquery.sap.global', './library', 'sap/ui/core/Item'
], function(jQuery, library, Item) {
"use strict";
/**
* Constructor for a new P13nSelectionItem.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] initial settings for the new control
* @class Type for <code>selectionItems</code> aggregation in <code>P13nSelectionPanel</code> control.
* @extends sap.ui.core.Item
* @version ${version}
* @constructor
* @author SAP SE
* @private
* @since 1.46.0
* @alias sap.m.P13nSelectionItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var P13nSelectionItem = Item.extend("sap.m.P13nSelectionItem", /** @lends sap.m.P13nSelectionItem.prototype */
{
metadata: {
library: "sap.m",
properties: {
/**
* Defines the unique table column key.
*/
columnKey: {
type: "string",
defaultValue: undefined
},
/**
* Defines the index of a table column.
*/
index: {
type: "int",
defaultValue: -1
},
/**
* Defines whether the <code>P13nSelectionItem</code> is selected.
*/
selected: {
type: "boolean", | }
}
}
});
return P13nSelectionItem;
}, /* bExport= */true); | defaultValue: false | random_line_split |
BalancedBinaryTree_rec.py | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
| """
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
isbalanced, h = self.isBalancedandHeight(root)
return isbalanced
def isBalancedandHeight(self, root):
if root is None:
return True, 0
l, r = root.left, root.right
l_balanced, l_h = self.isBalancedandHeight(l)
if not l_balanced:
return False, 0
r_balanced, r_h = self.isBalancedandHeight(r)
if not r_balanced:
return False, 0
if abs(l_h - r_h) < 2:
return True, max(l_h, r_h) + 1
return False, 0 | identifier_body | |
BalancedBinaryTree_rec.py | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
isbalanced, h = self.isBalancedandHeight(root)
return isbalanced
def isBalancedandHeight(self, root):
if root is None:
|
l, r = root.left, root.right
l_balanced, l_h = self.isBalancedandHeight(l)
if not l_balanced:
return False, 0
r_balanced, r_h = self.isBalancedandHeight(r)
if not r_balanced:
return False, 0
if abs(l_h - r_h) < 2:
return True, max(l_h, r_h) + 1
return False, 0
| return True, 0 | conditional_block |
BalancedBinaryTree_rec.py | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class | :
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
isbalanced, h = self.isBalancedandHeight(root)
return isbalanced
def isBalancedandHeight(self, root):
if root is None:
return True, 0
l, r = root.left, root.right
l_balanced, l_h = self.isBalancedandHeight(l)
if not l_balanced:
return False, 0
r_balanced, r_h = self.isBalancedandHeight(r)
if not r_balanced:
return False, 0
if abs(l_h - r_h) < 2:
return True, max(l_h, r_h) + 1
return False, 0
| Solution | identifier_name |
BalancedBinaryTree_rec.py | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
""" | class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
isbalanced, h = self.isBalancedandHeight(root)
return isbalanced
def isBalancedandHeight(self, root):
if root is None:
return True, 0
l, r = root.left, root.right
l_balanced, l_h = self.isBalancedandHeight(l)
if not l_balanced:
return False, 0
r_balanced, r_h = self.isBalancedandHeight(r)
if not r_balanced:
return False, 0
if abs(l_h - r_h) < 2:
return True, max(l_h, r_h) + 1
return False, 0 | random_line_split | |
__init__.py | """Support for MQTT lights."""
import logging
import voluptuous as vol
from homeassistant.components import light
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from homeassistant.components.mqtt.discovery import (
MQTT_DISCOVERY_NEW,
clear_discovery_hash,
)
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from .. import DOMAIN, PLATFORMS
from .schema import CONF_SCHEMA, MQTT_LIGHT_SCHEMA_SCHEMA
from .schema_basic import PLATFORM_SCHEMA_BASIC, async_setup_entity_basic
from .schema_json import PLATFORM_SCHEMA_JSON, async_setup_entity_json
from .schema_template import PLATFORM_SCHEMA_TEMPLATE, async_setup_entity_template
_LOGGER = logging.getLogger(__name__)
def validate_mqtt_light(value):
|
PLATFORM_SCHEMA = vol.All(
MQTT_LIGHT_SCHEMA_SCHEMA.extend({}, extra=vol.ALLOW_EXTRA), validate_mqtt_light
)
async def async_setup_platform(
hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None
):
"""Set up MQTT light through configuration.yaml."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
await _async_setup_entity(hass, config, async_add_entities)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up MQTT light dynamically through MQTT discovery."""
async def async_discover(discovery_payload):
"""Discover and add a MQTT light."""
discovery_data = discovery_payload.discovery_data
try:
config = PLATFORM_SCHEMA(discovery_payload)
await _async_setup_entity(
hass, config, async_add_entities, config_entry, discovery_data
)
except Exception:
clear_discovery_hash(hass, discovery_data[ATTR_DISCOVERY_HASH])
raise
async_dispatcher_connect(
hass, MQTT_DISCOVERY_NEW.format(light.DOMAIN, "mqtt"), async_discover
)
async def _async_setup_entity(
hass, config, async_add_entities, config_entry=None, discovery_data=None
):
"""Set up a MQTT Light."""
setup_entity = {
"basic": async_setup_entity_basic,
"json": async_setup_entity_json,
"template": async_setup_entity_template,
}
await setup_entity[config[CONF_SCHEMA]](
hass, config, async_add_entities, config_entry, discovery_data
)
| """Validate MQTT light schema."""
schemas = {
"basic": PLATFORM_SCHEMA_BASIC,
"json": PLATFORM_SCHEMA_JSON,
"template": PLATFORM_SCHEMA_TEMPLATE,
}
return schemas[value[CONF_SCHEMA]](value) | identifier_body |
__init__.py | """Support for MQTT lights."""
import logging
import voluptuous as vol
from homeassistant.components import light
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from homeassistant.components.mqtt.discovery import (
MQTT_DISCOVERY_NEW,
clear_discovery_hash,
)
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from .. import DOMAIN, PLATFORMS
from .schema import CONF_SCHEMA, MQTT_LIGHT_SCHEMA_SCHEMA
from .schema_basic import PLATFORM_SCHEMA_BASIC, async_setup_entity_basic
from .schema_json import PLATFORM_SCHEMA_JSON, async_setup_entity_json
from .schema_template import PLATFORM_SCHEMA_TEMPLATE, async_setup_entity_template
_LOGGER = logging.getLogger(__name__)
def validate_mqtt_light(value):
"""Validate MQTT light schema."""
schemas = {
"basic": PLATFORM_SCHEMA_BASIC,
"json": PLATFORM_SCHEMA_JSON,
"template": PLATFORM_SCHEMA_TEMPLATE,
}
return schemas[value[CONF_SCHEMA]](value)
PLATFORM_SCHEMA = vol.All(
MQTT_LIGHT_SCHEMA_SCHEMA.extend({}, extra=vol.ALLOW_EXTRA), validate_mqtt_light
)
async def async_setup_platform(
hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None
):
"""Set up MQTT light through configuration.yaml."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
await _async_setup_entity(hass, config, async_add_entities)
async def | (hass, config_entry, async_add_entities):
"""Set up MQTT light dynamically through MQTT discovery."""
async def async_discover(discovery_payload):
"""Discover and add a MQTT light."""
discovery_data = discovery_payload.discovery_data
try:
config = PLATFORM_SCHEMA(discovery_payload)
await _async_setup_entity(
hass, config, async_add_entities, config_entry, discovery_data
)
except Exception:
clear_discovery_hash(hass, discovery_data[ATTR_DISCOVERY_HASH])
raise
async_dispatcher_connect(
hass, MQTT_DISCOVERY_NEW.format(light.DOMAIN, "mqtt"), async_discover
)
async def _async_setup_entity(
hass, config, async_add_entities, config_entry=None, discovery_data=None
):
"""Set up a MQTT Light."""
setup_entity = {
"basic": async_setup_entity_basic,
"json": async_setup_entity_json,
"template": async_setup_entity_template,
}
await setup_entity[config[CONF_SCHEMA]](
hass, config, async_add_entities, config_entry, discovery_data
)
| async_setup_entry | identifier_name |
__init__.py | """Support for MQTT lights."""
import logging
import voluptuous as vol
from homeassistant.components import light
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from homeassistant.components.mqtt.discovery import (
MQTT_DISCOVERY_NEW,
clear_discovery_hash,
)
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from .. import DOMAIN, PLATFORMS
from .schema import CONF_SCHEMA, MQTT_LIGHT_SCHEMA_SCHEMA
from .schema_basic import PLATFORM_SCHEMA_BASIC, async_setup_entity_basic
from .schema_json import PLATFORM_SCHEMA_JSON, async_setup_entity_json
from .schema_template import PLATFORM_SCHEMA_TEMPLATE, async_setup_entity_template
_LOGGER = logging.getLogger(__name__)
def validate_mqtt_light(value):
"""Validate MQTT light schema."""
schemas = {
"basic": PLATFORM_SCHEMA_BASIC,
"json": PLATFORM_SCHEMA_JSON,
"template": PLATFORM_SCHEMA_TEMPLATE,
}
return schemas[value[CONF_SCHEMA]](value)
PLATFORM_SCHEMA = vol.All(
MQTT_LIGHT_SCHEMA_SCHEMA.extend({}, extra=vol.ALLOW_EXTRA), validate_mqtt_light
)
async def async_setup_platform(
hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None | await _async_setup_entity(hass, config, async_add_entities)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up MQTT light dynamically through MQTT discovery."""
async def async_discover(discovery_payload):
"""Discover and add a MQTT light."""
discovery_data = discovery_payload.discovery_data
try:
config = PLATFORM_SCHEMA(discovery_payload)
await _async_setup_entity(
hass, config, async_add_entities, config_entry, discovery_data
)
except Exception:
clear_discovery_hash(hass, discovery_data[ATTR_DISCOVERY_HASH])
raise
async_dispatcher_connect(
hass, MQTT_DISCOVERY_NEW.format(light.DOMAIN, "mqtt"), async_discover
)
async def _async_setup_entity(
hass, config, async_add_entities, config_entry=None, discovery_data=None
):
"""Set up a MQTT Light."""
setup_entity = {
"basic": async_setup_entity_basic,
"json": async_setup_entity_json,
"template": async_setup_entity_template,
}
await setup_entity[config[CONF_SCHEMA]](
hass, config, async_add_entities, config_entry, discovery_data
) | ):
"""Set up MQTT light through configuration.yaml."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS) | random_line_split |
nodes.py | import re
import base
import sam.models.nodes
from sam import errors
from sam import common
# This class is for getting the child nodes of all nodes in a node list, for the map
class Nodes(base.headless_post):
"""
The expected GET data includes:
'address': comma-seperated list of dotted-decimal IP addresses.
Each address is only as long as the subnet,
so 12.34.0.0/16 would be written as 12.34
A request for 1.2.3.0/24, 192.168.0.0/16, and 21.0.0.0/8
would be "1.2.3,192.168,21"
:return: A JSON-encoded dictionary where
the keys are the supplied addresses (or _ if no address) and
the values are a list of child nodes.
POST Expects a query string including:
node: ip address
like "189.179.4.0/24"
or "189.179" ( == 189.179.0.0/16)
or "189.2.3/8" ( == 189.0.0.0/8)
alias: (optional) new alias string for the node
tags: (optional) comma separated string of tags to associate with this node
env: (optional) string, this host's environment category
:return: | base.HeadlessPost.__init__(self)
self.flatmode_tolerance = 256
self.nodesModel = sam.models.nodes.Nodes(common.db, self.page.user.viewing)
def check_flat_tolerance(self):
endpoints = self.nodesModel.get_all_endpoints()
count = len(endpoints)
return count <= self.flatmode_tolerance
def decode_get_request(self, data):
addresses = []
address_str = data.get('address')
if address_str:
addresses = address_str.split(',')
addresses = filter(lambda x: bool(x), addresses)
flat = data.get('flat', 'false').lower() == 'true'
if 'ds' in data:
ds_match = re.search('(\d+)', data['ds'])
if ds_match:
ds = int(ds_match.group())
else:
raise errors.MalformedRequest("Could not read data source ('ds')")
else:
raise errors.RequiredKey('data source', 'ds')
return {'addresses': addresses, 'flat': flat, 'ds': ds}
def perform_get_command(self, request):
self.page.require_group('read')
if request['flat']:
if self.check_flat_tolerance():
response = {'flat': self.nodesModel.get_flat_nodes(request['ds'])}
else:
response = {'error': 'Flat mode is not supported once a graph has exceeded {} hosts.'.format(self.flatmode_tolerance)}
elif len(request['addresses']) == 0:
response = {'_': self.nodesModel.get_root_nodes()}
else:
response = {address: self.nodesModel.get_children(address) for address in request['addresses']}
return response
def encode_get_response(self, response):
return response
def decode_post_request(self, data):
node = data.get('node')
if not node:
raise errors.RequiredKey('node', 'node')
alias = data.get('alias')
tags = data.get('tags')
env = data.get('env')
request = {'node': node}
if alias is not None:
request['alias'] = alias
if tags is not None:
request['tags'] = tags
if env is not None:
request['env'] = env
return request
def perform_post_command(self, request):
self.page.require_group('write')
node = request.pop('node')
for key, value in request.iteritems():
if key == 'alias':
self.nodesModel.set_alias(node, value)
elif key == 'tags':
tags = filter(lambda x: bool(x), value.split(','))
self.nodesModel.set_tags(node, tags)
elif key == 'env':
if value:
self.nodesModel.set_env(node, value)
else:
self.nodesModel.set_env(node, None)
else:
print("Error in nodeinfo, unrecognized assignment {0} = {1}".format(key, value))
return 0, "Success"
def encode_post_response(self, response):
return {'code': response[0], 'message': response[1]} |
"""
def __init__(self): | random_line_split |
nodes.py | import re
import base
import sam.models.nodes
from sam import errors
from sam import common
# This class is for getting the child nodes of all nodes in a node list, for the map
class Nodes(base.headless_post):
"""
The expected GET data includes:
'address': comma-seperated list of dotted-decimal IP addresses.
Each address is only as long as the subnet,
so 12.34.0.0/16 would be written as 12.34
A request for 1.2.3.0/24, 192.168.0.0/16, and 21.0.0.0/8
would be "1.2.3,192.168,21"
:return: A JSON-encoded dictionary where
the keys are the supplied addresses (or _ if no address) and
the values are a list of child nodes.
POST Expects a query string including:
node: ip address
like "189.179.4.0/24"
or "189.179" ( == 189.179.0.0/16)
or "189.2.3/8" ( == 189.0.0.0/8)
alias: (optional) new alias string for the node
tags: (optional) comma separated string of tags to associate with this node
env: (optional) string, this host's environment category
:return:
"""
def __init__(self):
base.HeadlessPost.__init__(self)
self.flatmode_tolerance = 256
self.nodesModel = sam.models.nodes.Nodes(common.db, self.page.user.viewing)
def check_flat_tolerance(self):
endpoints = self.nodesModel.get_all_endpoints()
count = len(endpoints)
return count <= self.flatmode_tolerance
def decode_get_request(self, data):
addresses = []
address_str = data.get('address')
if address_str:
addresses = address_str.split(',')
addresses = filter(lambda x: bool(x), addresses)
flat = data.get('flat', 'false').lower() == 'true'
if 'ds' in data:
ds_match = re.search('(\d+)', data['ds'])
if ds_match:
ds = int(ds_match.group())
else:
raise errors.MalformedRequest("Could not read data source ('ds')")
else:
raise errors.RequiredKey('data source', 'ds')
return {'addresses': addresses, 'flat': flat, 'ds': ds}
def perform_get_command(self, request):
self.page.require_group('read')
if request['flat']:
if self.check_flat_tolerance():
response = {'flat': self.nodesModel.get_flat_nodes(request['ds'])}
else:
response = {'error': 'Flat mode is not supported once a graph has exceeded {} hosts.'.format(self.flatmode_tolerance)}
elif len(request['addresses']) == 0:
response = {'_': self.nodesModel.get_root_nodes()}
else:
response = {address: self.nodesModel.get_children(address) for address in request['addresses']}
return response
def encode_get_response(self, response):
|
def decode_post_request(self, data):
node = data.get('node')
if not node:
raise errors.RequiredKey('node', 'node')
alias = data.get('alias')
tags = data.get('tags')
env = data.get('env')
request = {'node': node}
if alias is not None:
request['alias'] = alias
if tags is not None:
request['tags'] = tags
if env is not None:
request['env'] = env
return request
def perform_post_command(self, request):
self.page.require_group('write')
node = request.pop('node')
for key, value in request.iteritems():
if key == 'alias':
self.nodesModel.set_alias(node, value)
elif key == 'tags':
tags = filter(lambda x: bool(x), value.split(','))
self.nodesModel.set_tags(node, tags)
elif key == 'env':
if value:
self.nodesModel.set_env(node, value)
else:
self.nodesModel.set_env(node, None)
else:
print("Error in nodeinfo, unrecognized assignment {0} = {1}".format(key, value))
return 0, "Success"
def encode_post_response(self, response):
return {'code': response[0], 'message': response[1]} | return response | identifier_body |
nodes.py | import re
import base
import sam.models.nodes
from sam import errors
from sam import common
# This class is for getting the child nodes of all nodes in a node list, for the map
class Nodes(base.headless_post):
"""
The expected GET data includes:
'address': comma-seperated list of dotted-decimal IP addresses.
Each address is only as long as the subnet,
so 12.34.0.0/16 would be written as 12.34
A request for 1.2.3.0/24, 192.168.0.0/16, and 21.0.0.0/8
would be "1.2.3,192.168,21"
:return: A JSON-encoded dictionary where
the keys are the supplied addresses (or _ if no address) and
the values are a list of child nodes.
POST Expects a query string including:
node: ip address
like "189.179.4.0/24"
or "189.179" ( == 189.179.0.0/16)
or "189.2.3/8" ( == 189.0.0.0/8)
alias: (optional) new alias string for the node
tags: (optional) comma separated string of tags to associate with this node
env: (optional) string, this host's environment category
:return:
"""
def | (self):
base.HeadlessPost.__init__(self)
self.flatmode_tolerance = 256
self.nodesModel = sam.models.nodes.Nodes(common.db, self.page.user.viewing)
def check_flat_tolerance(self):
endpoints = self.nodesModel.get_all_endpoints()
count = len(endpoints)
return count <= self.flatmode_tolerance
def decode_get_request(self, data):
addresses = []
address_str = data.get('address')
if address_str:
addresses = address_str.split(',')
addresses = filter(lambda x: bool(x), addresses)
flat = data.get('flat', 'false').lower() == 'true'
if 'ds' in data:
ds_match = re.search('(\d+)', data['ds'])
if ds_match:
ds = int(ds_match.group())
else:
raise errors.MalformedRequest("Could not read data source ('ds')")
else:
raise errors.RequiredKey('data source', 'ds')
return {'addresses': addresses, 'flat': flat, 'ds': ds}
def perform_get_command(self, request):
self.page.require_group('read')
if request['flat']:
if self.check_flat_tolerance():
response = {'flat': self.nodesModel.get_flat_nodes(request['ds'])}
else:
response = {'error': 'Flat mode is not supported once a graph has exceeded {} hosts.'.format(self.flatmode_tolerance)}
elif len(request['addresses']) == 0:
response = {'_': self.nodesModel.get_root_nodes()}
else:
response = {address: self.nodesModel.get_children(address) for address in request['addresses']}
return response
def encode_get_response(self, response):
return response
def decode_post_request(self, data):
node = data.get('node')
if not node:
raise errors.RequiredKey('node', 'node')
alias = data.get('alias')
tags = data.get('tags')
env = data.get('env')
request = {'node': node}
if alias is not None:
request['alias'] = alias
if tags is not None:
request['tags'] = tags
if env is not None:
request['env'] = env
return request
def perform_post_command(self, request):
self.page.require_group('write')
node = request.pop('node')
for key, value in request.iteritems():
if key == 'alias':
self.nodesModel.set_alias(node, value)
elif key == 'tags':
tags = filter(lambda x: bool(x), value.split(','))
self.nodesModel.set_tags(node, tags)
elif key == 'env':
if value:
self.nodesModel.set_env(node, value)
else:
self.nodesModel.set_env(node, None)
else:
print("Error in nodeinfo, unrecognized assignment {0} = {1}".format(key, value))
return 0, "Success"
def encode_post_response(self, response):
return {'code': response[0], 'message': response[1]} | __init__ | identifier_name |
nodes.py | import re
import base
import sam.models.nodes
from sam import errors
from sam import common
# This class is for getting the child nodes of all nodes in a node list, for the map
class Nodes(base.headless_post):
"""
The expected GET data includes:
'address': comma-seperated list of dotted-decimal IP addresses.
Each address is only as long as the subnet,
so 12.34.0.0/16 would be written as 12.34
A request for 1.2.3.0/24, 192.168.0.0/16, and 21.0.0.0/8
would be "1.2.3,192.168,21"
:return: A JSON-encoded dictionary where
the keys are the supplied addresses (or _ if no address) and
the values are a list of child nodes.
POST Expects a query string including:
node: ip address
like "189.179.4.0/24"
or "189.179" ( == 189.179.0.0/16)
or "189.2.3/8" ( == 189.0.0.0/8)
alias: (optional) new alias string for the node
tags: (optional) comma separated string of tags to associate with this node
env: (optional) string, this host's environment category
:return:
"""
def __init__(self):
base.HeadlessPost.__init__(self)
self.flatmode_tolerance = 256
self.nodesModel = sam.models.nodes.Nodes(common.db, self.page.user.viewing)
def check_flat_tolerance(self):
endpoints = self.nodesModel.get_all_endpoints()
count = len(endpoints)
return count <= self.flatmode_tolerance
def decode_get_request(self, data):
addresses = []
address_str = data.get('address')
if address_str:
addresses = address_str.split(',')
addresses = filter(lambda x: bool(x), addresses)
flat = data.get('flat', 'false').lower() == 'true'
if 'ds' in data:
ds_match = re.search('(\d+)', data['ds'])
if ds_match:
ds = int(ds_match.group())
else:
raise errors.MalformedRequest("Could not read data source ('ds')")
else:
raise errors.RequiredKey('data source', 'ds')
return {'addresses': addresses, 'flat': flat, 'ds': ds}
def perform_get_command(self, request):
self.page.require_group('read')
if request['flat']:
if self.check_flat_tolerance():
response = {'flat': self.nodesModel.get_flat_nodes(request['ds'])}
else:
response = {'error': 'Flat mode is not supported once a graph has exceeded {} hosts.'.format(self.flatmode_tolerance)}
elif len(request['addresses']) == 0:
response = {'_': self.nodesModel.get_root_nodes()}
else:
response = {address: self.nodesModel.get_children(address) for address in request['addresses']}
return response
def encode_get_response(self, response):
return response
def decode_post_request(self, data):
node = data.get('node')
if not node:
raise errors.RequiredKey('node', 'node')
alias = data.get('alias')
tags = data.get('tags')
env = data.get('env')
request = {'node': node}
if alias is not None:
request['alias'] = alias
if tags is not None:
request['tags'] = tags
if env is not None:
request['env'] = env
return request
def perform_post_command(self, request):
self.page.require_group('write')
node = request.pop('node')
for key, value in request.iteritems():
if key == 'alias':
self.nodesModel.set_alias(node, value)
elif key == 'tags':
tags = filter(lambda x: bool(x), value.split(','))
self.nodesModel.set_tags(node, tags)
elif key == 'env':
if value:
self.nodesModel.set_env(node, value)
else:
|
else:
print("Error in nodeinfo, unrecognized assignment {0} = {1}".format(key, value))
return 0, "Success"
def encode_post_response(self, response):
return {'code': response[0], 'message': response[1]} | self.nodesModel.set_env(node, None) | conditional_block |
base.py | import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display debug info
#f is features
class BaseFeature():
def __init__(self, text, textName="", args=[], debug=True):
self.text = text.lower()
self.args = args
self.debug = debug
self.textName = textName
#Features, not yet calculated
self.f = np.array([])
def debugStart(self):
if self.debug:
print "--BaseFeatures--"
def beginCalc(self):
if self.debug:
print "Feature calculation begining on " + self.textName
print "------"
def endCalc(self):
if self.debug:
print "Feature calculation finished on " + self.textName
print "Features Calculated:"
print self.f
print
def calc(self):
self.debugStart()
self.beginCalc()
#Calculations go here
self.endCalc()
return self.f
def getFeatures(self):
return self.f
def setText(self, text):
|
def setName(self, name):
if self.debug:
print "Name set to: " + self.textName
| if self.debug:
print self.textName + "'s text set."
self.text = text.lower() | identifier_body |
base.py | import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display debug info
#f is features
class BaseFeature():
def __init__(self, text, textName="", args=[], debug=True):
self.text = text.lower()
self.args = args
self.debug = debug
self.textName = textName
#Features, not yet calculated
self.f = np.array([])
def debugStart(self):
if self.debug:
print "--BaseFeatures--"
def beginCalc(self): | if self.debug:
print "Feature calculation begining on " + self.textName
print "------"
def endCalc(self):
if self.debug:
print "Feature calculation finished on " + self.textName
print "Features Calculated:"
print self.f
print
def calc(self):
self.debugStart()
self.beginCalc()
#Calculations go here
self.endCalc()
return self.f
def getFeatures(self):
return self.f
def setText(self, text):
if self.debug:
print self.textName + "'s text set."
self.text = text.lower()
def setName(self, name):
if self.debug:
print "Name set to: " + self.textName | random_line_split | |
base.py | import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display debug info
#f is features
class BaseFeature():
def __init__(self, text, textName="", args=[], debug=True):
self.text = text.lower()
self.args = args
self.debug = debug
self.textName = textName
#Features, not yet calculated
self.f = np.array([])
def debugStart(self):
if self.debug:
|
def beginCalc(self):
if self.debug:
print "Feature calculation begining on " + self.textName
print "------"
def endCalc(self):
if self.debug:
print "Feature calculation finished on " + self.textName
print "Features Calculated:"
print self.f
print
def calc(self):
self.debugStart()
self.beginCalc()
#Calculations go here
self.endCalc()
return self.f
def getFeatures(self):
return self.f
def setText(self, text):
if self.debug:
print self.textName + "'s text set."
self.text = text.lower()
def setName(self, name):
if self.debug:
print "Name set to: " + self.textName
| print "--BaseFeatures--" | conditional_block |
base.py | import numpy as np
#numpy is used for later classifiers
#Note: this is just a template with all required methods
#text is the text represented as a string
#textName is optional, indicate sthe name of the text, used for debug
#args are aditional arguments for the feature calculator
#debug indicates wheter to display debug info
#f is features
class BaseFeature():
def __init__(self, text, textName="", args=[], debug=True):
self.text = text.lower()
self.args = args
self.debug = debug
self.textName = textName
#Features, not yet calculated
self.f = np.array([])
def debugStart(self):
if self.debug:
print "--BaseFeatures--"
def beginCalc(self):
if self.debug:
print "Feature calculation begining on " + self.textName
print "------"
def endCalc(self):
if self.debug:
print "Feature calculation finished on " + self.textName
print "Features Calculated:"
print self.f
print
def calc(self):
self.debugStart()
self.beginCalc()
#Calculations go here
self.endCalc()
return self.f
def | (self):
return self.f
def setText(self, text):
if self.debug:
print self.textName + "'s text set."
self.text = text.lower()
def setName(self, name):
if self.debug:
print "Name set to: " + self.textName
| getFeatures | identifier_name |
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? */
use itertools::Itertools;
use shared::Permutations;
fn main() | {
let digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = digits.permutations().skip(1_000_000 - 1).next().unwrap();
println!("{}", result.into_iter().join(""));
} | identifier_body | |
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? */
use itertools::Itertools;
use shared::Permutations;
fn main() {
let digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = digits.permutations().skip(1_000_000 - 1).next().unwrap();
println!("{}", result.into_iter().join("")); | } | random_line_split | |
24.rs | /* Problem 24: Lexicographic permutations
*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation
* of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically,
* we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
*
* 012 021 102 120 201 210
*
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? */
use itertools::Itertools;
use shared::Permutations;
fn | () {
let digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let result = digits.permutations().skip(1_000_000 - 1).next().unwrap();
println!("{}", result.into_iter().join(""));
}
| main | identifier_name |
const.py | """Constants for the cloud component."""
DOMAIN = 'cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled'
PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE_ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
CONF_ALEXA = 'alexa'
CONF_ALIASES = 'aliases'
CONF_COGNITO_CLIENT_ID = 'cognito_client_id'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_FILTER = 'filter'
CONF_GOOGLE_ACTIONS = 'google_actions'
CONF_RELAYER = 'relayer'
CONF_USER_POOL_ID = 'user_pool_id'
CONF_GOOGLE_ACTIONS_SYNC_URL = 'google_actions_sync_url'
CONF_SUBSCRIPTION_INFO_URL = 'subscription_info_url'
CONF_CLOUDHOOK_CREATE_URL = 'cloudhook_create_url'
CONF_REMOTE_API_URL = 'remote_api_url'
CONF_ACME_DIRECTORY_SERVER = 'acme_directory_server'
MODE_DEV = "development"
MODE_PROD = "production"
DISPATCHER_REMOTE_UPDATE = 'cloud_remote_update'
class InvalidTrustedNetworks(Exception):
| """Raised when invalid trusted networks config.""" | identifier_body | |
const.py | """Constants for the cloud component."""
DOMAIN = 'cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled' | PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE_ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
CONF_ALEXA = 'alexa'
CONF_ALIASES = 'aliases'
CONF_COGNITO_CLIENT_ID = 'cognito_client_id'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_FILTER = 'filter'
CONF_GOOGLE_ACTIONS = 'google_actions'
CONF_RELAYER = 'relayer'
CONF_USER_POOL_ID = 'user_pool_id'
CONF_GOOGLE_ACTIONS_SYNC_URL = 'google_actions_sync_url'
CONF_SUBSCRIPTION_INFO_URL = 'subscription_info_url'
CONF_CLOUDHOOK_CREATE_URL = 'cloudhook_create_url'
CONF_REMOTE_API_URL = 'remote_api_url'
CONF_ACME_DIRECTORY_SERVER = 'acme_directory_server'
MODE_DEV = "development"
MODE_PROD = "production"
DISPATCHER_REMOTE_UPDATE = 'cloud_remote_update'
class InvalidTrustedNetworks(Exception):
"""Raised when invalid trusted networks config.""" | random_line_split | |
const.py | """Constants for the cloud component."""
DOMAIN = 'cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled'
PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE_ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
CONF_ALEXA = 'alexa'
CONF_ALIASES = 'aliases'
CONF_COGNITO_CLIENT_ID = 'cognito_client_id'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_FILTER = 'filter'
CONF_GOOGLE_ACTIONS = 'google_actions'
CONF_RELAYER = 'relayer'
CONF_USER_POOL_ID = 'user_pool_id'
CONF_GOOGLE_ACTIONS_SYNC_URL = 'google_actions_sync_url'
CONF_SUBSCRIPTION_INFO_URL = 'subscription_info_url'
CONF_CLOUDHOOK_CREATE_URL = 'cloudhook_create_url'
CONF_REMOTE_API_URL = 'remote_api_url'
CONF_ACME_DIRECTORY_SERVER = 'acme_directory_server'
MODE_DEV = "development"
MODE_PROD = "production"
DISPATCHER_REMOTE_UPDATE = 'cloud_remote_update'
class | (Exception):
"""Raised when invalid trusted networks config."""
| InvalidTrustedNetworks | identifier_name |
po_generic_page.py | from hubcheck.pageobjects.basepageobject import BasePageObject
from hubcheck.pageobjects.basepageelement import Link
from selenium.common.exceptions import NoSuchElementException
class GenericPage(BasePageObject):
"""Generic Page with just a header and footer"""
def __init__(self,browser,catalog):
super(GenericPage,self).__init__(browser,catalog)
self.path = '/'
# load hub's classes
GenericPage_Locators = self.load_class('GenericPage_Locators')
NeedHelpForm = self.load_class('NeedHelpForm')
Header = self.load_class('Header')
Footer = self.load_class('Footer')
# update this object's locator
self.locators = GenericPage_Locators.locators
# setup page object's components
self.needhelpform = NeedHelpForm(self,{},self.__refreshCaptchaCB)
self.needhelplink = Link(self,{'base':'needhelplink'})
self.header = Header(self)
# self.footer = Footer(self)
def __refreshCaptchaCB(self):
self._browser.refresh()
self.needhelplink.click()
def goto_login(self):
return self.header.goto_login()
def goto_register(self):
return self.header.goto_register()
def goto_logout(self):
return self.header.goto_logout()
def goto_myaccount(self):
return self.header.goto_myaccount()
def goto_profile(self):
return self.header.goto_profile()
def toggle_needhelp(self):
return self.needhelplink.click()
def is_logged_in(self):
"""check if user is logged in, returns True or False"""
return self.header.is_logged_in()
def get_account_number(self):
"""return the account number of a logged in user based on urls"""
if not self.is_logged_in():
raise RuntimeError("user is not logged in")
return self.header.get_account_number()
def get_debug_info(self):
rtxt = []
for e in self.find_elements(self.locators['debug']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_notification_info(self):
rtxt = []
for e in self.find_elements(self.locators['notification']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_success_info(self):
rtxt = []
for e in self.find_elements(self.locators['success']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_error_info(self):
rtxt = []
for e in self.find_elements(self.locators['error']):
|
return rtxt
def get_errorbox_info(self):
rtxt = []
for e in self.find_elements(self.locators['errorbox1']):
if e.is_displayed():
rtxt.append(e.text)
for e in self.find_elements(self.locators['errorbox2']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
class GenericPage_Locators_Base_1(object):
"""
locators for GenericPage object
"""
locators = {
'needhelplink' : "css=#tab",
'debug' : "css=#system-debug",
'error' : "css=.error",
'success' : "css=.passed",
'notification' : "css=#page_notifications",
'errorbox1' : "css=#errorbox",
'errorbox2' : "css=#error-box",
}
| if e.is_displayed():
rtxt.append(e.text) | conditional_block |
po_generic_page.py | from hubcheck.pageobjects.basepageobject import BasePageObject
from hubcheck.pageobjects.basepageelement import Link
from selenium.common.exceptions import NoSuchElementException
class GenericPage(BasePageObject):
"""Generic Page with just a header and footer"""
def __init__(self,browser,catalog):
super(GenericPage,self).__init__(browser,catalog)
self.path = '/'
# load hub's classes
GenericPage_Locators = self.load_class('GenericPage_Locators')
NeedHelpForm = self.load_class('NeedHelpForm')
Header = self.load_class('Header')
Footer = self.load_class('Footer')
# update this object's locator
self.locators = GenericPage_Locators.locators
# setup page object's components
self.needhelpform = NeedHelpForm(self,{},self.__refreshCaptchaCB)
self.needhelplink = Link(self,{'base':'needhelplink'})
self.header = Header(self)
# self.footer = Footer(self)
def __refreshCaptchaCB(self):
self._browser.refresh()
self.needhelplink.click()
def goto_login(self):
return self.header.goto_login()
def goto_register(self):
return self.header.goto_register()
def goto_logout(self):
return self.header.goto_logout()
def goto_myaccount(self):
return self.header.goto_myaccount()
def goto_profile(self):
return self.header.goto_profile()
def toggle_needhelp(self):
return self.needhelplink.click()
def is_logged_in(self):
"""check if user is logged in, returns True or False"""
return self.header.is_logged_in()
def get_account_number(self):
"""return the account number of a logged in user based on urls"""
if not self.is_logged_in():
raise RuntimeError("user is not logged in")
return self.header.get_account_number()
def get_debug_info(self):
rtxt = []
for e in self.find_elements(self.locators['debug']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_notification_info(self):
rtxt = []
for e in self.find_elements(self.locators['notification']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_success_info(self):
rtxt = []
for e in self.find_elements(self.locators['success']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_error_info(self):
rtxt = []
for e in self.find_elements(self.locators['error']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_errorbox_info(self): | for e in self.find_elements(self.locators['errorbox2']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
class GenericPage_Locators_Base_1(object):
"""
locators for GenericPage object
"""
locators = {
'needhelplink' : "css=#tab",
'debug' : "css=#system-debug",
'error' : "css=.error",
'success' : "css=.passed",
'notification' : "css=#page_notifications",
'errorbox1' : "css=#errorbox",
'errorbox2' : "css=#error-box",
} | rtxt = []
for e in self.find_elements(self.locators['errorbox1']):
if e.is_displayed():
rtxt.append(e.text) | random_line_split |
po_generic_page.py | from hubcheck.pageobjects.basepageobject import BasePageObject
from hubcheck.pageobjects.basepageelement import Link
from selenium.common.exceptions import NoSuchElementException
class GenericPage(BasePageObject):
"""Generic Page with just a header and footer"""
def __init__(self,browser,catalog):
super(GenericPage,self).__init__(browser,catalog)
self.path = '/'
# load hub's classes
GenericPage_Locators = self.load_class('GenericPage_Locators')
NeedHelpForm = self.load_class('NeedHelpForm')
Header = self.load_class('Header')
Footer = self.load_class('Footer')
# update this object's locator
self.locators = GenericPage_Locators.locators
# setup page object's components
self.needhelpform = NeedHelpForm(self,{},self.__refreshCaptchaCB)
self.needhelplink = Link(self,{'base':'needhelplink'})
self.header = Header(self)
# self.footer = Footer(self)
def __refreshCaptchaCB(self):
self._browser.refresh()
self.needhelplink.click()
def goto_login(self):
return self.header.goto_login()
def goto_register(self):
return self.header.goto_register()
def goto_logout(self):
return self.header.goto_logout()
def goto_myaccount(self):
return self.header.goto_myaccount()
def goto_profile(self):
return self.header.goto_profile()
def toggle_needhelp(self):
|
def is_logged_in(self):
"""check if user is logged in, returns True or False"""
return self.header.is_logged_in()
def get_account_number(self):
"""return the account number of a logged in user based on urls"""
if not self.is_logged_in():
raise RuntimeError("user is not logged in")
return self.header.get_account_number()
def get_debug_info(self):
rtxt = []
for e in self.find_elements(self.locators['debug']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_notification_info(self):
rtxt = []
for e in self.find_elements(self.locators['notification']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_success_info(self):
rtxt = []
for e in self.find_elements(self.locators['success']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_error_info(self):
rtxt = []
for e in self.find_elements(self.locators['error']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_errorbox_info(self):
rtxt = []
for e in self.find_elements(self.locators['errorbox1']):
if e.is_displayed():
rtxt.append(e.text)
for e in self.find_elements(self.locators['errorbox2']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
class GenericPage_Locators_Base_1(object):
"""
locators for GenericPage object
"""
locators = {
'needhelplink' : "css=#tab",
'debug' : "css=#system-debug",
'error' : "css=.error",
'success' : "css=.passed",
'notification' : "css=#page_notifications",
'errorbox1' : "css=#errorbox",
'errorbox2' : "css=#error-box",
}
| return self.needhelplink.click() | identifier_body |
po_generic_page.py | from hubcheck.pageobjects.basepageobject import BasePageObject
from hubcheck.pageobjects.basepageelement import Link
from selenium.common.exceptions import NoSuchElementException
class GenericPage(BasePageObject):
"""Generic Page with just a header and footer"""
def __init__(self,browser,catalog):
super(GenericPage,self).__init__(browser,catalog)
self.path = '/'
# load hub's classes
GenericPage_Locators = self.load_class('GenericPage_Locators')
NeedHelpForm = self.load_class('NeedHelpForm')
Header = self.load_class('Header')
Footer = self.load_class('Footer')
# update this object's locator
self.locators = GenericPage_Locators.locators
# setup page object's components
self.needhelpform = NeedHelpForm(self,{},self.__refreshCaptchaCB)
self.needhelplink = Link(self,{'base':'needhelplink'})
self.header = Header(self)
# self.footer = Footer(self)
def __refreshCaptchaCB(self):
self._browser.refresh()
self.needhelplink.click()
def goto_login(self):
return self.header.goto_login()
def goto_register(self):
return self.header.goto_register()
def goto_logout(self):
return self.header.goto_logout()
def goto_myaccount(self):
return self.header.goto_myaccount()
def goto_profile(self):
return self.header.goto_profile()
def toggle_needhelp(self):
return self.needhelplink.click()
def | (self):
"""check if user is logged in, returns True or False"""
return self.header.is_logged_in()
def get_account_number(self):
"""return the account number of a logged in user based on urls"""
if not self.is_logged_in():
raise RuntimeError("user is not logged in")
return self.header.get_account_number()
def get_debug_info(self):
rtxt = []
for e in self.find_elements(self.locators['debug']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_notification_info(self):
rtxt = []
for e in self.find_elements(self.locators['notification']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_success_info(self):
rtxt = []
for e in self.find_elements(self.locators['success']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_error_info(self):
rtxt = []
for e in self.find_elements(self.locators['error']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
def get_errorbox_info(self):
rtxt = []
for e in self.find_elements(self.locators['errorbox1']):
if e.is_displayed():
rtxt.append(e.text)
for e in self.find_elements(self.locators['errorbox2']):
if e.is_displayed():
rtxt.append(e.text)
return rtxt
class GenericPage_Locators_Base_1(object):
"""
locators for GenericPage object
"""
locators = {
'needhelplink' : "css=#tab",
'debug' : "css=#system-debug",
'error' : "css=.error",
'success' : "css=.passed",
'notification' : "css=#page_notifications",
'errorbox1' : "css=#errorbox",
'errorbox2' : "css=#error-box",
}
| is_logged_in | identifier_name |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds;
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
#[lang = "eh_personality"]
extern fn eh_personality() {}
#[cfg(target_os = "windows")]
#[lang = "eh_unwind_resume"]
extern fn | () {}
// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) {}
fn main() {
take_range(0..1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..1)
take_range(1..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(1..)
take_range(..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..)
take_range(0..=1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..=1)
take_range(..5);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..5)
take_range(..=42);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..=42)
}
| eh_unwind_resume | identifier_name |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds;
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
#[lang = "eh_personality"]
extern fn eh_personality() {}
#[cfg(target_os = "windows")]
#[lang = "eh_unwind_resume"]
extern fn eh_unwind_resume() {}
// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) {}
fn main() {
take_range(0..1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..1)
take_range(1..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(1..)
take_range(..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here | take_range(0..=1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..=1)
take_range(..5);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..5)
take_range(..=42);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..=42)
} | //~| SUGGESTION &(..)
| random_line_split |
issue-54505-no-std.rs | // error-pattern: `#[panic_handler]` function required, but not found
// Regression test for #54505 - range borrowing suggestion had
// incorrect syntax (missing parentheses).
// This test doesn't use std
// (so all Ranges resolve to core::ops::Range...)
#![no_std]
#![feature(lang_items)]
use core::ops::RangeBounds;
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
#[lang = "eh_personality"]
extern fn eh_personality() {}
#[cfg(target_os = "windows")]
#[lang = "eh_unwind_resume"]
extern fn eh_unwind_resume() {}
// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) |
fn main() {
take_range(0..1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..1)
take_range(1..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(1..)
take_range(..);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..)
take_range(0..=1);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(0..=1)
take_range(..5);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..5)
take_range(..=42);
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &(..=42)
}
| {} | identifier_body |
r.js | "use strict";
const fs = require('fs');
const path = require('path');
module.exports = {
| (opts, runCode) {
const entry = path.join(opts.dir, 'main.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(entry, opts.solution);
runCode({
name: 'Rscript',
args: ['--no-save', entry],
options: {
cwd: opts.dir,
}
});
},
testIntegration(opts, runCode) {
const entry = path.join(opts.dir, 'run-tests.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(path.join(opts.dir, 'solution.R'), opts.solution);
fs.writeFileSync(path.join(opts.dir, 'tests.R'), opts.fixture);
fs.writeFileSync(entry, [
`library(testthat)`,
`source("/runner/frameworks/r/codewars-reporter.R")`,
`source("solution.R")`,
`test_file("tests.R", reporter=CodewarsReporter$new())`,
].join('\n'));
runCode({
name: 'Rscript',
args: ['--no-save', entry],
options: {
cwd: opts.dir,
},
});
}
};
| solutionOnly | identifier_name |
r.js | "use strict";
const fs = require('fs');
const path = require('path');
module.exports = {
solutionOnly(opts, runCode) {
const entry = path.join(opts.dir, 'main.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(entry, opts.solution);
runCode({
name: 'Rscript',
args: ['--no-save', entry],
options: {
cwd: opts.dir,
}
});
},
testIntegration(opts, runCode) {
const entry = path.join(opts.dir, 'run-tests.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(path.join(opts.dir, 'solution.R'), opts.solution); | `source("solution.R")`,
`test_file("tests.R", reporter=CodewarsReporter$new())`,
].join('\n'));
runCode({
name: 'Rscript',
args: ['--no-save', entry],
options: {
cwd: opts.dir,
},
});
}
}; | fs.writeFileSync(path.join(opts.dir, 'tests.R'), opts.fixture);
fs.writeFileSync(entry, [
`library(testthat)`,
`source("/runner/frameworks/r/codewars-reporter.R")`, | random_line_split |
r.js | "use strict";
const fs = require('fs');
const path = require('path');
module.exports = {
solutionOnly(opts, runCode) {
const entry = path.join(opts.dir, 'main.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(entry, opts.solution);
runCode({
name: 'Rscript',
args: ['--no-save', entry],
options: {
cwd: opts.dir,
}
});
},
testIntegration(opts, runCode) |
};
| {
const entry = path.join(opts.dir, 'run-tests.R');
if (opts.setup) fs.writeFileSync(path.join(opts.dir, 'setup.R'), opts.setup);
fs.writeFileSync(path.join(opts.dir, 'solution.R'), opts.solution);
fs.writeFileSync(path.join(opts.dir, 'tests.R'), opts.fixture);
fs.writeFileSync(entry, [
`library(testthat)`,
`source("/runner/frameworks/r/codewars-reporter.R")`,
`source("solution.R")`,
`test_file("tests.R", reporter=CodewarsReporter$new())`,
].join('\n'));
runCode({
name: 'Rscript',
args: ['--no-save', entry],
options: {
cwd: opts.dir,
},
});
} | identifier_body |
replication-table-rows-test.js | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
const REPLICATION_DETAILS = {
clusterId: 'b829d963-6835-33eb-a903-57376024b97a',
merkleRoot: 'c21c8428a0a06135cef6ae25bf8e0267ff1592a6',
};
const CLUSTER_MODE = 'primary';
module('Integration | Component | replication-table-rows', function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
this.set('replicationDetails', REPLICATION_DETAILS);
this.set('clusterMode', CLUSTER_MODE);
});
test('it renders', async function (assert) {
await render(
hbs`<ReplicationTableRows @replicationDetails={{replicationDetails}} @clusterMode={{clusterMode}}/>`
);
assert.dom('[data-test-table-rows]').exists();
});
test('it renders with merkle root, mode, replication set', async function (assert) {
await render(
hbs`<ReplicationTableRows @replicationDetails={{replicationDetails}} @clusterMode={{clusterMode}}/>`
);
assert.dom('.empty-state').doesNotExist('does not show empty state when data is found'); |
assert
.dom('[data-test-row-value="Merkle root index"]')
.includesText(REPLICATION_DETAILS.merkleRoot, `shows the correct Merkle Root`);
assert.dom('[data-test-row-value="Mode"]').includesText(CLUSTER_MODE, `shows the correct Mode`);
assert
.dom('[data-test-row-value="Replication set"]')
.includesText(REPLICATION_DETAILS.clusterId, `shows the correct Cluster ID`);
});
test('it renders unknown if values cannot be found', async function (assert) {
const noAttrs = {
clusterId: null,
merkleRoot: null,
};
const clusterMode = null;
this.set('replicationDetails', noAttrs);
this.set('clusterMode', clusterMode);
await render(
hbs`<ReplicationTableRows @replicationDetails={{replicationDetails}} @clusterMode={{clusterMode}}/>`
);
assert.dom('[data-test-table-rows]').includesText('unknown');
});
}); | random_line_split | |
059_add_consumer_generation.py | # 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.
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import text
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
consumers = Table("consumers", meta, autoload=True)
if not hasattr(consumers.c, "generation"):
# This is adding a column to an existing table, so the server_default
# bit will make existing rows 0 for that column.
| consumers.create_column(Column("generation", Integer, default=0,
server_default=text("0"), nullable=False)) | conditional_block | |
059_add_consumer_generation.py | # 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.
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import text
def | (migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
consumers = Table("consumers", meta, autoload=True)
if not hasattr(consumers.c, "generation"):
# This is adding a column to an existing table, so the server_default
# bit will make existing rows 0 for that column.
consumers.create_column(Column("generation", Integer, default=0,
server_default=text("0"), nullable=False))
| upgrade | identifier_name |
059_add_consumer_generation.py | # 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.
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import text
def upgrade(migrate_engine):
| meta = MetaData()
meta.bind = migrate_engine
consumers = Table("consumers", meta, autoload=True)
if not hasattr(consumers.c, "generation"):
# This is adding a column to an existing table, so the server_default
# bit will make existing rows 0 for that column.
consumers.create_column(Column("generation", Integer, default=0,
server_default=text("0"), nullable=False)) | identifier_body | |
059_add_consumer_generation.py | # 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. | from sqlalchemy import text
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
consumers = Table("consumers", meta, autoload=True)
if not hasattr(consumers.c, "generation"):
# This is adding a column to an existing table, so the server_default
# bit will make existing rows 0 for that column.
consumers.create_column(Column("generation", Integer, default=0,
server_default=text("0"), nullable=False)) |
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table | random_line_split |
comments.js | var recast = require("../main");
var n = recast.types.namedTypes;
var b = recast.types.builders;
var fromString = require("../lib/lines").fromString;
var util = require("../lib/util");
var annotated = [
"function dup(/* string */ s,",
" /* int */ n) /* string */",
"{",
" // Use an array full of holes.",
" return Array(n + /*",
" * off-by-*/ 1).join(s);",
"}"
];
exports.testComments = function(t, assert) {
var code = annotated.join("\n");
var ast = recast.parse(code);
var dup = ast.program.body[0];
n.FunctionDeclaration.assert(dup);
assert.strictEqual(dup.id.name, "dup");
// More of a basic sanity test than a comment test.
assert.strictEqual(recast.print(ast).code, code);
assert.strictEqual(recast.print(ast.program).code, code);
assert.strictEqual(recast.print(dup).code, code);
assert.strictEqual(
recast.print(dup.params[0]).code,
"/* string */ s"
);
assert.strictEqual(
recast.print(dup.params[1]).code,
"/* int */ n"
);
assert.strictEqual(
recast.print(dup.body).code,
["/* string */"].concat(annotated.slice(2)).join("\n")
);
var retStmt = dup.body.body[0];
n.ReturnStatement.assert(retStmt); | var flush = fromString(indented).indent(-2);
assert.strictEqual(
recast.print(retStmt).code,
flush.toString()
);
var join = retStmt.argument;
n.CallExpression.assert(join);
var one = join.callee.object.arguments[0].right;
n.Literal.assert(one);
assert.strictEqual(one.value, 1);
assert.strictEqual(recast.print(one).code, [
"/*",
" * off-by-*/ 1"
].join("\n"));
t.finish();
};
var trailing = [
"Foo.prototype = {",
"// Copyright (c) 2013 Ben Newman <bn@cs.stanford.edu>",
"",
" /**",
" * Leading comment.",
" */",
" constructor: Foo, // Important for instanceof",
" // to work in all browsers.",
' bar: "baz", // Just in case we need it.',
" qux: { // Here is an object literal.",
" zxcv: 42",
" // Put more properties here when you think of them.",
" } // There was an object literal...",
" // ... and here I am continuing this comment.",
"",
"};"
];
var trailingExpected = [
"Foo.prototype = {",
" // Copyright (c) 2013 Ben Newman <bn@cs.stanford.edu>",
"",
" /**",
" * Leading comment.",
" */",
" // Important for instanceof",
" // to work in all browsers.",
" constructor: Foo,",
"",
" // Just in case we need it.",
' bar: "baz",',
"",
" // There was an object literal...",
" // ... and here I am continuing this comment.",
" qux: // Here is an object literal.",
" {",
" // Put more properties here when you think of them.",
" zxcv: 42,",
"",
" asdf: 43",
" },",
"",
' extra: "property"',
"};"
];
exports.testTrailingComments = function(t, assert) {
var code = trailing.join("\n");
var ast = recast.parse(code);
assert.strictEqual(recast.print(ast).code, code);
// Drop all original source information to force reprinting.
require("ast-types").traverse(ast, function(node) {
node.original = null;
});
var assign = ast.program.body[0].expression;
n.AssignmentExpression.assert(assign);
var props = assign.right.properties;
n.Property.arrayOf().assert(props);
props.push(b.property(
"init",
b.identifier("extra"),
b.literal("property")
));
var quxVal = props[2].value;
n.ObjectExpression.assert(quxVal);
quxVal.properties.push(b.property(
"init",
b.identifier("asdf"),
b.literal(43)
));
var actual = recast.print(ast, { tabWidth: 2 }).code;
var expected = trailingExpected.join("\n");
// Check semantic equivalence:
util.assertEquivalent(ast, recast.parse(actual));
assert.strictEqual(actual, expected);
t.finish();
};
var paramTrailing = [
"function foo(bar, baz /* = null */) {",
" assert.strictEqual(baz, null);",
"}"
];
var paramTrailingExpected = [
"function foo(zxcv, bar, baz /* = null */) {",
" assert.strictEqual(baz, null);",
"}"
];
exports.testParamTrailingComments = function(t, assert) {
var code = paramTrailing.join("\n");
var ast = recast.parse(code);
var func = ast.program.body[0];
n.FunctionDeclaration.assert(func);
func.params.unshift(b.identifier("zxcv"));
var actual = recast.print(ast, { tabWidth: 2 }).code;
var expected = paramTrailingExpected.join("\n");
assert.strictEqual(actual, expected);
t.finish();
};
var protoAssign = [
"A.prototype.foo = function() {",
" return this.bar();",
"}", // Lack of semicolon screws up location info.
"",
"// Comment about the bar method.",
"A.prototype.bar = function() {",
" return this.foo();",
"}"
];
exports.testProtoAssignComment = function(t, assert) {
var code = protoAssign.join("\n");
var ast = recast.parse(code);
var foo = ast.program.body[0];
var bar = ast.program.body[1];
n.ExpressionStatement.assert(foo);
n.ExpressionStatement.assert(bar);
assert.strictEqual(foo.expression.left.property.name, "foo");
assert.strictEqual(bar.expression.left.property.name, "bar");
assert.ok(!foo.comments);
assert.ok(bar.comments);
assert.strictEqual(bar.comments.length, 1);
assert.strictEqual(
bar.comments[0].value,
" Comment about the bar method."
);
t.finish();
}; |
var indented = annotated.slice(3, 6).join("\n"); | random_line_split |
kendo.culture.zh-SG.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) |
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(430);
module.exports = __webpack_require__(430);
/***/ }),
/***/ 430:
/***/ (function(module, exports) {
(function( window, undefined ) {
kendo.cultures["zh-SG"] = {
name: "zh-SG",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Singapore Dollar",
abbr: "SGD",
pattern: ["($n)","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "$"
}
},
calendars: {
standard: {
days: {
names: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
namesAbbr: ["周日","周一","周二","周三","周四","周五","周六"],
namesShort: ["日","一","二","三","四","五","六"]
},
months: {
names: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
namesAbbr: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
},
AM: ["上午","上午","上午"],
PM: ["下午","下午","下午"],
patterns: {
d: "d/M/yyyy",
D: "yyyy'年'M'月'd'日'",
F: "yyyy'年'M'月'd'日' tt h:mm:ss",
g: "d/M/yyyy tt h:mm",
G: "d/M/yyyy tt h:mm:ss",
m: "M'月'd'日'",
M: "M'月'd'日'",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "tt h:mm",
T: "tt h:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "yyyy'年'M'月'",
Y: "yyyy'年'M'月'"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
/***/ })
/******/ }); | {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ } | identifier_body |
kendo.culture.zh-SG.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function | (moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(430);
module.exports = __webpack_require__(430);
/***/ }),
/***/ 430:
/***/ (function(module, exports) {
(function( window, undefined ) {
kendo.cultures["zh-SG"] = {
name: "zh-SG",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Singapore Dollar",
abbr: "SGD",
pattern: ["($n)","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "$"
}
},
calendars: {
standard: {
days: {
names: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
namesAbbr: ["周日","周一","周二","周三","周四","周五","周六"],
namesShort: ["日","一","二","三","四","五","六"]
},
months: {
names: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
namesAbbr: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
},
AM: ["上午","上午","上午"],
PM: ["下午","下午","下午"],
patterns: {
d: "d/M/yyyy",
D: "yyyy'年'M'月'd'日'",
F: "yyyy'年'M'月'd'日' tt h:mm:ss",
g: "d/M/yyyy tt h:mm",
G: "d/M/yyyy tt h:mm:ss",
m: "M'月'd'日'",
M: "M'月'd'日'",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "tt h:mm",
T: "tt h:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "yyyy'年'M'月'",
Y: "yyyy'年'M'月'"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
/***/ })
/******/ }); | __webpack_require__ | identifier_name |
kendo.culture.zh-SG.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules; |
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(430);
module.exports = __webpack_require__(430);
/***/ }),
/***/ 430:
/***/ (function(module, exports) {
(function( window, undefined ) {
kendo.cultures["zh-SG"] = {
name: "zh-SG",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Singapore Dollar",
abbr: "SGD",
pattern: ["($n)","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "$"
}
},
calendars: {
standard: {
days: {
names: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
namesAbbr: ["周日","周一","周二","周三","周四","周五","周六"],
namesShort: ["日","一","二","三","四","五","六"]
},
months: {
names: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
namesAbbr: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
},
AM: ["上午","上午","上午"],
PM: ["下午","下午","下午"],
patterns: {
d: "d/M/yyyy",
D: "yyyy'年'M'月'd'日'",
F: "yyyy'年'M'月'd'日' tt h:mm:ss",
g: "d/M/yyyy tt h:mm",
G: "d/M/yyyy tt h:mm:ss",
m: "M'月'd'日'",
M: "M'月'd'日'",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "tt h:mm",
T: "tt h:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "yyyy'年'M'月'",
Y: "yyyy'年'M'月'"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
/***/ })
/******/ }); | random_line_split | |
index.spec.ts | import * as assert from 'power-assert';
import SUSH from 'sush';
import SUSHPluginAddObject from '../';
describe('SUSHPluginAddObject', () => {
let sush: SUSH;
beforeEach(() => {
// Init SUSH
sush = new SUSH();
});
it('dose nothing if argument is none', (done) => {
sush.flow([
SUSHPluginAddObject()
])
.then(() => {
done();
})
.catch((err) => done(err));
});
it('adds urls in Object', (done) => {
const expectedObj: {[key: string]: string} = {
example: 'https://example.com',
test: 'https://test.example'
};
sush.flow([
SUSHPluginAddObject(expectedObj)
])
.then(() => {
for (const key of Object.keys(expectedObj)) {
const expected = expectedObj[key];
assert.strictEqual(sush.stock.get(key), expected);
}
done();
})
.catch((err) => done(err));
});
it('adds urls in Map', (done) => { |
const expectedMap = new Map();
for (const key of Object.keys(basedObj)) {
expectedMap.set(key, basedObj[key]);
}
sush.flow([
SUSHPluginAddObject(expectedMap)
])
.then(() => {
for (const [key, expected] of expectedMap.entries()) {
assert.strictEqual(sush.stock.get(key), expected);
}
done();
})
.catch((err) => done(err));
});
}); | const basedObj: {[key: string]: string} = {
example: 'https://example.com',
test: 'https://test.example'
}; | random_line_split |
Administration.SentEmailsForm.ts | namespace PatientManagement.Administration {
export interface SentEmailsForm {
ToEmail: PatientManagement.LKCodeDescr;
Subject: Serenity.StringEditor;
Body: Serenity.HtmlContentEditor;
EmailSignature: Serenity.HtmlContentEditor;
}
export class SentEmailsForm extends Serenity.PrefixedContext {
static formKey = 'Administration.SentEmails';
private static init: boolean;
constructor(prefix: string) {
super(prefix);
if (!SentEmailsForm.init) {
| }
}
}
| SentEmailsForm.init = true;
var s = Serenity;
var w0 = PatientManagement.LKCodeDescr;
var w1 = s.StringEditor;
var w2 = s.HtmlContentEditor;
Q.initFormType(SentEmailsForm, [
'ToEmail', w0,
'Subject', w1,
'Body', w2,
'EmailSignature', w2
]);
}
| conditional_block |
Administration.SentEmailsForm.ts | namespace PatientManagement.Administration {
export interface SentEmailsForm {
ToEmail: PatientManagement.LKCodeDescr;
Subject: Serenity.StringEditor;
Body: Serenity.HtmlContentEditor;
EmailSignature: Serenity.HtmlContentEditor;
}
export class SentEmailsForm extends Serenity.PrefixedContext {
static formKey = 'Administration.SentEmails';
private static init: boolean;
constructor(prefix: string) {
super(prefix);
if (!SentEmailsForm.init) {
SentEmailsForm.init = true;
var s = Serenity;
var w0 = PatientManagement.LKCodeDescr;
var w1 = s.StringEditor;
var w2 = s.HtmlContentEditor; |
Q.initFormType(SentEmailsForm, [
'ToEmail', w0,
'Subject', w1,
'Body', w2,
'EmailSignature', w2
]);
}
}
}
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.