file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
12.1k
| suffix
large_stringlengths 0
12k
| middle
large_stringlengths 0
7.51k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
tweet-dump.py | """
Copyright (c) 2012 Casey Dunham <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
__author__ = 'Casey Dunham <[email protected]>'
__version__ = '0.1'
import argparse
import urllib
import sys
from urllib2 import (Request, urlopen, HTTPError, URLError)
try:
# Python >= 2.6
import json
except ImportError:
try:
# Python < 2.6
import simplejson as json
except ImportError:
try:
# Google App Engine
from django.utils import simplejson as json
except ImportError:
raise ImportError, "Unable to load a json library"
class | (Exception):
@property
def message(self):
return self.args[0]
class RateLimitError(TweetDumpError):
pass
API_URL = "https://api.twitter.com/1/statuses/user_timeline.json?%s"
# we are not authenticating so this will return the rate limit based on our IP
# see (https://dev.twitter.com/docs/api/1/get/account/rate_limit_status)
RATE_LIMIT_API_URL = "https://api.twitter.com/1/account/rate_limit_status.json"
parser = argparse.ArgumentParser(description="dump all tweets from user")
parser.add_argument("handle", type=str, help="twitter screen name")
def get_tweets(screen_name, count, maxid=None):
params = {
"screen_name": screen_name,
"count": count,
"exclude_replies": "true",
"include_rts": "true"
}
# if we include the max_id from the last tweet we retrieved, we will retrieve the same tweet again
# so decrement it by one to not retrieve duplicate tweets
if maxid:
params["max_id"] = int(maxid) - 1
encoded_params = urllib.urlencode(params)
query = API_URL % encoded_params
resp = fetch_url(query)
ratelimit_limit = resp.headers["X-RateLimit-Limit"]
ratelimit_remaining = resp.headers["X-RateLimit-Remaining"]
ratelimit_reset = resp.headers["X-RateLimit-Reset"]
tweets = json.loads(resp.read())
return ratelimit_remaining, tweets
def get_initial_rate_info():
resp = fetch_url(RATE_LIMIT_API_URL)
rate_info = json.loads(resp.read())
return rate_info["remaining_hits"], rate_info["reset_time_in_seconds"], rate_info["reset_time"]
def fetch_url(url):
try:
return urlopen(Request(url))
except HTTPError, e:
if e.code == 400: # twitter api limit reached
raise RateLimitError(e.code)
if e.code == 502: # Bad Gateway, sometimes get this when making requests. just try again
raise TweetDumpError(e.code)
print >> sys.stderr, "[!] HTTP Error %s: %s" % (e.code, e.msg)
except URLError, e:
print >> sys.stderr, "[!] URL Error: %s URL: %s" % (e.reason, url)
exit(1)
def print_banner():
print "tweet-dump %s (c) 2012 %s" % (__version__, __author__)
print """ .-.
(. .)__,')
/ V )
\ ( \/ .
`._`.__\\ o ,
<< `' .o..
"""
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="tweet-dump")
parser.add_argument('username', help="Twitter Screen Name")
parser.add_argument('file', help="File to write tweeets to")
parser.add_argument('--count', help="Number of tweets to retrieve per request", default=200)
parser.add_argument('--maxid', help="ID of Tweet to start dumping after", default=None)
args = parser.parse_args()
screen_name = args.username
count = args.count
maxid = args.maxid
out_file_name = args.file
out_file = None
try:
out_file = open(out_file_name, 'w')
except IOError, e:
print >> sys.stderr, "[!] error creating file %s" % out_file_name
exit(1)
print_banner()
print "[*] writing tweets to %s \n[*] dumping tweets for user %s" % (out_file_name, screen_name)
#print "[*] dumping tweets for user %s" % screen_name,
max_requests = 5
requests_made = 0
tweet_count = 0
while True:
# get initial rate information
(remaining, rst_time_s, rst_time) = get_initial_rate_info()
while remaining > 0:
try:
(remaining, tweets) = get_tweets(screen_name, count, maxid)
except RateLimitError:
pass
except TweetDumpError, e:
pass
else:
requests_made += 1
if len(tweets) > 0:
for tweet in tweets:
maxid = tweet["id"]
out_file.write(u"%s %s: %s\n" % (tweet["created_at"], maxid, repr(tweet["text"])))
tweet_count += 1
else:
print "[*] reached end of tweets"
break
break
print "[*] %d tweets dumped!" % tweet_count
| TweetDumpError | identifier_name |
tweet-dump.py | """
Copyright (c) 2012 Casey Dunham <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
__author__ = 'Casey Dunham <[email protected]>'
__version__ = '0.1'
import argparse
import urllib
import sys
from urllib2 import (Request, urlopen, HTTPError, URLError)
try:
# Python >= 2.6
import json
except ImportError:
try:
# Python < 2.6
import simplejson as json
except ImportError:
try:
# Google App Engine
from django.utils import simplejson as json
except ImportError:
raise ImportError, "Unable to load a json library"
class TweetDumpError(Exception):
@property
def message(self):
return self.args[0]
class RateLimitError(TweetDumpError):
pass
API_URL = "https://api.twitter.com/1/statuses/user_timeline.json?%s"
# we are not authenticating so this will return the rate limit based on our IP
# see (https://dev.twitter.com/docs/api/1/get/account/rate_limit_status)
RATE_LIMIT_API_URL = "https://api.twitter.com/1/account/rate_limit_status.json"
parser = argparse.ArgumentParser(description="dump all tweets from user")
parser.add_argument("handle", type=str, help="twitter screen name")
def get_tweets(screen_name, count, maxid=None):
params = {
"screen_name": screen_name,
"count": count,
"exclude_replies": "true",
"include_rts": "true"
}
# if we include the max_id from the last tweet we retrieved, we will retrieve the same tweet again
# so decrement it by one to not retrieve duplicate tweets
if maxid:
params["max_id"] = int(maxid) - 1
encoded_params = urllib.urlencode(params)
query = API_URL % encoded_params
resp = fetch_url(query)
ratelimit_limit = resp.headers["X-RateLimit-Limit"]
ratelimit_remaining = resp.headers["X-RateLimit-Remaining"]
ratelimit_reset = resp.headers["X-RateLimit-Reset"]
tweets = json.loads(resp.read())
return ratelimit_remaining, tweets
def get_initial_rate_info():
resp = fetch_url(RATE_LIMIT_API_URL)
rate_info = json.loads(resp.read())
return rate_info["remaining_hits"], rate_info["reset_time_in_seconds"], rate_info["reset_time"]
def fetch_url(url):
try:
return urlopen(Request(url))
except HTTPError, e:
if e.code == 400: # twitter api limit reached
raise RateLimitError(e.code)
if e.code == 502: # Bad Gateway, sometimes get this when making requests. just try again
raise TweetDumpError(e.code)
print >> sys.stderr, "[!] HTTP Error %s: %s" % (e.code, e.msg)
except URLError, e:
print >> sys.stderr, "[!] URL Error: %s URL: %s" % (e.reason, url)
exit(1)
def print_banner():
print "tweet-dump %s (c) 2012 %s" % (__version__, __author__)
print """ .-.
(. .)__,')
/ V )
\ ( \/ .
`._`.__\\ o ,
<< `' .o..
"""
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="tweet-dump")
parser.add_argument('username', help="Twitter Screen Name")
parser.add_argument('file', help="File to write tweeets to")
parser.add_argument('--count', help="Number of tweets to retrieve per request", default=200)
parser.add_argument('--maxid', help="ID of Tweet to start dumping after", default=None)
args = parser.parse_args()
screen_name = args.username
count = args.count
maxid = args.maxid
out_file_name = args.file
out_file = None
try:
out_file = open(out_file_name, 'w')
except IOError, e:
print >> sys.stderr, "[!] error creating file %s" % out_file_name
exit(1)
print_banner()
print "[*] writing tweets to %s \n[*] dumping tweets for user %s" % (out_file_name, screen_name)
#print "[*] dumping tweets for user %s" % screen_name,
max_requests = 5
requests_made = 0
tweet_count = 0
while True:
# get initial rate information
| break
print "[*] %d tweets dumped!" % tweet_count
| (remaining, rst_time_s, rst_time) = get_initial_rate_info()
while remaining > 0:
try:
(remaining, tweets) = get_tweets(screen_name, count, maxid)
except RateLimitError:
pass
except TweetDumpError, e:
pass
else:
requests_made += 1
if len(tweets) > 0:
for tweet in tweets:
maxid = tweet["id"]
out_file.write(u"%s %s: %s\n" % (tweet["created_at"], maxid, repr(tweet["text"])))
tweet_count += 1
else:
print "[*] reached end of tweets"
break
| conditional_block |
tweet-dump.py | """
Copyright (c) 2012 Casey Dunham <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
__author__ = 'Casey Dunham <[email protected]>'
__version__ = '0.1'
import argparse
import urllib
import sys
from urllib2 import (Request, urlopen, HTTPError, URLError)
try:
# Python >= 2.6
import json
except ImportError:
try:
# Python < 2.6
import simplejson as json
except ImportError:
try:
# Google App Engine
from django.utils import simplejson as json
except ImportError:
raise ImportError, "Unable to load a json library"
class TweetDumpError(Exception):
@property
def message(self):
return self.args[0]
class RateLimitError(TweetDumpError):
pass
API_URL = "https://api.twitter.com/1/statuses/user_timeline.json?%s"
# we are not authenticating so this will return the rate limit based on our IP
# see (https://dev.twitter.com/docs/api/1/get/account/rate_limit_status)
RATE_LIMIT_API_URL = "https://api.twitter.com/1/account/rate_limit_status.json"
parser = argparse.ArgumentParser(description="dump all tweets from user")
parser.add_argument("handle", type=str, help="twitter screen name")
def get_tweets(screen_name, count, maxid=None):
params = {
"screen_name": screen_name,
"count": count,
"exclude_replies": "true",
"include_rts": "true"
}
# if we include the max_id from the last tweet we retrieved, we will retrieve the same tweet again
# so decrement it by one to not retrieve duplicate tweets
if maxid:
params["max_id"] = int(maxid) - 1
encoded_params = urllib.urlencode(params)
query = API_URL % encoded_params
resp = fetch_url(query)
ratelimit_limit = resp.headers["X-RateLimit-Limit"]
ratelimit_remaining = resp.headers["X-RateLimit-Remaining"]
ratelimit_reset = resp.headers["X-RateLimit-Reset"]
tweets = json.loads(resp.read())
return ratelimit_remaining, tweets
def get_initial_rate_info():
resp = fetch_url(RATE_LIMIT_API_URL)
rate_info = json.loads(resp.read())
return rate_info["remaining_hits"], rate_info["reset_time_in_seconds"], rate_info["reset_time"]
def fetch_url(url):
try:
return urlopen(Request(url))
except HTTPError, e:
if e.code == 400: # twitter api limit reached
raise RateLimitError(e.code)
if e.code == 502: # Bad Gateway, sometimes get this when making requests. just try again
raise TweetDumpError(e.code)
print >> sys.stderr, "[!] HTTP Error %s: %s" % (e.code, e.msg)
except URLError, e:
print >> sys.stderr, "[!] URL Error: %s URL: %s" % (e.reason, url)
exit(1)
def print_banner():
print "tweet-dump %s (c) 2012 %s" % (__version__, __author__)
print """ .-.
(. .)__,')
/ V )
\ ( \/ .
`._`.__\\ o ,
<< `' .o..
"""
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="tweet-dump")
parser.add_argument('username', help="Twitter Screen Name")
parser.add_argument('file', help="File to write tweeets to")
parser.add_argument('--count', help="Number of tweets to retrieve per request", default=200)
parser.add_argument('--maxid', help="ID of Tweet to start dumping after", default=None)
args = parser.parse_args()
screen_name = args.username
count = args.count
maxid = args.maxid
out_file_name = args.file
out_file = None
try:
out_file = open(out_file_name, 'w')
except IOError, e:
print >> sys.stderr, "[!] error creating file %s" % out_file_name
exit(1)
print_banner()
print "[*] writing tweets to %s \n[*] dumping tweets for user %s" % (out_file_name, screen_name)
#print "[*] dumping tweets for user %s" % screen_name,
max_requests = 5
requests_made = 0
tweet_count = 0
| while True:
# get initial rate information
(remaining, rst_time_s, rst_time) = get_initial_rate_info()
while remaining > 0:
try:
(remaining, tweets) = get_tweets(screen_name, count, maxid)
except RateLimitError:
pass
except TweetDumpError, e:
pass
else:
requests_made += 1
if len(tweets) > 0:
for tweet in tweets:
maxid = tweet["id"]
out_file.write(u"%s %s: %s\n" % (tweet["created_at"], maxid, repr(tweet["text"])))
tweet_count += 1
else:
print "[*] reached end of tweets"
break
break
print "[*] %d tweets dumped!" % tweet_count | random_line_split |
|
post.js | (function() {
var Post, create, edit;
Post = function() {
this.title = "";
this.content = "";
this.author = "";
this.categories = [];
this.tags = [];
this.date = "";
this.modified = "";
return this.published = true;
};
create = function(title, content, categories, tags, published) {
var post;
post = new Post();
post.title = title;
post.content = content;
post.categories = categories;
post.tags = tags;
post.published = published;
post.date = Date.now();
return post;
};
edit = function(title, content, categories, tags, published) {
var modified, post;
post = new Post();
title = title; | tags = tags;
published = published;
modified = Date.now();
return post;
};
exports.create = create;
exports.edit = edit;
}).call(this); | content = content;
categories = categories; | random_line_split |
rscope.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.
use middle::ty;
use std::cell::Cell;
use syntax::ast;
use syntax::codemap::Span;
/// Defines strategies for handling regions that are omitted. For
/// example, if one writes the type `&Foo`, then the lifetime of
/// this reference has been omitted. When converting this
/// type, the generic functions in astconv will invoke `anon_regions`
/// on the provided region-scope to decide how to translate this
/// omitted region.
///
/// It is not always legal to omit regions, therefore `anon_regions`
/// can return `Err(())` to indicate that this is not a scope in which
/// regions can legally be omitted.
pub trait RegionScope {
fn anon_regions(&self,
span: Span,
count: uint)
-> Result<Vec<ty::Region> , ()>;
}
// A scope in which all regions must be explicitly named
pub struct ExplicitRscope;
impl RegionScope for ExplicitRscope {
fn anon_regions(&self,
_span: Span,
_count: uint)
-> Result<Vec<ty::Region> , ()> {
Err(())
}
}
/// A scope in which we generate anonymous, late-bound regions for
/// omitted regions. This occurs in function signatures.
pub struct BindingRscope {
binder_id: ast::NodeId,
anon_bindings: Cell<uint>,
}
impl BindingRscope {
pub fn new(binder_id: ast::NodeId) -> BindingRscope {
BindingRscope {
binder_id: binder_id,
anon_bindings: Cell::new(0),
}
}
}
impl RegionScope for BindingRscope {
fn anon_regions(&self,
_: Span,
count: uint)
-> Result<Vec<ty::Region>, ()> {
let idx = self.anon_bindings.get();
self.anon_bindings.set(idx + count);
Ok(Vec::from_fn(count, |i| ty::ReLateBound(self.binder_id,
ty::BrAnon(idx + i))))
}
}
/// A scope in which we generate one specific region. This occurs after the
/// `->` (i.e. in the return type) of function signatures.
pub struct ImpliedSingleRscope {
pub region: ty::Region,
}
impl RegionScope for ImpliedSingleRscope {
fn | (&self, _: Span, count: uint)
-> Result<Vec<ty::Region>,()> {
Ok(Vec::from_elem(count, self.region.clone()))
}
}
| anon_regions | identifier_name |
rscope.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.
use middle::ty;
use std::cell::Cell;
use syntax::ast;
use syntax::codemap::Span;
/// Defines strategies for handling regions that are omitted. For
/// example, if one writes the type `&Foo`, then the lifetime of
/// this reference has been omitted. When converting this
/// type, the generic functions in astconv will invoke `anon_regions`
/// on the provided region-scope to decide how to translate this
/// omitted region.
///
/// It is not always legal to omit regions, therefore `anon_regions`
/// can return `Err(())` to indicate that this is not a scope in which
/// regions can legally be omitted.
pub trait RegionScope {
fn anon_regions(&self,
span: Span,
count: uint)
-> Result<Vec<ty::Region> , ()>;
}
// A scope in which all regions must be explicitly named
pub struct ExplicitRscope;
impl RegionScope for ExplicitRscope {
fn anon_regions(&self,
_span: Span,
_count: uint)
-> Result<Vec<ty::Region> , ()> {
Err(())
}
}
/// A scope in which we generate anonymous, late-bound regions for
/// omitted regions. This occurs in function signatures.
pub struct BindingRscope {
binder_id: ast::NodeId,
anon_bindings: Cell<uint>,
}
impl BindingRscope {
pub fn new(binder_id: ast::NodeId) -> BindingRscope {
BindingRscope {
binder_id: binder_id,
anon_bindings: Cell::new(0),
}
}
}
impl RegionScope for BindingRscope {
fn anon_regions(&self,
_: Span,
count: uint)
-> Result<Vec<ty::Region>, ()> {
let idx = self.anon_bindings.get();
self.anon_bindings.set(idx + count);
Ok(Vec::from_fn(count, |i| ty::ReLateBound(self.binder_id,
ty::BrAnon(idx + i))))
}
}
/// A scope in which we generate one specific region. This occurs after the
/// `->` (i.e. in the return type) of function signatures.
pub struct ImpliedSingleRscope {
pub region: ty::Region,
}
impl RegionScope for ImpliedSingleRscope {
fn anon_regions(&self, _: Span, count: uint)
-> Result<Vec<ty::Region>,()> {
Ok(Vec::from_elem(count, self.region.clone()))
} | } | random_line_split |
|
parser.js | //process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); });
var fs = require('fs');
(function () {
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
}
var DocGen = {
filesArr: null,
files: {},
functions: [],
nbLoaded: 0,
init: function (files) {
this.filesArr = files;
},
start: function () {
for (var i=0, len=this.filesArr.length; i<len; i++) {
var file = this.filesArr[i];
this.processFile(file);
}
},
fileLoaded: function() {
this.nbLoaded++;
if (this.nbLoaded == this.filesArr.length) {
this.exportHtml();
}
},
getSignatures: function (m) {
var sig = null;
var signatures = [];
var rSig = /\\*\s?(@sig\s.*)\n/gi;
while (sig = rSig.exec(m)) {
var params = [];
var rParam = /(\w+):(\w+)/gi;
while (param = rParam.exec(sig[1])) {
var name = param[1];
var type = param[2];
params.push({ name: name, type: type });
}
if (params.length >= 1) {
ret = params.pop();
}
signatures.push({ params: params, ret: ret});
}
return signatures;
},
extractInfos: function (m) {
var self = this;
var fun = m[2];
var rFun = /['|"]?([a-zA-Z0-9._-]+)['|"]?\s?:\s?function\s?\(.*\)\s?{/gi;
var isFun = rFun.exec(fun);
if (!isFun) {
rFun = /socket\.on\(['|"]([a-zA-Z0-9._-]+)['|"]\s?,\s?function\s?\(.*\)\s?{/gi;
isFun = rFun.exec(fun);
}
if (isFun) {
var comment = m[1];
var name = isFun[1];
var sigs = self.getSignatures(comment);
var desc = (/\*\s(.*?)\n/gi).exec(m[1])[1];
var f = { name: name, description: desc, sigs: sigs };
return f;
}
return null;
},
processFile: function (file) {
var self = this;
// Get the file in a buffer
fs.readFile(file, function(err, data) {
var buf = data.toString('binary');
var functions = [];
// Get all long comment ( /** )
var rgx = new RegExp("/\\*\\*\n([a-zA-Z0-9 -_\n\t]*)\\*/\n(.*)\n", "gi");
while (m = rgx.exec(buf)) {
info = self.extractInfos(m);
if (info) {
functions.push(info);
}
}
self.files[file] = { functions: functions }; |
self.fileLoaded();
});
},
sortFunctions: function (fun1, fun2) {
var name1 = fun1.name.toLowerCase();
var name2 = fun2.name.toLowerCase();
if (name1 < name2) { return -1; }
else if (name1 > name2) { return 1; }
else { return 0; }
},
exportHtml: function() {
for (var fileName in this.files) {
var file = this.files[fileName];
file.functions.sort(this.sortFunctions);
console.log(fileName, file.functions.length);
var html = '<!DOCTYPE html>\n' +
'<html>\n' +
'<head>\n' +
' <title></title>\n' +
' <link rel="stylesheet" href="css/reset.css" type="text/css" media="screen" charset="utf-8" />\n' +
' <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />\n' +
//' <script src="js/scripts.js" type="text/javascript"></script>' +
'</head>\n' +
'<body>\n' +
'\n' +
'<div class="menu" id="menu">\n' +
' <h1>Files</h1>\n' +
' <ul>\n';
for (var f in this.files) {
html += ' <li><a href="'+f+'.html">'+f+'</a></li>\n';
}
html += ' </ul>\n' +
' <h1>Functions</h1>\n' +
' <ul>\n';
for (var i=0, len=file.functions.length; i<len; i++) {
html += ' <li><a href="#'+slugify(file.functions[i].name)+'">'+file.functions[i].name+'</a></li>\n';
}
html += ' </ul>\n'
html += '</div>\n' +
'<div id="page">\n' +
' <div class="content">\n';
for (var i=0, len=file.functions.length; i<len; i++) {
var fn = file.functions[i];
if (fn.sigs.length > 0) {
html += '<h3><a name="'+slugify(fn.name)+'">'+fn.name+'</a></h3>\n';
html += '<span class="signature">\n';
for (var s=0, len2=fn.sigs.length; s<len2; s++) {
var sig = fn.sigs[s];
html += '<span class="name">'+fn.name+'</span> ( ';
for (var p=0, len3=sig.params.length; p<len3; p++) {
var param = sig.params[p];
html += '<span class="param">'+param.name+'</span>:<span class="type">'+param.type+'</span>, ';
}
html = html.substr(0, html.length-2);
html += ' ) : <span class="param">'+sig.ret.name+'</span>:<span class="type">'+sig.ret.type+'</span><br />';
}
html = html.substr(0, html.length-6);
html += '</span>\n';
html += '<p>'+fn.description+'</p>';
}
}
html += ' </div>\n' +
'</div>\n' +
'\n' +
'</body>\n'
'</html>';
fs.writeFile('doc/'+fileName+'.html', html);
}
}
};
var files = ['sockets.js', 'database_operations.js'];
DocGen.init(files);
DocGen.start();
})(); | random_line_split |
|
parser.js | //process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); });
var fs = require('fs');
(function () {
function slugify(text) |
var DocGen = {
filesArr: null,
files: {},
functions: [],
nbLoaded: 0,
init: function (files) {
this.filesArr = files;
},
start: function () {
for (var i=0, len=this.filesArr.length; i<len; i++) {
var file = this.filesArr[i];
this.processFile(file);
}
},
fileLoaded: function() {
this.nbLoaded++;
if (this.nbLoaded == this.filesArr.length) {
this.exportHtml();
}
},
getSignatures: function (m) {
var sig = null;
var signatures = [];
var rSig = /\\*\s?(@sig\s.*)\n/gi;
while (sig = rSig.exec(m)) {
var params = [];
var rParam = /(\w+):(\w+)/gi;
while (param = rParam.exec(sig[1])) {
var name = param[1];
var type = param[2];
params.push({ name: name, type: type });
}
if (params.length >= 1) {
ret = params.pop();
}
signatures.push({ params: params, ret: ret});
}
return signatures;
},
extractInfos: function (m) {
var self = this;
var fun = m[2];
var rFun = /['|"]?([a-zA-Z0-9._-]+)['|"]?\s?:\s?function\s?\(.*\)\s?{/gi;
var isFun = rFun.exec(fun);
if (!isFun) {
rFun = /socket\.on\(['|"]([a-zA-Z0-9._-]+)['|"]\s?,\s?function\s?\(.*\)\s?{/gi;
isFun = rFun.exec(fun);
}
if (isFun) {
var comment = m[1];
var name = isFun[1];
var sigs = self.getSignatures(comment);
var desc = (/\*\s(.*?)\n/gi).exec(m[1])[1];
var f = { name: name, description: desc, sigs: sigs };
return f;
}
return null;
},
processFile: function (file) {
var self = this;
// Get the file in a buffer
fs.readFile(file, function(err, data) {
var buf = data.toString('binary');
var functions = [];
// Get all long comment ( /** )
var rgx = new RegExp("/\\*\\*\n([a-zA-Z0-9 -_\n\t]*)\\*/\n(.*)\n", "gi");
while (m = rgx.exec(buf)) {
info = self.extractInfos(m);
if (info) {
functions.push(info);
}
}
self.files[file] = { functions: functions };
self.fileLoaded();
});
},
sortFunctions: function (fun1, fun2) {
var name1 = fun1.name.toLowerCase();
var name2 = fun2.name.toLowerCase();
if (name1 < name2) { return -1; }
else if (name1 > name2) { return 1; }
else { return 0; }
},
exportHtml: function() {
for (var fileName in this.files) {
var file = this.files[fileName];
file.functions.sort(this.sortFunctions);
console.log(fileName, file.functions.length);
var html = '<!DOCTYPE html>\n' +
'<html>\n' +
'<head>\n' +
' <title></title>\n' +
' <link rel="stylesheet" href="css/reset.css" type="text/css" media="screen" charset="utf-8" />\n' +
' <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />\n' +
//' <script src="js/scripts.js" type="text/javascript"></script>' +
'</head>\n' +
'<body>\n' +
'\n' +
'<div class="menu" id="menu">\n' +
' <h1>Files</h1>\n' +
' <ul>\n';
for (var f in this.files) {
html += ' <li><a href="'+f+'.html">'+f+'</a></li>\n';
}
html += ' </ul>\n' +
' <h1>Functions</h1>\n' +
' <ul>\n';
for (var i=0, len=file.functions.length; i<len; i++) {
html += ' <li><a href="#'+slugify(file.functions[i].name)+'">'+file.functions[i].name+'</a></li>\n';
}
html += ' </ul>\n'
html += '</div>\n' +
'<div id="page">\n' +
' <div class="content">\n';
for (var i=0, len=file.functions.length; i<len; i++) {
var fn = file.functions[i];
if (fn.sigs.length > 0) {
html += '<h3><a name="'+slugify(fn.name)+'">'+fn.name+'</a></h3>\n';
html += '<span class="signature">\n';
for (var s=0, len2=fn.sigs.length; s<len2; s++) {
var sig = fn.sigs[s];
html += '<span class="name">'+fn.name+'</span> ( ';
for (var p=0, len3=sig.params.length; p<len3; p++) {
var param = sig.params[p];
html += '<span class="param">'+param.name+'</span>:<span class="type">'+param.type+'</span>, ';
}
html = html.substr(0, html.length-2);
html += ' ) : <span class="param">'+sig.ret.name+'</span>:<span class="type">'+sig.ret.type+'</span><br />';
}
html = html.substr(0, html.length-6);
html += '</span>\n';
html += '<p>'+fn.description+'</p>';
}
}
html += ' </div>\n' +
'</div>\n' +
'\n' +
'</body>\n'
'</html>';
fs.writeFile('doc/'+fileName+'.html', html);
}
}
};
var files = ['sockets.js', 'database_operations.js'];
DocGen.init(files);
DocGen.start();
})();
| {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
} | identifier_body |
parser.js | //process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); });
var fs = require('fs');
(function () {
function | (text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
}
var DocGen = {
filesArr: null,
files: {},
functions: [],
nbLoaded: 0,
init: function (files) {
this.filesArr = files;
},
start: function () {
for (var i=0, len=this.filesArr.length; i<len; i++) {
var file = this.filesArr[i];
this.processFile(file);
}
},
fileLoaded: function() {
this.nbLoaded++;
if (this.nbLoaded == this.filesArr.length) {
this.exportHtml();
}
},
getSignatures: function (m) {
var sig = null;
var signatures = [];
var rSig = /\\*\s?(@sig\s.*)\n/gi;
while (sig = rSig.exec(m)) {
var params = [];
var rParam = /(\w+):(\w+)/gi;
while (param = rParam.exec(sig[1])) {
var name = param[1];
var type = param[2];
params.push({ name: name, type: type });
}
if (params.length >= 1) {
ret = params.pop();
}
signatures.push({ params: params, ret: ret});
}
return signatures;
},
extractInfos: function (m) {
var self = this;
var fun = m[2];
var rFun = /['|"]?([a-zA-Z0-9._-]+)['|"]?\s?:\s?function\s?\(.*\)\s?{/gi;
var isFun = rFun.exec(fun);
if (!isFun) {
rFun = /socket\.on\(['|"]([a-zA-Z0-9._-]+)['|"]\s?,\s?function\s?\(.*\)\s?{/gi;
isFun = rFun.exec(fun);
}
if (isFun) {
var comment = m[1];
var name = isFun[1];
var sigs = self.getSignatures(comment);
var desc = (/\*\s(.*?)\n/gi).exec(m[1])[1];
var f = { name: name, description: desc, sigs: sigs };
return f;
}
return null;
},
processFile: function (file) {
var self = this;
// Get the file in a buffer
fs.readFile(file, function(err, data) {
var buf = data.toString('binary');
var functions = [];
// Get all long comment ( /** )
var rgx = new RegExp("/\\*\\*\n([a-zA-Z0-9 -_\n\t]*)\\*/\n(.*)\n", "gi");
while (m = rgx.exec(buf)) {
info = self.extractInfos(m);
if (info) {
functions.push(info);
}
}
self.files[file] = { functions: functions };
self.fileLoaded();
});
},
sortFunctions: function (fun1, fun2) {
var name1 = fun1.name.toLowerCase();
var name2 = fun2.name.toLowerCase();
if (name1 < name2) { return -1; }
else if (name1 > name2) { return 1; }
else { return 0; }
},
exportHtml: function() {
for (var fileName in this.files) {
var file = this.files[fileName];
file.functions.sort(this.sortFunctions);
console.log(fileName, file.functions.length);
var html = '<!DOCTYPE html>\n' +
'<html>\n' +
'<head>\n' +
' <title></title>\n' +
' <link rel="stylesheet" href="css/reset.css" type="text/css" media="screen" charset="utf-8" />\n' +
' <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />\n' +
//' <script src="js/scripts.js" type="text/javascript"></script>' +
'</head>\n' +
'<body>\n' +
'\n' +
'<div class="menu" id="menu">\n' +
' <h1>Files</h1>\n' +
' <ul>\n';
for (var f in this.files) {
html += ' <li><a href="'+f+'.html">'+f+'</a></li>\n';
}
html += ' </ul>\n' +
' <h1>Functions</h1>\n' +
' <ul>\n';
for (var i=0, len=file.functions.length; i<len; i++) {
html += ' <li><a href="#'+slugify(file.functions[i].name)+'">'+file.functions[i].name+'</a></li>\n';
}
html += ' </ul>\n'
html += '</div>\n' +
'<div id="page">\n' +
' <div class="content">\n';
for (var i=0, len=file.functions.length; i<len; i++) {
var fn = file.functions[i];
if (fn.sigs.length > 0) {
html += '<h3><a name="'+slugify(fn.name)+'">'+fn.name+'</a></h3>\n';
html += '<span class="signature">\n';
for (var s=0, len2=fn.sigs.length; s<len2; s++) {
var sig = fn.sigs[s];
html += '<span class="name">'+fn.name+'</span> ( ';
for (var p=0, len3=sig.params.length; p<len3; p++) {
var param = sig.params[p];
html += '<span class="param">'+param.name+'</span>:<span class="type">'+param.type+'</span>, ';
}
html = html.substr(0, html.length-2);
html += ' ) : <span class="param">'+sig.ret.name+'</span>:<span class="type">'+sig.ret.type+'</span><br />';
}
html = html.substr(0, html.length-6);
html += '</span>\n';
html += '<p>'+fn.description+'</p>';
}
}
html += ' </div>\n' +
'</div>\n' +
'\n' +
'</body>\n'
'</html>';
fs.writeFile('doc/'+fileName+'.html', html);
}
}
};
var files = ['sockets.js', 'database_operations.js'];
DocGen.init(files);
DocGen.start();
})();
| slugify | identifier_name |
parser.js | //process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); });
var fs = require('fs');
(function () {
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
}
var DocGen = {
filesArr: null,
files: {},
functions: [],
nbLoaded: 0,
init: function (files) {
this.filesArr = files;
},
start: function () {
for (var i=0, len=this.filesArr.length; i<len; i++) {
var file = this.filesArr[i];
this.processFile(file);
}
},
fileLoaded: function() {
this.nbLoaded++;
if (this.nbLoaded == this.filesArr.length) {
this.exportHtml();
}
},
getSignatures: function (m) {
var sig = null;
var signatures = [];
var rSig = /\\*\s?(@sig\s.*)\n/gi;
while (sig = rSig.exec(m)) |
return signatures;
},
extractInfos: function (m) {
var self = this;
var fun = m[2];
var rFun = /['|"]?([a-zA-Z0-9._-]+)['|"]?\s?:\s?function\s?\(.*\)\s?{/gi;
var isFun = rFun.exec(fun);
if (!isFun) {
rFun = /socket\.on\(['|"]([a-zA-Z0-9._-]+)['|"]\s?,\s?function\s?\(.*\)\s?{/gi;
isFun = rFun.exec(fun);
}
if (isFun) {
var comment = m[1];
var name = isFun[1];
var sigs = self.getSignatures(comment);
var desc = (/\*\s(.*?)\n/gi).exec(m[1])[1];
var f = { name: name, description: desc, sigs: sigs };
return f;
}
return null;
},
processFile: function (file) {
var self = this;
// Get the file in a buffer
fs.readFile(file, function(err, data) {
var buf = data.toString('binary');
var functions = [];
// Get all long comment ( /** )
var rgx = new RegExp("/\\*\\*\n([a-zA-Z0-9 -_\n\t]*)\\*/\n(.*)\n", "gi");
while (m = rgx.exec(buf)) {
info = self.extractInfos(m);
if (info) {
functions.push(info);
}
}
self.files[file] = { functions: functions };
self.fileLoaded();
});
},
sortFunctions: function (fun1, fun2) {
var name1 = fun1.name.toLowerCase();
var name2 = fun2.name.toLowerCase();
if (name1 < name2) { return -1; }
else if (name1 > name2) { return 1; }
else { return 0; }
},
exportHtml: function() {
for (var fileName in this.files) {
var file = this.files[fileName];
file.functions.sort(this.sortFunctions);
console.log(fileName, file.functions.length);
var html = '<!DOCTYPE html>\n' +
'<html>\n' +
'<head>\n' +
' <title></title>\n' +
' <link rel="stylesheet" href="css/reset.css" type="text/css" media="screen" charset="utf-8" />\n' +
' <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />\n' +
//' <script src="js/scripts.js" type="text/javascript"></script>' +
'</head>\n' +
'<body>\n' +
'\n' +
'<div class="menu" id="menu">\n' +
' <h1>Files</h1>\n' +
' <ul>\n';
for (var f in this.files) {
html += ' <li><a href="'+f+'.html">'+f+'</a></li>\n';
}
html += ' </ul>\n' +
' <h1>Functions</h1>\n' +
' <ul>\n';
for (var i=0, len=file.functions.length; i<len; i++) {
html += ' <li><a href="#'+slugify(file.functions[i].name)+'">'+file.functions[i].name+'</a></li>\n';
}
html += ' </ul>\n'
html += '</div>\n' +
'<div id="page">\n' +
' <div class="content">\n';
for (var i=0, len=file.functions.length; i<len; i++) {
var fn = file.functions[i];
if (fn.sigs.length > 0) {
html += '<h3><a name="'+slugify(fn.name)+'">'+fn.name+'</a></h3>\n';
html += '<span class="signature">\n';
for (var s=0, len2=fn.sigs.length; s<len2; s++) {
var sig = fn.sigs[s];
html += '<span class="name">'+fn.name+'</span> ( ';
for (var p=0, len3=sig.params.length; p<len3; p++) {
var param = sig.params[p];
html += '<span class="param">'+param.name+'</span>:<span class="type">'+param.type+'</span>, ';
}
html = html.substr(0, html.length-2);
html += ' ) : <span class="param">'+sig.ret.name+'</span>:<span class="type">'+sig.ret.type+'</span><br />';
}
html = html.substr(0, html.length-6);
html += '</span>\n';
html += '<p>'+fn.description+'</p>';
}
}
html += ' </div>\n' +
'</div>\n' +
'\n' +
'</body>\n'
'</html>';
fs.writeFile('doc/'+fileName+'.html', html);
}
}
};
var files = ['sockets.js', 'database_operations.js'];
DocGen.init(files);
DocGen.start();
})();
| {
var params = [];
var rParam = /(\w+):(\w+)/gi;
while (param = rParam.exec(sig[1])) {
var name = param[1];
var type = param[2];
params.push({ name: name, type: type });
}
if (params.length >= 1) {
ret = params.pop();
}
signatures.push({ params: params, ret: ret});
} | conditional_block |
player.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Rodrigo Silva (MestreLion) <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. See <http://www.gnu.org/licenses/gpl.html>
'''Player class'''
import logging
from . import g
from . import rnd
from . import enum2 as enum
log = logging.getLogger(__name__)
class HUNGER(enum.Enum):
'''Minimum food in stomach before some effect or warning
Values represent the last "safe" food amount before the step
'''
HUNGRY = 300 # WEAK * 2 in DOS. No effect, just a warning.
WEAK = 150 # No effect either, just the warning
FAINT = 0 # Start fainting. Unix: 20
STARVE = -851 # Die of starvation. Unix: 0. Ouch! :)
# This is the effective value in DOS, intended was probably -850
@classmethod
def name(cls, v):
if v == cls.STARVE: return "?" # Per DOS code, but never seen by player
return super(HUNGER, cls).name(v)
class Player(object):
# Constants
char = "@" # Display character
ac = 1 # Armor Class when wearing no armor
stomach = 2000 # Stomach size, how much food can the player have
xplevels = tuple(10*2**xplevels for xplevels in range(19)) + (0,)
def __init__(self, name, screen=None):
self.name = name
# Input and output
self.screen = screen
# Map and position
self.level = None
self.row = 0
self.col = 0
# Items
self.armor = None # Worn armor
self.weapon = None # Wielded weapon
self.ringright = None # Ring on right hand
self.ringleft = None # Ring on left hand
self.pack = [] # Inventory (list of items)
# Main status
self.hp = 12 # Current hit points left (life)
self.hpmax = 12 # Maximum hit points
self.str = 16 # Current strength
self.strmax = 16 # Maximum strength
self.gold = 0 # Gold (purse)
self.xp = 0 # Experience points
self.xplevel = 1 # Experience level
# Food left in stomach. Fixed 1250 in Unix
self.food = rnd.spread(1300)
# Condition status and flags
self.skipturns = 0 # Used by sleep, faint, freeze, etc
@property
def armorclass(self):
if self.armor is None:
return self.ac
else:
return self.armor.ac
@property
def hungerstage(self):
'''Name of the hunger stage, based on current food in stomach'''
# DOS: "Faint" in status bar is only displayed after player actually
# faints for the first time. This would require a private property,
# `hungry_stage` or similar, which would defeat the whole point
# of this function.
for food in HUNGER:
if self.food < food:
return HUNGER.name(food)
else:
|
@property
def metabolism(self):
'''How much food is consumed every turn.
Depends on current food, worn rings and screen width.
Some rings have random consumption, so this value may change
on every read!
'''
deltafood = 1
if self.food <= HUNGER.FAINT:
return deltafood
for ring in (self.ringleft,
self.ringright):
if ring is not None:
deltafood += ring.consumption
# DOS: 40 column mode use food twice as fast
if self.screen.size[1] <= 40:
deltafood *= 2
return deltafood
@property
def has_amulet(self):
return "AMULET" in self.pack # @@fake
# ACTIONS ###########
def move(self, dr, dc):
row = self.row + dr
col = self.col + dc
if not self.level.is_passable(row, col):
return
# Update current tile
self.level.reveal(self.row, self.col)
# Update to new position
self.row = row
self.col = col
self.level.draw(self)
self.level.tick()
def rest(self):
'''Do nothing for a turn'''
self.level.tick()
def show_inventory(self):
dialog = self.screen.dialog()
for item in self.pack:
dialog.addline(item)
dialog.show()
# DAEMONS ###########
def heal(self):
pass
def digest(self):
'''Deplete food in stomach'''
# Unix has very different mechanics, specially on fainting and rings
oldfood = self.food
self.food -= self.metabolism
if self.food < HUNGER.STARVE:
raise g.Lose("Starvation")
if self.food < HUNGER.FAINT:
# 80% chance to avoid fainting, if not already
if self.skipturns > 0 or rnd.perc(80):
return
# Faint for a few turns
self.skipturns += rnd.rand(4, 11) # Harsh!
#@@ Disable running
#@@ Cancel multiple actions
# DOS 1.1: "%sYou faint", "You feel too weak from lack of food. "
self.screen.message("%sYou faint from the lack of food",
"You feel very weak. ")
return
if self.food < HUNGER.WEAK and oldfood >= HUNGER.WEAK:
self.screen.message("You are starting to feel weak")
elif self.food < HUNGER.HUNGRY and oldfood >= HUNGER.HUNGRY:
self.screen.message("You are starting to get hungry")
| return "" # All fine :) | conditional_block |
player.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Rodrigo Silva (MestreLion) <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. See <http://www.gnu.org/licenses/gpl.html>
'''Player class'''
import logging
from . import g
from . import rnd
from . import enum2 as enum
log = logging.getLogger(__name__)
class HUNGER(enum.Enum):
'''Minimum food in stomach before some effect or warning
Values represent the last "safe" food amount before the step
'''
HUNGRY = 300 # WEAK * 2 in DOS. No effect, just a warning.
WEAK = 150 # No effect either, just the warning
FAINT = 0 # Start fainting. Unix: 20
STARVE = -851 # Die of starvation. Unix: 0. Ouch! :)
# This is the effective value in DOS, intended was probably -850
@classmethod
def name(cls, v):
if v == cls.STARVE: return "?" # Per DOS code, but never seen by player
return super(HUNGER, cls).name(v)
class Player(object):
# Constants
char = "@" # Display character
ac = 1 # Armor Class when wearing no armor
stomach = 2000 # Stomach size, how much food can the player have
xplevels = tuple(10*2**xplevels for xplevels in range(19)) + (0,)
def __init__(self, name, screen=None):
self.name = name
# Input and output
self.screen = screen
# Map and position
self.level = None
self.row = 0
self.col = 0
# Items
self.armor = None # Worn armor
self.weapon = None # Wielded weapon
self.ringright = None # Ring on right hand
self.ringleft = None # Ring on left hand
self.pack = [] # Inventory (list of items)
# Main status
self.hp = 12 # Current hit points left (life)
self.hpmax = 12 # Maximum hit points
self.str = 16 # Current strength
self.strmax = 16 # Maximum strength
self.gold = 0 # Gold (purse)
self.xp = 0 # Experience points
self.xplevel = 1 # Experience level
# Food left in stomach. Fixed 1250 in Unix
self.food = rnd.spread(1300)
# Condition status and flags
self.skipturns = 0 # Used by sleep, faint, freeze, etc
@property
def armorclass(self):
if self.armor is None:
return self.ac
else:
return self.armor.ac
@property
def hungerstage(self):
'''Name of the hunger stage, based on current food in stomach'''
# DOS: "Faint" in status bar is only displayed after player actually
# faints for the first time. This would require a private property,
# `hungry_stage` or similar, which would defeat the whole point
# of this function.
for food in HUNGER:
if self.food < food:
return HUNGER.name(food)
else:
return "" # All fine :)
@property
def metabolism(self):
'''How much food is consumed every turn.
Depends on current food, worn rings and screen width.
Some rings have random consumption, so this value may change
on every read!
'''
deltafood = 1
if self.food <= HUNGER.FAINT:
return deltafood
for ring in (self.ringleft,
self.ringright):
if ring is not None:
deltafood += ring.consumption
# DOS: 40 column mode use food twice as fast
if self.screen.size[1] <= 40:
deltafood *= 2
return deltafood
@property
def has_amulet(self):
return "AMULET" in self.pack # @@fake
# ACTIONS ###########
def | (self, dr, dc):
row = self.row + dr
col = self.col + dc
if not self.level.is_passable(row, col):
return
# Update current tile
self.level.reveal(self.row, self.col)
# Update to new position
self.row = row
self.col = col
self.level.draw(self)
self.level.tick()
def rest(self):
'''Do nothing for a turn'''
self.level.tick()
def show_inventory(self):
dialog = self.screen.dialog()
for item in self.pack:
dialog.addline(item)
dialog.show()
# DAEMONS ###########
def heal(self):
pass
def digest(self):
'''Deplete food in stomach'''
# Unix has very different mechanics, specially on fainting and rings
oldfood = self.food
self.food -= self.metabolism
if self.food < HUNGER.STARVE:
raise g.Lose("Starvation")
if self.food < HUNGER.FAINT:
# 80% chance to avoid fainting, if not already
if self.skipturns > 0 or rnd.perc(80):
return
# Faint for a few turns
self.skipturns += rnd.rand(4, 11) # Harsh!
#@@ Disable running
#@@ Cancel multiple actions
# DOS 1.1: "%sYou faint", "You feel too weak from lack of food. "
self.screen.message("%sYou faint from the lack of food",
"You feel very weak. ")
return
if self.food < HUNGER.WEAK and oldfood >= HUNGER.WEAK:
self.screen.message("You are starting to feel weak")
elif self.food < HUNGER.HUNGRY and oldfood >= HUNGER.HUNGRY:
self.screen.message("You are starting to get hungry")
| move | identifier_name |
player.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Rodrigo Silva (MestreLion) <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. See <http://www.gnu.org/licenses/gpl.html>
'''Player class'''
import logging
from . import g
from . import rnd
from . import enum2 as enum
log = logging.getLogger(__name__)
class HUNGER(enum.Enum):
'''Minimum food in stomach before some effect or warning
Values represent the last "safe" food amount before the step
'''
HUNGRY = 300 # WEAK * 2 in DOS. No effect, just a warning.
WEAK = 150 # No effect either, just the warning
FAINT = 0 # Start fainting. Unix: 20
STARVE = -851 # Die of starvation. Unix: 0. Ouch! :)
# This is the effective value in DOS, intended was probably -850
@classmethod
def name(cls, v):
if v == cls.STARVE: return "?" # Per DOS code, but never seen by player
return super(HUNGER, cls).name(v)
class Player(object):
# Constants
char = "@" # Display character
ac = 1 # Armor Class when wearing no armor
stomach = 2000 # Stomach size, how much food can the player have
xplevels = tuple(10*2**xplevels for xplevels in range(19)) + (0,)
def __init__(self, name, screen=None):
self.name = name |
# Map and position
self.level = None
self.row = 0
self.col = 0
# Items
self.armor = None # Worn armor
self.weapon = None # Wielded weapon
self.ringright = None # Ring on right hand
self.ringleft = None # Ring on left hand
self.pack = [] # Inventory (list of items)
# Main status
self.hp = 12 # Current hit points left (life)
self.hpmax = 12 # Maximum hit points
self.str = 16 # Current strength
self.strmax = 16 # Maximum strength
self.gold = 0 # Gold (purse)
self.xp = 0 # Experience points
self.xplevel = 1 # Experience level
# Food left in stomach. Fixed 1250 in Unix
self.food = rnd.spread(1300)
# Condition status and flags
self.skipturns = 0 # Used by sleep, faint, freeze, etc
@property
def armorclass(self):
if self.armor is None:
return self.ac
else:
return self.armor.ac
@property
def hungerstage(self):
'''Name of the hunger stage, based on current food in stomach'''
# DOS: "Faint" in status bar is only displayed after player actually
# faints for the first time. This would require a private property,
# `hungry_stage` or similar, which would defeat the whole point
# of this function.
for food in HUNGER:
if self.food < food:
return HUNGER.name(food)
else:
return "" # All fine :)
@property
def metabolism(self):
'''How much food is consumed every turn.
Depends on current food, worn rings and screen width.
Some rings have random consumption, so this value may change
on every read!
'''
deltafood = 1
if self.food <= HUNGER.FAINT:
return deltafood
for ring in (self.ringleft,
self.ringright):
if ring is not None:
deltafood += ring.consumption
# DOS: 40 column mode use food twice as fast
if self.screen.size[1] <= 40:
deltafood *= 2
return deltafood
@property
def has_amulet(self):
return "AMULET" in self.pack # @@fake
# ACTIONS ###########
def move(self, dr, dc):
row = self.row + dr
col = self.col + dc
if not self.level.is_passable(row, col):
return
# Update current tile
self.level.reveal(self.row, self.col)
# Update to new position
self.row = row
self.col = col
self.level.draw(self)
self.level.tick()
def rest(self):
'''Do nothing for a turn'''
self.level.tick()
def show_inventory(self):
dialog = self.screen.dialog()
for item in self.pack:
dialog.addline(item)
dialog.show()
# DAEMONS ###########
def heal(self):
pass
def digest(self):
'''Deplete food in stomach'''
# Unix has very different mechanics, specially on fainting and rings
oldfood = self.food
self.food -= self.metabolism
if self.food < HUNGER.STARVE:
raise g.Lose("Starvation")
if self.food < HUNGER.FAINT:
# 80% chance to avoid fainting, if not already
if self.skipturns > 0 or rnd.perc(80):
return
# Faint for a few turns
self.skipturns += rnd.rand(4, 11) # Harsh!
#@@ Disable running
#@@ Cancel multiple actions
# DOS 1.1: "%sYou faint", "You feel too weak from lack of food. "
self.screen.message("%sYou faint from the lack of food",
"You feel very weak. ")
return
if self.food < HUNGER.WEAK and oldfood >= HUNGER.WEAK:
self.screen.message("You are starting to feel weak")
elif self.food < HUNGER.HUNGRY and oldfood >= HUNGER.HUNGRY:
self.screen.message("You are starting to get hungry") |
# Input and output
self.screen = screen | random_line_split |
player.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Rodrigo Silva (MestreLion) <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. See <http://www.gnu.org/licenses/gpl.html>
'''Player class'''
import logging
from . import g
from . import rnd
from . import enum2 as enum
log = logging.getLogger(__name__)
class HUNGER(enum.Enum):
'''Minimum food in stomach before some effect or warning
Values represent the last "safe" food amount before the step
'''
HUNGRY = 300 # WEAK * 2 in DOS. No effect, just a warning.
WEAK = 150 # No effect either, just the warning
FAINT = 0 # Start fainting. Unix: 20
STARVE = -851 # Die of starvation. Unix: 0. Ouch! :)
# This is the effective value in DOS, intended was probably -850
@classmethod
def name(cls, v):
if v == cls.STARVE: return "?" # Per DOS code, but never seen by player
return super(HUNGER, cls).name(v)
class Player(object):
# Constants
char = "@" # Display character
ac = 1 # Armor Class when wearing no armor
stomach = 2000 # Stomach size, how much food can the player have
xplevels = tuple(10*2**xplevels for xplevels in range(19)) + (0,)
def __init__(self, name, screen=None):
| self.str = 16 # Current strength
self.strmax = 16 # Maximum strength
self.gold = 0 # Gold (purse)
self.xp = 0 # Experience points
self.xplevel = 1 # Experience level
# Food left in stomach. Fixed 1250 in Unix
self.food = rnd.spread(1300)
# Condition status and flags
self.skipturns = 0 # Used by sleep, faint, freeze, etc
@property
def armorclass(self):
if self.armor is None:
return self.ac
else:
return self.armor.ac
@property
def hungerstage(self):
'''Name of the hunger stage, based on current food in stomach'''
# DOS: "Faint" in status bar is only displayed after player actually
# faints for the first time. This would require a private property,
# `hungry_stage` or similar, which would defeat the whole point
# of this function.
for food in HUNGER:
if self.food < food:
return HUNGER.name(food)
else:
return "" # All fine :)
@property
def metabolism(self):
'''How much food is consumed every turn.
Depends on current food, worn rings and screen width.
Some rings have random consumption, so this value may change
on every read!
'''
deltafood = 1
if self.food <= HUNGER.FAINT:
return deltafood
for ring in (self.ringleft,
self.ringright):
if ring is not None:
deltafood += ring.consumption
# DOS: 40 column mode use food twice as fast
if self.screen.size[1] <= 40:
deltafood *= 2
return deltafood
@property
def has_amulet(self):
return "AMULET" in self.pack # @@fake
# ACTIONS ###########
def move(self, dr, dc):
row = self.row + dr
col = self.col + dc
if not self.level.is_passable(row, col):
return
# Update current tile
self.level.reveal(self.row, self.col)
# Update to new position
self.row = row
self.col = col
self.level.draw(self)
self.level.tick()
def rest(self):
'''Do nothing for a turn'''
self.level.tick()
def show_inventory(self):
dialog = self.screen.dialog()
for item in self.pack:
dialog.addline(item)
dialog.show()
# DAEMONS ###########
def heal(self):
pass
def digest(self):
'''Deplete food in stomach'''
# Unix has very different mechanics, specially on fainting and rings
oldfood = self.food
self.food -= self.metabolism
if self.food < HUNGER.STARVE:
raise g.Lose("Starvation")
if self.food < HUNGER.FAINT:
# 80% chance to avoid fainting, if not already
if self.skipturns > 0 or rnd.perc(80):
return
# Faint for a few turns
self.skipturns += rnd.rand(4, 11) # Harsh!
#@@ Disable running
#@@ Cancel multiple actions
# DOS 1.1: "%sYou faint", "You feel too weak from lack of food. "
self.screen.message("%sYou faint from the lack of food",
"You feel very weak. ")
return
if self.food < HUNGER.WEAK and oldfood >= HUNGER.WEAK:
self.screen.message("You are starting to feel weak")
elif self.food < HUNGER.HUNGRY and oldfood >= HUNGER.HUNGRY:
self.screen.message("You are starting to get hungry")
| self.name = name
# Input and output
self.screen = screen
# Map and position
self.level = None
self.row = 0
self.col = 0
# Items
self.armor = None # Worn armor
self.weapon = None # Wielded weapon
self.ringright = None # Ring on right hand
self.ringleft = None # Ring on left hand
self.pack = [] # Inventory (list of items)
# Main status
self.hp = 12 # Current hit points left (life)
self.hpmax = 12 # Maximum hit points | identifier_body |
cli_options.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export declare class CliOptions {
basePath: string;
constructor({basePath}: {
basePath?: string;
});
}
export declare class | extends CliOptions {
i18nFormat: string | null;
locale: string | null;
outFile: string | null;
constructor({i18nFormat, locale, outFile}: {
i18nFormat?: string;
locale?: string;
outFile?: string;
});
}
export declare class NgcCliOptions extends CliOptions {
i18nFormat: string;
i18nFile: string;
locale: string;
missingTranslation: string;
constructor({i18nFormat, i18nFile, locale, missingTranslation, basePath}: {
i18nFormat?: string;
i18nFile?: string;
locale?: string;
missingTranslation?: string;
basePath?: string;
});
}
| I18nExtractionCliOptions | identifier_name |
cli_options.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export declare class CliOptions {
basePath: string;
constructor({basePath}: {
basePath?: string;
});
}
export declare class I18nExtractionCliOptions extends CliOptions {
i18nFormat: string | null;
locale: string | null;
outFile: string | null;
constructor({i18nFormat, locale, outFile}: {
i18nFormat?: string; | });
}
export declare class NgcCliOptions extends CliOptions {
i18nFormat: string;
i18nFile: string;
locale: string;
missingTranslation: string;
constructor({i18nFormat, i18nFile, locale, missingTranslation, basePath}: {
i18nFormat?: string;
i18nFile?: string;
locale?: string;
missingTranslation?: string;
basePath?: string;
});
} | locale?: string;
outFile?: string; | random_line_split |
edit-rule-setformat.component.ts | You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AfterViewInit, Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Alert} from '@common/util/alert.util';
import {StringUtil} from '@common/util/string.util';
import {EventBroadcaster} from '@common/event/event.broadcaster';
import {Field} from '@domain/data-preparation/pr-dataset';
import {SetFormatRule} from '@domain/data-preparation/prep-rules';
import {DataflowService} from '../../../../service/dataflow.service';
import {PrepSelectBoxCustomComponent} from '../../../../../util/prep-select-box-custom.component';
import {EditRuleComponent} from './edit-rule.component';
@Component({
selector: 'edit-rule-setformat',
templateUrl: './edit-rule-setformat.component.html'
})
export class EditRuleSetformatComponent extends EditRuleComponent implements OnInit, AfterViewInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public selectedFields: Field[] = [];
public timestampFormats: any = [];
public dsId: string = '';
public isGetTimestampRunning: boolean = false;
// 상태 저장용 T/F
public isFocus: boolean = false; // Input Focus 여부
public isTooltipShow: boolean = false; // Tooltip Show/Hide
public selectedTimestamp: string = '';
public customTimestamp: string; // custom format
private tempTimetampValue: string = '';
public defaultIndex: number = -1;
public colTypes: any = [];
@ViewChild(PrepSelectBoxCustomComponent)
protected _custom: PrepSelectBoxCustomComponent;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(protected broadCaster: EventBroadcaster,
protected elementRef: ElementRef,
protected injector: Injector,
protected dataflowService: DataflowService) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 컴포넌트 초기 실행
*/
public ngOnInit() {
super.ngOnInit();
} // function - ngOnInit
/**
* 화면 초기화
*/
public ngAfterViewInit() {
super.ngAfterViewInit();
} // function - ngAfterViewInit
/**
* 컴포넌트 제거
*/
public ngOnDestroy() {
super.ngOnDestroy();
} // function - ngOnDestroy
| Public Method - API
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* When timestamp format is selected
* @param data
*/
public selectItem(data) {
this.selectedTimestamp = data.value;
}
/**
* Get timestamp formats from server
*/
private getTimestampFormats() {
if (!this.isGetTimestampRunning) {
this.isGetTimestampRunning = true;
const cols = this.selectedFields.map((item) => {
return item.name
});
this.tempTimetampValue = this.selectedTimestamp;
this.dataflowService.getTimestampFormatSuggestions(this.dsId, {colNames: cols}).then((result) => {
const keyList = [];
for (const key in result) {
if (result.hasOwnProperty(key)) {
keyList.push(key);
}
}
this.timestampFormats = [];
for (const i in result[keyList[0]]) {
if (result[keyList[0]].hasOwnProperty(i)) {
this.timestampFormats.push({value: i, isHover: false, matchValue: result[keyList[0]][i]})
}
}
// When at least one column is selected or this.selectedTimestamp is not empty
this.selectedTimestamp = this.tempTimetampValue;
if (cols.length > 0 || '' !== this.tempTimetampValue) {
if ('' === this.tempTimetampValue && this.selectedFields[0]) {
const idx = this._getFieldNameArray().indexOf(this.selectedFields[0].name);
if (idx !== undefined && idx >= 0) {
this.selectedTimestamp = this.colTypes[idx].timestampStyle;
}
}
}
this.isGetTimestampRunning = false;
this.setSelectedTimestamp();
});
}
}
/**
* Set selected timestamp index in select box
*/
private setSelectedTimestamp() {
let tempnum: number = -1;
if (this.selectedTimestamp !== null && this.selectedTimestamp !== '' && -1 !== this._timestampValueArray().indexOf(this.selectedTimestamp)) {
tempnum = this._timestampValueArray().indexOf(this.tempTimetampValue);
}
this._custom.setSelectedItem(this.timestampFormats, this.selectedTimestamp, tempnum);
}
/**
* Rule 형식 정의 및 반환
* @return {{command: string, col: string, ruleString: string}}
*/
public getRuleData(): { command: string, ruleString: string, uiRuleString: SetFormatRule } {
// 선택된 컬럼
if (0 === this.selectedFields.length) {
Alert.warning(this.translateService.instant('msg.dp.alert.sel.col'));
return undefined;
}
if ('Custom format' === this.selectedTimestamp && '' === this.customTimestamp || '' === this.selectedTimestamp) {
Alert.warning(this.translateService.instant('msg.dp.alert.format.error'));
return undefined;
}
let ruleString = 'setformat col: '
+ this.getColumnNamesInArray(this.selectedFields, true).toString()
+ ' format: ';
let val: any = this.selectedTimestamp === 'Custom format' ? this.customTimestamp : this.selectedTimestamp;
const check = StringUtil.checkSingleQuote(val, {isPairQuote: false, isWrapQuote: true});
if (check[0] === false) {
Alert.warning(this.translateService.instant('msg.dp.alert.invalid.timestamp.val'));
return undefined;
} else {
val = check[1];
}
ruleString += val;
return {
command: 'setformat',
ruleString: ruleString,
uiRuleString: {
name: 'setformat',
col: this.getColumnNamesInArray(this.selectedFields),
format: this.selectedTimestamp === 'Custom format' ? this.customTimestamp : this.selectedTimestamp,
isBuilder: true
}
};
} // function - getRuleData
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* When selected column is changed
* @param {{target: Field, isSelect: boolean, selectedList: Field[]}} data
*/
public changeFields(data: { target?: Field, isSelect?: boolean, selectedList: Field[] }) {
this.selectedFields = data.selectedList;
this.selectedTimestamp = '';
if (0 === this.selectedFields.length) { // if theres nothing selected
this.selectedTimestamp = '';
this.defaultIndex = -1;
} else {
this.getTimestampFormats();
}
} // function - changeFields
/**
* 패턴 정보 레이어 표시
* @param {boolean} isShow
*/
public showHidePatternLayer(isShow: boolean) {
this.broadCaster.broadcast('EDIT_RULE_SHOW_HIDE_LAYER', {isShow: isShow});
this.isFocus = isShow;
} // function - showHidePatternLayer
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* Before component is shown
* @protected
*/
protected beforeShowComp() {
this.fields = this.fields.filter((item) => {
return item.type === 'TIMESTAMP'
});
this.selectedFields = this.selectedFields.filter((item) => {
return item.type === 'TIMESTAMP'
});
} // function - _beforeShowComp
/**
* After component is shown
* @protected
*/
protected afterShowComp() {
} // function - _afterShowComp
/**
* Rule string parse
* @param data ({ruleString : string, jsonRuleString : any})
*/
protected parsingRuleString(data: { jsonRuleString: SetFormatRule }) {
// COLUMN
const arrFields: string[] = data.jsonRuleString.col;
this.selectedFields = arrFields.map(item => this.fields.find(orgItem => orgItem.name === item)).filter(field => !!field);
// FORMAT
if (!this.isNullOrUndefined(data.jsonRuleString.format)) {
this.selectedTimestamp = data.jsonRuleString.format;
this.getTimestampFormats();
}
} // function - _parsingRuleString
/**
* Get field name array
* @return {string[]}
* @private
*/
private _getFieldNameArray() {
return this.fields.map((item) => {
| /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| | identifier_body |
edit-rule-setformat.component.ts | may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AfterViewInit, Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Alert} from '@common/util/alert.util';
import {StringUtil} from '@common/util/string.util';
import {EventBroadcaster} from '@common/event/event.broadcaster';
import {Field} from '@domain/data-preparation/pr-dataset';
import {SetFormatRule} from '@domain/data-preparation/prep-rules';
import {DataflowService} from '../../../../service/dataflow.service';
import {PrepSelectBoxCustomComponent} from '../../../../../util/prep-select-box-custom.component';
import {EditRuleComponent} from './edit-rule.component';
@Component({
selector: 'edit-rule-setformat',
templateUrl: './edit-rule-setformat.component.html'
})
export class EditRuleSetformatComponent extends EditRuleComponent implements OnInit, AfterViewInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public selectedFields: Field[] = [];
public timestampFormats: any = [];
public dsId: string = '';
public isGetTimestampRunning: boolean = false;
// 상태 저장용 T/F
public isFocus: boolean = false; // Input Focus 여부
public isTooltipShow: boolean = false; // Tooltip Show/Hide
public selectedTimestamp: string = '';
public customTimestamp: string; // custom format
private tempTimetampValue: string = '';
public defaultIndex: number = -1;
public colTypes: any = [];
@ViewChild(PrepSelectBoxCustomComponent)
protected _custom: PrepSelectBoxCustomComponent;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(protected broadCaster: EventBroadcaster,
protected elementRef: ElementRef,
protected injector: Injector,
protected dataflowService: DataflowService) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 컴포넌트 초기 실행
*/
public ngOnInit() {
super.ngOnInit();
} // function - ngOnInit
/**
* 화면 초기화
*/
public ngAfterViewInit() {
super.ngAfterViewInit();
} // function - ngAfterViewInit
/**
* 컴포넌트 제거
*/
public ngOnDestroy() {
super.ngOnDestroy();
} // function - ngOnDestroy
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - API
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* When timestamp format is selected
* @param data
*/
public selectItem(data) {
this.selectedTimestamp = data.value;
}
/**
* Get timestamp formats from server
*/
private getTimestampFormats() {
if (!this.isGetTimestampRunning) {
this.isGetTimestampRunning = true;
const cols = this.selectedFields.map((item) => {
return item.name
});
this.tempTimetampValue = this.selectedTimestamp;
this.dataflowService.getTimestampFormatSuggestions(this.dsId, {colNames: cols}).then((result) => {
const keyList = [];
for (const key in result) {
if (result.hasOwnProperty(key)) {
keyList.push(key);
}
}
this.timestampFormats = [];
for (const i in result[keyList[0]]) {
if (result[keyList[0]].hasOwnProperty(i)) {
this.timestampFormats.push({value: i, isHove | d or this.selectedTimestamp is not empty
this.selectedTimestamp = this.tempTimetampValue;
if (cols.length > 0 || '' !== this.tempTimetampValue) {
if ('' === this.tempTimetampValue && this.selectedFields[0]) {
const idx = this._getFieldNameArray().indexOf(this.selectedFields[0].name);
if (idx !== undefined && idx >= 0) {
this.selectedTimestamp = this.colTypes[idx].timestampStyle;
}
}
}
this.isGetTimestampRunning = false;
this.setSelectedTimestamp();
});
}
}
/**
* Set selected timestamp index in select box
*/
private setSelectedTimestamp() {
let tempnum: number = -1;
if (this.selectedTimestamp !== null && this.selectedTimestamp !== '' && -1 !== this._timestampValueArray().indexOf(this.selectedTimestamp)) {
tempnum = this._timestampValueArray().indexOf(this.tempTimetampValue);
}
this._custom.setSelectedItem(this.timestampFormats, this.selectedTimestamp, tempnum);
}
/**
* Rule 형식 정의 및 반환
* @return {{command: string, col: string, ruleString: string}}
*/
public getRuleData(): { command: string, ruleString: string, uiRuleString: SetFormatRule } {
// 선택된 컬럼
if (0 === this.selectedFields.length) {
Alert.warning(this.translateService.instant('msg.dp.alert.sel.col'));
return undefined;
}
if ('Custom format' === this.selectedTimestamp && '' === this.customTimestamp || '' === this.selectedTimestamp) {
Alert.warning(this.translateService.instant('msg.dp.alert.format.error'));
return undefined;
}
let ruleString = 'setformat col: '
+ this.getColumnNamesInArray(this.selectedFields, true).toString()
+ ' format: ';
let val: any = this.selectedTimestamp === 'Custom format' ? this.customTimestamp : this.selectedTimestamp;
const check = StringUtil.checkSingleQuote(val, {isPairQuote: false, isWrapQuote: true});
if (check[0] === false) {
Alert.warning(this.translateService.instant('msg.dp.alert.invalid.timestamp.val'));
return undefined;
} else {
val = check[1];
}
ruleString += val;
return {
command: 'setformat',
ruleString: ruleString,
uiRuleString: {
name: 'setformat',
col: this.getColumnNamesInArray(this.selectedFields),
format: this.selectedTimestamp === 'Custom format' ? this.customTimestamp : this.selectedTimestamp,
isBuilder: true
}
};
} // function - getRuleData
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* When selected column is changed
* @param {{target: Field, isSelect: boolean, selectedList: Field[]}} data
*/
public changeFields(data: { target?: Field, isSelect?: boolean, selectedList: Field[] }) {
this.selectedFields = data.selectedList;
this.selectedTimestamp = '';
if (0 === this.selectedFields.length) { // if theres nothing selected
this.selectedTimestamp = '';
this.defaultIndex = -1;
} else {
this.getTimestampFormats();
}
} // function - changeFields
/**
* 패턴 정보 레이어 표시
* @param {boolean} isShow
*/
public showHidePatternLayer(isShow: boolean) {
this.broadCaster.broadcast('EDIT_RULE_SHOW_HIDE_LAYER', {isShow: isShow});
this.isFocus = isShow;
} // function - showHidePatternLayer
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* Before component is shown
* @protected
*/
protected beforeShowComp() {
this.fields = this.fields.filter((item) => {
return item.type === 'TIMESTAMP'
});
this.selectedFields = this.selectedFields.filter((item) => {
return item.type === 'TIMESTAMP'
});
} // function - _beforeShowComp
/**
* After component is shown
* @protected
*/
protected afterShowComp() {
} // function - _afterShowComp
/**
* Rule string parse
* @param data ({ruleString : string, jsonRuleString : any})
*/
protected parsingRuleString(data: { jsonRuleString: SetFormatRule }) {
// COLUMN
const arrFields: string[] = data.jsonRuleString.col;
this.selectedFields = arrFields.map(item => this.fields.find(orgItem => orgItem.name === item)).filter(field => !!field);
// FORMAT
if (!this.isNullOrUndefined(data.jsonRuleString.format)) {
this.selectedTimestamp = data.jsonRuleString.format;
this.getTimestampFormats();
}
} // function - _parsingRuleString
/**
* Get field name array
* @return {string[]}
* @private
*/
private _getFieldNameArray() {
return this.fields.map((item | r: false, matchValue: result[keyList[0]][i]})
}
}
// When at least one column is selecte | conditional_block |
edit-rule-setformat.component.ts | You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AfterViewInit, Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Alert} from '@common/util/alert.util';
import {StringUtil} from '@common/util/string.util';
import {EventBroadcaster} from '@common/event/event.broadcaster';
import {Field} from '@domain/data-preparation/pr-dataset';
import {SetFormatRule} from '@domain/data-preparation/prep-rules';
import {DataflowService} from '../../../../service/dataflow.service';
import {PrepSelectBoxCustomComponent} from '../../../../../util/prep-select-box-custom.component';
import {EditRuleComponent} from './edit-rule.component';
@Component({
selector: 'edit-rule-setformat',
templateUrl: './edit-rule-setformat.component.html'
})
export class EditRuleSetformatComponent extends EditRuleComponent implements OnInit, AfterViewInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public selectedFields: Field[] = [];
public timestampFormats: any = [];
public dsId: string = '';
public isGetTimestampRunning: boolean = false;
// 상태 저장용 T/F
public isFocus: boolean = false; // Input Focus 여부
public isTooltipShow: boolean = false; // Tooltip Show/Hide
public selectedTimestamp: string = '';
public customTimestamp: string; // custom format
private tempTimetampValue: string = '';
public defaultIndex: number = -1;
public colTypes: any = [];
@ViewChild(PrepSelectBoxCustomComponent)
protected _custom: PrepSelectBoxCustomComponent;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(protected broadCaster: EventBroadcaster,
protected elementRef: ElementRef,
protected injector: Injector,
protected dataflowService: DataflowService) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 컴포넌트 초기 실행
*/
public ngOnInit() {
super.ngOnInit();
} // function - ngOnInit
/**
* 화면 초기화
*/
public ngAfterViewInit() {
super.ngAfterViewInit();
} // function - ngAfterViewInit
/**
* 컴포넌트 제거
*/
public ngOnDestroy() {
super.ngOnDestroy();
} // function - ngOnDestroy
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - API
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* When timestamp format is selected
* @param data
*/
public selectItem(data) {
this.selectedTimestamp = data.value;
}
/**
* Get timestamp formats from server
*/
private getTimestampFormats() {
if (!this.isGetTimestampRunning) {
this.isGetTimestampRunning = true;
const cols = this.selectedFields.map((item) => {
return item.name
});
this.tempTimetampValue = this.selectedTimestamp;
this.dataflowService.getTimestampFormatSuggestions(this.dsId, {colNames: cols}).then((result) => {
const keyList = [];
for (const key in result) {
if (result.hasOwnProperty(key)) {
keyList.push(key);
}
}
this.timestampFormats = [];
for (const i in result[keyList[0]]) {
if (result[keyList[0]].hasOwnProperty(i)) {
this.timestampFormats.push({value: i, isHover: false, matchValue: result[keyList[0]][i]})
}
}
// When at least one column is selected or this.selectedTimestamp is not empty
this.selectedTimestamp = this.tempTimetampValue;
if (cols.length > 0 || '' !== this.tempTimetampValue) {
if ('' === this.tempTimetampValue && this.selectedFields[0]) {
const idx = this._getFieldNameArray().indexOf(this.selectedFields[0].name);
if (idx !== undefined && idx >= 0) {
this.selectedTimestamp = this.colTypes[idx].timestampStyle;
}
}
}
this.isGetTimestampRunning = false;
this.setSelectedTimestamp();
});
}
}
/**
* Set selected timestamp index in select box
*/
private setSelectedTimestamp() {
let tempnum: number = -1;
if (this.selectedTimestamp !== null && this.selectedTimestamp !== '' && -1 !== this._timestampValueArray().indexOf(this.selectedTimestamp)) {
tempnum = this._timestampValueArray().indexOf(this.tempTimetampValue);
}
this._custom.setSelectedItem(this.timestampFormats, this.selectedTimestamp, tempnum);
}
/**
* Rule 형식 정의 및 반환
* @return {{command: string, col: string, ruleString: string}}
*/
public getRuleData(): { command: string, ruleString: string, uiRuleString: SetFormatRule } {
// 선택된 컬럼
if (0 === this.selectedFields.length) {
Alert.warning(this.translateService.instant('msg.dp.alert.sel.col'));
return undefined;
}
if ('Custom format' === this.selectedTimestamp && '' === this.customTimestamp || '' === this.selectedTimestamp) {
Alert.warning(this.translateService.instant('msg.dp.alert.format.error'));
return undefined;
}
let ruleString = 'setformat col: '
+ this.getColumnNamesInArray(this.selectedFields, true).toString()
+ ' format: ';
let val: any = this.selectedTimestamp === 'Custom format' ? this.customTimestamp : this.selectedTimestamp;
const check = StringUtil.checkSingleQuote(val, {isPairQuote: false, isWrapQuote: true});
if (check[0] === false) {
Alert.warning(this.translateService.instant('msg.dp.alert.invalid.timestamp.val'));
return undefined;
} else {
val = check[1];
}
ruleString += val;
return {
command: 'setformat',
ruleString: ruleString,
uiRuleString: {
name: 'setformat',
col: this.getColumnNamesInArray(this.selectedFields),
format: this.selectedTimestamp === 'Custom format' ? this.customTimestamp : this.selectedTimestamp,
isBuilder: true
}
};
} // function - getRuleData
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* When selected column is changed
* @param {{target: Field, isSelect: boolean, selectedList: Field[]}} data
*/
public changeFields(data: { target?: Field, isSelect?: boolean, selectedList: Field[] }) {
this.selectedFields = data.selectedList;
this.selectedTimestamp = '';
if (0 === this.selectedFields.length) { // if theres nothing selected
this.selectedTimestamp = '';
this.defaultIndex = -1;
} else {
this.getTimestampFormats();
}
} // function - changeFields
/**
* 패턴 정보 레이어 표시
* @param {boolean} isShow
*/
public showHidePatternLayer(isShow: boolean) {
this.broadCaster.broadcast('EDIT_RULE_SHOW_HIDE_LAYER', {isShow: isShow}); | /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* Before component is shown
* @protected
*/
protected beforeShowComp() {
this.fields = this.fields.filter((item) => {
return item.type === 'TIMESTAMP'
});
this.selectedFields = this.selectedFields.filter((item) => {
return item.type === 'TIMESTAMP'
});
} // function - _beforeShowComp
/**
* After component is shown
* @protected
*/
protected afterShowComp() {
} // function - _afterShowComp
/**
* Rule string parse
* @param data ({ruleString : string, jsonRuleString : any})
*/
protected parsingRuleString(data: { jsonRuleString: SetFormatRule }) {
// COLUMN
const arrFields: string[] = data.jsonRuleString.col;
this.selectedFields = arrFields.map(item => this.fields.find(orgItem => orgItem.name === item)).filter(field => !!field);
// FORMAT
if (!this.isNullOrUndefined(data.jsonRuleString.format)) {
this.selectedTimestamp = data.jsonRuleString.format;
this.getTimestampFormats();
}
} // function - _parsingRuleString
/**
* Get field name array
* @return {string[]}
* @private
*/
private _getFieldNameArray() {
return this.fields.map((item) => {
| this.isFocus = isShow;
} // function - showHidePatternLayer
| random_line_split |
edit-rule-setformat.component.ts | may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AfterViewInit, Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Alert} from '@common/util/alert.util';
import {StringUtil} from '@common/util/string.util';
import {EventBroadcaster} from '@common/event/event.broadcaster';
import {Field} from '@domain/data-preparation/pr-dataset';
import {SetFormatRule} from '@domain/data-preparation/prep-rules';
import {DataflowService} from '../../../../service/dataflow.service';
import {PrepSelectBoxCustomComponent} from '../../../../../util/prep-select-box-custom.component';
import {EditRuleComponent} from './edit-rule.component';
@Component({
selector: 'edit-rule-setformat',
templateUrl: './edit-rule-setformat.component.html'
})
export class EditRuleSetformatComponent extends EditRuleComponent implements OnInit, AfterViewInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public selectedFields: Field[] = [];
public timestampFormats: any = [];
public dsId: string = '';
public isGetTimestampRunning: boolean = false;
// 상태 저장용 T/F
public isFocus: boolean = false; // Input Focus 여부
public isTooltipShow: boolean = false; // Tooltip Show/Hide
public selectedTimestamp: string = '';
public customTimestamp: string; // custom format
private tempTimetampValue: string = '';
public defaultIndex: number = -1;
public colTypes: any = [];
@ViewChild(PrepSelectBoxCustomComponent)
protected _custom: PrepSelectBoxCustomComponent;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(protected broadCaster: EventBroadcaster,
protected elementRef: ElementRef,
protected injector: Injector,
protected dataflowService: DataflowService) {
super(elementRef, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 컴포넌트 초기 실행
*/
public ngOnInit() {
super.ngOnInit();
} // function - ngOnInit
/**
* 화면 초기화
*/
public ngAfterViewInit() {
super.ngAfterViewInit();
} // function - ngAfterViewInit
/**
* 컴포넌트 제거
*/
public ngOnDestroy() {
super.ngOnDestroy();
} // function - ngOnDestroy
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - API
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* When timestamp format is selected
* @param data
*/
public selectItem(data) {
this.selectedTimestamp = data.value;
}
/**
* Get timestamp formats from server
*/
private getTimestampFormats() {
if (!this.isGetTimestampRunning) {
this.isGetTimestampRunning = true;
const cols = this.selectedFields.map((item) => {
return item.name
});
this.tempTimetampValue = this.selectedTimestamp;
this.dataflowService.getTimestampFormatSuggestions(this.dsId, {colNames: cols}).then((result) => {
const keyList = [];
for (const key in result) {
if (result.hasOwnProperty(key)) {
keyList.push(key);
}
}
this.timestampFormats = [];
for (const i in result[keyList[0]]) {
if (result[keyList[0]].hasOwnProperty(i)) {
this.timestampFormats.push({value: i, isHover: false, matchValue: result[keyList[0]][i]})
}
}
// When at least one column is selected or this.selectedTimestamp is not empty
this.selectedTimestamp = this.tempTimetampValue;
if (cols.length > 0 || '' !== this.tempTimetampValue) {
if ('' === this.tempTimetampValue && this.selectedFields[0]) {
const idx = this._getFieldNameArray().indexOf(this.selectedFields[0].name);
if (idx !== undefined && idx >= 0) {
this.selectedTimestamp = this.colTypes[idx].timestampStyle;
}
}
}
this.isGetTimestampRunning = false;
this.setSelectedTimestamp();
});
}
}
/**
* Set selected timestamp index in select box
*/
private setSelectedTimestamp() {
let tempnum: number = -1;
if (this.selectedTimestamp !== null && this.selectedTimestamp !== '' && -1 !== this._timestampValueArray().indexOf(this.selectedTimestamp)) {
tempnum = this._timestampValueArray().indexOf(this.tempTimetampValue);
}
this._custom.setSelectedItem(this.timestampFormats, this.selectedTimestamp, tempnum);
}
/**
* Rule 형식 정의 및 반환
* @return {{command: string, col: string, ruleString: string}}
*/
public getRuleData(): { command: string, ruleString: string, uiRuleString: SetFormatRule } {
// 선택된 컬럼
if (0 === this.selectedFields.length) {
Alert.warning(this.translateService.instant('msg.dp.alert.sel.col'));
return undefined;
}
if ('Custom format' === this.selectedTimestamp && '' === this.customTimestamp || '' === this.selectedTimestamp) {
Alert.warning(this.translateService.instant('msg.dp.alert.format.error'));
return undefined;
}
let ruleString = 'setformat col: '
+ this.getColumnNamesInArray(this.selectedFields, true).toString()
+ ' format: ';
let val: any = this.selectedTimestamp === 'Custom format' ? this.customTimestamp : this.selectedTimestamp;
const check = StringUtil.checkSingleQuote(val, {isPairQuote: false, isWrapQuote: true});
if (check[0] === false) {
Alert.warning(this.translateService.instant('msg.dp.alert.invalid.timestamp.val'));
return undefined;
} else {
val = check[1];
}
ruleString += val;
return {
command: 'setformat',
ruleString: ruleString,
uiRuleString: {
name: 'setformat',
col: this.getColumnNamesInArray(this.selectedFields),
format: this.selectedTimestamp === 'Custom format' ? this.customTimestamp : this.selectedTimestamp,
isBuilder: true
}
};
} // function - getRuleData
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* When selected column is changed
* @param {{target: Field, isSelect: boolean, selectedList: Field[]}} data
*/
public changeFields(data: { target?: Field, isSelect?: boolean, selectedList: Field[] }) | electedFields = data.selectedList;
this.selectedTimestamp = '';
if (0 === this.selectedFields.length) { // if theres nothing selected
this.selectedTimestamp = '';
this.defaultIndex = -1;
} else {
this.getTimestampFormats();
}
} // function - changeFields
/**
* 패턴 정보 레이어 표시
* @param {boolean} isShow
*/
public showHidePatternLayer(isShow: boolean) {
this.broadCaster.broadcast('EDIT_RULE_SHOW_HIDE_LAYER', {isShow: isShow});
this.isFocus = isShow;
} // function - showHidePatternLayer
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* Before component is shown
* @protected
*/
protected beforeShowComp() {
this.fields = this.fields.filter((item) => {
return item.type === 'TIMESTAMP'
});
this.selectedFields = this.selectedFields.filter((item) => {
return item.type === 'TIMESTAMP'
});
} // function - _beforeShowComp
/**
* After component is shown
* @protected
*/
protected afterShowComp() {
} // function - _afterShowComp
/**
* Rule string parse
* @param data ({ruleString : string, jsonRuleString : any})
*/
protected parsingRuleString(data: { jsonRuleString: SetFormatRule }) {
// COLUMN
const arrFields: string[] = data.jsonRuleString.col;
this.selectedFields = arrFields.map(item => this.fields.find(orgItem => orgItem.name === item)).filter(field => !!field);
// FORMAT
if (!this.isNullOrUndefined(data.jsonRuleString.format)) {
this.selectedTimestamp = data.jsonRuleString.format;
this.getTimestampFormats();
}
} // function - _parsingRuleString
/**
* Get field name array
* @return {string[]}
* @private
*/
private _getFieldNameArray() {
return this.fields.map((item) | {
this.s | identifier_name |
treena.js | (function($) {
var digestQueued = false;
var digestRunning = false;
var queueDigest = function() {
if (!digestQueued) {
digestQueued = true;
if (!digestRunning) {
setTimeout(function() {
var maxIters = 10;
digestRunning = true;
while (digestQueued && (maxIters-- > 0)) {
digestQueued = false;
$(".--treena-watched-element").triggerHandler('treena:data-change');
}
if (digestQueued) {
console.log('maxIters exceeded!');
digestQueued = false;
}
digestRunning = false;
}, 0);
}
}
};
var addWatcher = function($e, ifF, thenF) {
var oldValue = undefined;
$e.on("treena:data-change", function() {
var v = ifF.__watcher__ ? ifF.__watcher__() : ifF();
var newValue = (typeof(v) === 'number') ? v : JSON.stringify(v);
if (oldValue !== newValue) {
oldValue = newValue;
thenF && thenF(ifF(), $e);
queueDigest();
}
});
$e.addClass("--treena-watched-element");
queueDigest();
return $e;
};
var isWatcher = $.isFunction;
var setCss = function($e, css) {
if (isWatcher(css)) {
addWatcher($e, css, function(c) {
$e.css(c);
} );
} else if (typeof(css) === 'object') {
$.each(css, function(k, val) {
if (isWatcher(val)) {
addWatcher($e, val, function(c) { $e.css(k, c); } );
} else {
$e.css(k, val);
}
});
} else {
$e.css(css);
}
};
var setClass = function($e, val) {
if (typeof(val) == 'string') {
val = val.split(' ');
} else if (!$.isArray(val)) {
val = [ val ];
}
$.each(val, function(i, clas) {
if (isWatcher(clas)) {
var oldClass = null;
addWatcher($e, clas, function(newClass) {
if (oldClass) {
$e.removeClass(oldClass);
}
if (newClass) {
$e.addClass(newClass);
}
oldClass = newClass;
});
} else {
$e.addClass(clas);
}
});
};
/* fix some stupid IE capitalization bugs */
var IEcaps = {
"rowspan" : "rowSpan",
"colspan" : "colSpan",
"frameborder" : "frameBorder"
};
var setAttr = function($e, attr, val, initial) {
attr = attr.toLowerCase();
if ((attr === 'class') || (attr === 'clas') || (attr === 'clazz')) {
if (val) setClass($e, val);
} else if (attr === 'style') {
if (val) setCss($e, val);
} else {
attr = IEcaps[attr] || attr;
if (isWatcher(val)) {
if (initial) {
addWatcher($e, val, function(v) { $e.attr(attr, v); } );
} else {
$e.attr(attr, val());
}
} else {
$e.attr(attr, val);
}
}
};
var setAttrs = function($e, attrs, initial) {
if (isWatcher(attrs)) {
if (initial) {
addWatcher($e, attrs, function(a) { setAttrs($e, a, false); } );
} else {
attrs = attrs();
}
} else if ($.isPlainObject(attrs)) {
$.each(attrs, function(k, v) {
setAttr($e, k, v, initial);
});
}
};
var clickables = {
'a' : true,
'form' : true,
'button' : true
};
var createNode = function(node_name, node_args) {
var callback = (clickables[node_name] && node_args.length && $.isFunction(node_args[0])) ?
node_args.shift() : null;
var attrs = (node_args.length && ($.isPlainObject(node_args[0]) || isWatcher(node_args[0]))) ?
node_args.shift() : {};
var e = ($.browser && $.browser.msie && (node_name === "input") && attrs.name) ? ('<input name="' + attrs.name + '"/>') : node_name;
var $e = $(document.createElement(e));
setAttrs($e, attrs, true);
var processChild = function($parent, arg) {
if ((arg === null) || (arg === undefined)) {
// skip it
} else if ($.isArray(arg)) {
$.each(arg, function(i, c) {
processChild($parent, c);
});
} else {
if ((typeof(arg) === 'string') || (typeof(arg) === 'number')) {
arg = document.createTextNode(arg);
} else if (isWatcher(arg)) {
addWatcher($parent, arg,
function(v) {
$(arg).empty();
processChild($(arg), v);
});
arg = document.createElement('span');
}
$parent.append(arg);
}
};
processChild($e, node_args);
if ((node_name === "a") && !attrs.href) {
$e.attr("href", "#");
callback = callback || function() {};
};
if (callback) {
var f = function(ev) {
ev.preventDefault();
callback.apply(this);
queueDigest();
};
if (node_name === "form") {
$e.submit(f);
} else {
$e.click(f);
}
}
return $e;
};
var nodeNames = [ 'table', 'tbody','thead', 'tr', 'th', 'td', 'a', 'strong', 'div', 'img',
'br', 'b', 'span', 'li', 'ul', 'ol', 'iframe', 'form', 'h1',
'input', 'h2', 'h3', 'h4','h5','h6', 'p', 'br', 'select', 'option', 'optgroup',
'script', 'label', 'textarea', 'em', 'button', 'b', 'hr', 'fieldset', 'nobr',
'object', 'embed', 'param', 'style', 'tt', 'header', 'footer', 'section', 'i', 'small'];
var treena = {};
$.each(nodeNames, function(i, node_name) {
treena[node_name.toUpperCase()] = function() {
return createNode(node_name, $.map(arguments, function(x) { return x; }));
};
});
treena.NBSP = '\u00a0';
treena.px = function(n) {
return n + "px";
};
treena.url = function(n) {
return 'url("' + n + '")';
};
treena.setTimeout = function(f, tm) {
return window.setTimeout(function(a) {
f(a);
queueDigest();
}, tm || 0);
};
treena.setInterval = function(f, tm) {
return window.setInterval(function(a) {
f(a);
queueDigest();
}, tm);
};
treena.digest = function(cb) {
if (cb) {
return function(a,b,c) {
// cb.apply(this, Array.prototype.slice.apply(arguments));
cb(a,b,c);
queueDigest();
};
} else {
queueDigest();
}
};
treena.watcher = function(source, transformOut, transformIn) {
if (transformOut) {
var st = function(n) {
if (arguments.length) {
source(transformIn ? transformIn(n) : n);
} else {
return transformOut(source());
}
};
st.__watcher__ = function() {
return source.__watcher__ ? source.__watcher__() : source();
};
return st;
} else {
return source;
}
};
treena.watch = addWatcher;
treena.watchField = function(source, field) {
return treena.watcher(source,
function(s) {
return s && s[field];
},
function(n) {
var d = $.extend({}, source())
d[field] = n;
return d; | treena.settable = function(name, onchange) {
var statev = undefined;
return function (n) {
if (arguments.length === 0) {
return statev;
} else if (statev !== n) {
statev = n;
onchange && onchange();
treena.digest();
}
};
};
treena.setter = function(settable, $e) {
$e.change(function() {
settable($e.val());
});
return $e;
};
$.t = treena;
})(window.jQuery || window.Zeptos); | });
};
| random_line_split |
treena.js | (function($) {
var digestQueued = false;
var digestRunning = false;
var queueDigest = function() {
if (!digestQueued) {
digestQueued = true;
if (!digestRunning) {
setTimeout(function() {
var maxIters = 10;
digestRunning = true;
while (digestQueued && (maxIters-- > 0)) {
digestQueued = false;
$(".--treena-watched-element").triggerHandler('treena:data-change');
}
if (digestQueued) {
console.log('maxIters exceeded!');
digestQueued = false;
}
digestRunning = false;
}, 0);
}
}
};
var addWatcher = function($e, ifF, thenF) {
var oldValue = undefined;
$e.on("treena:data-change", function() {
var v = ifF.__watcher__ ? ifF.__watcher__() : ifF();
var newValue = (typeof(v) === 'number') ? v : JSON.stringify(v);
if (oldValue !== newValue) {
oldValue = newValue;
thenF && thenF(ifF(), $e);
queueDigest();
}
});
$e.addClass("--treena-watched-element");
queueDigest();
return $e;
};
var isWatcher = $.isFunction;
var setCss = function($e, css) {
if (isWatcher(css)) {
addWatcher($e, css, function(c) {
$e.css(c);
} );
} else if (typeof(css) === 'object') {
$.each(css, function(k, val) {
if (isWatcher(val)) {
addWatcher($e, val, function(c) { $e.css(k, c); } );
} else {
$e.css(k, val);
}
});
} else {
$e.css(css);
}
};
var setClass = function($e, val) {
if (typeof(val) == 'string') {
val = val.split(' ');
} else if (!$.isArray(val)) {
val = [ val ];
}
$.each(val, function(i, clas) {
if (isWatcher(clas)) {
var oldClass = null;
addWatcher($e, clas, function(newClass) {
if (oldClass) {
$e.removeClass(oldClass);
}
if (newClass) {
$e.addClass(newClass);
}
oldClass = newClass;
});
} else {
$e.addClass(clas);
}
});
};
/* fix some stupid IE capitalization bugs */
var IEcaps = {
"rowspan" : "rowSpan",
"colspan" : "colSpan",
"frameborder" : "frameBorder"
};
var setAttr = function($e, attr, val, initial) {
attr = attr.toLowerCase();
if ((attr === 'class') || (attr === 'clas') || (attr === 'clazz')) {
if (val) setClass($e, val);
} else if (attr === 'style') {
if (val) setCss($e, val);
} else {
attr = IEcaps[attr] || attr;
if (isWatcher(val)) {
if (initial) {
addWatcher($e, val, function(v) { $e.attr(attr, v); } );
} else {
$e.attr(attr, val());
}
} else {
$e.attr(attr, val);
}
}
};
var setAttrs = function($e, attrs, initial) {
if (isWatcher(attrs)) {
if (initial) {
addWatcher($e, attrs, function(a) { setAttrs($e, a, false); } );
} else {
attrs = attrs();
}
} else if ($.isPlainObject(attrs)) {
$.each(attrs, function(k, v) {
setAttr($e, k, v, initial);
});
}
};
var clickables = {
'a' : true,
'form' : true,
'button' : true
};
var createNode = function(node_name, node_args) {
var callback = (clickables[node_name] && node_args.length && $.isFunction(node_args[0])) ?
node_args.shift() : null;
var attrs = (node_args.length && ($.isPlainObject(node_args[0]) || isWatcher(node_args[0]))) ?
node_args.shift() : {};
var e = ($.browser && $.browser.msie && (node_name === "input") && attrs.name) ? ('<input name="' + attrs.name + '"/>') : node_name;
var $e = $(document.createElement(e));
setAttrs($e, attrs, true);
var processChild = function($parent, arg) {
if ((arg === null) || (arg === undefined)) {
// skip it
} else if ($.isArray(arg)) {
$.each(arg, function(i, c) {
processChild($parent, c);
});
} else {
if ((typeof(arg) === 'string') || (typeof(arg) === 'number')) {
arg = document.createTextNode(arg);
} else if (isWatcher(arg)) {
addWatcher($parent, arg,
function(v) {
$(arg).empty();
processChild($(arg), v);
});
arg = document.createElement('span');
}
$parent.append(arg);
}
};
processChild($e, node_args);
if ((node_name === "a") && !attrs.href) {
$e.attr("href", "#");
callback = callback || function() {};
};
if (callback) {
var f = function(ev) {
ev.preventDefault();
callback.apply(this);
queueDigest();
};
if (node_name === "form") {
$e.submit(f);
} else |
}
return $e;
};
var nodeNames = [ 'table', 'tbody','thead', 'tr', 'th', 'td', 'a', 'strong', 'div', 'img',
'br', 'b', 'span', 'li', 'ul', 'ol', 'iframe', 'form', 'h1',
'input', 'h2', 'h3', 'h4','h5','h6', 'p', 'br', 'select', 'option', 'optgroup',
'script', 'label', 'textarea', 'em', 'button', 'b', 'hr', 'fieldset', 'nobr',
'object', 'embed', 'param', 'style', 'tt', 'header', 'footer', 'section', 'i', 'small'];
var treena = {};
$.each(nodeNames, function(i, node_name) {
treena[node_name.toUpperCase()] = function() {
return createNode(node_name, $.map(arguments, function(x) { return x; }));
};
});
treena.NBSP = '\u00a0';
treena.px = function(n) {
return n + "px";
};
treena.url = function(n) {
return 'url("' + n + '")';
};
treena.setTimeout = function(f, tm) {
return window.setTimeout(function(a) {
f(a);
queueDigest();
}, tm || 0);
};
treena.setInterval = function(f, tm) {
return window.setInterval(function(a) {
f(a);
queueDigest();
}, tm);
};
treena.digest = function(cb) {
if (cb) {
return function(a,b,c) {
// cb.apply(this, Array.prototype.slice.apply(arguments));
cb(a,b,c);
queueDigest();
};
} else {
queueDigest();
}
};
treena.watcher = function(source, transformOut, transformIn) {
if (transformOut) {
var st = function(n) {
if (arguments.length) {
source(transformIn ? transformIn(n) : n);
} else {
return transformOut(source());
}
};
st.__watcher__ = function() {
return source.__watcher__ ? source.__watcher__() : source();
};
return st;
} else {
return source;
}
};
treena.watch = addWatcher;
treena.watchField = function(source, field) {
return treena.watcher(source,
function(s) {
return s && s[field];
},
function(n) {
var d = $.extend({}, source())
d[field] = n;
return d;
});
};
treena.settable = function(name, onchange) {
var statev = undefined;
return function (n) {
if (arguments.length === 0) {
return statev;
} else if (statev !== n) {
statev = n;
onchange && onchange();
treena.digest();
}
};
};
treena.setter = function(settable, $e) {
$e.change(function() {
settable($e.val());
});
return $e;
};
$.t = treena;
})(window.jQuery || window.Zeptos); | {
$e.click(f);
} | conditional_block |
borrowck-borrow-overloaded-auto-deref-mut.rs | // Copyright 2014 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.
// Test how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
struct Own<T> {
value: *mut T
}
impl<T> Deref<T> for Own<T> {
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut<T> for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
struct Point {
x: int,
y: int
}
impl Point {
fn get(&self) -> (int, int) {
(self.x, self.y)
}
fn set(&mut self, x: int, y: int) {
self.x = x;
self.y = y;
}
fn x_ref<'a>(&'a self) -> &'a int {
&self.x
}
fn y_mut<'a>(&'a mut self) -> &'a mut int |
}
fn deref_imm_field(x: Own<Point>) {
let _i = &x.y;
}
fn deref_mut_field1(x: Own<Point>) {
let _i = &mut x.y; //~ ERROR cannot borrow
}
fn deref_mut_field2(mut x: Own<Point>) {
let _i = &mut x.y;
}
fn deref_extend_field<'a>(x: &'a Own<Point>) -> &'a int {
&x.y
}
fn deref_extend_mut_field1<'a>(x: &'a Own<Point>) -> &'a mut int {
&mut x.y //~ ERROR cannot borrow
}
fn deref_extend_mut_field2<'a>(x: &'a mut Own<Point>) -> &'a mut int {
&mut x.y
}
fn deref_extend_mut_field3<'a>(x: &'a mut Own<Point>) {
// Hmm, this is unfortunate, because with ~ it would work,
// but it's presently the expected outcome. See `deref_extend_mut_field4`
// for the workaround.
let _x = &mut x.x;
let _y = &mut x.y; //~ ERROR cannot borrow
}
fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) {
let p = &mut **x;
let _x = &mut p.x;
let _y = &mut p.y;
}
fn assign_field1<'a>(x: Own<Point>) {
x.y = 3; //~ ERROR cannot borrow
}
fn assign_field2<'a>(x: &'a Own<Point>) {
x.y = 3; //~ ERROR cannot assign
}
fn assign_field3<'a>(x: &'a mut Own<Point>) {
x.y = 3;
}
fn assign_field4<'a>(x: &'a mut Own<Point>) {
let _p: &mut Point = &mut **x;
x.y = 3; //~ ERROR cannot borrow
}
// FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut.
/*
fn deref_imm_method(x: Own<Point>) {
let _i = x.get();
}
*/
fn deref_mut_method1(x: Own<Point>) {
x.set(0, 0); //~ ERROR cannot borrow
}
fn deref_mut_method2(mut x: Own<Point>) {
x.set(0, 0);
}
fn deref_extend_method<'a>(x: &'a Own<Point>) -> &'a int {
x.x_ref()
}
fn deref_extend_mut_method1<'a>(x: &'a Own<Point>) -> &'a mut int {
x.y_mut() //~ ERROR cannot borrow
}
fn deref_extend_mut_method2<'a>(x: &'a mut Own<Point>) -> &'a mut int {
x.y_mut()
}
fn assign_method1<'a>(x: Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method2<'a>(x: &'a Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method3<'a>(x: &'a mut Own<Point>) {
*x.y_mut() = 3;
}
pub fn main() {}
| {
&mut self.y
} | identifier_body |
borrowck-borrow-overloaded-auto-deref-mut.rs | // Copyright 2014 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.
// Test how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
struct Own<T> {
value: *mut T
}
impl<T> Deref<T> for Own<T> {
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut<T> for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
struct Point {
x: int,
y: int
}
impl Point {
fn get(&self) -> (int, int) {
(self.x, self.y)
}
fn set(&mut self, x: int, y: int) {
self.x = x;
self.y = y;
}
fn x_ref<'a>(&'a self) -> &'a int {
&self.x
}
fn y_mut<'a>(&'a mut self) -> &'a mut int {
&mut self.y
}
}
fn deref_imm_field(x: Own<Point>) {
let _i = &x.y;
}
fn deref_mut_field1(x: Own<Point>) {
let _i = &mut x.y; //~ ERROR cannot borrow
}
fn deref_mut_field2(mut x: Own<Point>) {
let _i = &mut x.y;
}
fn deref_extend_field<'a>(x: &'a Own<Point>) -> &'a int {
&x.y
}
fn deref_extend_mut_field1<'a>(x: &'a Own<Point>) -> &'a mut int {
&mut x.y //~ ERROR cannot borrow
}
fn deref_extend_mut_field2<'a>(x: &'a mut Own<Point>) -> &'a mut int {
&mut x.y
}
fn deref_extend_mut_field3<'a>(x: &'a mut Own<Point>) {
// Hmm, this is unfortunate, because with ~ it would work,
// but it's presently the expected outcome. See `deref_extend_mut_field4`
// for the workaround.
let _x = &mut x.x;
let _y = &mut x.y; //~ ERROR cannot borrow
}
fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) {
let p = &mut **x;
let _x = &mut p.x;
let _y = &mut p.y;
}
fn assign_field1<'a>(x: Own<Point>) {
x.y = 3; //~ ERROR cannot borrow
}
fn assign_field2<'a>(x: &'a Own<Point>) {
x.y = 3; //~ ERROR cannot assign
}
fn | <'a>(x: &'a mut Own<Point>) {
x.y = 3;
}
fn assign_field4<'a>(x: &'a mut Own<Point>) {
let _p: &mut Point = &mut **x;
x.y = 3; //~ ERROR cannot borrow
}
// FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut.
/*
fn deref_imm_method(x: Own<Point>) {
let _i = x.get();
}
*/
fn deref_mut_method1(x: Own<Point>) {
x.set(0, 0); //~ ERROR cannot borrow
}
fn deref_mut_method2(mut x: Own<Point>) {
x.set(0, 0);
}
fn deref_extend_method<'a>(x: &'a Own<Point>) -> &'a int {
x.x_ref()
}
fn deref_extend_mut_method1<'a>(x: &'a Own<Point>) -> &'a mut int {
x.y_mut() //~ ERROR cannot borrow
}
fn deref_extend_mut_method2<'a>(x: &'a mut Own<Point>) -> &'a mut int {
x.y_mut()
}
fn assign_method1<'a>(x: Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method2<'a>(x: &'a Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method3<'a>(x: &'a mut Own<Point>) {
*x.y_mut() = 3;
}
pub fn main() {}
| assign_field3 | identifier_name |
borrowck-borrow-overloaded-auto-deref-mut.rs | // Copyright 2014 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.
// Test how overloaded deref interacts with borrows when DerefMut
// is implemented.
use std::ops::{Deref, DerefMut};
struct Own<T> {
value: *mut T
}
impl<T> Deref<T> for Own<T> {
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut<T> for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
struct Point {
x: int,
y: int
}
impl Point {
fn get(&self) -> (int, int) {
(self.x, self.y)
}
fn set(&mut self, x: int, y: int) {
self.x = x;
self.y = y;
}
fn x_ref<'a>(&'a self) -> &'a int {
&self.x
}
fn y_mut<'a>(&'a mut self) -> &'a mut int {
&mut self.y
}
}
fn deref_imm_field(x: Own<Point>) {
let _i = &x.y;
}
fn deref_mut_field1(x: Own<Point>) {
let _i = &mut x.y; //~ ERROR cannot borrow
}
fn deref_mut_field2(mut x: Own<Point>) {
let _i = &mut x.y;
}
fn deref_extend_field<'a>(x: &'a Own<Point>) -> &'a int {
&x.y
}
fn deref_extend_mut_field1<'a>(x: &'a Own<Point>) -> &'a mut int {
&mut x.y //~ ERROR cannot borrow
}
fn deref_extend_mut_field2<'a>(x: &'a mut Own<Point>) -> &'a mut int {
&mut x.y
}
fn deref_extend_mut_field3<'a>(x: &'a mut Own<Point>) {
// Hmm, this is unfortunate, because with ~ it would work,
// but it's presently the expected outcome. See `deref_extend_mut_field4`
// for the workaround.
let _x = &mut x.x;
let _y = &mut x.y; //~ ERROR cannot borrow
}
fn deref_extend_mut_field4<'a>(x: &'a mut Own<Point>) {
let p = &mut **x;
let _x = &mut p.x;
let _y = &mut p.y;
}
fn assign_field1<'a>(x: Own<Point>) {
x.y = 3; //~ ERROR cannot borrow
}
fn assign_field2<'a>(x: &'a Own<Point>) {
x.y = 3; //~ ERROR cannot assign
}
fn assign_field3<'a>(x: &'a mut Own<Point>) {
x.y = 3;
}
fn assign_field4<'a>(x: &'a mut Own<Point>) {
let _p: &mut Point = &mut **x;
x.y = 3; //~ ERROR cannot borrow
}
// FIXME(eddyb) #12825 This shouldn't attempt to call deref_mut.
/*
fn deref_imm_method(x: Own<Point>) {
let _i = x.get();
}
*/
fn deref_mut_method1(x: Own<Point>) {
x.set(0, 0); //~ ERROR cannot borrow
}
fn deref_mut_method2(mut x: Own<Point>) {
x.set(0, 0);
}
fn deref_extend_method<'a>(x: &'a Own<Point>) -> &'a int {
x.x_ref()
}
fn deref_extend_mut_method1<'a>(x: &'a Own<Point>) -> &'a mut int {
x.y_mut() //~ ERROR cannot borrow
} | fn assign_method1<'a>(x: Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method2<'a>(x: &'a Own<Point>) {
*x.y_mut() = 3; //~ ERROR cannot borrow
}
fn assign_method3<'a>(x: &'a mut Own<Point>) {
*x.y_mut() = 3;
}
pub fn main() {} |
fn deref_extend_mut_method2<'a>(x: &'a mut Own<Point>) -> &'a mut int {
x.y_mut()
}
| random_line_split |
test_t1197_telem.py | import json
import pytest
from common.utils.attack_utils import ScanStatus
from infection_monkey.model import VictimHost
from infection_monkey.telemetry.attack.t1197_telem import T1197Telem
DOMAIN_NAME = "domain-name"
IP = "127.0.0.1"
MACHINE = VictimHost(IP, DOMAIN_NAME)
STATUS = ScanStatus.USED
USAGE_STR = "[Usage info]"
@pytest.fixture
def T1197_telem_test_instance():
return T1197Telem(STATUS, MACHINE, USAGE_STR)
| def test_T1197_send(T1197_telem_test_instance, spy_send_telemetry):
T1197_telem_test_instance.send()
expected_data = {
"status": STATUS.value,
"technique": "T1197",
"machine": {"domain_name": DOMAIN_NAME, "ip_addr": IP},
"usage": USAGE_STR,
}
expected_data = json.dumps(expected_data, cls=T1197_telem_test_instance.json_encoder)
assert spy_send_telemetry.data == expected_data
assert spy_send_telemetry.telem_category == "attack" | random_line_split |
|
test_t1197_telem.py | import json
import pytest
from common.utils.attack_utils import ScanStatus
from infection_monkey.model import VictimHost
from infection_monkey.telemetry.attack.t1197_telem import T1197Telem
DOMAIN_NAME = "domain-name"
IP = "127.0.0.1"
MACHINE = VictimHost(IP, DOMAIN_NAME)
STATUS = ScanStatus.USED
USAGE_STR = "[Usage info]"
@pytest.fixture
def | ():
return T1197Telem(STATUS, MACHINE, USAGE_STR)
def test_T1197_send(T1197_telem_test_instance, spy_send_telemetry):
T1197_telem_test_instance.send()
expected_data = {
"status": STATUS.value,
"technique": "T1197",
"machine": {"domain_name": DOMAIN_NAME, "ip_addr": IP},
"usage": USAGE_STR,
}
expected_data = json.dumps(expected_data, cls=T1197_telem_test_instance.json_encoder)
assert spy_send_telemetry.data == expected_data
assert spy_send_telemetry.telem_category == "attack"
| T1197_telem_test_instance | identifier_name |
test_t1197_telem.py | import json
import pytest
from common.utils.attack_utils import ScanStatus
from infection_monkey.model import VictimHost
from infection_monkey.telemetry.attack.t1197_telem import T1197Telem
DOMAIN_NAME = "domain-name"
IP = "127.0.0.1"
MACHINE = VictimHost(IP, DOMAIN_NAME)
STATUS = ScanStatus.USED
USAGE_STR = "[Usage info]"
@pytest.fixture
def T1197_telem_test_instance():
return T1197Telem(STATUS, MACHINE, USAGE_STR)
def test_T1197_send(T1197_telem_test_instance, spy_send_telemetry):
| T1197_telem_test_instance.send()
expected_data = {
"status": STATUS.value,
"technique": "T1197",
"machine": {"domain_name": DOMAIN_NAME, "ip_addr": IP},
"usage": USAGE_STR,
}
expected_data = json.dumps(expected_data, cls=T1197_telem_test_instance.json_encoder)
assert spy_send_telemetry.data == expected_data
assert spy_send_telemetry.telem_category == "attack" | identifier_body |
|
contact.py | def post(self):
to = self.request.get("to")
user_name = self.request.get("name")
user_address = self.request.get("email")
subject = self.request.get("subject")
body = self.request.get("message")
behalf_of = user_name + " <" + user_address +">"
sender_address ="CB Contact <[email protected]>"
if "<[email protected]>" not in to:
if "<[email protected]>" not in to:
return
mail.send_mail(sender= sender_address,
to = to,
#cc = behalf_of,
reply_to = behalf_of,
subject = subject+" | "+user_name+" | "+user_address,
body = body,
headers = {"On-Behalf-Of":behalf_of})
self.response.out.write(json.dumps({"done":"true"})) | from google.appengine.api import mail
import json
import webapp2
class SendEmail(webapp2.RequestHandler): | random_line_split |
|
contact.py | from google.appengine.api import mail
import json
import webapp2
class SendEmail(webapp2.RequestHandler):
def post(self):
to = self.request.get("to")
user_name = self.request.get("name")
user_address = self.request.get("email")
subject = self.request.get("subject")
body = self.request.get("message")
behalf_of = user_name + " <" + user_address +">"
sender_address ="CB Contact <[email protected]>"
if "<[email protected]>" not in to:
if "<[email protected]>" not in to:
|
mail.send_mail(sender= sender_address,
to = to,
#cc = behalf_of,
reply_to = behalf_of,
subject = subject+" | "+user_name+" | "+user_address,
body = body,
headers = {"On-Behalf-Of":behalf_of})
self.response.out.write(json.dumps({"done":"true"})) | return | conditional_block |
contact.py | from google.appengine.api import mail
import json
import webapp2
class SendEmail(webapp2.RequestHandler):
def | (self):
to = self.request.get("to")
user_name = self.request.get("name")
user_address = self.request.get("email")
subject = self.request.get("subject")
body = self.request.get("message")
behalf_of = user_name + " <" + user_address +">"
sender_address ="CB Contact <[email protected]>"
if "<[email protected]>" not in to:
if "<[email protected]>" not in to:
return
mail.send_mail(sender= sender_address,
to = to,
#cc = behalf_of,
reply_to = behalf_of,
subject = subject+" | "+user_name+" | "+user_address,
body = body,
headers = {"On-Behalf-Of":behalf_of})
self.response.out.write(json.dumps({"done":"true"})) | post | identifier_name |
contact.py | from google.appengine.api import mail
import json
import webapp2
class SendEmail(webapp2.RequestHandler):
| headers = {"On-Behalf-Of":behalf_of})
self.response.out.write(json.dumps({"done":"true"})) | def post(self):
to = self.request.get("to")
user_name = self.request.get("name")
user_address = self.request.get("email")
subject = self.request.get("subject")
body = self.request.get("message")
behalf_of = user_name + " <" + user_address +">"
sender_address ="CB Contact <[email protected]>"
if "<[email protected]>" not in to:
if "<[email protected]>" not in to:
return
mail.send_mail(sender= sender_address,
to = to,
#cc = behalf_of,
reply_to = behalf_of,
subject = subject+" | "+user_name+" | "+user_address,
body = body, | identifier_body |
get.rs | use super::with_path;
use util::*;
use hyper::client::Response;
use hyper::status::StatusCode;
fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) {
with_path(&format!("/get?{}", query), f)
}
fn assert_accepted(query: &str) {
with_query(query, |res| {
let s = read_body_to_string(res);
assert_eq!(res.status, StatusCode::Ok);
assert_eq!(s, "Congratulations on conforming!");
})
}
fn assert_rejected(query: &str) {
with_query(query, |res| {
assert_eq!(res.status, StatusCode::BadRequest)
})
}
mod accepts {
use super::assert_accepted;
#[test]
fn valid() {
assert_accepted("state=valid")
}
#[test]
fn | () {
assert_accepted("state=valid&state=foo")
}
}
mod rejects {
use super::assert_rejected;
#[test]
fn invalid() {
assert_rejected("state=foo")
}
#[test]
fn other_keys() {
assert_rejected("valid=valid")
}
#[test]
fn empty() {
assert_rejected("")
}
#[test]
fn second_valid() {
assert_rejected("state=foo&state=valid")
}
}
| first_valid | identifier_name |
get.rs | use super::with_path;
use util::*;
use hyper::client::Response;
use hyper::status::StatusCode;
fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) {
with_path(&format!("/get?{}", query), f)
}
fn assert_accepted(query: &str) {
with_query(query, |res| {
let s = read_body_to_string(res);
assert_eq!(res.status, StatusCode::Ok);
assert_eq!(s, "Congratulations on conforming!");
})
}
fn assert_rejected(query: &str) {
with_query(query, |res| {
assert_eq!(res.status, StatusCode::BadRequest)
})
}
mod accepts {
use super::assert_accepted;
#[test]
fn valid() {
assert_accepted("state=valid")
}
#[test]
fn first_valid() |
}
mod rejects {
use super::assert_rejected;
#[test]
fn invalid() {
assert_rejected("state=foo")
}
#[test]
fn other_keys() {
assert_rejected("valid=valid")
}
#[test]
fn empty() {
assert_rejected("")
}
#[test]
fn second_valid() {
assert_rejected("state=foo&state=valid")
}
}
| {
assert_accepted("state=valid&state=foo")
} | identifier_body |
get.rs | use super::with_path;
use util::*;
use hyper::client::Response;
use hyper::status::StatusCode;
fn with_query<F>(query: &str, f: F) where F: FnOnce(&mut Response) {
with_path(&format!("/get?{}", query), f)
}
fn assert_accepted(query: &str) {
with_query(query, |res| {
let s = read_body_to_string(res);
assert_eq!(res.status, StatusCode::Ok);
assert_eq!(s, "Congratulations on conforming!");
})
}
fn assert_rejected(query: &str) {
with_query(query, |res| {
assert_eq!(res.status, StatusCode::BadRequest)
})
}
mod accepts {
use super::assert_accepted;
#[test]
fn valid() {
assert_accepted("state=valid")
}
#[test]
fn first_valid() {
assert_accepted("state=valid&state=foo")
}
}
mod rejects { | #[test]
fn invalid() {
assert_rejected("state=foo")
}
#[test]
fn other_keys() {
assert_rejected("valid=valid")
}
#[test]
fn empty() {
assert_rejected("")
}
#[test]
fn second_valid() {
assert_rejected("state=foo&state=valid")
}
} | use super::assert_rejected;
| random_line_split |
test_drive.py | import os, sys
import tempfile
import unittest as unittest0
try:
unittest0.skipUnless
unittest0.skip
except AttributeError:
import unittest2 as unittest
else:
unittest = unittest0
del unittest0
import win32file
from winsys import fs
class TestDrive (unittest.TestCase):
#
# The name of the drive should be normalised:
# lowercase-letter;colon;backslash
#
def test_name (self):
names = ["C", "C:", "C:/", "C:\\"]
for name in names:
self.assertEquals (fs.drive (name).name, "c:\\")
self.assertEquals (fs.drive (name.lower ()).name, "c:\\")
def test_DriveType (self):
self.assertEquals (fs.drive ("C:").type, win32file.GetDriveTypeW ("C:"))
def test_DriveRoot (self):
self.assertEquals (fs.drive ("C:").root, fs.dir ("C:\\"))
def test_volume (self):
self.assertEquals (fs.drive ("C:").volume.name, win32file.GetVolumeNameForVolumeMountPoint ("C:\\"))
@unittest.skip ("Skip destructive test")
def test_mount (self):
#
# Difficult to test because it's not possible
# to mount a volume on two drive letters simultaneously.
# Try to find something unimportant, like a CDROM, and
# dismount it before remounting it.
#
pass
@unittest.skip ("Skip destructive test")
def test_dismount (self): | #
pass
if __name__ == "__main__":
unittest.main ()
if sys.stdout.isatty (): raw_input ("Press enter...") | #
# Likewise difficult to test because destructive | random_line_split |
test_drive.py | import os, sys
import tempfile
import unittest as unittest0
try:
unittest0.skipUnless
unittest0.skip
except AttributeError:
import unittest2 as unittest
else:
unittest = unittest0
del unittest0
import win32file
from winsys import fs
class TestDrive (unittest.TestCase):
#
# The name of the drive should be normalised:
# lowercase-letter;colon;backslash
#
def test_name (self):
names = ["C", "C:", "C:/", "C:\\"]
for name in names:
self.assertEquals (fs.drive (name).name, "c:\\")
self.assertEquals (fs.drive (name.lower ()).name, "c:\\")
def test_DriveType (self):
self.assertEquals (fs.drive ("C:").type, win32file.GetDriveTypeW ("C:"))
def test_DriveRoot (self):
self.assertEquals (fs.drive ("C:").root, fs.dir ("C:\\"))
def test_volume (self):
|
@unittest.skip ("Skip destructive test")
def test_mount (self):
#
# Difficult to test because it's not possible
# to mount a volume on two drive letters simultaneously.
# Try to find something unimportant, like a CDROM, and
# dismount it before remounting it.
#
pass
@unittest.skip ("Skip destructive test")
def test_dismount (self):
#
# Likewise difficult to test because destructive
#
pass
if __name__ == "__main__":
unittest.main ()
if sys.stdout.isatty (): raw_input ("Press enter...")
| self.assertEquals (fs.drive ("C:").volume.name, win32file.GetVolumeNameForVolumeMountPoint ("C:\\")) | identifier_body |
test_drive.py | import os, sys
import tempfile
import unittest as unittest0
try:
unittest0.skipUnless
unittest0.skip
except AttributeError:
import unittest2 as unittest
else:
unittest = unittest0
del unittest0
import win32file
from winsys import fs
class TestDrive (unittest.TestCase):
#
# The name of the drive should be normalised:
# lowercase-letter;colon;backslash
#
def test_name (self):
names = ["C", "C:", "C:/", "C:\\"]
for name in names:
self.assertEquals (fs.drive (name).name, "c:\\")
self.assertEquals (fs.drive (name.lower ()).name, "c:\\")
def test_DriveType (self):
self.assertEquals (fs.drive ("C:").type, win32file.GetDriveTypeW ("C:"))
def test_DriveRoot (self):
self.assertEquals (fs.drive ("C:").root, fs.dir ("C:\\"))
def test_volume (self):
self.assertEquals (fs.drive ("C:").volume.name, win32file.GetVolumeNameForVolumeMountPoint ("C:\\"))
@unittest.skip ("Skip destructive test")
def test_mount (self):
#
# Difficult to test because it's not possible
# to mount a volume on two drive letters simultaneously.
# Try to find something unimportant, like a CDROM, and
# dismount it before remounting it.
#
pass
@unittest.skip ("Skip destructive test")
def test_dismount (self):
#
# Likewise difficult to test because destructive
#
pass
if __name__ == "__main__":
unittest.main ()
if sys.stdout.isatty (): | raw_input ("Press enter...") | conditional_block |
|
test_drive.py | import os, sys
import tempfile
import unittest as unittest0
try:
unittest0.skipUnless
unittest0.skip
except AttributeError:
import unittest2 as unittest
else:
unittest = unittest0
del unittest0
import win32file
from winsys import fs
class TestDrive (unittest.TestCase):
#
# The name of the drive should be normalised:
# lowercase-letter;colon;backslash
#
def test_name (self):
names = ["C", "C:", "C:/", "C:\\"]
for name in names:
self.assertEquals (fs.drive (name).name, "c:\\")
self.assertEquals (fs.drive (name.lower ()).name, "c:\\")
def | (self):
self.assertEquals (fs.drive ("C:").type, win32file.GetDriveTypeW ("C:"))
def test_DriveRoot (self):
self.assertEquals (fs.drive ("C:").root, fs.dir ("C:\\"))
def test_volume (self):
self.assertEquals (fs.drive ("C:").volume.name, win32file.GetVolumeNameForVolumeMountPoint ("C:\\"))
@unittest.skip ("Skip destructive test")
def test_mount (self):
#
# Difficult to test because it's not possible
# to mount a volume on two drive letters simultaneously.
# Try to find something unimportant, like a CDROM, and
# dismount it before remounting it.
#
pass
@unittest.skip ("Skip destructive test")
def test_dismount (self):
#
# Likewise difficult to test because destructive
#
pass
if __name__ == "__main__":
unittest.main ()
if sys.stdout.isatty (): raw_input ("Press enter...")
| test_DriveType | identifier_name |
test_protocols.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc import RPCErrorResponse
@pytest.fixture(params=['jsonrpc'])
def protocol(request):
if 'jsonrpc':
return JSONRPCProtocol()
raise RuntimeError('Bad protocol name in test case')
def test_protocol_returns_bytes(protocol):
req = protocol.create_request('foo', ['bar'])
assert isinstance(req.serialize(), bytes)
def test_procotol_responds_bytes(protocol):
req = protocol.create_request('foo', ['bar'])
rep = req.respond(42)
err_rep = req.error_respond(Exception('foo'))
assert isinstance(rep.serialize(), bytes)
assert isinstance(err_rep.serialize(), bytes) | def test_one_way(protocol):
req = protocol.create_request('foo', None, {'a': 'b'}, True)
assert req.respond(None) == None
def test_raises_on_args_and_kwargs(protocol):
with pytest.raises(Exception):
protocol.create_request('foo', ['arg1', 'arg2'], {'kw_key': 'kw_value'})
def test_supports_no_args(protocol):
protocol.create_request('foo')
def test_creates_error_response(protocol):
req = protocol.create_request('foo', ['bar'])
err_rep = req.error_respond(Exception('foo'))
assert hasattr(err_rep, 'error')
def test_parses_error_response(protocol):
req = protocol.create_request('foo', ['bar'])
err_rep = req.error_respond(Exception('foo'))
parsed = protocol.parse_reply(err_rep.serialize())
assert hasattr(parsed, 'error')
def test_default_id_generator():
from tinyrpc.protocols import default_id_generator
g = default_id_generator(1)
assert next(g) == 1
assert next(g) == 2
assert next(g) == 3 | random_line_split |
|
test_protocols.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc import RPCErrorResponse
@pytest.fixture(params=['jsonrpc'])
def protocol(request):
if 'jsonrpc':
return JSONRPCProtocol()
raise RuntimeError('Bad protocol name in test case')
def test_protocol_returns_bytes(protocol):
req = protocol.create_request('foo', ['bar'])
assert isinstance(req.serialize(), bytes)
def test_procotol_responds_bytes(protocol):
req = protocol.create_request('foo', ['bar'])
rep = req.respond(42)
err_rep = req.error_respond(Exception('foo'))
assert isinstance(rep.serialize(), bytes)
assert isinstance(err_rep.serialize(), bytes)
def test_one_way(protocol):
req = protocol.create_request('foo', None, {'a': 'b'}, True)
assert req.respond(None) == None
def test_raises_on_args_and_kwargs(protocol):
with pytest.raises(Exception):
protocol.create_request('foo', ['arg1', 'arg2'], {'kw_key': 'kw_value'})
def test_supports_no_args(protocol):
protocol.create_request('foo')
def test_creates_error_response(protocol):
req = protocol.create_request('foo', ['bar'])
err_rep = req.error_respond(Exception('foo'))
assert hasattr(err_rep, 'error')
def test_parses_error_response(protocol):
|
def test_default_id_generator():
from tinyrpc.protocols import default_id_generator
g = default_id_generator(1)
assert next(g) == 1
assert next(g) == 2
assert next(g) == 3
| req = protocol.create_request('foo', ['bar'])
err_rep = req.error_respond(Exception('foo'))
parsed = protocol.parse_reply(err_rep.serialize())
assert hasattr(parsed, 'error') | identifier_body |
test_protocols.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc import RPCErrorResponse
@pytest.fixture(params=['jsonrpc'])
def protocol(request):
if 'jsonrpc':
return JSONRPCProtocol()
raise RuntimeError('Bad protocol name in test case')
def test_protocol_returns_bytes(protocol):
req = protocol.create_request('foo', ['bar'])
assert isinstance(req.serialize(), bytes)
def test_procotol_responds_bytes(protocol):
req = protocol.create_request('foo', ['bar'])
rep = req.respond(42)
err_rep = req.error_respond(Exception('foo'))
assert isinstance(rep.serialize(), bytes)
assert isinstance(err_rep.serialize(), bytes)
def test_one_way(protocol):
req = protocol.create_request('foo', None, {'a': 'b'}, True)
assert req.respond(None) == None
def test_raises_on_args_and_kwargs(protocol):
with pytest.raises(Exception):
protocol.create_request('foo', ['arg1', 'arg2'], {'kw_key': 'kw_value'})
def test_supports_no_args(protocol):
protocol.create_request('foo')
def test_creates_error_response(protocol):
req = protocol.create_request('foo', ['bar'])
err_rep = req.error_respond(Exception('foo'))
assert hasattr(err_rep, 'error')
def | (protocol):
req = protocol.create_request('foo', ['bar'])
err_rep = req.error_respond(Exception('foo'))
parsed = protocol.parse_reply(err_rep.serialize())
assert hasattr(parsed, 'error')
def test_default_id_generator():
from tinyrpc.protocols import default_id_generator
g = default_id_generator(1)
assert next(g) == 1
assert next(g) == 2
assert next(g) == 3
| test_parses_error_response | identifier_name |
test_protocols.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc import RPCErrorResponse
@pytest.fixture(params=['jsonrpc'])
def protocol(request):
if 'jsonrpc':
|
raise RuntimeError('Bad protocol name in test case')
def test_protocol_returns_bytes(protocol):
req = protocol.create_request('foo', ['bar'])
assert isinstance(req.serialize(), bytes)
def test_procotol_responds_bytes(protocol):
req = protocol.create_request('foo', ['bar'])
rep = req.respond(42)
err_rep = req.error_respond(Exception('foo'))
assert isinstance(rep.serialize(), bytes)
assert isinstance(err_rep.serialize(), bytes)
def test_one_way(protocol):
req = protocol.create_request('foo', None, {'a': 'b'}, True)
assert req.respond(None) == None
def test_raises_on_args_and_kwargs(protocol):
with pytest.raises(Exception):
protocol.create_request('foo', ['arg1', 'arg2'], {'kw_key': 'kw_value'})
def test_supports_no_args(protocol):
protocol.create_request('foo')
def test_creates_error_response(protocol):
req = protocol.create_request('foo', ['bar'])
err_rep = req.error_respond(Exception('foo'))
assert hasattr(err_rep, 'error')
def test_parses_error_response(protocol):
req = protocol.create_request('foo', ['bar'])
err_rep = req.error_respond(Exception('foo'))
parsed = protocol.parse_reply(err_rep.serialize())
assert hasattr(parsed, 'error')
def test_default_id_generator():
from tinyrpc.protocols import default_id_generator
g = default_id_generator(1)
assert next(g) == 1
assert next(g) == 2
assert next(g) == 3
| return JSONRPCProtocol() | conditional_block |
create-post.component.ts | import { Component, OnInit, Inject, EventEmitter, Output } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material';
import { CreatePost, File } from '../../model';
import { CreatePostService, SnackbarService, LocationService, FileService } from '../../services';
import { CreateFileComponent } from '../create-file';
import { FileDialogComponent } from '../file-dialog';
@Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent {
private internalIsLoading = false;
private internalPostText = '';
private selectedFile: number | undefined = undefined;
@Output() private postCreated = new EventEmitter<number>();
constructor(
public dialogRef: MatDialogRef<CreatePostComponent>,
private fileService: FileService,
private createPostService: CreatePostService,
private snackbarService: SnackbarService,
private locationService: LocationService,
private dialog: MatDialog) {
}
public get fileId(): number {
return this.selectedFile;
}
public get isLoading(): boolean {
return this.internalIsLoading;
}
public set | (value: boolean) {
this.internalIsLoading = value;
}
public set postText(value: string) {
this.internalPostText = value;
}
public get postText(): string {
return this.internalPostText;
}
public onFilePreview(): void {
if (this.selectedFile) {
this.isLoading = true;
this.fileService.getFile(this.selectedFile).then(x => {
this.isLoading = false;
this.dialog.open(FileDialogComponent, {
width: '70%',
data: {
file: <File>x
}
});
});
}
}
public onNoClick(): void {
this.dialogRef.close(-1);
}
public closeDialog(): void {
this.dialogRef.close(-1);
}
public removeFile(): void {
this.selectedFile = undefined;
}
public addFile(): void {
const dialogRef = this.dialog.open(CreateFileComponent, {
width: '60%'
});
dialogRef.afterClosed().subscribe(async result => {
if (result > 0) {
this.selectedFile = <number>result;
}
});
}
public async createPost(): Promise<void> {
try {
this.isLoading = true;
const createPost = await this.createCreatePostModel();
if (this.selectedFile) {
createPost.fileId = this.selectedFile;
}
const result = await this.createPostService.createPost(createPost);
this.dialogRef.close(result);
this.snackbarService.showMessage('Post created');
this.postCreated.emit(result);
} finally {
this.isLoading = false;
}
}
public async createCreatePostModel(): Promise<CreatePost> {
const location = await this.locationService.getLocation();
return new CreatePost(this.postText, <number>location['latitude'], <number>location['longitude']);
}
}
| isLoading | identifier_name |
create-post.component.ts | import { Component, OnInit, Inject, EventEmitter, Output } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material';
import { CreatePost, File } from '../../model';
import { CreatePostService, SnackbarService, LocationService, FileService } from '../../services';
import { CreateFileComponent } from '../create-file';
import { FileDialogComponent } from '../file-dialog';
@Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent {
private internalIsLoading = false;
private internalPostText = '';
private selectedFile: number | undefined = undefined;
@Output() private postCreated = new EventEmitter<number>();
constructor(
public dialogRef: MatDialogRef<CreatePostComponent>,
private fileService: FileService,
private createPostService: CreatePostService,
private snackbarService: SnackbarService,
private locationService: LocationService,
private dialog: MatDialog) {
}
public get fileId(): number {
return this.selectedFile;
}
public get isLoading(): boolean {
return this.internalIsLoading;
}
public set isLoading(value: boolean) {
this.internalIsLoading = value;
}
public set postText(value: string) {
this.internalPostText = value;
}
public get postText(): string {
return this.internalPostText;
}
public onFilePreview(): void {
if (this.selectedFile) |
}
public onNoClick(): void {
this.dialogRef.close(-1);
}
public closeDialog(): void {
this.dialogRef.close(-1);
}
public removeFile(): void {
this.selectedFile = undefined;
}
public addFile(): void {
const dialogRef = this.dialog.open(CreateFileComponent, {
width: '60%'
});
dialogRef.afterClosed().subscribe(async result => {
if (result > 0) {
this.selectedFile = <number>result;
}
});
}
public async createPost(): Promise<void> {
try {
this.isLoading = true;
const createPost = await this.createCreatePostModel();
if (this.selectedFile) {
createPost.fileId = this.selectedFile;
}
const result = await this.createPostService.createPost(createPost);
this.dialogRef.close(result);
this.snackbarService.showMessage('Post created');
this.postCreated.emit(result);
} finally {
this.isLoading = false;
}
}
public async createCreatePostModel(): Promise<CreatePost> {
const location = await this.locationService.getLocation();
return new CreatePost(this.postText, <number>location['latitude'], <number>location['longitude']);
}
}
| {
this.isLoading = true;
this.fileService.getFile(this.selectedFile).then(x => {
this.isLoading = false;
this.dialog.open(FileDialogComponent, {
width: '70%',
data: {
file: <File>x
}
});
});
} | conditional_block |
create-post.component.ts | import { Component, OnInit, Inject, EventEmitter, Output } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material';
import { CreatePost, File } from '../../model';
import { CreatePostService, SnackbarService, LocationService, FileService } from '../../services';
import { CreateFileComponent } from '../create-file';
import { FileDialogComponent } from '../file-dialog';
@Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent {
private internalIsLoading = false;
private internalPostText = '';
private selectedFile: number | undefined = undefined;
@Output() private postCreated = new EventEmitter<number>();
constructor(
public dialogRef: MatDialogRef<CreatePostComponent>,
private fileService: FileService,
private createPostService: CreatePostService,
private snackbarService: SnackbarService,
private locationService: LocationService,
private dialog: MatDialog) {
}
public get fileId(): number {
return this.selectedFile;
}
public get isLoading(): boolean {
return this.internalIsLoading;
}
public set isLoading(value: boolean) {
this.internalIsLoading = value;
}
public set postText(value: string) {
this.internalPostText = value;
}
public get postText(): string {
return this.internalPostText;
}
public onFilePreview(): void {
if (this.selectedFile) {
this.isLoading = true;
this.fileService.getFile(this.selectedFile).then(x => {
this.isLoading = false;
this.dialog.open(FileDialogComponent, {
width: '70%',
data: {
file: <File>x
}
});
});
}
}
public onNoClick(): void {
this.dialogRef.close(-1);
}
public closeDialog(): void {
this.dialogRef.close(-1);
}
public removeFile(): void {
this.selectedFile = undefined;
}
public addFile(): void {
const dialogRef = this.dialog.open(CreateFileComponent, {
width: '60%'
});
dialogRef.afterClosed().subscribe(async result => {
if (result > 0) {
this.selectedFile = <number>result;
}
});
}
public async createPost(): Promise<void> {
try {
this.isLoading = true;
const createPost = await this.createCreatePostModel();
if (this.selectedFile) {
createPost.fileId = this.selectedFile;
}
const result = await this.createPostService.createPost(createPost);
this.dialogRef.close(result);
this.snackbarService.showMessage('Post created');
this.postCreated.emit(result);
} finally {
this.isLoading = false;
}
}
public async createCreatePostModel(): Promise<CreatePost> |
}
| {
const location = await this.locationService.getLocation();
return new CreatePost(this.postText, <number>location['latitude'], <number>location['longitude']);
} | identifier_body |
create-post.component.ts | import { Component, OnInit, Inject, EventEmitter, Output } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material';
import { CreatePost, File } from '../../model';
import { CreatePostService, SnackbarService, LocationService, FileService } from '../../services';
import { CreateFileComponent } from '../create-file';
import { FileDialogComponent } from '../file-dialog'; | selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent {
private internalIsLoading = false;
private internalPostText = '';
private selectedFile: number | undefined = undefined;
@Output() private postCreated = new EventEmitter<number>();
constructor(
public dialogRef: MatDialogRef<CreatePostComponent>,
private fileService: FileService,
private createPostService: CreatePostService,
private snackbarService: SnackbarService,
private locationService: LocationService,
private dialog: MatDialog) {
}
public get fileId(): number {
return this.selectedFile;
}
public get isLoading(): boolean {
return this.internalIsLoading;
}
public set isLoading(value: boolean) {
this.internalIsLoading = value;
}
public set postText(value: string) {
this.internalPostText = value;
}
public get postText(): string {
return this.internalPostText;
}
public onFilePreview(): void {
if (this.selectedFile) {
this.isLoading = true;
this.fileService.getFile(this.selectedFile).then(x => {
this.isLoading = false;
this.dialog.open(FileDialogComponent, {
width: '70%',
data: {
file: <File>x
}
});
});
}
}
public onNoClick(): void {
this.dialogRef.close(-1);
}
public closeDialog(): void {
this.dialogRef.close(-1);
}
public removeFile(): void {
this.selectedFile = undefined;
}
public addFile(): void {
const dialogRef = this.dialog.open(CreateFileComponent, {
width: '60%'
});
dialogRef.afterClosed().subscribe(async result => {
if (result > 0) {
this.selectedFile = <number>result;
}
});
}
public async createPost(): Promise<void> {
try {
this.isLoading = true;
const createPost = await this.createCreatePostModel();
if (this.selectedFile) {
createPost.fileId = this.selectedFile;
}
const result = await this.createPostService.createPost(createPost);
this.dialogRef.close(result);
this.snackbarService.showMessage('Post created');
this.postCreated.emit(result);
} finally {
this.isLoading = false;
}
}
public async createCreatePostModel(): Promise<CreatePost> {
const location = await this.locationService.getLocation();
return new CreatePost(this.postText, <number>location['latitude'], <number>location['longitude']);
}
} |
@Component({ | random_line_split |
bounty.py | when reward is 0)
TDL -- More to be defined in later versions
"""
def __repr__(self):
"""Gives a string representation of the bounty"""
output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward)
output = output + ", id=" + str(self.ident) + ", timeout=" + str(self.timeout)
output = output + ", author=" + str(self.data.get('author'))
if self.data.get('reqs') != {} and isinstance(self.data.get('reqs'), dict):
output = output + ", reqs=" + str(sorted(self.data.get('reqs').items(), key=lambda x: x[0]))
if self.data.get('perms') != {} and isinstance(self.data.get('perms'), dict):
output = output + ", perms=" + str(sorted(self.data.get('perms').items(), key=lambda x: x[0]))
return output + ">"
def __eq__(self, other):
"""Determines whether the bounties are equal"""
try:
return (self.reward == other.reward) and (self.ident == other.ident) and (self.data == other.data)
except:
return other is not None
def __ne__(self, other):
"""Determines whether the bounties are unequal"""
try:
return not self.__eq__(other)
except:
return other is None
def __lt__(self, other):
"""Determines whether this bounty has a lower priority"""
try:
if self.reward < other.reward:
return True
elif self.timeout < other.timeout:
return True
else:
return False
except:
return other is not None
def __gt__(self, other):
"""Determines whether this bounty has a higher priority"""
try:
if self.reward > other.reward:
return True
elif self.timeout > other.timeout:
return True
else:
return False
except:
return other is None
def __le__(self, other):
"""Determines whether this bounty has a lower priority or is equal"""
boolean = self.__lt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __ge__(self, other):
"""Determines whether this bounty has a higher or is equal"""
boolean = self.__gt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __hash__(self):
return hash((self.__repr__(), str(self.data)))
def __init__(self, ipAddress, btcAddress, rewardAmount, **kargs):
"""Initialize a Bounty; constructor"""
self.ip = ipAddress
self.btc = btcAddress
self.reward = rewardAmount
self.ident = ''
if kargs.get('timeout') is not None:
self.timeout = kargs.get('timeout')
else:
self.timeout = getUTC() + 86400
self.data = {'author': '',
'reqs': {},
'perms': {}}
if kargs.get('ident') is not None:
self.ident = kargs.get('ident')
if kargs.get('dataDict') is not None:
self.data.update(kargs.get('dataDict'))
if kargs.get('keypair') is not None:
self.sign(kargs.get('keypair'))
def isValid(self):
"""Internal method which checks the Bounty as valid in the most minimal version
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(self.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(self.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if self.reward not in range(1440, 100000001) or (not self.reward and self.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if self.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(self.data.get('reqs')):
return 1
return -1
except:
return False
def isPayable(self, factor):
"""check if address has enough"""
return True # later make this a wrapper for pywallet.balance()
def checkSign(self):
"""check if the signature attatched to the Bounty is valid"""
try:
from rsa import verify, PublicKey
safeprint(keyList)
if self.data.get('cert'): # where key = (PublicKey.n, PublicKey.e)
expected = str(self).encode('utf-8')
data = self.data
n = data.get('key')[0]
e = data.get('key')[1]
if rsa.verify(str((n, e)).encode('utf-8'), data.get('cert'), masterKey):
return verify(expected, data.get('sig'), PublicKey(n, e))
return False
except:
return False
def sign(self, privateKey): # where privateKey is a private key generated by rsa.PrivateKey()
"""Signa bounty and attach the key value"""
try:
from rsa import sign
expected = str(self).encode('utf-8')
self.data.update({'key': (privateKey.n, privateKey.e),
'sig': sign(expected, privateKey, 'SHA-256')})
except:
return False
def checkBTCAddressValid(address):
"""Check to see if a Bitcoin address is within the valid namespace. Will potentially give false positives based on leading 1s"""
if not re.match(re.compile("^[a-km-zA-HJ-Z1-9]{26,35}$"), address):
return False
decimal = 0
for char in address:
decimal = decimal * 58 + '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.index(char)
bcbytes = ""
if sys.version_info[0] < 3:
"""long does not have a to_bytes() in versions less than 3. This is an equivalent function"""
bcbytes = (('%%0%dx' % (25 << 1) % decimal).decode('hex')[-25:])
else:
bcbytes = decimal.to_bytes(25, 'big')
return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
def | (address):
try:
import socket
socket.getaddrinfo(*address)
a = len(address[0].split(":")) == 1 # Make sure it's not ipv6
b = len(address[0].split(".")) == 4 # Make sure it's not shortened
return a and b and address[1] in range(49152)
except:
return False
def verify(string):
"""External method which checks the Bounty as valid under implementation-specific requirements. This can be defined per user.
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
test = depickle(string)
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(test.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(test.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if test.reward not in range(1440, 100000001) or (not test.reward and test.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if test.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(test.data.get('reqs')):
return 1
return -1
except:
return False
def getBountyList():
"""Retrieves the bounty list. Temporary method"""
temp = []
with bountyLock:
temp = bountyList[:]
return temp
def saveToFile():
"""Save the current bounty list to a file"""
if not os.path.exists(bounty_path.split(os.sep)[0]):
os.mkdir(bounty_path.split(os.sep)[0])
pickle.dump(getBountyList(), open(bounty_path, "wb"), 0)
return True
def loadFromFile():
"""Load a previous bounty list from a file"""
if os.path.exists(bounty_path):
with bountyLock:
try:
safeprint("Loading bounty list from file", verbosity=2)
templist = pickle.load(open(bounty_path, "rb"))
| checkIPAddressValid | identifier_name |
bounty.py | when reward is 0)
TDL -- More to be defined in later versions
"""
def __repr__(self):
"""Gives a string representation of the bounty"""
output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward)
output = output + ", id=" + str(self.ident) + ", timeout=" + str(self.timeout)
output = output + ", author=" + str(self.data.get('author'))
if self.data.get('reqs') != {} and isinstance(self.data.get('reqs'), dict):
output = output + ", reqs=" + str(sorted(self.data.get('reqs').items(), key=lambda x: x[0]))
if self.data.get('perms') != {} and isinstance(self.data.get('perms'), dict):
output = output + ", perms=" + str(sorted(self.data.get('perms').items(), key=lambda x: x[0]))
return output + ">"
def __eq__(self, other):
"""Determines whether the bounties are equal"""
try:
return (self.reward == other.reward) and (self.ident == other.ident) and (self.data == other.data)
except:
return other is not None
def __ne__(self, other):
"""Determines whether the bounties are unequal"""
try:
return not self.__eq__(other)
except:
return other is None
def __lt__(self, other):
"""Determines whether this bounty has a lower priority"""
try:
if self.reward < other.reward:
return True
elif self.timeout < other.timeout:
return True
else:
return False
except:
return other is not None
def __gt__(self, other):
|
def __le__(self, other):
"""Determines whether this bounty has a lower priority or is equal"""
boolean = self.__lt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __ge__(self, other):
"""Determines whether this bounty has a higher or is equal"""
boolean = self.__gt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __hash__(self):
return hash((self.__repr__(), str(self.data)))
def __init__(self, ipAddress, btcAddress, rewardAmount, **kargs):
"""Initialize a Bounty; constructor"""
self.ip = ipAddress
self.btc = btcAddress
self.reward = rewardAmount
self.ident = ''
if kargs.get('timeout') is not None:
self.timeout = kargs.get('timeout')
else:
self.timeout = getUTC() + 86400
self.data = {'author': '',
'reqs': {},
'perms': {}}
if kargs.get('ident') is not None:
self.ident = kargs.get('ident')
if kargs.get('dataDict') is not None:
self.data.update(kargs.get('dataDict'))
if kargs.get('keypair') is not None:
self.sign(kargs.get('keypair'))
def isValid(self):
"""Internal method which checks the Bounty as valid in the most minimal version
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(self.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(self.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if self.reward not in range(1440, 100000001) or (not self.reward and self.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if self.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(self.data.get('reqs')):
return 1
return -1
except:
return False
def isPayable(self, factor):
"""check if address has enough"""
return True # later make this a wrapper for pywallet.balance()
def checkSign(self):
"""check if the signature attatched to the Bounty is valid"""
try:
from rsa import verify, PublicKey
safeprint(keyList)
if self.data.get('cert'): # where key = (PublicKey.n, PublicKey.e)
expected = str(self).encode('utf-8')
data = self.data
n = data.get('key')[0]
e = data.get('key')[1]
if rsa.verify(str((n, e)).encode('utf-8'), data.get('cert'), masterKey):
return verify(expected, data.get('sig'), PublicKey(n, e))
return False
except:
return False
def sign(self, privateKey): # where privateKey is a private key generated by rsa.PrivateKey()
"""Signa bounty and attach the key value"""
try:
from rsa import sign
expected = str(self).encode('utf-8')
self.data.update({'key': (privateKey.n, privateKey.e),
'sig': sign(expected, privateKey, 'SHA-256')})
except:
return False
def checkBTCAddressValid(address):
"""Check to see if a Bitcoin address is within the valid namespace. Will potentially give false positives based on leading 1s"""
if not re.match(re.compile("^[a-km-zA-HJ-Z1-9]{26,35}$"), address):
return False
decimal = 0
for char in address:
decimal = decimal * 58 + '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.index(char)
bcbytes = ""
if sys.version_info[0] < 3:
"""long does not have a to_bytes() in versions less than 3. This is an equivalent function"""
bcbytes = (('%%0%dx' % (25 << 1) % decimal).decode('hex')[-25:])
else:
bcbytes = decimal.to_bytes(25, 'big')
return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
def checkIPAddressValid(address):
try:
import socket
socket.getaddrinfo(*address)
a = len(address[0].split(":")) == 1 # Make sure it's not ipv6
b = len(address[0].split(".")) == 4 # Make sure it's not shortened
return a and b and address[1] in range(49152)
except:
return False
def verify(string):
"""External method which checks the Bounty as valid under implementation-specific requirements. This can be defined per user.
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
test = depickle(string)
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(test.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(test.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if test.reward not in range(1440, 100000001) or (not test.reward and test.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if test.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(test.data.get('reqs')):
return 1
return -1
except:
return False
def getBountyList():
"""Retrieves the bounty list. Temporary method"""
temp = []
with bountyLock:
temp = bountyList[:]
return temp
def saveToFile():
"""Save the current bounty list to a file"""
if not os.path.exists(bounty_path.split(os.sep)[0]):
os.mkdir(bounty_path.split(os.sep)[0])
pickle.dump(getBountyList(), open(bounty_path, "wb"), 0)
return True
def loadFromFile():
"""Load a previous bounty list from a file"""
if os.path.exists(bounty_path):
with bountyLock:
try:
safeprint("Loading bounty list from file", verbosity=2)
templist = pickle.load(open(bounty_path, "rb"))
| """Determines whether this bounty has a higher priority"""
try:
if self.reward > other.reward:
return True
elif self.timeout > other.timeout:
return True
else:
return False
except:
return other is None | identifier_body |
bounty.py | output = output + ", id=" + str(self.ident) + ", timeout=" + str(self.timeout)
output = output + ", author=" + str(self.data.get('author'))
if self.data.get('reqs') != {} and isinstance(self.data.get('reqs'), dict):
output = output + ", reqs=" + str(sorted(self.data.get('reqs').items(), key=lambda x: x[0]))
if self.data.get('perms') != {} and isinstance(self.data.get('perms'), dict):
output = output + ", perms=" + str(sorted(self.data.get('perms').items(), key=lambda x: x[0]))
return output + ">"
def __eq__(self, other):
"""Determines whether the bounties are equal"""
try:
return (self.reward == other.reward) and (self.ident == other.ident) and (self.data == other.data)
except:
return other is not None
def __ne__(self, other):
"""Determines whether the bounties are unequal"""
try:
return not self.__eq__(other)
except:
return other is None
def __lt__(self, other):
"""Determines whether this bounty has a lower priority"""
try:
if self.reward < other.reward:
return True
elif self.timeout < other.timeout:
return True
else:
return False
except:
return other is not None
def __gt__(self, other):
"""Determines whether this bounty has a higher priority"""
try:
if self.reward > other.reward:
return True
elif self.timeout > other.timeout:
return True
else:
return False
except:
return other is None
def __le__(self, other):
"""Determines whether this bounty has a lower priority or is equal"""
boolean = self.__lt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __ge__(self, other):
"""Determines whether this bounty has a higher or is equal"""
boolean = self.__gt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __hash__(self):
return hash((self.__repr__(), str(self.data)))
def __init__(self, ipAddress, btcAddress, rewardAmount, **kargs):
"""Initialize a Bounty; constructor"""
self.ip = ipAddress
self.btc = btcAddress
self.reward = rewardAmount
self.ident = ''
if kargs.get('timeout') is not None:
self.timeout = kargs.get('timeout')
else:
self.timeout = getUTC() + 86400
self.data = {'author': '',
'reqs': {},
'perms': {}}
if kargs.get('ident') is not None:
self.ident = kargs.get('ident')
if kargs.get('dataDict') is not None:
self.data.update(kargs.get('dataDict'))
if kargs.get('keypair') is not None:
self.sign(kargs.get('keypair'))
def isValid(self):
"""Internal method which checks the Bounty as valid in the most minimal version
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(self.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(self.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if self.reward not in range(1440, 100000001) or (not self.reward and self.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if self.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(self.data.get('reqs')):
return 1
return -1
except:
return False
def isPayable(self, factor):
"""check if address has enough"""
return True # later make this a wrapper for pywallet.balance()
def checkSign(self):
"""check if the signature attatched to the Bounty is valid"""
try:
from rsa import verify, PublicKey
safeprint(keyList)
if self.data.get('cert'): # where key = (PublicKey.n, PublicKey.e)
expected = str(self).encode('utf-8')
data = self.data
n = data.get('key')[0]
e = data.get('key')[1]
if rsa.verify(str((n, e)).encode('utf-8'), data.get('cert'), masterKey):
return verify(expected, data.get('sig'), PublicKey(n, e))
return False
except:
return False
def sign(self, privateKey): # where privateKey is a private key generated by rsa.PrivateKey()
"""Signa bounty and attach the key value"""
try:
from rsa import sign
expected = str(self).encode('utf-8')
self.data.update({'key': (privateKey.n, privateKey.e),
'sig': sign(expected, privateKey, 'SHA-256')})
except:
return False
def checkBTCAddressValid(address):
"""Check to see if a Bitcoin address is within the valid namespace. Will potentially give false positives based on leading 1s"""
if not re.match(re.compile("^[a-km-zA-HJ-Z1-9]{26,35}$"), address):
return False
decimal = 0
for char in address:
decimal = decimal * 58 + '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.index(char)
bcbytes = ""
if sys.version_info[0] < 3:
"""long does not have a to_bytes() in versions less than 3. This is an equivalent function"""
bcbytes = (('%%0%dx' % (25 << 1) % decimal).decode('hex')[-25:])
else:
bcbytes = decimal.to_bytes(25, 'big')
return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
def checkIPAddressValid(address):
try:
import socket
socket.getaddrinfo(*address)
a = len(address[0].split(":")) == 1 # Make sure it's not ipv6
b = len(address[0].split(".")) == 4 # Make sure it's not shortened
return a and b and address[1] in range(49152)
except:
return False
def verify(string):
"""External method which checks the Bounty as valid under implementation-specific requirements. This can be defined per user.
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
test = depickle(string)
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(test.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(test.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if test.reward not in range(1440, 100000001) or (not test.reward and test.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if test.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(test.data.get('reqs')):
return 1
return -1
except:
return False
def getBountyList():
"""Retrieves the bounty list. Temporary method"""
temp = []
with bountyLock:
temp = bountyList[:]
return temp
def saveToFile():
"""Save the current bounty list to a file"""
if not os.path.exists(bounty_path.split(os.sep)[0]):
os.mkdir(bounty_path.split(os.sep)[0])
pickle.dump(getBountyList(), open(bounty_path, "wb"), 0)
return True
def loadFromFile():
"""Load a previous bounty list from a file"""
if os.path.exists(bounty_path):
with bountyLock:
try:
safeprint("Loading bounty list from file", verbosity=2)
templist = pickle.load(open(bounty_path, "rb"))
safeprint(addBounties(templist), verbosity=3)
safeprint("Bounty list loaded and added", verbosity=2)
except:
return False
return True
return False
def depickle(string): | """Handles the potential errors in unpickling a bounty"""
if isinstance(string, Bounty):
return string | random_line_split |
|
bounty.py | when reward is 0)
TDL -- More to be defined in later versions
"""
def __repr__(self):
"""Gives a string representation of the bounty"""
output = "<Bounty: ip=" + str(self.ip) + ", btc=" + str(self.btc) + ", reward=" + str(self.reward)
output = output + ", id=" + str(self.ident) + ", timeout=" + str(self.timeout)
output = output + ", author=" + str(self.data.get('author'))
if self.data.get('reqs') != {} and isinstance(self.data.get('reqs'), dict):
output = output + ", reqs=" + str(sorted(self.data.get('reqs').items(), key=lambda x: x[0]))
if self.data.get('perms') != {} and isinstance(self.data.get('perms'), dict):
output = output + ", perms=" + str(sorted(self.data.get('perms').items(), key=lambda x: x[0]))
return output + ">"
def __eq__(self, other):
"""Determines whether the bounties are equal"""
try:
return (self.reward == other.reward) and (self.ident == other.ident) and (self.data == other.data)
except:
return other is not None
def __ne__(self, other):
"""Determines whether the bounties are unequal"""
try:
return not self.__eq__(other)
except:
return other is None
def __lt__(self, other):
"""Determines whether this bounty has a lower priority"""
try:
if self.reward < other.reward:
return True
elif self.timeout < other.timeout:
return True
else:
return False
except:
return other is not None
def __gt__(self, other):
"""Determines whether this bounty has a higher priority"""
try:
if self.reward > other.reward:
return True
elif self.timeout > other.timeout:
return True
else:
return False
except:
return other is None
def __le__(self, other):
"""Determines whether this bounty has a lower priority or is equal"""
boolean = self.__lt__(other)
if boolean:
return boolean
else:
return self.__eq__(other)
def __ge__(self, other):
"""Determines whether this bounty has a higher or is equal"""
boolean = self.__gt__(other)
if boolean:
return boolean
else:
|
def __hash__(self):
return hash((self.__repr__(), str(self.data)))
def __init__(self, ipAddress, btcAddress, rewardAmount, **kargs):
"""Initialize a Bounty; constructor"""
self.ip = ipAddress
self.btc = btcAddress
self.reward = rewardAmount
self.ident = ''
if kargs.get('timeout') is not None:
self.timeout = kargs.get('timeout')
else:
self.timeout = getUTC() + 86400
self.data = {'author': '',
'reqs': {},
'perms': {}}
if kargs.get('ident') is not None:
self.ident = kargs.get('ident')
if kargs.get('dataDict') is not None:
self.data.update(kargs.get('dataDict'))
if kargs.get('keypair') is not None:
self.sign(kargs.get('keypair'))
def isValid(self):
"""Internal method which checks the Bounty as valid in the most minimal version
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(self.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(self.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if self.reward not in range(1440, 100000001) or (not self.reward and self.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if self.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(self.data.get('reqs')):
return 1
return -1
except:
return False
def isPayable(self, factor):
"""check if address has enough"""
return True # later make this a wrapper for pywallet.balance()
def checkSign(self):
"""check if the signature attatched to the Bounty is valid"""
try:
from rsa import verify, PublicKey
safeprint(keyList)
if self.data.get('cert'): # where key = (PublicKey.n, PublicKey.e)
expected = str(self).encode('utf-8')
data = self.data
n = data.get('key')[0]
e = data.get('key')[1]
if rsa.verify(str((n, e)).encode('utf-8'), data.get('cert'), masterKey):
return verify(expected, data.get('sig'), PublicKey(n, e))
return False
except:
return False
def sign(self, privateKey): # where privateKey is a private key generated by rsa.PrivateKey()
"""Signa bounty and attach the key value"""
try:
from rsa import sign
expected = str(self).encode('utf-8')
self.data.update({'key': (privateKey.n, privateKey.e),
'sig': sign(expected, privateKey, 'SHA-256')})
except:
return False
def checkBTCAddressValid(address):
"""Check to see if a Bitcoin address is within the valid namespace. Will potentially give false positives based on leading 1s"""
if not re.match(re.compile("^[a-km-zA-HJ-Z1-9]{26,35}$"), address):
return False
decimal = 0
for char in address:
decimal = decimal * 58 + '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.index(char)
bcbytes = ""
if sys.version_info[0] < 3:
"""long does not have a to_bytes() in versions less than 3. This is an equivalent function"""
bcbytes = (('%%0%dx' % (25 << 1) % decimal).decode('hex')[-25:])
else:
bcbytes = decimal.to_bytes(25, 'big')
return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
def checkIPAddressValid(address):
try:
import socket
socket.getaddrinfo(*address)
a = len(address[0].split(":")) == 1 # Make sure it's not ipv6
b = len(address[0].split(".")) == 4 # Make sure it's not shortened
return a and b and address[1] in range(49152)
except:
return False
def verify(string):
"""External method which checks the Bounty as valid under implementation-specific requirements. This can be defined per user.
ip -- Must be in valid range
btc -- Must be in valid namespace
reward -- Must be in valid range
timeout -- Must be greater than the current time
"""
test = depickle(string)
try:
safeprint("Testing IP address", verbosity=1)
if not checkIPAddressValid(test.ip):
return False
safeprint("Testing Bitcoin address", verbosity=1)
# The following is a soft check
# A deeper check will be needed in order to assure this is correct
if not checkBTCAddressValid(test.btc):
return False
safeprint("Testing reward and/or signiture validity", verbosity=1)
if test.reward not in range(1440, 100000001) or (not test.reward and test.checkSign()):
return False
safeprint("Testing timeout", verbosity=1)
if test.timeout < getUTC(): # check against current UTC
return False
safeprint("Testing bounty requirements", verbosity=1)
if parse(test.data.get('reqs')):
return 1
return -1
except:
return False
def getBountyList():
"""Retrieves the bounty list. Temporary method"""
temp = []
with bountyLock:
temp = bountyList[:]
return temp
def saveToFile():
"""Save the current bounty list to a file"""
if not os.path.exists(bounty_path.split(os.sep)[0]):
os.mkdir(bounty_path.split(os.sep)[0])
pickle.dump(getBountyList(), open(bounty_path, "wb"), 0)
return True
def loadFromFile():
"""Load a previous bounty list from a file"""
if os.path.exists(bounty_path):
with bountyLock:
try:
safeprint("Loading bounty list from file", verbosity=2)
templist = pickle.load(open(bounty_path, "rb"))
| return self.__eq__(other) | conditional_block |
record_type.rs | use crate::library;
#[derive(PartialEq, Eq)]
pub enum | {
/// Boxed record that use g_boxed_copy, g_boxed_free.
/// Must have glib_get_type function
AutoBoxed,
/// Boxed record with custom copy/free functions
Boxed,
/// Referencecounted record
Refcounted,
//TODO: detect and generate direct records
//Direct,
}
impl RecordType {
pub fn of(record: &library::Record) -> RecordType {
let mut has_copy = false;
let mut has_free = false;
let mut has_ref = false;
let mut has_unref = false;
let mut has_destroy = false;
for func in &record.functions {
match &func.name[..] {
"copy" => has_copy = true,
"free" => has_free = true,
"destroy" => has_destroy = true,
"ref" => has_ref = true,
"unref" => has_unref = true,
_ => (),
}
}
if has_destroy && has_copy {
has_free = true;
}
if has_ref && has_unref {
RecordType::Refcounted
} else if has_copy && has_free {
RecordType::Boxed
} else {
RecordType::AutoBoxed
}
}
}
| RecordType | identifier_name |
record_type.rs | use crate::library;
#[derive(PartialEq, Eq)]
pub enum RecordType {
/// Boxed record that use g_boxed_copy, g_boxed_free.
/// Must have glib_get_type function
AutoBoxed,
/// Boxed record with custom copy/free functions
Boxed,
/// Referencecounted record
Refcounted,
//TODO: detect and generate direct records
//Direct,
}
impl RecordType {
pub fn of(record: &library::Record) -> RecordType |
if has_ref && has_unref {
RecordType::Refcounted
} else if has_copy && has_free {
RecordType::Boxed
} else {
RecordType::AutoBoxed
}
}
}
| {
let mut has_copy = false;
let mut has_free = false;
let mut has_ref = false;
let mut has_unref = false;
let mut has_destroy = false;
for func in &record.functions {
match &func.name[..] {
"copy" => has_copy = true,
"free" => has_free = true,
"destroy" => has_destroy = true,
"ref" => has_ref = true,
"unref" => has_unref = true,
_ => (),
}
}
if has_destroy && has_copy {
has_free = true;
} | identifier_body |
record_type.rs | use crate::library;
#[derive(PartialEq, Eq)]
pub enum RecordType {
/// Boxed record that use g_boxed_copy, g_boxed_free.
/// Must have glib_get_type function
AutoBoxed,
/// Boxed record with custom copy/free functions
Boxed,
/// Referencecounted record
Refcounted,
//TODO: detect and generate direct records
//Direct,
}
impl RecordType {
pub fn of(record: &library::Record) -> RecordType {
let mut has_copy = false;
let mut has_free = false;
let mut has_ref = false;
let mut has_unref = false;
let mut has_destroy = false;
for func in &record.functions {
match &func.name[..] {
"copy" => has_copy = true,
"free" => has_free = true,
"destroy" => has_destroy = true,
"ref" => has_ref = true,
"unref" => has_unref = true,
_ => (),
}
}
if has_destroy && has_copy {
has_free = true;
}
if has_ref && has_unref {
RecordType::Refcounted
} else if has_copy && has_free {
RecordType::Boxed | } | } else {
RecordType::AutoBoxed
}
} | random_line_split |
stache.js | // RequireJS Mustache template plugin
// http://github.com/jfparadis/requirejs-mustache
//
// An alternative to https://github.com/millermedeiros/requirejs-hogan-plugin
//
// Using Mustache Logic-less templates at http://mustache.github.com
// Using and RequireJS text.js at http://requirejs.org/docs/api.html#text
// @author JF Paradis
// @version 0.0.3
//
// Released under the MIT license
// Usage:
// require(['backbone', 'stache!mytemplate'], function (Backbone, mytemplate) {
// return Backbone.View.extend({
// initialize: function(){
// this.render();
// },
// render: function(){
// this.$el.html(mytemplate({message: 'hello'}));
// });
// });
//
// Configuration: (optional)
// require.config({
// stache: {
// extension: '.stache' // default = '.html'
// }
// });
/*jslint nomen: true */
/*global define: false */
var mustacheDep = "bgpst.lib.mustache";
define(["bgpst.lib.text", mustacheDep], function (text, Mustache) {
var sourceMap = {},
buildMap = {},
buildTemplateSource = "define('{pluginName}!{moduleName}', ['" + mustacheDep + "'], function (Mustache) { " +
"var template = '{content}'; Mustache.parse( template ); " +
"return function( view, partials) { return Mustache.render( template, view, partials); } });\n";
return {
version: '0.0.3',
load: function (moduleName, parentRequire, onload, config) {
if (buildMap[moduleName]) {
onload(buildMap[moduleName]);
} else {
var ext = (config.stache && config.stache.extension) || '.html';
var path = (config.stache && config.stache.path) || '';
text.load(path + moduleName + ext, parentRequire, function (source) {
if (config.isBuild) {
sourceMap[moduleName] = source; | buildMap[moduleName] = function( view, partials) {
return Mustache.render( source, view, partials);
};
onload(buildMap[moduleName]);
}
}, config);
}
},
write: function (pluginName, moduleName, write, config) {
var source = sourceMap[moduleName],
content = source && text.jsEscape(source);
if (content) {
write.asModule(pluginName + '!' + moduleName,
buildTemplateSource
.replace('{pluginName}', pluginName)
.replace('{moduleName}', moduleName)
.replace('{content}', content));
}
}
};
}); | onload();
} else {
Mustache.parse(source); | random_line_split |
stache.js | // RequireJS Mustache template plugin
// http://github.com/jfparadis/requirejs-mustache
//
// An alternative to https://github.com/millermedeiros/requirejs-hogan-plugin
//
// Using Mustache Logic-less templates at http://mustache.github.com
// Using and RequireJS text.js at http://requirejs.org/docs/api.html#text
// @author JF Paradis
// @version 0.0.3
//
// Released under the MIT license
// Usage:
// require(['backbone', 'stache!mytemplate'], function (Backbone, mytemplate) {
// return Backbone.View.extend({
// initialize: function(){
// this.render();
// },
// render: function(){
// this.$el.html(mytemplate({message: 'hello'}));
// });
// });
//
// Configuration: (optional)
// require.config({
// stache: {
// extension: '.stache' // default = '.html'
// }
// });
/*jslint nomen: true */
/*global define: false */
var mustacheDep = "bgpst.lib.mustache";
define(["bgpst.lib.text", mustacheDep], function (text, Mustache) {
var sourceMap = {},
buildMap = {},
buildTemplateSource = "define('{pluginName}!{moduleName}', ['" + mustacheDep + "'], function (Mustache) { " +
"var template = '{content}'; Mustache.parse( template ); " +
"return function( view, partials) { return Mustache.render( template, view, partials); } });\n";
return {
version: '0.0.3',
load: function (moduleName, parentRequire, onload, config) {
if (buildMap[moduleName]) {
onload(buildMap[moduleName]);
} else {
var ext = (config.stache && config.stache.extension) || '.html';
var path = (config.stache && config.stache.path) || '';
text.load(path + moduleName + ext, parentRequire, function (source) {
if (config.isBuild) {
sourceMap[moduleName] = source;
onload();
} else |
}, config);
}
},
write: function (pluginName, moduleName, write, config) {
var source = sourceMap[moduleName],
content = source && text.jsEscape(source);
if (content) {
write.asModule(pluginName + '!' + moduleName,
buildTemplateSource
.replace('{pluginName}', pluginName)
.replace('{moduleName}', moduleName)
.replace('{content}', content));
}
}
};
}); | {
Mustache.parse(source);
buildMap[moduleName] = function( view, partials) {
return Mustache.render( source, view, partials);
};
onload(buildMap[moduleName]);
} | conditional_block |
base64.artifact.ts | import { module } from 'angular';
import { ArtifactTypePatterns } from 'core/artifact';
import { IArtifact } from 'core/domain/IArtifact';
import { Registry } from 'core/registry';
import './base64.artifact.less';
export const BASE64_ARTIFACT = 'spinnaker.core.pipeline.trigger.artifact.base64';
module(BASE64_ARTIFACT, []).config(() => {
Registry.pipeline.mergeArtifactKind({
label: 'Base64',
typePattern: ArtifactTypePatterns.EMBEDDED_BASE64,
type: 'embedded/base64',
description: 'An artifact that includes its referenced resource as part of its payload.',
key: 'base64',
isDefault: false,
isMatch: true,
controller: function(artifact: IArtifact) {
this.artifact = artifact;
this.artifact.type = 'embedded/base64';
},
controllerAs: 'ctrl',
template: `
<div class="col-md-12">
<div class="form-group row">
<label class="col-md-2 sm-label-right">
Name
</label> | class="form-control input-sm"
ng-model="ctrl.artifact.name" />
</div>
</div>
</div>
`,
});
}); | <div class="col-md-8">
<input type="text"
placeholder="base64-artifact" | random_line_split |
signup.ts | /*
* MIT License
*
* Copyright (c) 2017 David Garcia <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import {Component} from '@angular/core';
import {AlertController, App, Keyboard, LoadingController} from 'ionic-angular';
import {BarcodeScanner} from '@ionic-native/barcode-scanner';
import {TranslateService} from '@ngx-translate/core';
import {AlertProvider} from '../../providers/alert/alert.provider';
import {WalletProvider} from '../../providers/wallet/wallet.provider';
import {LoginPage} from '../login/login';
import {Password, QRService, SimpleWallet} from "nem-library";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {PasswordValidation} from "../../validators/password.validator";
import {NemValidator} from "../../validators/nem.validator";
@Component({
selector: 'page-signup-privatekey',
templateUrl: 'signup.html'
})
export class | {
private signupForm : FormGroup;
private qrService: QRService;
constructor(public app: App, private wallet: WalletProvider,
private loading: LoadingController, private alertCtrl: AlertController,
private alert: AlertProvider, public translate: TranslateService,
private barcodeScanner: BarcodeScanner, private keyboard: Keyboard) {
this.signupForm = new FormGroup ({
name: new FormControl('', Validators.required),
password: new FormControl('', Validators.minLength(8)),
repeatPassword: new FormControl(''),
privateKey: new FormControl('', NemValidator.isValidPrivateKey)
}, PasswordValidation.EqualPasswords);
this.qrService = new QRService();
}
/**
* Scans and decrypt QR wallet
*/
public scanWalletQR() {
this.barcodeScanner.scan().then(barcode => {
let walletInfo = JSON.parse(barcode.text);
this.translate
.get(['IMPORT_ACCOUNT_QR_WARNING', 'PASSWORD', 'CANCEL', 'CONFIRM', 'PLEASE_WAIT'], {})
.subscribe((res) => {
let alert = this.alertCtrl.create({
title: res['PASSWORD'],
subTitle: res['IMPORT_ACCOUNT_QR_WARNING'],
inputs: [{name: 'password', placeholder: res['PASSWORD'], type: 'password'}],
buttons: [{text: res['CANCEL'], role: 'cancel'}, { text: res['CONFIRM'], handler: data => {
this.keyboard.close();
let loader = this.loading.create({content: res['PLEASE_WAIT']});
loader.present().then(ignored => {
if (data.password.length < 8) {
this.alert.showWeakPassword();
loader.dismiss();
} else {
try {
const privateKey = this.qrService
.decryptWalletQRText(new Password(data.password), walletInfo);
this.signupForm.patchValue({'privateKey': privateKey});
loader.dismiss();
} catch (err) {
this.alert.showInvalidPasswordAlert();
loader.dismiss();
}
}
}).catch(err => console.log(err));
}
}]
});
alert.onDidDismiss(() => {
this.keyboard.close();
});
alert.present();
}, err => console.log(err));
}).catch(err => console.log("Error on scan"));
};
/**
* Creates a private key wallet
*/
public createPrivateKeyWallet() {
const form = this.signupForm.value;
this.translate
.get('PLEASE_WAIT', {})
.subscribe((res: string) => {
let loader = this.loading.create({content: res});
loader.present().then(ignored => {
this.wallet.checkIfWalletNameExists(form.name).then(exists => {
if (exists) {
loader.dismiss();
this.alert.showWalletNameAlreadyExists();
} else {
try {
const createdWallet = SimpleWallet
.createWithPrivateKey(form.name, new Password(form.password), form.privateKey);
this.wallet.storeWallet(createdWallet).then(ignored => {
loader.dismiss();
this.app.getRootNav().push(LoginPage);
});
} catch (e) {
loader.dismiss();
this.alert.showInvalidPrivateKey();
}
}
});
});
}, err => console.log(err));
}
}
| SignupPrivateKeyPage | identifier_name |
signup.ts | /*
* MIT License
*
* Copyright (c) 2017 David Garcia <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import {Component} from '@angular/core';
import {AlertController, App, Keyboard, LoadingController} from 'ionic-angular'; | import {WalletProvider} from '../../providers/wallet/wallet.provider';
import {LoginPage} from '../login/login';
import {Password, QRService, SimpleWallet} from "nem-library";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {PasswordValidation} from "../../validators/password.validator";
import {NemValidator} from "../../validators/nem.validator";
@Component({
selector: 'page-signup-privatekey',
templateUrl: 'signup.html'
})
export class SignupPrivateKeyPage {
private signupForm : FormGroup;
private qrService: QRService;
constructor(public app: App, private wallet: WalletProvider,
private loading: LoadingController, private alertCtrl: AlertController,
private alert: AlertProvider, public translate: TranslateService,
private barcodeScanner: BarcodeScanner, private keyboard: Keyboard) {
this.signupForm = new FormGroup ({
name: new FormControl('', Validators.required),
password: new FormControl('', Validators.minLength(8)),
repeatPassword: new FormControl(''),
privateKey: new FormControl('', NemValidator.isValidPrivateKey)
}, PasswordValidation.EqualPasswords);
this.qrService = new QRService();
}
/**
* Scans and decrypt QR wallet
*/
public scanWalletQR() {
this.barcodeScanner.scan().then(barcode => {
let walletInfo = JSON.parse(barcode.text);
this.translate
.get(['IMPORT_ACCOUNT_QR_WARNING', 'PASSWORD', 'CANCEL', 'CONFIRM', 'PLEASE_WAIT'], {})
.subscribe((res) => {
let alert = this.alertCtrl.create({
title: res['PASSWORD'],
subTitle: res['IMPORT_ACCOUNT_QR_WARNING'],
inputs: [{name: 'password', placeholder: res['PASSWORD'], type: 'password'}],
buttons: [{text: res['CANCEL'], role: 'cancel'}, { text: res['CONFIRM'], handler: data => {
this.keyboard.close();
let loader = this.loading.create({content: res['PLEASE_WAIT']});
loader.present().then(ignored => {
if (data.password.length < 8) {
this.alert.showWeakPassword();
loader.dismiss();
} else {
try {
const privateKey = this.qrService
.decryptWalletQRText(new Password(data.password), walletInfo);
this.signupForm.patchValue({'privateKey': privateKey});
loader.dismiss();
} catch (err) {
this.alert.showInvalidPasswordAlert();
loader.dismiss();
}
}
}).catch(err => console.log(err));
}
}]
});
alert.onDidDismiss(() => {
this.keyboard.close();
});
alert.present();
}, err => console.log(err));
}).catch(err => console.log("Error on scan"));
};
/**
* Creates a private key wallet
*/
public createPrivateKeyWallet() {
const form = this.signupForm.value;
this.translate
.get('PLEASE_WAIT', {})
.subscribe((res: string) => {
let loader = this.loading.create({content: res});
loader.present().then(ignored => {
this.wallet.checkIfWalletNameExists(form.name).then(exists => {
if (exists) {
loader.dismiss();
this.alert.showWalletNameAlreadyExists();
} else {
try {
const createdWallet = SimpleWallet
.createWithPrivateKey(form.name, new Password(form.password), form.privateKey);
this.wallet.storeWallet(createdWallet).then(ignored => {
loader.dismiss();
this.app.getRootNav().push(LoginPage);
});
} catch (e) {
loader.dismiss();
this.alert.showInvalidPrivateKey();
}
}
});
});
}, err => console.log(err));
}
} | import {BarcodeScanner} from '@ionic-native/barcode-scanner';
import {TranslateService} from '@ngx-translate/core';
import {AlertProvider} from '../../providers/alert/alert.provider'; | random_line_split |
signup.ts | /*
* MIT License
*
* Copyright (c) 2017 David Garcia <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import {Component} from '@angular/core';
import {AlertController, App, Keyboard, LoadingController} from 'ionic-angular';
import {BarcodeScanner} from '@ionic-native/barcode-scanner';
import {TranslateService} from '@ngx-translate/core';
import {AlertProvider} from '../../providers/alert/alert.provider';
import {WalletProvider} from '../../providers/wallet/wallet.provider';
import {LoginPage} from '../login/login';
import {Password, QRService, SimpleWallet} from "nem-library";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {PasswordValidation} from "../../validators/password.validator";
import {NemValidator} from "../../validators/nem.validator";
@Component({
selector: 'page-signup-privatekey',
templateUrl: 'signup.html'
})
export class SignupPrivateKeyPage {
private signupForm : FormGroup;
private qrService: QRService;
constructor(public app: App, private wallet: WalletProvider,
private loading: LoadingController, private alertCtrl: AlertController,
private alert: AlertProvider, public translate: TranslateService,
private barcodeScanner: BarcodeScanner, private keyboard: Keyboard) {
this.signupForm = new FormGroup ({
name: new FormControl('', Validators.required),
password: new FormControl('', Validators.minLength(8)),
repeatPassword: new FormControl(''),
privateKey: new FormControl('', NemValidator.isValidPrivateKey)
}, PasswordValidation.EqualPasswords);
this.qrService = new QRService();
}
/**
* Scans and decrypt QR wallet
*/
public scanWalletQR() {
this.barcodeScanner.scan().then(barcode => {
let walletInfo = JSON.parse(barcode.text);
this.translate
.get(['IMPORT_ACCOUNT_QR_WARNING', 'PASSWORD', 'CANCEL', 'CONFIRM', 'PLEASE_WAIT'], {})
.subscribe((res) => {
let alert = this.alertCtrl.create({
title: res['PASSWORD'],
subTitle: res['IMPORT_ACCOUNT_QR_WARNING'],
inputs: [{name: 'password', placeholder: res['PASSWORD'], type: 'password'}],
buttons: [{text: res['CANCEL'], role: 'cancel'}, { text: res['CONFIRM'], handler: data => {
this.keyboard.close();
let loader = this.loading.create({content: res['PLEASE_WAIT']});
loader.present().then(ignored => {
if (data.password.length < 8) {
this.alert.showWeakPassword();
loader.dismiss();
} else {
try {
const privateKey = this.qrService
.decryptWalletQRText(new Password(data.password), walletInfo);
this.signupForm.patchValue({'privateKey': privateKey});
loader.dismiss();
} catch (err) {
this.alert.showInvalidPasswordAlert();
loader.dismiss();
}
}
}).catch(err => console.log(err));
}
}]
});
alert.onDidDismiss(() => {
this.keyboard.close();
});
alert.present();
}, err => console.log(err));
}).catch(err => console.log("Error on scan"));
};
/**
* Creates a private key wallet
*/
public createPrivateKeyWallet() {
const form = this.signupForm.value;
this.translate
.get('PLEASE_WAIT', {})
.subscribe((res: string) => {
let loader = this.loading.create({content: res});
loader.present().then(ignored => {
this.wallet.checkIfWalletNameExists(form.name).then(exists => {
if (exists) {
loader.dismiss();
this.alert.showWalletNameAlreadyExists();
} else |
});
});
}, err => console.log(err));
}
}
| {
try {
const createdWallet = SimpleWallet
.createWithPrivateKey(form.name, new Password(form.password), form.privateKey);
this.wallet.storeWallet(createdWallet).then(ignored => {
loader.dismiss();
this.app.getRootNav().push(LoginPage);
});
} catch (e) {
loader.dismiss();
this.alert.showInvalidPrivateKey();
}
} | conditional_block |
signup.ts | /*
* MIT License
*
* Copyright (c) 2017 David Garcia <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import {Component} from '@angular/core';
import {AlertController, App, Keyboard, LoadingController} from 'ionic-angular';
import {BarcodeScanner} from '@ionic-native/barcode-scanner';
import {TranslateService} from '@ngx-translate/core';
import {AlertProvider} from '../../providers/alert/alert.provider';
import {WalletProvider} from '../../providers/wallet/wallet.provider';
import {LoginPage} from '../login/login';
import {Password, QRService, SimpleWallet} from "nem-library";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {PasswordValidation} from "../../validators/password.validator";
import {NemValidator} from "../../validators/nem.validator";
@Component({
selector: 'page-signup-privatekey',
templateUrl: 'signup.html'
})
export class SignupPrivateKeyPage {
private signupForm : FormGroup;
private qrService: QRService;
constructor(public app: App, private wallet: WalletProvider,
private loading: LoadingController, private alertCtrl: AlertController,
private alert: AlertProvider, public translate: TranslateService,
private barcodeScanner: BarcodeScanner, private keyboard: Keyboard) {
this.signupForm = new FormGroup ({
name: new FormControl('', Validators.required),
password: new FormControl('', Validators.minLength(8)),
repeatPassword: new FormControl(''),
privateKey: new FormControl('', NemValidator.isValidPrivateKey)
}, PasswordValidation.EqualPasswords);
this.qrService = new QRService();
}
/**
* Scans and decrypt QR wallet
*/
public scanWalletQR() {
this.barcodeScanner.scan().then(barcode => {
let walletInfo = JSON.parse(barcode.text);
this.translate
.get(['IMPORT_ACCOUNT_QR_WARNING', 'PASSWORD', 'CANCEL', 'CONFIRM', 'PLEASE_WAIT'], {})
.subscribe((res) => {
let alert = this.alertCtrl.create({
title: res['PASSWORD'],
subTitle: res['IMPORT_ACCOUNT_QR_WARNING'],
inputs: [{name: 'password', placeholder: res['PASSWORD'], type: 'password'}],
buttons: [{text: res['CANCEL'], role: 'cancel'}, { text: res['CONFIRM'], handler: data => {
this.keyboard.close();
let loader = this.loading.create({content: res['PLEASE_WAIT']});
loader.present().then(ignored => {
if (data.password.length < 8) {
this.alert.showWeakPassword();
loader.dismiss();
} else {
try {
const privateKey = this.qrService
.decryptWalletQRText(new Password(data.password), walletInfo);
this.signupForm.patchValue({'privateKey': privateKey});
loader.dismiss();
} catch (err) {
this.alert.showInvalidPasswordAlert();
loader.dismiss();
}
}
}).catch(err => console.log(err));
}
}]
});
alert.onDidDismiss(() => {
this.keyboard.close();
});
alert.present();
}, err => console.log(err));
}).catch(err => console.log("Error on scan"));
};
/**
* Creates a private key wallet
*/
public createPrivateKeyWallet() | });
} catch (e) {
loader.dismiss();
this.alert.showInvalidPrivateKey();
}
}
});
});
}, err => console.log(err));
}
}
| {
const form = this.signupForm.value;
this.translate
.get('PLEASE_WAIT', {})
.subscribe((res: string) => {
let loader = this.loading.create({content: res});
loader.present().then(ignored => {
this.wallet.checkIfWalletNameExists(form.name).then(exists => {
if (exists) {
loader.dismiss();
this.alert.showWalletNameAlreadyExists();
} else {
try {
const createdWallet = SimpleWallet
.createWithPrivateKey(form.name, new Password(form.password), form.privateKey);
this.wallet.storeWallet(createdWallet).then(ignored => {
loader.dismiss();
this.app.getRootNav().push(LoginPage); | identifier_body |
lib.rs | #![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
//!Load Cifar10
//!
//!Cifar10 Simple Loader
//!
//!Use image crate in CifarImage.
//!
//!##Examples
//!
//! Download CIFAR-10 binary version and extract.
//!
//!```
//!# extern crate cifar_10_loader;
//!# use cifar_10_loader::CifarDataset;
//!# fn main()
//!# {
//!//This path is directory of cifar-10-batches-bin.
//!//It's extracted from CIFAR-10 binary version.
//!let cifar10_path = "./cifar-10-batches-bin/";
//!let cifar_dataset = CifarDataset::new(cifar10_path).unwrap();
//! # }
//!```
//#![deny(missing_docs)]
pub use self::image_pub::CifarImage;
pub use self::dataset::CifarDataset;
use self::image_private::CifarImageTrait;
mod image_private;
mod image_pub;
mod dataset;
#[cfg(test)] | mod test; | random_line_split |
|
base.py | """
Project main settings file. These settings are common to the project
if you need to override something do it in local.pt
"""
from sys import path
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
# PATHS
# Path containing the django project
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
path.append(BASE_DIR)
# Path of the top level directory.
# This directory contains the django project, apps, libs, etc...
PROJECT_ROOT = os.path.dirname(BASE_DIR)
# Add apps and libs to the PROJECT_ROOT
path.append(os.path.join(PROJECT_ROOT, "apps"))
path.append(os.path.join(PROJECT_ROOT, "libs"))
# SITE SETTINGS
# https://docs.djangoproject.com/en/1.10/ref/settings/#site-id
SITE_ID = 1
# https://docs.djangoproject.com/en/1.10/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# https://docs.djangoproject.com/en/1.10/ref/settings/#installed-apps
INSTALLED_APPS = [
# Django apps
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.humanize',
'django.contrib.sitemaps',
'django.contrib.syndication',
'django.contrib.staticfiles',
# Third party apps
'compressor',
# Local apps
'base',
]
# https://docs.djangoproject.com/en/1.10/topics/auth/passwords/#using-argon2-with-django
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
# DEBUG SETTINGS
# https://docs.djangoproject.com/en/1.10/ref/settings/#debug
DEBUG = False
# https://docs.djangoproject.com/en/1.10/ref/settings/#internal-ips
INTERNAL_IPS = ('127.0.0.1')
# LOCALE SETTINGS
# Local time zone for this installation.
# https://docs.djangoproject.com/en/1.10/ref/settings/#time-zone
TIME_ZONE = 'America/Los_Angeles'
# https://docs.djangoproject.com/en/1.10/ref/settings/#language-code
LANGUAGE_CODE = 'en-us'
# https://docs.djangoproject.com/en/1.10/ref/settings/#use-i18n
USE_I18N = True
# https://docs.djangoproject.com/en/1.10/ref/settings/#use-l10n
USE_L10N = True
# https://docs.djangoproject.com/en/1.10/ref/settings/#use-tz
USE_TZ = True | MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'public/media')
# URL that handles the media served from MEDIA_ROOT. Use a trailing slash.
# https://docs.djangoproject.com/en/1.10/ref/settings/#media-url
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# https://docs.djangoproject.com/en/1.10/ref/settings/#static-root
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'public/static')
# URL prefix for static files.
# https://docs.djangoproject.com/en/1.10/ref/settings/#static-url
STATIC_URL = '/static/'
# Additional locations of static files
# https://docs.djangoproject.com/en/1.10/ref/settings/#staticfiles-dirs
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# TEMPLATE SETTINGS
# https://docs.djangoproject.com/en/1.10/ref/settings/#templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages'
],
},
},
]
# URL SETTINGS
# https://docs.djangoproject.com/en/1.10/ref/settings/#root-urlconf.
ROOT_URLCONF = 'shaping_templeat.urls'
# MIDDLEWARE SETTINGS
# See: https://docs.djangoproject.com/en/1.10/ref/settings/#middleware-classes
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# LOGGING
# https://docs.djangoproject.com/en/1.10/topics/logging/
LOGGING = {
'version': 1,
'loggers': {
'shaping_templeat': {
'level': "DEBUG"
}
}
} |
# MEDIA AND STATIC SETTINGS
# Absolute filesystem path to the directory that will hold user-uploaded files.
# https://docs.djangoproject.com/en/1.10/ref/settings/#media-root | random_line_split |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use rustorm::query::Query;
use rustorm::query::{Filter,Equality};
use rustorm::dao::{Dao,IsDao};
use gen::bazaar::Product;
use gen::bazaar::product;
use gen::bazaar::Photo;
use gen::bazaar::photo;
use gen::bazaar::Review;
use gen::bazaar::review;
use gen::bazaar::Category;
use gen::bazaar::category;
use gen::bazaar::product_category;
use gen::bazaar::ProductCategory;
use gen::bazaar::product_photo;
use gen::bazaar::ProductPhoto;
use gen::bazaar::ProductAvailability;
use gen::bazaar::product_availability;
use gen::bazaar;
use rustorm::table::IsTable;
use rustorm::pool::ManagedPool;
use rustorm::query::HasEquality;
use rustorm::query::QueryBuilder;
use rustorm::query::ToTableName;
use rustorm::query::function::COUNT;
use rustorm::query::order::HasDirection;
use rustorm::query::join::ToJoin;
use rustorm::query::operand::ToOperand;
use rustorm::query::builder::SELECT_ALL;
mod gen;
fn main(){
let mut pool = ManagedPool::init("postgres://postgres:p0stgr3s@localhost/bazaar_v8",1).unwrap();
let db = pool.connect().unwrap();
let frag = SELECT_ALL().FROM(&bazaar::product)
.LEFT_JOIN(bazaar::product_category
.ON(
product_category::product_id.EQ(&product::product_id)
.AND(product_category::product_id.EQ(&product::product_id))
)
)
.LEFT_JOIN(bazaar::category
.ON(category::category_id.EQ(&product_category::category_id)))
.LEFT_JOIN(bazaar::product_photo
.ON(product::product_id.EQ(&product_photo::product_id)))
.LEFT_JOIN(bazaar::photo
.ON(product_photo::photo_id.EQ(&photo::photo_id)))
.WHERE(
product::name.EQ(&"GTX660 Ti videocard".to_owned())
.AND(category::name.EQ(&"Electronic".to_owned())) | )
.GROUP_BY(&[category::name])
.HAVING(COUNT(&"*").GT(&1))
.HAVING(COUNT(&product::product_id).GT(&1))
.ORDER_BY(&[product::name.ASC(), product::created.DESC()])
.build(db.as_ref());
let expected = "
SELECT *
FROM bazaar.product
LEFT JOIN bazaar.product_category
ON ( product_category.product_id = product.product_id AND product_category.product_id = product.product_id )
LEFT JOIN bazaar.category
ON category.category_id = product_category.category_id
LEFT JOIN bazaar.product_photo
ON product.product_id = product_photo.product_id
LEFT JOIN bazaar.photo
ON product_photo.photo_id = photo.photo_id
WHERE ( product.name = $1 AND category.name = $2 )
GROUP BY category.name
HAVING COUNT(*) > $3 , COUNT(product.product_id) > $4
ORDER BY product.name ASC, product.created DESC
".to_string();
println!("actual: {{{}}} [{}]", frag.sql, frag.sql.len());
println!("expected: {{{}}} [{}]", expected, expected.len());
assert!(frag.sql.trim() == expected.trim());
} | random_line_split |
|
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use rustorm::query::Query;
use rustorm::query::{Filter,Equality};
use rustorm::dao::{Dao,IsDao};
use gen::bazaar::Product;
use gen::bazaar::product;
use gen::bazaar::Photo;
use gen::bazaar::photo;
use gen::bazaar::Review;
use gen::bazaar::review;
use gen::bazaar::Category;
use gen::bazaar::category;
use gen::bazaar::product_category;
use gen::bazaar::ProductCategory;
use gen::bazaar::product_photo;
use gen::bazaar::ProductPhoto;
use gen::bazaar::ProductAvailability;
use gen::bazaar::product_availability;
use gen::bazaar;
use rustorm::table::IsTable;
use rustorm::pool::ManagedPool;
use rustorm::query::HasEquality;
use rustorm::query::QueryBuilder;
use rustorm::query::ToTableName;
use rustorm::query::function::COUNT;
use rustorm::query::order::HasDirection;
use rustorm::query::join::ToJoin;
use rustorm::query::operand::ToOperand;
use rustorm::query::builder::SELECT_ALL;
mod gen;
fn main() | )
.GROUP_BY(&[category::name])
.HAVING(COUNT(&"*").GT(&1))
.HAVING(COUNT(&product::product_id).GT(&1))
.ORDER_BY(&[product::name.ASC(), product::created.DESC()])
.build(db.as_ref());
let expected = "
SELECT *
FROM bazaar.product
LEFT JOIN bazaar.product_category
ON ( product_category.product_id = product.product_id AND product_category.product_id = product.product_id )
LEFT JOIN bazaar.category
ON category.category_id = product_category.category_id
LEFT JOIN bazaar.product_photo
ON product.product_id = product_photo.product_id
LEFT JOIN bazaar.photo
ON product_photo.photo_id = photo.photo_id
WHERE ( product.name = $1 AND category.name = $2 )
GROUP BY category.name
HAVING COUNT(*) > $3 , COUNT(product.product_id) > $4
ORDER BY product.name ASC, product.created DESC
".to_string();
println!("actual: {{{}}} [{}]", frag.sql, frag.sql.len());
println!("expected: {{{}}} [{}]", expected, expected.len());
assert!(frag.sql.trim() == expected.trim());
}
| {
let mut pool = ManagedPool::init("postgres://postgres:p0stgr3s@localhost/bazaar_v8",1).unwrap();
let db = pool.connect().unwrap();
let frag = SELECT_ALL().FROM(&bazaar::product)
.LEFT_JOIN(bazaar::product_category
.ON(
product_category::product_id.EQ(&product::product_id)
.AND(product_category::product_id.EQ(&product::product_id))
)
)
.LEFT_JOIN(bazaar::category
.ON(category::category_id.EQ(&product_category::category_id)))
.LEFT_JOIN(bazaar::product_photo
.ON(product::product_id.EQ(&product_photo::product_id)))
.LEFT_JOIN(bazaar::photo
.ON(product_photo::photo_id.EQ(&photo::photo_id)))
.WHERE(
product::name.EQ(&"GTX660 Ti videocard".to_owned())
.AND(category::name.EQ(&"Electronic".to_owned())) | identifier_body |
complex_query.rs | extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use rustorm::query::Query;
use rustorm::query::{Filter,Equality};
use rustorm::dao::{Dao,IsDao};
use gen::bazaar::Product;
use gen::bazaar::product;
use gen::bazaar::Photo;
use gen::bazaar::photo;
use gen::bazaar::Review;
use gen::bazaar::review;
use gen::bazaar::Category;
use gen::bazaar::category;
use gen::bazaar::product_category;
use gen::bazaar::ProductCategory;
use gen::bazaar::product_photo;
use gen::bazaar::ProductPhoto;
use gen::bazaar::ProductAvailability;
use gen::bazaar::product_availability;
use gen::bazaar;
use rustorm::table::IsTable;
use rustorm::pool::ManagedPool;
use rustorm::query::HasEquality;
use rustorm::query::QueryBuilder;
use rustorm::query::ToTableName;
use rustorm::query::function::COUNT;
use rustorm::query::order::HasDirection;
use rustorm::query::join::ToJoin;
use rustorm::query::operand::ToOperand;
use rustorm::query::builder::SELECT_ALL;
mod gen;
fn | (){
let mut pool = ManagedPool::init("postgres://postgres:p0stgr3s@localhost/bazaar_v8",1).unwrap();
let db = pool.connect().unwrap();
let frag = SELECT_ALL().FROM(&bazaar::product)
.LEFT_JOIN(bazaar::product_category
.ON(
product_category::product_id.EQ(&product::product_id)
.AND(product_category::product_id.EQ(&product::product_id))
)
)
.LEFT_JOIN(bazaar::category
.ON(category::category_id.EQ(&product_category::category_id)))
.LEFT_JOIN(bazaar::product_photo
.ON(product::product_id.EQ(&product_photo::product_id)))
.LEFT_JOIN(bazaar::photo
.ON(product_photo::photo_id.EQ(&photo::photo_id)))
.WHERE(
product::name.EQ(&"GTX660 Ti videocard".to_owned())
.AND(category::name.EQ(&"Electronic".to_owned()))
)
.GROUP_BY(&[category::name])
.HAVING(COUNT(&"*").GT(&1))
.HAVING(COUNT(&product::product_id).GT(&1))
.ORDER_BY(&[product::name.ASC(), product::created.DESC()])
.build(db.as_ref());
let expected = "
SELECT *
FROM bazaar.product
LEFT JOIN bazaar.product_category
ON ( product_category.product_id = product.product_id AND product_category.product_id = product.product_id )
LEFT JOIN bazaar.category
ON category.category_id = product_category.category_id
LEFT JOIN bazaar.product_photo
ON product.product_id = product_photo.product_id
LEFT JOIN bazaar.photo
ON product_photo.photo_id = photo.photo_id
WHERE ( product.name = $1 AND category.name = $2 )
GROUP BY category.name
HAVING COUNT(*) > $3 , COUNT(product.product_id) > $4
ORDER BY product.name ASC, product.created DESC
".to_string();
println!("actual: {{{}}} [{}]", frag.sql, frag.sql.len());
println!("expected: {{{}}} [{}]", expected, expected.len());
assert!(frag.sql.trim() == expected.trim());
}
| main | identifier_name |
ofx.py | from datetime import datetime
from hashlib import sha1
from xml.sax.saxutils import escape as xml_escape
from .common import CHARSET
def xml_template(template, data):
""" | return template % escaped_data
class OFXExporter(object):
HEADER = """ENCODING:UTF-8
OFXHEADER:100
DATA:OFXSGML
VERSION:211
SECURITY:NONE
CHARSET:UTF-8
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>0</TRNUID>
<STMTRS>
<CURDEF>EUR</CURDEF>
<BANKACCTFROM>
<BANKID>info.hoffmann-christian.gnucash-export</BANKID>
<ACCTID>%(acctid)s</ACCTID>
<ACCTTYPE>CHECKING</ACCTTYPE>
</BANKACCTFROM>
<BANKTRANLIST>
<DTSTART>%(dtstart)s</DTSTART>
<DTEND>%(dtend)s</DTEND>"""
TRANSACTION = """
<STMTTRN>
<TRNTYPE>%(trntype)s</TRNTYPE>
<DTPOSTED>%(dtposted)s</DTPOSTED>
<DTUSER>%(dtuser)s</DTUSER>
<TRNAMT>%(trnamt)s</TRNAMT>
<FITID>%(fitid)s</FITID>
<NAME>%(name)s</NAME>
<MEMO>%(name)s</MEMO>
</STMTTRN>"""
FOOTER = """
</BANKTRANLIST>
</STMTRS>
</STMTTRNRS>
</BANKMSGSRSV1>
</OFX>
"""
def __init__(self):
self.transactions = []
def set_account(self, name):
self.account_name = name
self.account_id = sha1(name).hexdigest()
def add_transaction(self, guid, unixtime, memo, value):
self.transactions.append((guid, unixtime, memo, value))
def unixtime2ofx(self, unixtime):
dt = datetime.fromtimestamp(unixtime)
return dt.strftime("%Y%m%d%H%M%S")
def generate(self, reverse=False):
earliest_tx = None
latest_tx = None
transactions = ""
for guid, unixtime, memo, amount in self.transactions:
if reverse:
if amount[0] == '-':
amount = amount[1:]
else:
amount = '-' + amount
ofxdate = self.unixtime2ofx(unixtime)
transaction_type = "CREDIT"
if amount[0] == '-':
transaction_type = "DEBIT"
transactions += xml_template(self.TRANSACTION, {
'trntype': transaction_type,
'fitid': guid,
'dtposted': ofxdate,
'dtuser': ofxdate,
'trnamt': amount,
'name': memo
})
if not earliest_tx or earliest_tx > unixtime:
earliest_tx = unixtime
if not latest_tx or latest_tx < unixtime:
latest_tx = unixtime
header = xml_template(self.HEADER, {
'acctid': self.account_id,
'dtstart': self.unixtime2ofx(earliest_tx),
'dtend': self.unixtime2ofx(latest_tx)
})
footer = self.FOOTER % {
}
return (header + transactions + footer).encode(CHARSET) | return template % data but with proper escaping
"""
escaped_data = {}
for key, value in data.items():
escaped_data[key] = xml_escape(value) | random_line_split |
ofx.py | from datetime import datetime
from hashlib import sha1
from xml.sax.saxutils import escape as xml_escape
from .common import CHARSET
def xml_template(template, data):
"""
return template % data but with proper escaping
"""
escaped_data = {}
for key, value in data.items():
escaped_data[key] = xml_escape(value)
return template % escaped_data
class OFXExporter(object):
HEADER = """ENCODING:UTF-8
OFXHEADER:100
DATA:OFXSGML
VERSION:211
SECURITY:NONE
CHARSET:UTF-8
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>0</TRNUID>
<STMTRS>
<CURDEF>EUR</CURDEF>
<BANKACCTFROM>
<BANKID>info.hoffmann-christian.gnucash-export</BANKID>
<ACCTID>%(acctid)s</ACCTID>
<ACCTTYPE>CHECKING</ACCTTYPE>
</BANKACCTFROM>
<BANKTRANLIST>
<DTSTART>%(dtstart)s</DTSTART>
<DTEND>%(dtend)s</DTEND>"""
TRANSACTION = """
<STMTTRN>
<TRNTYPE>%(trntype)s</TRNTYPE>
<DTPOSTED>%(dtposted)s</DTPOSTED>
<DTUSER>%(dtuser)s</DTUSER>
<TRNAMT>%(trnamt)s</TRNAMT>
<FITID>%(fitid)s</FITID>
<NAME>%(name)s</NAME>
<MEMO>%(name)s</MEMO>
</STMTTRN>"""
FOOTER = """
</BANKTRANLIST>
</STMTRS>
</STMTTRNRS>
</BANKMSGSRSV1>
</OFX>
"""
def __init__(self):
self.transactions = []
def set_account(self, name):
self.account_name = name
self.account_id = sha1(name).hexdigest()
def add_transaction(self, guid, unixtime, memo, value):
self.transactions.append((guid, unixtime, memo, value))
def unixtime2ofx(self, unixtime):
dt = datetime.fromtimestamp(unixtime)
return dt.strftime("%Y%m%d%H%M%S")
def generate(self, reverse=False):
| })
if not earliest_tx or earliest_tx > unixtime:
earliest_tx = unixtime
if not latest_tx or latest_tx < unixtime:
latest_tx = unixtime
header = xml_template(self.HEADER, {
'acctid': self.account_id,
'dtstart': self.unixtime2ofx(earliest_tx),
'dtend': self.unixtime2ofx(latest_tx)
})
footer = self.FOOTER % {
}
return (header + transactions + footer).encode(CHARSET)
| earliest_tx = None
latest_tx = None
transactions = ""
for guid, unixtime, memo, amount in self.transactions:
if reverse:
if amount[0] == '-':
amount = amount[1:]
else:
amount = '-' + amount
ofxdate = self.unixtime2ofx(unixtime)
transaction_type = "CREDIT"
if amount[0] == '-':
transaction_type = "DEBIT"
transactions += xml_template(self.TRANSACTION, {
'trntype': transaction_type,
'fitid': guid,
'dtposted': ofxdate,
'dtuser': ofxdate,
'trnamt': amount,
'name': memo | identifier_body |
ofx.py | from datetime import datetime
from hashlib import sha1
from xml.sax.saxutils import escape as xml_escape
from .common import CHARSET
def xml_template(template, data):
"""
return template % data but with proper escaping
"""
escaped_data = {}
for key, value in data.items():
|
return template % escaped_data
class OFXExporter(object):
HEADER = """ENCODING:UTF-8
OFXHEADER:100
DATA:OFXSGML
VERSION:211
SECURITY:NONE
CHARSET:UTF-8
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>0</TRNUID>
<STMTRS>
<CURDEF>EUR</CURDEF>
<BANKACCTFROM>
<BANKID>info.hoffmann-christian.gnucash-export</BANKID>
<ACCTID>%(acctid)s</ACCTID>
<ACCTTYPE>CHECKING</ACCTTYPE>
</BANKACCTFROM>
<BANKTRANLIST>
<DTSTART>%(dtstart)s</DTSTART>
<DTEND>%(dtend)s</DTEND>"""
TRANSACTION = """
<STMTTRN>
<TRNTYPE>%(trntype)s</TRNTYPE>
<DTPOSTED>%(dtposted)s</DTPOSTED>
<DTUSER>%(dtuser)s</DTUSER>
<TRNAMT>%(trnamt)s</TRNAMT>
<FITID>%(fitid)s</FITID>
<NAME>%(name)s</NAME>
<MEMO>%(name)s</MEMO>
</STMTTRN>"""
FOOTER = """
</BANKTRANLIST>
</STMTRS>
</STMTTRNRS>
</BANKMSGSRSV1>
</OFX>
"""
def __init__(self):
self.transactions = []
def set_account(self, name):
self.account_name = name
self.account_id = sha1(name).hexdigest()
def add_transaction(self, guid, unixtime, memo, value):
self.transactions.append((guid, unixtime, memo, value))
def unixtime2ofx(self, unixtime):
dt = datetime.fromtimestamp(unixtime)
return dt.strftime("%Y%m%d%H%M%S")
def generate(self, reverse=False):
earliest_tx = None
latest_tx = None
transactions = ""
for guid, unixtime, memo, amount in self.transactions:
if reverse:
if amount[0] == '-':
amount = amount[1:]
else:
amount = '-' + amount
ofxdate = self.unixtime2ofx(unixtime)
transaction_type = "CREDIT"
if amount[0] == '-':
transaction_type = "DEBIT"
transactions += xml_template(self.TRANSACTION, {
'trntype': transaction_type,
'fitid': guid,
'dtposted': ofxdate,
'dtuser': ofxdate,
'trnamt': amount,
'name': memo
})
if not earliest_tx or earliest_tx > unixtime:
earliest_tx = unixtime
if not latest_tx or latest_tx < unixtime:
latest_tx = unixtime
header = xml_template(self.HEADER, {
'acctid': self.account_id,
'dtstart': self.unixtime2ofx(earliest_tx),
'dtend': self.unixtime2ofx(latest_tx)
})
footer = self.FOOTER % {
}
return (header + transactions + footer).encode(CHARSET)
| escaped_data[key] = xml_escape(value) | conditional_block |
ofx.py | from datetime import datetime
from hashlib import sha1
from xml.sax.saxutils import escape as xml_escape
from .common import CHARSET
def xml_template(template, data):
"""
return template % data but with proper escaping
"""
escaped_data = {}
for key, value in data.items():
escaped_data[key] = xml_escape(value)
return template % escaped_data
class OFXExporter(object):
HEADER = """ENCODING:UTF-8
OFXHEADER:100
DATA:OFXSGML
VERSION:211
SECURITY:NONE
CHARSET:UTF-8
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
<BANKMSGSRSV1>
<STMTTRNRS>
<TRNUID>0</TRNUID>
<STMTRS>
<CURDEF>EUR</CURDEF>
<BANKACCTFROM>
<BANKID>info.hoffmann-christian.gnucash-export</BANKID>
<ACCTID>%(acctid)s</ACCTID>
<ACCTTYPE>CHECKING</ACCTTYPE>
</BANKACCTFROM>
<BANKTRANLIST>
<DTSTART>%(dtstart)s</DTSTART>
<DTEND>%(dtend)s</DTEND>"""
TRANSACTION = """
<STMTTRN>
<TRNTYPE>%(trntype)s</TRNTYPE>
<DTPOSTED>%(dtposted)s</DTPOSTED>
<DTUSER>%(dtuser)s</DTUSER>
<TRNAMT>%(trnamt)s</TRNAMT>
<FITID>%(fitid)s</FITID>
<NAME>%(name)s</NAME>
<MEMO>%(name)s</MEMO>
</STMTTRN>"""
FOOTER = """
</BANKTRANLIST>
</STMTRS>
</STMTTRNRS>
</BANKMSGSRSV1>
</OFX>
"""
def __init__(self):
self.transactions = []
def set_account(self, name):
self.account_name = name
self.account_id = sha1(name).hexdigest()
def add_transaction(self, guid, unixtime, memo, value):
self.transactions.append((guid, unixtime, memo, value))
def | (self, unixtime):
dt = datetime.fromtimestamp(unixtime)
return dt.strftime("%Y%m%d%H%M%S")
def generate(self, reverse=False):
earliest_tx = None
latest_tx = None
transactions = ""
for guid, unixtime, memo, amount in self.transactions:
if reverse:
if amount[0] == '-':
amount = amount[1:]
else:
amount = '-' + amount
ofxdate = self.unixtime2ofx(unixtime)
transaction_type = "CREDIT"
if amount[0] == '-':
transaction_type = "DEBIT"
transactions += xml_template(self.TRANSACTION, {
'trntype': transaction_type,
'fitid': guid,
'dtposted': ofxdate,
'dtuser': ofxdate,
'trnamt': amount,
'name': memo
})
if not earliest_tx or earliest_tx > unixtime:
earliest_tx = unixtime
if not latest_tx or latest_tx < unixtime:
latest_tx = unixtime
header = xml_template(self.HEADER, {
'acctid': self.account_id,
'dtstart': self.unixtime2ofx(earliest_tx),
'dtend': self.unixtime2ofx(latest_tx)
})
footer = self.FOOTER % {
}
return (header + transactions + footer).encode(CHARSET)
| unixtime2ofx | identifier_name |
atomic_usize.rs | use std::cell::UnsafeCell;
use std::fmt;
use std::ops;
/// `AtomicUsize` providing an additional `load_unsync` function.
pub(crate) struct AtomicUsize {
inner: UnsafeCell<std::sync::atomic::AtomicUsize>,
}
unsafe impl Send for AtomicUsize {}
unsafe impl Sync for AtomicUsize {}
impl AtomicUsize {
pub(crate) const fn new(val: usize) -> AtomicUsize {
let inner = UnsafeCell::new(std::sync::atomic::AtomicUsize::new(val));
AtomicUsize { inner }
}
/// Performs an unsynchronized load.
///
/// # Safety
///
/// All mutations must have happened before the unsynchronized load.
/// Additionally, there must be no concurrent mutations.
pub(crate) unsafe fn unsync_load(&self) -> usize {
*(*self.inner.get()).get_mut() |
pub(crate) fn with_mut<R>(&mut self, f: impl FnOnce(&mut usize) -> R) -> R {
// safety: we have mutable access
f(unsafe { (*self.inner.get()).get_mut() })
}
}
impl ops::Deref for AtomicUsize {
type Target = std::sync::atomic::AtomicUsize;
fn deref(&self) -> &Self::Target {
// safety: it is always safe to access `&self` fns on the inner value as
// we never perform unsafe mutations.
unsafe { &*self.inner.get() }
}
}
impl ops::DerefMut for AtomicUsize {
fn deref_mut(&mut self) -> &mut Self::Target {
// safety: we hold `&mut self`
unsafe { &mut *self.inner.get() }
}
}
impl fmt::Debug for AtomicUsize {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(fmt)
}
} | } | random_line_split |
atomic_usize.rs | use std::cell::UnsafeCell;
use std::fmt;
use std::ops;
/// `AtomicUsize` providing an additional `load_unsync` function.
pub(crate) struct AtomicUsize {
inner: UnsafeCell<std::sync::atomic::AtomicUsize>,
}
unsafe impl Send for AtomicUsize {}
unsafe impl Sync for AtomicUsize {}
impl AtomicUsize {
pub(crate) const fn new(val: usize) -> AtomicUsize {
let inner = UnsafeCell::new(std::sync::atomic::AtomicUsize::new(val));
AtomicUsize { inner }
}
/// Performs an unsynchronized load.
///
/// # Safety
///
/// All mutations must have happened before the unsynchronized load.
/// Additionally, there must be no concurrent mutations.
pub(crate) unsafe fn unsync_load(&self) -> usize |
pub(crate) fn with_mut<R>(&mut self, f: impl FnOnce(&mut usize) -> R) -> R {
// safety: we have mutable access
f(unsafe { (*self.inner.get()).get_mut() })
}
}
impl ops::Deref for AtomicUsize {
type Target = std::sync::atomic::AtomicUsize;
fn deref(&self) -> &Self::Target {
// safety: it is always safe to access `&self` fns on the inner value as
// we never perform unsafe mutations.
unsafe { &*self.inner.get() }
}
}
impl ops::DerefMut for AtomicUsize {
fn deref_mut(&mut self) -> &mut Self::Target {
// safety: we hold `&mut self`
unsafe { &mut *self.inner.get() }
}
}
impl fmt::Debug for AtomicUsize {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(fmt)
}
}
| {
*(*self.inner.get()).get_mut()
} | identifier_body |
atomic_usize.rs | use std::cell::UnsafeCell;
use std::fmt;
use std::ops;
/// `AtomicUsize` providing an additional `load_unsync` function.
pub(crate) struct AtomicUsize {
inner: UnsafeCell<std::sync::atomic::AtomicUsize>,
}
unsafe impl Send for AtomicUsize {}
unsafe impl Sync for AtomicUsize {}
impl AtomicUsize {
pub(crate) const fn new(val: usize) -> AtomicUsize {
let inner = UnsafeCell::new(std::sync::atomic::AtomicUsize::new(val));
AtomicUsize { inner }
}
/// Performs an unsynchronized load.
///
/// # Safety
///
/// All mutations must have happened before the unsynchronized load.
/// Additionally, there must be no concurrent mutations.
pub(crate) unsafe fn unsync_load(&self) -> usize {
*(*self.inner.get()).get_mut()
}
pub(crate) fn with_mut<R>(&mut self, f: impl FnOnce(&mut usize) -> R) -> R {
// safety: we have mutable access
f(unsafe { (*self.inner.get()).get_mut() })
}
}
impl ops::Deref for AtomicUsize {
type Target = std::sync::atomic::AtomicUsize;
fn deref(&self) -> &Self::Target {
// safety: it is always safe to access `&self` fns on the inner value as
// we never perform unsafe mutations.
unsafe { &*self.inner.get() }
}
}
impl ops::DerefMut for AtomicUsize {
fn | (&mut self) -> &mut Self::Target {
// safety: we hold `&mut self`
unsafe { &mut *self.inner.get() }
}
}
impl fmt::Debug for AtomicUsize {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(fmt)
}
}
| deref_mut | identifier_name |
EventWindow.js | true,
layout: 'fit',
formPanelConfig: {
border: false
},
// private
initComponent: function(){
this.addEvents({
/**
* @event eventadd
* Fires after a new event is added
* @param {Extensible.calendar.form.EventWindow} this
* @param {Extensible.calendar.data.EventModel} rec The new {@link Extensible.calendar.data.EventModel record} that was added
* @param {Ext.Element} el The target element
*/
eventadd: true,
/**
* @event eventupdate
* Fires after an existing event is updated
* @param {Extensible.calendar.form.EventWindow} this
* @param {Extensible.calendar.data.EventModel} rec The new {@link Extensible.calendar.data.EventModel record} that was updated
* @param {Ext.Element} el The target element
*/
eventupdate: true,
/**
* @event eventdelete
* Fires after an event is deleted
* @param {Extensible.calendar.form.EventWindow} this
* @param {Extensible.calendar.data.EventModel} rec The new {@link Extensible.calendar.data.EventModel record} that was deleted
* @param {Ext.Element} el The target element
*/
eventdelete: true,
/**
* @event eventcancel
* Fires after an event add/edit operation is canceled by the user and no store update took place
* @param {Extensible.calendar.form.EventWindow} this
* @param {Extensible.calendar.data.EventModel} rec The new {@link Extensible.calendar.data.EventModel record} that was canceled
* @param {Ext.Element} el The target element
*/
eventcancel: true,
/**
* @event editdetails
* Fires when the user selects the option in this window to continue editing in the detailed edit form
* (by default, an instance of {@link Extensible.calendar.form.EventDetails}. Handling code should hide this window
* and transfer the current event record to the appropriate instance of the detailed form by showing it
* and calling {@link Extensible.calendar.form.EventDetails#loadRecord loadRecord}.
* @param {Extensible.calendar.form.EventWindow} this
* @param {Extensible.calendar.data.EventModel} rec The {@link Extensible.calendar.data.EventModel record} that is currently being edited
* @param {Ext.Element} el The target element
*/
editdetails: true
});
this.fbar = this.getFooterBarConfig();
this.callParent(arguments);
},
getFooterBarConfig: function() {
var cfg = ['->', {
text: this.saveButtonText,
itemId: this.id + '-save-btn',
disabled: false,
handler: this.onSave,
scope: this
},{
text: this.deleteButtonText,
itemId: this.id + '-delete-btn',
disabled: false,
handler: this.onDelete,
scope: this,
hideMode: 'offsets' // IE requires this
},{
text: this.cancelButtonText,
itemId: this.id + '-cancel-btn',
disabled: false,
handler: this.onCancel,
scope: this
}];
if(this.enableEditDetails !== false){
cfg.unshift({
xtype: 'tbtext',
itemId: this.id + '-details-btn',
text: '<a href="#" class="' + this.editDetailsLinkClass + '">' + this.detailsLinkText + '</a>'
});
}
return cfg;
},
// private
onRender : function(ct, position){
this.formPanel = Ext.create('Ext.form.Panel', Ext.applyIf({
fieldDefaults: {
labelWidth: this.labelWidth
},
items: this.getFormItemConfigs()
}, this.formPanelConfig));
this.add(this.formPanel);
this.callParent(arguments);
},
getFormItemConfigs: function() {
var items = [{
xtype: 'textfield',
itemId: this.id + '-title',
name: Extensible.calendar.data.EventMappings.Title.name,
fieldLabel: this.titleLabelText,
anchor: '100%'
},{
xtype: 'extensible.daterangefield',
itemId: this.id + '-dates',
name: 'dates',
anchor: '95%',
singleLine: true,
fieldLabel: this.datesLabelText
}];
if(this.calendarStore){
items.push({
xtype: 'extensible.calendarcombo',
itemId: this.id + '-calendar',
name: Extensible.calendar.data.EventMappings.CalendarId.name,
anchor: '100%',
fieldLabel: this.calendarLabelText,
store: this.calendarStore
});
}
return items;
},
// private
afterRender: function(){
this.callParent(arguments);
this.el.addCls('ext-cal-event-win');
this.initRefs();
// This junk spacer item gets added to the fbar by Ext (fixed in 4.0.2)
var junkSpacer = this.getDockedItems('toolbar')[0].items.items[0];
if (junkSpacer.el.hasCls('x-component-default')) {
Ext.destroy(junkSpacer);
}
},
initRefs: function() {
// toolbar button refs
this.saveButton = this.down('#' + this.id + '-save-btn');
this.deleteButton = this.down('#' + this.id + '-delete-btn');
this.cancelButton = this.down('#' + this.id + '-cancel-btn');
this.detailsButton = this.down('#' + this.id + '-details-btn');
if (this.detailsButton) {
this.detailsButton.getEl().on('click', this.onEditDetailsClick, this);
}
// form item refs
this.titleField = this.down('#' + this.id + '-title');
this.dateRangeField = this.down('#' + this.id + '-dates');
this.calendarField = this.down('#' + this.id + '-calendar');
},
// private
onEditDetailsClick: function(e){
e.stopEvent();
this.updateRecord(this.activeRecord, true);
this.fireEvent('editdetails', this, this.activeRecord, this.animateTarget);
},
/**
* Shows the window, rendering it first if necessary, or activates it and brings it to front if hidden.
* @param {Ext.data.Record/Object} o Either a {@link Ext.data.Record} if showing the form
* for an existing event in edit mode, or a plain object containing a StartDate property (and
* optionally an EndDate property) for showing the form in add mode.
* @param {String/Element} animateTarget (optional) The target element or id from which the window should
* animate while opening (defaults to null with no animation)
* @return {Ext.Window} this
*/
show: function(o, animateTarget){
// Work around the CSS day cell height hack needed for initial render in IE8/strict:
this.animateTarget = (Ext.isIE8 && Ext.isStrict) ? null : animateTarget,
M = Extensible.calendar.data.EventMappings;
this.callParent([this.animateTarget, function(){
this.titleField.focus(false, 100);
}, this]);
this.deleteButton[o.data && o.data[M.EventId.name] ? 'show' : 'hide']();
var rec, f = this.formPanel.form;
if(o.data){
rec = o;
//this.isAdd = !!rec.data[Extensible.calendar.data.EventMappings.IsNew.name];
if(rec.phantom){
// Enable adding the default record that was passed in
// if it's new even if the user makes no changes
//rec.markDirty();
this.setTitle(this.titleTextAdd);
}
else{
this.setTitle(this.titleTextEdit);
}
f.loadRecord(rec);
}
else{
//this.isAdd = true;
this.setTitle(this.titleTextAdd);
var start = o[M.StartDate.name],
end = o[M.EndDate.name] || Extensible.Date.add(start, {hours: 1});
rec = Ext.create('Extensible.calendar.data.EventModel');
//rec.data[M.EventId.name] = this.newId++;
rec.data[M.StartDate.name] = start;
rec.data[M.EndDate.name] = end;
rec.data[M.IsAllDay.name] = !!o[M.IsAllDay.name] || start.getDate() != Extensible.Date.add(end, {millis: 1}).getDate();
f.reset();
f.loadRecord(rec);
}
if(this.calendarStore){
this.calendarField.setValue(rec.data[M.CalendarId.name]);
}
this.dateRangeField.setValue(rec.data);
this.activeRecord = rec;
//this.el.setStyle('z-index', 12000);
return this;
},
// private
roundTime: function(dt, incr){
incr = incr || 15;
var m = parseInt(dt.getMinutes());
return dt.add('mi', incr - (m % incr));
},
// private
onCancel: function(){
this.cleanup(true);
this.fireEvent('eventcancel', this, this.activeRecord, this.animateTarget);
},
// private
cleanup: function(hide){
if (this.activeRecord) | {
this.activeRecord.reject();
} | conditional_block |
|
EventWindow.js | .calendar.data.EventModel} rec The new {@link Extensible.calendar.data.EventModel record} that was updated
* @param {Ext.Element} el The target element
*/
eventupdate: true,
/**
* @event eventdelete
* Fires after an event is deleted
* @param {Extensible.calendar.form.EventWindow} this
* @param {Extensible.calendar.data.EventModel} rec The new {@link Extensible.calendar.data.EventModel record} that was deleted
* @param {Ext.Element} el The target element
*/
eventdelete: true,
/**
* @event eventcancel
* Fires after an event add/edit operation is canceled by the user and no store update took place
* @param {Extensible.calendar.form.EventWindow} this
* @param {Extensible.calendar.data.EventModel} rec The new {@link Extensible.calendar.data.EventModel record} that was canceled
* @param {Ext.Element} el The target element
*/
eventcancel: true,
/**
* @event editdetails
* Fires when the user selects the option in this window to continue editing in the detailed edit form
* (by default, an instance of {@link Extensible.calendar.form.EventDetails}. Handling code should hide this window
* and transfer the current event record to the appropriate instance of the detailed form by showing it
* and calling {@link Extensible.calendar.form.EventDetails#loadRecord loadRecord}.
* @param {Extensible.calendar.form.EventWindow} this
* @param {Extensible.calendar.data.EventModel} rec The {@link Extensible.calendar.data.EventModel record} that is currently being edited
* @param {Ext.Element} el The target element
*/
editdetails: true
});
this.fbar = this.getFooterBarConfig();
this.callParent(arguments);
},
getFooterBarConfig: function() {
var cfg = ['->', {
text: this.saveButtonText,
itemId: this.id + '-save-btn',
disabled: false,
handler: this.onSave,
scope: this
},{
text: this.deleteButtonText,
itemId: this.id + '-delete-btn',
disabled: false,
handler: this.onDelete,
scope: this,
hideMode: 'offsets' // IE requires this
},{
text: this.cancelButtonText,
itemId: this.id + '-cancel-btn',
disabled: false,
handler: this.onCancel,
scope: this
}];
if(this.enableEditDetails !== false){
cfg.unshift({
xtype: 'tbtext',
itemId: this.id + '-details-btn',
text: '<a href="#" class="' + this.editDetailsLinkClass + '">' + this.detailsLinkText + '</a>'
});
}
return cfg;
},
// private
onRender : function(ct, position){
this.formPanel = Ext.create('Ext.form.Panel', Ext.applyIf({
fieldDefaults: {
labelWidth: this.labelWidth
},
items: this.getFormItemConfigs()
}, this.formPanelConfig));
this.add(this.formPanel);
this.callParent(arguments);
},
getFormItemConfigs: function() {
var items = [{
xtype: 'textfield',
itemId: this.id + '-title',
name: Extensible.calendar.data.EventMappings.Title.name,
fieldLabel: this.titleLabelText,
anchor: '100%'
},{
xtype: 'extensible.daterangefield',
itemId: this.id + '-dates',
name: 'dates',
anchor: '95%',
singleLine: true,
fieldLabel: this.datesLabelText
}];
if(this.calendarStore){
items.push({
xtype: 'extensible.calendarcombo',
itemId: this.id + '-calendar',
name: Extensible.calendar.data.EventMappings.CalendarId.name,
anchor: '100%',
fieldLabel: this.calendarLabelText,
store: this.calendarStore
});
}
return items;
},
// private
afterRender: function(){
this.callParent(arguments);
this.el.addCls('ext-cal-event-win');
this.initRefs();
// This junk spacer item gets added to the fbar by Ext (fixed in 4.0.2)
var junkSpacer = this.getDockedItems('toolbar')[0].items.items[0];
if (junkSpacer.el.hasCls('x-component-default')) {
Ext.destroy(junkSpacer);
}
},
initRefs: function() {
// toolbar button refs
this.saveButton = this.down('#' + this.id + '-save-btn');
this.deleteButton = this.down('#' + this.id + '-delete-btn');
this.cancelButton = this.down('#' + this.id + '-cancel-btn');
this.detailsButton = this.down('#' + this.id + '-details-btn');
if (this.detailsButton) {
this.detailsButton.getEl().on('click', this.onEditDetailsClick, this);
}
// form item refs
this.titleField = this.down('#' + this.id + '-title');
this.dateRangeField = this.down('#' + this.id + '-dates');
this.calendarField = this.down('#' + this.id + '-calendar');
},
// private
onEditDetailsClick: function(e){
e.stopEvent();
this.updateRecord(this.activeRecord, true);
this.fireEvent('editdetails', this, this.activeRecord, this.animateTarget);
},
/**
* Shows the window, rendering it first if necessary, or activates it and brings it to front if hidden.
* @param {Ext.data.Record/Object} o Either a {@link Ext.data.Record} if showing the form
* for an existing event in edit mode, or a plain object containing a StartDate property (and
* optionally an EndDate property) for showing the form in add mode.
* @param {String/Element} animateTarget (optional) The target element or id from which the window should
* animate while opening (defaults to null with no animation)
* @return {Ext.Window} this
*/
show: function(o, animateTarget){
// Work around the CSS day cell height hack needed for initial render in IE8/strict:
this.animateTarget = (Ext.isIE8 && Ext.isStrict) ? null : animateTarget,
M = Extensible.calendar.data.EventMappings;
this.callParent([this.animateTarget, function(){
this.titleField.focus(false, 100);
}, this]);
this.deleteButton[o.data && o.data[M.EventId.name] ? 'show' : 'hide']();
var rec, f = this.formPanel.form;
if(o.data){
rec = o;
//this.isAdd = !!rec.data[Extensible.calendar.data.EventMappings.IsNew.name];
if(rec.phantom){
// Enable adding the default record that was passed in
// if it's new even if the user makes no changes
//rec.markDirty();
this.setTitle(this.titleTextAdd);
}
else{
this.setTitle(this.titleTextEdit);
}
f.loadRecord(rec);
}
else{
//this.isAdd = true;
this.setTitle(this.titleTextAdd);
var start = o[M.StartDate.name],
end = o[M.EndDate.name] || Extensible.Date.add(start, {hours: 1});
rec = Ext.create('Extensible.calendar.data.EventModel');
//rec.data[M.EventId.name] = this.newId++;
rec.data[M.StartDate.name] = start;
rec.data[M.EndDate.name] = end;
rec.data[M.IsAllDay.name] = !!o[M.IsAllDay.name] || start.getDate() != Extensible.Date.add(end, {millis: 1}).getDate();
f.reset();
f.loadRecord(rec);
}
if(this.calendarStore){
this.calendarField.setValue(rec.data[M.CalendarId.name]);
}
this.dateRangeField.setValue(rec.data);
this.activeRecord = rec;
//this.el.setStyle('z-index', 12000);
return this;
},
// private
roundTime: function(dt, incr){
incr = incr || 15;
var m = parseInt(dt.getMinutes());
return dt.add('mi', incr - (m % incr));
},
// private
onCancel: function(){
this.cleanup(true);
this.fireEvent('eventcancel', this, this.activeRecord, this.animateTarget);
},
// private
cleanup: function(hide){
if (this.activeRecord) {
this.activeRecord.reject();
}
delete this.activeRecord;
if (hide===true) {
// Work around the CSS day cell height hack needed for initial render in IE8/strict:
//var anim = afterDelete || (Ext.isIE8 && Ext.isStrict) ? null : this.animateTarget;
this.hide();
}
},
// private
// updateRecord: function(keepEditing){
// var dates = this.dateRangeField.getValue(),
// M = Extensible.calendar.data.EventMappings,
// rec = this.activeRecord,
// form = this.formPanel.form,
// fs = rec.fields,
// dirty = false; | //
// rec.beginEdit();
//
// //TODO: This block is copied directly from BasicForm.updateRecord. | random_line_split |
|
scheduledprogram.py | # Copyright (c) 2016 Sebastian Kanis
# This file is part of pi-led-control.
# pi-led-control 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.
# pi-led-control is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with pi-led-control. If not, see <http://www.gnu.org/licenses/>.
import datetime
import logging
from server.programs.abstractprogram import AbstractProgram
class ScheduledProgram(AbstractProgram):
def __init__(self, program, timeOfDay):
super().__init__()
self._program = program
self._timeOfDay = timeOfDay
def | (self):
now = datetime.datetime.now()
secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second
if secondsInCurrentDay < self._timeOfDay:
sleepDuration = self._timeOfDay - secondsInCurrentDay
else:
sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay
logging.getLogger("main").info("sleeping for " + str(sleepDuration) + " seconds")
self._waitIfNotStopped(sleepDuration)
self._program.run()
def setThreadStopEvent(self, threadStopEvent):
self.threadStopEvent = threadStopEvent
self._program.setThreadStopEvent(threadStopEvent)
def setColorSetter(self, colorSetter):
self._colorSetter = colorSetter
self._program.setColorSetter(colorSetter)
def getCurrentColor(self):
return self._program.getCurrentColor()
def setLastColor(self, lastColor):
self._program.setLastColor(lastColor)
| run | identifier_name |
scheduledprogram.py | # Copyright (c) 2016 Sebastian Kanis
# This file is part of pi-led-control.
# pi-led-control 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.
# pi-led-control is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with pi-led-control. If not, see <http://www.gnu.org/licenses/>.
import datetime
import logging
from server.programs.abstractprogram import AbstractProgram
class ScheduledProgram(AbstractProgram):
def __init__(self, program, timeOfDay):
super().__init__()
self._program = program
self._timeOfDay = timeOfDay | now = datetime.datetime.now()
secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second
if secondsInCurrentDay < self._timeOfDay:
sleepDuration = self._timeOfDay - secondsInCurrentDay
else:
sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay
logging.getLogger("main").info("sleeping for " + str(sleepDuration) + " seconds")
self._waitIfNotStopped(sleepDuration)
self._program.run()
def setThreadStopEvent(self, threadStopEvent):
self.threadStopEvent = threadStopEvent
self._program.setThreadStopEvent(threadStopEvent)
def setColorSetter(self, colorSetter):
self._colorSetter = colorSetter
self._program.setColorSetter(colorSetter)
def getCurrentColor(self):
return self._program.getCurrentColor()
def setLastColor(self, lastColor):
self._program.setLastColor(lastColor) |
def run(self): | random_line_split |
scheduledprogram.py | # Copyright (c) 2016 Sebastian Kanis
# This file is part of pi-led-control.
# pi-led-control 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.
# pi-led-control is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with pi-led-control. If not, see <http://www.gnu.org/licenses/>.
import datetime
import logging
from server.programs.abstractprogram import AbstractProgram
class ScheduledProgram(AbstractProgram):
def __init__(self, program, timeOfDay):
super().__init__()
self._program = program
self._timeOfDay = timeOfDay
def run(self):
now = datetime.datetime.now()
secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second
if secondsInCurrentDay < self._timeOfDay:
|
else:
sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay
logging.getLogger("main").info("sleeping for " + str(sleepDuration) + " seconds")
self._waitIfNotStopped(sleepDuration)
self._program.run()
def setThreadStopEvent(self, threadStopEvent):
self.threadStopEvent = threadStopEvent
self._program.setThreadStopEvent(threadStopEvent)
def setColorSetter(self, colorSetter):
self._colorSetter = colorSetter
self._program.setColorSetter(colorSetter)
def getCurrentColor(self):
return self._program.getCurrentColor()
def setLastColor(self, lastColor):
self._program.setLastColor(lastColor)
| sleepDuration = self._timeOfDay - secondsInCurrentDay | conditional_block |
scheduledprogram.py | # Copyright (c) 2016 Sebastian Kanis
# This file is part of pi-led-control.
# pi-led-control 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.
# pi-led-control is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with pi-led-control. If not, see <http://www.gnu.org/licenses/>.
import datetime
import logging
from server.programs.abstractprogram import AbstractProgram
class ScheduledProgram(AbstractProgram):
def __init__(self, program, timeOfDay):
super().__init__()
self._program = program
self._timeOfDay = timeOfDay
def run(self):
now = datetime.datetime.now()
secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second
if secondsInCurrentDay < self._timeOfDay:
sleepDuration = self._timeOfDay - secondsInCurrentDay
else:
sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay
logging.getLogger("main").info("sleeping for " + str(sleepDuration) + " seconds")
self._waitIfNotStopped(sleepDuration)
self._program.run()
def setThreadStopEvent(self, threadStopEvent):
|
def setColorSetter(self, colorSetter):
self._colorSetter = colorSetter
self._program.setColorSetter(colorSetter)
def getCurrentColor(self):
return self._program.getCurrentColor()
def setLastColor(self, lastColor):
self._program.setLastColor(lastColor)
| self.threadStopEvent = threadStopEvent
self._program.setThreadStopEvent(threadStopEvent) | identifier_body |
parameters.ts | import { IConfig } from '../config';
function | (content: string, index: number): number {
let angleBracketCount = 0;
while (index < content.length) {
if (content[index] === '<') {
angleBracketCount++;
}
if (content[index] === '>' && angleBracketCount > 0) {
angleBracketCount--;
}
if (content[index] === ',' && angleBracketCount === 0) {
break;
}
index++;
}
return index;
}
function parseParameters(content: string): string[] {
let index = 0;
const result: string[] = [];
while (index < content.length) {
const end = findParameterEnd(content, index);
const parameter = content.substr(index, end - index).trim();
if (parameter.length) {
result.push(parameter);
}
index = end + 1;
}
return result;
}
export function parameters(config: IConfig, content: string): IConfig {
return {
...config,
parameters: [...config.parameters, ...parseParameters(content)]
};
}
| findParameterEnd | identifier_name |
parameters.ts | import { IConfig } from '../config';
function findParameterEnd(content: string, index: number): number {
let angleBracketCount = 0;
while (index < content.length) {
if (content[index] === '<') {
angleBracketCount++;
}
if (content[index] === '>' && angleBracketCount > 0) {
angleBracketCount--;
}
if (content[index] === ',' && angleBracketCount === 0) {
break;
}
index++;
}
return index;
}
function parseParameters(content: string): string[] |
export function parameters(config: IConfig, content: string): IConfig {
return {
...config,
parameters: [...config.parameters, ...parseParameters(content)]
};
}
| {
let index = 0;
const result: string[] = [];
while (index < content.length) {
const end = findParameterEnd(content, index);
const parameter = content.substr(index, end - index).trim();
if (parameter.length) {
result.push(parameter);
}
index = end + 1;
}
return result;
} | identifier_body |
parameters.ts | import { IConfig } from '../config';
function findParameterEnd(content: string, index: number): number {
let angleBracketCount = 0;
while (index < content.length) {
if (content[index] === '<') {
angleBracketCount++;
}
if (content[index] === '>' && angleBracketCount > 0) {
| break;
}
index++;
}
return index;
}
function parseParameters(content: string): string[] {
let index = 0;
const result: string[] = [];
while (index < content.length) {
const end = findParameterEnd(content, index);
const parameter = content.substr(index, end - index).trim();
if (parameter.length) {
result.push(parameter);
}
index = end + 1;
}
return result;
}
export function parameters(config: IConfig, content: string): IConfig {
return {
...config,
parameters: [...config.parameters, ...parseParameters(content)]
};
} | angleBracketCount--;
}
if (content[index] === ',' && angleBracketCount === 0) {
| random_line_split |
parameters.ts | import { IConfig } from '../config';
function findParameterEnd(content: string, index: number): number {
let angleBracketCount = 0;
while (index < content.length) {
if (content[index] === '<') {
angleBracketCount++;
}
if (content[index] === '>' && angleBracketCount > 0) {
angleBracketCount--;
}
if (content[index] === ',' && angleBracketCount === 0) |
index++;
}
return index;
}
function parseParameters(content: string): string[] {
let index = 0;
const result: string[] = [];
while (index < content.length) {
const end = findParameterEnd(content, index);
const parameter = content.substr(index, end - index).trim();
if (parameter.length) {
result.push(parameter);
}
index = end + 1;
}
return result;
}
export function parameters(config: IConfig, content: string): IConfig {
return {
...config,
parameters: [...config.parameters, ...parseParameters(content)]
};
}
| {
break;
} | conditional_block |
settings.py | """
Django settings for channel_worm project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd0vy02-g#nq@lg!s%5v$w(jilj@af791#1-3k9y7ea3c)djj!w'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'digitizer',
'ion_channel'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'channelworm.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(__file__), 'templates', )],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'channelworm.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
# Pycharm detected this
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates').replace('\\', '/'),
)
# TEMPLATE_LOADERS = (
# 'django.template.loaders.filesystem.Loader',
# 'django.template.loaders.app_directories.Loader',
# )
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(
os.path.dirname(__file__),
'static', | MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
MEDIA_URL = '/media/' | ),
)
| random_line_split |
RangeHTTPServer.py | #!/usr/bin/python
'''
Use this in the same way as Python's http.server / SimpleHTTPServer:
python -m RangeHTTPServer [port]
The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports
'Range:' headers to load portions of files. This is helpful for doing local web
development with genomic data files, which tend to be to large to load into the
browser all at once.
'''
import os
import re
import sys
import argparse
try:
from http.server import SimpleHTTPRequestHandler
import http.server as http_server
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
import SimpleHTTPServer as http_server
def copy_byte_range(infile, outfile, start=None, stop=None, bufsize=16*1024):
'''Like shutil.copyfileobj, but only copy a range of the streams.
Both start and stop are inclusive.
'''
if start is not None: infile.seek(start)
while 1:
|
BYTE_RANGE_RE = re.compile(r'bytes=(\d+)-(\d+)?$')
def parse_byte_range(byte_range):
'''Returns the two numbers in 'bytes=123-456' or throws ValueError.
The last number or both numbers may be None.
'''
if byte_range.strip() == '':
return None, None
m = BYTE_RANGE_RE.match(byte_range)
if not m:
raise ValueError('Invalid byte range %s' % byte_range)
first, last = [x and int(x) for x in m.groups()]
if last and last < first:
raise ValueError('Invalid byte range %s' % byte_range)
return first, last
class RangeRequestHandler(SimpleHTTPRequestHandler):
"""Adds support for HTTP 'Range' requests to SimpleHTTPRequestHandler
The approach is to:
- Override send_head to look for 'Range' and respond appropriately.
- Override copyfile to only transmit a range when requested.
"""
def send_head(self):
if 'Range' not in self.headers:
self.range = None
return SimpleHTTPRequestHandler.send_head(self)
try:
self.range = parse_byte_range(self.headers['Range'])
except ValueError as e:
self.send_error(400, 'Invalid byte range')
return None
first, last = self.range
# Mirroring SimpleHTTPServer.py here
path = self.translate_path(self.path)
f = None
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, 'File not found')
return None
fs = os.fstat(f.fileno())
file_len = fs[6]
if first >= file_len:
self.send_error(416, 'Requested Range Not Satisfiable')
return None
self.send_response(206)
self.send_header('Content-type', ctype)
self.send_header('Accept-Ranges', 'bytes')
if last is None or last >= file_len:
last = file_len - 1
response_length = last - first + 1
self.send_header('Content-Range',
'bytes %s-%s/%s' % (first, last, file_len))
self.send_header('Content-Length', str(response_length))
self.send_header('Last-Modified', self.date_time_string(fs.st_mtime))
self.end_headers()
return f
def copyfile(self, source, outputfile):
if not self.range:
return SimpleHTTPRequestHandler.copyfile(self, source, outputfile)
# SimpleHTTPRequestHandler uses shutil.copyfileobj, which doesn't let
# you stop the copying before the end of the file.
start, stop = self.range # set in send_head()
copy_byte_range(source, outputfile, start, stop)
if __name__ == '__main__':
if sys.version_info[0] == 2:
http_server.test(HandlerClass=RangeRequestHandler)
# Python2's SimpleHTTPServer.test doesn't support bind and port args
else:
parser = argparse.ArgumentParser()
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
http_server.test(HandlerClass=RangeRequestHandler, port=args.port, bind=args.bind)
| to_read = min(bufsize, stop + 1 - infile.tell() if stop else bufsize)
buf = infile.read(to_read)
if not buf:
break
outfile.write(buf) | conditional_block |
RangeHTTPServer.py | #!/usr/bin/python
'''
Use this in the same way as Python's http.server / SimpleHTTPServer:
python -m RangeHTTPServer [port]
The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports
'Range:' headers to load portions of files. This is helpful for doing local web
development with genomic data files, which tend to be to large to load into the
browser all at once.
'''
import os
import re
import sys
import argparse
try:
from http.server import SimpleHTTPRequestHandler
import http.server as http_server
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
import SimpleHTTPServer as http_server
def copy_byte_range(infile, outfile, start=None, stop=None, bufsize=16*1024):
'''Like shutil.copyfileobj, but only copy a range of the streams.
Both start and stop are inclusive.
'''
if start is not None: infile.seek(start)
while 1:
to_read = min(bufsize, stop + 1 - infile.tell() if stop else bufsize)
buf = infile.read(to_read)
if not buf:
break
outfile.write(buf)
BYTE_RANGE_RE = re.compile(r'bytes=(\d+)-(\d+)?$')
def parse_byte_range(byte_range):
'''Returns the two numbers in 'bytes=123-456' or throws ValueError.
The last number or both numbers may be None.
'''
if byte_range.strip() == '':
return None, None
m = BYTE_RANGE_RE.match(byte_range)
if not m:
raise ValueError('Invalid byte range %s' % byte_range)
first, last = [x and int(x) for x in m.groups()]
if last and last < first:
raise ValueError('Invalid byte range %s' % byte_range)
return first, last
class RangeRequestHandler(SimpleHTTPRequestHandler):
"""Adds support for HTTP 'Range' requests to SimpleHTTPRequestHandler
The approach is to:
- Override send_head to look for 'Range' and respond appropriately.
- Override copyfile to only transmit a range when requested.
"""
def send_head(self):
if 'Range' not in self.headers:
self.range = None
return SimpleHTTPRequestHandler.send_head(self)
try:
self.range = parse_byte_range(self.headers['Range'])
except ValueError as e:
self.send_error(400, 'Invalid byte range')
return None
first, last = self.range |
# Mirroring SimpleHTTPServer.py here
path = self.translate_path(self.path)
f = None
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, 'File not found')
return None
fs = os.fstat(f.fileno())
file_len = fs[6]
if first >= file_len:
self.send_error(416, 'Requested Range Not Satisfiable')
return None
self.send_response(206)
self.send_header('Content-type', ctype)
self.send_header('Accept-Ranges', 'bytes')
if last is None or last >= file_len:
last = file_len - 1
response_length = last - first + 1
self.send_header('Content-Range',
'bytes %s-%s/%s' % (first, last, file_len))
self.send_header('Content-Length', str(response_length))
self.send_header('Last-Modified', self.date_time_string(fs.st_mtime))
self.end_headers()
return f
def copyfile(self, source, outputfile):
if not self.range:
return SimpleHTTPRequestHandler.copyfile(self, source, outputfile)
# SimpleHTTPRequestHandler uses shutil.copyfileobj, which doesn't let
# you stop the copying before the end of the file.
start, stop = self.range # set in send_head()
copy_byte_range(source, outputfile, start, stop)
if __name__ == '__main__':
if sys.version_info[0] == 2:
http_server.test(HandlerClass=RangeRequestHandler)
# Python2's SimpleHTTPServer.test doesn't support bind and port args
else:
parser = argparse.ArgumentParser()
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
http_server.test(HandlerClass=RangeRequestHandler, port=args.port, bind=args.bind) | random_line_split |
|
RangeHTTPServer.py | #!/usr/bin/python
'''
Use this in the same way as Python's http.server / SimpleHTTPServer:
python -m RangeHTTPServer [port]
The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports
'Range:' headers to load portions of files. This is helpful for doing local web
development with genomic data files, which tend to be to large to load into the
browser all at once.
'''
import os
import re
import sys
import argparse
try:
from http.server import SimpleHTTPRequestHandler
import http.server as http_server
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
import SimpleHTTPServer as http_server
def copy_byte_range(infile, outfile, start=None, stop=None, bufsize=16*1024):
'''Like shutil.copyfileobj, but only copy a range of the streams.
Both start and stop are inclusive.
'''
if start is not None: infile.seek(start)
while 1:
to_read = min(bufsize, stop + 1 - infile.tell() if stop else bufsize)
buf = infile.read(to_read)
if not buf:
break
outfile.write(buf)
BYTE_RANGE_RE = re.compile(r'bytes=(\d+)-(\d+)?$')
def parse_byte_range(byte_range):
'''Returns the two numbers in 'bytes=123-456' or throws ValueError.
The last number or both numbers may be None.
'''
if byte_range.strip() == '':
return None, None
m = BYTE_RANGE_RE.match(byte_range)
if not m:
raise ValueError('Invalid byte range %s' % byte_range)
first, last = [x and int(x) for x in m.groups()]
if last and last < first:
raise ValueError('Invalid byte range %s' % byte_range)
return first, last
class RangeRequestHandler(SimpleHTTPRequestHandler):
"""Adds support for HTTP 'Range' requests to SimpleHTTPRequestHandler
The approach is to:
- Override send_head to look for 'Range' and respond appropriately.
- Override copyfile to only transmit a range when requested.
"""
def send_head(self):
| fs = os.fstat(f.fileno())
file_len = fs[6]
if first >= file_len:
self.send_error(416, 'Requested Range Not Satisfiable')
return None
self.send_response(206)
self.send_header('Content-type', ctype)
self.send_header('Accept-Ranges', 'bytes')
if last is None or last >= file_len:
last = file_len - 1
response_length = last - first + 1
self.send_header('Content-Range',
'bytes %s-%s/%s' % (first, last, file_len))
self.send_header('Content-Length', str(response_length))
self.send_header('Last-Modified', self.date_time_string(fs.st_mtime))
self.end_headers()
return f
def copyfile(self, source, outputfile):
if not self.range:
return SimpleHTTPRequestHandler.copyfile(self, source, outputfile)
# SimpleHTTPRequestHandler uses shutil.copyfileobj, which doesn't let
# you stop the copying before the end of the file.
start, stop = self.range # set in send_head()
copy_byte_range(source, outputfile, start, stop)
if __name__ == '__main__':
if sys.version_info[0] == 2:
http_server.test(HandlerClass=RangeRequestHandler)
# Python2's SimpleHTTPServer.test doesn't support bind and port args
else:
parser = argparse.ArgumentParser()
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
http_server.test(HandlerClass=RangeRequestHandler, port=args.port, bind=args.bind)
| if 'Range' not in self.headers:
self.range = None
return SimpleHTTPRequestHandler.send_head(self)
try:
self.range = parse_byte_range(self.headers['Range'])
except ValueError as e:
self.send_error(400, 'Invalid byte range')
return None
first, last = self.range
# Mirroring SimpleHTTPServer.py here
path = self.translate_path(self.path)
f = None
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, 'File not found')
return None
| identifier_body |
RangeHTTPServer.py | #!/usr/bin/python
'''
Use this in the same way as Python's http.server / SimpleHTTPServer:
python -m RangeHTTPServer [port]
The only difference from http.server / SimpleHTTPServer is that RangeHTTPServer supports
'Range:' headers to load portions of files. This is helpful for doing local web
development with genomic data files, which tend to be to large to load into the
browser all at once.
'''
import os
import re
import sys
import argparse
try:
from http.server import SimpleHTTPRequestHandler
import http.server as http_server
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
import SimpleHTTPServer as http_server
def copy_byte_range(infile, outfile, start=None, stop=None, bufsize=16*1024):
'''Like shutil.copyfileobj, but only copy a range of the streams.
Both start and stop are inclusive.
'''
if start is not None: infile.seek(start)
while 1:
to_read = min(bufsize, stop + 1 - infile.tell() if stop else bufsize)
buf = infile.read(to_read)
if not buf:
break
outfile.write(buf)
BYTE_RANGE_RE = re.compile(r'bytes=(\d+)-(\d+)?$')
def parse_byte_range(byte_range):
'''Returns the two numbers in 'bytes=123-456' or throws ValueError.
The last number or both numbers may be None.
'''
if byte_range.strip() == '':
return None, None
m = BYTE_RANGE_RE.match(byte_range)
if not m:
raise ValueError('Invalid byte range %s' % byte_range)
first, last = [x and int(x) for x in m.groups()]
if last and last < first:
raise ValueError('Invalid byte range %s' % byte_range)
return first, last
class RangeRequestHandler(SimpleHTTPRequestHandler):
"""Adds support for HTTP 'Range' requests to SimpleHTTPRequestHandler
The approach is to:
- Override send_head to look for 'Range' and respond appropriately.
- Override copyfile to only transmit a range when requested.
"""
def send_head(self):
if 'Range' not in self.headers:
self.range = None
return SimpleHTTPRequestHandler.send_head(self)
try:
self.range = parse_byte_range(self.headers['Range'])
except ValueError as e:
self.send_error(400, 'Invalid byte range')
return None
first, last = self.range
# Mirroring SimpleHTTPServer.py here
path = self.translate_path(self.path)
f = None
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, 'File not found')
return None
fs = os.fstat(f.fileno())
file_len = fs[6]
if first >= file_len:
self.send_error(416, 'Requested Range Not Satisfiable')
return None
self.send_response(206)
self.send_header('Content-type', ctype)
self.send_header('Accept-Ranges', 'bytes')
if last is None or last >= file_len:
last = file_len - 1
response_length = last - first + 1
self.send_header('Content-Range',
'bytes %s-%s/%s' % (first, last, file_len))
self.send_header('Content-Length', str(response_length))
self.send_header('Last-Modified', self.date_time_string(fs.st_mtime))
self.end_headers()
return f
def | (self, source, outputfile):
if not self.range:
return SimpleHTTPRequestHandler.copyfile(self, source, outputfile)
# SimpleHTTPRequestHandler uses shutil.copyfileobj, which doesn't let
# you stop the copying before the end of the file.
start, stop = self.range # set in send_head()
copy_byte_range(source, outputfile, start, stop)
if __name__ == '__main__':
if sys.version_info[0] == 2:
http_server.test(HandlerClass=RangeRequestHandler)
# Python2's SimpleHTTPServer.test doesn't support bind and port args
else:
parser = argparse.ArgumentParser()
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
http_server.test(HandlerClass=RangeRequestHandler, port=args.port, bind=args.bind)
| copyfile | identifier_name |
webpack-dev.config.js | entry: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'./src/index.js'
],
output: {
publicPath: '/',
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-0']
}
}
]
},
devtool: 'source-map',
devServer: {
contentBase: path.join(__dirname, 'dist'),
host: '0.0.0.0',
port: 8080,
historyApiFallback: true
}
}; | var path = require('path');
module.exports = { | random_line_split |
|
error.rs | ExceptionMethods;
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
use dom::bindings::conversions::root_from_object;
use dom::bindings::str::USVString;
use dom::domexception::{DOMErrorName, DOMException};
use dom::globalscope::GlobalScope;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsval::UndefinedValue;
use js::rust::HandleObject;
use js::rust::MutableHandleValue;
use js::rust::wrappers::JS_ErrorFromException;
use js::rust::wrappers::JS_GetPendingException;
use js::rust::wrappers::JS_SetPendingException;
use libc::c_uint;
use std::slice::from_raw_parts;
/// An optional stringified JS backtrace and stringified native backtrace from the
/// the last DOM exception that was reported.
#[cfg(feature = "js_backtrace")]
thread_local!(static LAST_EXCEPTION_BACKTRACE: DomRefCell<Option<(Option<String>, String)>> = DomRefCell::new(None));
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// NotReadableError DOMException
NotReadable,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn | (cx: *mut JSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
{
capture_stack!(in(cx) let stack);
let js_stack = stack.and_then(|s| s.as_string(None));
let rust_stack = Backtrace::new();
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
*backtrace.borrow_mut() = Some((js_stack, format!("{:?}", rust_stack)));
});
}
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::NotReadable => DOMErrorName::NotReadableError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
},
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report)._base.filename as *const u8;
if !filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report)._base.lineno;
let column = (*report)._base.column;
let message = {
let message = (*report)._base.message_.data_ as *const u8;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf8_lossy(message).into_owned()
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if !JS_IsExceptionPending(cx) {
return;
}
rooted!(in(cx) let mut value = UndefinedValue());
if !JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!(
"Error at {}:{}:{} {}",
error_info.filename, error_info.lineno, error_info.column, error_info.message
);
#[cfg(feature = "js_backtrace")]
{
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() {
| throw_dom_exception | identifier_name |
error.rs | FromException;
use js::rust::wrappers::JS_GetPendingException;
use js::rust::wrappers::JS_SetPendingException;
use libc::c_uint;
use std::slice::from_raw_parts;
/// An optional stringified JS backtrace and stringified native backtrace from the
/// the last DOM exception that was reported.
#[cfg(feature = "js_backtrace")]
thread_local!(static LAST_EXCEPTION_BACKTRACE: DomRefCell<Option<(Option<String>, String)>> = DomRefCell::new(None));
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// NotReadableError DOMException
NotReadable,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
{
capture_stack!(in(cx) let stack);
let js_stack = stack.and_then(|s| s.as_string(None));
let rust_stack = Backtrace::new();
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
*backtrace.borrow_mut() = Some((js_stack, format!("{:?}", rust_stack)));
});
}
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::NotReadable => DOMErrorName::NotReadableError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
},
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report)._base.filename as *const u8;
if !filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report)._base.lineno;
let column = (*report)._base.column;
let message = {
let message = (*report)._base.message_.data_ as *const u8;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf8_lossy(message).into_owned()
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if !JS_IsExceptionPending(cx) {
return;
}
rooted!(in(cx) let mut value = UndefinedValue());
if !JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!(
"Error at {}:{}:{} {}",
error_info.filename, error_info.lineno, error_info.column, error_info.message
);
#[cfg(feature = "js_backtrace")]
{
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() {
if let Some(stack) = js_backtrace {
eprintln!("JS backtrace:\n{}", stack);
}
eprintln!("Rust backtrace:\n{}", rust_backtrace);
}
});
}
if dispatch_event {
GlobalScope::from_context(cx).report_an_error(error_info, value.handle());
}
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) | {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!(
"\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id)
);
throw_type_error(cx, &error);
} | identifier_body |
|
error.rs | ExceptionMethods;
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
use dom::bindings::conversions::root_from_object;
use dom::bindings::str::USVString;
use dom::domexception::{DOMErrorName, DOMException};
use dom::globalscope::GlobalScope;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsval::UndefinedValue;
use js::rust::HandleObject;
use js::rust::MutableHandleValue;
use js::rust::wrappers::JS_ErrorFromException;
use js::rust::wrappers::JS_GetPendingException;
use js::rust::wrappers::JS_SetPendingException;
use libc::c_uint;
use std::slice::from_raw_parts;
/// An optional stringified JS backtrace and stringified native backtrace from the
/// the last DOM exception that was reported.
#[cfg(feature = "js_backtrace")]
thread_local!(static LAST_EXCEPTION_BACKTRACE: DomRefCell<Option<(Option<String>, String)>> = DomRefCell::new(None));
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// NotReadableError DOMException
NotReadable,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
{
capture_stack!(in(cx) let stack);
let js_stack = stack.and_then(|s| s.as_string(None));
let rust_stack = Backtrace::new();
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
*backtrace.borrow_mut() = Some((js_stack, format!("{:?}", rust_stack)));
});
}
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::NotReadable => DOMErrorName::NotReadableError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
},
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() |
let filename = {
let filename = (*report)._base.filename as *const u8;
if !filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report)._base.lineno;
let column = (*report)._base.column;
let message = {
let message = (*report)._base.message_.data_ as *const u8;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf8_lossy(message).into_owned()
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if !JS_IsExceptionPending(cx) {
return;
}
rooted!(in(cx) let mut value = UndefinedValue());
if !JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!(
"Error at {}:{}:{} {}",
error_info.filename, error_info.lineno, error_info.column, error_info.message
);
#[cfg(feature = "js_backtrace")]
{
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() | {
return None;
} | conditional_block |
error.rs | ExceptionMethods;
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
use dom::bindings::conversions::root_from_object;
use dom::bindings::str::USVString;
use dom::domexception::{DOMErrorName, DOMException};
use dom::globalscope::GlobalScope;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsval::UndefinedValue;
use js::rust::HandleObject;
use js::rust::MutableHandleValue;
use js::rust::wrappers::JS_ErrorFromException;
use js::rust::wrappers::JS_GetPendingException;
use js::rust::wrappers::JS_SetPendingException;
use libc::c_uint;
use std::slice::from_raw_parts;
/// An optional stringified JS backtrace and stringified native backtrace from the
/// the last DOM exception that was reported.
#[cfg(feature = "js_backtrace")]
thread_local!(static LAST_EXCEPTION_BACKTRACE: DomRefCell<Option<(Option<String>, String)>> = DomRefCell::new(None));
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// NotReadableError DOMException
NotReadable,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
#[cfg(feature = "js_backtrace")]
{
capture_stack!(in(cx) let stack);
let js_stack = stack.and_then(|s| s.as_string(None));
let rust_stack = Backtrace::new();
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
*backtrace.borrow_mut() = Some((js_stack, format!("{:?}", rust_stack)));
});
}
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::NotReadable => DOMErrorName::NotReadableError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
},
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject) -> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = { | let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report)._base.lineno;
let column = (*report)._base.column;
let message = {
let message = (*report)._base.message_.data_ as *const u8;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf8_lossy(message).into_owned()
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if !JS_IsExceptionPending(cx) {
return;
}
rooted!(in(cx) let mut value = UndefinedValue());
if !JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!(
"Error at {}:{}:{} {}",
error_info.filename, error_info.lineno, error_info.column, error_info.message
);
#[cfg(feature = "js_backtrace")]
{
LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() {
| let filename = (*report)._base.filename as *const u8;
if !filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap(); | random_line_split |
client_activity.py | from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from django.db.models import Count, QuerySet
from zerver.models import UserActivity, UserProfile, Realm, \
get_realm, get_user_profile_by_email
import datetime
class Command(BaseCommand):
help = """Report rough client activity globally, for a realm, or for a user
Usage examples:
./manage.py client_activity
./manage.py client_activity zulip.com
./manage.py client_activity [email protected]"""
def add_arguments(self, parser):
# type: (ArgumentParser) -> None
parser.add_argument('arg', metavar='<arg>', type=str, nargs='?', default=None,
help="realm or user to estimate client activity for")
def compute_activity(self, user_activity_objects):
# type: (QuerySet) -> None
# Report data from the past week.
#
# This is a rough report of client activity because we inconsistently
# register activity from various clients; think of it as telling you
# approximately how many people from a group have used a particular
# client recently. For example, this might be useful to get a sense of
# how popular different versions of a desktop client are.
#
# Importantly, this does NOT tell you anything about the relative
# volumes of requests from clients.
threshold = datetime.datetime.now() - datetime.timedelta(days=7)
client_counts = user_activity_objects.filter(
last_visit__gt=threshold).values("client__name").annotate(
count=Count('client__name'))
total = 0
counts = []
for client_type in client_counts:
count = client_type["count"]
client = client_type["client__name"]
total += count
counts.append((count, client))
counts.sort()
for count in counts:
print("%25s %15d" % (count[1], count[0]))
print("Total:", total)
def handle(self, *args, **options):
# type: (*Any, **str) -> None
if options['arg'] is None:
# Report global activity.
|
else:
arg = options['arg']
try:
# Report activity for a user.
user_profile = get_user_profile_by_email(arg)
self.compute_activity(UserActivity.objects.filter(
user_profile=user_profile))
except UserProfile.DoesNotExist:
try:
# Report activity for a realm.
realm = get_realm(arg)
self.compute_activity(UserActivity.objects.filter(
user_profile__realm=realm))
except Realm.DoesNotExist:
print("Unknown user or domain %s" % (arg,))
exit(1)
| self.compute_activity(UserActivity.objects.all()) | conditional_block |
client_activity.py | from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from django.db.models import Count, QuerySet
from zerver.models import UserActivity, UserProfile, Realm, \
get_realm, get_user_profile_by_email
import datetime
class | (BaseCommand):
help = """Report rough client activity globally, for a realm, or for a user
Usage examples:
./manage.py client_activity
./manage.py client_activity zulip.com
./manage.py client_activity [email protected]"""
def add_arguments(self, parser):
# type: (ArgumentParser) -> None
parser.add_argument('arg', metavar='<arg>', type=str, nargs='?', default=None,
help="realm or user to estimate client activity for")
def compute_activity(self, user_activity_objects):
# type: (QuerySet) -> None
# Report data from the past week.
#
# This is a rough report of client activity because we inconsistently
# register activity from various clients; think of it as telling you
# approximately how many people from a group have used a particular
# client recently. For example, this might be useful to get a sense of
# how popular different versions of a desktop client are.
#
# Importantly, this does NOT tell you anything about the relative
# volumes of requests from clients.
threshold = datetime.datetime.now() - datetime.timedelta(days=7)
client_counts = user_activity_objects.filter(
last_visit__gt=threshold).values("client__name").annotate(
count=Count('client__name'))
total = 0
counts = []
for client_type in client_counts:
count = client_type["count"]
client = client_type["client__name"]
total += count
counts.append((count, client))
counts.sort()
for count in counts:
print("%25s %15d" % (count[1], count[0]))
print("Total:", total)
def handle(self, *args, **options):
# type: (*Any, **str) -> None
if options['arg'] is None:
# Report global activity.
self.compute_activity(UserActivity.objects.all())
else:
arg = options['arg']
try:
# Report activity for a user.
user_profile = get_user_profile_by_email(arg)
self.compute_activity(UserActivity.objects.filter(
user_profile=user_profile))
except UserProfile.DoesNotExist:
try:
# Report activity for a realm.
realm = get_realm(arg)
self.compute_activity(UserActivity.objects.filter(
user_profile__realm=realm))
except Realm.DoesNotExist:
print("Unknown user or domain %s" % (arg,))
exit(1)
| Command | identifier_name |
client_activity.py | from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from django.db.models import Count, QuerySet
from zerver.models import UserActivity, UserProfile, Realm, \
get_realm, get_user_profile_by_email
import datetime
class Command(BaseCommand):
help = """Report rough client activity globally, for a realm, or for a user
Usage examples:
./manage.py client_activity
./manage.py client_activity zulip.com
./manage.py client_activity [email protected]"""
def add_arguments(self, parser):
# type: (ArgumentParser) -> None
parser.add_argument('arg', metavar='<arg>', type=str, nargs='?', default=None,
help="realm or user to estimate client activity for")
def compute_activity(self, user_activity_objects):
# type: (QuerySet) -> None
# Report data from the past week.
#
# This is a rough report of client activity because we inconsistently
# register activity from various clients; think of it as telling you
# approximately how many people from a group have used a particular
# client recently. For example, this might be useful to get a sense of
# how popular different versions of a desktop client are.
#
# Importantly, this does NOT tell you anything about the relative
# volumes of requests from clients.
threshold = datetime.datetime.now() - datetime.timedelta(days=7)
client_counts = user_activity_objects.filter(
last_visit__gt=threshold).values("client__name").annotate(
count=Count('client__name'))
total = 0
counts = []
for client_type in client_counts:
count = client_type["count"]
client = client_type["client__name"]
total += count
counts.append((count, client))
counts.sort()
for count in counts:
print("%25s %15d" % (count[1], count[0]))
print("Total:", total)
def handle(self, *args, **options):
# type: (*Any, **str) -> None | else:
arg = options['arg']
try:
# Report activity for a user.
user_profile = get_user_profile_by_email(arg)
self.compute_activity(UserActivity.objects.filter(
user_profile=user_profile))
except UserProfile.DoesNotExist:
try:
# Report activity for a realm.
realm = get_realm(arg)
self.compute_activity(UserActivity.objects.filter(
user_profile__realm=realm))
except Realm.DoesNotExist:
print("Unknown user or domain %s" % (arg,))
exit(1) | if options['arg'] is None:
# Report global activity.
self.compute_activity(UserActivity.objects.all()) | random_line_split |
client_activity.py | from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from django.db.models import Count, QuerySet
from zerver.models import UserActivity, UserProfile, Realm, \
get_realm, get_user_profile_by_email
import datetime
class Command(BaseCommand):
| # client recently. For example, this might be useful to get a sense of
# how popular different versions of a desktop client are.
#
# Importantly, this does NOT tell you anything about the relative
# volumes of requests from clients.
threshold = datetime.datetime.now() - datetime.timedelta(days=7)
client_counts = user_activity_objects.filter(
last_visit__gt=threshold).values("client__name").annotate(
count=Count('client__name'))
total = 0
counts = []
for client_type in client_counts:
count = client_type["count"]
client = client_type["client__name"]
total += count
counts.append((count, client))
counts.sort()
for count in counts:
print("%25s %15d" % (count[1], count[0]))
print("Total:", total)
def handle(self, *args, **options):
# type: (*Any, **str) -> None
if options['arg'] is None:
# Report global activity.
self.compute_activity(UserActivity.objects.all())
else:
arg = options['arg']
try:
# Report activity for a user.
user_profile = get_user_profile_by_email(arg)
self.compute_activity(UserActivity.objects.filter(
user_profile=user_profile))
except UserProfile.DoesNotExist:
try:
# Report activity for a realm.
realm = get_realm(arg)
self.compute_activity(UserActivity.objects.filter(
user_profile__realm=realm))
except Realm.DoesNotExist:
print("Unknown user or domain %s" % (arg,))
exit(1)
| help = """Report rough client activity globally, for a realm, or for a user
Usage examples:
./manage.py client_activity
./manage.py client_activity zulip.com
./manage.py client_activity [email protected]"""
def add_arguments(self, parser):
# type: (ArgumentParser) -> None
parser.add_argument('arg', metavar='<arg>', type=str, nargs='?', default=None,
help="realm or user to estimate client activity for")
def compute_activity(self, user_activity_objects):
# type: (QuerySet) -> None
# Report data from the past week.
#
# This is a rough report of client activity because we inconsistently
# register activity from various clients; think of it as telling you
# approximately how many people from a group have used a particular | identifier_body |
iadfa.py | from fsa import *
from nameGenerator import *
class IncrementalAdfa(Dfa):
"""This class is an Acyclic Deterministic Finite State Automaton
constructed by a list of words.
"""
def __init__(self, words, nameGenerator = None, sorted = False):
if nameGenerator is None:
nameGenerator = IndexNameGenerator()
self.nameGenerator = nameGenerator
if sorted:
self.createFromSortedListOfWords(words)
else:
self.createFromArbitraryListOfWords(words)
def getCommonPrefix(self, word):
stateName = self.startState
index = 0
nextStateName = stateName
while nextStateName is not None:
symbol = word[index]
stateName = nextStateName
if symbol in self.states[stateName].transitions:
nextStateName = self.states[stateName].transitions[symbol]
index += 1
else:
nextStateName = None
return (stateName, word[index:])
def hasChildren(self, stateName):
okay = False
if [s for s in list(self.states[stateName].transitions.values()) if s]:
okay = True
return okay
def addSuffix(self, stateName, currentSuffix):
lastState = stateName
while len(currentSuffix) > 0:
newStateName = self.nameGenerator.generate()
symbol = currentSuffix[0]
currentSuffix = currentSuffix[1:]
self.states[stateName].transitions[symbol] = newStateName
self.states[newStateName] = State(newStateName)
stateName = newStateName
self.finalStates.append(stateName)
def | (self, stateName):
return stateName in self.register
def markAsRegistered(self, stateName):
self.register[stateName] = True
def equivalentRegisteredState(self, stateName):
equivatentState = None
for state in list(self.register.keys()):
if self.areEquivalents(state, stateName):
equivatentState = state
return equivatentState
def lastChild(self, stateName):
input = list(self.states[stateName].transitions.keys())
input.sort()
return (self.states[stateName].transitions[input[-1]], input[-1])
def replaceOrRegister(self, stateName):
#childName = self.finalStates[-1]
childName, lastSymbol = self.lastChild(stateName)
if not self.markedAsRegistered(childName):
if self.hasChildren(childName):
self.replaceOrRegister(childName)
equivalentState = self.equivalentRegisteredState(childName)
if equivalentState is not None:
self.deleteBranch(childName)
self.states[stateName].transitions[lastSymbol] = equivalentState
else:
self.markAsRegistered(childName)
def deleteBranch(self, child):
childs = [child]
while len(childs) > 0:
nextChilds = []
for child in childs:
nextChilds += [s for s in list(self.states[child].transitions.values()) if not self.markedAsRegistered(s)]
self.states.pop(child)
if child in self.finalStates:
self.finalStates.remove(child)
childs = nextChilds
def createFromSortedListOfWords(self, words):
self.register = {}
self.finalStates = []
self.startState = self.nameGenerator.generate()
self.states = {self.startState : State(self.startState)}
lastWord = None
for word in words:
if word.endswith('\n'):
word = word[:-1]
lastStateName, currentSuffix = self.getCommonPrefix(word)
if self.hasChildren(lastStateName):
self.replaceOrRegister(lastStateName)
self.addSuffix(lastStateName, currentSuffix)
self.replaceOrRegister(self.startState)
def createFromArbitraryListOfWords(self, words):
self.register = {}
self.finalStates = []
self.startState = self.nameGenerator.generate()
self.states = {self.startState : State(self.startState)}
| markedAsRegistered | identifier_name |
iadfa.py | from fsa import *
from nameGenerator import *
class IncrementalAdfa(Dfa):
"""This class is an Acyclic Deterministic Finite State Automaton
constructed by a list of words.
"""
def __init__(self, words, nameGenerator = None, sorted = False):
if nameGenerator is None:
nameGenerator = IndexNameGenerator()
self.nameGenerator = nameGenerator
if sorted:
self.createFromSortedListOfWords(words)
else:
self.createFromArbitraryListOfWords(words)
def getCommonPrefix(self, word):
stateName = self.startState
index = 0
nextStateName = stateName
while nextStateName is not None:
symbol = word[index]
stateName = nextStateName
if symbol in self.states[stateName].transitions:
nextStateName = self.states[stateName].transitions[symbol]
index += 1
else:
|
return (stateName, word[index:])
def hasChildren(self, stateName):
okay = False
if [s for s in list(self.states[stateName].transitions.values()) if s]:
okay = True
return okay
def addSuffix(self, stateName, currentSuffix):
lastState = stateName
while len(currentSuffix) > 0:
newStateName = self.nameGenerator.generate()
symbol = currentSuffix[0]
currentSuffix = currentSuffix[1:]
self.states[stateName].transitions[symbol] = newStateName
self.states[newStateName] = State(newStateName)
stateName = newStateName
self.finalStates.append(stateName)
def markedAsRegistered(self, stateName):
return stateName in self.register
def markAsRegistered(self, stateName):
self.register[stateName] = True
def equivalentRegisteredState(self, stateName):
equivatentState = None
for state in list(self.register.keys()):
if self.areEquivalents(state, stateName):
equivatentState = state
return equivatentState
def lastChild(self, stateName):
input = list(self.states[stateName].transitions.keys())
input.sort()
return (self.states[stateName].transitions[input[-1]], input[-1])
def replaceOrRegister(self, stateName):
#childName = self.finalStates[-1]
childName, lastSymbol = self.lastChild(stateName)
if not self.markedAsRegistered(childName):
if self.hasChildren(childName):
self.replaceOrRegister(childName)
equivalentState = self.equivalentRegisteredState(childName)
if equivalentState is not None:
self.deleteBranch(childName)
self.states[stateName].transitions[lastSymbol] = equivalentState
else:
self.markAsRegistered(childName)
def deleteBranch(self, child):
childs = [child]
while len(childs) > 0:
nextChilds = []
for child in childs:
nextChilds += [s for s in list(self.states[child].transitions.values()) if not self.markedAsRegistered(s)]
self.states.pop(child)
if child in self.finalStates:
self.finalStates.remove(child)
childs = nextChilds
def createFromSortedListOfWords(self, words):
self.register = {}
self.finalStates = []
self.startState = self.nameGenerator.generate()
self.states = {self.startState : State(self.startState)}
lastWord = None
for word in words:
if word.endswith('\n'):
word = word[:-1]
lastStateName, currentSuffix = self.getCommonPrefix(word)
if self.hasChildren(lastStateName):
self.replaceOrRegister(lastStateName)
self.addSuffix(lastStateName, currentSuffix)
self.replaceOrRegister(self.startState)
def createFromArbitraryListOfWords(self, words):
self.register = {}
self.finalStates = []
self.startState = self.nameGenerator.generate()
self.states = {self.startState : State(self.startState)}
| nextStateName = None | conditional_block |
iadfa.py | from fsa import *
from nameGenerator import *
class IncrementalAdfa(Dfa):
"""This class is an Acyclic Deterministic Finite State Automaton
constructed by a list of words.
"""
def __init__(self, words, nameGenerator = None, sorted = False):
if nameGenerator is None:
nameGenerator = IndexNameGenerator()
self.nameGenerator = nameGenerator
if sorted:
self.createFromSortedListOfWords(words)
else:
self.createFromArbitraryListOfWords(words)
def getCommonPrefix(self, word):
stateName = self.startState
index = 0
nextStateName = stateName
while nextStateName is not None:
symbol = word[index]
stateName = nextStateName
if symbol in self.states[stateName].transitions:
nextStateName = self.states[stateName].transitions[symbol]
index += 1
else:
nextStateName = None
return (stateName, word[index:])
def hasChildren(self, stateName):
okay = False
if [s for s in list(self.states[stateName].transitions.values()) if s]:
okay = True
return okay
def addSuffix(self, stateName, currentSuffix):
lastState = stateName
while len(currentSuffix) > 0:
newStateName = self.nameGenerator.generate()
symbol = currentSuffix[0]
currentSuffix = currentSuffix[1:]
self.states[stateName].transitions[symbol] = newStateName
self.states[newStateName] = State(newStateName)
stateName = newStateName
self.finalStates.append(stateName)
def markedAsRegistered(self, stateName):
return stateName in self.register
def markAsRegistered(self, stateName):
self.register[stateName] = True
def equivalentRegisteredState(self, stateName):
equivatentState = None
for state in list(self.register.keys()):
if self.areEquivalents(state, stateName):
equivatentState = state
return equivatentState
def lastChild(self, stateName):
input = list(self.states[stateName].transitions.keys())
input.sort()
return (self.states[stateName].transitions[input[-1]], input[-1])
def replaceOrRegister(self, stateName):
#childName = self.finalStates[-1]
childName, lastSymbol = self.lastChild(stateName)
if not self.markedAsRegistered(childName):
if self.hasChildren(childName):
self.replaceOrRegister(childName)
equivalentState = self.equivalentRegisteredState(childName)
if equivalentState is not None:
self.deleteBranch(childName)
self.states[stateName].transitions[lastSymbol] = equivalentState
else:
self.markAsRegistered(childName)
def deleteBranch(self, child):
childs = [child]
while len(childs) > 0:
nextChilds = []
for child in childs:
nextChilds += [s for s in list(self.states[child].transitions.values()) if not self.markedAsRegistered(s)]
self.states.pop(child)
if child in self.finalStates:
self.finalStates.remove(child) |
def createFromSortedListOfWords(self, words):
self.register = {}
self.finalStates = []
self.startState = self.nameGenerator.generate()
self.states = {self.startState : State(self.startState)}
lastWord = None
for word in words:
if word.endswith('\n'):
word = word[:-1]
lastStateName, currentSuffix = self.getCommonPrefix(word)
if self.hasChildren(lastStateName):
self.replaceOrRegister(lastStateName)
self.addSuffix(lastStateName, currentSuffix)
self.replaceOrRegister(self.startState)
def createFromArbitraryListOfWords(self, words):
self.register = {}
self.finalStates = []
self.startState = self.nameGenerator.generate()
self.states = {self.startState : State(self.startState)} | childs = nextChilds
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.