file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
setup.py
with open('README.txt') as f: long_description = f.read() from distutils.core import setup setup( name = "nomit", packages = ["nomit"], version = "1.0", description = "Process Monit HTTP/XML", author = "Markus Juenemann", author_email = "markus@juenemann.net", url = "https://github.com/mjuenema/nomit", download_url = "https://github.com/mjuenema/nomit/tarball/1.0", keywords = ["xml", "Monit", "MMonit"], classifiers = [ "Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Monitoring", ], long_description = long_description )
"Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent",
random_line_split
modifyexperience.js
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker({ format: 'm/d/yyyy', autoclose: true }); initializeMap(); }; function initializeTypeahead() { $("#Experience_Name").typeahead({ name: 'title', prefetch: options.TitlesUrl, limit: 10 }); $("#Experience_Organization").typeahead({ name: 'orgs', prefetch: options.OrganizationsUrl, limit: 10 }); } function initializeImagePreview() { $("#cover-image").change(function () { var filesToUpload = this.files; if (filesToUpload.length !== 1) return; var file = filesToUpload[0]; if (!file.type.match(/image.*/)) { alert("only images, please"); } var img = document.getElementById("cover-preview"); img.src = window.URL.createObjectURL(file); img.onload = function(e) { window.URL.revokeObjectURL(this.src); }; //img.height = 500; }); } function initializeMap() {
}(window.Badges = window.Badges || {}, jQuery));
var davisLatLng = new google.maps.LatLng(38.5449065, -121.7405167); geocoder = new google.maps.Geocoder(); var mapOptions = { center: davisLatLng, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); marker = new google.maps.Marker({ map: map, position: davisLatLng }); $("#Experience_Location").blur(function () { var address = this.value; geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (marker) marker.setMap(null); //clear existing marker map.setCenter(results[0].geometry.location); marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }); }
identifier_body
modifyexperience.js
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker({ format: 'm/d/yyyy', autoclose: true }); initializeMap(); }; function initializeTypeahead() { $("#Experience_Name").typeahead({ name: 'title', prefetch: options.TitlesUrl, limit: 10 }); $("#Experience_Organization").typeahead({ name: 'orgs', prefetch: options.OrganizationsUrl, limit: 10 }); } function initializeImagePreview() { $("#cover-image").change(function () { var filesToUpload = this.files; if (filesToUpload.length !== 1) return; var file = filesToUpload[0]; if (!file.type.match(/image.*/)) { alert("only images, please"); } var img = document.getElementById("cover-preview"); img.src = window.URL.createObjectURL(file); img.onload = function(e) { window.URL.revokeObjectURL(this.src); }; //img.height = 500; }); } function initializeMap() { var davisLatLng = new google.maps.LatLng(38.5449065, -121.7405167); geocoder = new google.maps.Geocoder(); var mapOptions = {
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); marker = new google.maps.Marker({ map: map, position: davisLatLng }); $("#Experience_Location").blur(function () { var address = this.value; geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (marker) marker.setMap(null); //clear existing marker map.setCenter(results[0].geometry.location); marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }); } }(window.Badges = window.Badges || {}, jQuery));
center: davisLatLng, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP };
random_line_split
modifyexperience.js
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker({ format: 'm/d/yyyy', autoclose: true }); initializeMap(); }; function initializeTypeahead() { $("#Experience_Name").typeahead({ name: 'title', prefetch: options.TitlesUrl, limit: 10 }); $("#Experience_Organization").typeahead({ name: 'orgs', prefetch: options.OrganizationsUrl, limit: 10 }); } function initializeImagePreview() { $("#cover-image").change(function () { var filesToUpload = this.files; if (filesToUpload.length !== 1) return; var file = filesToUpload[0]; if (!file.type.match(/image.*/)) { alert("only images, please"); } var img = document.getElementById("cover-preview"); img.src = window.URL.createObjectURL(file); img.onload = function(e) { window.URL.revokeObjectURL(this.src); }; //img.height = 500; }); } function initializeMap() { var davisLatLng = new google.maps.LatLng(38.5449065, -121.7405167); geocoder = new google.maps.Geocoder(); var mapOptions = { center: davisLatLng, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); marker = new google.maps.Marker({ map: map, position: davisLatLng }); $("#Experience_Location").blur(function () { var address = this.value; geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (marker) marker.setMap(null); //clear existing marker map.setCenter(results[0].geometry.location); marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport); } else {
}); }); } }(window.Badges = window.Badges || {}, jQuery));
alert('Geocode was not successful for the following reason: ' + status); }
conditional_block
modifyexperience.js
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker({ format: 'm/d/yyyy', autoclose: true }); initializeMap(); }; function initializeTypeahead() { $("#Experience_Name").typeahead({ name: 'title', prefetch: options.TitlesUrl, limit: 10 }); $("#Experience_Organization").typeahead({ name: 'orgs', prefetch: options.OrganizationsUrl, limit: 10 }); } function in
{ $("#cover-image").change(function () { var filesToUpload = this.files; if (filesToUpload.length !== 1) return; var file = filesToUpload[0]; if (!file.type.match(/image.*/)) { alert("only images, please"); } var img = document.getElementById("cover-preview"); img.src = window.URL.createObjectURL(file); img.onload = function(e) { window.URL.revokeObjectURL(this.src); }; //img.height = 500; }); } function initializeMap() { var davisLatLng = new google.maps.LatLng(38.5449065, -121.7405167); geocoder = new google.maps.Geocoder(); var mapOptions = { center: davisLatLng, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); marker = new google.maps.Marker({ map: map, position: davisLatLng }); $("#Experience_Location").blur(function () { var address = this.value; geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (marker) marker.setMap(null); //clear existing marker map.setCenter(results[0].geometry.location); marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }); } }(window.Badges = window.Badges || {}, jQuery));
itializeImagePreview()
identifier_name
objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.ts
// Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those // parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required, // optional or rest) and types, and identical return types. class B<T, U> { constructor(x: T, y: U) { return null; } } class C<T, U> { constructor(x: T, y?: U) { return null; } } interface I<T, U> { new(x: T, y?: U): B<T, U>; } interface I2 { new<T, U>(x: T, y: U): C<T, U>; } var a: { new <T, U>(x: T, y?: U): B<T, U> }; var b = { new<T, U>(x: T, y: U) { return new C<T, U>(x, y); } }; // not a construct signature, function called new function foo1b(x: B<string, number>); function foo1b(x: B<string, number>); // error function foo1b(x: any)
function foo1c(x: C<string, number>); function foo1c(x: C<string, number>); // error function foo1c(x: any) { } function foo2(x: I<string, number>); function foo2(x: I<string, number>); // error function foo2(x: any) { } function foo3(x: typeof a); function foo3(x: typeof a); // error function foo3(x: any) { } function foo4(x: typeof b); function foo4(x: typeof b); // error function foo4(x: any) { } function foo8(x: B<string, number>); function foo8(x: I<string, number>); // BUG 832086 function foo8(x: any) { } function foo9(x: B<string, number>); function foo9(x: C<string, number>); // error, differ only by return type function foo9(x: any) { } function foo10(x: B<string, number>); function foo10(x: typeof a); // BUG 832086 function foo10(x: any) { } function foo11(x: B<string, number>); function foo11(x: typeof b); // ok function foo11(x: any) { } function foo12(x: I<string, number>); function foo12(x: C<string, number>); // ok function foo12(x: any) { } function foo12b(x: I2); function foo12b(x: C<string, number>); // BUG 832086 function foo12b(x: any) { } function foo13(x: I<string, number>); function foo13(x: typeof a); // BUG 832086 function foo13(x: any) { } function foo14(x: I<string, number>); function foo14(x: typeof b); // ok function foo14(x: any) { }
{ }
identifier_body
objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.ts
// Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those // parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required, // optional or rest) and types, and identical return types. class B<T, U> { constructor(x: T, y: U) { return null; } } class C<T, U> { constructor(x: T, y?: U) { return null; } } interface I<T, U> { new(x: T, y?: U): B<T, U>; } interface I2 { new<T, U>(x: T, y: U): C<T, U>; } var a: { new <T, U>(x: T, y?: U): B<T, U> }; var b = { new<T, U>(x: T, y: U) { return new C<T, U>(x, y); } }; // not a construct signature, function called new function foo1b(x: B<string, number>); function foo1b(x: B<string, number>); // error function foo1b(x: any) { } function foo1c(x: C<string, number>); function foo1c(x: C<string, number>); // error function foo1c(x: any) { } function foo2(x: I<string, number>); function foo2(x: I<string, number>); // error function foo2(x: any) { } function foo3(x: typeof a); function foo3(x: typeof a); // error
function foo3(x: any) { } function foo4(x: typeof b); function foo4(x: typeof b); // error function foo4(x: any) { } function foo8(x: B<string, number>); function foo8(x: I<string, number>); // BUG 832086 function foo8(x: any) { } function foo9(x: B<string, number>); function foo9(x: C<string, number>); // error, differ only by return type function foo9(x: any) { } function foo10(x: B<string, number>); function foo10(x: typeof a); // BUG 832086 function foo10(x: any) { } function foo11(x: B<string, number>); function foo11(x: typeof b); // ok function foo11(x: any) { } function foo12(x: I<string, number>); function foo12(x: C<string, number>); // ok function foo12(x: any) { } function foo12b(x: I2); function foo12b(x: C<string, number>); // BUG 832086 function foo12b(x: any) { } function foo13(x: I<string, number>); function foo13(x: typeof a); // BUG 832086 function foo13(x: any) { } function foo14(x: I<string, number>); function foo14(x: typeof b); // ok function foo14(x: any) { }
random_line_split
objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.ts
// Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those // parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required, // optional or rest) and types, and identical return types. class B<T, U> { constructor(x: T, y: U) { return null; } } class C<T, U> {
(x: T, y?: U) { return null; } } interface I<T, U> { new(x: T, y?: U): B<T, U>; } interface I2 { new<T, U>(x: T, y: U): C<T, U>; } var a: { new <T, U>(x: T, y?: U): B<T, U> }; var b = { new<T, U>(x: T, y: U) { return new C<T, U>(x, y); } }; // not a construct signature, function called new function foo1b(x: B<string, number>); function foo1b(x: B<string, number>); // error function foo1b(x: any) { } function foo1c(x: C<string, number>); function foo1c(x: C<string, number>); // error function foo1c(x: any) { } function foo2(x: I<string, number>); function foo2(x: I<string, number>); // error function foo2(x: any) { } function foo3(x: typeof a); function foo3(x: typeof a); // error function foo3(x: any) { } function foo4(x: typeof b); function foo4(x: typeof b); // error function foo4(x: any) { } function foo8(x: B<string, number>); function foo8(x: I<string, number>); // BUG 832086 function foo8(x: any) { } function foo9(x: B<string, number>); function foo9(x: C<string, number>); // error, differ only by return type function foo9(x: any) { } function foo10(x: B<string, number>); function foo10(x: typeof a); // BUG 832086 function foo10(x: any) { } function foo11(x: B<string, number>); function foo11(x: typeof b); // ok function foo11(x: any) { } function foo12(x: I<string, number>); function foo12(x: C<string, number>); // ok function foo12(x: any) { } function foo12b(x: I2); function foo12b(x: C<string, number>); // BUG 832086 function foo12b(x: any) { } function foo13(x: I<string, number>); function foo13(x: typeof a); // BUG 832086 function foo13(x: any) { } function foo14(x: I<string, number>); function foo14(x: typeof b); // ok function foo14(x: any) { }
constructor
identifier_name
extrapolatable.rs
// // This file is part of zero_sum. // // zero_sum 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. // // zero_sum 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 zero_sum. If not, see <http://www.gnu.org/licenses/>. // // Copyright 2016-2017 Chris Foster // use ply::Ply; /// Provides the possible plies from a given state. pub trait Extrapolatable<P> where P: Ply { /// Returns a list of plies that should be considered from the current state. The search
fn extrapolate(&self) -> Vec<P>; }
/// system does not assume that all plies returned are correct.
random_line_split
mobile.py
#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, CommAdminView class MobilePlugin(BaseAdminPlugin): def _test_mobile(self):
def init_request(self, *args, **kwargs): return self._test_mobile() def get_context(self, context): #context['base_template'] = 'nadmin/base_mobile.html' context['is_mob'] = True return context # Media # def get_media(self, media): # return media + self.vendor('nadmin.mobile.css', ) def block_extrahead(self, context, nodes): nodes.append('<script>window.__admin_ismobile__ = true;</script>') site.register_plugin(MobilePlugin, CommAdminView)
try: return self.request.META['HTTP_USER_AGENT'].find('Android') >= 0 or \ self.request.META['HTTP_USER_AGENT'].find('iPhone') >= 0 except Exception: return False
identifier_body
mobile.py
#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, CommAdminView class MobilePlugin(BaseAdminPlugin): def _test_mobile(self): try: return self.request.META['HTTP_USER_AGENT'].find('Android') >= 0 or \
def init_request(self, *args, **kwargs): return self._test_mobile() def get_context(self, context): #context['base_template'] = 'nadmin/base_mobile.html' context['is_mob'] = True return context # Media # def get_media(self, media): # return media + self.vendor('nadmin.mobile.css', ) def block_extrahead(self, context, nodes): nodes.append('<script>window.__admin_ismobile__ = true;</script>') site.register_plugin(MobilePlugin, CommAdminView)
self.request.META['HTTP_USER_AGENT'].find('iPhone') >= 0 except Exception: return False
random_line_split
mobile.py
#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, CommAdminView class
(BaseAdminPlugin): def _test_mobile(self): try: return self.request.META['HTTP_USER_AGENT'].find('Android') >= 0 or \ self.request.META['HTTP_USER_AGENT'].find('iPhone') >= 0 except Exception: return False def init_request(self, *args, **kwargs): return self._test_mobile() def get_context(self, context): #context['base_template'] = 'nadmin/base_mobile.html' context['is_mob'] = True return context # Media # def get_media(self, media): # return media + self.vendor('nadmin.mobile.css', ) def block_extrahead(self, context, nodes): nodes.append('<script>window.__admin_ismobile__ = true;</script>') site.register_plugin(MobilePlugin, CommAdminView)
MobilePlugin
identifier_name
redis-to-sqs.rs
#[tokio::main] async fn
() -> Result<(), anyhow::Error> { use redis::Commands as _; use rusoto_sqs::Sqs as _; let config = encoder::load_config()?; let redis_client = redis::Client::open(config.redis.url)?; let mut conn = redis_client.get_connection()?; let sqs_client = rusoto_sqs::SqsClient::new(Default::default()); loop { let job: Vec<String> = conn.blpop(&["jobs", "0"], 5)?; if job.is_empty() { break; } let fname = job.into_iter().nth(1).unwrap(); println!("Enqueue {}", fname); sqs_client .send_message(rusoto_sqs::SendMessageRequest { queue_url: config.sqs.queue_url.clone(), message_body: fname, ..Default::default() }) .await?; } Ok(()) }
main
identifier_name
redis-to-sqs.rs
#[tokio::main] async fn main() -> Result<(), anyhow::Error> { use redis::Commands as _; use rusoto_sqs::Sqs as _; let config = encoder::load_config()?; let redis_client = redis::Client::open(config.redis.url)?; let mut conn = redis_client.get_connection()?; let sqs_client = rusoto_sqs::SqsClient::new(Default::default()); loop { let job: Vec<String> = conn.blpop(&["jobs", "0"], 5)?; if job.is_empty() { break; } let fname = job.into_iter().nth(1).unwrap(); println!("Enqueue {}", fname);
.send_message(rusoto_sqs::SendMessageRequest { queue_url: config.sqs.queue_url.clone(), message_body: fname, ..Default::default() }) .await?; } Ok(()) }
sqs_client
random_line_split
redis-to-sqs.rs
#[tokio::main] async fn main() -> Result<(), anyhow::Error>
{ use redis::Commands as _; use rusoto_sqs::Sqs as _; let config = encoder::load_config()?; let redis_client = redis::Client::open(config.redis.url)?; let mut conn = redis_client.get_connection()?; let sqs_client = rusoto_sqs::SqsClient::new(Default::default()); loop { let job: Vec<String> = conn.blpop(&["jobs", "0"], 5)?; if job.is_empty() { break; } let fname = job.into_iter().nth(1).unwrap(); println!("Enqueue {}", fname); sqs_client .send_message(rusoto_sqs::SendMessageRequest { queue_url: config.sqs.queue_url.clone(), message_body: fname, ..Default::default() }) .await?; } Ok(()) }
identifier_body
redis-to-sqs.rs
#[tokio::main] async fn main() -> Result<(), anyhow::Error> { use redis::Commands as _; use rusoto_sqs::Sqs as _; let config = encoder::load_config()?; let redis_client = redis::Client::open(config.redis.url)?; let mut conn = redis_client.get_connection()?; let sqs_client = rusoto_sqs::SqsClient::new(Default::default()); loop { let job: Vec<String> = conn.blpop(&["jobs", "0"], 5)?; if job.is_empty()
let fname = job.into_iter().nth(1).unwrap(); println!("Enqueue {}", fname); sqs_client .send_message(rusoto_sqs::SendMessageRequest { queue_url: config.sqs.queue_url.clone(), message_body: fname, ..Default::default() }) .await?; } Ok(()) }
{ break; }
conditional_block
lens_flare.py
# OpenShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor 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. # # OpenShot Video Editor 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 OpenShot Video Editor. If not, see <http://www.gnu.org/licenses/>. # Import Blender's python API. This only works when the script is being # run from the context of Blender. Blender contains it's own version of Python # with this library pre-installed. import bpy # Debug Info: # ./blender -b test.blend -P demo.py # -b = background mode # -P = run a Python script within the context of the project file # Init all of the variables needed by this script. Because Blender executes # this script, OpenShot will inject a dictionary of the required parameters # before this script is executed. params = { 'title' : 'Oh Yeah! OpenShot!', 'extrude' : 0.1, 'bevel_depth' : 0.02, 'spacemode' : 'CENTER', 'text_size' : 1.5, 'width' : 1.0, 'fontname' : 'Bfont', 'color' : [0.8,0.8,0.8], 'alpha' : 1.0, 'alpha_mode' : 'TRANSPARENT', 'output_path' : '/tmp/', 'fps' : 24, 'quality' : 90, 'file_format' : 'PNG', 'color_mode' : 'RGBA', 'horizon_color' : [0.57, 0.57, 0.57], 'resolution_x' : 1920, 'resolution_y' : 1080, 'resolution_percentage' : 100, 'start_frame' : 20, 'end_frame' : 25, 'animation' : True, } #INJECT_PARAMS_HERE # The remainder of this script will modify the current Blender .blend project # file, and adjust the settings. The .blend file is specified in the XML file # that defines this template in OpenShot. #---------------------------------------------------------------------------- # Modify the Location of the Wand sphere_object = bpy.data.objects["Sphere"] sphere_object.location = [params["start_x"], params["start_y"], params["start_z"]] # Modify the Start and End keyframes bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[0].co = (1.0, params["start_x"]) bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[0].handle_left.y = params["start_x"] bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[0].handle_right.y = params["start_x"] bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[0].co = (1.0, params["start_y"]) bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[0].handle_left.y = params["start_y"] bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[0].handle_right.y = params["start_y"] bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[0].co = (1.0, params["start_z"]) bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[0].handle_left.y = params["start_z"] bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[0].handle_right.y = params["start_z"] ################# bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[1].co = (300.0, params["end_x"]) bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[1].handle_left.y = params["end_x"] bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[1].handle_right.y = params["end_x"] bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[1].co = (300.0, params["end_y"]) bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[1].handle_left.y = params["end_y"] bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[1].handle_right.y = params["end_y"] bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[1].co = (300.0, params["end_z"]) bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[1].handle_left.y = params["end_z"] bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[1].handle_right.y = params["end_z"] # Modfiy the Material Keyframe (i.e. the keyframed halo size setting) bpy.data.actions["Material.001Action"].fcurves[0].keyframe_points[0].co = (1.0, params["start_halo_size"]) bpy.data.actions["Material.001Action"].fcurves[0].keyframe_points[1].co = (300.00, params["end_halo_size"]) # Change the material settings (color, alpha, etc...) material_object = bpy.data.materials["Material.001"] material_object.diffuse_color = params["diffuse_color"] material_object.specular_color = params["specular_color"] material_object.mirror_color = params["mirror_color"] material_object.alpha = params["alpha"] # Change Composite Node settings sun_glare_node = bpy.data.scenes[0].node_tree.nodes["Glare"] sun_glare_node.color_modulation = params["sun_glare_color"] sun_glare_node.glare_type = params["sun_glare_type"] sun_glare_node.streaks = params["sun_streaks"] sun_glare_node.angle_offset = params["sun_angle_offset"] spots_glare_node = bpy.data.scenes[0].node_tree.nodes["Glare.000"] spots_glare_node.color_modulation = params["spots_glare_color"] # Change Halo settings material_object.halo.size = params["start_halo_size"] material_object.halo.hardness = params["halo_hardness"] if params["halo_use_lines"] == "Yes": material_object.halo.use_lines = True else: material_object.halo.use_lines = False material_object.halo.line_count = params["halo_line_count"] if params["halo_use_ring"] == "Yes": material_object.halo.use_ring = True else: material_object.halo.use_ring = False material_object.halo.ring_count = params["halo_ring_count"] if params["halo_use_star"] == "Yes":
else: material_object.halo.use_star = False material_object.halo.star_tip_count = params["halo_star_tip_count"] # Set the render options. It is important that these are set # to the same values as the current OpenShot project. These # params are automatically set by OpenShot bpy.context.scene.render.filepath = params["output_path"] bpy.context.scene.render.fps = params["fps"] #bpy.context.scene.render.quality = params["quality"] try: bpy.context.scene.render.file_format = params["file_format"] bpy.context.scene.render.color_mode = params["color_mode"] except: bpy.context.scene.render.image_settings.file_format = params["file_format"] bpy.context.scene.render.image_settings.color_mode = params["color_mode"] # Set background transparency (SKY or TRANSPARENT) try: bpy.context.scene.render.alpha_mode = params["alpha_mode"] except: pass bpy.context.scene.render.resolution_x = params["resolution_x"] bpy.context.scene.render.resolution_y = params["resolution_y"] bpy.context.scene.render.resolution_percentage = params["resolution_percentage"] bpy.context.scene.frame_start = params["start_frame"] bpy.context.scene.frame_end = params["end_frame"] # Animation Speed (use Blender's time remapping to slow or speed up animation) animation_speed = int(params["animation_speed"]) # time remapping multiplier new_length = int(params["end_frame"]) * animation_speed # new length (in frames) bpy.context.scene.frame_end = new_length bpy.context.scene.render.frame_map_old = 1 bpy.context.scene.render.frame_map_new = animation_speed if params["start_frame"] == params["end_frame"]: bpy.context.scene.frame_start = params["end_frame"] bpy.context.scene.frame_end = params["end_frame"] # Render the current animation to the params["output_path"] folder bpy.ops.render.render(animation=params["animation"])
material_object.halo.use_star = True
conditional_block
lens_flare.py
# OpenShot Video Editor is a program that creates, modifies, and edits video files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor 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. # # OpenShot Video Editor 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 OpenShot Video Editor. If not, see <http://www.gnu.org/licenses/>. # Import Blender's python API. This only works when the script is being # run from the context of Blender. Blender contains it's own version of Python # with this library pre-installed. import bpy # Debug Info: # ./blender -b test.blend -P demo.py # -b = background mode # -P = run a Python script within the context of the project file # Init all of the variables needed by this script. Because Blender executes # this script, OpenShot will inject a dictionary of the required parameters # before this script is executed. params = { 'title' : 'Oh Yeah! OpenShot!', 'extrude' : 0.1, 'bevel_depth' : 0.02, 'spacemode' : 'CENTER', 'text_size' : 1.5, 'width' : 1.0, 'fontname' : 'Bfont', 'color' : [0.8,0.8,0.8], 'alpha' : 1.0, 'alpha_mode' : 'TRANSPARENT', 'output_path' : '/tmp/', 'fps' : 24, 'quality' : 90, 'file_format' : 'PNG', 'color_mode' : 'RGBA', 'horizon_color' : [0.57, 0.57, 0.57], 'resolution_x' : 1920, 'resolution_y' : 1080, 'resolution_percentage' : 100, 'start_frame' : 20, 'end_frame' : 25, 'animation' : True, } #INJECT_PARAMS_HERE # The remainder of this script will modify the current Blender .blend project # file, and adjust the settings. The .blend file is specified in the XML file # that defines this template in OpenShot. #---------------------------------------------------------------------------- # Modify the Location of the Wand sphere_object = bpy.data.objects["Sphere"] sphere_object.location = [params["start_x"], params["start_y"], params["start_z"]] # Modify the Start and End keyframes bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[0].co = (1.0, params["start_x"]) bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[0].handle_left.y = params["start_x"] bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[0].handle_right.y = params["start_x"] bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[0].co = (1.0, params["start_y"]) bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[0].handle_left.y = params["start_y"] bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[0].handle_right.y = params["start_y"] bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[0].co = (1.0, params["start_z"]) bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[0].handle_left.y = params["start_z"] bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[0].handle_right.y = params["start_z"] ################# bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[1].co = (300.0, params["end_x"]) bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[1].handle_left.y = params["end_x"] bpy.data.actions["SphereAction"].fcurves[0].keyframe_points[1].handle_right.y = params["end_x"] bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[1].co = (300.0, params["end_y"]) bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[1].handle_left.y = params["end_y"] bpy.data.actions["SphereAction"].fcurves[1].keyframe_points[1].handle_right.y = params["end_y"] bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[1].co = (300.0, params["end_z"]) bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[1].handle_left.y = params["end_z"] bpy.data.actions["SphereAction"].fcurves[2].keyframe_points[1].handle_right.y = params["end_z"] # Modfiy the Material Keyframe (i.e. the keyframed halo size setting) bpy.data.actions["Material.001Action"].fcurves[0].keyframe_points[0].co = (1.0, params["start_halo_size"]) bpy.data.actions["Material.001Action"].fcurves[0].keyframe_points[1].co = (300.00, params["end_halo_size"]) # Change the material settings (color, alpha, etc...) material_object = bpy.data.materials["Material.001"] material_object.diffuse_color = params["diffuse_color"] material_object.specular_color = params["specular_color"] material_object.mirror_color = params["mirror_color"] material_object.alpha = params["alpha"] # Change Composite Node settings sun_glare_node = bpy.data.scenes[0].node_tree.nodes["Glare"] sun_glare_node.color_modulation = params["sun_glare_color"] sun_glare_node.glare_type = params["sun_glare_type"] sun_glare_node.streaks = params["sun_streaks"] sun_glare_node.angle_offset = params["sun_angle_offset"] spots_glare_node = bpy.data.scenes[0].node_tree.nodes["Glare.000"] spots_glare_node.color_modulation = params["spots_glare_color"] # Change Halo settings material_object.halo.size = params["start_halo_size"] material_object.halo.hardness = params["halo_hardness"] if params["halo_use_lines"] == "Yes": material_object.halo.use_lines = True else: material_object.halo.use_lines = False material_object.halo.line_count = params["halo_line_count"] if params["halo_use_ring"] == "Yes": material_object.halo.use_ring = True else: material_object.halo.use_ring = False material_object.halo.ring_count = params["halo_ring_count"] if params["halo_use_star"] == "Yes": material_object.halo.use_star = True else: material_object.halo.use_star = False material_object.halo.star_tip_count = params["halo_star_tip_count"] # Set the render options. It is important that these are set # to the same values as the current OpenShot project. These # params are automatically set by OpenShot bpy.context.scene.render.filepath = params["output_path"] bpy.context.scene.render.fps = params["fps"] #bpy.context.scene.render.quality = params["quality"] try: bpy.context.scene.render.file_format = params["file_format"] bpy.context.scene.render.color_mode = params["color_mode"] except: bpy.context.scene.render.image_settings.file_format = params["file_format"] bpy.context.scene.render.image_settings.color_mode = params["color_mode"] # Set background transparency (SKY or TRANSPARENT) try: bpy.context.scene.render.alpha_mode = params["alpha_mode"] except: pass bpy.context.scene.render.resolution_x = params["resolution_x"] bpy.context.scene.render.resolution_y = params["resolution_y"] bpy.context.scene.render.resolution_percentage = params["resolution_percentage"] bpy.context.scene.frame_start = params["start_frame"] bpy.context.scene.frame_end = params["end_frame"] # Animation Speed (use Blender's time remapping to slow or speed up animation) animation_speed = int(params["animation_speed"]) # time remapping multiplier new_length = int(params["end_frame"]) * animation_speed # new length (in frames) bpy.context.scene.frame_end = new_length bpy.context.scene.render.frame_map_old = 1 bpy.context.scene.render.frame_map_new = animation_speed if params["start_frame"] == params["end_frame"]: bpy.context.scene.frame_start = params["end_frame"] bpy.context.scene.frame_end = params["end_frame"]
# Render the current animation to the params["output_path"] folder bpy.ops.render.render(animation=params["animation"])
random_line_split
weight.rs
use super::Scorer; use crate::core::SegmentReader; use crate::query::Explanation; use crate::{DocId, Score, TERMINATED}; /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. pub(crate) fn for_each_scorer<TScorer: Scorer + ?Sized>( scorer: &mut TScorer, callback: &mut dyn FnMut(DocId, Score), ) { let mut doc = scorer.doc(); while doc != TERMINATED { callback(doc, scorer.score()); doc = scorer.advance(); } } /// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector. /// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement /// important optimization (e.g. BlockWAND for union). pub(crate) fn for_each_pruning_scorer<TScorer: Scorer + ?Sized>( scorer: &mut TScorer, mut threshold: Score, callback: &mut dyn FnMut(DocId, Score) -> Score, ) { let mut doc = scorer.doc(); while doc != TERMINATED { let score = scorer.score(); if score > threshold { threshold = callback(doc, score); } doc = scorer.advance(); } } /// A Weight is the specialization of a Query /// for a given set of segments. /// /// See [`Query`](./trait.Query.html). pub trait Weight: Send + Sync + 'static { /// Returns the scorer for the given segment. /// /// `boost` is a multiplier to apply to the score. /// /// See [`Query`](./trait.Query.html). fn scorer(&self, reader: &SegmentReader, boost: Score) -> crate::Result<Box<dyn Scorer>>; /// Returns an `Explanation` for the given document. fn explain(&self, reader: &SegmentReader, doc: DocId) -> crate::Result<Explanation>; /// Returns the number documents within the given `SegmentReader`. fn count(&self, reader: &SegmentReader) -> crate::Result<u32> { let mut scorer = self.scorer(reader, 1.0)?; if let Some(alive_bitset) = reader.alive_bitset() { Ok(scorer.count(alive_bitset)) } else
} /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. fn for_each( &self, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score), ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_scorer(scorer.as_mut(), callback); Ok(()) } /// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector. /// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement /// important optimization (e.g. BlockWAND for union). fn for_each_pruning( &self, threshold: Score, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score) -> Score, ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_pruning_scorer(scorer.as_mut(), threshold, callback); Ok(()) } }
{ Ok(scorer.count_including_deleted()) }
conditional_block
weight.rs
use super::Scorer; use crate::core::SegmentReader; use crate::query::Explanation; use crate::{DocId, Score, TERMINATED}; /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. pub(crate) fn for_each_scorer<TScorer: Scorer + ?Sized>( scorer: &mut TScorer, callback: &mut dyn FnMut(DocId, Score), )
/// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector. /// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement /// important optimization (e.g. BlockWAND for union). pub(crate) fn for_each_pruning_scorer<TScorer: Scorer + ?Sized>( scorer: &mut TScorer, mut threshold: Score, callback: &mut dyn FnMut(DocId, Score) -> Score, ) { let mut doc = scorer.doc(); while doc != TERMINATED { let score = scorer.score(); if score > threshold { threshold = callback(doc, score); } doc = scorer.advance(); } } /// A Weight is the specialization of a Query /// for a given set of segments. /// /// See [`Query`](./trait.Query.html). pub trait Weight: Send + Sync + 'static { /// Returns the scorer for the given segment. /// /// `boost` is a multiplier to apply to the score. /// /// See [`Query`](./trait.Query.html). fn scorer(&self, reader: &SegmentReader, boost: Score) -> crate::Result<Box<dyn Scorer>>; /// Returns an `Explanation` for the given document. fn explain(&self, reader: &SegmentReader, doc: DocId) -> crate::Result<Explanation>; /// Returns the number documents within the given `SegmentReader`. fn count(&self, reader: &SegmentReader) -> crate::Result<u32> { let mut scorer = self.scorer(reader, 1.0)?; if let Some(alive_bitset) = reader.alive_bitset() { Ok(scorer.count(alive_bitset)) } else { Ok(scorer.count_including_deleted()) } } /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. fn for_each( &self, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score), ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_scorer(scorer.as_mut(), callback); Ok(()) } /// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector. /// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement /// important optimization (e.g. BlockWAND for union). fn for_each_pruning( &self, threshold: Score, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score) -> Score, ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_pruning_scorer(scorer.as_mut(), threshold, callback); Ok(()) } }
{ let mut doc = scorer.doc(); while doc != TERMINATED { callback(doc, scorer.score()); doc = scorer.advance(); } }
identifier_body
weight.rs
use super::Scorer; use crate::core::SegmentReader; use crate::query::Explanation; use crate::{DocId, Score, TERMINATED}; /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. pub(crate) fn for_each_scorer<TScorer: Scorer + ?Sized>( scorer: &mut TScorer, callback: &mut dyn FnMut(DocId, Score), ) { let mut doc = scorer.doc(); while doc != TERMINATED { callback(doc, scorer.score()); doc = scorer.advance(); } } /// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector. /// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement /// important optimization (e.g. BlockWAND for union). pub(crate) fn for_each_pruning_scorer<TScorer: Scorer + ?Sized>( scorer: &mut TScorer, mut threshold: Score, callback: &mut dyn FnMut(DocId, Score) -> Score, ) { let mut doc = scorer.doc(); while doc != TERMINATED { let score = scorer.score(); if score > threshold { threshold = callback(doc, score); } doc = scorer.advance(); } } /// A Weight is the specialization of a Query /// for a given set of segments. /// /// See [`Query`](./trait.Query.html). pub trait Weight: Send + Sync + 'static { /// Returns the scorer for the given segment. /// /// `boost` is a multiplier to apply to the score. /// /// See [`Query`](./trait.Query.html). fn scorer(&self, reader: &SegmentReader, boost: Score) -> crate::Result<Box<dyn Scorer>>; /// Returns an `Explanation` for the given document. fn explain(&self, reader: &SegmentReader, doc: DocId) -> crate::Result<Explanation>; /// Returns the number documents within the given `SegmentReader`. fn count(&self, reader: &SegmentReader) -> crate::Result<u32> { let mut scorer = self.scorer(reader, 1.0)?; if let Some(alive_bitset) = reader.alive_bitset() { Ok(scorer.count(alive_bitset)) } else { Ok(scorer.count_including_deleted()) } } /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. fn
( &self, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score), ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_scorer(scorer.as_mut(), callback); Ok(()) } /// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector. /// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement /// important optimization (e.g. BlockWAND for union). fn for_each_pruning( &self, threshold: Score, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score) -> Score, ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_pruning_scorer(scorer.as_mut(), threshold, callback); Ok(()) } }
for_each
identifier_name
weight.rs
use super::Scorer; use crate::core::SegmentReader; use crate::query::Explanation; use crate::{DocId, Score, TERMINATED}; /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. pub(crate) fn for_each_scorer<TScorer: Scorer + ?Sized>( scorer: &mut TScorer, callback: &mut dyn FnMut(DocId, Score), ) { let mut doc = scorer.doc(); while doc != TERMINATED { callback(doc, scorer.score()); doc = scorer.advance(); } } /// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector. /// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement /// important optimization (e.g. BlockWAND for union). pub(crate) fn for_each_pruning_scorer<TScorer: Scorer + ?Sized>( scorer: &mut TScorer, mut threshold: Score, callback: &mut dyn FnMut(DocId, Score) -> Score, ) { let mut doc = scorer.doc(); while doc != TERMINATED { let score = scorer.score(); if score > threshold { threshold = callback(doc, score); } doc = scorer.advance(); } } /// A Weight is the specialization of a Query /// for a given set of segments. /// /// See [`Query`](./trait.Query.html). pub trait Weight: Send + Sync + 'static { /// Returns the scorer for the given segment. /// /// `boost` is a multiplier to apply to the score. /// /// See [`Query`](./trait.Query.html). fn scorer(&self, reader: &SegmentReader, boost: Score) -> crate::Result<Box<dyn Scorer>>; /// Returns an `Explanation` for the given document. fn explain(&self, reader: &SegmentReader, doc: DocId) -> crate::Result<Explanation>; /// Returns the number documents within the given `SegmentReader`. fn count(&self, reader: &SegmentReader) -> crate::Result<u32> { let mut scorer = self.scorer(reader, 1.0)?; if let Some(alive_bitset) = reader.alive_bitset() { Ok(scorer.count(alive_bitset)) } else { Ok(scorer.count_including_deleted()) } } /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. fn for_each( &self, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score), ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_scorer(scorer.as_mut(), callback); Ok(()) } /// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector.
/// important optimization (e.g. BlockWAND for union). fn for_each_pruning( &self, threshold: Score, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score) -> Score, ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_pruning_scorer(scorer.as_mut(), threshold, callback); Ok(()) } }
/// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement
random_line_split
operations.py
import re from decimal import Decimal from django.conf import settings from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.postgresql_psycopg2.base import DatabaseOperations from django.db.utils import DatabaseError from django.utils import six #### Classes used in constructing PostGIS spatial SQL #### class PostGISOperator(SpatialOperation): "For PostGIS operators (e.g. `&&`, `~`)." def __init__(self, operator): super(PostGISOperator, self).__init__(operator=operator) class PostGISFunction(SpatialFunction): "For PostGIS function calls (e.g., `ST_Contains(table, geom)`)." def __init__(self, prefix, function, **kwargs): super(PostGISFunction, self).__init__(prefix + function, **kwargs) class PostGISFunctionParam(PostGISFunction): "For PostGIS functions that take another parameter (e.g. DWithin, Relate)." sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)' class PostGISDistance(PostGISFunction): "For PostGIS distance operations." dist_func = 'Distance' sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s' def __init__(self, prefix, operator): super(PostGISDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSpheroidDistance(PostGISFunction): "For PostGIS spherical distance operations (using the spheroid)." dist_func = 'distance_spheroid' sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s) %(operator)s %%s' def __init__(self, prefix, operator): # An extra parameter in `end_subst` is needed for the spheroid string. super(PostGISSpheroidDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSphereDistance(PostGISDistance): "For PostGIS spherical distance operations." dist_func = 'distance_sphere' class PostGISRelate(PostGISFunctionParam): "For PostGIS Relate(<geom>, <pattern>) calls." pattern_regex = re.compile(r'^[012TF\*]{9}$') def __init__(self, prefix, pattern): if not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) super(PostGISRelate, self).__init__(prefix, 'Relate') class PostGISOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = 'django.contrib.gis.db.models.sql.compiler' name = 'postgis' postgis = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)') valid_aggregates = dict([(k, None) for k in ('Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union')]) Adapter = PostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. def __init__(self, connection): super(PostGISOperations, self).__init__(connection) # Trying to get the PostGIS version because the function # signatures will depend on the version used. The cost # here is a database query to determine the version, which # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple # comprising user-supplied values for the major, minor, and # subminor revision of PostGIS. try: if hasattr(settings, 'POSTGIS_VERSION'): vtup = settings.POSTGIS_VERSION if len(vtup) == 3: # The user-supplied PostGIS version. version = vtup else: # This was the old documented way, but it's stupid to # include the string. version = vtup[1:4] else: vtup = self.postgis_version_tuple() version = vtup[1:] # Getting the prefix -- even though we don't officially support # PostGIS 1.2 anymore, keeping it anyway in case a prefix change # for something else is necessary. if version >= (1, 2, 2): prefix = 'ST_' else: prefix = '' self.geom_func_prefix = prefix self.spatial_version = version except DatabaseError: raise ImproperlyConfigured( 'Cannot determine PostGIS version for database "%s". ' 'GeoDjango requires at least PostGIS version 1.3. ' 'Was the database created from a spatial database ' 'template?' % self.connection.settings_dict['NAME'] ) # TODO: Raise helpful exceptions as they become known. # PostGIS-specific operators. The commented descriptions of these # operators come from Section 7.6 of the PostGIS 1.4 documentation. self.geometry_operators = { # The "&<" operator returns true if A's bounding box overlaps or # is to the left of B's bounding box. 'overlaps_left' : PostGISOperator('&<'), # The "&>" operator returns true if A's bounding box overlaps or # is to the right of B's bounding box. 'overlaps_right' : PostGISOperator('&>'), # The "<<" operator returns true if A's bounding box is strictly # to the left of B's bounding box. 'left' : PostGISOperator('<<'), # The ">>" operator returns true if A's bounding box is strictly # to the right of B's bounding box. 'right' : PostGISOperator('>>'), # The "&<|" operator returns true if A's bounding box overlaps or # is below B's bounding box. 'overlaps_below' : PostGISOperator('&<|'), # The "|&>" operator returns true if A's bounding box overlaps or # is above B's bounding box. 'overlaps_above' : PostGISOperator('|&>'), # The "<<|" operator returns true if A's bounding box is strictly # below B's bounding box. 'strictly_below' : PostGISOperator('<<|'), # The "|>>" operator returns true if A's bounding box is strictly # above B's bounding box. 'strictly_above' : PostGISOperator('|>>'), # The "~=" operator is the "same as" operator. It tests actual # geometric equality of two features. So if A and B are the same feature, # vertex-by-vertex, the operator returns true. 'same_as' : PostGISOperator('~='), 'exact' : PostGISOperator('~='), # The "@" operator returns true if A's bounding box is completely contained # by B's bounding box. 'contained' : PostGISOperator('@'), # The "~" operator returns true if A's bounding box completely contains # by B's bounding box. 'bbcontains' : PostGISOperator('~'), # The "&&" operator returns true if A's bounding box overlaps # B's bounding box. 'bboverlaps' : PostGISOperator('&&'), } self.geometry_functions = { 'equals' : PostGISFunction(prefix, 'Equals'), 'disjoint' : PostGISFunction(prefix, 'Disjoint'), 'touches' : PostGISFunction(prefix, 'Touches'), 'crosses' : PostGISFunction(prefix, 'Crosses'), 'within' : PostGISFunction(prefix, 'Within'), 'overlaps' : PostGISFunction(prefix, 'Overlaps'), 'contains' : PostGISFunction(prefix, 'Contains'), 'intersects' : PostGISFunction(prefix, 'Intersects'), 'relate' : (PostGISRelate, six.string_types), 'coveredby' : PostGISFunction(prefix, 'CoveredBy'), 'covers' : PostGISFunction(prefix, 'Covers'), } # Valid distance types and substitutions dtypes = (Decimal, Distance, float) + six.integer_types def get_dist_ops(operator): "Returns operations for both regular and spherical distances." return {'cartesian' : PostGISDistance(prefix, operator), 'sphere' : PostGISSphereDistance(prefix, operator), 'spheroid' : PostGISSpheroidDistance(prefix, operator), } self.distance_functions = { 'distance_gt' : (get_dist_ops('>'), dtypes), 'distance_gte' : (get_dist_ops('>='), dtypes), 'distance_lt' : (get_dist_ops('<'), dtypes), 'distance_lte' : (get_dist_ops('<='), dtypes), 'dwithin' : (PostGISFunctionParam(prefix, 'DWithin'), dtypes) } # Adding the distance functions to the geometries lookup. self.geometry_functions.update(self.distance_functions) # Only PostGIS versions 1.3.4+ have GeoJSON serialization support. if version < (1, 3, 4): GEOJSON = False else: GEOJSON = prefix + 'AsGeoJson' # ST_ContainsProperly ST_MakeLine, and ST_GeoHash added in 1.4. if version >= (1, 4, 0): GEOHASH = 'ST_GeoHash' BOUNDINGCIRCLE = 'ST_MinimumBoundingCircle' self.geometry_functions['contains_properly'] = PostGISFunction(prefix, 'ContainsProperly') else: GEOHASH, BOUNDINGCIRCLE = False, False # Geography type support added in 1.5. if version >= (1, 5, 0): self.geography = True # Only a subset of the operators and functions are available # for the geography type. self.geography_functions = self.distance_functions.copy() self.geography_functions.update({ 'coveredby': self.geometry_functions['coveredby'], 'covers': self.geometry_functions['covers'], 'intersects': self.geometry_functions['intersects'], }) self.geography_operators = { 'bboverlaps': PostGISOperator('&&'), } # Native geometry type support added in PostGIS 2.0. if version >= (2, 0, 0): self.geometry = True # Creating a dictionary lookup of all GIS terms for PostGIS. self.gis_terms = set(['isnull']) self.gis_terms.update(self.geometry_operators) self.gis_terms.update(self.geometry_functions) self.area = prefix + 'Area' self.bounding_circle = BOUNDINGCIRCLE self.centroid = prefix + 'Centroid' self.collect = prefix + 'Collect' self.difference = prefix + 'Difference' self.distance = prefix + 'Distance' self.distance_sphere = prefix + 'distance_sphere' self.distance_spheroid = prefix + 'distance_spheroid' self.envelope = prefix + 'Envelope' self.extent = prefix + 'Extent' self.force_rhr = prefix + 'ForceRHR' self.geohash = GEOHASH self.geojson = GEOJSON self.gml = prefix + 'AsGML' self.intersection = prefix + 'Intersection' self.kml = prefix + 'AsKML' self.length = prefix + 'Length' self.length_spheroid = prefix + 'length_spheroid' self.makeline = prefix + 'MakeLine' self.mem_size = prefix + 'mem_size' self.num_geom = prefix + 'NumGeometries' self.num_points = prefix + 'npoints' self.perimeter = prefix + 'Perimeter' self.point_on_surface = prefix + 'PointOnSurface' self.polygonize = prefix + 'Polygonize' self.reverse = prefix + 'Reverse' self.scale = prefix + 'Scale' self.snap_to_grid = prefix + 'SnapToGrid' self.svg = prefix + 'AsSVG' self.sym_difference = prefix + 'SymDifference' self.transform = prefix + 'Transform' self.translate = prefix + 'Translate' self.union = prefix + 'Union' self.unionagg = prefix + 'Union' if version >= (2, 0, 0): self.extent3d = prefix + '3DExtent' self.length3d = prefix + '3DLength' self.perimeter3d = prefix + '3DPerimeter' else: self.extent3d = prefix + 'Extent3D' self.length3d = prefix + 'Length3D' self.perimeter3d = prefix + 'Perimeter3D' def check_aggregate_support(self, aggregate): """ Checks if the given aggregate name is supported (that is, if it's in `self.valid_aggregates`). """ agg_name = aggregate.__class__.__name__ return agg_name in self.valid_aggregates def convert_extent(self, box): """ Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)". """ ll, ur = box[4:-1].split(',') xmin, ymin = map(float, ll.split()) xmax, ymax = map(float, ur.split()) return (xmin, ymin, xmax, ymax) def convert_extent3d(self, box3d): """ Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)". """ ll, ur = box3d[6:-1].split(',') xmin, ymin, zmin = map(float, ll.split()) xmax, ymax, zmax = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax) def convert_geom(self, hex, geo_field): """ Converts the geometry returned from PostGIS aggretates. """ if hex: return Geometry(hex) else: return None def geo_db_type(self, f): """ Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead. """ if f.geography: if not self.geography: raise NotImplementedError('PostGIS 1.5 required for geography column support.') if f.srid != 4326: raise NotImplementedError('PostGIS 1.5 supports geography columns ' 'only with an SRID of 4326.') return 'geography(%s,%d)' % (f.geom_type, f.srid) elif self.geometry: # Postgis 2.0 supports type-based geometries. # TODO: Support 'M' extension. if f.dim == 3: geom_type = f.geom_type + 'Z' else: geom_type = f.geom_type return 'geometry(%s,%d)' % (geom_type, f.srid) else: return None def get_distance(self, f, dist_val, lookup_type): """ Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what's available on projected geometry columns. In addition, it has to take into account the newly introduced geography column type introudced in PostGIS 1.5. """ # Getting the distance parameter and any options. if len(dist_val) == 1: value, option = dist_val[0], None else: value, option = dist_val # Shorthand boolean flags. geodetic = f.geodetic(self.connection) geography = f.geography and self.geography if isinstance(value, Distance): if geography: dist_param = value.m elif geodetic: if lookup_type == 'dwithin': raise ValueError('Only numeric values of degree units are ' 'allowed on geographic DWithin queries.') dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: # Assuming the distance is in the units of the field. dist_param = value if (not geography and geodetic and lookup_type != 'dwithin' and option == 'spheroid'): # using distance_spheroid requires the spheroid of the field as # a parameter. return [f._spheroid, dist_param] else: return [dist_param] def
(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call. """ if value is None or value.srid == f.srid: placeholder = '%s' else: # Adding Transform() to the SQL placeholder. placeholder = '%s(%%s, %s)' % (self.transform, f.srid) if hasattr(value, 'expression'): # If this is an F expression, then we don't really want # a placeholder and instead substitute in the column # of the expression. placeholder = placeholder % self.get_expression_column(value) return placeholder def _get_postgis_func(self, func): """ Helper routine for calling PostGIS functions and returning their result. """ # Close out the connection. See #9437. with self.connection.temporary_connection() as cursor: cursor.execute('SELECT %s()' % func) return cursor.fetchone()[0] def postgis_geos_version(self): "Returns the version of the GEOS library used with PostGIS." return self._get_postgis_func('postgis_geos_version') def postgis_lib_version(self): "Returns the version number of the PostGIS library used with PostgreSQL." return self._get_postgis_func('postgis_lib_version') def postgis_proj_version(self): "Returns the version of the PROJ.4 library used with PostGIS." return self._get_postgis_func('postgis_proj_version') def postgis_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_version') def postgis_full_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_full_version') def postgis_version_tuple(self): """ Returns the PostGIS version as a tuple (version string, major, minor, subminor). """ # Getting the PostGIS version version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse PostGIS version string: %s' % version) return (version, major, minor1, minor2) def proj_version_tuple(self): """ Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers. """ proj_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostGIS.') def num_params(self, lookup_type, num_param): """ Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type. """ def exactly_two(np): return np == 2 def two_to_three(np): return np >= 2 and np <=3 if (lookup_type in self.distance_functions and lookup_type != 'dwithin'): return two_to_three(num_param) else: return exactly_two(num_param) def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): """ Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field. """ alias, col, db_type = lvalue # Getting the quoted geometry column. geo_col = '%s.%s' % (qn(alias), qn(col)) if lookup_type in self.geometry_operators: if field.geography and not lookup_type in self.geography_operators: raise ValueError('PostGIS geography does not support the ' '"%s" lookup.' % lookup_type) # Handling a PostGIS operator. op = self.geometry_operators[lookup_type] return op.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif lookup_type in self.geometry_functions: if field.geography and not lookup_type in self.geography_functions: raise ValueError('PostGIS geography type does not support the ' '"%s" lookup.' % lookup_type) # See if a PostGIS geometry function matches the lookup type. tmp = self.geometry_functions[lookup_type] # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # distance lookups. if isinstance(tmp, tuple): # First element of tuple is the PostGISOperation instance, and the # second element is either the type or a tuple of acceptable types # that may passed in as further parameters for the lookup type. op, arg_type = tmp # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, (tuple, list)): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) # Geometry is first element of lookup tuple. geom = value[0] # Number of valid tuple parameters depends on the lookup type. nparams = len(value) if not self.num_params(lookup_type, nparams): raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) # For lookup type `relate`, the op instance is not yet created (has # to be instantiated here to check the pattern parameter). if lookup_type == 'relate': op = op(self.geom_func_prefix, value[1]) elif lookup_type in self.distance_functions and lookup_type != 'dwithin': if not field.geography and field.geodetic(self.connection): # Geodetic distances are only available from Points to # PointFields on PostGIS 1.4 and below. if not self.connection.ops.geography: if field.geom_type != 'POINT': raise ValueError('PostGIS spherical operations are only valid on PointFields.') if str(geom.geom_type) != 'Point': raise ValueError('PostGIS geometry distance parameter is required to be of type Point.') # Setting up the geodetic operation appropriately. if nparams == 3 and value[2] == 'spheroid': op = op['spheroid'] else: op = op['sphere'] else: op = op['cartesian'] else: op = tmp geom = value # Calling the `as_sql` function on the operation instance. return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, ('' if value else 'NOT ')), [] raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__ if not self.check_aggregate_support(agg): raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name) agg_name = agg_name.lower() if agg_name == 'union': agg_name += 'agg' sql_template = '%(function)s(%(field)s)' sql_function = getattr(self, agg_name) return sql_template, sql_function # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.postgis.models import GeometryColumns return GeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.postgis.models import SpatialRefSys return SpatialRefSys
get_geom_placeholder
identifier_name
operations.py
import re from decimal import Decimal from django.conf import settings from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.postgresql_psycopg2.base import DatabaseOperations from django.db.utils import DatabaseError from django.utils import six #### Classes used in constructing PostGIS spatial SQL #### class PostGISOperator(SpatialOperation): "For PostGIS operators (e.g. `&&`, `~`)." def __init__(self, operator): super(PostGISOperator, self).__init__(operator=operator) class PostGISFunction(SpatialFunction): "For PostGIS function calls (e.g., `ST_Contains(table, geom)`)." def __init__(self, prefix, function, **kwargs): super(PostGISFunction, self).__init__(prefix + function, **kwargs) class PostGISFunctionParam(PostGISFunction): "For PostGIS functions that take another parameter (e.g. DWithin, Relate)." sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)' class PostGISDistance(PostGISFunction): "For PostGIS distance operations." dist_func = 'Distance' sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s' def __init__(self, prefix, operator): super(PostGISDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSpheroidDistance(PostGISFunction): "For PostGIS spherical distance operations (using the spheroid)." dist_func = 'distance_spheroid' sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s) %(operator)s %%s' def __init__(self, prefix, operator): # An extra parameter in `end_subst` is needed for the spheroid string. super(PostGISSpheroidDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSphereDistance(PostGISDistance): "For PostGIS spherical distance operations." dist_func = 'distance_sphere' class PostGISRelate(PostGISFunctionParam): "For PostGIS Relate(<geom>, <pattern>) calls." pattern_regex = re.compile(r'^[012TF\*]{9}$') def __init__(self, prefix, pattern): if not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) super(PostGISRelate, self).__init__(prefix, 'Relate') class PostGISOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = 'django.contrib.gis.db.models.sql.compiler' name = 'postgis' postgis = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)') valid_aggregates = dict([(k, None) for k in ('Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union')]) Adapter = PostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. def __init__(self, connection): super(PostGISOperations, self).__init__(connection) # Trying to get the PostGIS version because the function # signatures will depend on the version used. The cost # here is a database query to determine the version, which # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple # comprising user-supplied values for the major, minor, and # subminor revision of PostGIS. try: if hasattr(settings, 'POSTGIS_VERSION'): vtup = settings.POSTGIS_VERSION if len(vtup) == 3: # The user-supplied PostGIS version. version = vtup else: # This was the old documented way, but it's stupid to # include the string. version = vtup[1:4] else: vtup = self.postgis_version_tuple() version = vtup[1:] # Getting the prefix -- even though we don't officially support # PostGIS 1.2 anymore, keeping it anyway in case a prefix change # for something else is necessary. if version >= (1, 2, 2): prefix = 'ST_' else: prefix = '' self.geom_func_prefix = prefix self.spatial_version = version except DatabaseError: raise ImproperlyConfigured( 'Cannot determine PostGIS version for database "%s". ' 'GeoDjango requires at least PostGIS version 1.3. ' 'Was the database created from a spatial database ' 'template?' % self.connection.settings_dict['NAME'] ) # TODO: Raise helpful exceptions as they become known. # PostGIS-specific operators. The commented descriptions of these # operators come from Section 7.6 of the PostGIS 1.4 documentation. self.geometry_operators = { # The "&<" operator returns true if A's bounding box overlaps or # is to the left of B's bounding box. 'overlaps_left' : PostGISOperator('&<'), # The "&>" operator returns true if A's bounding box overlaps or # is to the right of B's bounding box. 'overlaps_right' : PostGISOperator('&>'), # The "<<" operator returns true if A's bounding box is strictly # to the left of B's bounding box. 'left' : PostGISOperator('<<'), # The ">>" operator returns true if A's bounding box is strictly # to the right of B's bounding box. 'right' : PostGISOperator('>>'), # The "&<|" operator returns true if A's bounding box overlaps or # is below B's bounding box. 'overlaps_below' : PostGISOperator('&<|'), # The "|&>" operator returns true if A's bounding box overlaps or # is above B's bounding box. 'overlaps_above' : PostGISOperator('|&>'), # The "<<|" operator returns true if A's bounding box is strictly # below B's bounding box. 'strictly_below' : PostGISOperator('<<|'), # The "|>>" operator returns true if A's bounding box is strictly # above B's bounding box. 'strictly_above' : PostGISOperator('|>>'), # The "~=" operator is the "same as" operator. It tests actual # geometric equality of two features. So if A and B are the same feature, # vertex-by-vertex, the operator returns true. 'same_as' : PostGISOperator('~='), 'exact' : PostGISOperator('~='), # The "@" operator returns true if A's bounding box is completely contained # by B's bounding box. 'contained' : PostGISOperator('@'), # The "~" operator returns true if A's bounding box completely contains # by B's bounding box. 'bbcontains' : PostGISOperator('~'), # The "&&" operator returns true if A's bounding box overlaps # B's bounding box. 'bboverlaps' : PostGISOperator('&&'), } self.geometry_functions = { 'equals' : PostGISFunction(prefix, 'Equals'), 'disjoint' : PostGISFunction(prefix, 'Disjoint'), 'touches' : PostGISFunction(prefix, 'Touches'), 'crosses' : PostGISFunction(prefix, 'Crosses'), 'within' : PostGISFunction(prefix, 'Within'), 'overlaps' : PostGISFunction(prefix, 'Overlaps'), 'contains' : PostGISFunction(prefix, 'Contains'), 'intersects' : PostGISFunction(prefix, 'Intersects'), 'relate' : (PostGISRelate, six.string_types), 'coveredby' : PostGISFunction(prefix, 'CoveredBy'), 'covers' : PostGISFunction(prefix, 'Covers'), } # Valid distance types and substitutions dtypes = (Decimal, Distance, float) + six.integer_types def get_dist_ops(operator): "Returns operations for both regular and spherical distances." return {'cartesian' : PostGISDistance(prefix, operator), 'sphere' : PostGISSphereDistance(prefix, operator), 'spheroid' : PostGISSpheroidDistance(prefix, operator), } self.distance_functions = { 'distance_gt' : (get_dist_ops('>'), dtypes), 'distance_gte' : (get_dist_ops('>='), dtypes), 'distance_lt' : (get_dist_ops('<'), dtypes), 'distance_lte' : (get_dist_ops('<='), dtypes), 'dwithin' : (PostGISFunctionParam(prefix, 'DWithin'), dtypes) } # Adding the distance functions to the geometries lookup. self.geometry_functions.update(self.distance_functions) # Only PostGIS versions 1.3.4+ have GeoJSON serialization support. if version < (1, 3, 4): GEOJSON = False else: GEOJSON = prefix + 'AsGeoJson' # ST_ContainsProperly ST_MakeLine, and ST_GeoHash added in 1.4. if version >= (1, 4, 0): GEOHASH = 'ST_GeoHash' BOUNDINGCIRCLE = 'ST_MinimumBoundingCircle' self.geometry_functions['contains_properly'] = PostGISFunction(prefix, 'ContainsProperly') else: GEOHASH, BOUNDINGCIRCLE = False, False # Geography type support added in 1.5. if version >= (1, 5, 0): self.geography = True # Only a subset of the operators and functions are available # for the geography type. self.geography_functions = self.distance_functions.copy() self.geography_functions.update({ 'coveredby': self.geometry_functions['coveredby'], 'covers': self.geometry_functions['covers'], 'intersects': self.geometry_functions['intersects'], }) self.geography_operators = { 'bboverlaps': PostGISOperator('&&'), } # Native geometry type support added in PostGIS 2.0. if version >= (2, 0, 0): self.geometry = True # Creating a dictionary lookup of all GIS terms for PostGIS. self.gis_terms = set(['isnull']) self.gis_terms.update(self.geometry_operators) self.gis_terms.update(self.geometry_functions) self.area = prefix + 'Area' self.bounding_circle = BOUNDINGCIRCLE self.centroid = prefix + 'Centroid' self.collect = prefix + 'Collect' self.difference = prefix + 'Difference' self.distance = prefix + 'Distance' self.distance_sphere = prefix + 'distance_sphere' self.distance_spheroid = prefix + 'distance_spheroid' self.envelope = prefix + 'Envelope' self.extent = prefix + 'Extent' self.force_rhr = prefix + 'ForceRHR' self.geohash = GEOHASH self.geojson = GEOJSON self.gml = prefix + 'AsGML' self.intersection = prefix + 'Intersection' self.kml = prefix + 'AsKML' self.length = prefix + 'Length' self.length_spheroid = prefix + 'length_spheroid' self.makeline = prefix + 'MakeLine' self.mem_size = prefix + 'mem_size' self.num_geom = prefix + 'NumGeometries' self.num_points = prefix + 'npoints' self.perimeter = prefix + 'Perimeter' self.point_on_surface = prefix + 'PointOnSurface' self.polygonize = prefix + 'Polygonize' self.reverse = prefix + 'Reverse' self.scale = prefix + 'Scale' self.snap_to_grid = prefix + 'SnapToGrid' self.svg = prefix + 'AsSVG' self.sym_difference = prefix + 'SymDifference' self.transform = prefix + 'Transform' self.translate = prefix + 'Translate' self.union = prefix + 'Union' self.unionagg = prefix + 'Union' if version >= (2, 0, 0): self.extent3d = prefix + '3DExtent' self.length3d = prefix + '3DLength' self.perimeter3d = prefix + '3DPerimeter' else: self.extent3d = prefix + 'Extent3D' self.length3d = prefix + 'Length3D' self.perimeter3d = prefix + 'Perimeter3D' def check_aggregate_support(self, aggregate): """ Checks if the given aggregate name is supported (that is, if it's in `self.valid_aggregates`). """ agg_name = aggregate.__class__.__name__ return agg_name in self.valid_aggregates def convert_extent(self, box): """ Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)". """ ll, ur = box[4:-1].split(',') xmin, ymin = map(float, ll.split()) xmax, ymax = map(float, ur.split()) return (xmin, ymin, xmax, ymax) def convert_extent3d(self, box3d): """ Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)". """ ll, ur = box3d[6:-1].split(',') xmin, ymin, zmin = map(float, ll.split()) xmax, ymax, zmax = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax) def convert_geom(self, hex, geo_field): """ Converts the geometry returned from PostGIS aggretates. """ if hex: return Geometry(hex) else: return None def geo_db_type(self, f): """ Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead. """ if f.geography: if not self.geography: raise NotImplementedError('PostGIS 1.5 required for geography column support.') if f.srid != 4326: raise NotImplementedError('PostGIS 1.5 supports geography columns ' 'only with an SRID of 4326.') return 'geography(%s,%d)' % (f.geom_type, f.srid) elif self.geometry: # Postgis 2.0 supports type-based geometries. # TODO: Support 'M' extension. if f.dim == 3: geom_type = f.geom_type + 'Z' else: geom_type = f.geom_type return 'geometry(%s,%d)' % (geom_type, f.srid) else: return None def get_distance(self, f, dist_val, lookup_type): """ Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what's available on projected geometry columns. In addition, it has to take into account the newly introduced geography column type introudced in PostGIS 1.5. """ # Getting the distance parameter and any options. if len(dist_val) == 1: value, option = dist_val[0], None else: value, option = dist_val # Shorthand boolean flags. geodetic = f.geodetic(self.connection) geography = f.geography and self.geography if isinstance(value, Distance): if geography: dist_param = value.m elif geodetic: if lookup_type == 'dwithin': raise ValueError('Only numeric values of degree units are ' 'allowed on geographic DWithin queries.') dist_param = value.m else:
else: # Assuming the distance is in the units of the field. dist_param = value if (not geography and geodetic and lookup_type != 'dwithin' and option == 'spheroid'): # using distance_spheroid requires the spheroid of the field as # a parameter. return [f._spheroid, dist_param] else: return [dist_param] def get_geom_placeholder(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call. """ if value is None or value.srid == f.srid: placeholder = '%s' else: # Adding Transform() to the SQL placeholder. placeholder = '%s(%%s, %s)' % (self.transform, f.srid) if hasattr(value, 'expression'): # If this is an F expression, then we don't really want # a placeholder and instead substitute in the column # of the expression. placeholder = placeholder % self.get_expression_column(value) return placeholder def _get_postgis_func(self, func): """ Helper routine for calling PostGIS functions and returning their result. """ # Close out the connection. See #9437. with self.connection.temporary_connection() as cursor: cursor.execute('SELECT %s()' % func) return cursor.fetchone()[0] def postgis_geos_version(self): "Returns the version of the GEOS library used with PostGIS." return self._get_postgis_func('postgis_geos_version') def postgis_lib_version(self): "Returns the version number of the PostGIS library used with PostgreSQL." return self._get_postgis_func('postgis_lib_version') def postgis_proj_version(self): "Returns the version of the PROJ.4 library used with PostGIS." return self._get_postgis_func('postgis_proj_version') def postgis_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_version') def postgis_full_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_full_version') def postgis_version_tuple(self): """ Returns the PostGIS version as a tuple (version string, major, minor, subminor). """ # Getting the PostGIS version version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse PostGIS version string: %s' % version) return (version, major, minor1, minor2) def proj_version_tuple(self): """ Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers. """ proj_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostGIS.') def num_params(self, lookup_type, num_param): """ Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type. """ def exactly_two(np): return np == 2 def two_to_three(np): return np >= 2 and np <=3 if (lookup_type in self.distance_functions and lookup_type != 'dwithin'): return two_to_three(num_param) else: return exactly_two(num_param) def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): """ Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field. """ alias, col, db_type = lvalue # Getting the quoted geometry column. geo_col = '%s.%s' % (qn(alias), qn(col)) if lookup_type in self.geometry_operators: if field.geography and not lookup_type in self.geography_operators: raise ValueError('PostGIS geography does not support the ' '"%s" lookup.' % lookup_type) # Handling a PostGIS operator. op = self.geometry_operators[lookup_type] return op.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif lookup_type in self.geometry_functions: if field.geography and not lookup_type in self.geography_functions: raise ValueError('PostGIS geography type does not support the ' '"%s" lookup.' % lookup_type) # See if a PostGIS geometry function matches the lookup type. tmp = self.geometry_functions[lookup_type] # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # distance lookups. if isinstance(tmp, tuple): # First element of tuple is the PostGISOperation instance, and the # second element is either the type or a tuple of acceptable types # that may passed in as further parameters for the lookup type. op, arg_type = tmp # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, (tuple, list)): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) # Geometry is first element of lookup tuple. geom = value[0] # Number of valid tuple parameters depends on the lookup type. nparams = len(value) if not self.num_params(lookup_type, nparams): raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) # For lookup type `relate`, the op instance is not yet created (has # to be instantiated here to check the pattern parameter). if lookup_type == 'relate': op = op(self.geom_func_prefix, value[1]) elif lookup_type in self.distance_functions and lookup_type != 'dwithin': if not field.geography and field.geodetic(self.connection): # Geodetic distances are only available from Points to # PointFields on PostGIS 1.4 and below. if not self.connection.ops.geography: if field.geom_type != 'POINT': raise ValueError('PostGIS spherical operations are only valid on PointFields.') if str(geom.geom_type) != 'Point': raise ValueError('PostGIS geometry distance parameter is required to be of type Point.') # Setting up the geodetic operation appropriately. if nparams == 3 and value[2] == 'spheroid': op = op['spheroid'] else: op = op['sphere'] else: op = op['cartesian'] else: op = tmp geom = value # Calling the `as_sql` function on the operation instance. return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, ('' if value else 'NOT ')), [] raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__ if not self.check_aggregate_support(agg): raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name) agg_name = agg_name.lower() if agg_name == 'union': agg_name += 'agg' sql_template = '%(function)s(%(field)s)' sql_function = getattr(self, agg_name) return sql_template, sql_function # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.postgis.models import GeometryColumns return GeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.postgis.models import SpatialRefSys return SpatialRefSys
dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection)))
conditional_block
operations.py
import re from decimal import Decimal from django.conf import settings from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.postgresql_psycopg2.base import DatabaseOperations from django.db.utils import DatabaseError from django.utils import six #### Classes used in constructing PostGIS spatial SQL #### class PostGISOperator(SpatialOperation): "For PostGIS operators (e.g. `&&`, `~`)." def __init__(self, operator): super(PostGISOperator, self).__init__(operator=operator) class PostGISFunction(SpatialFunction): "For PostGIS function calls (e.g., `ST_Contains(table, geom)`)." def __init__(self, prefix, function, **kwargs): super(PostGISFunction, self).__init__(prefix + function, **kwargs) class PostGISFunctionParam(PostGISFunction): "For PostGIS functions that take another parameter (e.g. DWithin, Relate)." sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)' class PostGISDistance(PostGISFunction): "For PostGIS distance operations." dist_func = 'Distance' sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s' def __init__(self, prefix, operator): super(PostGISDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSpheroidDistance(PostGISFunction): "For PostGIS spherical distance operations (using the spheroid)." dist_func = 'distance_spheroid' sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s) %(operator)s %%s' def __init__(self, prefix, operator): # An extra parameter in `end_subst` is needed for the spheroid string. super(PostGISSpheroidDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSphereDistance(PostGISDistance): "For PostGIS spherical distance operations." dist_func = 'distance_sphere' class PostGISRelate(PostGISFunctionParam): "For PostGIS Relate(<geom>, <pattern>) calls." pattern_regex = re.compile(r'^[012TF\*]{9}$') def __init__(self, prefix, pattern): if not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) super(PostGISRelate, self).__init__(prefix, 'Relate') class PostGISOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = 'django.contrib.gis.db.models.sql.compiler'
valid_aggregates = dict([(k, None) for k in ('Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union')]) Adapter = PostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. def __init__(self, connection): super(PostGISOperations, self).__init__(connection) # Trying to get the PostGIS version because the function # signatures will depend on the version used. The cost # here is a database query to determine the version, which # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple # comprising user-supplied values for the major, minor, and # subminor revision of PostGIS. try: if hasattr(settings, 'POSTGIS_VERSION'): vtup = settings.POSTGIS_VERSION if len(vtup) == 3: # The user-supplied PostGIS version. version = vtup else: # This was the old documented way, but it's stupid to # include the string. version = vtup[1:4] else: vtup = self.postgis_version_tuple() version = vtup[1:] # Getting the prefix -- even though we don't officially support # PostGIS 1.2 anymore, keeping it anyway in case a prefix change # for something else is necessary. if version >= (1, 2, 2): prefix = 'ST_' else: prefix = '' self.geom_func_prefix = prefix self.spatial_version = version except DatabaseError: raise ImproperlyConfigured( 'Cannot determine PostGIS version for database "%s". ' 'GeoDjango requires at least PostGIS version 1.3. ' 'Was the database created from a spatial database ' 'template?' % self.connection.settings_dict['NAME'] ) # TODO: Raise helpful exceptions as they become known. # PostGIS-specific operators. The commented descriptions of these # operators come from Section 7.6 of the PostGIS 1.4 documentation. self.geometry_operators = { # The "&<" operator returns true if A's bounding box overlaps or # is to the left of B's bounding box. 'overlaps_left' : PostGISOperator('&<'), # The "&>" operator returns true if A's bounding box overlaps or # is to the right of B's bounding box. 'overlaps_right' : PostGISOperator('&>'), # The "<<" operator returns true if A's bounding box is strictly # to the left of B's bounding box. 'left' : PostGISOperator('<<'), # The ">>" operator returns true if A's bounding box is strictly # to the right of B's bounding box. 'right' : PostGISOperator('>>'), # The "&<|" operator returns true if A's bounding box overlaps or # is below B's bounding box. 'overlaps_below' : PostGISOperator('&<|'), # The "|&>" operator returns true if A's bounding box overlaps or # is above B's bounding box. 'overlaps_above' : PostGISOperator('|&>'), # The "<<|" operator returns true if A's bounding box is strictly # below B's bounding box. 'strictly_below' : PostGISOperator('<<|'), # The "|>>" operator returns true if A's bounding box is strictly # above B's bounding box. 'strictly_above' : PostGISOperator('|>>'), # The "~=" operator is the "same as" operator. It tests actual # geometric equality of two features. So if A and B are the same feature, # vertex-by-vertex, the operator returns true. 'same_as' : PostGISOperator('~='), 'exact' : PostGISOperator('~='), # The "@" operator returns true if A's bounding box is completely contained # by B's bounding box. 'contained' : PostGISOperator('@'), # The "~" operator returns true if A's bounding box completely contains # by B's bounding box. 'bbcontains' : PostGISOperator('~'), # The "&&" operator returns true if A's bounding box overlaps # B's bounding box. 'bboverlaps' : PostGISOperator('&&'), } self.geometry_functions = { 'equals' : PostGISFunction(prefix, 'Equals'), 'disjoint' : PostGISFunction(prefix, 'Disjoint'), 'touches' : PostGISFunction(prefix, 'Touches'), 'crosses' : PostGISFunction(prefix, 'Crosses'), 'within' : PostGISFunction(prefix, 'Within'), 'overlaps' : PostGISFunction(prefix, 'Overlaps'), 'contains' : PostGISFunction(prefix, 'Contains'), 'intersects' : PostGISFunction(prefix, 'Intersects'), 'relate' : (PostGISRelate, six.string_types), 'coveredby' : PostGISFunction(prefix, 'CoveredBy'), 'covers' : PostGISFunction(prefix, 'Covers'), } # Valid distance types and substitutions dtypes = (Decimal, Distance, float) + six.integer_types def get_dist_ops(operator): "Returns operations for both regular and spherical distances." return {'cartesian' : PostGISDistance(prefix, operator), 'sphere' : PostGISSphereDistance(prefix, operator), 'spheroid' : PostGISSpheroidDistance(prefix, operator), } self.distance_functions = { 'distance_gt' : (get_dist_ops('>'), dtypes), 'distance_gte' : (get_dist_ops('>='), dtypes), 'distance_lt' : (get_dist_ops('<'), dtypes), 'distance_lte' : (get_dist_ops('<='), dtypes), 'dwithin' : (PostGISFunctionParam(prefix, 'DWithin'), dtypes) } # Adding the distance functions to the geometries lookup. self.geometry_functions.update(self.distance_functions) # Only PostGIS versions 1.3.4+ have GeoJSON serialization support. if version < (1, 3, 4): GEOJSON = False else: GEOJSON = prefix + 'AsGeoJson' # ST_ContainsProperly ST_MakeLine, and ST_GeoHash added in 1.4. if version >= (1, 4, 0): GEOHASH = 'ST_GeoHash' BOUNDINGCIRCLE = 'ST_MinimumBoundingCircle' self.geometry_functions['contains_properly'] = PostGISFunction(prefix, 'ContainsProperly') else: GEOHASH, BOUNDINGCIRCLE = False, False # Geography type support added in 1.5. if version >= (1, 5, 0): self.geography = True # Only a subset of the operators and functions are available # for the geography type. self.geography_functions = self.distance_functions.copy() self.geography_functions.update({ 'coveredby': self.geometry_functions['coveredby'], 'covers': self.geometry_functions['covers'], 'intersects': self.geometry_functions['intersects'], }) self.geography_operators = { 'bboverlaps': PostGISOperator('&&'), } # Native geometry type support added in PostGIS 2.0. if version >= (2, 0, 0): self.geometry = True # Creating a dictionary lookup of all GIS terms for PostGIS. self.gis_terms = set(['isnull']) self.gis_terms.update(self.geometry_operators) self.gis_terms.update(self.geometry_functions) self.area = prefix + 'Area' self.bounding_circle = BOUNDINGCIRCLE self.centroid = prefix + 'Centroid' self.collect = prefix + 'Collect' self.difference = prefix + 'Difference' self.distance = prefix + 'Distance' self.distance_sphere = prefix + 'distance_sphere' self.distance_spheroid = prefix + 'distance_spheroid' self.envelope = prefix + 'Envelope' self.extent = prefix + 'Extent' self.force_rhr = prefix + 'ForceRHR' self.geohash = GEOHASH self.geojson = GEOJSON self.gml = prefix + 'AsGML' self.intersection = prefix + 'Intersection' self.kml = prefix + 'AsKML' self.length = prefix + 'Length' self.length_spheroid = prefix + 'length_spheroid' self.makeline = prefix + 'MakeLine' self.mem_size = prefix + 'mem_size' self.num_geom = prefix + 'NumGeometries' self.num_points = prefix + 'npoints' self.perimeter = prefix + 'Perimeter' self.point_on_surface = prefix + 'PointOnSurface' self.polygonize = prefix + 'Polygonize' self.reverse = prefix + 'Reverse' self.scale = prefix + 'Scale' self.snap_to_grid = prefix + 'SnapToGrid' self.svg = prefix + 'AsSVG' self.sym_difference = prefix + 'SymDifference' self.transform = prefix + 'Transform' self.translate = prefix + 'Translate' self.union = prefix + 'Union' self.unionagg = prefix + 'Union' if version >= (2, 0, 0): self.extent3d = prefix + '3DExtent' self.length3d = prefix + '3DLength' self.perimeter3d = prefix + '3DPerimeter' else: self.extent3d = prefix + 'Extent3D' self.length3d = prefix + 'Length3D' self.perimeter3d = prefix + 'Perimeter3D' def check_aggregate_support(self, aggregate): """ Checks if the given aggregate name is supported (that is, if it's in `self.valid_aggregates`). """ agg_name = aggregate.__class__.__name__ return agg_name in self.valid_aggregates def convert_extent(self, box): """ Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)". """ ll, ur = box[4:-1].split(',') xmin, ymin = map(float, ll.split()) xmax, ymax = map(float, ur.split()) return (xmin, ymin, xmax, ymax) def convert_extent3d(self, box3d): """ Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)". """ ll, ur = box3d[6:-1].split(',') xmin, ymin, zmin = map(float, ll.split()) xmax, ymax, zmax = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax) def convert_geom(self, hex, geo_field): """ Converts the geometry returned from PostGIS aggretates. """ if hex: return Geometry(hex) else: return None def geo_db_type(self, f): """ Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead. """ if f.geography: if not self.geography: raise NotImplementedError('PostGIS 1.5 required for geography column support.') if f.srid != 4326: raise NotImplementedError('PostGIS 1.5 supports geography columns ' 'only with an SRID of 4326.') return 'geography(%s,%d)' % (f.geom_type, f.srid) elif self.geometry: # Postgis 2.0 supports type-based geometries. # TODO: Support 'M' extension. if f.dim == 3: geom_type = f.geom_type + 'Z' else: geom_type = f.geom_type return 'geometry(%s,%d)' % (geom_type, f.srid) else: return None def get_distance(self, f, dist_val, lookup_type): """ Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what's available on projected geometry columns. In addition, it has to take into account the newly introduced geography column type introudced in PostGIS 1.5. """ # Getting the distance parameter and any options. if len(dist_val) == 1: value, option = dist_val[0], None else: value, option = dist_val # Shorthand boolean flags. geodetic = f.geodetic(self.connection) geography = f.geography and self.geography if isinstance(value, Distance): if geography: dist_param = value.m elif geodetic: if lookup_type == 'dwithin': raise ValueError('Only numeric values of degree units are ' 'allowed on geographic DWithin queries.') dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: # Assuming the distance is in the units of the field. dist_param = value if (not geography and geodetic and lookup_type != 'dwithin' and option == 'spheroid'): # using distance_spheroid requires the spheroid of the field as # a parameter. return [f._spheroid, dist_param] else: return [dist_param] def get_geom_placeholder(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call. """ if value is None or value.srid == f.srid: placeholder = '%s' else: # Adding Transform() to the SQL placeholder. placeholder = '%s(%%s, %s)' % (self.transform, f.srid) if hasattr(value, 'expression'): # If this is an F expression, then we don't really want # a placeholder and instead substitute in the column # of the expression. placeholder = placeholder % self.get_expression_column(value) return placeholder def _get_postgis_func(self, func): """ Helper routine for calling PostGIS functions and returning their result. """ # Close out the connection. See #9437. with self.connection.temporary_connection() as cursor: cursor.execute('SELECT %s()' % func) return cursor.fetchone()[0] def postgis_geos_version(self): "Returns the version of the GEOS library used with PostGIS." return self._get_postgis_func('postgis_geos_version') def postgis_lib_version(self): "Returns the version number of the PostGIS library used with PostgreSQL." return self._get_postgis_func('postgis_lib_version') def postgis_proj_version(self): "Returns the version of the PROJ.4 library used with PostGIS." return self._get_postgis_func('postgis_proj_version') def postgis_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_version') def postgis_full_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_full_version') def postgis_version_tuple(self): """ Returns the PostGIS version as a tuple (version string, major, minor, subminor). """ # Getting the PostGIS version version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse PostGIS version string: %s' % version) return (version, major, minor1, minor2) def proj_version_tuple(self): """ Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers. """ proj_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostGIS.') def num_params(self, lookup_type, num_param): """ Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type. """ def exactly_two(np): return np == 2 def two_to_three(np): return np >= 2 and np <=3 if (lookup_type in self.distance_functions and lookup_type != 'dwithin'): return two_to_three(num_param) else: return exactly_two(num_param) def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): """ Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field. """ alias, col, db_type = lvalue # Getting the quoted geometry column. geo_col = '%s.%s' % (qn(alias), qn(col)) if lookup_type in self.geometry_operators: if field.geography and not lookup_type in self.geography_operators: raise ValueError('PostGIS geography does not support the ' '"%s" lookup.' % lookup_type) # Handling a PostGIS operator. op = self.geometry_operators[lookup_type] return op.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif lookup_type in self.geometry_functions: if field.geography and not lookup_type in self.geography_functions: raise ValueError('PostGIS geography type does not support the ' '"%s" lookup.' % lookup_type) # See if a PostGIS geometry function matches the lookup type. tmp = self.geometry_functions[lookup_type] # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # distance lookups. if isinstance(tmp, tuple): # First element of tuple is the PostGISOperation instance, and the # second element is either the type or a tuple of acceptable types # that may passed in as further parameters for the lookup type. op, arg_type = tmp # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, (tuple, list)): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) # Geometry is first element of lookup tuple. geom = value[0] # Number of valid tuple parameters depends on the lookup type. nparams = len(value) if not self.num_params(lookup_type, nparams): raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) # For lookup type `relate`, the op instance is not yet created (has # to be instantiated here to check the pattern parameter). if lookup_type == 'relate': op = op(self.geom_func_prefix, value[1]) elif lookup_type in self.distance_functions and lookup_type != 'dwithin': if not field.geography and field.geodetic(self.connection): # Geodetic distances are only available from Points to # PointFields on PostGIS 1.4 and below. if not self.connection.ops.geography: if field.geom_type != 'POINT': raise ValueError('PostGIS spherical operations are only valid on PointFields.') if str(geom.geom_type) != 'Point': raise ValueError('PostGIS geometry distance parameter is required to be of type Point.') # Setting up the geodetic operation appropriately. if nparams == 3 and value[2] == 'spheroid': op = op['spheroid'] else: op = op['sphere'] else: op = op['cartesian'] else: op = tmp geom = value # Calling the `as_sql` function on the operation instance. return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, ('' if value else 'NOT ')), [] raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__ if not self.check_aggregate_support(agg): raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name) agg_name = agg_name.lower() if agg_name == 'union': agg_name += 'agg' sql_template = '%(function)s(%(field)s)' sql_function = getattr(self, agg_name) return sql_template, sql_function # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.postgis.models import GeometryColumns return GeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.postgis.models import SpatialRefSys return SpatialRefSys
name = 'postgis' postgis = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)')
random_line_split
operations.py
import re from decimal import Decimal from django.conf import settings from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.postgresql_psycopg2.base import DatabaseOperations from django.db.utils import DatabaseError from django.utils import six #### Classes used in constructing PostGIS spatial SQL #### class PostGISOperator(SpatialOperation): "For PostGIS operators (e.g. `&&`, `~`)." def __init__(self, operator): super(PostGISOperator, self).__init__(operator=operator) class PostGISFunction(SpatialFunction): "For PostGIS function calls (e.g., `ST_Contains(table, geom)`)." def __init__(self, prefix, function, **kwargs): super(PostGISFunction, self).__init__(prefix + function, **kwargs) class PostGISFunctionParam(PostGISFunction): "For PostGIS functions that take another parameter (e.g. DWithin, Relate)." sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)' class PostGISDistance(PostGISFunction): "For PostGIS distance operations." dist_func = 'Distance' sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s' def __init__(self, prefix, operator): super(PostGISDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSpheroidDistance(PostGISFunction): "For PostGIS spherical distance operations (using the spheroid)." dist_func = 'distance_spheroid' sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s) %(operator)s %%s' def __init__(self, prefix, operator): # An extra parameter in `end_subst` is needed for the spheroid string. super(PostGISSpheroidDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSphereDistance(PostGISDistance): "For PostGIS spherical distance operations." dist_func = 'distance_sphere' class PostGISRelate(PostGISFunctionParam): "For PostGIS Relate(<geom>, <pattern>) calls." pattern_regex = re.compile(r'^[012TF\*]{9}$') def __init__(self, prefix, pattern): if not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) super(PostGISRelate, self).__init__(prefix, 'Relate') class PostGISOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = 'django.contrib.gis.db.models.sql.compiler' name = 'postgis' postgis = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)') valid_aggregates = dict([(k, None) for k in ('Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union')]) Adapter = PostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. def __init__(self, connection): super(PostGISOperations, self).__init__(connection) # Trying to get the PostGIS version because the function # signatures will depend on the version used. The cost # here is a database query to determine the version, which # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple # comprising user-supplied values for the major, minor, and # subminor revision of PostGIS. try: if hasattr(settings, 'POSTGIS_VERSION'): vtup = settings.POSTGIS_VERSION if len(vtup) == 3: # The user-supplied PostGIS version. version = vtup else: # This was the old documented way, but it's stupid to # include the string. version = vtup[1:4] else: vtup = self.postgis_version_tuple() version = vtup[1:] # Getting the prefix -- even though we don't officially support # PostGIS 1.2 anymore, keeping it anyway in case a prefix change # for something else is necessary. if version >= (1, 2, 2): prefix = 'ST_' else: prefix = '' self.geom_func_prefix = prefix self.spatial_version = version except DatabaseError: raise ImproperlyConfigured( 'Cannot determine PostGIS version for database "%s". ' 'GeoDjango requires at least PostGIS version 1.3. ' 'Was the database created from a spatial database ' 'template?' % self.connection.settings_dict['NAME'] ) # TODO: Raise helpful exceptions as they become known. # PostGIS-specific operators. The commented descriptions of these # operators come from Section 7.6 of the PostGIS 1.4 documentation. self.geometry_operators = { # The "&<" operator returns true if A's bounding box overlaps or # is to the left of B's bounding box. 'overlaps_left' : PostGISOperator('&<'), # The "&>" operator returns true if A's bounding box overlaps or # is to the right of B's bounding box. 'overlaps_right' : PostGISOperator('&>'), # The "<<" operator returns true if A's bounding box is strictly # to the left of B's bounding box. 'left' : PostGISOperator('<<'), # The ">>" operator returns true if A's bounding box is strictly # to the right of B's bounding box. 'right' : PostGISOperator('>>'), # The "&<|" operator returns true if A's bounding box overlaps or # is below B's bounding box. 'overlaps_below' : PostGISOperator('&<|'), # The "|&>" operator returns true if A's bounding box overlaps or # is above B's bounding box. 'overlaps_above' : PostGISOperator('|&>'), # The "<<|" operator returns true if A's bounding box is strictly # below B's bounding box. 'strictly_below' : PostGISOperator('<<|'), # The "|>>" operator returns true if A's bounding box is strictly # above B's bounding box. 'strictly_above' : PostGISOperator('|>>'), # The "~=" operator is the "same as" operator. It tests actual # geometric equality of two features. So if A and B are the same feature, # vertex-by-vertex, the operator returns true. 'same_as' : PostGISOperator('~='), 'exact' : PostGISOperator('~='), # The "@" operator returns true if A's bounding box is completely contained # by B's bounding box. 'contained' : PostGISOperator('@'), # The "~" operator returns true if A's bounding box completely contains # by B's bounding box. 'bbcontains' : PostGISOperator('~'), # The "&&" operator returns true if A's bounding box overlaps # B's bounding box. 'bboverlaps' : PostGISOperator('&&'), } self.geometry_functions = { 'equals' : PostGISFunction(prefix, 'Equals'), 'disjoint' : PostGISFunction(prefix, 'Disjoint'), 'touches' : PostGISFunction(prefix, 'Touches'), 'crosses' : PostGISFunction(prefix, 'Crosses'), 'within' : PostGISFunction(prefix, 'Within'), 'overlaps' : PostGISFunction(prefix, 'Overlaps'), 'contains' : PostGISFunction(prefix, 'Contains'), 'intersects' : PostGISFunction(prefix, 'Intersects'), 'relate' : (PostGISRelate, six.string_types), 'coveredby' : PostGISFunction(prefix, 'CoveredBy'), 'covers' : PostGISFunction(prefix, 'Covers'), } # Valid distance types and substitutions dtypes = (Decimal, Distance, float) + six.integer_types def get_dist_ops(operator): "Returns operations for both regular and spherical distances." return {'cartesian' : PostGISDistance(prefix, operator), 'sphere' : PostGISSphereDistance(prefix, operator), 'spheroid' : PostGISSpheroidDistance(prefix, operator), } self.distance_functions = { 'distance_gt' : (get_dist_ops('>'), dtypes), 'distance_gte' : (get_dist_ops('>='), dtypes), 'distance_lt' : (get_dist_ops('<'), dtypes), 'distance_lte' : (get_dist_ops('<='), dtypes), 'dwithin' : (PostGISFunctionParam(prefix, 'DWithin'), dtypes) } # Adding the distance functions to the geometries lookup. self.geometry_functions.update(self.distance_functions) # Only PostGIS versions 1.3.4+ have GeoJSON serialization support. if version < (1, 3, 4): GEOJSON = False else: GEOJSON = prefix + 'AsGeoJson' # ST_ContainsProperly ST_MakeLine, and ST_GeoHash added in 1.4. if version >= (1, 4, 0): GEOHASH = 'ST_GeoHash' BOUNDINGCIRCLE = 'ST_MinimumBoundingCircle' self.geometry_functions['contains_properly'] = PostGISFunction(prefix, 'ContainsProperly') else: GEOHASH, BOUNDINGCIRCLE = False, False # Geography type support added in 1.5. if version >= (1, 5, 0): self.geography = True # Only a subset of the operators and functions are available # for the geography type. self.geography_functions = self.distance_functions.copy() self.geography_functions.update({ 'coveredby': self.geometry_functions['coveredby'], 'covers': self.geometry_functions['covers'], 'intersects': self.geometry_functions['intersects'], }) self.geography_operators = { 'bboverlaps': PostGISOperator('&&'), } # Native geometry type support added in PostGIS 2.0. if version >= (2, 0, 0): self.geometry = True # Creating a dictionary lookup of all GIS terms for PostGIS. self.gis_terms = set(['isnull']) self.gis_terms.update(self.geometry_operators) self.gis_terms.update(self.geometry_functions) self.area = prefix + 'Area' self.bounding_circle = BOUNDINGCIRCLE self.centroid = prefix + 'Centroid' self.collect = prefix + 'Collect' self.difference = prefix + 'Difference' self.distance = prefix + 'Distance' self.distance_sphere = prefix + 'distance_sphere' self.distance_spheroid = prefix + 'distance_spheroid' self.envelope = prefix + 'Envelope' self.extent = prefix + 'Extent' self.force_rhr = prefix + 'ForceRHR' self.geohash = GEOHASH self.geojson = GEOJSON self.gml = prefix + 'AsGML' self.intersection = prefix + 'Intersection' self.kml = prefix + 'AsKML' self.length = prefix + 'Length' self.length_spheroid = prefix + 'length_spheroid' self.makeline = prefix + 'MakeLine' self.mem_size = prefix + 'mem_size' self.num_geom = prefix + 'NumGeometries' self.num_points = prefix + 'npoints' self.perimeter = prefix + 'Perimeter' self.point_on_surface = prefix + 'PointOnSurface' self.polygonize = prefix + 'Polygonize' self.reverse = prefix + 'Reverse' self.scale = prefix + 'Scale' self.snap_to_grid = prefix + 'SnapToGrid' self.svg = prefix + 'AsSVG' self.sym_difference = prefix + 'SymDifference' self.transform = prefix + 'Transform' self.translate = prefix + 'Translate' self.union = prefix + 'Union' self.unionagg = prefix + 'Union' if version >= (2, 0, 0): self.extent3d = prefix + '3DExtent' self.length3d = prefix + '3DLength' self.perimeter3d = prefix + '3DPerimeter' else: self.extent3d = prefix + 'Extent3D' self.length3d = prefix + 'Length3D' self.perimeter3d = prefix + 'Perimeter3D' def check_aggregate_support(self, aggregate): """ Checks if the given aggregate name is supported (that is, if it's in `self.valid_aggregates`). """ agg_name = aggregate.__class__.__name__ return agg_name in self.valid_aggregates def convert_extent(self, box): """ Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)". """ ll, ur = box[4:-1].split(',') xmin, ymin = map(float, ll.split()) xmax, ymax = map(float, ur.split()) return (xmin, ymin, xmax, ymax) def convert_extent3d(self, box3d): """ Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)". """ ll, ur = box3d[6:-1].split(',') xmin, ymin, zmin = map(float, ll.split()) xmax, ymax, zmax = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax) def convert_geom(self, hex, geo_field): """ Converts the geometry returned from PostGIS aggretates. """ if hex: return Geometry(hex) else: return None def geo_db_type(self, f): """ Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead. """ if f.geography: if not self.geography: raise NotImplementedError('PostGIS 1.5 required for geography column support.') if f.srid != 4326: raise NotImplementedError('PostGIS 1.5 supports geography columns ' 'only with an SRID of 4326.') return 'geography(%s,%d)' % (f.geom_type, f.srid) elif self.geometry: # Postgis 2.0 supports type-based geometries. # TODO: Support 'M' extension. if f.dim == 3: geom_type = f.geom_type + 'Z' else: geom_type = f.geom_type return 'geometry(%s,%d)' % (geom_type, f.srid) else: return None def get_distance(self, f, dist_val, lookup_type): """ Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what's available on projected geometry columns. In addition, it has to take into account the newly introduced geography column type introudced in PostGIS 1.5. """ # Getting the distance parameter and any options. if len(dist_val) == 1: value, option = dist_val[0], None else: value, option = dist_val # Shorthand boolean flags. geodetic = f.geodetic(self.connection) geography = f.geography and self.geography if isinstance(value, Distance): if geography: dist_param = value.m elif geodetic: if lookup_type == 'dwithin': raise ValueError('Only numeric values of degree units are ' 'allowed on geographic DWithin queries.') dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: # Assuming the distance is in the units of the field. dist_param = value if (not geography and geodetic and lookup_type != 'dwithin' and option == 'spheroid'): # using distance_spheroid requires the spheroid of the field as # a parameter. return [f._spheroid, dist_param] else: return [dist_param] def get_geom_placeholder(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call. """ if value is None or value.srid == f.srid: placeholder = '%s' else: # Adding Transform() to the SQL placeholder. placeholder = '%s(%%s, %s)' % (self.transform, f.srid) if hasattr(value, 'expression'): # If this is an F expression, then we don't really want # a placeholder and instead substitute in the column # of the expression. placeholder = placeholder % self.get_expression_column(value) return placeholder def _get_postgis_func(self, func): """ Helper routine for calling PostGIS functions and returning their result. """ # Close out the connection. See #9437. with self.connection.temporary_connection() as cursor: cursor.execute('SELECT %s()' % func) return cursor.fetchone()[0] def postgis_geos_version(self): "Returns the version of the GEOS library used with PostGIS." return self._get_postgis_func('postgis_geos_version') def postgis_lib_version(self): "Returns the version number of the PostGIS library used with PostgreSQL." return self._get_postgis_func('postgis_lib_version') def postgis_proj_version(self): "Returns the version of the PROJ.4 library used with PostGIS." return self._get_postgis_func('postgis_proj_version') def postgis_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_version') def postgis_full_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_full_version') def postgis_version_tuple(self): """ Returns the PostGIS version as a tuple (version string, major, minor, subminor). """ # Getting the PostGIS version version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse PostGIS version string: %s' % version) return (version, major, minor1, minor2) def proj_version_tuple(self): """ Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers. """ proj_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostGIS.') def num_params(self, lookup_type, num_param):
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): """ Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field. """ alias, col, db_type = lvalue # Getting the quoted geometry column. geo_col = '%s.%s' % (qn(alias), qn(col)) if lookup_type in self.geometry_operators: if field.geography and not lookup_type in self.geography_operators: raise ValueError('PostGIS geography does not support the ' '"%s" lookup.' % lookup_type) # Handling a PostGIS operator. op = self.geometry_operators[lookup_type] return op.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif lookup_type in self.geometry_functions: if field.geography and not lookup_type in self.geography_functions: raise ValueError('PostGIS geography type does not support the ' '"%s" lookup.' % lookup_type) # See if a PostGIS geometry function matches the lookup type. tmp = self.geometry_functions[lookup_type] # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # distance lookups. if isinstance(tmp, tuple): # First element of tuple is the PostGISOperation instance, and the # second element is either the type or a tuple of acceptable types # that may passed in as further parameters for the lookup type. op, arg_type = tmp # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, (tuple, list)): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) # Geometry is first element of lookup tuple. geom = value[0] # Number of valid tuple parameters depends on the lookup type. nparams = len(value) if not self.num_params(lookup_type, nparams): raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) # For lookup type `relate`, the op instance is not yet created (has # to be instantiated here to check the pattern parameter). if lookup_type == 'relate': op = op(self.geom_func_prefix, value[1]) elif lookup_type in self.distance_functions and lookup_type != 'dwithin': if not field.geography and field.geodetic(self.connection): # Geodetic distances are only available from Points to # PointFields on PostGIS 1.4 and below. if not self.connection.ops.geography: if field.geom_type != 'POINT': raise ValueError('PostGIS spherical operations are only valid on PointFields.') if str(geom.geom_type) != 'Point': raise ValueError('PostGIS geometry distance parameter is required to be of type Point.') # Setting up the geodetic operation appropriately. if nparams == 3 and value[2] == 'spheroid': op = op['spheroid'] else: op = op['sphere'] else: op = op['cartesian'] else: op = tmp geom = value # Calling the `as_sql` function on the operation instance. return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, ('' if value else 'NOT ')), [] raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__ if not self.check_aggregate_support(agg): raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name) agg_name = agg_name.lower() if agg_name == 'union': agg_name += 'agg' sql_template = '%(function)s(%(field)s)' sql_function = getattr(self, agg_name) return sql_template, sql_function # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.postgis.models import GeometryColumns return GeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.postgis.models import SpatialRefSys return SpatialRefSys
""" Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type. """ def exactly_two(np): return np == 2 def two_to_three(np): return np >= 2 and np <=3 if (lookup_type in self.distance_functions and lookup_type != 'dwithin'): return two_to_three(num_param) else: return exactly_two(num_param)
identifier_body
Attribute.ts
/* Copyright 2016 Ling Zhang Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
* Attribute. extend from Object is required for type checking of { } attribute */ export interface Attribute extends Object { /** * Before decoration hook. Return false to stop decorate this attribute to a class * * NOTE: we must define something on the interface * * @param {Object | Function} target * @param {string | Symbol} key * @param {PropertyDescriptor} descriptor * @returns {boolean} */ beforeDecorate?(target: object | Function, key?: string | symbol, descriptor?: PropertyDescriptor | number): boolean; /** * Get an interceptor for this attribute * * @param target * @param params * @param receiver */ readonly interceptor?: Interceptor; }
import { Interceptor } from './Interceptor'; /**
random_line_split
init-page.tsx
import * as React from 'react'; import Container from '../components/container'; import { setWine } from '../api/wine'; import { Link } from 'react-router'; export interface ICreatePageProps extends React.Props<any> {} export interface ICreatePageState { isLoading?: boolean; showModal?: boolean; } const styles = { style1: { width: '80%', height: '550px', fontFamily: 'Andika', fontSize: '36px', color: 'white', backgroundImage: 'url(\'assets/bg.jpg\')', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', marginTop: '-19px', padding: '180px', textSlign: 'center', textShadow: '1px 1px 1px #000' }, style2: { marginRight: '6px' }, style3: { opacity: '.9', textAlign: 'center' }, style4: { position: 'static', visibility: 'visible', width: '61px', height: '20px' }, style5: { display: 'inline-block', margin: '1%' }, style6: { textAlign: 'center' }, style7: { fontStyle: 'none', background: 'white', padding: '9px 14px', fontSize: '16px', lineHeight: 'normal', borderRadius: '5px', color: 'black', fontWeight: '200', textShadow: 'rgba(0, 0, 0, 0.39) 1px 1px 1px', margin: '5px' } }; class InitPage extends React.Component<ICreatePageProps, ICreatePageState> { componentWillMount() { this.setState({ isLoading: false, showModal: false }); }; onSubmit(values) { setWine(values); } render() { return ( <div> <Container size={0} style={styles.style1} center> <div className="home-hero"> <h1>Welcome to React Cellar</h1> <h3> A sample app built with React, Bootstrap, Node.js, and MongoDB </h3> <br></br> <div style={styles.style3}> <Link className="btn btn-large" to="/list" style={styles.style7} > <img src="http://nodecellar.coenraets.org/img/wine.png" className="pull-left" style={ styles.style2 }/> Start Browsing<br/>Node Cellar </Link> <a className="btn btn-large" href="https://github.com/ayxos/react-cellar" style={styles.style7}> <img src="http://nodecellar.coenraets.org/img/github.png" className="pull-left" style={styles.style2}/> View Project <br/>on GitHub </a> </div> </div> </Container> <div className="container"> <ul className="bs-docs-social-buttons" style={styles.style6}> <li style={styles.style5}> <a className="github-button" href="https://github.com/ayxos" data-style="mega" data-count-href="/ayxos/followers" data-count-api="/users/ayxos#followers" data-count-aria-label="# followers on GitHub" aria-label="Follow @ayxos on GitHub"> Follow @ayxos </a> </li> <li style={styles.style5}> <a className="github-button" href="https://github.com/ayxos/react-cellar" data-icon="octicon-star" data-style="mega" data-count-href="/ayxos/react-cellar/stargazers" data-count-api="/repos/ayxos/react-cellar#stargazers_count" data-count-aria-label="# stargazers on GitHub" aria-label="Star ayxos/react-cellar on GitHub"> Star</a> </li> <li style={styles.style5}>
<a className="github-button" href="https://github.com/ayxos/react-cellar/fork" data-icon="octicon-repo-forked" data-style="mega" data-count-href="/ayxos/react-cellar/network" data-count-api="/repos/ayxos/react-cellar#forks_count" data-count-aria-label="# forks on GitHub" aria-label="Fork ayxos/react-cellar on GitHub"> Fork </a> </li> <li className="follow-btn" style={styles.style5}> <a href="https://twitter.com/ayxos" className="twitter-follow-button" data-size="large" data-show-count="false"/> </li> </ul> </div> </div> ); } } export default InitPage;
random_line_split
init-page.tsx
import * as React from 'react'; import Container from '../components/container'; import { setWine } from '../api/wine'; import { Link } from 'react-router'; export interface ICreatePageProps extends React.Props<any> {} export interface ICreatePageState { isLoading?: boolean; showModal?: boolean; } const styles = { style1: { width: '80%', height: '550px', fontFamily: 'Andika', fontSize: '36px', color: 'white', backgroundImage: 'url(\'assets/bg.jpg\')', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', marginTop: '-19px', padding: '180px', textSlign: 'center', textShadow: '1px 1px 1px #000' }, style2: { marginRight: '6px' }, style3: { opacity: '.9', textAlign: 'center' }, style4: { position: 'static', visibility: 'visible', width: '61px', height: '20px' }, style5: { display: 'inline-block', margin: '1%' }, style6: { textAlign: 'center' }, style7: { fontStyle: 'none', background: 'white', padding: '9px 14px', fontSize: '16px', lineHeight: 'normal', borderRadius: '5px', color: 'black', fontWeight: '200', textShadow: 'rgba(0, 0, 0, 0.39) 1px 1px 1px', margin: '5px' } }; class
extends React.Component<ICreatePageProps, ICreatePageState> { componentWillMount() { this.setState({ isLoading: false, showModal: false }); }; onSubmit(values) { setWine(values); } render() { return ( <div> <Container size={0} style={styles.style1} center> <div className="home-hero"> <h1>Welcome to React Cellar</h1> <h3> A sample app built with React, Bootstrap, Node.js, and MongoDB </h3> <br></br> <div style={styles.style3}> <Link className="btn btn-large" to="/list" style={styles.style7} > <img src="http://nodecellar.coenraets.org/img/wine.png" className="pull-left" style={ styles.style2 }/> Start Browsing<br/>Node Cellar </Link> <a className="btn btn-large" href="https://github.com/ayxos/react-cellar" style={styles.style7}> <img src="http://nodecellar.coenraets.org/img/github.png" className="pull-left" style={styles.style2}/> View Project <br/>on GitHub </a> </div> </div> </Container> <div className="container"> <ul className="bs-docs-social-buttons" style={styles.style6}> <li style={styles.style5}> <a className="github-button" href="https://github.com/ayxos" data-style="mega" data-count-href="/ayxos/followers" data-count-api="/users/ayxos#followers" data-count-aria-label="# followers on GitHub" aria-label="Follow @ayxos on GitHub"> Follow @ayxos </a> </li> <li style={styles.style5}> <a className="github-button" href="https://github.com/ayxos/react-cellar" data-icon="octicon-star" data-style="mega" data-count-href="/ayxos/react-cellar/stargazers" data-count-api="/repos/ayxos/react-cellar#stargazers_count" data-count-aria-label="# stargazers on GitHub" aria-label="Star ayxos/react-cellar on GitHub"> Star</a> </li> <li style={styles.style5}> <a className="github-button" href="https://github.com/ayxos/react-cellar/fork" data-icon="octicon-repo-forked" data-style="mega" data-count-href="/ayxos/react-cellar/network" data-count-api="/repos/ayxos/react-cellar#forks_count" data-count-aria-label="# forks on GitHub" aria-label="Fork ayxos/react-cellar on GitHub"> Fork </a> </li> <li className="follow-btn" style={styles.style5}> <a href="https://twitter.com/ayxos" className="twitter-follow-button" data-size="large" data-show-count="false"/> </li> </ul> </div> </div> ); } } export default InitPage;
InitPage
identifier_name
init-page.tsx
import * as React from 'react'; import Container from '../components/container'; import { setWine } from '../api/wine'; import { Link } from 'react-router'; export interface ICreatePageProps extends React.Props<any> {} export interface ICreatePageState { isLoading?: boolean; showModal?: boolean; } const styles = { style1: { width: '80%', height: '550px', fontFamily: 'Andika', fontSize: '36px', color: 'white', backgroundImage: 'url(\'assets/bg.jpg\')', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', marginTop: '-19px', padding: '180px', textSlign: 'center', textShadow: '1px 1px 1px #000' }, style2: { marginRight: '6px' }, style3: { opacity: '.9', textAlign: 'center' }, style4: { position: 'static', visibility: 'visible', width: '61px', height: '20px' }, style5: { display: 'inline-block', margin: '1%' }, style6: { textAlign: 'center' }, style7: { fontStyle: 'none', background: 'white', padding: '9px 14px', fontSize: '16px', lineHeight: 'normal', borderRadius: '5px', color: 'black', fontWeight: '200', textShadow: 'rgba(0, 0, 0, 0.39) 1px 1px 1px', margin: '5px' } }; class InitPage extends React.Component<ICreatePageProps, ICreatePageState> { componentWillMount()
; onSubmit(values) { setWine(values); } render() { return ( <div> <Container size={0} style={styles.style1} center> <div className="home-hero"> <h1>Welcome to React Cellar</h1> <h3> A sample app built with React, Bootstrap, Node.js, and MongoDB </h3> <br></br> <div style={styles.style3}> <Link className="btn btn-large" to="/list" style={styles.style7} > <img src="http://nodecellar.coenraets.org/img/wine.png" className="pull-left" style={ styles.style2 }/> Start Browsing<br/>Node Cellar </Link> <a className="btn btn-large" href="https://github.com/ayxos/react-cellar" style={styles.style7}> <img src="http://nodecellar.coenraets.org/img/github.png" className="pull-left" style={styles.style2}/> View Project <br/>on GitHub </a> </div> </div> </Container> <div className="container"> <ul className="bs-docs-social-buttons" style={styles.style6}> <li style={styles.style5}> <a className="github-button" href="https://github.com/ayxos" data-style="mega" data-count-href="/ayxos/followers" data-count-api="/users/ayxos#followers" data-count-aria-label="# followers on GitHub" aria-label="Follow @ayxos on GitHub"> Follow @ayxos </a> </li> <li style={styles.style5}> <a className="github-button" href="https://github.com/ayxos/react-cellar" data-icon="octicon-star" data-style="mega" data-count-href="/ayxos/react-cellar/stargazers" data-count-api="/repos/ayxos/react-cellar#stargazers_count" data-count-aria-label="# stargazers on GitHub" aria-label="Star ayxos/react-cellar on GitHub"> Star</a> </li> <li style={styles.style5}> <a className="github-button" href="https://github.com/ayxos/react-cellar/fork" data-icon="octicon-repo-forked" data-style="mega" data-count-href="/ayxos/react-cellar/network" data-count-api="/repos/ayxos/react-cellar#forks_count" data-count-aria-label="# forks on GitHub" aria-label="Fork ayxos/react-cellar on GitHub"> Fork </a> </li> <li className="follow-btn" style={styles.style5}> <a href="https://twitter.com/ayxos" className="twitter-follow-button" data-size="large" data-show-count="false"/> </li> </ul> </div> </div> ); } } export default InitPage;
{ this.setState({ isLoading: false, showModal: false }); }
identifier_body
objects-owned-object-borrowed-method-headerless.rs
// // 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 invoked `&self` methods on owned objects where the values // closed over do not contain managed values, and thus the boxes do // not have headers. trait FooTrait { fn foo(&self) -> uint; } struct BarStruct { x: uint } impl FooTrait for BarStruct { fn foo(&self) -> uint { self.x } } pub fn main() { let foos: Vec<Box<FooTrait>> = vec!( box BarStruct{ x: 0 } as Box<FooTrait>, box BarStruct{ x: 1 } as Box<FooTrait>, box BarStruct{ x: 2 } as Box<FooTrait> ); for i in range(0u, foos.len()) { assert_eq!(i, foos[i].foo()); } }
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
objects-owned-object-borrowed-method-headerless.rs
// Copyright 2013 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 invoked `&self` methods on owned objects where the values // closed over do not contain managed values, and thus the boxes do // not have headers. trait FooTrait { fn foo(&self) -> uint; } struct
{ x: uint } impl FooTrait for BarStruct { fn foo(&self) -> uint { self.x } } pub fn main() { let foos: Vec<Box<FooTrait>> = vec!( box BarStruct{ x: 0 } as Box<FooTrait>, box BarStruct{ x: 1 } as Box<FooTrait>, box BarStruct{ x: 2 } as Box<FooTrait> ); for i in range(0u, foos.len()) { assert_eq!(i, foos[i].foo()); } }
BarStruct
identifier_name
intrinsic-raw_eq-const.rs
// run-pass #![feature(core_intrinsics)] #![feature(const_intrinsic_raw_eq)] #![deny(const_err)] pub fn
() { use std::intrinsics::raw_eq; const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) }; assert!(RAW_EQ_I32_TRUE); const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) }; assert!(!RAW_EQ_I32_FALSE); const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') }; assert!(RAW_EQ_CHAR_TRUE); const RAW_EQ_CHAR_FALSE: bool = unsafe { raw_eq(&'a', &'A') }; assert!(!RAW_EQ_CHAR_FALSE); const RAW_EQ_ARRAY_TRUE: bool = unsafe { raw_eq(&[13_u8, 42], &[13, 42]) }; assert!(RAW_EQ_ARRAY_TRUE); const RAW_EQ_ARRAY_FALSE: bool = unsafe { raw_eq(&[13_u8, 42], &[42, 13]) }; assert!(!RAW_EQ_ARRAY_FALSE); }
main
identifier_name
intrinsic-raw_eq-const.rs
// run-pass #![feature(core_intrinsics)] #![feature(const_intrinsic_raw_eq)] #![deny(const_err)] pub fn main()
{ use std::intrinsics::raw_eq; const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) }; assert!(RAW_EQ_I32_TRUE); const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) }; assert!(!RAW_EQ_I32_FALSE); const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') }; assert!(RAW_EQ_CHAR_TRUE); const RAW_EQ_CHAR_FALSE: bool = unsafe { raw_eq(&'a', &'A') }; assert!(!RAW_EQ_CHAR_FALSE); const RAW_EQ_ARRAY_TRUE: bool = unsafe { raw_eq(&[13_u8, 42], &[13, 42]) }; assert!(RAW_EQ_ARRAY_TRUE); const RAW_EQ_ARRAY_FALSE: bool = unsafe { raw_eq(&[13_u8, 42], &[42, 13]) }; assert!(!RAW_EQ_ARRAY_FALSE); }
identifier_body
intrinsic-raw_eq-const.rs
// run-pass #![feature(core_intrinsics)] #![feature(const_intrinsic_raw_eq)] #![deny(const_err)] pub fn main() { use std::intrinsics::raw_eq; const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) }; assert!(RAW_EQ_I32_TRUE); const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) }; assert!(!RAW_EQ_I32_FALSE);
const RAW_EQ_CHAR_FALSE: bool = unsafe { raw_eq(&'a', &'A') }; assert!(!RAW_EQ_CHAR_FALSE); const RAW_EQ_ARRAY_TRUE: bool = unsafe { raw_eq(&[13_u8, 42], &[13, 42]) }; assert!(RAW_EQ_ARRAY_TRUE); const RAW_EQ_ARRAY_FALSE: bool = unsafe { raw_eq(&[13_u8, 42], &[42, 13]) }; assert!(!RAW_EQ_ARRAY_FALSE); }
const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') }; assert!(RAW_EQ_CHAR_TRUE);
random_line_split
WikipediaService.ts
import { RemoteAPIService } from './RemoteAPIService'; /** * Wikipedia retrieval service */ export class
extends RemoteAPIService { private static jobName = 'Wikipedia'; /** * Init the queue with the number of workers and a specific job */ public static init() { super.init(); this.workers = +process.env.WIKIPEDIA_WORKERS; // Register the queue's processing behaviour this.queue.process(this.jobName, this.workers, (job, done) => { // Fire a request this.get(job.data.options, done); }); } /** * Get a glimpse of the artist's Wikipedia page */ public static async getArtist(name: string): Promise<any> { const data = { options: { host: 'en.wikipedia.org', path: `/w/api.php?action=query&format=json&prop=extracts&exintro=true&redirects=true&titles=${name}`, headers: {'user-agent': 'music-api (https://github.com/alcappello/music-api; alessandro@cappello.se)'}, }, }; return this.getWithPromise(this.jobName, data); } }
WikipediaService
identifier_name
WikipediaService.ts
import { RemoteAPIService } from './RemoteAPIService'; /** * Wikipedia retrieval service */
private static jobName = 'Wikipedia'; /** * Init the queue with the number of workers and a specific job */ public static init() { super.init(); this.workers = +process.env.WIKIPEDIA_WORKERS; // Register the queue's processing behaviour this.queue.process(this.jobName, this.workers, (job, done) => { // Fire a request this.get(job.data.options, done); }); } /** * Get a glimpse of the artist's Wikipedia page */ public static async getArtist(name: string): Promise<any> { const data = { options: { host: 'en.wikipedia.org', path: `/w/api.php?action=query&format=json&prop=extracts&exintro=true&redirects=true&titles=${name}`, headers: {'user-agent': 'music-api (https://github.com/alcappello/music-api; alessandro@cappello.se)'}, }, }; return this.getWithPromise(this.jobName, data); } }
export class WikipediaService extends RemoteAPIService {
random_line_split
index.d.ts
// Type definitions for node-srp // Project: https://github.com/mozilla/node-srp // Definitions by: Pat Smuk <https://github.com/Patman64> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="bignum" /> /// <reference types="node" /> import * as BigNum from 'bignum'; export = SRP; declare namespace SRP { export interface Params { N_length_bits: number; N: BigNum; g: BigNum; hash: string; } export var params: { [bits: string]: Params; }; /** * The verifier is calculated as described in Section 3 of [SRP-RFC]. * We give the algorithm here for convenience. * * The verifier (v) is computed based on the salt (s), user name (I), * password (P), and group parameters (N, g). * * x = H(s | H(I | ":" | P)) * v = g^x % N * * @param {Params} params group parameters, with .N, .g, .hash * @param {Buffer} salt salt * @param {Buffer} I user identity * @param {Buffer} P user password * * @returns {Buffer} */ export function computeVerifier(params: Params, salt: Buffer, I: Buffer, P: Buffer): Buffer; /** * Generate a random key. * * @param {number} bytes length of key (default=32) * @param {function} callback function to call with err,key */ export function genKey(bytes: number, callback: (error: Error, key: Buffer) => void): void; /** * Generate a random 32-byte key. * * @param {function} callback function to call with err,key */ export function genKey(callback: (error: Error, key: Buffer) => void): void; export class
{ constructor(params: Params, salt: Buffer, identity: Buffer, password: Buffer, secret1: Buffer); computeA(): Buffer; setB(B: Buffer): void; computeM1(): Buffer; checkM2(M2: Buffer): void; computeK(): Buffer; } export class Server { constructor(params: Params, verifier: Buffer, secret2: Buffer); computeB(): Buffer; setA(A: Buffer): void; checkM1(M1: Buffer): Buffer; computeK(): Buffer; } }
Client
identifier_name
index.d.ts
// Type definitions for node-srp // Project: https://github.com/mozilla/node-srp // Definitions by: Pat Smuk <https://github.com/Patman64> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="bignum" /> /// <reference types="node" /> import * as BigNum from 'bignum'; export = SRP; declare namespace SRP { export interface Params { N_length_bits: number; N: BigNum; g: BigNum; hash: string; } export var params: { [bits: string]: Params; }; /** * The verifier is calculated as described in Section 3 of [SRP-RFC]. * We give the algorithm here for convenience. * * The verifier (v) is computed based on the salt (s), user name (I), * password (P), and group parameters (N, g). * * x = H(s | H(I | ":" | P)) * v = g^x % N * * @param {Params} params group parameters, with .N, .g, .hash * @param {Buffer} salt salt * @param {Buffer} I user identity * @param {Buffer} P user password * * @returns {Buffer} */ export function computeVerifier(params: Params, salt: Buffer, I: Buffer, P: Buffer): Buffer; /** * Generate a random key. * * @param {number} bytes length of key (default=32) * @param {function} callback function to call with err,key */ export function genKey(bytes: number, callback: (error: Error, key: Buffer) => void): void; /** * Generate a random 32-byte key. * * @param {function} callback function to call with err,key */ export function genKey(callback: (error: Error, key: Buffer) => void): void; export class Client { constructor(params: Params, salt: Buffer, identity: Buffer, password: Buffer, secret1: Buffer); computeA(): Buffer; setB(B: Buffer): void;
} export class Server { constructor(params: Params, verifier: Buffer, secret2: Buffer); computeB(): Buffer; setA(A: Buffer): void; checkM1(M1: Buffer): Buffer; computeK(): Buffer; } }
computeM1(): Buffer; checkM2(M2: Buffer): void; computeK(): Buffer;
random_line_split
main.rs
extern crate parolrs; extern crate sodiumoxide; use parolrs::core::{Parols, Parol}; use parolrs::utils::{load_database, save_database}; use sodiumoxide::crypto::secretbox::gen_nonce; // in 9.90user 3.55system 0:14.92elapsed 90%CPU :) fn main() { let mut parols = Parols::new(); for i in 0 .. 100_000 { let parol = Parol::new_with_arguments(
"Ogromny", "admin", "blabla", ); parols.push(parol); } for i in 0 .. 100 { let nonce = gen_nonce(); save_database(&parols, &nonce, "admin").unwrap(); if i == 99 { println!("load_database(\"admin\").ok().unwrap() = {:#?}", load_database("admin").ok().unwrap()); } else { load_database("admin").ok().unwrap(); } } }
&format!("tox{}", i),
random_line_split
main.rs
extern crate parolrs; extern crate sodiumoxide; use parolrs::core::{Parols, Parol}; use parolrs::utils::{load_database, save_database}; use sodiumoxide::crypto::secretbox::gen_nonce; // in 9.90user 3.55system 0:14.92elapsed 90%CPU :) fn
() { let mut parols = Parols::new(); for i in 0 .. 100_000 { let parol = Parol::new_with_arguments( &format!("tox{}", i), "Ogromny", "admin", "blabla", ); parols.push(parol); } for i in 0 .. 100 { let nonce = gen_nonce(); save_database(&parols, &nonce, "admin").unwrap(); if i == 99 { println!("load_database(\"admin\").ok().unwrap() = {:#?}", load_database("admin").ok().unwrap()); } else { load_database("admin").ok().unwrap(); } } }
main
identifier_name
main.rs
extern crate parolrs; extern crate sodiumoxide; use parolrs::core::{Parols, Parol}; use parolrs::utils::{load_database, save_database}; use sodiumoxide::crypto::secretbox::gen_nonce; // in 9.90user 3.55system 0:14.92elapsed 90%CPU :) fn main() { let mut parols = Parols::new(); for i in 0 .. 100_000 { let parol = Parol::new_with_arguments( &format!("tox{}", i), "Ogromny", "admin", "blabla", ); parols.push(parol); } for i in 0 .. 100 { let nonce = gen_nonce(); save_database(&parols, &nonce, "admin").unwrap(); if i == 99 { println!("load_database(\"admin\").ok().unwrap() = {:#?}", load_database("admin").ok().unwrap()); } else
} }
{ load_database("admin").ok().unwrap(); }
conditional_block
main.rs
extern crate parolrs; extern crate sodiumoxide; use parolrs::core::{Parols, Parol}; use parolrs::utils::{load_database, save_database}; use sodiumoxide::crypto::secretbox::gen_nonce; // in 9.90user 3.55system 0:14.92elapsed 90%CPU :) fn main()
{ let mut parols = Parols::new(); for i in 0 .. 100_000 { let parol = Parol::new_with_arguments( &format!("tox{}", i), "Ogromny", "admin", "blabla", ); parols.push(parol); } for i in 0 .. 100 { let nonce = gen_nonce(); save_database(&parols, &nonce, "admin").unwrap(); if i == 99 { println!("load_database(\"admin\").ok().unwrap() = {:#?}", load_database("admin").ok().unwrap()); } else { load_database("admin").ok().unwrap(); } } }
identifier_body
codemirror.component.js
/* Misojs Codemirror component */ var m = require('mithril'), basePath = "external/codemirror/", pjson = require("./package.json"); // Here we have a few fixes to make CM work in node - we only setup each, // if they don't already exist, otherwise we would override the browser global.document = global.document || {}; global.document.createElement = global.document.createElement || function(){ return { setAttribute: function(){} }; }; global.window = global.window || {}; global.window.getSelection = global.window.getSelection || function(){ return false; }; global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36"; // Grab code mirror and the javascript language // Note: you cannot dynamically require with browserify, // so we must get whatever modes we need here. // If you need other languages, simply equire them statically in your program. var CodeMirror = require('codemirror'); require("codemirror/mode/javascript/javascript.js"); require("codemirror/mode/htmlmixed/htmlmixed.js"); require("codemirror/mode/css/css.js"); // Our component var CodemirrorComponent = { // Returns a textarea view: function(ctrl, attrs) { return m("div", [ // It is ok to include CSS here - the browser will cache it, // though a more ideal setup would be the ability to load only // once when required. m("LINK", { href: basePath + "lib/codemirror.css", rel: "stylesheet"}), m("textarea", {config: CodemirrorComponent.config(attrs)}, attrs.value()) ]); }, config: function(attrs) { return function(element, isInitialized) { if(typeof CodeMirror !== 'undefined') { if (!isInitialized) {
var editor = CodeMirror.fromTextArea(element, { lineNumbers: true }); editor.on("change", function(instance, object) { m.startComputation(); attrs.value(editor.doc.getValue()); if (typeof attrs.onchange == "function"){ attrs.onchange(instance, object); } m.endComputation(); }); } } else { console.warn('ERROR: You need Codemirror in the page'); } }; } }; // Allow the user to pass in arguments when loading. module.exports = function(args){ if(args && args.basePath) { basePath = args.basePath; } return CodemirrorComponent; };
random_line_split
codemirror.component.js
/* Misojs Codemirror component */ var m = require('mithril'), basePath = "external/codemirror/", pjson = require("./package.json"); // Here we have a few fixes to make CM work in node - we only setup each, // if they don't already exist, otherwise we would override the browser global.document = global.document || {}; global.document.createElement = global.document.createElement || function(){ return { setAttribute: function(){} }; }; global.window = global.window || {}; global.window.getSelection = global.window.getSelection || function(){ return false; }; global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36"; // Grab code mirror and the javascript language // Note: you cannot dynamically require with browserify, // so we must get whatever modes we need here. // If you need other languages, simply equire them statically in your program. var CodeMirror = require('codemirror'); require("codemirror/mode/javascript/javascript.js"); require("codemirror/mode/htmlmixed/htmlmixed.js"); require("codemirror/mode/css/css.js"); // Our component var CodemirrorComponent = { // Returns a textarea view: function(ctrl, attrs) { return m("div", [ // It is ok to include CSS here - the browser will cache it, // though a more ideal setup would be the ability to load only // once when required. m("LINK", { href: basePath + "lib/codemirror.css", rel: "stylesheet"}), m("textarea", {config: CodemirrorComponent.config(attrs)}, attrs.value()) ]); }, config: function(attrs) { return function(element, isInitialized) { if(typeof CodeMirror !== 'undefined') { if (!isInitialized) { var editor = CodeMirror.fromTextArea(element, { lineNumbers: true }); editor.on("change", function(instance, object) { m.startComputation(); attrs.value(editor.doc.getValue()); if (typeof attrs.onchange == "function"){ attrs.onchange(instance, object); } m.endComputation(); }); } } else { console.warn('ERROR: You need Codemirror in the page'); } }; } }; // Allow the user to pass in arguments when loading. module.exports = function(args){ if(args && args.basePath)
return CodemirrorComponent; };
{ basePath = args.basePath; }
conditional_block
rec-align-u64.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. // xfail-fast: check-fast screws up repr paths // Issue #2303 use std::sys; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> uint; pub fn min_align_of<T>() -> uint; } } // This is the type with the questionable alignment struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing struct Outer { c8: u8, t: Inner } #[cfg(target_os = "linux")] #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> uint { 4u } pub fn
() -> uint { 12u } } #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "win32")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "android")] mod m { #[cfg(target_arch = "arm")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } pub fn main() { unsafe { let x = Outer {c8: 22u8, t: Inner {c64: 44u64}}; // Send it through the shape code let y = format!("{:?}", x); info2!("align inner = {}", rusti::min_align_of::<Inner>()); info2!("size outer = {}", sys::size_of::<Outer>()); info2!("y = {}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(sys::size_of::<Outer>(), m::m::size()); assert_eq!(y, ~"Outer{c8: 22u8, t: Inner{c64: 44u64}}"); } }
size
identifier_name
rec-align-u64.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. // xfail-fast: check-fast screws up repr paths // Issue #2303 use std::sys; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> uint; pub fn min_align_of<T>() -> uint; } } // This is the type with the questionable alignment struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing struct Outer { c8: u8, t: Inner } #[cfg(target_os = "linux")] #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> uint
pub fn size() -> uint { 12u } } #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "win32")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "android")] mod m { #[cfg(target_arch = "arm")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } pub fn main() { unsafe { let x = Outer {c8: 22u8, t: Inner {c64: 44u64}}; // Send it through the shape code let y = format!("{:?}", x); info2!("align inner = {}", rusti::min_align_of::<Inner>()); info2!("size outer = {}", sys::size_of::<Outer>()); info2!("y = {}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(sys::size_of::<Outer>(), m::m::size()); assert_eq!(y, ~"Outer{c8: 22u8, t: Inner{c64: 44u64}}"); } }
{ 4u }
identifier_body
rec-align-u64.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. //
// option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast: check-fast screws up repr paths // Issue #2303 use std::sys; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> uint; pub fn min_align_of<T>() -> uint; } } // This is the type with the questionable alignment struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing struct Outer { c8: u8, t: Inner } #[cfg(target_os = "linux")] #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> uint { 4u } pub fn size() -> uint { 12u } } #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "win32")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "android")] mod m { #[cfg(target_arch = "arm")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } pub fn main() { unsafe { let x = Outer {c8: 22u8, t: Inner {c64: 44u64}}; // Send it through the shape code let y = format!("{:?}", x); info2!("align inner = {}", rusti::min_align_of::<Inner>()); info2!("size outer = {}", sys::size_of::<Outer>()); info2!("y = {}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(sys::size_of::<Outer>(), m::m::size()); assert_eq!(y, ~"Outer{c8: 22u8, t: Inner{c64: 44u64}}"); } }
// 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
random_line_split
nopromise.js
/* * NoPromise: Promise A+ compliant implementation, also with ES6 interface * Copyright 2016 Avi Halachmi (:avih) http://github.com/avih/nopromise * License: MIT * * Interface, e.g. after var Promise = require("nopromise") : * new Promise(function executor(resolveFn, rejectFn) { ... }) * Promise.prototype.then(onFulfilled, onRejected) * Promise.prototype.catch(onRejected) * Promise.prototype.finally(onFinally) * Promise.resolve(value) * Promise.reject(reason) * Promise.all(iterator) * Promise.race(iterator) * * Legacy interface is also supported: * Promise.defer() or Promise.deferred() * Promise.prototype.resolve(value) * Promise.prototype.reject(reason) */ (function(G){ // Promise terminology: // State: begins with pending, may move once to fulfilled+value/rejected+reason. // Settled: at its final fulfilled/rejected state. // Resolved = sealed fate: settled or (pending and) follows another thenable T. // resolved + pending = follows only T - ignores later resolve/reject calls. // Thenable = has .then(): promise but not necessarily our implementation. // Note: the API has reject(r)/resolve(v) but not fulfill(v). that is because: // resolve(v) already fulfills with value v if v is not a promise. // if v is a promise then it should be followed - not be a fulfilled value. // hence resolve(v) either fulfills with v, or follows + seals the fate to v. var globalQ, async, staticNativePromise, FULFILLED = 1, REJECTED = 2, FUNCTION = "function"; // Try to find the fastest asynchronous scheduler for this environment: // setImmediate -> native Promise scheduler -> setTimeout async = this.setImmediate; // nodejs, IE 10+ try { staticNativePromise = Promise.resolve(); async = async || function(f) { staticNativePromise.then(f) }; // Firefox/Chrome } catch (e) {} async = async || setTimeout; // IE < 10, others // The invariant between internalAsync and dequeue is that if globalQ is thuthy, // then a dequeue is already scheduled and will execute globalQ asynchronously, // otherwise, globalQ needs to be created and dequeue needs to be scheduled. // The elements (functions) of the globalQ array need to be invoked in order. function dequeue() { var f, tmp = globalQ.reverse(); globalQ = 0; while (f = tmp.pop()) f(); } // This is used throughout the implementation as the asynchronous scheduler. // While satisfying the contract to invoke f asynchronously, it batches // individual f's into a single group which is later iterated synchronously. function internalAsync(f) { if (globalQ) { globalQ.push(f); } else { globalQ = [f]; async(dequeue); } } // fulfill/reject a promise if it's pending, else no-op. function settle(p, state, value) { if (!p._state) { p._state = state; p._output = value; var f, arr = p._resolvers; if (arr) { // The case where `then` is called many times for the same promise // is rare, so for simplicity, we're not optimizing for it, or else // if globalQ is empty, we can just do: globalQ = p._resolvers; arr.reverse(); while (f = arr.pop()) internalAsync(f); } } } function reject(promise, reason) { promise._sealed || promise._state || settle(promise, REJECTED, reason); } // a promise's fate may be set only once. fullfill/reject trivially set its fate // (and also settle it), but resolving it with another promise P must also seal // its fate, such that no later fulfill/reject/resolve are allowed to affect its // fate - onlt P will do so once/if it settles. // promise here is always NoPromise, but x might be a value/NoPromise/thenable. function resolve(promise, x, decidingFate) { if (promise._state || (promise._sealed && !decidingFate)) return; // seal fate. only this instance of resolve can settle it [recursively] promise._sealed = 1; var then, done = 0; try { if (x == promise) { settle(promise, REJECTED, TypeError()); } else if (x instanceof NoPromise && x._state) { // we can settle synchronously if we know that x is settled and also // know how to adopt its state, which we do when x is NoPromise. settle(promise, x._state, x._output); // Check for generic thenable... which includes unsettled NoPromise. } else if ((x && typeof x == "object" || typeof x == FUNCTION) && typeof (then = x.then) == FUNCTION) { then.call(x, function(y) { done++ || resolve(promise, y, 1) }, // decidingFate function(r) { done++ || settle(promise, REJECTED, r)}); } else { settle(promise, FULFILLED, x); } } catch (e) { done++ || settle(promise, REJECTED, e); } } // Other than the prototype methods, the object may also have: // ._state : 1 if fulfilled, 2 if rejected (doesn't exist otherwise). // ._output : value if fulfilled, reason if rejected (doesn't exist otherwise). // ._resolvers: array of functions (closures) for each .then call while pending (if there were any). // ._sealed : new resolve/reject are ignored (exists if resolve was called). NoPromise.prototype = { // Each call to `then` returns a new NoPromise object and creates a closure // which is used to resolve it after then's this is fulfilled/rejected. then: function(onFulfilled, onRejected) { var _self = this, promise2 = new NoPromise; this._state ? internalAsync(promise2Resolver) : this._resolvers ? this._resolvers.push(promise2Resolver) : this._resolvers = [promise2Resolver]; return promise2; // Invoked asynchronously to `then` and after _self is settled. // _self._state here is FULFILLED/REJECTED function promise2Resolver() { var handler = _self._state == FULFILLED ? onFulfilled : onRejected; // no executor for promise2, so not yet sealed, but the legacy API // can make it already sealed here, e.g. p2=p.then(); p2.resolve(X) // So we still need to check ._sealed before settle(..) below if (typeof handler != FUNCTION) { promise2._sealed || settle(promise2, _self._state, _self._output); } else { try { resolve(promise2, handler(_self._output)); } catch (e) { reject(promise2, e); } } } }, // then catch: function(onRejected) { return this.then(undefined, onRejected); }, // P.finaly(fn) returns a promise X, and calls fn after P settles as S. // if fn throws E: X is rejected with E. // Else if fn returns a promise F: X is settled once F is settled: // If F is rejected with FJ: X is rejected with FJ. // Else: X settles as S [ignoring fn's retval or F's fulfillment value] finally: function(onFinally) { function fin_noargs() { return onFinally() } var fn; return this .then(function(v) { fn = function() { return v } }, function(r) { fn = function() { throw r } }) .then(fin_noargs, fin_noargs) .then(function finallyOK() { return fn() }); }, } // CTOR: // return new NoPromise(function(resolve, reject) { setTimeout(function() { resolve(42); }, 100); }); function NoPromise(executor) { if (executor) { // not used inside 'then' nor by the legacy interface var self = this; try { executor(function(v) { resolve(self, v) }, function(r) { reject(self, r) }); } catch (e) { reject(self, e); } } } // detect a generic thenable - same logic as at resolve(). may throw. function is_thenable(x) { return ((x && typeof x == "object") || typeof x == FUNCTION) && typeof x.then == FUNCTION; } // Static methods // -------------- // Returns a resolved/rejected promise with specified value(or promise)/reason NoPromise.resolve = function(v) { return new NoPromise(function(res, rej) { res(v) }); }; NoPromise.reject = function(r) { return new NoPromise(function(res, rej) { rej(r) }); }; // For .all and .race: we support iterators as array or array-like, and slack // when it comes to throwing on invalid iterators (we only try [].slice.call). // Static NoPromise.all(iter) returns a promise X. // If iter is empty: X fulfills synchronously to an empty array. // Else for the first promise in iter which rejects with J: X rejects a-sync with J. // Else (all fulfill): X fulfills a-sync to an array of iter's fulfilled-values // (non-promise values are considered already fulfilled with that value). NoPromise.all = function(iter) { Array.isArray(iter) || (iter = [].slice.call(iter)); var len = iter.length; if (!len) return NoPromise.resolve([]); // empty fulfills synchronously return new NoPromise(function(allful, allrej) { var rv = [], pending = 0; function fulOne(i, val) { rv[i] = val; --pending || allful(rv); } iter.forEach(function(v, i) { if (is_thenable(v))
else { rv[i] = v; } }); // Non empty but without promises - fulfills a-sync if (!pending) NoPromise.resolve(rv).then(allful); }); } // Static NoPromise.race(iter) returns a promise X: // If iter is empty: X never settles. // Else: X settles always a-sync and mirrors the first promise in iter which settles. // (non-promise values are considered already fulfilled with that value). NoPromise.race = function(iter) { return new NoPromise(function(allful, allrej) { Array.isArray(iter) || (iter = [].slice.call(iter)); iter.some(function(v, i) { if (is_thenable(v)) { v.then(allful, allrej); } else { NoPromise.resolve(v).then(allful); return true; // continuing would end up no-op } }); }); } // Legacy interface - not used elsewhere in NoPromise, used by the test suit (below) // var d = NoPromise.defer(); setTimeout(function() { d.resolve(42); }, 100); return d.promise; NoPromise.defer = function() { var d = new NoPromise; return d.promise = d; }; NoPromise.prototype.resolve = function(value) { resolve(this, value); } NoPromise.prototype.reject = function(reason) { reject(this, reason); } // End of legacy interface // Promises/A+ Compliance Test Suite // https://github.com/promises-aplus/promises-tests // nopromise.js itself can be the adapter: promises-aplus-tests ./nopromise.js // The only required modification is that it wants different names - dup below. NoPromise.deferred = NoPromise.defer; // Static legacy API NoPromise.resolved = NoPromise.resolve; // Static standard, optional but tested NoPromise.rejected = NoPromise.reject; // Static standard, optional but tested // The tests also use the legacy dynamic API: prototype.resolve(v)/.reject(r) try { module.exports = NoPromise; } catch (e) { G.NoPromise = NoPromise; } })( // used to setup a global NoPromise - not when using require("nopromise") typeof global != "undefined" ? global : typeof window != "undefined" ? window : this)
{ pending++; v.then(fulOne.bind(null, i), allrej); }
conditional_block
nopromise.js
/* * NoPromise: Promise A+ compliant implementation, also with ES6 interface * Copyright 2016 Avi Halachmi (:avih) http://github.com/avih/nopromise * License: MIT * * Interface, e.g. after var Promise = require("nopromise") : * new Promise(function executor(resolveFn, rejectFn) { ... }) * Promise.prototype.then(onFulfilled, onRejected) * Promise.prototype.catch(onRejected) * Promise.prototype.finally(onFinally) * Promise.resolve(value) * Promise.reject(reason) * Promise.all(iterator) * Promise.race(iterator) * * Legacy interface is also supported: * Promise.defer() or Promise.deferred() * Promise.prototype.resolve(value) * Promise.prototype.reject(reason) */ (function(G){ // Promise terminology: // State: begins with pending, may move once to fulfilled+value/rejected+reason. // Settled: at its final fulfilled/rejected state. // Resolved = sealed fate: settled or (pending and) follows another thenable T. // resolved + pending = follows only T - ignores later resolve/reject calls. // Thenable = has .then(): promise but not necessarily our implementation. // Note: the API has reject(r)/resolve(v) but not fulfill(v). that is because: // resolve(v) already fulfills with value v if v is not a promise. // if v is a promise then it should be followed - not be a fulfilled value. // hence resolve(v) either fulfills with v, or follows + seals the fate to v. var globalQ, async, staticNativePromise, FULFILLED = 1, REJECTED = 2, FUNCTION = "function"; // Try to find the fastest asynchronous scheduler for this environment: // setImmediate -> native Promise scheduler -> setTimeout async = this.setImmediate; // nodejs, IE 10+ try { staticNativePromise = Promise.resolve(); async = async || function(f) { staticNativePromise.then(f) }; // Firefox/Chrome } catch (e) {} async = async || setTimeout; // IE < 10, others // The invariant between internalAsync and dequeue is that if globalQ is thuthy, // then a dequeue is already scheduled and will execute globalQ asynchronously, // otherwise, globalQ needs to be created and dequeue needs to be scheduled. // The elements (functions) of the globalQ array need to be invoked in order. function dequeue() { var f, tmp = globalQ.reverse(); globalQ = 0; while (f = tmp.pop()) f(); } // This is used throughout the implementation as the asynchronous scheduler. // While satisfying the contract to invoke f asynchronously, it batches // individual f's into a single group which is later iterated synchronously. function internalAsync(f) { if (globalQ) { globalQ.push(f); } else { globalQ = [f]; async(dequeue); } } // fulfill/reject a promise if it's pending, else no-op. function settle(p, state, value) { if (!p._state) { p._state = state; p._output = value; var f, arr = p._resolvers; if (arr) { // The case where `then` is called many times for the same promise // is rare, so for simplicity, we're not optimizing for it, or else // if globalQ is empty, we can just do: globalQ = p._resolvers; arr.reverse(); while (f = arr.pop()) internalAsync(f); } } } function reject(promise, reason) { promise._sealed || promise._state || settle(promise, REJECTED, reason); } // a promise's fate may be set only once. fullfill/reject trivially set its fate // (and also settle it), but resolving it with another promise P must also seal // its fate, such that no later fulfill/reject/resolve are allowed to affect its // fate - onlt P will do so once/if it settles. // promise here is always NoPromise, but x might be a value/NoPromise/thenable. function
(promise, x, decidingFate) { if (promise._state || (promise._sealed && !decidingFate)) return; // seal fate. only this instance of resolve can settle it [recursively] promise._sealed = 1; var then, done = 0; try { if (x == promise) { settle(promise, REJECTED, TypeError()); } else if (x instanceof NoPromise && x._state) { // we can settle synchronously if we know that x is settled and also // know how to adopt its state, which we do when x is NoPromise. settle(promise, x._state, x._output); // Check for generic thenable... which includes unsettled NoPromise. } else if ((x && typeof x == "object" || typeof x == FUNCTION) && typeof (then = x.then) == FUNCTION) { then.call(x, function(y) { done++ || resolve(promise, y, 1) }, // decidingFate function(r) { done++ || settle(promise, REJECTED, r)}); } else { settle(promise, FULFILLED, x); } } catch (e) { done++ || settle(promise, REJECTED, e); } } // Other than the prototype methods, the object may also have: // ._state : 1 if fulfilled, 2 if rejected (doesn't exist otherwise). // ._output : value if fulfilled, reason if rejected (doesn't exist otherwise). // ._resolvers: array of functions (closures) for each .then call while pending (if there were any). // ._sealed : new resolve/reject are ignored (exists if resolve was called). NoPromise.prototype = { // Each call to `then` returns a new NoPromise object and creates a closure // which is used to resolve it after then's this is fulfilled/rejected. then: function(onFulfilled, onRejected) { var _self = this, promise2 = new NoPromise; this._state ? internalAsync(promise2Resolver) : this._resolvers ? this._resolvers.push(promise2Resolver) : this._resolvers = [promise2Resolver]; return promise2; // Invoked asynchronously to `then` and after _self is settled. // _self._state here is FULFILLED/REJECTED function promise2Resolver() { var handler = _self._state == FULFILLED ? onFulfilled : onRejected; // no executor for promise2, so not yet sealed, but the legacy API // can make it already sealed here, e.g. p2=p.then(); p2.resolve(X) // So we still need to check ._sealed before settle(..) below if (typeof handler != FUNCTION) { promise2._sealed || settle(promise2, _self._state, _self._output); } else { try { resolve(promise2, handler(_self._output)); } catch (e) { reject(promise2, e); } } } }, // then catch: function(onRejected) { return this.then(undefined, onRejected); }, // P.finaly(fn) returns a promise X, and calls fn after P settles as S. // if fn throws E: X is rejected with E. // Else if fn returns a promise F: X is settled once F is settled: // If F is rejected with FJ: X is rejected with FJ. // Else: X settles as S [ignoring fn's retval or F's fulfillment value] finally: function(onFinally) { function fin_noargs() { return onFinally() } var fn; return this .then(function(v) { fn = function() { return v } }, function(r) { fn = function() { throw r } }) .then(fin_noargs, fin_noargs) .then(function finallyOK() { return fn() }); }, } // CTOR: // return new NoPromise(function(resolve, reject) { setTimeout(function() { resolve(42); }, 100); }); function NoPromise(executor) { if (executor) { // not used inside 'then' nor by the legacy interface var self = this; try { executor(function(v) { resolve(self, v) }, function(r) { reject(self, r) }); } catch (e) { reject(self, e); } } } // detect a generic thenable - same logic as at resolve(). may throw. function is_thenable(x) { return ((x && typeof x == "object") || typeof x == FUNCTION) && typeof x.then == FUNCTION; } // Static methods // -------------- // Returns a resolved/rejected promise with specified value(or promise)/reason NoPromise.resolve = function(v) { return new NoPromise(function(res, rej) { res(v) }); }; NoPromise.reject = function(r) { return new NoPromise(function(res, rej) { rej(r) }); }; // For .all and .race: we support iterators as array or array-like, and slack // when it comes to throwing on invalid iterators (we only try [].slice.call). // Static NoPromise.all(iter) returns a promise X. // If iter is empty: X fulfills synchronously to an empty array. // Else for the first promise in iter which rejects with J: X rejects a-sync with J. // Else (all fulfill): X fulfills a-sync to an array of iter's fulfilled-values // (non-promise values are considered already fulfilled with that value). NoPromise.all = function(iter) { Array.isArray(iter) || (iter = [].slice.call(iter)); var len = iter.length; if (!len) return NoPromise.resolve([]); // empty fulfills synchronously return new NoPromise(function(allful, allrej) { var rv = [], pending = 0; function fulOne(i, val) { rv[i] = val; --pending || allful(rv); } iter.forEach(function(v, i) { if (is_thenable(v)) { pending++; v.then(fulOne.bind(null, i), allrej); } else { rv[i] = v; } }); // Non empty but without promises - fulfills a-sync if (!pending) NoPromise.resolve(rv).then(allful); }); } // Static NoPromise.race(iter) returns a promise X: // If iter is empty: X never settles. // Else: X settles always a-sync and mirrors the first promise in iter which settles. // (non-promise values are considered already fulfilled with that value). NoPromise.race = function(iter) { return new NoPromise(function(allful, allrej) { Array.isArray(iter) || (iter = [].slice.call(iter)); iter.some(function(v, i) { if (is_thenable(v)) { v.then(allful, allrej); } else { NoPromise.resolve(v).then(allful); return true; // continuing would end up no-op } }); }); } // Legacy interface - not used elsewhere in NoPromise, used by the test suit (below) // var d = NoPromise.defer(); setTimeout(function() { d.resolve(42); }, 100); return d.promise; NoPromise.defer = function() { var d = new NoPromise; return d.promise = d; }; NoPromise.prototype.resolve = function(value) { resolve(this, value); } NoPromise.prototype.reject = function(reason) { reject(this, reason); } // End of legacy interface // Promises/A+ Compliance Test Suite // https://github.com/promises-aplus/promises-tests // nopromise.js itself can be the adapter: promises-aplus-tests ./nopromise.js // The only required modification is that it wants different names - dup below. NoPromise.deferred = NoPromise.defer; // Static legacy API NoPromise.resolved = NoPromise.resolve; // Static standard, optional but tested NoPromise.rejected = NoPromise.reject; // Static standard, optional but tested // The tests also use the legacy dynamic API: prototype.resolve(v)/.reject(r) try { module.exports = NoPromise; } catch (e) { G.NoPromise = NoPromise; } })( // used to setup a global NoPromise - not when using require("nopromise") typeof global != "undefined" ? global : typeof window != "undefined" ? window : this)
resolve
identifier_name
nopromise.js
/* * NoPromise: Promise A+ compliant implementation, also with ES6 interface * Copyright 2016 Avi Halachmi (:avih) http://github.com/avih/nopromise * License: MIT * * Interface, e.g. after var Promise = require("nopromise") : * new Promise(function executor(resolveFn, rejectFn) { ... }) * Promise.prototype.then(onFulfilled, onRejected) * Promise.prototype.catch(onRejected) * Promise.prototype.finally(onFinally) * Promise.resolve(value) * Promise.reject(reason) * Promise.all(iterator) * Promise.race(iterator) * * Legacy interface is also supported: * Promise.defer() or Promise.deferred() * Promise.prototype.resolve(value) * Promise.prototype.reject(reason) */ (function(G){ // Promise terminology: // State: begins with pending, may move once to fulfilled+value/rejected+reason. // Settled: at its final fulfilled/rejected state. // Resolved = sealed fate: settled or (pending and) follows another thenable T. // resolved + pending = follows only T - ignores later resolve/reject calls. // Thenable = has .then(): promise but not necessarily our implementation. // Note: the API has reject(r)/resolve(v) but not fulfill(v). that is because: // resolve(v) already fulfills with value v if v is not a promise. // if v is a promise then it should be followed - not be a fulfilled value. // hence resolve(v) either fulfills with v, or follows + seals the fate to v. var globalQ, async, staticNativePromise, FULFILLED = 1, REJECTED = 2, FUNCTION = "function"; // Try to find the fastest asynchronous scheduler for this environment: // setImmediate -> native Promise scheduler -> setTimeout async = this.setImmediate; // nodejs, IE 10+ try { staticNativePromise = Promise.resolve(); async = async || function(f) { staticNativePromise.then(f) }; // Firefox/Chrome } catch (e) {} async = async || setTimeout; // IE < 10, others // The invariant between internalAsync and dequeue is that if globalQ is thuthy, // then a dequeue is already scheduled and will execute globalQ asynchronously, // otherwise, globalQ needs to be created and dequeue needs to be scheduled. // The elements (functions) of the globalQ array need to be invoked in order. function dequeue() { var f, tmp = globalQ.reverse(); globalQ = 0; while (f = tmp.pop()) f(); } // This is used throughout the implementation as the asynchronous scheduler. // While satisfying the contract to invoke f asynchronously, it batches // individual f's into a single group which is later iterated synchronously. function internalAsync(f) { if (globalQ) { globalQ.push(f); } else { globalQ = [f]; async(dequeue); } } // fulfill/reject a promise if it's pending, else no-op. function settle(p, state, value) { if (!p._state) { p._state = state; p._output = value; var f, arr = p._resolvers; if (arr) { // The case where `then` is called many times for the same promise // is rare, so for simplicity, we're not optimizing for it, or else // if globalQ is empty, we can just do: globalQ = p._resolvers; arr.reverse(); while (f = arr.pop()) internalAsync(f); } } } function reject(promise, reason) { promise._sealed || promise._state || settle(promise, REJECTED, reason); } // a promise's fate may be set only once. fullfill/reject trivially set its fate // (and also settle it), but resolving it with another promise P must also seal // its fate, such that no later fulfill/reject/resolve are allowed to affect its // fate - onlt P will do so once/if it settles. // promise here is always NoPromise, but x might be a value/NoPromise/thenable. function resolve(promise, x, decidingFate) { if (promise._state || (promise._sealed && !decidingFate)) return; // seal fate. only this instance of resolve can settle it [recursively] promise._sealed = 1; var then, done = 0; try { if (x == promise) { settle(promise, REJECTED, TypeError()); } else if (x instanceof NoPromise && x._state) { // we can settle synchronously if we know that x is settled and also // know how to adopt its state, which we do when x is NoPromise. settle(promise, x._state, x._output); // Check for generic thenable... which includes unsettled NoPromise. } else if ((x && typeof x == "object" || typeof x == FUNCTION) && typeof (then = x.then) == FUNCTION) { then.call(x, function(y) { done++ || resolve(promise, y, 1) }, // decidingFate function(r) { done++ || settle(promise, REJECTED, r)}); } else { settle(promise, FULFILLED, x); } } catch (e) { done++ || settle(promise, REJECTED, e); } } // Other than the prototype methods, the object may also have: // ._state : 1 if fulfilled, 2 if rejected (doesn't exist otherwise). // ._output : value if fulfilled, reason if rejected (doesn't exist otherwise). // ._resolvers: array of functions (closures) for each .then call while pending (if there were any). // ._sealed : new resolve/reject are ignored (exists if resolve was called). NoPromise.prototype = { // Each call to `then` returns a new NoPromise object and creates a closure // which is used to resolve it after then's this is fulfilled/rejected. then: function(onFulfilled, onRejected) { var _self = this, promise2 = new NoPromise; this._state ? internalAsync(promise2Resolver) : this._resolvers ? this._resolvers.push(promise2Resolver) : this._resolvers = [promise2Resolver]; return promise2; // Invoked asynchronously to `then` and after _self is settled. // _self._state here is FULFILLED/REJECTED function promise2Resolver() { var handler = _self._state == FULFILLED ? onFulfilled : onRejected; // no executor for promise2, so not yet sealed, but the legacy API // can make it already sealed here, e.g. p2=p.then(); p2.resolve(X) // So we still need to check ._sealed before settle(..) below if (typeof handler != FUNCTION) { promise2._sealed || settle(promise2, _self._state, _self._output); } else { try { resolve(promise2, handler(_self._output)); } catch (e) { reject(promise2, e); } } } }, // then catch: function(onRejected) { return this.then(undefined, onRejected); }, // P.finaly(fn) returns a promise X, and calls fn after P settles as S. // if fn throws E: X is rejected with E. // Else if fn returns a promise F: X is settled once F is settled: // If F is rejected with FJ: X is rejected with FJ. // Else: X settles as S [ignoring fn's retval or F's fulfillment value] finally: function(onFinally) { function fin_noargs() { return onFinally() } var fn; return this .then(function(v) { fn = function() { return v } }, function(r) { fn = function() { throw r } }) .then(fin_noargs, fin_noargs) .then(function finallyOK() { return fn() }); }, } // CTOR: // return new NoPromise(function(resolve, reject) { setTimeout(function() { resolve(42); }, 100); }); function NoPromise(executor) { if (executor) { // not used inside 'then' nor by the legacy interface var self = this; try { executor(function(v) { resolve(self, v) }, function(r) { reject(self, r) }); } catch (e) { reject(self, e); } } } // detect a generic thenable - same logic as at resolve(). may throw. function is_thenable(x) { return ((x && typeof x == "object") || typeof x == FUNCTION) && typeof x.then == FUNCTION; } // Static methods // -------------- // Returns a resolved/rejected promise with specified value(or promise)/reason NoPromise.resolve = function(v) { return new NoPromise(function(res, rej) { res(v) }); }; NoPromise.reject = function(r) { return new NoPromise(function(res, rej) { rej(r) }); }; // For .all and .race: we support iterators as array or array-like, and slack // when it comes to throwing on invalid iterators (we only try [].slice.call). // Static NoPromise.all(iter) returns a promise X. // If iter is empty: X fulfills synchronously to an empty array. // Else for the first promise in iter which rejects with J: X rejects a-sync with J. // Else (all fulfill): X fulfills a-sync to an array of iter's fulfilled-values // (non-promise values are considered already fulfilled with that value). NoPromise.all = function(iter) { Array.isArray(iter) || (iter = [].slice.call(iter)); var len = iter.length; if (!len) return NoPromise.resolve([]); // empty fulfills synchronously return new NoPromise(function(allful, allrej) { var rv = [], pending = 0; function fulOne(i, val)
iter.forEach(function(v, i) { if (is_thenable(v)) { pending++; v.then(fulOne.bind(null, i), allrej); } else { rv[i] = v; } }); // Non empty but without promises - fulfills a-sync if (!pending) NoPromise.resolve(rv).then(allful); }); } // Static NoPromise.race(iter) returns a promise X: // If iter is empty: X never settles. // Else: X settles always a-sync and mirrors the first promise in iter which settles. // (non-promise values are considered already fulfilled with that value). NoPromise.race = function(iter) { return new NoPromise(function(allful, allrej) { Array.isArray(iter) || (iter = [].slice.call(iter)); iter.some(function(v, i) { if (is_thenable(v)) { v.then(allful, allrej); } else { NoPromise.resolve(v).then(allful); return true; // continuing would end up no-op } }); }); } // Legacy interface - not used elsewhere in NoPromise, used by the test suit (below) // var d = NoPromise.defer(); setTimeout(function() { d.resolve(42); }, 100); return d.promise; NoPromise.defer = function() { var d = new NoPromise; return d.promise = d; }; NoPromise.prototype.resolve = function(value) { resolve(this, value); } NoPromise.prototype.reject = function(reason) { reject(this, reason); } // End of legacy interface // Promises/A+ Compliance Test Suite // https://github.com/promises-aplus/promises-tests // nopromise.js itself can be the adapter: promises-aplus-tests ./nopromise.js // The only required modification is that it wants different names - dup below. NoPromise.deferred = NoPromise.defer; // Static legacy API NoPromise.resolved = NoPromise.resolve; // Static standard, optional but tested NoPromise.rejected = NoPromise.reject; // Static standard, optional but tested // The tests also use the legacy dynamic API: prototype.resolve(v)/.reject(r) try { module.exports = NoPromise; } catch (e) { G.NoPromise = NoPromise; } })( // used to setup a global NoPromise - not when using require("nopromise") typeof global != "undefined" ? global : typeof window != "undefined" ? window : this)
{ rv[i] = val; --pending || allful(rv); }
identifier_body
nopromise.js
/* * NoPromise: Promise A+ compliant implementation, also with ES6 interface * Copyright 2016 Avi Halachmi (:avih) http://github.com/avih/nopromise * License: MIT * * Interface, e.g. after var Promise = require("nopromise") : * new Promise(function executor(resolveFn, rejectFn) { ... }) * Promise.prototype.then(onFulfilled, onRejected) * Promise.prototype.catch(onRejected) * Promise.prototype.finally(onFinally) * Promise.resolve(value) * Promise.reject(reason) * Promise.all(iterator) * Promise.race(iterator) * * Legacy interface is also supported: * Promise.defer() or Promise.deferred() * Promise.prototype.resolve(value) * Promise.prototype.reject(reason) */ (function(G){ // Promise terminology: // State: begins with pending, may move once to fulfilled+value/rejected+reason. // Settled: at its final fulfilled/rejected state. // Resolved = sealed fate: settled or (pending and) follows another thenable T. // resolved + pending = follows only T - ignores later resolve/reject calls. // Thenable = has .then(): promise but not necessarily our implementation. // Note: the API has reject(r)/resolve(v) but not fulfill(v). that is because: // resolve(v) already fulfills with value v if v is not a promise. // if v is a promise then it should be followed - not be a fulfilled value. // hence resolve(v) either fulfills with v, or follows + seals the fate to v. var globalQ, async, staticNativePromise, FULFILLED = 1, REJECTED = 2, FUNCTION = "function"; // Try to find the fastest asynchronous scheduler for this environment: // setImmediate -> native Promise scheduler -> setTimeout async = this.setImmediate; // nodejs, IE 10+ try { staticNativePromise = Promise.resolve(); async = async || function(f) { staticNativePromise.then(f) }; // Firefox/Chrome } catch (e) {} async = async || setTimeout; // IE < 10, others // The invariant between internalAsync and dequeue is that if globalQ is thuthy, // then a dequeue is already scheduled and will execute globalQ asynchronously, // otherwise, globalQ needs to be created and dequeue needs to be scheduled. // The elements (functions) of the globalQ array need to be invoked in order. function dequeue() { var f, tmp = globalQ.reverse(); globalQ = 0; while (f = tmp.pop()) f(); } // This is used throughout the implementation as the asynchronous scheduler. // While satisfying the contract to invoke f asynchronously, it batches // individual f's into a single group which is later iterated synchronously. function internalAsync(f) { if (globalQ) { globalQ.push(f); } else { globalQ = [f]; async(dequeue); } } // fulfill/reject a promise if it's pending, else no-op. function settle(p, state, value) { if (!p._state) { p._state = state; p._output = value; var f, arr = p._resolvers; if (arr) { // The case where `then` is called many times for the same promise // is rare, so for simplicity, we're not optimizing for it, or else // if globalQ is empty, we can just do: globalQ = p._resolvers; arr.reverse(); while (f = arr.pop()) internalAsync(f); } } } function reject(promise, reason) { promise._sealed || promise._state || settle(promise, REJECTED, reason); } // a promise's fate may be set only once. fullfill/reject trivially set its fate // (and also settle it), but resolving it with another promise P must also seal // its fate, such that no later fulfill/reject/resolve are allowed to affect its // fate - onlt P will do so once/if it settles. // promise here is always NoPromise, but x might be a value/NoPromise/thenable. function resolve(promise, x, decidingFate) { if (promise._state || (promise._sealed && !decidingFate)) return; // seal fate. only this instance of resolve can settle it [recursively] promise._sealed = 1; var then, done = 0; try { if (x == promise) { settle(promise, REJECTED, TypeError()); } else if (x instanceof NoPromise && x._state) { // we can settle synchronously if we know that x is settled and also // know how to adopt its state, which we do when x is NoPromise. settle(promise, x._state, x._output); // Check for generic thenable... which includes unsettled NoPromise. } else if ((x && typeof x == "object" || typeof x == FUNCTION) && typeof (then = x.then) == FUNCTION) { then.call(x, function(y) { done++ || resolve(promise, y, 1) }, // decidingFate function(r) { done++ || settle(promise, REJECTED, r)}); } else { settle(promise, FULFILLED, x); } } catch (e) { done++ || settle(promise, REJECTED, e); } } // Other than the prototype methods, the object may also have: // ._state : 1 if fulfilled, 2 if rejected (doesn't exist otherwise). // ._output : value if fulfilled, reason if rejected (doesn't exist otherwise). // ._resolvers: array of functions (closures) for each .then call while pending (if there were any). // ._sealed : new resolve/reject are ignored (exists if resolve was called). NoPromise.prototype = { // Each call to `then` returns a new NoPromise object and creates a closure // which is used to resolve it after then's this is fulfilled/rejected. then: function(onFulfilled, onRejected) { var _self = this, promise2 = new NoPromise; this._state ? internalAsync(promise2Resolver) : this._resolvers ? this._resolvers.push(promise2Resolver) : this._resolvers = [promise2Resolver]; return promise2; // Invoked asynchronously to `then` and after _self is settled. // _self._state here is FULFILLED/REJECTED function promise2Resolver() { var handler = _self._state == FULFILLED ? onFulfilled : onRejected; // no executor for promise2, so not yet sealed, but the legacy API // can make it already sealed here, e.g. p2=p.then(); p2.resolve(X) // So we still need to check ._sealed before settle(..) below if (typeof handler != FUNCTION) { promise2._sealed || settle(promise2, _self._state, _self._output); } else { try { resolve(promise2, handler(_self._output)); } catch (e) { reject(promise2, e); } } } }, // then catch: function(onRejected) { return this.then(undefined, onRejected); }, // P.finaly(fn) returns a promise X, and calls fn after P settles as S. // if fn throws E: X is rejected with E. // Else if fn returns a promise F: X is settled once F is settled: // If F is rejected with FJ: X is rejected with FJ. // Else: X settles as S [ignoring fn's retval or F's fulfillment value] finally: function(onFinally) { function fin_noargs() { return onFinally() } var fn; return this .then(function(v) { fn = function() { return v } }, function(r) { fn = function() { throw r } }) .then(fin_noargs, fin_noargs) .then(function finallyOK() { return fn() }); }, } // CTOR: // return new NoPromise(function(resolve, reject) { setTimeout(function() { resolve(42); }, 100); }); function NoPromise(executor) { if (executor) { // not used inside 'then' nor by the legacy interface var self = this; try { executor(function(v) { resolve(self, v) }, function(r) { reject(self, r) }); } catch (e) { reject(self, e); } } } // detect a generic thenable - same logic as at resolve(). may throw. function is_thenable(x) { return ((x && typeof x == "object") || typeof x == FUNCTION) && typeof x.then == FUNCTION; } // Static methods // -------------- // Returns a resolved/rejected promise with specified value(or promise)/reason NoPromise.resolve = function(v) { return new NoPromise(function(res, rej) { res(v) }); }; NoPromise.reject = function(r) { return new NoPromise(function(res, rej) { rej(r) }); }; // For .all and .race: we support iterators as array or array-like, and slack // when it comes to throwing on invalid iterators (we only try [].slice.call). // Static NoPromise.all(iter) returns a promise X. // If iter is empty: X fulfills synchronously to an empty array. // Else for the first promise in iter which rejects with J: X rejects a-sync with J. // Else (all fulfill): X fulfills a-sync to an array of iter's fulfilled-values // (non-promise values are considered already fulfilled with that value). NoPromise.all = function(iter) { Array.isArray(iter) || (iter = [].slice.call(iter)); var len = iter.length; if (!len) return NoPromise.resolve([]); // empty fulfills synchronously return new NoPromise(function(allful, allrej) { var rv = [], pending = 0; function fulOne(i, val) { rv[i] = val; --pending || allful(rv); } iter.forEach(function(v, i) { if (is_thenable(v)) { pending++; v.then(fulOne.bind(null, i), allrej); } else { rv[i] = v; } }); // Non empty but without promises - fulfills a-sync if (!pending) NoPromise.resolve(rv).then(allful); }); } // Static NoPromise.race(iter) returns a promise X: // If iter is empty: X never settles. // Else: X settles always a-sync and mirrors the first promise in iter which settles. // (non-promise values are considered already fulfilled with that value). NoPromise.race = function(iter) { return new NoPromise(function(allful, allrej) { Array.isArray(iter) || (iter = [].slice.call(iter)); iter.some(function(v, i) { if (is_thenable(v)) { v.then(allful, allrej); } else { NoPromise.resolve(v).then(allful); return true; // continuing would end up no-op } }); }); } // Legacy interface - not used elsewhere in NoPromise, used by the test suit (below) // var d = NoPromise.defer(); setTimeout(function() { d.resolve(42); }, 100); return d.promise; NoPromise.defer = function() {
}; NoPromise.prototype.resolve = function(value) { resolve(this, value); } NoPromise.prototype.reject = function(reason) { reject(this, reason); } // End of legacy interface // Promises/A+ Compliance Test Suite // https://github.com/promises-aplus/promises-tests // nopromise.js itself can be the adapter: promises-aplus-tests ./nopromise.js // The only required modification is that it wants different names - dup below. NoPromise.deferred = NoPromise.defer; // Static legacy API NoPromise.resolved = NoPromise.resolve; // Static standard, optional but tested NoPromise.rejected = NoPromise.reject; // Static standard, optional but tested // The tests also use the legacy dynamic API: prototype.resolve(v)/.reject(r) try { module.exports = NoPromise; } catch (e) { G.NoPromise = NoPromise; } })( // used to setup a global NoPromise - not when using require("nopromise") typeof global != "undefined" ? global : typeof window != "undefined" ? window : this)
var d = new NoPromise; return d.promise = d;
random_line_split
issue-7013.rs
// Copyright 2013 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 std::rc::RcMut; trait Foo { fn set(&mut self, v: RcMut<A>); } struct B { v: Option<RcMut<A>> }
} } struct A { v: ~Foo, } fn main() { let a = A {v: ~B{v: None} as ~Foo}; //~ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = RcMut::new(a); //~ ERROR instantiating a type parameter with an incompatible type let w = v.clone(); v.with_mut_borrow(|p| {p.v.set(w.clone());}) }
impl Foo for B { fn set(&mut self, v: RcMut<A>) { self.v = Some(v);
random_line_split
issue-7013.rs
// Copyright 2013 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 std::rc::RcMut; trait Foo { fn set(&mut self, v: RcMut<A>); } struct B { v: Option<RcMut<A>> } impl Foo for B { fn set(&mut self, v: RcMut<A>) { self.v = Some(v); } } struct A { v: ~Foo, } fn
() { let a = A {v: ~B{v: None} as ~Foo}; //~ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = RcMut::new(a); //~ ERROR instantiating a type parameter with an incompatible type let w = v.clone(); v.with_mut_borrow(|p| {p.v.set(w.clone());}) }
main
identifier_name
setup.py
# pyresample, Resampling of remote sensing image data in python # # Copyright (C) 2012, 2014, 2015 Esben S. Nielsen # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # workaround python bug: http://bugs.python.org/issue15881#msg170215 import multiprocessing from setuptools import setup import sys import imp version = imp.load_source('pyresample.version', 'pyresample/version.py') requirements = ['pyproj', 'numpy', 'configobj'] extras_require = {'pykdtree': ['pykdtree'], 'numexpr': ['numexpr'], 'quicklook': ['matplotlib', 'basemap']} if sys.version_info < (2, 6): # multiprocessing is not in the standard library
setup(name='pyresample', version=version.__version__, description='Resampling of remote sensing data in Python', author='Thomas Lavergne', author_email='t.lavergne@met.no', package_dir={'pyresample': 'pyresample'}, packages=['pyresample'], install_requires=requirements, extras_require=extras_require, test_suite='pyresample.test.suite', zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)', 'Programming Language :: Python', 'Operating System :: OS Independent', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering' ] )
requirements.append('multiprocessing')
conditional_block
setup.py
# pyresample, Resampling of remote sensing image data in python # # Copyright (C) 2012, 2014, 2015 Esben S. Nielsen # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # workaround python bug: http://bugs.python.org/issue15881#msg170215 import multiprocessing from setuptools import setup import sys import imp version = imp.load_source('pyresample.version', 'pyresample/version.py') requirements = ['pyproj', 'numpy', 'configobj'] extras_require = {'pykdtree': ['pykdtree'], 'numexpr': ['numexpr'], 'quicklook': ['matplotlib', 'basemap']} if sys.version_info < (2, 6): # multiprocessing is not in the standard library requirements.append('multiprocessing')
description='Resampling of remote sensing data in Python', author='Thomas Lavergne', author_email='t.lavergne@met.no', package_dir={'pyresample': 'pyresample'}, packages=['pyresample'], install_requires=requirements, extras_require=extras_require, test_suite='pyresample.test.suite', zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)', 'Programming Language :: Python', 'Operating System :: OS Independent', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering' ] )
setup(name='pyresample', version=version.__version__,
random_line_split
PropertyConstants.js
export const FILLPATTERN = { none: '', crossHatched: 'Crosshatched', hatched: 'Hatched', solid: 'Solid' };
dotted: 'Dotted', solid: 'Solid' }; export const ALTITUDEMODE = { NONE: '', ABSOLUTE: 'Absolute', RELATIVE_TO_GROUND: 'Relative to ground', CLAMP_TO_GROUND: 'Clamp to ground' }; export const ICONSIZE = { none: '', verySmall: 'Very Small', small: 'Small', medium: 'Medium', large: 'Large', extraLarge: 'Extra Large' }; export const ACMATTRIBUTES = { innerRadius: 'Inner Radius', leftAzimuth: 'Left Azimuth', rightAzimuth: 'Right Azimuth', minAlt: 'Minimum Altitude', maxAlt: 'Maximum Altitude', leftWidth: 'Left Width', rightWidth: 'Right Width', radius: 'Radius', turn: 'Turn', width: 'Width' }; export const WMSVERSION = { WMS: 'none', WMS1_1: '1.0', WMS1_1_1: '1.1.1', WMS1_3_0: '1.3.0' }; export const WMTSVERSION = { WMTS: 'none', WMTS1_0_0: '1.0.0' };
export const STROKEPATTERN = { none: '', dashed: 'Dashed',
random_line_split
config.py
# -*- coding: utf-8 -*- """ :copyright: (C) 2010-2013 by Contrail Consortium. """ from conpaas.core.log import create_logger from conpaas.core.node import ServiceNode E_ARGS_UNEXPECTED = 0 E_CONFIG_READ_FAILED = 1 E_CONFIG_NOT_EXIST = 2 E_UNKNOWN = 3 E_ARGS_MISSING = 4 E_ARGS_INVALID = 5 E_STATE_ERROR = 6 E_STRINGS = ['Unexpected arguments %s', 'Unable to open configuration file: %s', 'Configuration file does not exist: %s', 'Unknown error.', 'Missing argument: %s', 'Invalid argument: %s', 'Service in wrong state' ] class SQLServiceNode(ServiceNode): ''' Holds information on service nodes. :param vm: Service node id :type vm: array :param runMySQL: Indicator if service node is running MySQL :type runMySQL: boolean ''' isNode=True isGlb_node=False; def __init__(self, node): ServiceNode.__init__(self, node.vmid, node.ip, node.private_ip, node.cloud_name, role=node.role) self.port = 5555 '''String representation of the ServiceNode. @return: returns service nodes information. Id ip and if mysql is running on this service node.''' def __repr__(self): return 'ServiceNode(ip=%s, port=%s)' % (self.ip, self.port) class GLBServiceNode(ServiceNode): ''' Holds information on Galera Balancer nodes. :param vm: Service node id :type vm: array :param runMySQL: Indicator if service node is running MySQL :type runMySQL: boolean ''' isGlb_node=True isNode=False def __init__(self, node): ServiceNode.__init__(self, node.vmid, node.ip, node.private_ip, node.cloud_name, role=node.role) self.port = 5555 '''String representation of the ServiceNode. @return: returns service nodes information. Id ip and if mysql is running on this service node.''' def __repr__(self): return 'GLBServiceNode(ip=%s, port=%s)' % (self.ip, self.port) class Configuration(object): MYSQL_PORT = 3306 GLB_PORT = 3307 # The port on which the agent listens AGENT_PORT = 5555 '''Galera Load Balancer Nodes''' glb_service_nodes = {} serviceNodes = {} def __init__(self, configuration, logger): '''Representation of the deployment configuration''' self.logger = logger self.mysql_count = 0 self.serviceNodes = {} self.glb_service_nodes = {} def getMySQLTuples(self): '''Returns the list of service nodes as tuples <IP, PORT>.''' return [[serviceNode.ip, self.MYSQL_PORT] for serviceNode in self.serviceNodes.values()] ''' Returns the list of IPs of MySQL instances''' def get_nodes_addr(self): return [serviceNode.ip for serviceNode in self.serviceNodes.values()] def get_nodes(self): """ Returns the list of MySQL nodes.""" return [serviceNode for serviceNode in self.serviceNodes.values()] def get_glb_nodes(self): ''' Returns the list of GLB nodes''' return [serviceNode for serviceNode in self.glb_service_nodes.values()] def getMySQLNode(self, id): if self.serviceNodes.has_key(id): node = self.serviceNodes[id] else: node = self.glb_service_nodes[id] return node def addGLBServiceNodes(self, nodes): ''' Add new GLB Node to the server (configuration). ''' self.logger.debug('Entering addGLBServiceNodes') for node in nodes: self.glb_service_nodes[str(node.id)] = GLBServiceNode(node) self.logger.debug('Exiting addGLBServiceNodes') def removeGLBServiceNode(self, id): ''' Remove GLB Node to the server (configuration). ''' del self.glb_service_nodes[id] def
(self, nodes): for node in nodes: del self.glb_service_nodes[node.id] def addMySQLServiceNodes(self, nodes): ''' Add new Service Node to the server (configuration). ''' for node in nodes: self.serviceNodes[str(node.id)] = SQLServiceNode(node) def removeMySQLServiceNode(self, id): ''' Remove Service Node to the server (configuration). ''' del self.serviceNodes[id] def remove_nodes(self, nodes): for node in nodes: self.logger.debug('RemoveNodes node.id=%s' % node.id ) self.logger.debug('RemoveNodes node=%s' % node ) self.logger.debug('RemoveNodes self.ServiceNodes=%s' % self.serviceNodes ) if self.serviceNodes.has_key(node.id) : self.serviceNodes.pop(node.id, None) else : self.glb_service_nodes.pop(node.id,None)
remove_glb_nodes
identifier_name
config.py
# -*- coding: utf-8 -*- """ :copyright: (C) 2010-2013 by Contrail Consortium. """ from conpaas.core.log import create_logger from conpaas.core.node import ServiceNode E_ARGS_UNEXPECTED = 0 E_CONFIG_READ_FAILED = 1 E_CONFIG_NOT_EXIST = 2 E_UNKNOWN = 3 E_ARGS_MISSING = 4 E_ARGS_INVALID = 5 E_STATE_ERROR = 6 E_STRINGS = ['Unexpected arguments %s', 'Unable to open configuration file: %s', 'Configuration file does not exist: %s', 'Unknown error.', 'Missing argument: %s', 'Invalid argument: %s', 'Service in wrong state' ] class SQLServiceNode(ServiceNode): ''' Holds information on service nodes. :param vm: Service node id :type vm: array :param runMySQL: Indicator if service node is running MySQL :type runMySQL: boolean ''' isNode=True isGlb_node=False; def __init__(self, node): ServiceNode.__init__(self, node.vmid, node.ip, node.private_ip, node.cloud_name, role=node.role) self.port = 5555 '''String representation of the ServiceNode. @return: returns service nodes information. Id ip and if mysql is running on this service node.''' def __repr__(self): return 'ServiceNode(ip=%s, port=%s)' % (self.ip, self.port) class GLBServiceNode(ServiceNode): ''' Holds information on Galera Balancer nodes. :param vm: Service node id :type vm: array :param runMySQL: Indicator if service node is running MySQL :type runMySQL: boolean ''' isGlb_node=True isNode=False def __init__(self, node): ServiceNode.__init__(self, node.vmid, node.ip, node.private_ip, node.cloud_name, role=node.role) self.port = 5555 '''String representation of the ServiceNode. @return: returns service nodes information. Id ip and if mysql is running on this service node.''' def __repr__(self): return 'GLBServiceNode(ip=%s, port=%s)' % (self.ip, self.port) class Configuration(object): MYSQL_PORT = 3306 GLB_PORT = 3307 # The port on which the agent listens AGENT_PORT = 5555 '''Galera Load Balancer Nodes''' glb_service_nodes = {} serviceNodes = {} def __init__(self, configuration, logger): '''Representation of the deployment configuration''' self.logger = logger self.mysql_count = 0 self.serviceNodes = {} self.glb_service_nodes = {} def getMySQLTuples(self): '''Returns the list of service nodes as tuples <IP, PORT>.''' return [[serviceNode.ip, self.MYSQL_PORT] for serviceNode in self.serviceNodes.values()] ''' Returns the list of IPs of MySQL instances''' def get_nodes_addr(self): return [serviceNode.ip for serviceNode in self.serviceNodes.values()] def get_nodes(self): """ Returns the list of MySQL nodes.""" return [serviceNode for serviceNode in self.serviceNodes.values()] def get_glb_nodes(self): ''' Returns the list of GLB nodes''' return [serviceNode for serviceNode in self.glb_service_nodes.values()] def getMySQLNode(self, id): if self.serviceNodes.has_key(id): node = self.serviceNodes[id] else: node = self.glb_service_nodes[id] return node def addGLBServiceNodes(self, nodes): ''' Add new GLB Node to the server (configuration). ''' self.logger.debug('Entering addGLBServiceNodes') for node in nodes: self.glb_service_nodes[str(node.id)] = GLBServiceNode(node) self.logger.debug('Exiting addGLBServiceNodes') def removeGLBServiceNode(self, id): ''' Remove GLB Node to the server (configuration). ''' del self.glb_service_nodes[id] def remove_glb_nodes(self, nodes): for node in nodes: del self.glb_service_nodes[node.id] def addMySQLServiceNodes(self, nodes): ''' Add new Service Node to the server (configuration). ''' for node in nodes: self.serviceNodes[str(node.id)] = SQLServiceNode(node) def removeMySQLServiceNode(self, id): ''' Remove Service Node to the server (configuration). ''' del self.serviceNodes[id] def remove_nodes(self, nodes): for node in nodes: self.logger.debug('RemoveNodes node.id=%s' % node.id ) self.logger.debug('RemoveNodes node=%s' % node ) self.logger.debug('RemoveNodes self.ServiceNodes=%s' % self.serviceNodes ) if self.serviceNodes.has_key(node.id) :
else : self.glb_service_nodes.pop(node.id,None)
self.serviceNodes.pop(node.id, None)
conditional_block
config.py
# -*- coding: utf-8 -*- """ :copyright: (C) 2010-2013 by Contrail Consortium. """ from conpaas.core.log import create_logger from conpaas.core.node import ServiceNode E_ARGS_UNEXPECTED = 0 E_CONFIG_READ_FAILED = 1 E_CONFIG_NOT_EXIST = 2 E_UNKNOWN = 3 E_ARGS_MISSING = 4 E_ARGS_INVALID = 5 E_STATE_ERROR = 6 E_STRINGS = ['Unexpected arguments %s', 'Unable to open configuration file: %s', 'Configuration file does not exist: %s', 'Unknown error.', 'Missing argument: %s', 'Invalid argument: %s', 'Service in wrong state' ] class SQLServiceNode(ServiceNode): ''' Holds information on service nodes. :param vm: Service node id :type vm: array :param runMySQL: Indicator if service node is running MySQL :type runMySQL: boolean ''' isNode=True isGlb_node=False; def __init__(self, node): ServiceNode.__init__(self, node.vmid, node.ip, node.private_ip, node.cloud_name, role=node.role) self.port = 5555 '''String representation of the ServiceNode. @return: returns service nodes information. Id ip and if mysql is running on this service node.''' def __repr__(self): return 'ServiceNode(ip=%s, port=%s)' % (self.ip, self.port) class GLBServiceNode(ServiceNode): ''' Holds information on Galera Balancer nodes. :param vm: Service node id :type vm: array :param runMySQL: Indicator if service node is running MySQL :type runMySQL: boolean ''' isGlb_node=True isNode=False def __init__(self, node): ServiceNode.__init__(self, node.vmid, node.ip, node.private_ip, node.cloud_name, role=node.role) self.port = 5555 '''String representation of the ServiceNode. @return: returns service nodes information. Id ip and if mysql is running on this service node.''' def __repr__(self): return 'GLBServiceNode(ip=%s, port=%s)' % (self.ip, self.port) class Configuration(object): MYSQL_PORT = 3306 GLB_PORT = 3307 # The port on which the agent listens AGENT_PORT = 5555 '''Galera Load Balancer Nodes''' glb_service_nodes = {} serviceNodes = {} def __init__(self, configuration, logger): '''Representation of the deployment configuration''' self.logger = logger self.mysql_count = 0 self.serviceNodes = {} self.glb_service_nodes = {} def getMySQLTuples(self): '''Returns the list of service nodes as tuples <IP, PORT>.''' return [[serviceNode.ip, self.MYSQL_PORT] for serviceNode in self.serviceNodes.values()] ''' Returns the list of IPs of MySQL instances''' def get_nodes_addr(self): return [serviceNode.ip for serviceNode in self.serviceNodes.values()] def get_nodes(self): """ Returns the list of MySQL nodes.""" return [serviceNode for serviceNode in self.serviceNodes.values()] def get_glb_nodes(self): ''' Returns the list of GLB nodes''' return [serviceNode for serviceNode in self.glb_service_nodes.values()] def getMySQLNode(self, id): if self.serviceNodes.has_key(id): node = self.serviceNodes[id] else: node = self.glb_service_nodes[id] return node def addGLBServiceNodes(self, nodes): ''' Add new GLB Node to the server (configuration). ''' self.logger.debug('Entering addGLBServiceNodes') for node in nodes: self.glb_service_nodes[str(node.id)] = GLBServiceNode(node) self.logger.debug('Exiting addGLBServiceNodes') def removeGLBServiceNode(self, id): ''' Remove GLB Node to the server (configuration). ''' del self.glb_service_nodes[id] def remove_glb_nodes(self, nodes):
def addMySQLServiceNodes(self, nodes): ''' Add new Service Node to the server (configuration). ''' for node in nodes: self.serviceNodes[str(node.id)] = SQLServiceNode(node) def removeMySQLServiceNode(self, id): ''' Remove Service Node to the server (configuration). ''' del self.serviceNodes[id] def remove_nodes(self, nodes): for node in nodes: self.logger.debug('RemoveNodes node.id=%s' % node.id ) self.logger.debug('RemoveNodes node=%s' % node ) self.logger.debug('RemoveNodes self.ServiceNodes=%s' % self.serviceNodes ) if self.serviceNodes.has_key(node.id) : self.serviceNodes.pop(node.id, None) else : self.glb_service_nodes.pop(node.id,None)
for node in nodes: del self.glb_service_nodes[node.id]
identifier_body
config.py
# -*- coding: utf-8 -*- """ :copyright: (C) 2010-2013 by Contrail Consortium. """ from conpaas.core.log import create_logger from conpaas.core.node import ServiceNode E_ARGS_UNEXPECTED = 0 E_CONFIG_READ_FAILED = 1 E_CONFIG_NOT_EXIST = 2 E_UNKNOWN = 3 E_ARGS_MISSING = 4 E_ARGS_INVALID = 5 E_STATE_ERROR = 6 E_STRINGS = ['Unexpected arguments %s', 'Unable to open configuration file: %s', 'Configuration file does not exist: %s', 'Unknown error.', 'Missing argument: %s', 'Invalid argument: %s', 'Service in wrong state' ] class SQLServiceNode(ServiceNode): ''' Holds information on service nodes. :param vm: Service node id :type vm: array :param runMySQL: Indicator if service node is running MySQL :type runMySQL: boolean ''' isNode=True isGlb_node=False; def __init__(self, node): ServiceNode.__init__(self, node.vmid, node.ip, node.private_ip, node.cloud_name, role=node.role) self.port = 5555 '''String representation of the ServiceNode. @return: returns service nodes information. Id ip and if mysql is running on this service node.''' def __repr__(self): return 'ServiceNode(ip=%s, port=%s)' % (self.ip, self.port) class GLBServiceNode(ServiceNode): ''' Holds information on Galera Balancer nodes. :param vm: Service node id :type vm: array :param runMySQL: Indicator if service node is running MySQL :type runMySQL: boolean ''' isGlb_node=True isNode=False def __init__(self, node): ServiceNode.__init__(self, node.vmid, node.ip, node.private_ip, node.cloud_name, role=node.role) self.port = 5555 '''String representation of the ServiceNode. @return: returns service nodes information. Id ip and if mysql is running on this service node.''' def __repr__(self): return 'GLBServiceNode(ip=%s, port=%s)' % (self.ip, self.port) class Configuration(object): MYSQL_PORT = 3306 GLB_PORT = 3307 # The port on which the agent listens AGENT_PORT = 5555 '''Galera Load Balancer Nodes''' glb_service_nodes = {} serviceNodes = {} def __init__(self, configuration, logger): '''Representation of the deployment configuration''' self.logger = logger self.mysql_count = 0 self.serviceNodes = {} self.glb_service_nodes = {} def getMySQLTuples(self): '''Returns the list of service nodes as tuples <IP, PORT>.''' return [[serviceNode.ip, self.MYSQL_PORT] for serviceNode in self.serviceNodes.values()] ''' Returns the list of IPs of MySQL instances''' def get_nodes_addr(self): return [serviceNode.ip for serviceNode in self.serviceNodes.values()]
def get_nodes(self): """ Returns the list of MySQL nodes.""" return [serviceNode for serviceNode in self.serviceNodes.values()] def get_glb_nodes(self): ''' Returns the list of GLB nodes''' return [serviceNode for serviceNode in self.glb_service_nodes.values()] def getMySQLNode(self, id): if self.serviceNodes.has_key(id): node = self.serviceNodes[id] else: node = self.glb_service_nodes[id] return node def addGLBServiceNodes(self, nodes): ''' Add new GLB Node to the server (configuration). ''' self.logger.debug('Entering addGLBServiceNodes') for node in nodes: self.glb_service_nodes[str(node.id)] = GLBServiceNode(node) self.logger.debug('Exiting addGLBServiceNodes') def removeGLBServiceNode(self, id): ''' Remove GLB Node to the server (configuration). ''' del self.glb_service_nodes[id] def remove_glb_nodes(self, nodes): for node in nodes: del self.glb_service_nodes[node.id] def addMySQLServiceNodes(self, nodes): ''' Add new Service Node to the server (configuration). ''' for node in nodes: self.serviceNodes[str(node.id)] = SQLServiceNode(node) def removeMySQLServiceNode(self, id): ''' Remove Service Node to the server (configuration). ''' del self.serviceNodes[id] def remove_nodes(self, nodes): for node in nodes: self.logger.debug('RemoveNodes node.id=%s' % node.id ) self.logger.debug('RemoveNodes node=%s' % node ) self.logger.debug('RemoveNodes self.ServiceNodes=%s' % self.serviceNodes ) if self.serviceNodes.has_key(node.id) : self.serviceNodes.pop(node.id, None) else : self.glb_service_nodes.pop(node.id,None)
random_line_split
contextHelpers.js
const path = require('path'); const wmd = require('wmd'); const {getFile} = require('./importHelpers'); const createContextForList = (folderContents) => { let promises = []; return new Promise((resolve, reject) => { for (let file in folderContents) { let promise = getFile(folderContents[file].path); promises.push(promise); } Promise.all(promises).then(results => { for (let file in folderContents) { const content = wmd(results[file], { preprocessors: [wmd.preprocessors.metadata, wmd.preprocessors.fencedCodeBlocks] }); folderContents[file].meta = content.metadata; } resolve(folderContents); }); }); } // gets context data from file url - works both for list entries and pages const createContextFromFile = (fileUrl) => { return new Promise((resolve, reject) => { getFile(fileUrl).then(data => { const parsedData = { context: wmd(data, { preprocessors: [wmd.preprocessors.metadata, wmd.preprocessors.fencedCodeBlocks] }), fileName: path.parse(fileUrl).name, } resolve(parsedData); }); });
module.exports.createContextFromFile = createContextFromFile;
} module.exports.createContextForList = createContextForList;
random_line_split
CollectableV1Mixin.js
// @link http://schemas.wbeme.com/json-schema/eme/collector/mixin/collectable/1-0-0.json# import Fb from '@gdbots/pbj/FieldBuilder'; import Mixin from '@gdbots/pbj/Mixin'; import SchemaId from '@gdbots/pbj/SchemaId'; import T from '@gdbots/pbj/types'; export default class CollectableV1Mixin extends Mixin { /** * @returns {SchemaId} */ getId() { return SchemaId.fromString('pbj:eme:collector:mixin:collectable:1-0-0'); } /** * @returns {Field[]} */ getFields() {
*/ Fb.create('collector', T.MessageType.create()) .anyOfCuries([ 'gdbots:contexts::app', ]) .build(), ]; } }
return [ /* * The application collecting the message. This is set on the * server by the collector app itself.
random_line_split
CollectableV1Mixin.js
// @link http://schemas.wbeme.com/json-schema/eme/collector/mixin/collectable/1-0-0.json# import Fb from '@gdbots/pbj/FieldBuilder'; import Mixin from '@gdbots/pbj/Mixin'; import SchemaId from '@gdbots/pbj/SchemaId'; import T from '@gdbots/pbj/types'; export default class CollectableV1Mixin extends Mixin { /** * @returns {SchemaId} */ getId() { return SchemaId.fromString('pbj:eme:collector:mixin:collectable:1-0-0'); } /** * @returns {Field[]} */
() { return [ /* * The application collecting the message. This is set on the * server by the collector app itself. */ Fb.create('collector', T.MessageType.create()) .anyOfCuries([ 'gdbots:contexts::app', ]) .build(), ]; } }
getFields
identifier_name
index.js
'use strict'; var staticMatch = require('css-mediaquery').match; var dynamicMatch = typeof window !== 'undefined' ? window.matchMedia : null; // our fake MediaQueryList function Mql(query, values){ var self = this; if(dynamicMatch){ var mql = dynamicMatch.call(window, query); this.matches = mql.matches; this.media = mql.media; // TODO: is there a time it makes sense to remove this listener? mql.addListener(update); } else { this.matches = staticMatch(query, values); this.media = query; } this.addListener = addListener; this.removeListener = removeListener; this.dispose = dispose; function addListener(listener){ if(mql){ mql.addListener(listener); } } function removeListener(listener){ if(mql){ mql.removeListener(listener); } } // update ourselves! function update(evt){ self.matches = evt.matches; self.media = evt.media; } function
(){ if(mql){ mql.removeListener(update); } } } function matchMedia(query, values){ return new Mql(query, values); } module.exports = matchMedia;
dispose
identifier_name
index.js
'use strict'; var staticMatch = require('css-mediaquery').match; var dynamicMatch = typeof window !== 'undefined' ? window.matchMedia : null; // our fake MediaQueryList function Mql(query, values){ var self = this; if(dynamicMatch){ var mql = dynamicMatch.call(window, query); this.matches = mql.matches; this.media = mql.media; // TODO: is there a time it makes sense to remove this listener? mql.addListener(update); } else { this.matches = staticMatch(query, values); this.media = query; } this.addListener = addListener; this.removeListener = removeListener; this.dispose = dispose; function addListener(listener){ if(mql){ mql.addListener(listener); } } function removeListener(listener){ if(mql){ mql.removeListener(listener); } } // update ourselves! function update(evt){ self.matches = evt.matches; self.media = evt.media; } function dispose(){ if(mql){ mql.removeListener(update); } } }
module.exports = matchMedia;
function matchMedia(query, values){ return new Mql(query, values); }
random_line_split
index.js
'use strict'; var staticMatch = require('css-mediaquery').match; var dynamicMatch = typeof window !== 'undefined' ? window.matchMedia : null; // our fake MediaQueryList function Mql(query, values){ var self = this; if(dynamicMatch){ var mql = dynamicMatch.call(window, query); this.matches = mql.matches; this.media = mql.media; // TODO: is there a time it makes sense to remove this listener? mql.addListener(update); } else { this.matches = staticMatch(query, values); this.media = query; } this.addListener = addListener; this.removeListener = removeListener; this.dispose = dispose; function addListener(listener){ if(mql){ mql.addListener(listener); } } function removeListener(listener){ if(mql){ mql.removeListener(listener); } } // update ourselves! function update(evt){ self.matches = evt.matches; self.media = evt.media; } function dispose(){ if(mql)
} } function matchMedia(query, values){ return new Mql(query, values); } module.exports = matchMedia;
{ mql.removeListener(update); }
conditional_block
index.js
'use strict'; var staticMatch = require('css-mediaquery').match; var dynamicMatch = typeof window !== 'undefined' ? window.matchMedia : null; // our fake MediaQueryList function Mql(query, values)
function matchMedia(query, values){ return new Mql(query, values); } module.exports = matchMedia;
{ var self = this; if(dynamicMatch){ var mql = dynamicMatch.call(window, query); this.matches = mql.matches; this.media = mql.media; // TODO: is there a time it makes sense to remove this listener? mql.addListener(update); } else { this.matches = staticMatch(query, values); this.media = query; } this.addListener = addListener; this.removeListener = removeListener; this.dispose = dispose; function addListener(listener){ if(mql){ mql.addListener(listener); } } function removeListener(listener){ if(mql){ mql.removeListener(listener); } } // update ourselves! function update(evt){ self.matches = evt.matches; self.media = evt.media; } function dispose(){ if(mql){ mql.removeListener(update); } } }
identifier_body
webgl_camera.ts
/// <reference path="../../three.d.ts" /> /// <reference path="../three-tests-setup.ts" /> // https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html () => { var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container, stats; var camera, scene, renderer, mesh; var cameraRig, activeCamera, activeHelper; var cameraPerspective, cameraOrtho; var cameraPerspectiveHelper, cameraOrthoHelper; init(); animate(); function init() { container = document.createElement( 'div' ); document.body.appendChild( container ); scene = new THREE.Scene(); // camera = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); camera.position.z = 2500; cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 150, 1000 ); cameraPerspectiveHelper = new THREE.CameraHelper( cameraPerspective ); scene.add( cameraPerspectiveHelper ); // cameraOrtho = new THREE.OrthographicCamera( 0.5 * SCREEN_WIDTH / - 2, 0.5 * SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, 150, 1000 ); cameraOrthoHelper = new THREE.CameraHelper( cameraOrtho ); scene.add( cameraOrthoHelper ); // activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; // counteract different front orientation of cameras vs rig cameraOrtho.rotation.y = Math.PI; cameraPerspective.rotation.y = Math.PI; cameraRig = new THREE.Group(); cameraRig.add( cameraPerspective ); cameraRig.add( cameraOrtho ); scene.add( cameraRig ); // mesh = new THREE.Mesh( new THREE.SphereBufferGeometry( 100, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true } ) ); scene.add( mesh ); var mesh2 = new THREE.Mesh( new THREE.SphereBufferGeometry( 50, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x00ff00, wireframe: true } ) ); mesh2.position.y = 150; mesh.add( mesh2 ); var mesh3 = new THREE.Mesh( new THREE.SphereBufferGeometry( 5, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x0000ff, wireframe: true } ) ); mesh3.position.z = 150; cameraRig.add( mesh3 ); // var geometry = new THREE.Geometry(); for ( var i = 0; i < 10000; i ++ ) {
var particles = new THREE.Points( geometry, new THREE.PointsMaterial( { color: 0x888888 } ) ); scene.add( particles ); // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); renderer.domElement.style.position = "relative"; container.appendChild( renderer.domElement ); renderer.autoClear = false; // stats = new Stats(); container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); document.addEventListener( 'keydown', onKeyDown, false ); } // function onKeyDown ( event ) { switch( event.keyCode ) { case 79: /*O*/ activeCamera = cameraOrtho; activeHelper = cameraOrthoHelper; break; case 80: /*P*/ activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; break; } } // function onWindowResize( event ) { SCREEN_WIDTH = window.innerWidth; SCREEN_HEIGHT = window.innerHeight; renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); camera.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; camera.updateProjectionMatrix(); cameraPerspective.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; cameraPerspective.updateProjectionMatrix(); cameraOrtho.left = - 0.5 * SCREEN_WIDTH / 2; cameraOrtho.right = 0.5 * SCREEN_WIDTH / 2; cameraOrtho.top = SCREEN_HEIGHT / 2; cameraOrtho.bottom = - SCREEN_HEIGHT / 2; cameraOrtho.updateProjectionMatrix(); } // function animate() { requestAnimationFrame( animate ); render(); stats.update(); } function render() { var r = Date.now() * 0.0005; mesh.position.x = 700 * Math.cos( r ); mesh.position.z = 700 * Math.sin( r ); mesh.position.y = 700 * Math.sin( r ); mesh.children[ 0 ].position.x = 70 * Math.cos( 2 * r ); mesh.children[ 0 ].position.z = 70 * Math.sin( r ); if ( activeCamera === cameraPerspective ) { cameraPerspective.fov = 35 + 30 * Math.sin( 0.5 * r ); cameraPerspective.far = mesh.position.length(); cameraPerspective.updateProjectionMatrix(); cameraPerspectiveHelper.update(); cameraPerspectiveHelper.visible = true; cameraOrthoHelper.visible = false; } else { cameraOrtho.far = mesh.position.length(); cameraOrtho.updateProjectionMatrix(); cameraOrthoHelper.update(); cameraOrthoHelper.visible = true; cameraPerspectiveHelper.visible = false; } cameraRig.lookAt( mesh.position ); renderer.clear(); activeHelper.visible = false; renderer.setViewport( 0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); renderer.render( scene, activeCamera ); activeHelper.visible = true; renderer.setViewport( SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); renderer.render( scene, camera ); } }
var vertex = new THREE.Vector3(); vertex.x = THREE.Math.randFloatSpread( 2000 ); vertex.y = THREE.Math.randFloatSpread( 2000 ); vertex.z = THREE.Math.randFloatSpread( 2000 ); geometry.vertices.push( vertex ); }
conditional_block
webgl_camera.ts
/// <reference path="../../three.d.ts" /> /// <reference path="../three-tests-setup.ts" /> // https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html () => { var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container, stats; var camera, scene, renderer, mesh; var cameraRig, activeCamera, activeHelper; var cameraPerspective, cameraOrtho; var cameraPerspectiveHelper, cameraOrthoHelper; init(); animate(); function init() { container = document.createElement( 'div' ); document.body.appendChild( container ); scene = new THREE.Scene(); // camera = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); camera.position.z = 2500; cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 150, 1000 ); cameraPerspectiveHelper = new THREE.CameraHelper( cameraPerspective ); scene.add( cameraPerspectiveHelper ); // cameraOrtho = new THREE.OrthographicCamera( 0.5 * SCREEN_WIDTH / - 2, 0.5 * SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, 150, 1000 ); cameraOrthoHelper = new THREE.CameraHelper( cameraOrtho ); scene.add( cameraOrthoHelper ); // activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; // counteract different front orientation of cameras vs rig cameraOrtho.rotation.y = Math.PI; cameraPerspective.rotation.y = Math.PI; cameraRig = new THREE.Group(); cameraRig.add( cameraPerspective ); cameraRig.add( cameraOrtho ); scene.add( cameraRig ); // mesh = new THREE.Mesh( new THREE.SphereBufferGeometry( 100, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true } ) ); scene.add( mesh ); var mesh2 = new THREE.Mesh( new THREE.SphereBufferGeometry( 50, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x00ff00, wireframe: true } ) ); mesh2.position.y = 150; mesh.add( mesh2 ); var mesh3 = new THREE.Mesh( new THREE.SphereBufferGeometry( 5, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x0000ff, wireframe: true } ) ); mesh3.position.z = 150; cameraRig.add( mesh3 ); // var geometry = new THREE.Geometry(); for ( var i = 0; i < 10000; i ++ ) { var vertex = new THREE.Vector3(); vertex.x = THREE.Math.randFloatSpread( 2000 ); vertex.y = THREE.Math.randFloatSpread( 2000 ); vertex.z = THREE.Math.randFloatSpread( 2000 ); geometry.vertices.push( vertex ); } var particles = new THREE.Points( geometry, new THREE.PointsMaterial( { color: 0x888888 } ) ); scene.add( particles ); // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); renderer.domElement.style.position = "relative"; container.appendChild( renderer.domElement ); renderer.autoClear = false; // stats = new Stats(); container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); document.addEventListener( 'keydown', onKeyDown, false ); } // function onKeyDown ( event ) { switch( event.keyCode ) { case 79: /*O*/ activeCamera = cameraOrtho; activeHelper = cameraOrthoHelper; break; case 80: /*P*/ activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; break; } } // function onWindowResize( event ) {
// function animate() { requestAnimationFrame( animate ); render(); stats.update(); } function render() { var r = Date.now() * 0.0005; mesh.position.x = 700 * Math.cos( r ); mesh.position.z = 700 * Math.sin( r ); mesh.position.y = 700 * Math.sin( r ); mesh.children[ 0 ].position.x = 70 * Math.cos( 2 * r ); mesh.children[ 0 ].position.z = 70 * Math.sin( r ); if ( activeCamera === cameraPerspective ) { cameraPerspective.fov = 35 + 30 * Math.sin( 0.5 * r ); cameraPerspective.far = mesh.position.length(); cameraPerspective.updateProjectionMatrix(); cameraPerspectiveHelper.update(); cameraPerspectiveHelper.visible = true; cameraOrthoHelper.visible = false; } else { cameraOrtho.far = mesh.position.length(); cameraOrtho.updateProjectionMatrix(); cameraOrthoHelper.update(); cameraOrthoHelper.visible = true; cameraPerspectiveHelper.visible = false; } cameraRig.lookAt( mesh.position ); renderer.clear(); activeHelper.visible = false; renderer.setViewport( 0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); renderer.render( scene, activeCamera ); activeHelper.visible = true; renderer.setViewport( SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); renderer.render( scene, camera ); } }
SCREEN_WIDTH = window.innerWidth; SCREEN_HEIGHT = window.innerHeight; renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); camera.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; camera.updateProjectionMatrix(); cameraPerspective.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; cameraPerspective.updateProjectionMatrix(); cameraOrtho.left = - 0.5 * SCREEN_WIDTH / 2; cameraOrtho.right = 0.5 * SCREEN_WIDTH / 2; cameraOrtho.top = SCREEN_HEIGHT / 2; cameraOrtho.bottom = - SCREEN_HEIGHT / 2; cameraOrtho.updateProjectionMatrix(); }
identifier_body
webgl_camera.ts
/// <reference path="../../three.d.ts" /> /// <reference path="../three-tests-setup.ts" /> // https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html () => { var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container, stats; var camera, scene, renderer, mesh; var cameraRig, activeCamera, activeHelper; var cameraPerspective, cameraOrtho; var cameraPerspectiveHelper, cameraOrthoHelper; init(); animate(); function init() { container = document.createElement( 'div' ); document.body.appendChild( container ); scene = new THREE.Scene(); // camera = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); camera.position.z = 2500; cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 150, 1000 ); cameraPerspectiveHelper = new THREE.CameraHelper( cameraPerspective ); scene.add( cameraPerspectiveHelper ); // cameraOrtho = new THREE.OrthographicCamera( 0.5 * SCREEN_WIDTH / - 2, 0.5 * SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, 150, 1000 ); cameraOrthoHelper = new THREE.CameraHelper( cameraOrtho ); scene.add( cameraOrthoHelper ); // activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; // counteract different front orientation of cameras vs rig cameraOrtho.rotation.y = Math.PI; cameraPerspective.rotation.y = Math.PI; cameraRig = new THREE.Group(); cameraRig.add( cameraPerspective ); cameraRig.add( cameraOrtho ); scene.add( cameraRig ); // mesh = new THREE.Mesh( new THREE.SphereBufferGeometry( 100, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true } ) ); scene.add( mesh ); var mesh2 = new THREE.Mesh( new THREE.SphereBufferGeometry( 50, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x00ff00, wireframe: true } ) ); mesh2.position.y = 150; mesh.add( mesh2 ); var mesh3 = new THREE.Mesh( new THREE.SphereBufferGeometry( 5, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x0000ff, wireframe: true } ) ); mesh3.position.z = 150; cameraRig.add( mesh3 ); // var geometry = new THREE.Geometry(); for ( var i = 0; i < 10000; i ++ ) { var vertex = new THREE.Vector3(); vertex.x = THREE.Math.randFloatSpread( 2000 ); vertex.y = THREE.Math.randFloatSpread( 2000 ); vertex.z = THREE.Math.randFloatSpread( 2000 ); geometry.vertices.push( vertex ); } var particles = new THREE.Points( geometry, new THREE.PointsMaterial( { color: 0x888888 } ) ); scene.add( particles ); // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); renderer.domElement.style.position = "relative"; container.appendChild( renderer.domElement ); renderer.autoClear = false; // stats = new Stats(); container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); document.addEventListener( 'keydown', onKeyDown, false ); }
switch( event.keyCode ) { case 79: /*O*/ activeCamera = cameraOrtho; activeHelper = cameraOrthoHelper; break; case 80: /*P*/ activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; break; } } // function onWindowResize( event ) { SCREEN_WIDTH = window.innerWidth; SCREEN_HEIGHT = window.innerHeight; renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); camera.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; camera.updateProjectionMatrix(); cameraPerspective.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; cameraPerspective.updateProjectionMatrix(); cameraOrtho.left = - 0.5 * SCREEN_WIDTH / 2; cameraOrtho.right = 0.5 * SCREEN_WIDTH / 2; cameraOrtho.top = SCREEN_HEIGHT / 2; cameraOrtho.bottom = - SCREEN_HEIGHT / 2; cameraOrtho.updateProjectionMatrix(); } // function animate() { requestAnimationFrame( animate ); render(); stats.update(); } function render() { var r = Date.now() * 0.0005; mesh.position.x = 700 * Math.cos( r ); mesh.position.z = 700 * Math.sin( r ); mesh.position.y = 700 * Math.sin( r ); mesh.children[ 0 ].position.x = 70 * Math.cos( 2 * r ); mesh.children[ 0 ].position.z = 70 * Math.sin( r ); if ( activeCamera === cameraPerspective ) { cameraPerspective.fov = 35 + 30 * Math.sin( 0.5 * r ); cameraPerspective.far = mesh.position.length(); cameraPerspective.updateProjectionMatrix(); cameraPerspectiveHelper.update(); cameraPerspectiveHelper.visible = true; cameraOrthoHelper.visible = false; } else { cameraOrtho.far = mesh.position.length(); cameraOrtho.updateProjectionMatrix(); cameraOrthoHelper.update(); cameraOrthoHelper.visible = true; cameraPerspectiveHelper.visible = false; } cameraRig.lookAt( mesh.position ); renderer.clear(); activeHelper.visible = false; renderer.setViewport( 0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); renderer.render( scene, activeCamera ); activeHelper.visible = true; renderer.setViewport( SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); renderer.render( scene, camera ); } }
// function onKeyDown ( event ) {
random_line_split
webgl_camera.ts
/// <reference path="../../three.d.ts" /> /// <reference path="../three-tests-setup.ts" /> // https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html () => { var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container, stats; var camera, scene, renderer, mesh; var cameraRig, activeCamera, activeHelper; var cameraPerspective, cameraOrtho; var cameraPerspectiveHelper, cameraOrthoHelper; init(); animate(); function init() { container = document.createElement( 'div' ); document.body.appendChild( container ); scene = new THREE.Scene(); // camera = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); camera.position.z = 2500; cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT, 150, 1000 ); cameraPerspectiveHelper = new THREE.CameraHelper( cameraPerspective ); scene.add( cameraPerspectiveHelper ); // cameraOrtho = new THREE.OrthographicCamera( 0.5 * SCREEN_WIDTH / - 2, 0.5 * SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_HEIGHT / - 2, 150, 1000 ); cameraOrthoHelper = new THREE.CameraHelper( cameraOrtho ); scene.add( cameraOrthoHelper ); // activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; // counteract different front orientation of cameras vs rig cameraOrtho.rotation.y = Math.PI; cameraPerspective.rotation.y = Math.PI; cameraRig = new THREE.Group(); cameraRig.add( cameraPerspective ); cameraRig.add( cameraOrtho ); scene.add( cameraRig ); // mesh = new THREE.Mesh( new THREE.SphereBufferGeometry( 100, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true } ) ); scene.add( mesh ); var mesh2 = new THREE.Mesh( new THREE.SphereBufferGeometry( 50, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x00ff00, wireframe: true } ) ); mesh2.position.y = 150; mesh.add( mesh2 ); var mesh3 = new THREE.Mesh( new THREE.SphereBufferGeometry( 5, 16, 8 ), new THREE.MeshBasicMaterial( { color: 0x0000ff, wireframe: true } ) ); mesh3.position.z = 150; cameraRig.add( mesh3 ); // var geometry = new THREE.Geometry(); for ( var i = 0; i < 10000; i ++ ) { var vertex = new THREE.Vector3(); vertex.x = THREE.Math.randFloatSpread( 2000 ); vertex.y = THREE.Math.randFloatSpread( 2000 ); vertex.z = THREE.Math.randFloatSpread( 2000 ); geometry.vertices.push( vertex ); } var particles = new THREE.Points( geometry, new THREE.PointsMaterial( { color: 0x888888 } ) ); scene.add( particles ); // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); renderer.domElement.style.position = "relative"; container.appendChild( renderer.domElement ); renderer.autoClear = false; // stats = new Stats(); container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); document.addEventListener( 'keydown', onKeyDown, false ); } // function onKeyDown ( event ) { switch( event.keyCode ) { case 79: /*O*/ activeCamera = cameraOrtho; activeHelper = cameraOrthoHelper; break; case 80: /*P*/ activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; break; } } // function onWindowResize( event ) { SCREEN_WIDTH = window.innerWidth; SCREEN_HEIGHT = window.innerHeight; renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); camera.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; camera.updateProjectionMatrix(); cameraPerspective.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; cameraPerspective.updateProjectionMatrix(); cameraOrtho.left = - 0.5 * SCREEN_WIDTH / 2; cameraOrtho.right = 0.5 * SCREEN_WIDTH / 2; cameraOrtho.top = SCREEN_HEIGHT / 2; cameraOrtho.bottom = - SCREEN_HEIGHT / 2; cameraOrtho.updateProjectionMatrix(); } // function an
{ requestAnimationFrame( animate ); render(); stats.update(); } function render() { var r = Date.now() * 0.0005; mesh.position.x = 700 * Math.cos( r ); mesh.position.z = 700 * Math.sin( r ); mesh.position.y = 700 * Math.sin( r ); mesh.children[ 0 ].position.x = 70 * Math.cos( 2 * r ); mesh.children[ 0 ].position.z = 70 * Math.sin( r ); if ( activeCamera === cameraPerspective ) { cameraPerspective.fov = 35 + 30 * Math.sin( 0.5 * r ); cameraPerspective.far = mesh.position.length(); cameraPerspective.updateProjectionMatrix(); cameraPerspectiveHelper.update(); cameraPerspectiveHelper.visible = true; cameraOrthoHelper.visible = false; } else { cameraOrtho.far = mesh.position.length(); cameraOrtho.updateProjectionMatrix(); cameraOrthoHelper.update(); cameraOrthoHelper.visible = true; cameraPerspectiveHelper.visible = false; } cameraRig.lookAt( mesh.position ); renderer.clear(); activeHelper.visible = false; renderer.setViewport( 0, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); renderer.render( scene, activeCamera ); activeHelper.visible = true; renderer.setViewport( SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, SCREEN_HEIGHT ); renderer.render( scene, camera ); } }
imate()
identifier_name
utils.py
from __future__ import annotations import base64 from collections import OrderedDict from datetime import timedelta from itertools import chain import numbers import random import re import sys from typing import ( Any, Iterable, Iterator, Mapping, Tuple, TYPE_CHECKING, TypeVar, Union, ) import uuid if TYPE_CHECKING: from decimal import Decimal # It is a bad practice to keep all "miscellaneous" stuffs # into the single "utils" module. # Let's categorize them by purpose and domain, and keep # refactoring to use the proper module names. from .asyncio import ( # for legacy imports # noqa AsyncBarrier, cancel_tasks, current_loop, run_through, ) from .enum_extension import StringSetFlag # for legacy imports # noqa from .files import AsyncFileWriter # for legacy imports # noqa from .networking import ( # for legacy imports # noqa curl, find_free_port, ) from .types import BinarySize
KT = TypeVar('KT') VT = TypeVar('VT') def env_info() -> str: """ Returns a string that contains the Python version and runtime path. """ v = sys.version_info pyver = f'Python {v.major}.{v.minor}.{v.micro}' if v.releaselevel == 'alpha': pyver += 'a' if v.releaselevel == 'beta': pyver += 'b' if v.releaselevel == 'candidate': pyver += 'rc' if v.releaselevel != 'final': pyver += str(v.serial) return f'{pyver} (env: {sys.prefix})' def odict(*args: Tuple[KT, VT]) -> OrderedDict[KT, VT]: """ A short-hand for the constructor of OrderedDict. :code:`odict(('a',1), ('b',2))` is equivalent to :code:`OrderedDict([('a',1), ('b',2)])`. """ return OrderedDict(args) def dict2kvlist(o: Mapping[KT, VT]) -> Iterable[Union[KT, VT]]: """ Serializes a dict-like object into a generator of the flatten list of repeating key-value pairs. It is useful when using HMSET method in Redis. Example: >>> list(dict2kvlist({'a': 1, 'b': 2})) ['a', 1, 'b', 2] """ return chain.from_iterable((k, v) for k, v in o.items()) def generate_uuid() -> str: u = uuid.uuid4() # Strip the last two padding characters because u always has fixed length. return base64.urlsafe_b64encode(u.bytes)[:-2].decode('ascii') def get_random_seq(length: float, num_points: int, min_distance: float) -> Iterator[float]: """ Generate a random sequence of numbers within the range [0, length] with the given number of points and the minimum distance between the points. Note that X ( = the minimum distance d x the number of points N) must be equivalent to or smaller than the length L + d to guarantee the the minimum distance between the points. If X == L + d, the points are always equally spaced with d. :return: An iterator over the generated sequence """ assert num_points * min_distance <= length + min_distance, \ 'There are too many points or it has a too large distance which cannot be fit into the given length.' extra = length - (num_points - 1) * min_distance ro = [random.uniform(0, 1) for _ in range(num_points + 1)] sum_ro = sum(ro) rn = [extra * r / sum_ro for r in ro[0:num_points]] spacing = [min_distance + rn[i] for i in range(num_points)] cumulative_sum = 0.0 for s in spacing: cumulative_sum += s yield cumulative_sum - min_distance def nmget( o: Mapping[str, Any], key_path: str, def_val: Any = None, path_delimiter: str = '.', null_as_default: bool = True, ) -> Any: """ A short-hand for retrieving a value from nested mappings ("nested-mapping-get"). At each level it checks if the given "path" component in the given key exists and return the default value whenever fails. Example: >>> o = {'a':{'b':1}, 'x': None} >>> nmget(o, 'a', 0) {'b': 1} >>> nmget(o, 'a.b', 0) 1 >>> nmget(o, 'a/b', 0, '/') 1 >>> nmget(o, 'a.c', 0) 0 >>> nmget(o, 'x', 0) 0 >>> nmget(o, 'x', 0, null_as_default=False) None """ pieces = key_path.split(path_delimiter) while pieces: p = pieces.pop(0) if o is None or p not in o: return def_val o = o[p] if o is None and null_as_default: return def_val return o def readable_size_to_bytes(expr: Any) -> BinarySize | Decimal: if isinstance(expr, numbers.Real): return BinarySize(expr) return BinarySize.from_str(expr) def str_to_timedelta(tstr: str) -> timedelta: """ Convert humanized timedelta string into a Python timedelta object. Example: >>> str_to_timedelta('30min') datetime.timedelta(seconds=1800) >>> str_to_timedelta('1d1hr') datetime.timedelta(days=1, seconds=3600) >>> str_to_timedelta('2hours 15min') datetime.timedelta(seconds=8100) >>> str_to_timedelta('20sec') datetime.timedelta(seconds=20) >>> str_to_timedelta('300') datetime.timedelta(seconds=300) >>> str_to_timedelta('-1day') datetime.timedelta(days=-1) """ _rx = re.compile(r'(?P<sign>[+|-])?\s*' r'((?P<days>\d+(\.\d+)?)(d|day|days))?\s*' r'((?P<hours>\d+(\.\d+)?)(h|hr|hrs|hour|hours))?\s*' r'((?P<minutes>\d+(\.\d+)?)(m|min|mins|minute|minutes))?\s*' r'((?P<seconds>\d+(\.\d+)?)(s|sec|secs|second|seconds))?$') match = _rx.match(tstr) if not match: try: return timedelta(seconds=float(tstr)) # consider bare number string as seconds except TypeError: pass raise ValueError('Invalid time expression') groups = match.groupdict() sign = groups.pop('sign', None) if set(groups.values()) == {None}: raise ValueError('Invalid time expression') params = {n: -float(t) if sign == '-' else float(t) for n, t in groups.items() if t} return timedelta(**params) # type: ignore class FstabEntry: """ Entry class represents a non-comment line on the `fstab` file. """ def __init__(self, device, mountpoint, fstype, options, d=0, p=0) -> None: self.device = device self.mountpoint = mountpoint self.fstype = fstype if not options: options = 'defaults' self.options = options self.d = d self.p = p def __eq__(self, o): return str(self) == str(o) def __str__(self): return "{} {} {} {} {} {}".format(self.device, self.mountpoint, self.fstype, self.options, self.d, self.p) class Fstab: """ Reader/writer for fstab file. Takes aiofile pointer for async I/O. It should be writable if add/remove operations are needed. NOTE: This class references Jorge Niedbalski R.'s gist snippet. We have been converted it to be compatible with Python 3 and to support async I/O. (https://gist.github.com/niedbalski/507e974ed2d54a87ad37) """ def __init__(self, fp) -> None: self._fp = fp def _hydrate_entry(self, line): return FstabEntry(*[x for x in line.strip('\n').split(' ') if x not in ('', None)]) async def get_entries(self): await self._fp.seek(0) for line in await self._fp.readlines(): try: line = line.strip() if not line.startswith("#"): yield self._hydrate_entry(line) except TypeError: pass async def get_entry_by_attr(self, attr, value): async for entry in self.get_entries(): e_attr = getattr(entry, attr) if e_attr == value: return entry return None async def add_entry(self, entry): if await self.get_entry_by_attr('device', entry.device): return False await self._fp.write(str(entry) + '\n') await self._fp.truncate() return entry async def add(self, device, mountpoint, fstype, options=None, d=0, p=0): return await self.add_entry(FstabEntry(device, mountpoint, fstype, options, d, p)) async def remove_entry(self, entry): await self._fp.seek(0) lines = await self._fp.readlines() found = False for index, line in enumerate(lines): try: if not line.strip().startswith("#"): if self._hydrate_entry(line) == entry: found = True break except TypeError: pass if not found: return False lines.remove(line) await self._fp.seek(0) await self._fp.write(''.join(lines)) await self._fp.truncate() return True async def remove_by_mountpoint(self, mountpoint): entry = await self.get_entry_by_attr('mountpoint', mountpoint) if entry: return await self.remove_entry(entry) return False
random_line_split
utils.py
from __future__ import annotations import base64 from collections import OrderedDict from datetime import timedelta from itertools import chain import numbers import random import re import sys from typing import ( Any, Iterable, Iterator, Mapping, Tuple, TYPE_CHECKING, TypeVar, Union, ) import uuid if TYPE_CHECKING: from decimal import Decimal # It is a bad practice to keep all "miscellaneous" stuffs # into the single "utils" module. # Let's categorize them by purpose and domain, and keep # refactoring to use the proper module names. from .asyncio import ( # for legacy imports # noqa AsyncBarrier, cancel_tasks, current_loop, run_through, ) from .enum_extension import StringSetFlag # for legacy imports # noqa from .files import AsyncFileWriter # for legacy imports # noqa from .networking import ( # for legacy imports # noqa curl, find_free_port, ) from .types import BinarySize KT = TypeVar('KT') VT = TypeVar('VT') def env_info() -> str: """ Returns a string that contains the Python version and runtime path. """ v = sys.version_info pyver = f'Python {v.major}.{v.minor}.{v.micro}' if v.releaselevel == 'alpha': pyver += 'a' if v.releaselevel == 'beta': pyver += 'b' if v.releaselevel == 'candidate': pyver += 'rc' if v.releaselevel != 'final': pyver += str(v.serial) return f'{pyver} (env: {sys.prefix})' def odict(*args: Tuple[KT, VT]) -> OrderedDict[KT, VT]: """ A short-hand for the constructor of OrderedDict. :code:`odict(('a',1), ('b',2))` is equivalent to :code:`OrderedDict([('a',1), ('b',2)])`. """ return OrderedDict(args) def dict2kvlist(o: Mapping[KT, VT]) -> Iterable[Union[KT, VT]]: """ Serializes a dict-like object into a generator of the flatten list of repeating key-value pairs. It is useful when using HMSET method in Redis. Example: >>> list(dict2kvlist({'a': 1, 'b': 2})) ['a', 1, 'b', 2] """ return chain.from_iterable((k, v) for k, v in o.items()) def generate_uuid() -> str: u = uuid.uuid4() # Strip the last two padding characters because u always has fixed length. return base64.urlsafe_b64encode(u.bytes)[:-2].decode('ascii') def get_random_seq(length: float, num_points: int, min_distance: float) -> Iterator[float]: """ Generate a random sequence of numbers within the range [0, length] with the given number of points and the minimum distance between the points. Note that X ( = the minimum distance d x the number of points N) must be equivalent to or smaller than the length L + d to guarantee the the minimum distance between the points. If X == L + d, the points are always equally spaced with d. :return: An iterator over the generated sequence """ assert num_points * min_distance <= length + min_distance, \ 'There are too many points or it has a too large distance which cannot be fit into the given length.' extra = length - (num_points - 1) * min_distance ro = [random.uniform(0, 1) for _ in range(num_points + 1)] sum_ro = sum(ro) rn = [extra * r / sum_ro for r in ro[0:num_points]] spacing = [min_distance + rn[i] for i in range(num_points)] cumulative_sum = 0.0 for s in spacing: cumulative_sum += s yield cumulative_sum - min_distance def nmget( o: Mapping[str, Any], key_path: str, def_val: Any = None, path_delimiter: str = '.', null_as_default: bool = True, ) -> Any: """ A short-hand for retrieving a value from nested mappings ("nested-mapping-get"). At each level it checks if the given "path" component in the given key exists and return the default value whenever fails. Example: >>> o = {'a':{'b':1}, 'x': None} >>> nmget(o, 'a', 0) {'b': 1} >>> nmget(o, 'a.b', 0) 1 >>> nmget(o, 'a/b', 0, '/') 1 >>> nmget(o, 'a.c', 0) 0 >>> nmget(o, 'x', 0) 0 >>> nmget(o, 'x', 0, null_as_default=False) None """ pieces = key_path.split(path_delimiter) while pieces: p = pieces.pop(0) if o is None or p not in o: return def_val o = o[p] if o is None and null_as_default: return def_val return o def readable_size_to_bytes(expr: Any) -> BinarySize | Decimal: if isinstance(expr, numbers.Real): return BinarySize(expr) return BinarySize.from_str(expr) def str_to_timedelta(tstr: str) -> timedelta: """ Convert humanized timedelta string into a Python timedelta object. Example: >>> str_to_timedelta('30min') datetime.timedelta(seconds=1800) >>> str_to_timedelta('1d1hr') datetime.timedelta(days=1, seconds=3600) >>> str_to_timedelta('2hours 15min') datetime.timedelta(seconds=8100) >>> str_to_timedelta('20sec') datetime.timedelta(seconds=20) >>> str_to_timedelta('300') datetime.timedelta(seconds=300) >>> str_to_timedelta('-1day') datetime.timedelta(days=-1) """ _rx = re.compile(r'(?P<sign>[+|-])?\s*' r'((?P<days>\d+(\.\d+)?)(d|day|days))?\s*' r'((?P<hours>\d+(\.\d+)?)(h|hr|hrs|hour|hours))?\s*' r'((?P<minutes>\d+(\.\d+)?)(m|min|mins|minute|minutes))?\s*' r'((?P<seconds>\d+(\.\d+)?)(s|sec|secs|second|seconds))?$') match = _rx.match(tstr) if not match: try: return timedelta(seconds=float(tstr)) # consider bare number string as seconds except TypeError: pass raise ValueError('Invalid time expression') groups = match.groupdict() sign = groups.pop('sign', None) if set(groups.values()) == {None}: raise ValueError('Invalid time expression') params = {n: -float(t) if sign == '-' else float(t) for n, t in groups.items() if t} return timedelta(**params) # type: ignore class
: """ Entry class represents a non-comment line on the `fstab` file. """ def __init__(self, device, mountpoint, fstype, options, d=0, p=0) -> None: self.device = device self.mountpoint = mountpoint self.fstype = fstype if not options: options = 'defaults' self.options = options self.d = d self.p = p def __eq__(self, o): return str(self) == str(o) def __str__(self): return "{} {} {} {} {} {}".format(self.device, self.mountpoint, self.fstype, self.options, self.d, self.p) class Fstab: """ Reader/writer for fstab file. Takes aiofile pointer for async I/O. It should be writable if add/remove operations are needed. NOTE: This class references Jorge Niedbalski R.'s gist snippet. We have been converted it to be compatible with Python 3 and to support async I/O. (https://gist.github.com/niedbalski/507e974ed2d54a87ad37) """ def __init__(self, fp) -> None: self._fp = fp def _hydrate_entry(self, line): return FstabEntry(*[x for x in line.strip('\n').split(' ') if x not in ('', None)]) async def get_entries(self): await self._fp.seek(0) for line in await self._fp.readlines(): try: line = line.strip() if not line.startswith("#"): yield self._hydrate_entry(line) except TypeError: pass async def get_entry_by_attr(self, attr, value): async for entry in self.get_entries(): e_attr = getattr(entry, attr) if e_attr == value: return entry return None async def add_entry(self, entry): if await self.get_entry_by_attr('device', entry.device): return False await self._fp.write(str(entry) + '\n') await self._fp.truncate() return entry async def add(self, device, mountpoint, fstype, options=None, d=0, p=0): return await self.add_entry(FstabEntry(device, mountpoint, fstype, options, d, p)) async def remove_entry(self, entry): await self._fp.seek(0) lines = await self._fp.readlines() found = False for index, line in enumerate(lines): try: if not line.strip().startswith("#"): if self._hydrate_entry(line) == entry: found = True break except TypeError: pass if not found: return False lines.remove(line) await self._fp.seek(0) await self._fp.write(''.join(lines)) await self._fp.truncate() return True async def remove_by_mountpoint(self, mountpoint): entry = await self.get_entry_by_attr('mountpoint', mountpoint) if entry: return await self.remove_entry(entry) return False
FstabEntry
identifier_name
utils.py
from __future__ import annotations import base64 from collections import OrderedDict from datetime import timedelta from itertools import chain import numbers import random import re import sys from typing import ( Any, Iterable, Iterator, Mapping, Tuple, TYPE_CHECKING, TypeVar, Union, ) import uuid if TYPE_CHECKING: from decimal import Decimal # It is a bad practice to keep all "miscellaneous" stuffs # into the single "utils" module. # Let's categorize them by purpose and domain, and keep # refactoring to use the proper module names. from .asyncio import ( # for legacy imports # noqa AsyncBarrier, cancel_tasks, current_loop, run_through, ) from .enum_extension import StringSetFlag # for legacy imports # noqa from .files import AsyncFileWriter # for legacy imports # noqa from .networking import ( # for legacy imports # noqa curl, find_free_port, ) from .types import BinarySize KT = TypeVar('KT') VT = TypeVar('VT') def env_info() -> str: """ Returns a string that contains the Python version and runtime path. """ v = sys.version_info pyver = f'Python {v.major}.{v.minor}.{v.micro}' if v.releaselevel == 'alpha': pyver += 'a' if v.releaselevel == 'beta': pyver += 'b' if v.releaselevel == 'candidate': pyver += 'rc' if v.releaselevel != 'final': pyver += str(v.serial) return f'{pyver} (env: {sys.prefix})' def odict(*args: Tuple[KT, VT]) -> OrderedDict[KT, VT]: """ A short-hand for the constructor of OrderedDict. :code:`odict(('a',1), ('b',2))` is equivalent to :code:`OrderedDict([('a',1), ('b',2)])`. """ return OrderedDict(args) def dict2kvlist(o: Mapping[KT, VT]) -> Iterable[Union[KT, VT]]: """ Serializes a dict-like object into a generator of the flatten list of repeating key-value pairs. It is useful when using HMSET method in Redis. Example: >>> list(dict2kvlist({'a': 1, 'b': 2})) ['a', 1, 'b', 2] """ return chain.from_iterable((k, v) for k, v in o.items()) def generate_uuid() -> str: u = uuid.uuid4() # Strip the last two padding characters because u always has fixed length. return base64.urlsafe_b64encode(u.bytes)[:-2].decode('ascii') def get_random_seq(length: float, num_points: int, min_distance: float) -> Iterator[float]: """ Generate a random sequence of numbers within the range [0, length] with the given number of points and the minimum distance between the points. Note that X ( = the minimum distance d x the number of points N) must be equivalent to or smaller than the length L + d to guarantee the the minimum distance between the points. If X == L + d, the points are always equally spaced with d. :return: An iterator over the generated sequence """ assert num_points * min_distance <= length + min_distance, \ 'There are too many points or it has a too large distance which cannot be fit into the given length.' extra = length - (num_points - 1) * min_distance ro = [random.uniform(0, 1) for _ in range(num_points + 1)] sum_ro = sum(ro) rn = [extra * r / sum_ro for r in ro[0:num_points]] spacing = [min_distance + rn[i] for i in range(num_points)] cumulative_sum = 0.0 for s in spacing: cumulative_sum += s yield cumulative_sum - min_distance def nmget( o: Mapping[str, Any], key_path: str, def_val: Any = None, path_delimiter: str = '.', null_as_default: bool = True, ) -> Any: """ A short-hand for retrieving a value from nested mappings ("nested-mapping-get"). At each level it checks if the given "path" component in the given key exists and return the default value whenever fails. Example: >>> o = {'a':{'b':1}, 'x': None} >>> nmget(o, 'a', 0) {'b': 1} >>> nmget(o, 'a.b', 0) 1 >>> nmget(o, 'a/b', 0, '/') 1 >>> nmget(o, 'a.c', 0) 0 >>> nmget(o, 'x', 0) 0 >>> nmget(o, 'x', 0, null_as_default=False) None """ pieces = key_path.split(path_delimiter) while pieces: p = pieces.pop(0) if o is None or p not in o: return def_val o = o[p] if o is None and null_as_default: return def_val return o def readable_size_to_bytes(expr: Any) -> BinarySize | Decimal: if isinstance(expr, numbers.Real): return BinarySize(expr) return BinarySize.from_str(expr) def str_to_timedelta(tstr: str) -> timedelta: """ Convert humanized timedelta string into a Python timedelta object. Example: >>> str_to_timedelta('30min') datetime.timedelta(seconds=1800) >>> str_to_timedelta('1d1hr') datetime.timedelta(days=1, seconds=3600) >>> str_to_timedelta('2hours 15min') datetime.timedelta(seconds=8100) >>> str_to_timedelta('20sec') datetime.timedelta(seconds=20) >>> str_to_timedelta('300') datetime.timedelta(seconds=300) >>> str_to_timedelta('-1day') datetime.timedelta(days=-1) """ _rx = re.compile(r'(?P<sign>[+|-])?\s*' r'((?P<days>\d+(\.\d+)?)(d|day|days))?\s*' r'((?P<hours>\d+(\.\d+)?)(h|hr|hrs|hour|hours))?\s*' r'((?P<minutes>\d+(\.\d+)?)(m|min|mins|minute|minutes))?\s*' r'((?P<seconds>\d+(\.\d+)?)(s|sec|secs|second|seconds))?$') match = _rx.match(tstr) if not match: try: return timedelta(seconds=float(tstr)) # consider bare number string as seconds except TypeError: pass raise ValueError('Invalid time expression') groups = match.groupdict() sign = groups.pop('sign', None) if set(groups.values()) == {None}: raise ValueError('Invalid time expression') params = {n: -float(t) if sign == '-' else float(t) for n, t in groups.items() if t} return timedelta(**params) # type: ignore class FstabEntry: """ Entry class represents a non-comment line on the `fstab` file. """ def __init__(self, device, mountpoint, fstype, options, d=0, p=0) -> None: self.device = device self.mountpoint = mountpoint self.fstype = fstype if not options: options = 'defaults' self.options = options self.d = d self.p = p def __eq__(self, o): return str(self) == str(o) def __str__(self): return "{} {} {} {} {} {}".format(self.device, self.mountpoint, self.fstype, self.options, self.d, self.p) class Fstab: """ Reader/writer for fstab file. Takes aiofile pointer for async I/O. It should be writable if add/remove operations are needed. NOTE: This class references Jorge Niedbalski R.'s gist snippet. We have been converted it to be compatible with Python 3 and to support async I/O. (https://gist.github.com/niedbalski/507e974ed2d54a87ad37) """ def __init__(self, fp) -> None: self._fp = fp def _hydrate_entry(self, line): return FstabEntry(*[x for x in line.strip('\n').split(' ') if x not in ('', None)]) async def get_entries(self): await self._fp.seek(0) for line in await self._fp.readlines(): try: line = line.strip() if not line.startswith("#"): yield self._hydrate_entry(line) except TypeError: pass async def get_entry_by_attr(self, attr, value): async for entry in self.get_entries(): e_attr = getattr(entry, attr) if e_attr == value: return entry return None async def add_entry(self, entry): if await self.get_entry_by_attr('device', entry.device): return False await self._fp.write(str(entry) + '\n') await self._fp.truncate() return entry async def add(self, device, mountpoint, fstype, options=None, d=0, p=0): return await self.add_entry(FstabEntry(device, mountpoint, fstype, options, d, p)) async def remove_entry(self, entry): await self._fp.seek(0) lines = await self._fp.readlines() found = False for index, line in enumerate(lines): try: if not line.strip().startswith("#"):
except TypeError: pass if not found: return False lines.remove(line) await self._fp.seek(0) await self._fp.write(''.join(lines)) await self._fp.truncate() return True async def remove_by_mountpoint(self, mountpoint): entry = await self.get_entry_by_attr('mountpoint', mountpoint) if entry: return await self.remove_entry(entry) return False
if self._hydrate_entry(line) == entry: found = True break
conditional_block
utils.py
from __future__ import annotations import base64 from collections import OrderedDict from datetime import timedelta from itertools import chain import numbers import random import re import sys from typing import ( Any, Iterable, Iterator, Mapping, Tuple, TYPE_CHECKING, TypeVar, Union, ) import uuid if TYPE_CHECKING: from decimal import Decimal # It is a bad practice to keep all "miscellaneous" stuffs # into the single "utils" module. # Let's categorize them by purpose and domain, and keep # refactoring to use the proper module names. from .asyncio import ( # for legacy imports # noqa AsyncBarrier, cancel_tasks, current_loop, run_through, ) from .enum_extension import StringSetFlag # for legacy imports # noqa from .files import AsyncFileWriter # for legacy imports # noqa from .networking import ( # for legacy imports # noqa curl, find_free_port, ) from .types import BinarySize KT = TypeVar('KT') VT = TypeVar('VT') def env_info() -> str: """ Returns a string that contains the Python version and runtime path. """ v = sys.version_info pyver = f'Python {v.major}.{v.minor}.{v.micro}' if v.releaselevel == 'alpha': pyver += 'a' if v.releaselevel == 'beta': pyver += 'b' if v.releaselevel == 'candidate': pyver += 'rc' if v.releaselevel != 'final': pyver += str(v.serial) return f'{pyver} (env: {sys.prefix})' def odict(*args: Tuple[KT, VT]) -> OrderedDict[KT, VT]: """ A short-hand for the constructor of OrderedDict. :code:`odict(('a',1), ('b',2))` is equivalent to :code:`OrderedDict([('a',1), ('b',2)])`. """ return OrderedDict(args) def dict2kvlist(o: Mapping[KT, VT]) -> Iterable[Union[KT, VT]]: """ Serializes a dict-like object into a generator of the flatten list of repeating key-value pairs. It is useful when using HMSET method in Redis. Example: >>> list(dict2kvlist({'a': 1, 'b': 2})) ['a', 1, 'b', 2] """ return chain.from_iterable((k, v) for k, v in o.items()) def generate_uuid() -> str: u = uuid.uuid4() # Strip the last two padding characters because u always has fixed length. return base64.urlsafe_b64encode(u.bytes)[:-2].decode('ascii') def get_random_seq(length: float, num_points: int, min_distance: float) -> Iterator[float]: """ Generate a random sequence of numbers within the range [0, length] with the given number of points and the minimum distance between the points. Note that X ( = the minimum distance d x the number of points N) must be equivalent to or smaller than the length L + d to guarantee the the minimum distance between the points. If X == L + d, the points are always equally spaced with d. :return: An iterator over the generated sequence """ assert num_points * min_distance <= length + min_distance, \ 'There are too many points or it has a too large distance which cannot be fit into the given length.' extra = length - (num_points - 1) * min_distance ro = [random.uniform(0, 1) for _ in range(num_points + 1)] sum_ro = sum(ro) rn = [extra * r / sum_ro for r in ro[0:num_points]] spacing = [min_distance + rn[i] for i in range(num_points)] cumulative_sum = 0.0 for s in spacing: cumulative_sum += s yield cumulative_sum - min_distance def nmget( o: Mapping[str, Any], key_path: str, def_val: Any = None, path_delimiter: str = '.', null_as_default: bool = True, ) -> Any: """ A short-hand for retrieving a value from nested mappings ("nested-mapping-get"). At each level it checks if the given "path" component in the given key exists and return the default value whenever fails. Example: >>> o = {'a':{'b':1}, 'x': None} >>> nmget(o, 'a', 0) {'b': 1} >>> nmget(o, 'a.b', 0) 1 >>> nmget(o, 'a/b', 0, '/') 1 >>> nmget(o, 'a.c', 0) 0 >>> nmget(o, 'x', 0) 0 >>> nmget(o, 'x', 0, null_as_default=False) None """ pieces = key_path.split(path_delimiter) while pieces: p = pieces.pop(0) if o is None or p not in o: return def_val o = o[p] if o is None and null_as_default: return def_val return o def readable_size_to_bytes(expr: Any) -> BinarySize | Decimal: if isinstance(expr, numbers.Real): return BinarySize(expr) return BinarySize.from_str(expr) def str_to_timedelta(tstr: str) -> timedelta: """ Convert humanized timedelta string into a Python timedelta object. Example: >>> str_to_timedelta('30min') datetime.timedelta(seconds=1800) >>> str_to_timedelta('1d1hr') datetime.timedelta(days=1, seconds=3600) >>> str_to_timedelta('2hours 15min') datetime.timedelta(seconds=8100) >>> str_to_timedelta('20sec') datetime.timedelta(seconds=20) >>> str_to_timedelta('300') datetime.timedelta(seconds=300) >>> str_to_timedelta('-1day') datetime.timedelta(days=-1) """ _rx = re.compile(r'(?P<sign>[+|-])?\s*' r'((?P<days>\d+(\.\d+)?)(d|day|days))?\s*' r'((?P<hours>\d+(\.\d+)?)(h|hr|hrs|hour|hours))?\s*' r'((?P<minutes>\d+(\.\d+)?)(m|min|mins|minute|minutes))?\s*' r'((?P<seconds>\d+(\.\d+)?)(s|sec|secs|second|seconds))?$') match = _rx.match(tstr) if not match: try: return timedelta(seconds=float(tstr)) # consider bare number string as seconds except TypeError: pass raise ValueError('Invalid time expression') groups = match.groupdict() sign = groups.pop('sign', None) if set(groups.values()) == {None}: raise ValueError('Invalid time expression') params = {n: -float(t) if sign == '-' else float(t) for n, t in groups.items() if t} return timedelta(**params) # type: ignore class FstabEntry: """ Entry class represents a non-comment line on the `fstab` file. """ def __init__(self, device, mountpoint, fstype, options, d=0, p=0) -> None: self.device = device self.mountpoint = mountpoint self.fstype = fstype if not options: options = 'defaults' self.options = options self.d = d self.p = p def __eq__(self, o): return str(self) == str(o) def __str__(self): return "{} {} {} {} {} {}".format(self.device, self.mountpoint, self.fstype, self.options, self.d, self.p) class Fstab: """ Reader/writer for fstab file. Takes aiofile pointer for async I/O. It should be writable if add/remove operations are needed. NOTE: This class references Jorge Niedbalski R.'s gist snippet. We have been converted it to be compatible with Python 3 and to support async I/O. (https://gist.github.com/niedbalski/507e974ed2d54a87ad37) """ def __init__(self, fp) -> None: self._fp = fp def _hydrate_entry(self, line): return FstabEntry(*[x for x in line.strip('\n').split(' ') if x not in ('', None)]) async def get_entries(self): await self._fp.seek(0) for line in await self._fp.readlines(): try: line = line.strip() if not line.startswith("#"): yield self._hydrate_entry(line) except TypeError: pass async def get_entry_by_attr(self, attr, value): async for entry in self.get_entries(): e_attr = getattr(entry, attr) if e_attr == value: return entry return None async def add_entry(self, entry): if await self.get_entry_by_attr('device', entry.device): return False await self._fp.write(str(entry) + '\n') await self._fp.truncate() return entry async def add(self, device, mountpoint, fstype, options=None, d=0, p=0): return await self.add_entry(FstabEntry(device, mountpoint, fstype, options, d, p)) async def remove_entry(self, entry):
async def remove_by_mountpoint(self, mountpoint): entry = await self.get_entry_by_attr('mountpoint', mountpoint) if entry: return await self.remove_entry(entry) return False
await self._fp.seek(0) lines = await self._fp.readlines() found = False for index, line in enumerate(lines): try: if not line.strip().startswith("#"): if self._hydrate_entry(line) == entry: found = True break except TypeError: pass if not found: return False lines.remove(line) await self._fp.seek(0) await self._fp.write(''.join(lines)) await self._fp.truncate() return True
identifier_body
mavlog.py
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def
(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parser.add_argument("--device", required=True, help="serial port") parser.add_argument("--log", type=argparse.FileType('w'), help="Log file") parser.add_argument("--baudrate", type=int, help="serial port baud rate", default=57600) args = parser.parse_args() conn = mavutil.mavlink_connection(args.device, baud=args.baudrate) conn.logfile = args.log while True: msg = conn.recv_msg() if args.verbose and msg is not None: print(msg) if __name__ == '__main__': main()
main
identifier_name
mavlog.py
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parser.add_argument("--device", required=True, help="serial port") parser.add_argument("--log", type=argparse.FileType('w'), help="Log file") parser.add_argument("--baudrate", type=int, help="serial port baud rate", default=57600) args = parser.parse_args() conn = mavutil.mavlink_connection(args.device, baud=args.baudrate) conn.logfile = args.log while True:
if __name__ == '__main__': main()
msg = conn.recv_msg() if args.verbose and msg is not None: print(msg)
conditional_block
mavlog.py
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parser.add_argument("--device", required=True, help="serial port") parser.add_argument("--log", type=argparse.FileType('w'), help="Log file") parser.add_argument("--baudrate", type=int, help="serial port baud rate", default=57600) args = parser.parse_args() conn = mavutil.mavlink_connection(args.device, baud=args.baudrate) conn.logfile = args.log while True: msg = conn.recv_msg() if args.verbose and msg is not None: print(msg) if __name__ == '__main__':
main()
random_line_split
mavlog.py
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def main():
if __name__ == '__main__': main()
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parser.add_argument("--device", required=True, help="serial port") parser.add_argument("--log", type=argparse.FileType('w'), help="Log file") parser.add_argument("--baudrate", type=int, help="serial port baud rate", default=57600) args = parser.parse_args() conn = mavutil.mavlink_connection(args.device, baud=args.baudrate) conn.logfile = args.log while True: msg = conn.recv_msg() if args.verbose and msg is not None: print(msg)
identifier_body
server.py
############################################################################### # # # Peekaboo Extended Email Attachment Behavior Observation Owl # # # # server.py # ############################################################################### # # # Copyright (C) 2016-2020 science + computing ag # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or (at # # your option) any later version. # # # # This program is distributed in the hope that it will be useful, but # # WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # # General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### """ This module implements the Peekaboo server, i.e. the frontend to the client. """ import asyncio import email.utils import logging import urllib.parse import sanic import sanic.headers import sanic.response from peekaboo.db import PeekabooDatabaseError logger = logging.getLogger(__name__) class PeekabooServer: """ A class wrapping the server components of Peekaboo. """ def __init__(self, host, port, job_queue, sample_factory, request_queue_size, db_con): """ Initialise a new server and start it. All error conditions are returned as exceptions. @param host: The local address to bind the socket to. @type host: String @param port: The local port to listen on for client connections. @type port: int @param job_queue: A reference to the job queue for submission of samples. @type job_queue: JobQueue @param sample_factory: A reference to a sample factory for creating new samples. @type sample_factory: SampleFactory @param request_queue_size: Number of requests that may be pending on the socket. @type request_queue_size: int """ logger.debug('Starting up server.') self.app = sanic.Sanic("PeekabooAV", configure_logging=False) self.app.config.FALLBACK_ERROR_FORMAT = "json" # silence sanic to a reasonable amount logging.getLogger('sanic.root').setLevel(logging.WARNING) logging.getLogger('sanic.access').setLevel(logging.WARNING) self.loop = asyncio.get_event_loop() self.server_coroutine = self.app.create_server( host=host, port=port, return_asyncio_server=True, backlog=request_queue_size, asyncio_server_kwargs=dict(start_serving=False)) self.server = None self.job_queue = job_queue self.sample_factory = sample_factory self.db_con = db_con # remember for diagnostics self.host = host self.port = port self.app.add_route(self.hello, '/') self.app.add_route(self.ping, '/ping') self.app.add_route(self.scan, "/v1/scan", methods=['POST']) self.app.add_route( self.report, '/v1/report/<job_id:int>', methods=['GET']) async def hello(self, _): """ hello endpoint as fallback and catch all @returns: hello world json response """ return sanic.response.json({'hello': 'PeekabooAV'}) async def ping(self, _): """ ping endpoint for diagnostics @returns: pong json response """ return sanic.response.json({'answer': 'pong'}) async def scan(self, request): """ scan endpoint for job submission @param request: sanic request object @type request: sanic.Request @returns: json response containing ID of newly created job """ # this is sanic's multipart/form-data parser in a version that knows # that our file field contains binary data. This allows transferring # files without a filename. The generic parser would treat those as # text fields and try to decode them using the form charset or UTF-8 as # a fallback and cause errors such as: UnicodeDecodeError: 'utf-8' # codec can't decode byte 0xc0 in position 1: invalid start byte content_type, parameters = sanic.headers.parse_content_header( request.content_type) # application/x-www-form-urlencoded is inefficient at transporting # binary data. Also it needs a separate field to transfer the filename. # Make clear here that we do not support that format (yet). if content_type != 'multipart/form-data': logger.error('Invalid content type %s', content_type) return sanic.response.json( {'message': 'Invalid content type, use multipart/form-data'}, 400) boundary = parameters["boundary"].encode("utf-8") form_parts = request.body.split(boundary) # split above leaves preamble in form_parts[0] and epilogue in # form_parts[2] num_fields = len(form_parts) - 2 if num_fields <= 0: logger.error('Invalid MIME structure in request, no fields ' 'or preamble or epilogue missing') return sanic.response.json( {'message': 'Invalid MIME structure in request'}, 400) if num_fields != 1: logger.error('Invalid number of fields in form: %d', num_fields) return sanic.response.json( {'message': 'Invalid number of fields in form, we accept ' 'only one field "file"'}, 400) form_part = form_parts[1] file_name = None content_type = None field_name = None line_index = 2 line_end_index = 0 while line_end_index != -1: line_end_index = form_part.find(b'\r\n', line_index) # this constitutes a hard requirement for the multipart headers # (and filenames therein) to be UTF-8-encoded. There are some # obscure provisions for transferring an encoding in RFC7578 # section 5.1.2 for HTML forms which don't apply here so its # fallback to UTF-8 applies. This is no problem for our field name # (ASCII) and file names in RFC2231 encoding. For HTML5-style # percent-encoded filenames it means that whatever isn't # percent-encoded needs to be UTF-8 encoded. There are no rules in # HTML5 currently to percent-encode any UTF-8 byte sequences. form_line = form_part[line_index:line_end_index].decode('utf-8') line_index = line_end_index + 2 if not form_line: break colon_index = form_line.index(':') idx = colon_index + 2 form_header_field = form_line[0:colon_index].lower() # parse_content_header() reverts some of the percent encoding as # per HTML5 WHATWG spec. As it is a "living standard" (i.e. moving # target), it has changed over the years. There used to be # backslash doubling and explicit control sequence encoding. As of # this writing this has been changed to escaping only newline, # linefeed and double quote. Sanic only supports the double quote # part of that: %22 are reverted back to %. Luckily this interacts # reasonably well with RFC2231 decoding below since that would do # the same. # # There is no way to tell what version of the standard (or draft # thereof) the client was following when encoding. It seems accepted # practice in the browser world to just require current versions of # everything so their behaviour hopefully converges eventually. # This is also the reason why we do not try to improve upon it here # because it's bound to become outdated. # # NOTE: Since we fork the sanic code here we need to keep track of # its changes, particularly how it interacts with RFC2231 encoding # if escaping of the escape character %25 is ever added to the # HTML5 WHATWG spec. In that case parse_content_header() would # start breaking the RFC2231 encoding which would explain why its # use is forbidden in RFC7578 section 4.2 via RFC5987. form_header_value, form_parameters = sanic.headers.parse_content_header( form_line[idx:] ) if form_header_field == 'content-disposition': field_name = form_parameters.get('name') file_name = form_parameters.get('filename') # non-ASCII filenames in RFC2231, "filename*" format if file_name is None and form_parameters.get('filename*'): encoding, _, value = email.utils.decode_rfc2231( form_parameters['filename*'] ) file_name = urllib.parse.unquote(value, encoding=encoding) elif form_header_field == 'content-type': content_type = form_header_value if field_name != 'file': logger.error('Field file missing from request') return sanic.response.json( {'message': 'Field "file" missing from request'}, 400) file_content = form_part[line_index:-4] content_disposition = request.headers.get('x-content-disposition') sample = self.sample_factory.make_sample( file_content, file_name, content_type, content_disposition) try: await self.db_con.analysis_add(sample) except PeekabooDatabaseError as dberr: logger.error('Failed to add analysis to database: %s', dberr) return sanic.response.json( {'message': 'Failed to add analysis to database'}, 500) if not self.job_queue.submit(sample): logger.error('Error submitting sample to job queue') return sanic.response.json( {'message': 'Error submitting sample to job queue'}, 500) # send answer to client return sanic.response.json({'job_id': sample.id}, 200) async def report(self, _, job_id): """ report endpoint for report retrieval by job ID @param request: sanic request object @type request: sanic.Request @param job_id: job ID extracted from endpoint path @type job_id: int @returns: report json response """ if not job_id: return sanic.response.json( {'message': 'job ID missing from request'}, 400) try: job_info = await self.db_con.analysis_retrieve(job_id) except PeekabooDatabaseError as dberr: logger.error('Failed to retrieve analysis result from ' 'database: %s', dberr) return sanic.response.json( {'message': 'Failed to retrieve analysis result ' 'from database'}, 500) if job_info is None: logger.debug('No analysis result yet for job %d', job_id) return sanic.response.json( {'message': 'No analysis result yet for job %d' % job_id}, 404) reason, result = job_info return sanic.response.json({ 'result': result.name, 'reason': reason, # FIXME: depends on saving the report to the database # 'report': report, }, 200) def serve(self): """ Serves requests until shutdown is requested from the outside. """ self.server = self.loop.run_until_complete(self.server_coroutine) # sanic 21.9 introduced an explicit startup that finalizes the app, # particularly the request routing. So we need to run it if present. if hasattr(self.server, 'startup'): self.loop.run_until_complete(self.server.startup()) self.loop.run_until_complete(self.server.start_serving()) logger.info('Peekaboo server is now listening on %s:%d', self.host, self.port) self.loop.run_until_complete(self.server.wait_closed()) logger.debug('Server shut down.') def shut_down(self): """ Triggers a shutdown of the server, used by the signal handler and potentially other components to cause the main loop to exit. """ logger.debug('Server shutdown requested.') if self.server is not None:
self.server.close()
conditional_block
server.py
############################################################################### # # # Peekaboo Extended Email Attachment Behavior Observation Owl # # # # server.py # ############################################################################### # # # Copyright (C) 2016-2020 science + computing ag # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or (at # # your option) any later version. # # # # This program is distributed in the hope that it will be useful, but # # WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # # General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### """ This module implements the Peekaboo server, i.e. the frontend to the client. """ import asyncio import email.utils import logging import urllib.parse import sanic import sanic.headers import sanic.response from peekaboo.db import PeekabooDatabaseError logger = logging.getLogger(__name__) class PeekabooServer: """ A class wrapping the server components of Peekaboo. """ def __init__(self, host, port, job_queue, sample_factory, request_queue_size, db_con): """ Initialise a new server and start it. All error conditions are returned as exceptions. @param host: The local address to bind the socket to. @type host: String @param port: The local port to listen on for client connections. @type port: int @param job_queue: A reference to the job queue for submission of samples. @type job_queue: JobQueue @param sample_factory: A reference to a sample factory for creating new samples. @type sample_factory: SampleFactory @param request_queue_size: Number of requests that may be pending on the socket. @type request_queue_size: int """ logger.debug('Starting up server.') self.app = sanic.Sanic("PeekabooAV", configure_logging=False) self.app.config.FALLBACK_ERROR_FORMAT = "json" # silence sanic to a reasonable amount logging.getLogger('sanic.root').setLevel(logging.WARNING) logging.getLogger('sanic.access').setLevel(logging.WARNING) self.loop = asyncio.get_event_loop() self.server_coroutine = self.app.create_server( host=host, port=port, return_asyncio_server=True, backlog=request_queue_size, asyncio_server_kwargs=dict(start_serving=False)) self.server = None self.job_queue = job_queue self.sample_factory = sample_factory self.db_con = db_con # remember for diagnostics self.host = host self.port = port self.app.add_route(self.hello, '/') self.app.add_route(self.ping, '/ping') self.app.add_route(self.scan, "/v1/scan", methods=['POST']) self.app.add_route( self.report, '/v1/report/<job_id:int>', methods=['GET']) async def hello(self, _):
async def ping(self, _): """ ping endpoint for diagnostics @returns: pong json response """ return sanic.response.json({'answer': 'pong'}) async def scan(self, request): """ scan endpoint for job submission @param request: sanic request object @type request: sanic.Request @returns: json response containing ID of newly created job """ # this is sanic's multipart/form-data parser in a version that knows # that our file field contains binary data. This allows transferring # files without a filename. The generic parser would treat those as # text fields and try to decode them using the form charset or UTF-8 as # a fallback and cause errors such as: UnicodeDecodeError: 'utf-8' # codec can't decode byte 0xc0 in position 1: invalid start byte content_type, parameters = sanic.headers.parse_content_header( request.content_type) # application/x-www-form-urlencoded is inefficient at transporting # binary data. Also it needs a separate field to transfer the filename. # Make clear here that we do not support that format (yet). if content_type != 'multipart/form-data': logger.error('Invalid content type %s', content_type) return sanic.response.json( {'message': 'Invalid content type, use multipart/form-data'}, 400) boundary = parameters["boundary"].encode("utf-8") form_parts = request.body.split(boundary) # split above leaves preamble in form_parts[0] and epilogue in # form_parts[2] num_fields = len(form_parts) - 2 if num_fields <= 0: logger.error('Invalid MIME structure in request, no fields ' 'or preamble or epilogue missing') return sanic.response.json( {'message': 'Invalid MIME structure in request'}, 400) if num_fields != 1: logger.error('Invalid number of fields in form: %d', num_fields) return sanic.response.json( {'message': 'Invalid number of fields in form, we accept ' 'only one field "file"'}, 400) form_part = form_parts[1] file_name = None content_type = None field_name = None line_index = 2 line_end_index = 0 while line_end_index != -1: line_end_index = form_part.find(b'\r\n', line_index) # this constitutes a hard requirement for the multipart headers # (and filenames therein) to be UTF-8-encoded. There are some # obscure provisions for transferring an encoding in RFC7578 # section 5.1.2 for HTML forms which don't apply here so its # fallback to UTF-8 applies. This is no problem for our field name # (ASCII) and file names in RFC2231 encoding. For HTML5-style # percent-encoded filenames it means that whatever isn't # percent-encoded needs to be UTF-8 encoded. There are no rules in # HTML5 currently to percent-encode any UTF-8 byte sequences. form_line = form_part[line_index:line_end_index].decode('utf-8') line_index = line_end_index + 2 if not form_line: break colon_index = form_line.index(':') idx = colon_index + 2 form_header_field = form_line[0:colon_index].lower() # parse_content_header() reverts some of the percent encoding as # per HTML5 WHATWG spec. As it is a "living standard" (i.e. moving # target), it has changed over the years. There used to be # backslash doubling and explicit control sequence encoding. As of # this writing this has been changed to escaping only newline, # linefeed and double quote. Sanic only supports the double quote # part of that: %22 are reverted back to %. Luckily this interacts # reasonably well with RFC2231 decoding below since that would do # the same. # # There is no way to tell what version of the standard (or draft # thereof) the client was following when encoding. It seems accepted # practice in the browser world to just require current versions of # everything so their behaviour hopefully converges eventually. # This is also the reason why we do not try to improve upon it here # because it's bound to become outdated. # # NOTE: Since we fork the sanic code here we need to keep track of # its changes, particularly how it interacts with RFC2231 encoding # if escaping of the escape character %25 is ever added to the # HTML5 WHATWG spec. In that case parse_content_header() would # start breaking the RFC2231 encoding which would explain why its # use is forbidden in RFC7578 section 4.2 via RFC5987. form_header_value, form_parameters = sanic.headers.parse_content_header( form_line[idx:] ) if form_header_field == 'content-disposition': field_name = form_parameters.get('name') file_name = form_parameters.get('filename') # non-ASCII filenames in RFC2231, "filename*" format if file_name is None and form_parameters.get('filename*'): encoding, _, value = email.utils.decode_rfc2231( form_parameters['filename*'] ) file_name = urllib.parse.unquote(value, encoding=encoding) elif form_header_field == 'content-type': content_type = form_header_value if field_name != 'file': logger.error('Field file missing from request') return sanic.response.json( {'message': 'Field "file" missing from request'}, 400) file_content = form_part[line_index:-4] content_disposition = request.headers.get('x-content-disposition') sample = self.sample_factory.make_sample( file_content, file_name, content_type, content_disposition) try: await self.db_con.analysis_add(sample) except PeekabooDatabaseError as dberr: logger.error('Failed to add analysis to database: %s', dberr) return sanic.response.json( {'message': 'Failed to add analysis to database'}, 500) if not self.job_queue.submit(sample): logger.error('Error submitting sample to job queue') return sanic.response.json( {'message': 'Error submitting sample to job queue'}, 500) # send answer to client return sanic.response.json({'job_id': sample.id}, 200) async def report(self, _, job_id): """ report endpoint for report retrieval by job ID @param request: sanic request object @type request: sanic.Request @param job_id: job ID extracted from endpoint path @type job_id: int @returns: report json response """ if not job_id: return sanic.response.json( {'message': 'job ID missing from request'}, 400) try: job_info = await self.db_con.analysis_retrieve(job_id) except PeekabooDatabaseError as dberr: logger.error('Failed to retrieve analysis result from ' 'database: %s', dberr) return sanic.response.json( {'message': 'Failed to retrieve analysis result ' 'from database'}, 500) if job_info is None: logger.debug('No analysis result yet for job %d', job_id) return sanic.response.json( {'message': 'No analysis result yet for job %d' % job_id}, 404) reason, result = job_info return sanic.response.json({ 'result': result.name, 'reason': reason, # FIXME: depends on saving the report to the database # 'report': report, }, 200) def serve(self): """ Serves requests until shutdown is requested from the outside. """ self.server = self.loop.run_until_complete(self.server_coroutine) # sanic 21.9 introduced an explicit startup that finalizes the app, # particularly the request routing. So we need to run it if present. if hasattr(self.server, 'startup'): self.loop.run_until_complete(self.server.startup()) self.loop.run_until_complete(self.server.start_serving()) logger.info('Peekaboo server is now listening on %s:%d', self.host, self.port) self.loop.run_until_complete(self.server.wait_closed()) logger.debug('Server shut down.') def shut_down(self): """ Triggers a shutdown of the server, used by the signal handler and potentially other components to cause the main loop to exit. """ logger.debug('Server shutdown requested.') if self.server is not None: self.server.close()
""" hello endpoint as fallback and catch all @returns: hello world json response """ return sanic.response.json({'hello': 'PeekabooAV'})
identifier_body
server.py
############################################################################### # # # Peekaboo Extended Email Attachment Behavior Observation Owl # # # # server.py # ############################################################################### # # # Copyright (C) 2016-2020 science + computing ag # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or (at # # your option) any later version. # # # # This program is distributed in the hope that it will be useful, but # # WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # # General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### """ This module implements the Peekaboo server, i.e. the frontend to the client. """ import asyncio import email.utils import logging import urllib.parse import sanic import sanic.headers import sanic.response from peekaboo.db import PeekabooDatabaseError logger = logging.getLogger(__name__) class
: """ A class wrapping the server components of Peekaboo. """ def __init__(self, host, port, job_queue, sample_factory, request_queue_size, db_con): """ Initialise a new server and start it. All error conditions are returned as exceptions. @param host: The local address to bind the socket to. @type host: String @param port: The local port to listen on for client connections. @type port: int @param job_queue: A reference to the job queue for submission of samples. @type job_queue: JobQueue @param sample_factory: A reference to a sample factory for creating new samples. @type sample_factory: SampleFactory @param request_queue_size: Number of requests that may be pending on the socket. @type request_queue_size: int """ logger.debug('Starting up server.') self.app = sanic.Sanic("PeekabooAV", configure_logging=False) self.app.config.FALLBACK_ERROR_FORMAT = "json" # silence sanic to a reasonable amount logging.getLogger('sanic.root').setLevel(logging.WARNING) logging.getLogger('sanic.access').setLevel(logging.WARNING) self.loop = asyncio.get_event_loop() self.server_coroutine = self.app.create_server( host=host, port=port, return_asyncio_server=True, backlog=request_queue_size, asyncio_server_kwargs=dict(start_serving=False)) self.server = None self.job_queue = job_queue self.sample_factory = sample_factory self.db_con = db_con # remember for diagnostics self.host = host self.port = port self.app.add_route(self.hello, '/') self.app.add_route(self.ping, '/ping') self.app.add_route(self.scan, "/v1/scan", methods=['POST']) self.app.add_route( self.report, '/v1/report/<job_id:int>', methods=['GET']) async def hello(self, _): """ hello endpoint as fallback and catch all @returns: hello world json response """ return sanic.response.json({'hello': 'PeekabooAV'}) async def ping(self, _): """ ping endpoint for diagnostics @returns: pong json response """ return sanic.response.json({'answer': 'pong'}) async def scan(self, request): """ scan endpoint for job submission @param request: sanic request object @type request: sanic.Request @returns: json response containing ID of newly created job """ # this is sanic's multipart/form-data parser in a version that knows # that our file field contains binary data. This allows transferring # files without a filename. The generic parser would treat those as # text fields and try to decode them using the form charset or UTF-8 as # a fallback and cause errors such as: UnicodeDecodeError: 'utf-8' # codec can't decode byte 0xc0 in position 1: invalid start byte content_type, parameters = sanic.headers.parse_content_header( request.content_type) # application/x-www-form-urlencoded is inefficient at transporting # binary data. Also it needs a separate field to transfer the filename. # Make clear here that we do not support that format (yet). if content_type != 'multipart/form-data': logger.error('Invalid content type %s', content_type) return sanic.response.json( {'message': 'Invalid content type, use multipart/form-data'}, 400) boundary = parameters["boundary"].encode("utf-8") form_parts = request.body.split(boundary) # split above leaves preamble in form_parts[0] and epilogue in # form_parts[2] num_fields = len(form_parts) - 2 if num_fields <= 0: logger.error('Invalid MIME structure in request, no fields ' 'or preamble or epilogue missing') return sanic.response.json( {'message': 'Invalid MIME structure in request'}, 400) if num_fields != 1: logger.error('Invalid number of fields in form: %d', num_fields) return sanic.response.json( {'message': 'Invalid number of fields in form, we accept ' 'only one field "file"'}, 400) form_part = form_parts[1] file_name = None content_type = None field_name = None line_index = 2 line_end_index = 0 while line_end_index != -1: line_end_index = form_part.find(b'\r\n', line_index) # this constitutes a hard requirement for the multipart headers # (and filenames therein) to be UTF-8-encoded. There are some # obscure provisions for transferring an encoding in RFC7578 # section 5.1.2 for HTML forms which don't apply here so its # fallback to UTF-8 applies. This is no problem for our field name # (ASCII) and file names in RFC2231 encoding. For HTML5-style # percent-encoded filenames it means that whatever isn't # percent-encoded needs to be UTF-8 encoded. There are no rules in # HTML5 currently to percent-encode any UTF-8 byte sequences. form_line = form_part[line_index:line_end_index].decode('utf-8') line_index = line_end_index + 2 if not form_line: break colon_index = form_line.index(':') idx = colon_index + 2 form_header_field = form_line[0:colon_index].lower() # parse_content_header() reverts some of the percent encoding as # per HTML5 WHATWG spec. As it is a "living standard" (i.e. moving # target), it has changed over the years. There used to be # backslash doubling and explicit control sequence encoding. As of # this writing this has been changed to escaping only newline, # linefeed and double quote. Sanic only supports the double quote # part of that: %22 are reverted back to %. Luckily this interacts # reasonably well with RFC2231 decoding below since that would do # the same. # # There is no way to tell what version of the standard (or draft # thereof) the client was following when encoding. It seems accepted # practice in the browser world to just require current versions of # everything so their behaviour hopefully converges eventually. # This is also the reason why we do not try to improve upon it here # because it's bound to become outdated. # # NOTE: Since we fork the sanic code here we need to keep track of # its changes, particularly how it interacts with RFC2231 encoding # if escaping of the escape character %25 is ever added to the # HTML5 WHATWG spec. In that case parse_content_header() would # start breaking the RFC2231 encoding which would explain why its # use is forbidden in RFC7578 section 4.2 via RFC5987. form_header_value, form_parameters = sanic.headers.parse_content_header( form_line[idx:] ) if form_header_field == 'content-disposition': field_name = form_parameters.get('name') file_name = form_parameters.get('filename') # non-ASCII filenames in RFC2231, "filename*" format if file_name is None and form_parameters.get('filename*'): encoding, _, value = email.utils.decode_rfc2231( form_parameters['filename*'] ) file_name = urllib.parse.unquote(value, encoding=encoding) elif form_header_field == 'content-type': content_type = form_header_value if field_name != 'file': logger.error('Field file missing from request') return sanic.response.json( {'message': 'Field "file" missing from request'}, 400) file_content = form_part[line_index:-4] content_disposition = request.headers.get('x-content-disposition') sample = self.sample_factory.make_sample( file_content, file_name, content_type, content_disposition) try: await self.db_con.analysis_add(sample) except PeekabooDatabaseError as dberr: logger.error('Failed to add analysis to database: %s', dberr) return sanic.response.json( {'message': 'Failed to add analysis to database'}, 500) if not self.job_queue.submit(sample): logger.error('Error submitting sample to job queue') return sanic.response.json( {'message': 'Error submitting sample to job queue'}, 500) # send answer to client return sanic.response.json({'job_id': sample.id}, 200) async def report(self, _, job_id): """ report endpoint for report retrieval by job ID @param request: sanic request object @type request: sanic.Request @param job_id: job ID extracted from endpoint path @type job_id: int @returns: report json response """ if not job_id: return sanic.response.json( {'message': 'job ID missing from request'}, 400) try: job_info = await self.db_con.analysis_retrieve(job_id) except PeekabooDatabaseError as dberr: logger.error('Failed to retrieve analysis result from ' 'database: %s', dberr) return sanic.response.json( {'message': 'Failed to retrieve analysis result ' 'from database'}, 500) if job_info is None: logger.debug('No analysis result yet for job %d', job_id) return sanic.response.json( {'message': 'No analysis result yet for job %d' % job_id}, 404) reason, result = job_info return sanic.response.json({ 'result': result.name, 'reason': reason, # FIXME: depends on saving the report to the database # 'report': report, }, 200) def serve(self): """ Serves requests until shutdown is requested from the outside. """ self.server = self.loop.run_until_complete(self.server_coroutine) # sanic 21.9 introduced an explicit startup that finalizes the app, # particularly the request routing. So we need to run it if present. if hasattr(self.server, 'startup'): self.loop.run_until_complete(self.server.startup()) self.loop.run_until_complete(self.server.start_serving()) logger.info('Peekaboo server is now listening on %s:%d', self.host, self.port) self.loop.run_until_complete(self.server.wait_closed()) logger.debug('Server shut down.') def shut_down(self): """ Triggers a shutdown of the server, used by the signal handler and potentially other components to cause the main loop to exit. """ logger.debug('Server shutdown requested.') if self.server is not None: self.server.close()
PeekabooServer
identifier_name
server.py
############################################################################### # # # Peekaboo Extended Email Attachment Behavior Observation Owl # # # # server.py # ############################################################################### # # # Copyright (C) 2016-2020 science + computing ag # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or (at # # your option) any later version. # # # # This program is distributed in the hope that it will be useful, but # # WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # # General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### """ This module implements the Peekaboo server, i.e. the frontend to the client. """ import asyncio import email.utils import logging import urllib.parse import sanic import sanic.headers import sanic.response from peekaboo.db import PeekabooDatabaseError logger = logging.getLogger(__name__) class PeekabooServer: """ A class wrapping the server components of Peekaboo. """ def __init__(self, host, port, job_queue, sample_factory, request_queue_size, db_con): """ Initialise a new server and start it. All error conditions are returned as exceptions. @param host: The local address to bind the socket to. @type host: String @param port: The local port to listen on for client connections. @type port: int @param job_queue: A reference to the job queue for submission of samples. @type job_queue: JobQueue @param sample_factory: A reference to a sample factory for creating new
@type request_queue_size: int """ logger.debug('Starting up server.') self.app = sanic.Sanic("PeekabooAV", configure_logging=False) self.app.config.FALLBACK_ERROR_FORMAT = "json" # silence sanic to a reasonable amount logging.getLogger('sanic.root').setLevel(logging.WARNING) logging.getLogger('sanic.access').setLevel(logging.WARNING) self.loop = asyncio.get_event_loop() self.server_coroutine = self.app.create_server( host=host, port=port, return_asyncio_server=True, backlog=request_queue_size, asyncio_server_kwargs=dict(start_serving=False)) self.server = None self.job_queue = job_queue self.sample_factory = sample_factory self.db_con = db_con # remember for diagnostics self.host = host self.port = port self.app.add_route(self.hello, '/') self.app.add_route(self.ping, '/ping') self.app.add_route(self.scan, "/v1/scan", methods=['POST']) self.app.add_route( self.report, '/v1/report/<job_id:int>', methods=['GET']) async def hello(self, _): """ hello endpoint as fallback and catch all @returns: hello world json response """ return sanic.response.json({'hello': 'PeekabooAV'}) async def ping(self, _): """ ping endpoint for diagnostics @returns: pong json response """ return sanic.response.json({'answer': 'pong'}) async def scan(self, request): """ scan endpoint for job submission @param request: sanic request object @type request: sanic.Request @returns: json response containing ID of newly created job """ # this is sanic's multipart/form-data parser in a version that knows # that our file field contains binary data. This allows transferring # files without a filename. The generic parser would treat those as # text fields and try to decode them using the form charset or UTF-8 as # a fallback and cause errors such as: UnicodeDecodeError: 'utf-8' # codec can't decode byte 0xc0 in position 1: invalid start byte content_type, parameters = sanic.headers.parse_content_header( request.content_type) # application/x-www-form-urlencoded is inefficient at transporting # binary data. Also it needs a separate field to transfer the filename. # Make clear here that we do not support that format (yet). if content_type != 'multipart/form-data': logger.error('Invalid content type %s', content_type) return sanic.response.json( {'message': 'Invalid content type, use multipart/form-data'}, 400) boundary = parameters["boundary"].encode("utf-8") form_parts = request.body.split(boundary) # split above leaves preamble in form_parts[0] and epilogue in # form_parts[2] num_fields = len(form_parts) - 2 if num_fields <= 0: logger.error('Invalid MIME structure in request, no fields ' 'or preamble or epilogue missing') return sanic.response.json( {'message': 'Invalid MIME structure in request'}, 400) if num_fields != 1: logger.error('Invalid number of fields in form: %d', num_fields) return sanic.response.json( {'message': 'Invalid number of fields in form, we accept ' 'only one field "file"'}, 400) form_part = form_parts[1] file_name = None content_type = None field_name = None line_index = 2 line_end_index = 0 while line_end_index != -1: line_end_index = form_part.find(b'\r\n', line_index) # this constitutes a hard requirement for the multipart headers # (and filenames therein) to be UTF-8-encoded. There are some # obscure provisions for transferring an encoding in RFC7578 # section 5.1.2 for HTML forms which don't apply here so its # fallback to UTF-8 applies. This is no problem for our field name # (ASCII) and file names in RFC2231 encoding. For HTML5-style # percent-encoded filenames it means that whatever isn't # percent-encoded needs to be UTF-8 encoded. There are no rules in # HTML5 currently to percent-encode any UTF-8 byte sequences. form_line = form_part[line_index:line_end_index].decode('utf-8') line_index = line_end_index + 2 if not form_line: break colon_index = form_line.index(':') idx = colon_index + 2 form_header_field = form_line[0:colon_index].lower() # parse_content_header() reverts some of the percent encoding as # per HTML5 WHATWG spec. As it is a "living standard" (i.e. moving # target), it has changed over the years. There used to be # backslash doubling and explicit control sequence encoding. As of # this writing this has been changed to escaping only newline, # linefeed and double quote. Sanic only supports the double quote # part of that: %22 are reverted back to %. Luckily this interacts # reasonably well with RFC2231 decoding below since that would do # the same. # # There is no way to tell what version of the standard (or draft # thereof) the client was following when encoding. It seems accepted # practice in the browser world to just require current versions of # everything so their behaviour hopefully converges eventually. # This is also the reason why we do not try to improve upon it here # because it's bound to become outdated. # # NOTE: Since we fork the sanic code here we need to keep track of # its changes, particularly how it interacts with RFC2231 encoding # if escaping of the escape character %25 is ever added to the # HTML5 WHATWG spec. In that case parse_content_header() would # start breaking the RFC2231 encoding which would explain why its # use is forbidden in RFC7578 section 4.2 via RFC5987. form_header_value, form_parameters = sanic.headers.parse_content_header( form_line[idx:] ) if form_header_field == 'content-disposition': field_name = form_parameters.get('name') file_name = form_parameters.get('filename') # non-ASCII filenames in RFC2231, "filename*" format if file_name is None and form_parameters.get('filename*'): encoding, _, value = email.utils.decode_rfc2231( form_parameters['filename*'] ) file_name = urllib.parse.unquote(value, encoding=encoding) elif form_header_field == 'content-type': content_type = form_header_value if field_name != 'file': logger.error('Field file missing from request') return sanic.response.json( {'message': 'Field "file" missing from request'}, 400) file_content = form_part[line_index:-4] content_disposition = request.headers.get('x-content-disposition') sample = self.sample_factory.make_sample( file_content, file_name, content_type, content_disposition) try: await self.db_con.analysis_add(sample) except PeekabooDatabaseError as dberr: logger.error('Failed to add analysis to database: %s', dberr) return sanic.response.json( {'message': 'Failed to add analysis to database'}, 500) if not self.job_queue.submit(sample): logger.error('Error submitting sample to job queue') return sanic.response.json( {'message': 'Error submitting sample to job queue'}, 500) # send answer to client return sanic.response.json({'job_id': sample.id}, 200) async def report(self, _, job_id): """ report endpoint for report retrieval by job ID @param request: sanic request object @type request: sanic.Request @param job_id: job ID extracted from endpoint path @type job_id: int @returns: report json response """ if not job_id: return sanic.response.json( {'message': 'job ID missing from request'}, 400) try: job_info = await self.db_con.analysis_retrieve(job_id) except PeekabooDatabaseError as dberr: logger.error('Failed to retrieve analysis result from ' 'database: %s', dberr) return sanic.response.json( {'message': 'Failed to retrieve analysis result ' 'from database'}, 500) if job_info is None: logger.debug('No analysis result yet for job %d', job_id) return sanic.response.json( {'message': 'No analysis result yet for job %d' % job_id}, 404) reason, result = job_info return sanic.response.json({ 'result': result.name, 'reason': reason, # FIXME: depends on saving the report to the database # 'report': report, }, 200) def serve(self): """ Serves requests until shutdown is requested from the outside. """ self.server = self.loop.run_until_complete(self.server_coroutine) # sanic 21.9 introduced an explicit startup that finalizes the app, # particularly the request routing. So we need to run it if present. if hasattr(self.server, 'startup'): self.loop.run_until_complete(self.server.startup()) self.loop.run_until_complete(self.server.start_serving()) logger.info('Peekaboo server is now listening on %s:%d', self.host, self.port) self.loop.run_until_complete(self.server.wait_closed()) logger.debug('Server shut down.') def shut_down(self): """ Triggers a shutdown of the server, used by the signal handler and potentially other components to cause the main loop to exit. """ logger.debug('Server shutdown requested.') if self.server is not None: self.server.close()
samples. @type sample_factory: SampleFactory @param request_queue_size: Number of requests that may be pending on the socket.
random_line_split
mut_ref.rs
// Compiler: // // Run-time: // stdout: 2 // 7 // 6 // 11 #![allow(unused_attributes)] #![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {} #[lang = "copy"] trait Copy { } impl Copy for isize {} impl Copy for *mut i32 {} impl Copy for usize {} impl Copy for u8 {} impl Copy for i8 {} impl Copy for i32 {} #[lang = "receiver"] trait Receiver { } #[lang = "freeze"] pub(crate) unsafe auto trait Freeze {} #[lang = "panic_location"] struct PanicLocation { file: &'static str, line: u32, column: u32, } mod libc { #[link(name = "c")] extern "C" { pub fn puts(s: *const u8) -> i32; pub fn fflush(stream: *mut i32) -> i32; pub fn printf(format: *const i8, ...) -> i32; pub static STDOUT: *mut i32; } } mod intrinsics { extern "rust-intrinsic" { pub fn abort() -> !; } } #[lang = "panic"] #[track_caller] #[no_mangle] pub fn panic(_msg: &str) -> !
#[lang = "add"] trait Add<RHS = Self> { type Output; fn add(self, rhs: RHS) -> Self::Output; } impl Add for u8 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for i8 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for i32 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for usize { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for isize { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } /* * Code */ struct Test { field: isize, } fn test(num: isize) -> Test { Test { field: num + 1, } } fn update_num(num: &mut isize) { *num = *num + 5; } #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { let mut test = test(argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); } update_num(&mut test.field); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); } update_num(&mut argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc); } let refe = &mut argc; *refe = *refe + 5; unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc); } 0 }
{ unsafe { libc::puts("Panicking\0" as *const str as *const u8); libc::fflush(libc::STDOUT); intrinsics::abort(); } }
identifier_body
mut_ref.rs
// Compiler: // // Run-time: // stdout: 2 // 7 // 6 // 11 #![allow(unused_attributes)] #![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {}
#[lang = "copy"] trait Copy { } impl Copy for isize {} impl Copy for *mut i32 {} impl Copy for usize {} impl Copy for u8 {} impl Copy for i8 {} impl Copy for i32 {} #[lang = "receiver"] trait Receiver { } #[lang = "freeze"] pub(crate) unsafe auto trait Freeze {} #[lang = "panic_location"] struct PanicLocation { file: &'static str, line: u32, column: u32, } mod libc { #[link(name = "c")] extern "C" { pub fn puts(s: *const u8) -> i32; pub fn fflush(stream: *mut i32) -> i32; pub fn printf(format: *const i8, ...) -> i32; pub static STDOUT: *mut i32; } } mod intrinsics { extern "rust-intrinsic" { pub fn abort() -> !; } } #[lang = "panic"] #[track_caller] #[no_mangle] pub fn panic(_msg: &str) -> ! { unsafe { libc::puts("Panicking\0" as *const str as *const u8); libc::fflush(libc::STDOUT); intrinsics::abort(); } } #[lang = "add"] trait Add<RHS = Self> { type Output; fn add(self, rhs: RHS) -> Self::Output; } impl Add for u8 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for i8 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for i32 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for usize { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for isize { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } /* * Code */ struct Test { field: isize, } fn test(num: isize) -> Test { Test { field: num + 1, } } fn update_num(num: &mut isize) { *num = *num + 5; } #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { let mut test = test(argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); } update_num(&mut test.field); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); } update_num(&mut argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc); } let refe = &mut argc; *refe = *refe + 5; unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc); } 0 }
random_line_split
mut_ref.rs
// Compiler: // // Run-time: // stdout: 2 // 7 // 6 // 11 #![allow(unused_attributes)] #![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {} #[lang = "copy"] trait Copy { } impl Copy for isize {} impl Copy for *mut i32 {} impl Copy for usize {} impl Copy for u8 {} impl Copy for i8 {} impl Copy for i32 {} #[lang = "receiver"] trait Receiver { } #[lang = "freeze"] pub(crate) unsafe auto trait Freeze {} #[lang = "panic_location"] struct PanicLocation { file: &'static str, line: u32, column: u32, } mod libc { #[link(name = "c")] extern "C" { pub fn puts(s: *const u8) -> i32; pub fn fflush(stream: *mut i32) -> i32; pub fn printf(format: *const i8, ...) -> i32; pub static STDOUT: *mut i32; } } mod intrinsics { extern "rust-intrinsic" { pub fn abort() -> !; } } #[lang = "panic"] #[track_caller] #[no_mangle] pub fn panic(_msg: &str) -> ! { unsafe { libc::puts("Panicking\0" as *const str as *const u8); libc::fflush(libc::STDOUT); intrinsics::abort(); } } #[lang = "add"] trait Add<RHS = Self> { type Output; fn add(self, rhs: RHS) -> Self::Output; } impl Add for u8 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for i8 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for i32 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for usize { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for isize { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } /* * Code */ struct Test { field: isize, } fn test(num: isize) -> Test { Test { field: num + 1, } } fn
(num: &mut isize) { *num = *num + 5; } #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { let mut test = test(argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); } update_num(&mut test.field); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); } update_num(&mut argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc); } let refe = &mut argc; *refe = *refe + 5; unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, argc); } 0 }
update_num
identifier_name
issue-84973-blacklist.rs
// Checks that certain traits for which we don't want to suggest borrowing // are blacklisted and don't cause the suggestion to be issued. #![feature(generators)] fn f_copy<T: Copy>(t: T) {} fn f_clone<T: Clone>(t: T) {} fn f_unpin<T: Unpin>(t: T) {} fn f_sized<T: Sized>(t: T) {} fn f_send<T: Send>(t: T) {} struct S; fn main() { f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277] f_clone(S); //~ ERROR: the trait bound `S: Clone` is not satisfied [E0277] f_unpin(static || { yield; }); //~^ ERROR: cannot be unpinned [E0277] let cl = || (); let ref_cl: &dyn Fn() -> () = &cl; f_sized(*ref_cl); //~^ ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277] //~| ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277] use std::rc::Rc; let rc = Rc::new(0); f_send(rc); //~ ERROR: `Rc<{integer}>` cannot be sent between threads safely [E0277]
}
random_line_split
issue-84973-blacklist.rs
// Checks that certain traits for which we don't want to suggest borrowing // are blacklisted and don't cause the suggestion to be issued. #![feature(generators)] fn
<T: Copy>(t: T) {} fn f_clone<T: Clone>(t: T) {} fn f_unpin<T: Unpin>(t: T) {} fn f_sized<T: Sized>(t: T) {} fn f_send<T: Send>(t: T) {} struct S; fn main() { f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277] f_clone(S); //~ ERROR: the trait bound `S: Clone` is not satisfied [E0277] f_unpin(static || { yield; }); //~^ ERROR: cannot be unpinned [E0277] let cl = || (); let ref_cl: &dyn Fn() -> () = &cl; f_sized(*ref_cl); //~^ ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277] //~| ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277] use std::rc::Rc; let rc = Rc::new(0); f_send(rc); //~ ERROR: `Rc<{integer}>` cannot be sent between threads safely [E0277] }
f_copy
identifier_name
issue-84973-blacklist.rs
// Checks that certain traits for which we don't want to suggest borrowing // are blacklisted and don't cause the suggestion to be issued. #![feature(generators)] fn f_copy<T: Copy>(t: T) {} fn f_clone<T: Clone>(t: T) {} fn f_unpin<T: Unpin>(t: T)
fn f_sized<T: Sized>(t: T) {} fn f_send<T: Send>(t: T) {} struct S; fn main() { f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277] f_clone(S); //~ ERROR: the trait bound `S: Clone` is not satisfied [E0277] f_unpin(static || { yield; }); //~^ ERROR: cannot be unpinned [E0277] let cl = || (); let ref_cl: &dyn Fn() -> () = &cl; f_sized(*ref_cl); //~^ ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277] //~| ERROR: the size for values of type `dyn Fn()` cannot be known at compilation time [E0277] use std::rc::Rc; let rc = Rc::new(0); f_send(rc); //~ ERROR: `Rc<{integer}>` cannot be sent between threads safely [E0277] }
{}
identifier_body
custom.js
$(document).ready(function() { $('.fancybox').fancybox(); $(".fancybox-effects-a").fancybox({ helpers: { title : { type : 'outside' }, overlay : { speedOut : 0 } } }); $(".fancybox-effects-b").fancybox({ openEffect : 'none', closeEffect : 'none', helpers : { title : { type : 'over' } } }); $(".fancybox-effects-c").fancybox({ wrapCSS : 'fancybox-custom', closeClick : true, openEffect : 'none', helpers : { title : { type : 'inside' }, overlay : { css : { 'background' : 'rgba(238,238,238,0.85)' } } } }); $(".fancybox-effects-d").fancybox({ padding: 0, openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, closeClick : true, helpers : { overlay : null } }); $('.fancybox-buttons').fancybox({ openEffect : 'none', closeEffect : 'none', prevEffect : 'none', nextEffect : 'none', closeBtn : false, helpers : { title : { type : 'inside' }, buttons : {} }, afterLoad : function() { this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : ''); } }); $('.fancybox-thumbs').fancybox({ prevEffect : 'none', nextEffect : 'none', closeBtn : false, arrows : false, nextClick : true, helpers : { thumbs : { width : 50, height : 50 } } }); $('.fancybox-media') .attr('rel', 'media-gallery') .fancybox({ openEffect : 'none', closeEffect : 'none', prevEffect : 'none', nextEffect : 'none', arrows : false, helpers : { media : {}, buttons : {} } }); $("#fancybox-manual-a").click(function() { $.fancybox.open('1_b.jpg'); }); $("#fancybox-manual-b").click(function() { $.fancybox.open({ href : 'iframe.html', type : 'iframe', padding : 5 }); }); $("#fancybox-manual-c").click(function() { $.fancybox.open([ { href : '1_b.jpg', title : 'My title' }, { href : '2_b.jpg', title : '2nd title' }, { href : '3_b.jpg' }
helpers : { thumbs : { width: 75, height: 50 } } }); }); });
], {
random_line_split
__init__.py
""" Initialize the application. """ import logging logger = logging.getLogger(__name__) import appdirs import click import datetime import distutils.dir_util import os import putiopy import sqlite3 APP_NAME = 'putio-automator' APP_AUTHOR = 'datashaman' DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR) from .db import create_db, database_path create_db() def date_handler(obj): "Date handler for JSON serialization" if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date): return obj.isoformat() else: return None def find_config(verbose=False): "Search for config on wellknown paths" search_paths = [ os.path.join(os.getcwd(), 'config.py'), os.path.join(DIRS.user_data_dir, 'config.py'), os.path.join(DIRS.site_data_dir, 'config.py'), ] config = None for search_path in search_paths: message = 'Searching %s' % search_path logger.debug(message) if verbose:
if os.path.exists(search_path) and not os.path.isdir(search_path): config = search_path break return config def echo(level, message): log_func = getattr(logger, level) log_func(message) click.echo(message)
click.echo(message)
conditional_block
__init__.py
""" Initialize the application. """ import logging logger = logging.getLogger(__name__) import appdirs import click import datetime import distutils.dir_util import os import putiopy import sqlite3 APP_NAME = 'putio-automator' APP_AUTHOR = 'datashaman' DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR) from .db import create_db, database_path create_db() def date_handler(obj):
def find_config(verbose=False): "Search for config on wellknown paths" search_paths = [ os.path.join(os.getcwd(), 'config.py'), os.path.join(DIRS.user_data_dir, 'config.py'), os.path.join(DIRS.site_data_dir, 'config.py'), ] config = None for search_path in search_paths: message = 'Searching %s' % search_path logger.debug(message) if verbose: click.echo(message) if os.path.exists(search_path) and not os.path.isdir(search_path): config = search_path break return config def echo(level, message): log_func = getattr(logger, level) log_func(message) click.echo(message)
"Date handler for JSON serialization" if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date): return obj.isoformat() else: return None
identifier_body
__init__.py
""" Initialize the application. """ import logging logger = logging.getLogger(__name__) import appdirs import click import datetime import distutils.dir_util import os import putiopy import sqlite3 APP_NAME = 'putio-automator' APP_AUTHOR = 'datashaman' DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR) from .db import create_db, database_path create_db() def date_handler(obj): "Date handler for JSON serialization" if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date): return obj.isoformat() else: return None def find_config(verbose=False): "Search for config on wellknown paths" search_paths = [ os.path.join(os.getcwd(), 'config.py'), os.path.join(DIRS.user_data_dir, 'config.py'), os.path.join(DIRS.site_data_dir, 'config.py'), ] config = None for search_path in search_paths: message = 'Searching %s' % search_path logger.debug(message) if verbose: click.echo(message) if os.path.exists(search_path) and not os.path.isdir(search_path): config = search_path break return config def
(level, message): log_func = getattr(logger, level) log_func(message) click.echo(message)
echo
identifier_name
__init__.py
""" Initialize the application.
import appdirs import click import datetime import distutils.dir_util import os import putiopy import sqlite3 APP_NAME = 'putio-automator' APP_AUTHOR = 'datashaman' DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR) from .db import create_db, database_path create_db() def date_handler(obj): "Date handler for JSON serialization" if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date): return obj.isoformat() else: return None def find_config(verbose=False): "Search for config on wellknown paths" search_paths = [ os.path.join(os.getcwd(), 'config.py'), os.path.join(DIRS.user_data_dir, 'config.py'), os.path.join(DIRS.site_data_dir, 'config.py'), ] config = None for search_path in search_paths: message = 'Searching %s' % search_path logger.debug(message) if verbose: click.echo(message) if os.path.exists(search_path) and not os.path.isdir(search_path): config = search_path break return config def echo(level, message): log_func = getattr(logger, level) log_func(message) click.echo(message)
""" import logging logger = logging.getLogger(__name__)
random_line_split
path_parsing.rs
extern crate memchr; use self::memchr::{memchr, memrchr}; use memrnchr::memrnchr; use std::path::MAIN_SEPARATOR; use std::str; pub const SEP: u8 = MAIN_SEPARATOR as u8; lazy_static! { pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap(); } // Returns the byte offset of the last byte that equals MAIN_SEPARATOR. #[inline(always)] pub fn find_last_sep_pos(bytes: &[u8]) -> Option<usize> { memrchr(SEP, bytes) } // Returns the byte offset of the last byte that is not MAIN_SEPARATOR. #[inline(always)]
#[inline(always)] pub fn contains_sep(bytes: &[u8]) -> bool { memchr(SEP, bytes) != None }
pub fn find_last_non_sep_pos(bytes: &[u8]) -> Option<usize> { memrnchr(SEP, bytes) } // Whether the given byte sequence contains a MAIN_SEPARATOR.
random_line_split
path_parsing.rs
extern crate memchr; use self::memchr::{memchr, memrchr}; use memrnchr::memrnchr; use std::path::MAIN_SEPARATOR; use std::str; pub const SEP: u8 = MAIN_SEPARATOR as u8; lazy_static! { pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap(); } // Returns the byte offset of the last byte that equals MAIN_SEPARATOR. #[inline(always)] pub fn find_last_sep_pos(bytes: &[u8]) -> Option<usize> { memrchr(SEP, bytes) } // Returns the byte offset of the last byte that is not MAIN_SEPARATOR. #[inline(always)] pub fn find_last_non_sep_pos(bytes: &[u8]) -> Option<usize>
// Whether the given byte sequence contains a MAIN_SEPARATOR. #[inline(always)] pub fn contains_sep(bytes: &[u8]) -> bool { memchr(SEP, bytes) != None }
{ memrnchr(SEP, bytes) }
identifier_body
path_parsing.rs
extern crate memchr; use self::memchr::{memchr, memrchr}; use memrnchr::memrnchr; use std::path::MAIN_SEPARATOR; use std::str; pub const SEP: u8 = MAIN_SEPARATOR as u8; lazy_static! { pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap(); } // Returns the byte offset of the last byte that equals MAIN_SEPARATOR. #[inline(always)] pub fn find_last_sep_pos(bytes: &[u8]) -> Option<usize> { memrchr(SEP, bytes) } // Returns the byte offset of the last byte that is not MAIN_SEPARATOR. #[inline(always)] pub fn find_last_non_sep_pos(bytes: &[u8]) -> Option<usize> { memrnchr(SEP, bytes) } // Whether the given byte sequence contains a MAIN_SEPARATOR. #[inline(always)] pub fn
(bytes: &[u8]) -> bool { memchr(SEP, bytes) != None }
contains_sep
identifier_name
bootstrap.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. """ import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py'
# parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout's main function if options.config_file is not None: args += ['-c', options.config_file] if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.append('buildout:accept-buildout-test-releases=true') args.append('bootstrap') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)] if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0: sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode) ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir)
distribute_source = 'http://python-distribute.org/distribute_setup.py'
random_line_split
bootstrap.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. """ import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' distribute_source = 'http://python-distribute.org/distribute_setup.py' # parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout's main function if options.config_file is not None: args += ['-c', options.config_file] if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.append('buildout:accept-buildout-test-releases=true') args.append('bootstrap') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)] if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0:
ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir)
sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode)
conditional_block