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
mut_dns_packet.rs
use buf::*; #[derive(Debug)] pub struct MutDnsPacket<'a> { buf: &'a mut [u8], pos: usize, } impl<'a> MutDnsPacket<'a> { pub fn new(buf: &mut [u8]) -> MutDnsPacket { MutDnsPacket::new_at(buf, 0) } pub fn new_at(buf: &mut [u8], pos: usize) -> MutDnsPacket { debug!("New MutDnsPacket. buf.len()= {:?}", buf.len()); MutDnsPacket { buf: buf, pos: pos, } } } impl<'a> BufWrite for MutDnsPacket<'a> { fn
(&mut self) -> &mut [u8] { self.buf } } impl<'a> BufRead for MutDnsPacket<'a> { fn buf(&self) -> &[u8] { self.buf } } impl<'a> DirectAccessBuf for MutDnsPacket<'a> { fn pos(&self) -> usize { self.pos } fn set_pos(&mut self, pos: usize) { self.pos = pos; } fn len(&self) -> usize { self.buf().len() } } ///Iterate each 16bit word in the packet impl<'a> Iterator for MutDnsPacket<'a> { ///2 octets of data and the position type Item = (u16, usize); /// ///Returns two octets in the order they expressed in the spec. I.e. first byte shifted to the left /// fn next(&mut self) -> Option<Self::Item> { self.next_u16().and_then(|n| Some((n, self.pos))) } } #[cfg(test)] mod tests { use super::MutDnsPacket; use buf::*; fn test_buf() -> Vec<u8> { // // 00001000 01110001 00000001 00000000 00000000 00000001 00000000 00000000 00000000 // 00000000 00000000 00000000 00000101 01111001 01100001 01101000 01101111 01101111 // 00000011 01100011 01101111 01101101 00000000 00000000 00000001 00000000 00000001 // return vec![8, 113, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 5, 121, 97, 104, 111, 111, 3, 99, 111, 109, 0, 0, 1, 0, 1]; } #[test] fn write_u8() { let mut buf = test_buf(); let mut slice = buf.as_mut_slice(); let mut packet = MutDnsPacket::new(&mut slice); packet.write_u8(7); packet.write_u8(8); packet.write_u8(9); packet.seek(0); assert_eq!(7, packet.next_u8().unwrap()); assert_eq!(8, packet.next_u8().unwrap()); assert_eq!(9, packet.next_u8().unwrap()); } #[test] fn write_u16() { let mut vec = test_buf(); let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); packet.write_u16(2161); packet.write_u16(1); packet.seek(0); println!("{:?}", packet); assert_eq!(2161, packet.next_u16().unwrap()); assert_eq!(1, packet.next_u16().unwrap()); } #[test] fn write_u16_bounds() { let mut vec = vec![0, 0, 0, 0]; let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); assert_eq!(true, packet.write_u16(1)); assert_eq!(true, packet.write_u16(1)); assert_eq!(false, packet.write_u16(1)); //no room println!("{:?}", packet); } #[test] fn write_u32() { let mut vec = vec![0, 0, 0, 0]; let mut buf = vec.as_mut_slice(); let mut packet = MutDnsPacket::new(buf); assert_eq!(true, packet.write_u32(123456789)); println!("{:?}", packet); packet.seek(0); assert_eq!(123456789, packet.next_u32().unwrap()); } }
buf
identifier_name
nuevo-pedido.js
var _servicio = '../php/servicios/proc-pedidos.php'; var _idPedidoX = 0, _docGenerate = '', _serieUsar = ''; (function($){ var _cboProd = []; var template = Handlebars.compile($("#result-template").html()); var empty = Handlebars.compile($("#empty-template").html()); $(document).ready(function(){ /* -------------------------------------- */ $('#txtProducto').autoComplete({ source: function(term, response){ $.post('../php/servicios/get_prods_lotes.php', { q: term }, function(data){ response(data); },'json'); }, renderItem: function (item, search){ var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi"); var _html = ''; _html += '<div class="autocomplete-suggestion" data-prodi="'+item[0]+'" data-lote="'+item[1]+'" data-val="'+search+'" data-idprod="'+item[5]+'" data-idum="'+item[6]+'" data-precio="'+item[4]+'" data-idlote="'+item[7]+'" >'; _html += item[0].replace(re, "<b>$1</b>")+' Precio <strong>S/. '+item[4]+'</strong>, Stock: '+item[2]+', Lote: '+item[1]+', Vence: '+item[3]; _html += '</div>'; return _html; }, onSelect: function(e, term, item){ $('#idProd').val( item.data('idprod') ); $('#idUM').val( item.data('idum') ); $('#txtPrecio').val( item.data('precio') ); $('#txtProducto').val( item.data('prodi') ); $('#idLote').val( item.data('idlote') ); $('#txtCantidad').focus(); //alert('Item "'+item.data('prodi')+' Lote: '+item.data('lote')+' " selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.'); e.preventDefault(); } }); /* -------------------------------------- */ _cboCLiente = $('#cboCliente').selectize({ options: _json_clientes, labelField: 'texto', valueField: 'id', }); if( _idCliente > 0 ){ _cboCLiente[0].selectize.setValue(_idCliente); }else{ _cboCLiente[0].selectize.setValue("1"); } /* -------------------------------------- */ $('#txtVence').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'year' }); /* -------------------------------------- */ $('#txtFecha').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'day' }); /* -------------------------------------- */ $('[data-toggle="tooltip"]').tooltip(); /* -------------------------------------- */ $(document).delegate('.copiarPedido', 'click', function(event) { /**/ var _idPedido = $(this).attr('href'); $('#CopiarModal').modal('show'); $.post( _servicio , {f:'copy',idp:_idPedido} , function(data, textStatus, xhr) { $('#CopiarModal').modal('hide'); document.location.reload(); },'json'); event.preventDefault(); /**/ }); /* -------------------------------------- */ $('#addNuevoItem').click(function(event) { resetAddItems(); $('#editorProducto').fadeIn('fast'); $('#txtProducto').focus(); event.preventDefault(); }); /* -------------------------------------- */ $('#cerrarProd').click(function(event) { resetAddItems(); $('#editorProducto').fadeOut('fast'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtCantidad').keypress(function(event) { /* Act on the event */ if( event.keyCode == 13 ){ $('#addProducto').focus(); } }); /* -------------------------------------- */ $('#SavePedido').click(function(event) { /* Act on the event */ var _data = $('#frmData').serialize(); var $btn = $(this).button('loading') $.post( _servicio , _data , function(data, textStatus, xhr) { if( data.error == '' ){ $('#idPedido').val( data.idPedido ); _idPedidoX = data.idPedido; $('#labelidPedido').html( 'Pre venta #'+data.idPedido ); $('#labelPedido').html( '#'+data.idPedido ); alertify.alert('Pre venta generado #'+data.idPedido,function(){ document.location.href = 'nuevo-pedido.php?idpedido='+data.idPedido; }); $('#panelFacturar').show(); } $btn.button('reset'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#NuevoItem').click(function(event) { /* Act on the event */ $('#myModal').modal('show'); $('#myModalLabel').html('Nuevo Pedido'); event.preventDefault(); }); /* -------------------------------------- */ //$('.jChosen').chosen({width: "100%"}); /* -------------------------------------- */ $('#addProducto').click(function(event) { $(this).attr({'disabled':'disabled'}); // var _data = $('#frmEditor').serialize(); // $.post( _servicio , _data , function(data, textStatus, xhr) { $('#addProducto').removeAttr('disabled'); loadTablita(data); resetAddItems(); $('#txtProducto').val(''); $('#txtProducto').focus(); alertify.success('Producto agregado'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtPrecio').keyup(function(event) { var _cant = $('#txtCantidad').val(), _precio = $(this).val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $('#txtCantidad').keyup(function(event) { var _cant = $(this).val(), _precio = $('#txtPrecio').val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $(document).delegate('.quitarProd', 'click', function(event) { /* Quitar un item de la lista y volver a dibujar la tabla. */ var _Nombre = $(this).attr('rel'), _idd = $(this).attr('href'); alertify.confirm('Confirme quitar Item: '+_Nombre,function(e){ if(e){ $.post( _servicio , {f:'delItem',idItem:_idd,'idp':_idPedido} , function(data, textStatus, xhr) { $('#Fila_'+_idd).hide('slow'); loadTablita(data); alertify.error('Producto quitado.'); },'json'); } }); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.ItemLista', 'click', function(event) { /* Agregar un item de la lista y volver a dibujar la tabla. */ var _idp = $(this).attr('href'); $.post( _servicio , { f:'getItem', idp:_idp } , function(data, textStatus, xhr) { LoadItem( data ); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.goPedido', 'click', function(event) { var _idp = $(this).attr('href'); $('#myModal').modal('show'); event.preventDefault(); }); /* -------------------------------------- */ $('#btnGoFacturar').click(function(event) { var _filtro = ''; _docGenerate = $('#Documento').val(); _serieUsar = $('#Correlativo').val(); var _idPedido = $('#idPedido').val(); _filtro = 'goBoleta'; /**/ $.post( _servicio , { f:_filtro, idp:_idPedido, 'TipoDoc':_docGenerate, serie:_serieUsar} , function(data, textStatus, xhr) { if( data.idVenta > 0 ){ switch(_docGenerate){ case 'B': document.location.href = 'nueva-boleta.php?id='+data.idVenta; break; case 'F': document.location.href = 'nueva-factura.php?id='+data.idVenta; break; case 'R': document.location.href = 'nuevo-recibo.php?id='+data.idVenta; break; } } },'json'); /**/ event.preventDefault(); }); /* -------------------------------------- */ }); })(jQuery); function LoadItem( json ){ if( json.data != undefined || json.data != null ){ var _html = '', _item = []; for (var i = 0; i < json.data.length; i++) { _item = json.data[0]; $('#txtCantidad').val( _item.int_Cantidad ); //$('#txtProducto').val( _item.var_Nombre+' x '+_item.unidadMedida ); $('#txtPrecio').val( _item.flt_Precio ); $('#txtTotal').val( _item.flt_Total ); // $('#idProd').val( _item.int_IdProducto ); $('#idUM').val( _item.int_IdUnidadMedida ); $('#idItem').val( _item.int_IdDetallePedido ); $('#editorProducto').fadeIn('fast'); }; } } function resetAddItems(){ $('#containerProducto').removeClass().addClass('form-group'); $('#idProd').val('0'); $('#idUM').val('0'); $('#txtPrecio').val( '0' ); $('#txtCantidad').val( '' ); $('#txtTotal').val( '0' ); //$("#txtProducto").val(''); $("#idItem").val('0'); } function loadTablita( json ){ if( json.data != undefined || json.data != null ){ var _fila = [], _html = '', _total = 0; for (var i = 0; i < json.data.length; i++) { _fila = json.data[i]; _html += '<tr id="Fila_'+_fila.int_IdDetallePedido+'" >'; _html += '<td>'; _html += '<span class="fa fa-barcode" ></span> '+_fila.prod+' x '+_fila.um+''; if( _fila.int_IdPromo != null ){ _html += '<br/><small>'+_fila.var_Promo+' antes ('+_fila.flt_Precio+')</small>'; } _html += '</td>'; _html += '<td>'+_fila.lote+'</td>'; if( _fila.int_IdPromo != null )
else{ _html += '<td class="text-right" >S/. '+_fila.flt_Precio+'</td>'; } _html += '<td class="text-right" >'+_fila.cant+'</td>'; _total = _total + parseFloat(_fila.flt_Total); _html += '<td class="text-right" >'+_fila.flt_Total+'</td>'; _html += '<td>'; _html += '<a href="'+_fila.int_IdDetallePedido+'" class="pull-right quitarProd" rel="'+_fila.prod+'" ><span class="glyphicon glyphicon-remove" ></span></a>'; _html += '</td>'; }; $('#TotalPedido').val( _total ); $('#LabelTotal').html('Total Pre venta: '+_total); $('#Tablita tbody').html( _html ); } } /*Solo Numeros*/ /* onkeypress="return validar(event);" */ function validar(e) { tecla = (document.all)?e.keyCode:e.which;//ascii //alert(tecla); switch(tecla){ case 8: return true; break; case 46://punto return true; break; case 43://Mas return true; break; case 45://Menos return true; break; case 44://Coma return true; break; case 0://Suprimir return true; break; default: break; } patron = /\d/; te = String.fromCharCode(tecla); return patron.test(te); }
{ _html += '<td class="text-right" >S/. '+_fila.flt_Promo+'</td>'; }
conditional_block
nuevo-pedido.js
var _servicio = '../php/servicios/proc-pedidos.php'; var _idPedidoX = 0, _docGenerate = '', _serieUsar = ''; (function($){ var _cboProd = []; var template = Handlebars.compile($("#result-template").html()); var empty = Handlebars.compile($("#empty-template").html()); $(document).ready(function(){ /* -------------------------------------- */ $('#txtProducto').autoComplete({ source: function(term, response){ $.post('../php/servicios/get_prods_lotes.php', { q: term }, function(data){ response(data); },'json'); }, renderItem: function (item, search){ var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi"); var _html = ''; _html += '<div class="autocomplete-suggestion" data-prodi="'+item[0]+'" data-lote="'+item[1]+'" data-val="'+search+'" data-idprod="'+item[5]+'" data-idum="'+item[6]+'" data-precio="'+item[4]+'" data-idlote="'+item[7]+'" >'; _html += item[0].replace(re, "<b>$1</b>")+' Precio <strong>S/. '+item[4]+'</strong>, Stock: '+item[2]+', Lote: '+item[1]+', Vence: '+item[3]; _html += '</div>'; return _html; }, onSelect: function(e, term, item){ $('#idProd').val( item.data('idprod') ); $('#idUM').val( item.data('idum') ); $('#txtPrecio').val( item.data('precio') ); $('#txtProducto').val( item.data('prodi') ); $('#idLote').val( item.data('idlote') ); $('#txtCantidad').focus(); //alert('Item "'+item.data('prodi')+' Lote: '+item.data('lote')+' " selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.'); e.preventDefault(); } }); /* -------------------------------------- */ _cboCLiente = $('#cboCliente').selectize({ options: _json_clientes, labelField: 'texto', valueField: 'id', }); if( _idCliente > 0 ){ _cboCLiente[0].selectize.setValue(_idCliente); }else{ _cboCLiente[0].selectize.setValue("1"); } /* -------------------------------------- */ $('#txtVence').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'year' }); /* -------------------------------------- */ $('#txtFecha').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'day' }); /* -------------------------------------- */ $('[data-toggle="tooltip"]').tooltip(); /* -------------------------------------- */ $(document).delegate('.copiarPedido', 'click', function(event) { /**/ var _idPedido = $(this).attr('href'); $('#CopiarModal').modal('show'); $.post( _servicio , {f:'copy',idp:_idPedido} , function(data, textStatus, xhr) { $('#CopiarModal').modal('hide'); document.location.reload(); },'json'); event.preventDefault(); /**/ }); /* -------------------------------------- */ $('#addNuevoItem').click(function(event) { resetAddItems(); $('#editorProducto').fadeIn('fast'); $('#txtProducto').focus(); event.preventDefault(); }); /* -------------------------------------- */ $('#cerrarProd').click(function(event) { resetAddItems(); $('#editorProducto').fadeOut('fast'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtCantidad').keypress(function(event) { /* Act on the event */ if( event.keyCode == 13 ){ $('#addProducto').focus(); } }); /* -------------------------------------- */ $('#SavePedido').click(function(event) { /* Act on the event */ var _data = $('#frmData').serialize(); var $btn = $(this).button('loading') $.post( _servicio , _data , function(data, textStatus, xhr) { if( data.error == '' ){ $('#idPedido').val( data.idPedido ); _idPedidoX = data.idPedido; $('#labelidPedido').html( 'Pre venta #'+data.idPedido ); $('#labelPedido').html( '#'+data.idPedido ); alertify.alert('Pre venta generado #'+data.idPedido,function(){ document.location.href = 'nuevo-pedido.php?idpedido='+data.idPedido; }); $('#panelFacturar').show(); } $btn.button('reset'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#NuevoItem').click(function(event) { /* Act on the event */ $('#myModal').modal('show'); $('#myModalLabel').html('Nuevo Pedido'); event.preventDefault(); }); /* -------------------------------------- */ //$('.jChosen').chosen({width: "100%"}); /* -------------------------------------- */ $('#addProducto').click(function(event) { $(this).attr({'disabled':'disabled'}); // var _data = $('#frmEditor').serialize(); // $.post( _servicio , _data , function(data, textStatus, xhr) { $('#addProducto').removeAttr('disabled'); loadTablita(data); resetAddItems(); $('#txtProducto').val(''); $('#txtProducto').focus(); alertify.success('Producto agregado'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtPrecio').keyup(function(event) { var _cant = $('#txtCantidad').val(), _precio = $(this).val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $('#txtCantidad').keyup(function(event) { var _cant = $(this).val(), _precio = $('#txtPrecio').val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $(document).delegate('.quitarProd', 'click', function(event) { /* Quitar un item de la lista y volver a dibujar la tabla. */ var _Nombre = $(this).attr('rel'), _idd = $(this).attr('href'); alertify.confirm('Confirme quitar Item: '+_Nombre,function(e){ if(e){ $.post( _servicio , {f:'delItem',idItem:_idd,'idp':_idPedido} , function(data, textStatus, xhr) { $('#Fila_'+_idd).hide('slow'); loadTablita(data); alertify.error('Producto quitado.'); },'json'); } }); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.ItemLista', 'click', function(event) { /* Agregar un item de la lista y volver a dibujar la tabla. */ var _idp = $(this).attr('href'); $.post( _servicio , { f:'getItem', idp:_idp } , function(data, textStatus, xhr) { LoadItem( data ); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.goPedido', 'click', function(event) { var _idp = $(this).attr('href'); $('#myModal').modal('show'); event.preventDefault(); }); /* -------------------------------------- */ $('#btnGoFacturar').click(function(event) { var _filtro = ''; _docGenerate = $('#Documento').val(); _serieUsar = $('#Correlativo').val(); var _idPedido = $('#idPedido').val(); _filtro = 'goBoleta'; /**/ $.post( _servicio , { f:_filtro, idp:_idPedido, 'TipoDoc':_docGenerate, serie:_serieUsar} , function(data, textStatus, xhr) { if( data.idVenta > 0 ){ switch(_docGenerate){ case 'B': document.location.href = 'nueva-boleta.php?id='+data.idVenta; break; case 'F': document.location.href = 'nueva-factura.php?id='+data.idVenta; break; case 'R': document.location.href = 'nuevo-recibo.php?id='+data.idVenta; break; } } },'json'); /**/ event.preventDefault(); }); /* -------------------------------------- */ }); })(jQuery); function LoadItem( json ){ if( json.data != undefined || json.data != null ){ var _html = '', _item = []; for (var i = 0; i < json.data.length; i++) { _item = json.data[0]; $('#txtCantidad').val( _item.int_Cantidad ); //$('#txtProducto').val( _item.var_Nombre+' x '+_item.unidadMedida ); $('#txtPrecio').val( _item.flt_Precio ); $('#txtTotal').val( _item.flt_Total ); // $('#idProd').val( _item.int_IdProducto ); $('#idUM').val( _item.int_IdUnidadMedida ); $('#idItem').val( _item.int_IdDetallePedido ); $('#editorProducto').fadeIn('fast'); }; } } function resetAddItems(){ $('#containerProducto').removeClass().addClass('form-group'); $('#idProd').val('0'); $('#idUM').val('0'); $('#txtPrecio').val( '0' ); $('#txtCantidad').val( '' ); $('#txtTotal').val( '0' ); //$("#txtProducto").val(''); $("#idItem").val('0'); } function loadTablita( json )
/*Solo Numeros*/ /* onkeypress="return validar(event);" */ function validar(e) { tecla = (document.all)?e.keyCode:e.which;//ascii //alert(tecla); switch(tecla){ case 8: return true; break; case 46://punto return true; break; case 43://Mas return true; break; case 45://Menos return true; break; case 44://Coma return true; break; case 0://Suprimir return true; break; default: break; } patron = /\d/; te = String.fromCharCode(tecla); return patron.test(te); }
{ if( json.data != undefined || json.data != null ){ var _fila = [], _html = '', _total = 0; for (var i = 0; i < json.data.length; i++) { _fila = json.data[i]; _html += '<tr id="Fila_'+_fila.int_IdDetallePedido+'" >'; _html += '<td>'; _html += '<span class="fa fa-barcode" ></span> '+_fila.prod+' x '+_fila.um+''; if( _fila.int_IdPromo != null ){ _html += '<br/><small>'+_fila.var_Promo+' antes ('+_fila.flt_Precio+')</small>'; } _html += '</td>'; _html += '<td>'+_fila.lote+'</td>'; if( _fila.int_IdPromo != null ){ _html += '<td class="text-right" >S/. '+_fila.flt_Promo+'</td>'; }else{ _html += '<td class="text-right" >S/. '+_fila.flt_Precio+'</td>'; } _html += '<td class="text-right" >'+_fila.cant+'</td>'; _total = _total + parseFloat(_fila.flt_Total); _html += '<td class="text-right" >'+_fila.flt_Total+'</td>'; _html += '<td>'; _html += '<a href="'+_fila.int_IdDetallePedido+'" class="pull-right quitarProd" rel="'+_fila.prod+'" ><span class="glyphicon glyphicon-remove" ></span></a>'; _html += '</td>'; }; $('#TotalPedido').val( _total ); $('#LabelTotal').html('Total Pre venta: '+_total); $('#Tablita tbody').html( _html ); } }
identifier_body
nuevo-pedido.js
var _servicio = '../php/servicios/proc-pedidos.php'; var _idPedidoX = 0, _docGenerate = '', _serieUsar = ''; (function($){ var _cboProd = []; var template = Handlebars.compile($("#result-template").html()); var empty = Handlebars.compile($("#empty-template").html()); $(document).ready(function(){ /* -------------------------------------- */ $('#txtProducto').autoComplete({ source: function(term, response){ $.post('../php/servicios/get_prods_lotes.php', { q: term }, function(data){ response(data); },'json'); }, renderItem: function (item, search){ var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi"); var _html = ''; _html += '<div class="autocomplete-suggestion" data-prodi="'+item[0]+'" data-lote="'+item[1]+'" data-val="'+search+'" data-idprod="'+item[5]+'" data-idum="'+item[6]+'" data-precio="'+item[4]+'" data-idlote="'+item[7]+'" >'; _html += item[0].replace(re, "<b>$1</b>")+' Precio <strong>S/. '+item[4]+'</strong>, Stock: '+item[2]+', Lote: '+item[1]+', Vence: '+item[3]; _html += '</div>'; return _html; }, onSelect: function(e, term, item){ $('#idProd').val( item.data('idprod') ); $('#idUM').val( item.data('idum') ); $('#txtPrecio').val( item.data('precio') ); $('#txtProducto').val( item.data('prodi') ); $('#idLote').val( item.data('idlote') ); $('#txtCantidad').focus(); //alert('Item "'+item.data('prodi')+' Lote: '+item.data('lote')+' " selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.'); e.preventDefault(); } }); /* -------------------------------------- */ _cboCLiente = $('#cboCliente').selectize({ options: _json_clientes, labelField: 'texto', valueField: 'id', }); if( _idCliente > 0 ){ _cboCLiente[0].selectize.setValue(_idCliente); }else{ _cboCLiente[0].selectize.setValue("1"); } /* -------------------------------------- */ $('#txtVence').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'year' }); /* -------------------------------------- */ $('#txtFecha').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'day' }); /* -------------------------------------- */ $('[data-toggle="tooltip"]').tooltip(); /* -------------------------------------- */ $(document).delegate('.copiarPedido', 'click', function(event) { /**/ var _idPedido = $(this).attr('href'); $('#CopiarModal').modal('show'); $.post( _servicio , {f:'copy',idp:_idPedido} , function(data, textStatus, xhr) { $('#CopiarModal').modal('hide'); document.location.reload(); },'json'); event.preventDefault(); /**/ }); /* -------------------------------------- */ $('#addNuevoItem').click(function(event) { resetAddItems(); $('#editorProducto').fadeIn('fast'); $('#txtProducto').focus(); event.preventDefault(); }); /* -------------------------------------- */ $('#cerrarProd').click(function(event) { resetAddItems(); $('#editorProducto').fadeOut('fast'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtCantidad').keypress(function(event) { /* Act on the event */ if( event.keyCode == 13 ){ $('#addProducto').focus(); } }); /* -------------------------------------- */ $('#SavePedido').click(function(event) { /* Act on the event */ var _data = $('#frmData').serialize(); var $btn = $(this).button('loading') $.post( _servicio , _data , function(data, textStatus, xhr) { if( data.error == '' ){ $('#idPedido').val( data.idPedido ); _idPedidoX = data.idPedido; $('#labelidPedido').html( 'Pre venta #'+data.idPedido ); $('#labelPedido').html( '#'+data.idPedido ); alertify.alert('Pre venta generado #'+data.idPedido,function(){ document.location.href = 'nuevo-pedido.php?idpedido='+data.idPedido; }); $('#panelFacturar').show(); } $btn.button('reset'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#NuevoItem').click(function(event) { /* Act on the event */ $('#myModal').modal('show'); $('#myModalLabel').html('Nuevo Pedido'); event.preventDefault(); }); /* -------------------------------------- */ //$('.jChosen').chosen({width: "100%"}); /* -------------------------------------- */ $('#addProducto').click(function(event) { $(this).attr({'disabled':'disabled'}); // var _data = $('#frmEditor').serialize(); // $.post( _servicio , _data , function(data, textStatus, xhr) { $('#addProducto').removeAttr('disabled'); loadTablita(data); resetAddItems(); $('#txtProducto').val(''); $('#txtProducto').focus(); alertify.success('Producto agregado'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtPrecio').keyup(function(event) { var _cant = $('#txtCantidad').val(), _precio = $(this).val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $('#txtCantidad').keyup(function(event) { var _cant = $(this).val(), _precio = $('#txtPrecio').val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $(document).delegate('.quitarProd', 'click', function(event) { /* Quitar un item de la lista y volver a dibujar la tabla. */ var _Nombre = $(this).attr('rel'), _idd = $(this).attr('href'); alertify.confirm('Confirme quitar Item: '+_Nombre,function(e){ if(e){ $.post( _servicio , {f:'delItem',idItem:_idd,'idp':_idPedido} , function(data, textStatus, xhr) { $('#Fila_'+_idd).hide('slow'); loadTablita(data); alertify.error('Producto quitado.'); },'json'); } }); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.ItemLista', 'click', function(event) { /* Agregar un item de la lista y volver a dibujar la tabla. */ var _idp = $(this).attr('href'); $.post( _servicio , { f:'getItem', idp:_idp } , function(data, textStatus, xhr) { LoadItem( data ); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.goPedido', 'click', function(event) { var _idp = $(this).attr('href'); $('#myModal').modal('show'); event.preventDefault(); }); /* -------------------------------------- */ $('#btnGoFacturar').click(function(event) { var _filtro = ''; _docGenerate = $('#Documento').val(); _serieUsar = $('#Correlativo').val(); var _idPedido = $('#idPedido').val(); _filtro = 'goBoleta'; /**/ $.post( _servicio , { f:_filtro, idp:_idPedido, 'TipoDoc':_docGenerate, serie:_serieUsar} , function(data, textStatus, xhr) { if( data.idVenta > 0 ){ switch(_docGenerate){ case 'B': document.location.href = 'nueva-boleta.php?id='+data.idVenta; break; case 'F': document.location.href = 'nueva-factura.php?id='+data.idVenta; break; case 'R': document.location.href = 'nuevo-recibo.php?id='+data.idVenta; break; } } },'json'); /**/ event.preventDefault(); }); /* -------------------------------------- */ }); })(jQuery); function LoadItem( json ){ if( json.data != undefined || json.data != null ){ var _html = '', _item = []; for (var i = 0; i < json.data.length; i++) { _item = json.data[0]; $('#txtCantidad').val( _item.int_Cantidad ); //$('#txtProducto').val( _item.var_Nombre+' x '+_item.unidadMedida ); $('#txtPrecio').val( _item.flt_Precio ); $('#txtTotal').val( _item.flt_Total ); // $('#idProd').val( _item.int_IdProducto ); $('#idUM').val( _item.int_IdUnidadMedida ); $('#idItem').val( _item.int_IdDetallePedido ); $('#editorProducto').fadeIn('fast'); }; } } function
(){ $('#containerProducto').removeClass().addClass('form-group'); $('#idProd').val('0'); $('#idUM').val('0'); $('#txtPrecio').val( '0' ); $('#txtCantidad').val( '' ); $('#txtTotal').val( '0' ); //$("#txtProducto").val(''); $("#idItem").val('0'); } function loadTablita( json ){ if( json.data != undefined || json.data != null ){ var _fila = [], _html = '', _total = 0; for (var i = 0; i < json.data.length; i++) { _fila = json.data[i]; _html += '<tr id="Fila_'+_fila.int_IdDetallePedido+'" >'; _html += '<td>'; _html += '<span class="fa fa-barcode" ></span> '+_fila.prod+' x '+_fila.um+''; if( _fila.int_IdPromo != null ){ _html += '<br/><small>'+_fila.var_Promo+' antes ('+_fila.flt_Precio+')</small>'; } _html += '</td>'; _html += '<td>'+_fila.lote+'</td>'; if( _fila.int_IdPromo != null ){ _html += '<td class="text-right" >S/. '+_fila.flt_Promo+'</td>'; }else{ _html += '<td class="text-right" >S/. '+_fila.flt_Precio+'</td>'; } _html += '<td class="text-right" >'+_fila.cant+'</td>'; _total = _total + parseFloat(_fila.flt_Total); _html += '<td class="text-right" >'+_fila.flt_Total+'</td>'; _html += '<td>'; _html += '<a href="'+_fila.int_IdDetallePedido+'" class="pull-right quitarProd" rel="'+_fila.prod+'" ><span class="glyphicon glyphicon-remove" ></span></a>'; _html += '</td>'; }; $('#TotalPedido').val( _total ); $('#LabelTotal').html('Total Pre venta: '+_total); $('#Tablita tbody').html( _html ); } } /*Solo Numeros*/ /* onkeypress="return validar(event);" */ function validar(e) { tecla = (document.all)?e.keyCode:e.which;//ascii //alert(tecla); switch(tecla){ case 8: return true; break; case 46://punto return true; break; case 43://Mas return true; break; case 45://Menos return true; break; case 44://Coma return true; break; case 0://Suprimir return true; break; default: break; } patron = /\d/; te = String.fromCharCode(tecla); return patron.test(te); }
resetAddItems
identifier_name
nuevo-pedido.js
var _servicio = '../php/servicios/proc-pedidos.php'; var _idPedidoX = 0, _docGenerate = '', _serieUsar = ''; (function($){ var _cboProd = []; var template = Handlebars.compile($("#result-template").html()); var empty = Handlebars.compile($("#empty-template").html()); $(document).ready(function(){ /* -------------------------------------- */ $('#txtProducto').autoComplete({ source: function(term, response){ $.post('../php/servicios/get_prods_lotes.php', { q: term }, function(data){ response(data); },'json'); }, renderItem: function (item, search){ var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi"); var _html = ''; _html += '<div class="autocomplete-suggestion" data-prodi="'+item[0]+'" data-lote="'+item[1]+'" data-val="'+search+'" data-idprod="'+item[5]+'" data-idum="'+item[6]+'" data-precio="'+item[4]+'" data-idlote="'+item[7]+'" >'; _html += item[0].replace(re, "<b>$1</b>")+' Precio <strong>S/. '+item[4]+'</strong>, Stock: '+item[2]+', Lote: '+item[1]+', Vence: '+item[3]; _html += '</div>'; return _html; }, onSelect: function(e, term, item){ $('#idProd').val( item.data('idprod') ); $('#idUM').val( item.data('idum') ); $('#txtPrecio').val( item.data('precio') ); $('#txtProducto').val( item.data('prodi') ); $('#idLote').val( item.data('idlote') ); $('#txtCantidad').focus(); //alert('Item "'+item.data('prodi')+' Lote: '+item.data('lote')+' " selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.'); e.preventDefault(); } }); /* -------------------------------------- */ _cboCLiente = $('#cboCliente').selectize({ options: _json_clientes, labelField: 'texto', valueField: 'id', }); if( _idCliente > 0 ){ _cboCLiente[0].selectize.setValue(_idCliente); }else{ _cboCLiente[0].selectize.setValue("1"); } /* -------------------------------------- */ $('#txtVence').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'year' }); /* -------------------------------------- */ $('#txtFecha').datepicker({ format: 'dd/mm/yyyy', startDate: '-3d', language : 'es', startView : 'day' }); /* -------------------------------------- */ $('[data-toggle="tooltip"]').tooltip(); /* -------------------------------------- */ $(document).delegate('.copiarPedido', 'click', function(event) { /**/ var _idPedido = $(this).attr('href'); $('#CopiarModal').modal('show'); $.post( _servicio , {f:'copy',idp:_idPedido} , function(data, textStatus, xhr) { $('#CopiarModal').modal('hide'); document.location.reload(); },'json'); event.preventDefault(); /**/ }); /* -------------------------------------- */ $('#addNuevoItem').click(function(event) { resetAddItems(); $('#editorProducto').fadeIn('fast'); $('#txtProducto').focus(); event.preventDefault(); }); /* -------------------------------------- */ $('#cerrarProd').click(function(event) { resetAddItems(); $('#editorProducto').fadeOut('fast'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtCantidad').keypress(function(event) { /* Act on the event */ if( event.keyCode == 13 ){ $('#addProducto').focus(); } }); /* -------------------------------------- */ $('#SavePedido').click(function(event) { /* Act on the event */ var _data = $('#frmData').serialize(); var $btn = $(this).button('loading') $.post( _servicio , _data , function(data, textStatus, xhr) { if( data.error == '' ){ $('#idPedido').val( data.idPedido ); _idPedidoX = data.idPedido; $('#labelidPedido').html( 'Pre venta #'+data.idPedido ); $('#labelPedido').html( '#'+data.idPedido ); alertify.alert('Pre venta generado #'+data.idPedido,function(){ document.location.href = 'nuevo-pedido.php?idpedido='+data.idPedido; }); $('#panelFacturar').show(); } $btn.button('reset'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#NuevoItem').click(function(event) { /* Act on the event */ $('#myModal').modal('show'); $('#myModalLabel').html('Nuevo Pedido'); event.preventDefault(); }); /* -------------------------------------- */ //$('.jChosen').chosen({width: "100%"}); /* -------------------------------------- */ $('#addProducto').click(function(event) { $(this).attr({'disabled':'disabled'}); // var _data = $('#frmEditor').serialize(); // $.post( _servicio , _data , function(data, textStatus, xhr) { $('#addProducto').removeAttr('disabled'); loadTablita(data); resetAddItems(); $('#txtProducto').val(''); $('#txtProducto').focus(); alertify.success('Producto agregado'); },'json'); event.preventDefault(); }); /* -------------------------------------- */ $('#txtPrecio').keyup(function(event) { var _cant = $('#txtCantidad').val(), _precio = $(this).val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $('#txtCantidad').keyup(function(event) { var _cant = $(this).val(), _precio = $('#txtPrecio').val(); var _total = _cant * _precio; $('#txtTotal').val(_total); }); /* -------------------------------------- */ $(document).delegate('.quitarProd', 'click', function(event) { /* Quitar un item de la lista y volver a dibujar la tabla. */ var _Nombre = $(this).attr('rel'), _idd = $(this).attr('href'); alertify.confirm('Confirme quitar Item: '+_Nombre,function(e){ if(e){ $.post( _servicio , {f:'delItem',idItem:_idd,'idp':_idPedido} , function(data, textStatus, xhr) { $('#Fila_'+_idd).hide('slow'); loadTablita(data); alertify.error('Producto quitado.'); },'json'); } }); event.preventDefault(); }); /* -------------------------------------- */ $(document).delegate('.ItemLista', 'click', function(event) { /* Agregar un item de la lista y volver a dibujar la tabla. */ var _idp = $(this).attr('href'); $.post( _servicio , { f:'getItem', idp:_idp } , function(data, textStatus, xhr) { LoadItem( data ); },'json'); event.preventDefault();
event.preventDefault(); }); /* -------------------------------------- */ $('#btnGoFacturar').click(function(event) { var _filtro = ''; _docGenerate = $('#Documento').val(); _serieUsar = $('#Correlativo').val(); var _idPedido = $('#idPedido').val(); _filtro = 'goBoleta'; /**/ $.post( _servicio , { f:_filtro, idp:_idPedido, 'TipoDoc':_docGenerate, serie:_serieUsar} , function(data, textStatus, xhr) { if( data.idVenta > 0 ){ switch(_docGenerate){ case 'B': document.location.href = 'nueva-boleta.php?id='+data.idVenta; break; case 'F': document.location.href = 'nueva-factura.php?id='+data.idVenta; break; case 'R': document.location.href = 'nuevo-recibo.php?id='+data.idVenta; break; } } },'json'); /**/ event.preventDefault(); }); /* -------------------------------------- */ }); })(jQuery); function LoadItem( json ){ if( json.data != undefined || json.data != null ){ var _html = '', _item = []; for (var i = 0; i < json.data.length; i++) { _item = json.data[0]; $('#txtCantidad').val( _item.int_Cantidad ); //$('#txtProducto').val( _item.var_Nombre+' x '+_item.unidadMedida ); $('#txtPrecio').val( _item.flt_Precio ); $('#txtTotal').val( _item.flt_Total ); // $('#idProd').val( _item.int_IdProducto ); $('#idUM').val( _item.int_IdUnidadMedida ); $('#idItem').val( _item.int_IdDetallePedido ); $('#editorProducto').fadeIn('fast'); }; } } function resetAddItems(){ $('#containerProducto').removeClass().addClass('form-group'); $('#idProd').val('0'); $('#idUM').val('0'); $('#txtPrecio').val( '0' ); $('#txtCantidad').val( '' ); $('#txtTotal').val( '0' ); //$("#txtProducto").val(''); $("#idItem").val('0'); } function loadTablita( json ){ if( json.data != undefined || json.data != null ){ var _fila = [], _html = '', _total = 0; for (var i = 0; i < json.data.length; i++) { _fila = json.data[i]; _html += '<tr id="Fila_'+_fila.int_IdDetallePedido+'" >'; _html += '<td>'; _html += '<span class="fa fa-barcode" ></span> '+_fila.prod+' x '+_fila.um+''; if( _fila.int_IdPromo != null ){ _html += '<br/><small>'+_fila.var_Promo+' antes ('+_fila.flt_Precio+')</small>'; } _html += '</td>'; _html += '<td>'+_fila.lote+'</td>'; if( _fila.int_IdPromo != null ){ _html += '<td class="text-right" >S/. '+_fila.flt_Promo+'</td>'; }else{ _html += '<td class="text-right" >S/. '+_fila.flt_Precio+'</td>'; } _html += '<td class="text-right" >'+_fila.cant+'</td>'; _total = _total + parseFloat(_fila.flt_Total); _html += '<td class="text-right" >'+_fila.flt_Total+'</td>'; _html += '<td>'; _html += '<a href="'+_fila.int_IdDetallePedido+'" class="pull-right quitarProd" rel="'+_fila.prod+'" ><span class="glyphicon glyphicon-remove" ></span></a>'; _html += '</td>'; }; $('#TotalPedido').val( _total ); $('#LabelTotal').html('Total Pre venta: '+_total); $('#Tablita tbody').html( _html ); } } /*Solo Numeros*/ /* onkeypress="return validar(event);" */ function validar(e) { tecla = (document.all)?e.keyCode:e.which;//ascii //alert(tecla); switch(tecla){ case 8: return true; break; case 46://punto return true; break; case 43://Mas return true; break; case 45://Menos return true; break; case 44://Coma return true; break; case 0://Suprimir return true; break; default: break; } patron = /\d/; te = String.fromCharCode(tecla); return patron.test(te); }
}); /* -------------------------------------- */ $(document).delegate('.goPedido', 'click', function(event) { var _idp = $(this).attr('href'); $('#myModal').modal('show');
random_line_split
user-webuploader.js
// 文件上传 jQuery(function() { var $ = jQuery, $list = $('#thelist'), $btn = $('#ctlBtn'), state = 'pending', // 优化retina, 在retina下这个值是2 ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 100 * ratio, thumbnailHeight = 100 * ratio, uploader; uploader = WebUploader.create({ // 单文件上传 multiple: false, // 不压缩image resize: false, // swf文件路径 swf: '/webuploader/Uploader.swf', // 文件接收服务端。 server: '/upload', // 选择文件的按钮。可选。 // 内部根据当前运行是创建,可能是input元素,也可能是flash. pick: '#picker', // 只允许选择图片文件。 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }); // 当有文件添加进来的时候 uploader.on( 'fileQueued', function( file ) { var $li = $( '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>' ), $img = $li.find('img'); $list.append( $li ); // 创建缩略图 uploader.makeThumb( file, function( error, src ) { if ( error ) { $img.replaceWith('<span>不能预览</span>'); return; } $img.attr( 'src', src ); }, thumbnailWidth, thumbnailHeight ); }); // 文件上传过程中创建进度条实时显示。 uploader.on( 'uploadProgress', function( file, percentage ) { var $li = $( '#'+file.id ), $percent = $li.find('.progress .progress-bar'); // 避免重复创建 if ( !$percent.length ) { $percent = $('<div class="progress progress-striped active">' + '<div class="progress-bar" role="progressbar" style="width: 0%">' + '</div>' + '</div>').appendTo( $li ).find('.progress-bar'); } $li.find('p.state').text('上传中'); $percent.css( 'width', percentage * 100 + '%' ); }); uploader.on( 'uploadSuccess', function( file , data) { $( '#'+file.id ).find('p.state').text('已上传'); $('#user_avatar').val(data.imageurl) $('#avatar').attr("src",data.imageurl) }); uploader.on( 'uploadError', function( file ) { $( '#'+file.id ).find('p.state').text('上传出错'); }); uploader.on( 'uploadComplete', function( file ) { $( '#'+file.id ).find('.progress').fadeOut(); }); uploader.on( 'all', function( type ) { if ( type === 'startUpload' ) { state = 'uploading'; } else if ( type === 'stopUpload' ) { state = 'paused'; } else if ( type === 'uploadFinished' ) { state = 'done'; } if ( state === 'uploading' ) { $btn.text('暂停上传'); } else { $btn.text('开始上传'); } }); $btn.on( 'click', function() { if ( state === 'uploading' ) { uploader.stop(); } else { uploader.upload(); } }); });
conditional_block
user-webuploader.js
// 文件上传 jQuery(function() { var $ = jQuery, $list = $('#thelist'), $btn = $('#ctlBtn'), state = 'pending', // 优化retina, 在retina下这个值是2 ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 100 * ratio, thumbnailHeight = 100 * ratio,
multiple: false, // 不压缩image resize: false, // swf文件路径 swf: '/webuploader/Uploader.swf', // 文件接收服务端。 server: '/upload', // 选择文件的按钮。可选。 // 内部根据当前运行是创建,可能是input元素,也可能是flash. pick: '#picker', // 只允许选择图片文件。 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }); // 当有文件添加进来的时候 uploader.on( 'fileQueued', function( file ) { var $li = $( '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>' ), $img = $li.find('img'); $list.append( $li ); // 创建缩略图 uploader.makeThumb( file, function( error, src ) { if ( error ) { $img.replaceWith('<span>不能预览</span>'); return; } $img.attr( 'src', src ); }, thumbnailWidth, thumbnailHeight ); }); // 文件上传过程中创建进度条实时显示。 uploader.on( 'uploadProgress', function( file, percentage ) { var $li = $( '#'+file.id ), $percent = $li.find('.progress .progress-bar'); // 避免重复创建 if ( !$percent.length ) { $percent = $('<div class="progress progress-striped active">' + '<div class="progress-bar" role="progressbar" style="width: 0%">' + '</div>' + '</div>').appendTo( $li ).find('.progress-bar'); } $li.find('p.state').text('上传中'); $percent.css( 'width', percentage * 100 + '%' ); }); uploader.on( 'uploadSuccess', function( file , data) { $( '#'+file.id ).find('p.state').text('已上传'); $('#user_avatar').val(data.imageurl) $('#avatar').attr("src",data.imageurl) }); uploader.on( 'uploadError', function( file ) { $( '#'+file.id ).find('p.state').text('上传出错'); }); uploader.on( 'uploadComplete', function( file ) { $( '#'+file.id ).find('.progress').fadeOut(); }); uploader.on( 'all', function( type ) { if ( type === 'startUpload' ) { state = 'uploading'; } else if ( type === 'stopUpload' ) { state = 'paused'; } else if ( type === 'uploadFinished' ) { state = 'done'; } if ( state === 'uploading' ) { $btn.text('暂停上传'); } else { $btn.text('开始上传'); } }); $btn.on( 'click', function() { if ( state === 'uploading' ) { uploader.stop(); } else { uploader.upload(); } }); });
uploader; uploader = WebUploader.create({ // 单文件上传
random_line_split
proxyLinda.py
''' PyDALI proxyLinda module to encapsulate DALI agent communication in the ASP solver case study Licensed with Apache Public License by AAAI Research Group Department of Information Engineering and Computer Science and Mathematics University of L'Aquila, ITALY http://www.disim.univaq.it ''' __author__ = 'AAAI-DISIM@UnivAQ' from aspsolver import AspSolver import threading from lin import * import socket import json import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web
tornado.platform.twisted.install() from twisted.internet import protocol, reactor AG_COORDINATOR = 'agCoordinator' AG_METAPLANNER = 'agMetaPlanner' # localmachine = socket.gethostname().lower() localmachine = 'localhost' sock = socket.socket() sock.connect((localmachine, 3010)) # root = '.' + os.sep + os.path.dirname(__file__) + os.sep + 'web' root = './web' print 'myroot:', root system_connection = {} TMAX = 100 # secondi def createmessage(sender, destination, typefunc, message): m = "message(%s:3010,%s,%s:3010,%s,italian,[],%s(%s,%s))" % (localmachine, destination, localmachine, sender, typefunc, message, sender) return m system_connection = {} class WSHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True def sendConsoleMessage(self, message): console = {} console['type'] = 'console' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def sendPath(self, message): console = {} console['type'] = 'path' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def open(self): print 'new connection' self.identifier = str(int(time.time())) system_connection[self.identifier] = self m = createmessage('user', AG_COORDINATOR, 'send_message', "new_connection(%s)" % self.identifier) wrm = write_message(m) sock.send(wrm) self.sendConsoleMessage('System Ready') def on_message(self, message): print message jsonmessage = json.loads(message) # print jsonmessage # # m = createmessage(jsonmessage['sender'], jsonmessage['destination'], jsonmessage['typefunc'], jsonmessage['message']) # print m # wrm = write_message(m) # print 'message received %s' % message # print wrm # sock.send(wrm) # self.write_message(wrm) def on_close(self): print 'connection closed' system_connection.pop(self.identifier) class MainHandler(tornado.web.RequestHandler): def get(self): try: with open(os.path.join(root, 'knight' + os.sep + 'index.html')) as f: self.write(f.read()) except IOError as e: self.write("404: Not Found") class PlanHandler(tornado.web.RequestHandler): def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None def post(self): identifier = self.json_args.get('identifier') forbidden = self.json_args.get('forbidden') mandatory = self.json_args.get('mandatory') size = self.json_args.get('size') f = open('dlvprogram/instance.dl', 'w') f.write('size(%s). ' % size) for forb in forbidden: f.write("forbidden(%s,%s). " % (forb.get('x'), forb.get('y'))) for mark in mandatory: f.write("must_reach(%s,%s). " % (mark.get('x'), mark.get('y'))) f.close() m = "instanceReady(%s, %s)" % (size, len(forbidden)) m = createmessage('user', AG_COORDINATOR, 'send_message', m) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) for forb in forbidden: mess = "forbidden_of_problem([%s,%s])" % (forb.get('x'), forb.get('y')) m = createmessage('user', AG_COORDINATOR, 'send_message', mess) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) system_connection[identifier].sendConsoleMessage('Request sent to system') class ResetHandler(tornado.web.RequestHandler): def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None def post(self): identifier = self.json_args.get('identifier') m = createmessage('user', AG_COORDINATOR, 'send_message', "new_connection(%s)" % identifier) wrm = write_message(m) sock.send(wrm) application = tornado.web.Application([ (r'/ws', WSHandler), (r"/", MainHandler), (r"/api/plan", PlanHandler), (r"/api/reset", ResetHandler), (r"/(.*)", tornado.web.StaticFileHandler, dict(path=root)), ]) temporaryresult = None class DALI(protocol.Protocol): def notifyFailure(self): message = 'problem_failed(%s)' % self.currentproblem m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) def checkPlan(self): if not self.planner.is_alive(): print 'DLV ended.' try: self.planner.readresult() global temporaryresult temporaryresult = self.planner.getresult() if self.currentproblem == 1: system_connection[self.identifier].sendConsoleMessage( 'Hamiltonian Tour Problem has found a solution') elif self.currentproblem == 2: system_connection[self.identifier].sendConsoleMessage('Weak Constraint Problem has found a solution') elif self.currentproblem == 3: system_connection[self.identifier].sendConsoleMessage('With Blank Problem has found a solution') message = 'new_moves_for_evaluate(%s)' % len(temporaryresult) m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) system_connection[self.identifier].sendConsoleMessage('Plan sent to MAS') except: self.notifyFailure() else: print 'DLV is alive' dt = time.time() - self.t0 print dt, 'secs elapsed' if dt > TMAX: self.planner.terminate() print 'DLV terminated' self.notifyFailure() threading.Timer(1, self.checkPlan).start() def makePlan(self, problem): path = "dlvprogram" + os.sep + "problem%s.dl" % problem self.currentproblem = problem self.planner = AspSolver("dlvprogram" + os.sep + "instance.dl", path) self.planner.run() self.t0 = time.time() time.sleep(5) threading.Timer(1, self.checkPlan).start() def dataReceived(self, data): # print 'data', data fs = data.split('_.._') identifier = fs[1] self.identifier = identifier if len(fs) > 3: cmd = fs[2] if cmd == 'path': strJSONPath = fs[3] print strJSONPath system_connection[identifier].sendPath(strJSONPath) elif cmd == 'as': state = fs[3] system_connection[identifier].sendConsoleMessage('State of agent: ' + str(state)) elif len(fs) > 2: cmd = fs[2] if cmd == 'pr': system_connection[identifier].sendConsoleMessage('Plan Received From MAS') elif cmd == 'ss1': self.makePlan(1) system_connection[identifier].sendConsoleMessage('Testing problem Hamiltonian Tour') elif cmd == 'ss2': self.makePlan(2) system_connection[identifier].sendConsoleMessage('Testing problem Weak Constraint') elif cmd == 'ss3': system_connection[identifier].sendConsoleMessage('Trivial Solution') elif cmd == 'ss4': self.makePlan(3) system_connection[identifier].sendConsoleMessage('Testing problem must reach') elif cmd == 'pf1': system_connection[identifier].sendConsoleMessage('Hamiltonian Tour Failed') elif cmd == 'pf2': system_connection[identifier].sendConsoleMessage('Weak Constraint Failed') elif cmd == 'pf3': system_connection[identifier].sendConsoleMessage('Blank Failed') elif cmd == 'pft': system_connection[identifier].sendConsoleMessage('Weak Constraint is not optimal') elif cmd == 'rs': system_connection[identifier].sendConsoleMessage('State of agent: 0') elif cmd == 'smr': for mv in temporaryresult: mv = mv[5:-1] x1, y1, x2, y2 = mv.split(',') message = 'moves_for_evaluate([%s,%s,%s,%s])' % (x1, y1, x2, y2) m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) system_connection[identifier].sendConsoleMessage('MAS: Waiting for Plan elaboration') else: system_connection[identifier].sendConsoleMessage('MAS Ready') class DALIFactory(protocol.Factory): def buildProtocol(self, addr): return DALI() if __name__ == "__main__": print 'http://localhost:8888/knight/index.html' http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) reactor.listenTCP(3333, DALIFactory()) tornado.ioloop.IOLoop.instance().start()
import os import time import select import tornado.platform.twisted
random_line_split
proxyLinda.py
''' PyDALI proxyLinda module to encapsulate DALI agent communication in the ASP solver case study Licensed with Apache Public License by AAAI Research Group Department of Information Engineering and Computer Science and Mathematics University of L'Aquila, ITALY http://www.disim.univaq.it ''' __author__ = 'AAAI-DISIM@UnivAQ' from aspsolver import AspSolver import threading from lin import * import socket import json import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import os import time import select import tornado.platform.twisted tornado.platform.twisted.install() from twisted.internet import protocol, reactor AG_COORDINATOR = 'agCoordinator' AG_METAPLANNER = 'agMetaPlanner' # localmachine = socket.gethostname().lower() localmachine = 'localhost' sock = socket.socket() sock.connect((localmachine, 3010)) # root = '.' + os.sep + os.path.dirname(__file__) + os.sep + 'web' root = './web' print 'myroot:', root system_connection = {} TMAX = 100 # secondi def createmessage(sender, destination, typefunc, message): m = "message(%s:3010,%s,%s:3010,%s,italian,[],%s(%s,%s))" % (localmachine, destination, localmachine, sender, typefunc, message, sender) return m system_connection = {} class WSHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True def sendConsoleMessage(self, message): console = {} console['type'] = 'console' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def sendPath(self, message): console = {} console['type'] = 'path' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def open(self): print 'new connection' self.identifier = str(int(time.time())) system_connection[self.identifier] = self m = createmessage('user', AG_COORDINATOR, 'send_message', "new_connection(%s)" % self.identifier) wrm = write_message(m) sock.send(wrm) self.sendConsoleMessage('System Ready') def on_message(self, message): print message jsonmessage = json.loads(message) # print jsonmessage # # m = createmessage(jsonmessage['sender'], jsonmessage['destination'], jsonmessage['typefunc'], jsonmessage['message']) # print m # wrm = write_message(m) # print 'message received %s' % message # print wrm # sock.send(wrm) # self.write_message(wrm) def on_close(self): print 'connection closed' system_connection.pop(self.identifier) class MainHandler(tornado.web.RequestHandler): def get(self): try: with open(os.path.join(root, 'knight' + os.sep + 'index.html')) as f: self.write(f.read()) except IOError as e: self.write("404: Not Found") class PlanHandler(tornado.web.RequestHandler): def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None def post(self): identifier = self.json_args.get('identifier') forbidden = self.json_args.get('forbidden') mandatory = self.json_args.get('mandatory') size = self.json_args.get('size') f = open('dlvprogram/instance.dl', 'w') f.write('size(%s). ' % size) for forb in forbidden: f.write("forbidden(%s,%s). " % (forb.get('x'), forb.get('y'))) for mark in mandatory: f.write("must_reach(%s,%s). " % (mark.get('x'), mark.get('y'))) f.close() m = "instanceReady(%s, %s)" % (size, len(forbidden)) m = createmessage('user', AG_COORDINATOR, 'send_message', m) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) for forb in forbidden: mess = "forbidden_of_problem([%s,%s])" % (forb.get('x'), forb.get('y')) m = createmessage('user', AG_COORDINATOR, 'send_message', mess) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) system_connection[identifier].sendConsoleMessage('Request sent to system') class ResetHandler(tornado.web.RequestHandler): def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None def post(self): identifier = self.json_args.get('identifier') m = createmessage('user', AG_COORDINATOR, 'send_message', "new_connection(%s)" % identifier) wrm = write_message(m) sock.send(wrm) application = tornado.web.Application([ (r'/ws', WSHandler), (r"/", MainHandler), (r"/api/plan", PlanHandler), (r"/api/reset", ResetHandler), (r"/(.*)", tornado.web.StaticFileHandler, dict(path=root)), ]) temporaryresult = None class DALI(protocol.Protocol): def notifyFailure(self): message = 'problem_failed(%s)' % self.currentproblem m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) def checkPlan(self): if not self.planner.is_alive(): print 'DLV ended.' try: self.planner.readresult() global temporaryresult temporaryresult = self.planner.getresult() if self.currentproblem == 1: system_connection[self.identifier].sendConsoleMessage( 'Hamiltonian Tour Problem has found a solution') elif self.currentproblem == 2:
elif self.currentproblem == 3: system_connection[self.identifier].sendConsoleMessage('With Blank Problem has found a solution') message = 'new_moves_for_evaluate(%s)' % len(temporaryresult) m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) system_connection[self.identifier].sendConsoleMessage('Plan sent to MAS') except: self.notifyFailure() else: print 'DLV is alive' dt = time.time() - self.t0 print dt, 'secs elapsed' if dt > TMAX: self.planner.terminate() print 'DLV terminated' self.notifyFailure() threading.Timer(1, self.checkPlan).start() def makePlan(self, problem): path = "dlvprogram" + os.sep + "problem%s.dl" % problem self.currentproblem = problem self.planner = AspSolver("dlvprogram" + os.sep + "instance.dl", path) self.planner.run() self.t0 = time.time() time.sleep(5) threading.Timer(1, self.checkPlan).start() def dataReceived(self, data): # print 'data', data fs = data.split('_.._') identifier = fs[1] self.identifier = identifier if len(fs) > 3: cmd = fs[2] if cmd == 'path': strJSONPath = fs[3] print strJSONPath system_connection[identifier].sendPath(strJSONPath) elif cmd == 'as': state = fs[3] system_connection[identifier].sendConsoleMessage('State of agent: ' + str(state)) elif len(fs) > 2: cmd = fs[2] if cmd == 'pr': system_connection[identifier].sendConsoleMessage('Plan Received From MAS') elif cmd == 'ss1': self.makePlan(1) system_connection[identifier].sendConsoleMessage('Testing problem Hamiltonian Tour') elif cmd == 'ss2': self.makePlan(2) system_connection[identifier].sendConsoleMessage('Testing problem Weak Constraint') elif cmd == 'ss3': system_connection[identifier].sendConsoleMessage('Trivial Solution') elif cmd == 'ss4': self.makePlan(3) system_connection[identifier].sendConsoleMessage('Testing problem must reach') elif cmd == 'pf1': system_connection[identifier].sendConsoleMessage('Hamiltonian Tour Failed') elif cmd == 'pf2': system_connection[identifier].sendConsoleMessage('Weak Constraint Failed') elif cmd == 'pf3': system_connection[identifier].sendConsoleMessage('Blank Failed') elif cmd == 'pft': system_connection[identifier].sendConsoleMessage('Weak Constraint is not optimal') elif cmd == 'rs': system_connection[identifier].sendConsoleMessage('State of agent: 0') elif cmd == 'smr': for mv in temporaryresult: mv = mv[5:-1] x1, y1, x2, y2 = mv.split(',') message = 'moves_for_evaluate([%s,%s,%s,%s])' % (x1, y1, x2, y2) m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) system_connection[identifier].sendConsoleMessage('MAS: Waiting for Plan elaboration') else: system_connection[identifier].sendConsoleMessage('MAS Ready') class DALIFactory(protocol.Factory): def buildProtocol(self, addr): return DALI() if __name__ == "__main__": print 'http://localhost:8888/knight/index.html' http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) reactor.listenTCP(3333, DALIFactory()) tornado.ioloop.IOLoop.instance().start()
system_connection[self.identifier].sendConsoleMessage('Weak Constraint Problem has found a solution')
conditional_block
proxyLinda.py
''' PyDALI proxyLinda module to encapsulate DALI agent communication in the ASP solver case study Licensed with Apache Public License by AAAI Research Group Department of Information Engineering and Computer Science and Mathematics University of L'Aquila, ITALY http://www.disim.univaq.it ''' __author__ = 'AAAI-DISIM@UnivAQ' from aspsolver import AspSolver import threading from lin import * import socket import json import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import os import time import select import tornado.platform.twisted tornado.platform.twisted.install() from twisted.internet import protocol, reactor AG_COORDINATOR = 'agCoordinator' AG_METAPLANNER = 'agMetaPlanner' # localmachine = socket.gethostname().lower() localmachine = 'localhost' sock = socket.socket() sock.connect((localmachine, 3010)) # root = '.' + os.sep + os.path.dirname(__file__) + os.sep + 'web' root = './web' print 'myroot:', root system_connection = {} TMAX = 100 # secondi def createmessage(sender, destination, typefunc, message): m = "message(%s:3010,%s,%s:3010,%s,italian,[],%s(%s,%s))" % (localmachine, destination, localmachine, sender, typefunc, message, sender) return m system_connection = {} class WSHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True def sendConsoleMessage(self, message): console = {} console['type'] = 'console' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def sendPath(self, message): console = {} console['type'] = 'path' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def open(self): print 'new connection' self.identifier = str(int(time.time())) system_connection[self.identifier] = self m = createmessage('user', AG_COORDINATOR, 'send_message', "new_connection(%s)" % self.identifier) wrm = write_message(m) sock.send(wrm) self.sendConsoleMessage('System Ready') def on_message(self, message): print message jsonmessage = json.loads(message) # print jsonmessage # # m = createmessage(jsonmessage['sender'], jsonmessage['destination'], jsonmessage['typefunc'], jsonmessage['message']) # print m # wrm = write_message(m) # print 'message received %s' % message # print wrm # sock.send(wrm) # self.write_message(wrm) def on_close(self): print 'connection closed' system_connection.pop(self.identifier) class MainHandler(tornado.web.RequestHandler): def get(self):
class PlanHandler(tornado.web.RequestHandler): def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None def post(self): identifier = self.json_args.get('identifier') forbidden = self.json_args.get('forbidden') mandatory = self.json_args.get('mandatory') size = self.json_args.get('size') f = open('dlvprogram/instance.dl', 'w') f.write('size(%s). ' % size) for forb in forbidden: f.write("forbidden(%s,%s). " % (forb.get('x'), forb.get('y'))) for mark in mandatory: f.write("must_reach(%s,%s). " % (mark.get('x'), mark.get('y'))) f.close() m = "instanceReady(%s, %s)" % (size, len(forbidden)) m = createmessage('user', AG_COORDINATOR, 'send_message', m) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) for forb in forbidden: mess = "forbidden_of_problem([%s,%s])" % (forb.get('x'), forb.get('y')) m = createmessage('user', AG_COORDINATOR, 'send_message', mess) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) system_connection[identifier].sendConsoleMessage('Request sent to system') class ResetHandler(tornado.web.RequestHandler): def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None def post(self): identifier = self.json_args.get('identifier') m = createmessage('user', AG_COORDINATOR, 'send_message', "new_connection(%s)" % identifier) wrm = write_message(m) sock.send(wrm) application = tornado.web.Application([ (r'/ws', WSHandler), (r"/", MainHandler), (r"/api/plan", PlanHandler), (r"/api/reset", ResetHandler), (r"/(.*)", tornado.web.StaticFileHandler, dict(path=root)), ]) temporaryresult = None class DALI(protocol.Protocol): def notifyFailure(self): message = 'problem_failed(%s)' % self.currentproblem m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) def checkPlan(self): if not self.planner.is_alive(): print 'DLV ended.' try: self.planner.readresult() global temporaryresult temporaryresult = self.planner.getresult() if self.currentproblem == 1: system_connection[self.identifier].sendConsoleMessage( 'Hamiltonian Tour Problem has found a solution') elif self.currentproblem == 2: system_connection[self.identifier].sendConsoleMessage('Weak Constraint Problem has found a solution') elif self.currentproblem == 3: system_connection[self.identifier].sendConsoleMessage('With Blank Problem has found a solution') message = 'new_moves_for_evaluate(%s)' % len(temporaryresult) m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) system_connection[self.identifier].sendConsoleMessage('Plan sent to MAS') except: self.notifyFailure() else: print 'DLV is alive' dt = time.time() - self.t0 print dt, 'secs elapsed' if dt > TMAX: self.planner.terminate() print 'DLV terminated' self.notifyFailure() threading.Timer(1, self.checkPlan).start() def makePlan(self, problem): path = "dlvprogram" + os.sep + "problem%s.dl" % problem self.currentproblem = problem self.planner = AspSolver("dlvprogram" + os.sep + "instance.dl", path) self.planner.run() self.t0 = time.time() time.sleep(5) threading.Timer(1, self.checkPlan).start() def dataReceived(self, data): # print 'data', data fs = data.split('_.._') identifier = fs[1] self.identifier = identifier if len(fs) > 3: cmd = fs[2] if cmd == 'path': strJSONPath = fs[3] print strJSONPath system_connection[identifier].sendPath(strJSONPath) elif cmd == 'as': state = fs[3] system_connection[identifier].sendConsoleMessage('State of agent: ' + str(state)) elif len(fs) > 2: cmd = fs[2] if cmd == 'pr': system_connection[identifier].sendConsoleMessage('Plan Received From MAS') elif cmd == 'ss1': self.makePlan(1) system_connection[identifier].sendConsoleMessage('Testing problem Hamiltonian Tour') elif cmd == 'ss2': self.makePlan(2) system_connection[identifier].sendConsoleMessage('Testing problem Weak Constraint') elif cmd == 'ss3': system_connection[identifier].sendConsoleMessage('Trivial Solution') elif cmd == 'ss4': self.makePlan(3) system_connection[identifier].sendConsoleMessage('Testing problem must reach') elif cmd == 'pf1': system_connection[identifier].sendConsoleMessage('Hamiltonian Tour Failed') elif cmd == 'pf2': system_connection[identifier].sendConsoleMessage('Weak Constraint Failed') elif cmd == 'pf3': system_connection[identifier].sendConsoleMessage('Blank Failed') elif cmd == 'pft': system_connection[identifier].sendConsoleMessage('Weak Constraint is not optimal') elif cmd == 'rs': system_connection[identifier].sendConsoleMessage('State of agent: 0') elif cmd == 'smr': for mv in temporaryresult: mv = mv[5:-1] x1, y1, x2, y2 = mv.split(',') message = 'moves_for_evaluate([%s,%s,%s,%s])' % (x1, y1, x2, y2) m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) system_connection[identifier].sendConsoleMessage('MAS: Waiting for Plan elaboration') else: system_connection[identifier].sendConsoleMessage('MAS Ready') class DALIFactory(protocol.Factory): def buildProtocol(self, addr): return DALI() if __name__ == "__main__": print 'http://localhost:8888/knight/index.html' http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) reactor.listenTCP(3333, DALIFactory()) tornado.ioloop.IOLoop.instance().start()
try: with open(os.path.join(root, 'knight' + os.sep + 'index.html')) as f: self.write(f.read()) except IOError as e: self.write("404: Not Found")
identifier_body
proxyLinda.py
''' PyDALI proxyLinda module to encapsulate DALI agent communication in the ASP solver case study Licensed with Apache Public License by AAAI Research Group Department of Information Engineering and Computer Science and Mathematics University of L'Aquila, ITALY http://www.disim.univaq.it ''' __author__ = 'AAAI-DISIM@UnivAQ' from aspsolver import AspSolver import threading from lin import * import socket import json import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import os import time import select import tornado.platform.twisted tornado.platform.twisted.install() from twisted.internet import protocol, reactor AG_COORDINATOR = 'agCoordinator' AG_METAPLANNER = 'agMetaPlanner' # localmachine = socket.gethostname().lower() localmachine = 'localhost' sock = socket.socket() sock.connect((localmachine, 3010)) # root = '.' + os.sep + os.path.dirname(__file__) + os.sep + 'web' root = './web' print 'myroot:', root system_connection = {} TMAX = 100 # secondi def createmessage(sender, destination, typefunc, message): m = "message(%s:3010,%s,%s:3010,%s,italian,[],%s(%s,%s))" % (localmachine, destination, localmachine, sender, typefunc, message, sender) return m system_connection = {} class WSHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True def sendConsoleMessage(self, message): console = {} console['type'] = 'console' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def sendPath(self, message): console = {} console['type'] = 'path' console['identifier'] = self.identifier console['message'] = message self.write_message(json.dumps(console)) def
(self): print 'new connection' self.identifier = str(int(time.time())) system_connection[self.identifier] = self m = createmessage('user', AG_COORDINATOR, 'send_message', "new_connection(%s)" % self.identifier) wrm = write_message(m) sock.send(wrm) self.sendConsoleMessage('System Ready') def on_message(self, message): print message jsonmessage = json.loads(message) # print jsonmessage # # m = createmessage(jsonmessage['sender'], jsonmessage['destination'], jsonmessage['typefunc'], jsonmessage['message']) # print m # wrm = write_message(m) # print 'message received %s' % message # print wrm # sock.send(wrm) # self.write_message(wrm) def on_close(self): print 'connection closed' system_connection.pop(self.identifier) class MainHandler(tornado.web.RequestHandler): def get(self): try: with open(os.path.join(root, 'knight' + os.sep + 'index.html')) as f: self.write(f.read()) except IOError as e: self.write("404: Not Found") class PlanHandler(tornado.web.RequestHandler): def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None def post(self): identifier = self.json_args.get('identifier') forbidden = self.json_args.get('forbidden') mandatory = self.json_args.get('mandatory') size = self.json_args.get('size') f = open('dlvprogram/instance.dl', 'w') f.write('size(%s). ' % size) for forb in forbidden: f.write("forbidden(%s,%s). " % (forb.get('x'), forb.get('y'))) for mark in mandatory: f.write("must_reach(%s,%s). " % (mark.get('x'), mark.get('y'))) f.close() m = "instanceReady(%s, %s)" % (size, len(forbidden)) m = createmessage('user', AG_COORDINATOR, 'send_message', m) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) for forb in forbidden: mess = "forbidden_of_problem([%s,%s])" % (forb.get('x'), forb.get('y')) m = createmessage('user', AG_COORDINATOR, 'send_message', mess) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) system_connection[identifier].sendConsoleMessage('Request sent to system') class ResetHandler(tornado.web.RequestHandler): def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None def post(self): identifier = self.json_args.get('identifier') m = createmessage('user', AG_COORDINATOR, 'send_message', "new_connection(%s)" % identifier) wrm = write_message(m) sock.send(wrm) application = tornado.web.Application([ (r'/ws', WSHandler), (r"/", MainHandler), (r"/api/plan", PlanHandler), (r"/api/reset", ResetHandler), (r"/(.*)", tornado.web.StaticFileHandler, dict(path=root)), ]) temporaryresult = None class DALI(protocol.Protocol): def notifyFailure(self): message = 'problem_failed(%s)' % self.currentproblem m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) def checkPlan(self): if not self.planner.is_alive(): print 'DLV ended.' try: self.planner.readresult() global temporaryresult temporaryresult = self.planner.getresult() if self.currentproblem == 1: system_connection[self.identifier].sendConsoleMessage( 'Hamiltonian Tour Problem has found a solution') elif self.currentproblem == 2: system_connection[self.identifier].sendConsoleMessage('Weak Constraint Problem has found a solution') elif self.currentproblem == 3: system_connection[self.identifier].sendConsoleMessage('With Blank Problem has found a solution') message = 'new_moves_for_evaluate(%s)' % len(temporaryresult) m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) system_connection[self.identifier].sendConsoleMessage('Plan sent to MAS') except: self.notifyFailure() else: print 'DLV is alive' dt = time.time() - self.t0 print dt, 'secs elapsed' if dt > TMAX: self.planner.terminate() print 'DLV terminated' self.notifyFailure() threading.Timer(1, self.checkPlan).start() def makePlan(self, problem): path = "dlvprogram" + os.sep + "problem%s.dl" % problem self.currentproblem = problem self.planner = AspSolver("dlvprogram" + os.sep + "instance.dl", path) self.planner.run() self.t0 = time.time() time.sleep(5) threading.Timer(1, self.checkPlan).start() def dataReceived(self, data): # print 'data', data fs = data.split('_.._') identifier = fs[1] self.identifier = identifier if len(fs) > 3: cmd = fs[2] if cmd == 'path': strJSONPath = fs[3] print strJSONPath system_connection[identifier].sendPath(strJSONPath) elif cmd == 'as': state = fs[3] system_connection[identifier].sendConsoleMessage('State of agent: ' + str(state)) elif len(fs) > 2: cmd = fs[2] if cmd == 'pr': system_connection[identifier].sendConsoleMessage('Plan Received From MAS') elif cmd == 'ss1': self.makePlan(1) system_connection[identifier].sendConsoleMessage('Testing problem Hamiltonian Tour') elif cmd == 'ss2': self.makePlan(2) system_connection[identifier].sendConsoleMessage('Testing problem Weak Constraint') elif cmd == 'ss3': system_connection[identifier].sendConsoleMessage('Trivial Solution') elif cmd == 'ss4': self.makePlan(3) system_connection[identifier].sendConsoleMessage('Testing problem must reach') elif cmd == 'pf1': system_connection[identifier].sendConsoleMessage('Hamiltonian Tour Failed') elif cmd == 'pf2': system_connection[identifier].sendConsoleMessage('Weak Constraint Failed') elif cmd == 'pf3': system_connection[identifier].sendConsoleMessage('Blank Failed') elif cmd == 'pft': system_connection[identifier].sendConsoleMessage('Weak Constraint is not optimal') elif cmd == 'rs': system_connection[identifier].sendConsoleMessage('State of agent: 0') elif cmd == 'smr': for mv in temporaryresult: mv = mv[5:-1] x1, y1, x2, y2 = mv.split(',') message = 'moves_for_evaluate([%s,%s,%s,%s])' % (x1, y1, x2, y2) m = createmessage('user', AG_METAPLANNER, 'send_message', message) wrm = write_message(m) sock.send(wrm) time.sleep(0.2) system_connection[identifier].sendConsoleMessage('MAS: Waiting for Plan elaboration') else: system_connection[identifier].sendConsoleMessage('MAS Ready') class DALIFactory(protocol.Factory): def buildProtocol(self, addr): return DALI() if __name__ == "__main__": print 'http://localhost:8888/knight/index.html' http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) reactor.listenTCP(3333, DALIFactory()) tornado.ioloop.IOLoop.instance().start()
open
identifier_name
other_eval.py
""" Provides the evaluator backends for Numexpr and the Python interpreter """ from expression_builder import Visitor import blaze import math def evaluate(expression, chunk_size, vm='python', out_flavor='blaze', user_dict={}, **kwargs): """ evaluate(expression, vm=None, out_flavor=None, chunk_size=None, user_dict=None, **kwargs) Evaluate an `expression` and return the result. Parameters ---------- expression : string A string forming an expression, like '2*a+3*b'. The values for 'a' and 'b' are variable names to be taken from the calling function's frame. These variables may be scalars, carrays or NumPy arrays. vm : string The virtual machine to be used in computations. It can be 'numexpr' or 'python'. The default is to use 'numexpr' if it is installed. chunk_size : size of the chunk for chunked evaluation. If None, use some heuristics to infer it. out_flavor : string The flavor for the `out` object. It can be 'Blaze' or 'numpy'. user_dict : dict An user-provided dictionary where the variables in expression can be found by name. kwargs : list of parameters or dictionary Any parameter supported by the carray constructor. Returns ------- out : Blaze object The outcome of the expression. You can tailor the properties of this Blaze array by passing additional arguments supported by carray constructor in `kwargs`. """ if vm not in ('numexpr', 'python'): raiseValue, "`vm` must be either 'numexpr' or 'python'" if out_flavor not in ('blaze', 'numpy'): raiseValue, "`out_flavor` must be either 'blaze' or 'numpy'" # Get variables and column names participating in expression vars = user_dict # Gather info about sizes and lengths typesize, vlen = 0, 1 for var in vars.itervalues(): if not hasattr(var, "datashape"): # scalar detection continue else: # blaze arrays shape, dtype = blaze.to_numpy(var.datashape) typesize += dtype.itemsize lvar = shape[0] if vlen > 1 and vlen != lvar: raise ValueError, "arrays must have the same length" vlen = lvar if typesize == 0: # All scalars if vm == "python": return eval(expression, vars) else: import numexpr return numexpr.evaluate(expression, local_dict=vars) return _eval_blocks(expression, chunk_size, vars, vlen, typesize, vm, out_flavor, **kwargs) def _ndims_var(a_var): if hasattr(a_var, 'datashape'): # a blaze array return len(a_var.datashape.shape) elif hasattr(a_var, 'shape'): # a numpy array return len(a_var.shape) elif hasattr(a_var, '__get_item__'): # neither a blaze nor a numpy array, but indexable: # assume just 1 dimension :-/ return 1 else: # not indexable: a scalar return 0 def _max_ndims_vars(a_dict_of_vars):
class _ResultGatherer(object): def __init__(self, vlen, maxndims, flavour): self.vlen = vlen self.flavour = flavour self.maxndims = maxndims self.accumulate = self._entry def _entry(self, chunk_result, curr_slice): self.scalar = False self.dim_reduction = False l = len(chunk_result.shape) if l < self.maxndims: self.accumulate = self._reduce self.result = (self._scalar_result if l == 0 else self._array_result) self._result = chunk_result else: if out_flavor == "blaze": self._result = blaze.array(chunk_result, **kwargs) self.accumulate = self._blaze_append self.result = self._array_result else: out_shape = list(res_block.shape) out_shape[0] = self.vlen self._result = np.empty(chunk_result, dtype=chunk_result.dtype) self._result[curr_slice] = chunk_result def _reduce(self, chunk_result, curr_slice): self._result += chunk_result def _blaze_append(self, chunk_result, curr_slice): self._result.append(chunk_result) def _np_append(self, chunk_result, slice_, curr_slice): self._result[slice_] = chunk_result def _array_result(self): return self._result def _scalar_result(self): return self._result[()] def _eval_blocks(expression, chunk_size, vars, vlen, typesize, vm, out_flavor, **kwargs): """Perform the evaluation in blocks.""" if vm == 'python': def eval_flavour(expr, vars_): return eval(expr, None, vars_) else: import numexpr def eval_flavour(expr, vars_): return numexpr.evaluate(expr, local_dict=vars_) # Get temporaries for vars maxndims = _max_ndims_vars(vars) vars_ = { name: var for name, var in vars.iteritems() if not hasattr(var, '__getitem__') } arrays = [ (name, var) for name, var in vars.iteritems() if hasattr(var, '__getitem__') ] result = _ResultGatherer(vlen, maxndims, out_flavor) offset = 0 while offset < vlen: # Get buffers for vars curr_slice = slice(offset, min(vlen, offset+chunk_size)) for name, array in arrays: vars_[name] = array[curr_slice] # Perform the evaluation for this block result.accumulate(eval_flavour(expression, vars_), curr_slice) offset = curr_slice.stop #for next iteration return result.result() # End of machinery for evaluating expressions via python or numexpr # --------------- class _ExpressionBuilder(Visitor): def accept_operation(self, node): str_lhs = self.accept(node.lhs) str_rhs = self.accept(node.rhs) if node.op == "dot": # Re-express dot product in terms of a product and an sum() return 'sum' + "(" + str_lhs + "*" + str_rhs + ")" else: return "(" + str_lhs + node.op + str_rhs + ')' def accept_terminal(self, node): return node.source # ================================================================ class NumexprEvaluator(object): """ Evaluates expressions using numexpr """ name = 'numexpr' def __init__(self, root_node, operands=None): assert(operands) self.str_expr = _ExpressionBuilder().accept(root_node) self.operands = operands def eval(self, chunk_size=None): chunk_size = (chunk_size if chunk_size is not None else self._infer_chunksize()) return evaluate(self.str_expr, chunk_size, vm='numexpr', user_dict=self.operands) def _infer_chunksize(self): typesize = _per_element_size(self.operands) vlen = _array_length(self.operands) bsize = 2**20 bsize //= typesize bsize = 2 ** (int(math.log(bsize,2))) if vlen < 100*1000: bsize //= 8 elif vlen < 1000*1000: bsize //= 4 elif vlen < 10*1000*1000: bsize //= 2 return bsize if bsize > 0 else 1 class NumpyEvaluator(object): name = 'python interpreter with numpy' def __init__(self, root_node, operands=None): assert(operands) self.str_expr = _ExpressionBuilder().accept(root_node) self.operands = operands def eval(self, chunk_size=None): chunk_size = (chunk_size if chunk_size is not None else self._infer_chunksize()) return evaluate(self.str_expr, chunk_size, vm='python', user_dict=self.operands) def _infer_chunksize(self): """this is somehow similar to the numexpr version, but the heuristics are slightly changed as there will be temporaries """ typesize = _per_element_size(self.operands) vlen = _array_length(self.operands) bsize = 2**17 bsize //= typesize bsize = 2 ** (int(math.log(bsize,2))) if vlen < 100*1000: bsize //= 8 elif vlen < 1000*1000: bsize //= 4 elif vlen < 10*1000*1000: bsize //= 2 return bsize if bsize > 0 else 1
return max([_ndims_var(var) for var in a_dict_of_vars.itervalues()])
identifier_body
other_eval.py
""" Provides the evaluator backends for Numexpr and the Python interpreter """ from expression_builder import Visitor import blaze import math def evaluate(expression, chunk_size, vm='python', out_flavor='blaze', user_dict={}, **kwargs): """ evaluate(expression, vm=None, out_flavor=None, chunk_size=None, user_dict=None, **kwargs) Evaluate an `expression` and return the result. Parameters ---------- expression : string A string forming an expression, like '2*a+3*b'. The values for 'a' and 'b' are variable names to be taken from the calling function's frame. These variables may be scalars, carrays or NumPy arrays. vm : string The virtual machine to be used in computations. It can be 'numexpr' or 'python'. The default is to use 'numexpr' if it is installed. chunk_size : size of the chunk for chunked evaluation. If None, use some heuristics to infer it. out_flavor : string The flavor for the `out` object. It can be 'Blaze' or 'numpy'. user_dict : dict An user-provided dictionary where the variables in expression can be found by name. kwargs : list of parameters or dictionary Any parameter supported by the carray constructor. Returns ------- out : Blaze object The outcome of the expression. You can tailor the properties of this Blaze array by passing additional arguments supported by carray constructor in `kwargs`. """ if vm not in ('numexpr', 'python'): raiseValue, "`vm` must be either 'numexpr' or 'python'" if out_flavor not in ('blaze', 'numpy'): raiseValue, "`out_flavor` must be either 'blaze' or 'numpy'" # Get variables and column names participating in expression vars = user_dict # Gather info about sizes and lengths typesize, vlen = 0, 1 for var in vars.itervalues(): if not hasattr(var, "datashape"): # scalar detection continue else: # blaze arrays shape, dtype = blaze.to_numpy(var.datashape) typesize += dtype.itemsize lvar = shape[0] if vlen > 1 and vlen != lvar: raise ValueError, "arrays must have the same length" vlen = lvar if typesize == 0: # All scalars if vm == "python": return eval(expression, vars) else: import numexpr return numexpr.evaluate(expression, local_dict=vars) return _eval_blocks(expression, chunk_size, vars, vlen, typesize, vm, out_flavor, **kwargs) def _ndims_var(a_var): if hasattr(a_var, 'datashape'): # a blaze array return len(a_var.datashape.shape) elif hasattr(a_var, 'shape'): # a numpy array return len(a_var.shape) elif hasattr(a_var, '__get_item__'): # neither a blaze nor a numpy array, but indexable: # assume just 1 dimension :-/ return 1 else: # not indexable: a scalar return 0 def _max_ndims_vars(a_dict_of_vars): return max([_ndims_var(var) for var in a_dict_of_vars.itervalues()]) class _ResultGatherer(object): def __init__(self, vlen, maxndims, flavour): self.vlen = vlen self.flavour = flavour self.maxndims = maxndims self.accumulate = self._entry def _entry(self, chunk_result, curr_slice): self.scalar = False self.dim_reduction = False l = len(chunk_result.shape) if l < self.maxndims: self.accumulate = self._reduce self.result = (self._scalar_result if l == 0 else self._array_result) self._result = chunk_result else: if out_flavor == "blaze": self._result = blaze.array(chunk_result, **kwargs) self.accumulate = self._blaze_append self.result = self._array_result else: out_shape = list(res_block.shape) out_shape[0] = self.vlen self._result = np.empty(chunk_result, dtype=chunk_result.dtype) self._result[curr_slice] = chunk_result def
(self, chunk_result, curr_slice): self._result += chunk_result def _blaze_append(self, chunk_result, curr_slice): self._result.append(chunk_result) def _np_append(self, chunk_result, slice_, curr_slice): self._result[slice_] = chunk_result def _array_result(self): return self._result def _scalar_result(self): return self._result[()] def _eval_blocks(expression, chunk_size, vars, vlen, typesize, vm, out_flavor, **kwargs): """Perform the evaluation in blocks.""" if vm == 'python': def eval_flavour(expr, vars_): return eval(expr, None, vars_) else: import numexpr def eval_flavour(expr, vars_): return numexpr.evaluate(expr, local_dict=vars_) # Get temporaries for vars maxndims = _max_ndims_vars(vars) vars_ = { name: var for name, var in vars.iteritems() if not hasattr(var, '__getitem__') } arrays = [ (name, var) for name, var in vars.iteritems() if hasattr(var, '__getitem__') ] result = _ResultGatherer(vlen, maxndims, out_flavor) offset = 0 while offset < vlen: # Get buffers for vars curr_slice = slice(offset, min(vlen, offset+chunk_size)) for name, array in arrays: vars_[name] = array[curr_slice] # Perform the evaluation for this block result.accumulate(eval_flavour(expression, vars_), curr_slice) offset = curr_slice.stop #for next iteration return result.result() # End of machinery for evaluating expressions via python or numexpr # --------------- class _ExpressionBuilder(Visitor): def accept_operation(self, node): str_lhs = self.accept(node.lhs) str_rhs = self.accept(node.rhs) if node.op == "dot": # Re-express dot product in terms of a product and an sum() return 'sum' + "(" + str_lhs + "*" + str_rhs + ")" else: return "(" + str_lhs + node.op + str_rhs + ')' def accept_terminal(self, node): return node.source # ================================================================ class NumexprEvaluator(object): """ Evaluates expressions using numexpr """ name = 'numexpr' def __init__(self, root_node, operands=None): assert(operands) self.str_expr = _ExpressionBuilder().accept(root_node) self.operands = operands def eval(self, chunk_size=None): chunk_size = (chunk_size if chunk_size is not None else self._infer_chunksize()) return evaluate(self.str_expr, chunk_size, vm='numexpr', user_dict=self.operands) def _infer_chunksize(self): typesize = _per_element_size(self.operands) vlen = _array_length(self.operands) bsize = 2**20 bsize //= typesize bsize = 2 ** (int(math.log(bsize,2))) if vlen < 100*1000: bsize //= 8 elif vlen < 1000*1000: bsize //= 4 elif vlen < 10*1000*1000: bsize //= 2 return bsize if bsize > 0 else 1 class NumpyEvaluator(object): name = 'python interpreter with numpy' def __init__(self, root_node, operands=None): assert(operands) self.str_expr = _ExpressionBuilder().accept(root_node) self.operands = operands def eval(self, chunk_size=None): chunk_size = (chunk_size if chunk_size is not None else self._infer_chunksize()) return evaluate(self.str_expr, chunk_size, vm='python', user_dict=self.operands) def _infer_chunksize(self): """this is somehow similar to the numexpr version, but the heuristics are slightly changed as there will be temporaries """ typesize = _per_element_size(self.operands) vlen = _array_length(self.operands) bsize = 2**17 bsize //= typesize bsize = 2 ** (int(math.log(bsize,2))) if vlen < 100*1000: bsize //= 8 elif vlen < 1000*1000: bsize //= 4 elif vlen < 10*1000*1000: bsize //= 2 return bsize if bsize > 0 else 1
_reduce
identifier_name
other_eval.py
""" Provides the evaluator backends for Numexpr and the Python interpreter """ from expression_builder import Visitor import blaze import math def evaluate(expression, chunk_size, vm='python', out_flavor='blaze', user_dict={}, **kwargs): """ evaluate(expression, vm=None, out_flavor=None, chunk_size=None, user_dict=None, **kwargs) Evaluate an `expression` and return the result. Parameters ---------- expression : string A string forming an expression, like '2*a+3*b'. The values for 'a' and 'b' are variable names to be taken from the calling function's frame. These variables may be scalars, carrays or NumPy arrays. vm : string The virtual machine to be used in computations. It can be 'numexpr' or 'python'. The default is to use 'numexpr' if it is installed. chunk_size : size of the chunk for chunked evaluation. If None, use some heuristics to infer it. out_flavor : string
user_dict : dict An user-provided dictionary where the variables in expression can be found by name. kwargs : list of parameters or dictionary Any parameter supported by the carray constructor. Returns ------- out : Blaze object The outcome of the expression. You can tailor the properties of this Blaze array by passing additional arguments supported by carray constructor in `kwargs`. """ if vm not in ('numexpr', 'python'): raiseValue, "`vm` must be either 'numexpr' or 'python'" if out_flavor not in ('blaze', 'numpy'): raiseValue, "`out_flavor` must be either 'blaze' or 'numpy'" # Get variables and column names participating in expression vars = user_dict # Gather info about sizes and lengths typesize, vlen = 0, 1 for var in vars.itervalues(): if not hasattr(var, "datashape"): # scalar detection continue else: # blaze arrays shape, dtype = blaze.to_numpy(var.datashape) typesize += dtype.itemsize lvar = shape[0] if vlen > 1 and vlen != lvar: raise ValueError, "arrays must have the same length" vlen = lvar if typesize == 0: # All scalars if vm == "python": return eval(expression, vars) else: import numexpr return numexpr.evaluate(expression, local_dict=vars) return _eval_blocks(expression, chunk_size, vars, vlen, typesize, vm, out_flavor, **kwargs) def _ndims_var(a_var): if hasattr(a_var, 'datashape'): # a blaze array return len(a_var.datashape.shape) elif hasattr(a_var, 'shape'): # a numpy array return len(a_var.shape) elif hasattr(a_var, '__get_item__'): # neither a blaze nor a numpy array, but indexable: # assume just 1 dimension :-/ return 1 else: # not indexable: a scalar return 0 def _max_ndims_vars(a_dict_of_vars): return max([_ndims_var(var) for var in a_dict_of_vars.itervalues()]) class _ResultGatherer(object): def __init__(self, vlen, maxndims, flavour): self.vlen = vlen self.flavour = flavour self.maxndims = maxndims self.accumulate = self._entry def _entry(self, chunk_result, curr_slice): self.scalar = False self.dim_reduction = False l = len(chunk_result.shape) if l < self.maxndims: self.accumulate = self._reduce self.result = (self._scalar_result if l == 0 else self._array_result) self._result = chunk_result else: if out_flavor == "blaze": self._result = blaze.array(chunk_result, **kwargs) self.accumulate = self._blaze_append self.result = self._array_result else: out_shape = list(res_block.shape) out_shape[0] = self.vlen self._result = np.empty(chunk_result, dtype=chunk_result.dtype) self._result[curr_slice] = chunk_result def _reduce(self, chunk_result, curr_slice): self._result += chunk_result def _blaze_append(self, chunk_result, curr_slice): self._result.append(chunk_result) def _np_append(self, chunk_result, slice_, curr_slice): self._result[slice_] = chunk_result def _array_result(self): return self._result def _scalar_result(self): return self._result[()] def _eval_blocks(expression, chunk_size, vars, vlen, typesize, vm, out_flavor, **kwargs): """Perform the evaluation in blocks.""" if vm == 'python': def eval_flavour(expr, vars_): return eval(expr, None, vars_) else: import numexpr def eval_flavour(expr, vars_): return numexpr.evaluate(expr, local_dict=vars_) # Get temporaries for vars maxndims = _max_ndims_vars(vars) vars_ = { name: var for name, var in vars.iteritems() if not hasattr(var, '__getitem__') } arrays = [ (name, var) for name, var in vars.iteritems() if hasattr(var, '__getitem__') ] result = _ResultGatherer(vlen, maxndims, out_flavor) offset = 0 while offset < vlen: # Get buffers for vars curr_slice = slice(offset, min(vlen, offset+chunk_size)) for name, array in arrays: vars_[name] = array[curr_slice] # Perform the evaluation for this block result.accumulate(eval_flavour(expression, vars_), curr_slice) offset = curr_slice.stop #for next iteration return result.result() # End of machinery for evaluating expressions via python or numexpr # --------------- class _ExpressionBuilder(Visitor): def accept_operation(self, node): str_lhs = self.accept(node.lhs) str_rhs = self.accept(node.rhs) if node.op == "dot": # Re-express dot product in terms of a product and an sum() return 'sum' + "(" + str_lhs + "*" + str_rhs + ")" else: return "(" + str_lhs + node.op + str_rhs + ')' def accept_terminal(self, node): return node.source # ================================================================ class NumexprEvaluator(object): """ Evaluates expressions using numexpr """ name = 'numexpr' def __init__(self, root_node, operands=None): assert(operands) self.str_expr = _ExpressionBuilder().accept(root_node) self.operands = operands def eval(self, chunk_size=None): chunk_size = (chunk_size if chunk_size is not None else self._infer_chunksize()) return evaluate(self.str_expr, chunk_size, vm='numexpr', user_dict=self.operands) def _infer_chunksize(self): typesize = _per_element_size(self.operands) vlen = _array_length(self.operands) bsize = 2**20 bsize //= typesize bsize = 2 ** (int(math.log(bsize,2))) if vlen < 100*1000: bsize //= 8 elif vlen < 1000*1000: bsize //= 4 elif vlen < 10*1000*1000: bsize //= 2 return bsize if bsize > 0 else 1 class NumpyEvaluator(object): name = 'python interpreter with numpy' def __init__(self, root_node, operands=None): assert(operands) self.str_expr = _ExpressionBuilder().accept(root_node) self.operands = operands def eval(self, chunk_size=None): chunk_size = (chunk_size if chunk_size is not None else self._infer_chunksize()) return evaluate(self.str_expr, chunk_size, vm='python', user_dict=self.operands) def _infer_chunksize(self): """this is somehow similar to the numexpr version, but the heuristics are slightly changed as there will be temporaries """ typesize = _per_element_size(self.operands) vlen = _array_length(self.operands) bsize = 2**17 bsize //= typesize bsize = 2 ** (int(math.log(bsize,2))) if vlen < 100*1000: bsize //= 8 elif vlen < 1000*1000: bsize //= 4 elif vlen < 10*1000*1000: bsize //= 2 return bsize if bsize > 0 else 1
The flavor for the `out` object. It can be 'Blaze' or 'numpy'.
random_line_split
other_eval.py
""" Provides the evaluator backends for Numexpr and the Python interpreter """ from expression_builder import Visitor import blaze import math def evaluate(expression, chunk_size, vm='python', out_flavor='blaze', user_dict={}, **kwargs): """ evaluate(expression, vm=None, out_flavor=None, chunk_size=None, user_dict=None, **kwargs) Evaluate an `expression` and return the result. Parameters ---------- expression : string A string forming an expression, like '2*a+3*b'. The values for 'a' and 'b' are variable names to be taken from the calling function's frame. These variables may be scalars, carrays or NumPy arrays. vm : string The virtual machine to be used in computations. It can be 'numexpr' or 'python'. The default is to use 'numexpr' if it is installed. chunk_size : size of the chunk for chunked evaluation. If None, use some heuristics to infer it. out_flavor : string The flavor for the `out` object. It can be 'Blaze' or 'numpy'. user_dict : dict An user-provided dictionary where the variables in expression can be found by name. kwargs : list of parameters or dictionary Any parameter supported by the carray constructor. Returns ------- out : Blaze object The outcome of the expression. You can tailor the properties of this Blaze array by passing additional arguments supported by carray constructor in `kwargs`. """ if vm not in ('numexpr', 'python'): raiseValue, "`vm` must be either 'numexpr' or 'python'" if out_flavor not in ('blaze', 'numpy'): raiseValue, "`out_flavor` must be either 'blaze' or 'numpy'" # Get variables and column names participating in expression vars = user_dict # Gather info about sizes and lengths typesize, vlen = 0, 1 for var in vars.itervalues(): if not hasattr(var, "datashape"): # scalar detection continue else: # blaze arrays shape, dtype = blaze.to_numpy(var.datashape) typesize += dtype.itemsize lvar = shape[0] if vlen > 1 and vlen != lvar: raise ValueError, "arrays must have the same length" vlen = lvar if typesize == 0: # All scalars if vm == "python": return eval(expression, vars) else: import numexpr return numexpr.evaluate(expression, local_dict=vars) return _eval_blocks(expression, chunk_size, vars, vlen, typesize, vm, out_flavor, **kwargs) def _ndims_var(a_var): if hasattr(a_var, 'datashape'): # a blaze array return len(a_var.datashape.shape) elif hasattr(a_var, 'shape'): # a numpy array return len(a_var.shape) elif hasattr(a_var, '__get_item__'): # neither a blaze nor a numpy array, but indexable: # assume just 1 dimension :-/ return 1 else: # not indexable: a scalar return 0 def _max_ndims_vars(a_dict_of_vars): return max([_ndims_var(var) for var in a_dict_of_vars.itervalues()]) class _ResultGatherer(object): def __init__(self, vlen, maxndims, flavour): self.vlen = vlen self.flavour = flavour self.maxndims = maxndims self.accumulate = self._entry def _entry(self, chunk_result, curr_slice): self.scalar = False self.dim_reduction = False l = len(chunk_result.shape) if l < self.maxndims: self.accumulate = self._reduce self.result = (self._scalar_result if l == 0 else self._array_result) self._result = chunk_result else: if out_flavor == "blaze": self._result = blaze.array(chunk_result, **kwargs) self.accumulate = self._blaze_append self.result = self._array_result else: out_shape = list(res_block.shape) out_shape[0] = self.vlen self._result = np.empty(chunk_result, dtype=chunk_result.dtype) self._result[curr_slice] = chunk_result def _reduce(self, chunk_result, curr_slice): self._result += chunk_result def _blaze_append(self, chunk_result, curr_slice): self._result.append(chunk_result) def _np_append(self, chunk_result, slice_, curr_slice): self._result[slice_] = chunk_result def _array_result(self): return self._result def _scalar_result(self): return self._result[()] def _eval_blocks(expression, chunk_size, vars, vlen, typesize, vm, out_flavor, **kwargs): """Perform the evaluation in blocks.""" if vm == 'python': def eval_flavour(expr, vars_): return eval(expr, None, vars_) else: import numexpr def eval_flavour(expr, vars_): return numexpr.evaluate(expr, local_dict=vars_) # Get temporaries for vars maxndims = _max_ndims_vars(vars) vars_ = { name: var for name, var in vars.iteritems() if not hasattr(var, '__getitem__') } arrays = [ (name, var) for name, var in vars.iteritems() if hasattr(var, '__getitem__') ] result = _ResultGatherer(vlen, maxndims, out_flavor) offset = 0 while offset < vlen: # Get buffers for vars curr_slice = slice(offset, min(vlen, offset+chunk_size)) for name, array in arrays: vars_[name] = array[curr_slice] # Perform the evaluation for this block result.accumulate(eval_flavour(expression, vars_), curr_slice) offset = curr_slice.stop #for next iteration return result.result() # End of machinery for evaluating expressions via python or numexpr # --------------- class _ExpressionBuilder(Visitor): def accept_operation(self, node): str_lhs = self.accept(node.lhs) str_rhs = self.accept(node.rhs) if node.op == "dot": # Re-express dot product in terms of a product and an sum() return 'sum' + "(" + str_lhs + "*" + str_rhs + ")" else: return "(" + str_lhs + node.op + str_rhs + ')' def accept_terminal(self, node): return node.source # ================================================================ class NumexprEvaluator(object): """ Evaluates expressions using numexpr """ name = 'numexpr' def __init__(self, root_node, operands=None): assert(operands) self.str_expr = _ExpressionBuilder().accept(root_node) self.operands = operands def eval(self, chunk_size=None): chunk_size = (chunk_size if chunk_size is not None else self._infer_chunksize()) return evaluate(self.str_expr, chunk_size, vm='numexpr', user_dict=self.operands) def _infer_chunksize(self): typesize = _per_element_size(self.operands) vlen = _array_length(self.operands) bsize = 2**20 bsize //= typesize bsize = 2 ** (int(math.log(bsize,2))) if vlen < 100*1000: bsize //= 8 elif vlen < 1000*1000:
elif vlen < 10*1000*1000: bsize //= 2 return bsize if bsize > 0 else 1 class NumpyEvaluator(object): name = 'python interpreter with numpy' def __init__(self, root_node, operands=None): assert(operands) self.str_expr = _ExpressionBuilder().accept(root_node) self.operands = operands def eval(self, chunk_size=None): chunk_size = (chunk_size if chunk_size is not None else self._infer_chunksize()) return evaluate(self.str_expr, chunk_size, vm='python', user_dict=self.operands) def _infer_chunksize(self): """this is somehow similar to the numexpr version, but the heuristics are slightly changed as there will be temporaries """ typesize = _per_element_size(self.operands) vlen = _array_length(self.operands) bsize = 2**17 bsize //= typesize bsize = 2 ** (int(math.log(bsize,2))) if vlen < 100*1000: bsize //= 8 elif vlen < 1000*1000: bsize //= 4 elif vlen < 10*1000*1000: bsize //= 2 return bsize if bsize > 0 else 1
bsize //= 4
conditional_block
crc32.rs
//! Helper module to compute a CRC32 checksum use std::io; use std::io::prelude::*; static CRC32_TABLE : [u32; 256] = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d ]; /// Update the checksum prev based upon the contents of buf. pub fn update(prev: u32, buf: &[u8]) -> u32 { let mut crc = !prev; for &byte in buf.iter() { crc = CRC32_TABLE[((crc as u8) ^ byte) as usize] ^ (crc >> 8); } !crc } /// Reader that validates the CRC32 when it reaches the EOF. pub struct Crc32Reader<R> { inner: R, crc: u32, check: u32, } impl<R> Crc32Reader<R> { /// Get a new Crc32Reader which check the inner reader against checksum. pub fn new(inner: R, checksum: u32) -> Crc32Reader<R> { Crc32Reader { inner: inner, crc: 0, check: checksum, } } fn check_matches(&self) -> bool { self.check == self.crc } } impl<R: Read> Read for Crc32Reader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let count = match self.inner.read(buf) { Ok(0) if !self.check_matches() => { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) }, Ok(n) => n, Err(e) => return Err(e), }; self.crc = update(self.crc, &buf[0..count]); Ok(count) } } #[cfg(test)] mod test { #[test] fn samples() { assert_eq!(super::update(0, b""), 0); // test vectors from the iPXE project (input and output are bitwise negated) assert_eq!(super::update(!0x12345678, b""), !0x12345678); assert_eq!(super::update(!0xffffffff, b"hello world"), !0xf2b5ee7a); assert_eq!(super::update(!0xffffffff, b"hello"), !0xc9ef5979); assert_eq!(super::update(!0xc9ef5979, b" world"), !0xf2b5ee7a); // Some vectors found on Rosetta code assert_eq!(super::update(0, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 0x190A55AD); assert_eq!(super::update(0, b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), 0xFF6CAB0B); assert_eq!(super::update(0, b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"), 0x91267E8A); } }
random_line_split
crc32.rs
//! Helper module to compute a CRC32 checksum use std::io; use std::io::prelude::*; static CRC32_TABLE : [u32; 256] = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d ]; /// Update the checksum prev based upon the contents of buf. pub fn update(prev: u32, buf: &[u8]) -> u32
/// Reader that validates the CRC32 when it reaches the EOF. pub struct Crc32Reader<R> { inner: R, crc: u32, check: u32, } impl<R> Crc32Reader<R> { /// Get a new Crc32Reader which check the inner reader against checksum. pub fn new(inner: R, checksum: u32) -> Crc32Reader<R> { Crc32Reader { inner: inner, crc: 0, check: checksum, } } fn check_matches(&self) -> bool { self.check == self.crc } } impl<R: Read> Read for Crc32Reader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let count = match self.inner.read(buf) { Ok(0) if !self.check_matches() => { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) }, Ok(n) => n, Err(e) => return Err(e), }; self.crc = update(self.crc, &buf[0..count]); Ok(count) } } #[cfg(test)] mod test { #[test] fn samples() { assert_eq!(super::update(0, b""), 0); // test vectors from the iPXE project (input and output are bitwise negated) assert_eq!(super::update(!0x12345678, b""), !0x12345678); assert_eq!(super::update(!0xffffffff, b"hello world"), !0xf2b5ee7a); assert_eq!(super::update(!0xffffffff, b"hello"), !0xc9ef5979); assert_eq!(super::update(!0xc9ef5979, b" world"), !0xf2b5ee7a); // Some vectors found on Rosetta code assert_eq!(super::update(0, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 0x190A55AD); assert_eq!(super::update(0, b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), 0xFF6CAB0B); assert_eq!(super::update(0, b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"), 0x91267E8A); } }
{ let mut crc = !prev; for &byte in buf.iter() { crc = CRC32_TABLE[((crc as u8) ^ byte) as usize] ^ (crc >> 8); } !crc }
identifier_body
crc32.rs
//! Helper module to compute a CRC32 checksum use std::io; use std::io::prelude::*; static CRC32_TABLE : [u32; 256] = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d ]; /// Update the checksum prev based upon the contents of buf. pub fn
(prev: u32, buf: &[u8]) -> u32 { let mut crc = !prev; for &byte in buf.iter() { crc = CRC32_TABLE[((crc as u8) ^ byte) as usize] ^ (crc >> 8); } !crc } /// Reader that validates the CRC32 when it reaches the EOF. pub struct Crc32Reader<R> { inner: R, crc: u32, check: u32, } impl<R> Crc32Reader<R> { /// Get a new Crc32Reader which check the inner reader against checksum. pub fn new(inner: R, checksum: u32) -> Crc32Reader<R> { Crc32Reader { inner: inner, crc: 0, check: checksum, } } fn check_matches(&self) -> bool { self.check == self.crc } } impl<R: Read> Read for Crc32Reader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let count = match self.inner.read(buf) { Ok(0) if !self.check_matches() => { return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) }, Ok(n) => n, Err(e) => return Err(e), }; self.crc = update(self.crc, &buf[0..count]); Ok(count) } } #[cfg(test)] mod test { #[test] fn samples() { assert_eq!(super::update(0, b""), 0); // test vectors from the iPXE project (input and output are bitwise negated) assert_eq!(super::update(!0x12345678, b""), !0x12345678); assert_eq!(super::update(!0xffffffff, b"hello world"), !0xf2b5ee7a); assert_eq!(super::update(!0xffffffff, b"hello"), !0xc9ef5979); assert_eq!(super::update(!0xc9ef5979, b" world"), !0xf2b5ee7a); // Some vectors found on Rosetta code assert_eq!(super::update(0, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 0x190A55AD); assert_eq!(super::update(0, b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), 0xFF6CAB0B); assert_eq!(super::update(0, b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"), 0x91267E8A); } }
update
identifier_name
crc32.rs
//! Helper module to compute a CRC32 checksum use std::io; use std::io::prelude::*; static CRC32_TABLE : [u32; 256] = [ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d ]; /// Update the checksum prev based upon the contents of buf. pub fn update(prev: u32, buf: &[u8]) -> u32 { let mut crc = !prev; for &byte in buf.iter() { crc = CRC32_TABLE[((crc as u8) ^ byte) as usize] ^ (crc >> 8); } !crc } /// Reader that validates the CRC32 when it reaches the EOF. pub struct Crc32Reader<R> { inner: R, crc: u32, check: u32, } impl<R> Crc32Reader<R> { /// Get a new Crc32Reader which check the inner reader against checksum. pub fn new(inner: R, checksum: u32) -> Crc32Reader<R> { Crc32Reader { inner: inner, crc: 0, check: checksum, } } fn check_matches(&self) -> bool { self.check == self.crc } } impl<R: Read> Read for Crc32Reader<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let count = match self.inner.read(buf) { Ok(0) if !self.check_matches() =>
, Ok(n) => n, Err(e) => return Err(e), }; self.crc = update(self.crc, &buf[0..count]); Ok(count) } } #[cfg(test)] mod test { #[test] fn samples() { assert_eq!(super::update(0, b""), 0); // test vectors from the iPXE project (input and output are bitwise negated) assert_eq!(super::update(!0x12345678, b""), !0x12345678); assert_eq!(super::update(!0xffffffff, b"hello world"), !0xf2b5ee7a); assert_eq!(super::update(!0xffffffff, b"hello"), !0xc9ef5979); assert_eq!(super::update(!0xc9ef5979, b" world"), !0xf2b5ee7a); // Some vectors found on Rosetta code assert_eq!(super::update(0, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 0x190A55AD); assert_eq!(super::update(0, b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"), 0xFF6CAB0B); assert_eq!(super::update(0, b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"), 0x91267E8A); } }
{ return Err(io::Error::new(io::ErrorKind::Other, "Invalid checksum")) }
conditional_block
Effects.js
import { UrlUtil } from './UrlUtil' export class Effects { constructor () { this.bindHighlight() } // if a var highlight exists in the url it will be highlighted bindHighlight () { // get highlight from url const highlightId = UrlUtil.getGetValue('highlight') // id is set if (highlightId !== '') { // init selector of the element we want to highlight let selector = '#' + highlightId // item exists if ($(selector).length > 0) { // if its a table row we need to highlight all cells in that row if ($(selector)[0].tagName.toLowerCase() === 'tr')
// when we hover over the item we stop the effect, otherwise we will mess up background hover styles $(selector).on('mouseover', () => { $(selector).removeClass('highlighted') }) // highlight! $(selector).addClass('highlighted') setTimeout(() => { $(selector).removeClass('highlighted') }, 5000) } } } }
{ selector += ' td' }
conditional_block
Effects.js
import { UrlUtil } from './UrlUtil' export class Effects { constructor () { this.bindHighlight() } // if a var highlight exists in the url it will be highlighted bindHighlight () { // get highlight from url const highlightId = UrlUtil.getGetValue('highlight') // id is set if (highlightId !== '') { // init selector of the element we want to highlight let selector = '#' + highlightId // item exists if ($(selector).length > 0) { // if its a table row we need to highlight all cells in that row if ($(selector)[0].tagName.toLowerCase() === 'tr') { selector += ' td' } // when we hover over the item we stop the effect, otherwise we will mess up background hover styles $(selector).on('mouseover', () => { $(selector).removeClass('highlighted') }) // highlight! $(selector).addClass('highlighted') setTimeout(() => { $(selector).removeClass('highlighted')
}
}, 5000) } } }
random_line_split
Effects.js
import { UrlUtil } from './UrlUtil' export class Effects { constructor ()
// if a var highlight exists in the url it will be highlighted bindHighlight () { // get highlight from url const highlightId = UrlUtil.getGetValue('highlight') // id is set if (highlightId !== '') { // init selector of the element we want to highlight let selector = '#' + highlightId // item exists if ($(selector).length > 0) { // if its a table row we need to highlight all cells in that row if ($(selector)[0].tagName.toLowerCase() === 'tr') { selector += ' td' } // when we hover over the item we stop the effect, otherwise we will mess up background hover styles $(selector).on('mouseover', () => { $(selector).removeClass('highlighted') }) // highlight! $(selector).addClass('highlighted') setTimeout(() => { $(selector).removeClass('highlighted') }, 5000) } } } }
{ this.bindHighlight() }
identifier_body
Effects.js
import { UrlUtil } from './UrlUtil' export class
{ constructor () { this.bindHighlight() } // if a var highlight exists in the url it will be highlighted bindHighlight () { // get highlight from url const highlightId = UrlUtil.getGetValue('highlight') // id is set if (highlightId !== '') { // init selector of the element we want to highlight let selector = '#' + highlightId // item exists if ($(selector).length > 0) { // if its a table row we need to highlight all cells in that row if ($(selector)[0].tagName.toLowerCase() === 'tr') { selector += ' td' } // when we hover over the item we stop the effect, otherwise we will mess up background hover styles $(selector).on('mouseover', () => { $(selector).removeClass('highlighted') }) // highlight! $(selector).addClass('highlighted') setTimeout(() => { $(selector).removeClass('highlighted') }, 5000) } } } }
Effects
identifier_name
types.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. /// MethodCall denotes a specific request to be carried out by routing. #[derive(Clone, PartialEq, Eq, Debug)] pub enum MethodCall { /// request to have `location` to handle put for the `content` Put {
}, /// request to retreive data with specified type and location from network Get { location: ::routing::authority::Authority, data_request: ::routing::data::DataRequest, }, // /// request to post // Post { destination: ::routing::NameType, content: Data }, // /// Request delete // Delete { name: ::routing::NameType, data : Data }, /// request to refresh Refresh { type_tag: u64, our_authority: ::routing::Authority, payload: Vec<u8>, }, /// reply Reply { data: ::routing::data::Data, }, /// response error indicating failed in putting data FailedPut { location: ::routing::authority::Authority, data: ::routing::data::Data, }, /// response error indicating clearing sarificial data ClearSacrificial { location: ::routing::authority::Authority, name: ::routing::NameType, size: u32, }, /// response error indicating not enough allowance LowBalance{ location: ::routing::authority::Authority, data: ::routing::data::Data, balance: u32}, /// response error indicating invalid request InvalidRequest { data: ::routing::data::Data, }, } /// This trait is required for any type (normally an account) which is refreshed on a churn event. pub trait Refreshable : ::rustc_serialize::Encodable + ::rustc_serialize::Decodable { /// The serialised contents fn serialised_contents(&self) -> Vec<u8> { ::routing::utils::encode(&self).unwrap_or(vec![]) } /// Merge multiple refreshable objects into one fn merge(from_group: ::routing::NameType, responses: Vec<Self>) -> Option<Self>; }
location: ::routing::authority::Authority, content: ::routing::data::Data,
random_line_split
types.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. /// MethodCall denotes a specific request to be carried out by routing. #[derive(Clone, PartialEq, Eq, Debug)] pub enum MethodCall { /// request to have `location` to handle put for the `content` Put { location: ::routing::authority::Authority, content: ::routing::data::Data, }, /// request to retreive data with specified type and location from network Get { location: ::routing::authority::Authority, data_request: ::routing::data::DataRequest, }, // /// request to post // Post { destination: ::routing::NameType, content: Data }, // /// Request delete // Delete { name: ::routing::NameType, data : Data }, /// request to refresh Refresh { type_tag: u64, our_authority: ::routing::Authority, payload: Vec<u8>, }, /// reply Reply { data: ::routing::data::Data, }, /// response error indicating failed in putting data FailedPut { location: ::routing::authority::Authority, data: ::routing::data::Data, }, /// response error indicating clearing sarificial data ClearSacrificial { location: ::routing::authority::Authority, name: ::routing::NameType, size: u32, }, /// response error indicating not enough allowance LowBalance{ location: ::routing::authority::Authority, data: ::routing::data::Data, balance: u32}, /// response error indicating invalid request InvalidRequest { data: ::routing::data::Data, }, } /// This trait is required for any type (normally an account) which is refreshed on a churn event. pub trait Refreshable : ::rustc_serialize::Encodable + ::rustc_serialize::Decodable { /// The serialised contents fn serialised_contents(&self) -> Vec<u8>
/// Merge multiple refreshable objects into one fn merge(from_group: ::routing::NameType, responses: Vec<Self>) -> Option<Self>; }
{ ::routing::utils::encode(&self).unwrap_or(vec![]) }
identifier_body
types.rs
// Copyright 2015 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By contributing code to the SAFE Network Software, or to this project generally, you agree to be // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. // // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. // // Please review the Licences for the specific language governing permissions and limitations // relating to use of the SAFE Network Software. /// MethodCall denotes a specific request to be carried out by routing. #[derive(Clone, PartialEq, Eq, Debug)] pub enum MethodCall { /// request to have `location` to handle put for the `content` Put { location: ::routing::authority::Authority, content: ::routing::data::Data, }, /// request to retreive data with specified type and location from network Get { location: ::routing::authority::Authority, data_request: ::routing::data::DataRequest, }, // /// request to post // Post { destination: ::routing::NameType, content: Data }, // /// Request delete // Delete { name: ::routing::NameType, data : Data }, /// request to refresh Refresh { type_tag: u64, our_authority: ::routing::Authority, payload: Vec<u8>, }, /// reply Reply { data: ::routing::data::Data, }, /// response error indicating failed in putting data FailedPut { location: ::routing::authority::Authority, data: ::routing::data::Data, }, /// response error indicating clearing sarificial data ClearSacrificial { location: ::routing::authority::Authority, name: ::routing::NameType, size: u32, }, /// response error indicating not enough allowance LowBalance{ location: ::routing::authority::Authority, data: ::routing::data::Data, balance: u32}, /// response error indicating invalid request InvalidRequest { data: ::routing::data::Data, }, } /// This trait is required for any type (normally an account) which is refreshed on a churn event. pub trait Refreshable : ::rustc_serialize::Encodable + ::rustc_serialize::Decodable { /// The serialised contents fn
(&self) -> Vec<u8> { ::routing::utils::encode(&self).unwrap_or(vec![]) } /// Merge multiple refreshable objects into one fn merge(from_group: ::routing::NameType, responses: Vec<Self>) -> Option<Self>; }
serialised_contents
identifier_name
worker.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.six.moves import queue import json import multiprocessing import os import signal import sys import time import traceback import zlib from jinja2.exceptions import TemplateNotFound # TODO: not needed if we use the cryptography library with its default RNG # engine HAS_ATFORK=True try: from Crypto.Random import atfork except ImportError: HAS_ATFORK=False from ansible.errors import AnsibleError, AnsibleConnectionFailure from ansible.executor.task_executor import TaskExecutor from ansible.executor.task_result import TaskResult from ansible.playbook.handler import Handler from ansible.playbook.task import Task from ansible.vars.unsafe_proxy import AnsibleJSONUnsafeDecoder from ansible.utils.unicode import to_unicode try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() __all__ = ['WorkerProcess'] class WorkerProcess(multiprocessing.Process):
''' The worker thread class, which uses TaskExecutor to run tasks read from a job queue and pushes results into a results queue for reading later. ''' def __init__(self, rslt_q, task_vars, host, task, play_context, loader, variable_manager, shared_loader_obj): super(WorkerProcess, self).__init__() # takes a task queue manager as the sole param: self._rslt_q = rslt_q self._task_vars = task_vars self._host = host self._task = task self._play_context = play_context self._loader = loader self._variable_manager = variable_manager self._shared_loader_obj = shared_loader_obj # dupe stdin, if we have one self._new_stdin = sys.stdin try: fileno = sys.stdin.fileno() if fileno is not None: try: self._new_stdin = os.fdopen(os.dup(fileno)) except OSError: # couldn't dupe stdin, most likely because it's # not a valid file descriptor, so we just rely on # using the one that was passed in pass except ValueError: # couldn't get stdin's fileno, so we just carry on pass def run(self): ''' Called when the process is started. Pushes the result onto the results queue. We also remove the host from the blocked hosts list, to signify that they are ready for their next task. ''' #import cProfile, pstats, StringIO #pr = cProfile.Profile() #pr.enable() if HAS_ATFORK: atfork() try: # execute the task and build a TaskResult from the result display.debug("running TaskExecutor() for %s/%s" % (self._host, self._task)) executor_result = TaskExecutor( self._host, self._task, self._task_vars, self._play_context, self._new_stdin, self._loader, self._shared_loader_obj, self._rslt_q ).run() display.debug("done running TaskExecutor() for %s/%s" % (self._host, self._task)) self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, executor_result) # put the result on the result queue display.debug("sending task result") self._rslt_q.put(task_result) display.debug("done sending task result") except AnsibleConnectionFailure: self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, dict(unreachable=True)) self._rslt_q.put(task_result, block=False) except Exception as e: if not isinstance(e, (IOError, EOFError, KeyboardInterrupt, SystemExit)) or isinstance(e, TemplateNotFound): try: self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, dict(failed=True, exception=to_unicode(traceback.format_exc()), stdout='')) self._rslt_q.put(task_result, block=False) except: display.debug(u"WORKER EXCEPTION: %s" % to_unicode(e)) display.debug(u"WORKER TRACEBACK: %s" % to_unicode(traceback.format_exc())) display.debug("WORKER PROCESS EXITING") #pr.disable() #s = StringIO.StringIO() #sortby = 'time' #ps = pstats.Stats(pr, stream=s).sort_stats(sortby) #ps.print_stats() #with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue())
identifier_body
worker.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.six.moves import queue import json import multiprocessing import os import signal import sys import time import traceback import zlib from jinja2.exceptions import TemplateNotFound # TODO: not needed if we use the cryptography library with its default RNG # engine HAS_ATFORK=True try: from Crypto.Random import atfork except ImportError: HAS_ATFORK=False from ansible.errors import AnsibleError, AnsibleConnectionFailure from ansible.executor.task_executor import TaskExecutor from ansible.executor.task_result import TaskResult from ansible.playbook.handler import Handler from ansible.playbook.task import Task from ansible.vars.unsafe_proxy import AnsibleJSONUnsafeDecoder from ansible.utils.unicode import to_unicode try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() __all__ = ['WorkerProcess'] class WorkerProcess(multiprocessing.Process): ''' The worker thread class, which uses TaskExecutor to run tasks read from a job queue and pushes results into a results queue for reading later. ''' def __init__(self, rslt_q, task_vars, host, task, play_context, loader, variable_manager, shared_loader_obj): super(WorkerProcess, self).__init__() # takes a task queue manager as the sole param: self._rslt_q = rslt_q self._task_vars = task_vars self._host = host self._task = task self._play_context = play_context self._loader = loader self._variable_manager = variable_manager self._shared_loader_obj = shared_loader_obj # dupe stdin, if we have one self._new_stdin = sys.stdin try: fileno = sys.stdin.fileno() if fileno is not None: try: self._new_stdin = os.fdopen(os.dup(fileno)) except OSError: # couldn't dupe stdin, most likely because it's # not a valid file descriptor, so we just rely on # using the one that was passed in pass except ValueError: # couldn't get stdin's fileno, so we just carry on pass def run(self): ''' Called when the process is started. Pushes the result onto the results queue. We also remove the host from the blocked hosts list, to signify that they are ready for their next task. ''' #import cProfile, pstats, StringIO #pr = cProfile.Profile() #pr.enable() if HAS_ATFORK: atfork() try: # execute the task and build a TaskResult from the result display.debug("running TaskExecutor() for %s/%s" % (self._host, self._task)) executor_result = TaskExecutor( self._host, self._task, self._task_vars, self._play_context, self._new_stdin, self._loader, self._shared_loader_obj, self._rslt_q ).run() display.debug("done running TaskExecutor() for %s/%s" % (self._host, self._task)) self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, executor_result)
# put the result on the result queue display.debug("sending task result") self._rslt_q.put(task_result) display.debug("done sending task result") except AnsibleConnectionFailure: self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, dict(unreachable=True)) self._rslt_q.put(task_result, block=False) except Exception as e: if not isinstance(e, (IOError, EOFError, KeyboardInterrupt, SystemExit)) or isinstance(e, TemplateNotFound): try: self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, dict(failed=True, exception=to_unicode(traceback.format_exc()), stdout='')) self._rslt_q.put(task_result, block=False) except: display.debug(u"WORKER EXCEPTION: %s" % to_unicode(e)) display.debug(u"WORKER TRACEBACK: %s" % to_unicode(traceback.format_exc())) display.debug("WORKER PROCESS EXITING") #pr.disable() #s = StringIO.StringIO() #sortby = 'time' #ps = pstats.Stats(pr, stream=s).sort_stats(sortby) #ps.print_stats() #with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue())
random_line_split
worker.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.six.moves import queue import json import multiprocessing import os import signal import sys import time import traceback import zlib from jinja2.exceptions import TemplateNotFound # TODO: not needed if we use the cryptography library with its default RNG # engine HAS_ATFORK=True try: from Crypto.Random import atfork except ImportError: HAS_ATFORK=False from ansible.errors import AnsibleError, AnsibleConnectionFailure from ansible.executor.task_executor import TaskExecutor from ansible.executor.task_result import TaskResult from ansible.playbook.handler import Handler from ansible.playbook.task import Task from ansible.vars.unsafe_proxy import AnsibleJSONUnsafeDecoder from ansible.utils.unicode import to_unicode try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() __all__ = ['WorkerProcess'] class WorkerProcess(multiprocessing.Process): ''' The worker thread class, which uses TaskExecutor to run tasks read from a job queue and pushes results into a results queue for reading later. ''' def
(self, rslt_q, task_vars, host, task, play_context, loader, variable_manager, shared_loader_obj): super(WorkerProcess, self).__init__() # takes a task queue manager as the sole param: self._rslt_q = rslt_q self._task_vars = task_vars self._host = host self._task = task self._play_context = play_context self._loader = loader self._variable_manager = variable_manager self._shared_loader_obj = shared_loader_obj # dupe stdin, if we have one self._new_stdin = sys.stdin try: fileno = sys.stdin.fileno() if fileno is not None: try: self._new_stdin = os.fdopen(os.dup(fileno)) except OSError: # couldn't dupe stdin, most likely because it's # not a valid file descriptor, so we just rely on # using the one that was passed in pass except ValueError: # couldn't get stdin's fileno, so we just carry on pass def run(self): ''' Called when the process is started. Pushes the result onto the results queue. We also remove the host from the blocked hosts list, to signify that they are ready for their next task. ''' #import cProfile, pstats, StringIO #pr = cProfile.Profile() #pr.enable() if HAS_ATFORK: atfork() try: # execute the task and build a TaskResult from the result display.debug("running TaskExecutor() for %s/%s" % (self._host, self._task)) executor_result = TaskExecutor( self._host, self._task, self._task_vars, self._play_context, self._new_stdin, self._loader, self._shared_loader_obj, self._rslt_q ).run() display.debug("done running TaskExecutor() for %s/%s" % (self._host, self._task)) self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, executor_result) # put the result on the result queue display.debug("sending task result") self._rslt_q.put(task_result) display.debug("done sending task result") except AnsibleConnectionFailure: self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, dict(unreachable=True)) self._rslt_q.put(task_result, block=False) except Exception as e: if not isinstance(e, (IOError, EOFError, KeyboardInterrupt, SystemExit)) or isinstance(e, TemplateNotFound): try: self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, dict(failed=True, exception=to_unicode(traceback.format_exc()), stdout='')) self._rslt_q.put(task_result, block=False) except: display.debug(u"WORKER EXCEPTION: %s" % to_unicode(e)) display.debug(u"WORKER TRACEBACK: %s" % to_unicode(traceback.format_exc())) display.debug("WORKER PROCESS EXITING") #pr.disable() #s = StringIO.StringIO() #sortby = 'time' #ps = pstats.Stats(pr, stream=s).sort_stats(sortby) #ps.print_stats() #with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue())
__init__
identifier_name
worker.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.six.moves import queue import json import multiprocessing import os import signal import sys import time import traceback import zlib from jinja2.exceptions import TemplateNotFound # TODO: not needed if we use the cryptography library with its default RNG # engine HAS_ATFORK=True try: from Crypto.Random import atfork except ImportError: HAS_ATFORK=False from ansible.errors import AnsibleError, AnsibleConnectionFailure from ansible.executor.task_executor import TaskExecutor from ansible.executor.task_result import TaskResult from ansible.playbook.handler import Handler from ansible.playbook.task import Task from ansible.vars.unsafe_proxy import AnsibleJSONUnsafeDecoder from ansible.utils.unicode import to_unicode try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() __all__ = ['WorkerProcess'] class WorkerProcess(multiprocessing.Process): ''' The worker thread class, which uses TaskExecutor to run tasks read from a job queue and pushes results into a results queue for reading later. ''' def __init__(self, rslt_q, task_vars, host, task, play_context, loader, variable_manager, shared_loader_obj): super(WorkerProcess, self).__init__() # takes a task queue manager as the sole param: self._rslt_q = rslt_q self._task_vars = task_vars self._host = host self._task = task self._play_context = play_context self._loader = loader self._variable_manager = variable_manager self._shared_loader_obj = shared_loader_obj # dupe stdin, if we have one self._new_stdin = sys.stdin try: fileno = sys.stdin.fileno() if fileno is not None: try: self._new_stdin = os.fdopen(os.dup(fileno)) except OSError: # couldn't dupe stdin, most likely because it's # not a valid file descriptor, so we just rely on # using the one that was passed in pass except ValueError: # couldn't get stdin's fileno, so we just carry on pass def run(self): ''' Called when the process is started. Pushes the result onto the results queue. We also remove the host from the blocked hosts list, to signify that they are ready for their next task. ''' #import cProfile, pstats, StringIO #pr = cProfile.Profile() #pr.enable() if HAS_ATFORK:
try: # execute the task and build a TaskResult from the result display.debug("running TaskExecutor() for %s/%s" % (self._host, self._task)) executor_result = TaskExecutor( self._host, self._task, self._task_vars, self._play_context, self._new_stdin, self._loader, self._shared_loader_obj, self._rslt_q ).run() display.debug("done running TaskExecutor() for %s/%s" % (self._host, self._task)) self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, executor_result) # put the result on the result queue display.debug("sending task result") self._rslt_q.put(task_result) display.debug("done sending task result") except AnsibleConnectionFailure: self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, dict(unreachable=True)) self._rslt_q.put(task_result, block=False) except Exception as e: if not isinstance(e, (IOError, EOFError, KeyboardInterrupt, SystemExit)) or isinstance(e, TemplateNotFound): try: self._host.vars = dict() self._host.groups = [] task_result = TaskResult(self._host.name, self._task._uuid, dict(failed=True, exception=to_unicode(traceback.format_exc()), stdout='')) self._rslt_q.put(task_result, block=False) except: display.debug(u"WORKER EXCEPTION: %s" % to_unicode(e)) display.debug(u"WORKER TRACEBACK: %s" % to_unicode(traceback.format_exc())) display.debug("WORKER PROCESS EXITING") #pr.disable() #s = StringIO.StringIO() #sortby = 'time' #ps = pstats.Stats(pr, stream=s).sort_stats(sortby) #ps.print_stats() #with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue())
atfork()
conditional_block
confirmbox.js
/** * This file is part of "PCPIN Chat 6". * * "PCPIN Chat 6" 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. * * "PCPIN Chat 6" 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/>. */ /** * Callback function to execute after confirm box receives "OK". */ var confirmboxCallback=''; /** * Display confirm box * @param string $text Text to display * @param int top_offset Optional. How many pixels to add to the top position. Can be negative or positive. * @param int left_offset Optional. How many pixels to add to the left position. Can be negative or positive. * @param string callback Optional. Callback function to execute after confirm box receives "OK". */ function confirm(text, top_offset, left_offset, callback) { if (typeof(text)!='undefined' && typeof(text)!='string') { try { text=text.toString(); } catch (e) {} } if (typeof(text)=='string') { document.onkeyup_confirmbox=document.onkeyup; document.onkeyup=function(e) { switch (getKC(e)) { case 27: hideConfirmBox(false); break; } }; if (typeof(top_offset)!='number') top_offset=0; if (typeof(left_offset)!='number') left_offset=0; $('confirmbox_text').innerHTML=nl2br(htmlspecialchars(text)); $('confirmbox').style.display=''; $('confirmbox_btn_ok').focus(); setTimeout("moveToCenter($('confirmbox'), "+top_offset+", "+left_offset+"); $('confirmbox_btn_ok').focus();", 25); if (typeof(callback)=='string') { confirmboxCallback=callback; } else { confirmboxCallback=''; } setTimeout("$('confirmbox').style.display='none'; $('confirmbox').style.display='';", 200); } } /** * Hide confirm box @param boolean ok TRUE, if "OK" button was clicked */ function hideConfirmBox(ok)
{ document.onkeyup=document.onkeyup_confirmbox; $('confirmbox').style.display='none'; if (typeof(ok)=='boolean' && ok && confirmboxCallback!='') { eval('try { '+confirmboxCallback+' } catch(e) {}'); } }
identifier_body
confirmbox.js
/** * This file is part of "PCPIN Chat 6". * * "PCPIN Chat 6" 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. * * "PCPIN Chat 6" 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/>. */ /** * Callback function to execute after confirm box receives "OK". */ var confirmboxCallback=''; /** * Display confirm box * @param string $text Text to display * @param int top_offset Optional. How many pixels to add to the top position. Can be negative or positive. * @param int left_offset Optional. How many pixels to add to the left position. Can be negative or positive. * @param string callback Optional. Callback function to execute after confirm box receives "OK". */ function confirm(text, top_offset, left_offset, callback) { if (typeof(text)!='undefined' && typeof(text)!='string') { try { text=text.toString(); } catch (e) {} } if (typeof(text)=='string') { document.onkeyup_confirmbox=document.onkeyup; document.onkeyup=function(e) { switch (getKC(e)) { case 27: hideConfirmBox(false); break; } }; if (typeof(top_offset)!='number') top_offset=0; if (typeof(left_offset)!='number') left_offset=0; $('confirmbox_text').innerHTML=nl2br(htmlspecialchars(text)); $('confirmbox').style.display=''; $('confirmbox_btn_ok').focus(); setTimeout("moveToCenter($('confirmbox'), "+top_offset+", "+left_offset+"); $('confirmbox_btn_ok').focus();", 25); if (typeof(callback)=='string') { confirmboxCallback=callback; } else { confirmboxCallback=''; } setTimeout("$('confirmbox').style.display='none'; $('confirmbox').style.display='';", 200); } } /** * Hide confirm box @param boolean ok TRUE, if "OK" button was clicked */ function
(ok) { document.onkeyup=document.onkeyup_confirmbox; $('confirmbox').style.display='none'; if (typeof(ok)=='boolean' && ok && confirmboxCallback!='') { eval('try { '+confirmboxCallback+' } catch(e) {}'); } }
hideConfirmBox
identifier_name
confirmbox.js
/** * This file is part of "PCPIN Chat 6". * * "PCPIN Chat 6" 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. * * "PCPIN Chat 6" 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/>. */ /** * Callback function to execute after confirm box receives "OK". */
/** * Display confirm box * @param string $text Text to display * @param int top_offset Optional. How many pixels to add to the top position. Can be negative or positive. * @param int left_offset Optional. How many pixels to add to the left position. Can be negative or positive. * @param string callback Optional. Callback function to execute after confirm box receives "OK". */ function confirm(text, top_offset, left_offset, callback) { if (typeof(text)!='undefined' && typeof(text)!='string') { try { text=text.toString(); } catch (e) {} } if (typeof(text)=='string') { document.onkeyup_confirmbox=document.onkeyup; document.onkeyup=function(e) { switch (getKC(e)) { case 27: hideConfirmBox(false); break; } }; if (typeof(top_offset)!='number') top_offset=0; if (typeof(left_offset)!='number') left_offset=0; $('confirmbox_text').innerHTML=nl2br(htmlspecialchars(text)); $('confirmbox').style.display=''; $('confirmbox_btn_ok').focus(); setTimeout("moveToCenter($('confirmbox'), "+top_offset+", "+left_offset+"); $('confirmbox_btn_ok').focus();", 25); if (typeof(callback)=='string') { confirmboxCallback=callback; } else { confirmboxCallback=''; } setTimeout("$('confirmbox').style.display='none'; $('confirmbox').style.display='';", 200); } } /** * Hide confirm box @param boolean ok TRUE, if "OK" button was clicked */ function hideConfirmBox(ok) { document.onkeyup=document.onkeyup_confirmbox; $('confirmbox').style.display='none'; if (typeof(ok)=='boolean' && ok && confirmboxCallback!='') { eval('try { '+confirmboxCallback+' } catch(e) {}'); } }
var confirmboxCallback='';
random_line_split
confirmbox.js
/** * This file is part of "PCPIN Chat 6". * * "PCPIN Chat 6" 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. * * "PCPIN Chat 6" 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/>. */ /** * Callback function to execute after confirm box receives "OK". */ var confirmboxCallback=''; /** * Display confirm box * @param string $text Text to display * @param int top_offset Optional. How many pixels to add to the top position. Can be negative or positive. * @param int left_offset Optional. How many pixels to add to the left position. Can be negative or positive. * @param string callback Optional. Callback function to execute after confirm box receives "OK". */ function confirm(text, top_offset, left_offset, callback) { if (typeof(text)!='undefined' && typeof(text)!='string') { try { text=text.toString(); } catch (e) {} } if (typeof(text)=='string')
} /** * Hide confirm box @param boolean ok TRUE, if "OK" button was clicked */ function hideConfirmBox(ok) { document.onkeyup=document.onkeyup_confirmbox; $('confirmbox').style.display='none'; if (typeof(ok)=='boolean' && ok && confirmboxCallback!='') { eval('try { '+confirmboxCallback+' } catch(e) {}'); } }
{ document.onkeyup_confirmbox=document.onkeyup; document.onkeyup=function(e) { switch (getKC(e)) { case 27: hideConfirmBox(false); break; } }; if (typeof(top_offset)!='number') top_offset=0; if (typeof(left_offset)!='number') left_offset=0; $('confirmbox_text').innerHTML=nl2br(htmlspecialchars(text)); $('confirmbox').style.display=''; $('confirmbox_btn_ok').focus(); setTimeout("moveToCenter($('confirmbox'), "+top_offset+", "+left_offset+"); $('confirmbox_btn_ok').focus();", 25); if (typeof(callback)=='string') { confirmboxCallback=callback; } else { confirmboxCallback=''; } setTimeout("$('confirmbox').style.display='none'; $('confirmbox').style.display='';", 200); }
conditional_block
button.spec.js
import Vue from 'vue' import CButton from 'components/c-button' describe('button.vue', () => { let el beforeEach(() => { el = document.createElement('div') document.body.appendChild(el) }) afterEach(() => { document.body.removeChild(el) }) it('should render correct contents', () => { const vm = new Vue({ el, replace: false, template: '<c-button>PLATO</c-button>', components: { CButton } }) expect(vm.$children.length).to.equal(1) const el0 = vm.$children[0].$el
it('type', () => { const vm = new Vue({ el, replace: false, template: '<c-button type="submit">PLATO</c-button>', components: { CButton } }) expect(vm.$children[0].$el.type).to.equal('submit') }) })
expect(el0.textContent).to.equal('PLATO') expect(el0.type).to.equal('button') })
random_line_split
gridcolumn.ts
import { Teq } from '../types/ej-types'; import { ElementIdForLog, EnableLog } from '../../../common-types'; import { ComponentActions, ComponentChecks, ComponentGrabs, ComponentLogs } from './component'; import { queryAndAction } from '../tia-extjs-query'; const compName = 'GridColumn'; /** * gT.eC.gridcolumn.a or gT.eC.gridcolumn.actions */ export class GridColumnActions extends ComponentActions { static compName = compName; /** * Left mouse click on GridColumn trigger element. */ static async clickTrigger( tEQ: Teq, idForLog?: ElementIdForLog, enableLog?: EnableLog ): Promise<void> { return gT.e.q.wrap({ tEQ, compName, idForLog, act: async () => { const { el, trigger } = await queryAndAction({ tEQ, action: 'return { el: cmpInfo.constProps.domEl, trigger: cmpInfo.constProps.triggerEl } ;', idForLog, enableLog: false, }); await gT.sOrig.driver .actions({ bridge: true }) .move({ origin: el, x: 1, y: 1, duration: 0, }) .perform(); await gT.sOrig.driver.wait(gT.sOrig.until.elementIsVisible(trigger)); await trigger.click(); }, actionDesc: 'Click trigger', enableLog, }); } } /** * gT.eC.gridcolumn.c or gT.eC.gridcolumn.checks */ export class GridColumnChecks extends ComponentChecks { static compName = compName; } /** * gT.eC.gridcolumn.g or gT.eC.gridcolumn.grabs */ export class
extends ComponentGrabs { static compName = compName; } /** * gT.eC.gridcolumn.l or gT.eC.gridcolumn.logs */ export class GridColumnLogs extends ComponentLogs { static compName = compName; } export class GridColumnAPI { static a = GridColumnActions; static actions = GridColumnActions; static c = GridColumnChecks; static checks = GridColumnChecks; static g = GridColumnGrabs; static grabs = GridColumnGrabs; static l = GridColumnLogs; static logs = GridColumnLogs; }
GridColumnGrabs
identifier_name
gridcolumn.ts
import { Teq } from '../types/ej-types'; import { ElementIdForLog, EnableLog } from '../../../common-types'; import { ComponentActions, ComponentChecks, ComponentGrabs, ComponentLogs } from './component'; import { queryAndAction } from '../tia-extjs-query'; const compName = 'GridColumn'; /** * gT.eC.gridcolumn.a or gT.eC.gridcolumn.actions */ export class GridColumnActions extends ComponentActions { static compName = compName; /** * Left mouse click on GridColumn trigger element. */ static async clickTrigger( tEQ: Teq, idForLog?: ElementIdForLog, enableLog?: EnableLog ): Promise<void> { return gT.e.q.wrap({ tEQ, compName, idForLog, act: async () => { const { el, trigger } = await queryAndAction({ tEQ, action: 'return { el: cmpInfo.constProps.domEl, trigger: cmpInfo.constProps.triggerEl } ;', idForLog, enableLog: false, }); await gT.sOrig.driver .actions({ bridge: true }) .move({ origin: el, x: 1, y: 1, duration: 0, }) .perform(); await gT.sOrig.driver.wait(gT.sOrig.until.elementIsVisible(trigger)); await trigger.click(); }, actionDesc: 'Click trigger', enableLog, }); } } /** * gT.eC.gridcolumn.c or gT.eC.gridcolumn.checks */ export class GridColumnChecks extends ComponentChecks { static compName = compName; } /** * gT.eC.gridcolumn.g or gT.eC.gridcolumn.grabs */ export class GridColumnGrabs extends ComponentGrabs { static compName = compName;
*/ export class GridColumnLogs extends ComponentLogs { static compName = compName; } export class GridColumnAPI { static a = GridColumnActions; static actions = GridColumnActions; static c = GridColumnChecks; static checks = GridColumnChecks; static g = GridColumnGrabs; static grabs = GridColumnGrabs; static l = GridColumnLogs; static logs = GridColumnLogs; }
} /** * gT.eC.gridcolumn.l or gT.eC.gridcolumn.logs
random_line_split
__init__.py
from tilequeue.query.fixture import make_fixture_data_fetcher from tilequeue.query.pool import DBConnectionPool from tilequeue.query.postgres import make_db_data_fetcher from tilequeue.query.rawr import make_rawr_data_fetcher from tilequeue.query.split import make_split_data_fetcher from tilequeue.process import Source from tilequeue.store import make_s3_tile_key_generator __all__ = [ 'DBConnectionPool', 'make_db_data_fetcher', 'make_fixture_data_fetcher', 'make_data_fetcher', ] def make_data_fetcher(cfg, layer_data, query_cfg, io_pool): db_fetcher = make_db_data_fetcher( cfg.postgresql_conn_info, cfg.template_path, cfg.reload_templates, query_cfg, io_pool) if cfg.yml.get('use-rawr-tiles'): rawr_fetcher = _make_rawr_fetcher( cfg, layer_data, query_cfg, io_pool) group_by_zoom = cfg.yml.get('rawr').get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' return make_split_data_fetcher( group_by_zoom, db_fetcher, rawr_fetcher) else: return db_fetcher class _NullRawrStorage(object): def __init__(self, data_source, table_sources): self.data_source = data_source self.table_sources = table_sources def __call__(self, tile): # returns a "tables" object, which responds to __call__(table_name) # with tuples for that table. data = {} for location in self.data_source(tile): data[location.name] = location.records def _tables(table_name): from tilequeue.query.common import Table source = self.table_sources[table_name] return Table(source, data.get(table_name, [])) return _tables def _make_rawr_fetcher(cfg, layer_data, query_cfg, io_pool): rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' group_by_zoom = rawr_yaml.get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' rawr_source_yaml = rawr_yaml.get('source') assert rawr_source_yaml, 'Missing rawr source config' table_sources = rawr_source_yaml.get('table-sources') assert table_sources, 'Missing definitions of source per table' # map text for table source onto Source objects for tbl, data in table_sources.items(): source_name = data['name'] source_value = data['value'] table_sources[tbl] = Source(source_name, source_value) label_placement_layers = rawr_yaml.get('label-placement-layers', {}) for geom_type, layers in label_placement_layers.items(): assert geom_type in ('point', 'polygon', 'linestring'), \ 'Geom type %r not understood, expecting point, polygon or ' \ 'linestring.' % (geom_type,) label_placement_layers[geom_type] = set(layers) indexes_cfg = rawr_yaml.get('indexes') assert indexes_cfg, 'Missing definitions of table indexes.' # source types are: # s3 - to fetch RAWR tiles from S3 # store - to fetch RAWR tiles from any tilequeue tile source # generate - to generate RAWR tiles directly, rather than trying to load # them from S3. this can be useful for standalone use and # testing. provide a postgresql subkey for database connection # settings. source_type = rawr_source_yaml.get('type') if source_type == 's3': rawr_source_s3_yaml = rawr_source_yaml.get('s3') bucket = rawr_source_s3_yaml.get('bucket') assert bucket, 'Missing rawr source s3 bucket' region = rawr_source_s3_yaml.get('region') assert region, 'Missing rawr source s3 region' prefix = rawr_source_s3_yaml.get('prefix') assert prefix, 'Missing rawr source s3 prefix' extension = rawr_source_s3_yaml.get('extension') assert extension, 'Missing rawr source s3 extension' allow_missing_tiles = rawr_source_s3_yaml.get( 'allow-missing-tiles', False) import boto3 from tilequeue.rawr import RawrS3Source s3_client = boto3.client('s3', region_name=region) tile_key_gen = make_s3_tile_key_generator(rawr_source_s3_yaml) storage = RawrS3Source( s3_client, bucket, prefix, extension, table_sources, tile_key_gen, allow_missing_tiles) elif source_type == 'generate': from raw_tiles.source.conn import ConnectionContextManager from raw_tiles.source.osm import OsmSource postgresql_cfg = rawr_source_yaml.get('postgresql') assert postgresql_cfg, 'Missing rawr postgresql config' conn_ctx = ConnectionContextManager(postgresql_cfg) rawr_osm_source = OsmSource(conn_ctx) storage = _NullRawrStorage(rawr_osm_source, table_sources) elif source_type == 'store': from tilequeue.store import make_store from tilequeue.rawr import RawrStoreSource store_cfg = rawr_source_yaml.get('store') store = make_store(store_cfg, credentials=cfg.subtree('aws credentials')) storage = RawrStoreSource(store, table_sources) else: assert False, 'Source type %r not understood. ' \ 'Options are s3, generate and store.' % (source_type,) # TODO: this needs to be configurable, everywhere! this is a long term # refactor - it's hard-coded in a bunch of places :-( max_z = 16 layers = _make_layer_info(layer_data, cfg.process_yaml_cfg) return make_rawr_data_fetcher( group_by_zoom, max_z, storage, layers, indexes_cfg, label_placement_layers) def _make_layer_info(layer_data, process_yaml_cfg): from tilequeue.query.common import LayerInfo, ShapeType layers = {} functions = _parse_yaml_functions(process_yaml_cfg) for layer_datum in layer_data: name = layer_datum['name'] min_zoom_fn, props_fn = functions[name] shape_types = ShapeType.parse_set(layer_datum['geometry_types']) layer_info = LayerInfo(min_zoom_fn, props_fn, shape_types) layers[name] = layer_info return layers def _parse_yaml_functions(process_yaml_cfg): from tilequeue.command import make_output_calc_mapping from tilequeue.command import make_min_zoom_calc_mapping
output_layer_data = make_output_calc_mapping(process_yaml_cfg) min_zoom_layer_data = make_min_zoom_calc_mapping(process_yaml_cfg) keys = set(output_layer_data.keys()) assert keys == set(min_zoom_layer_data.keys()) functions = {} for key in keys: min_zoom_fn = min_zoom_layer_data[key] output_fn = output_layer_data[key] functions[key] = (min_zoom_fn, output_fn) return functions
random_line_split
__init__.py
from tilequeue.query.fixture import make_fixture_data_fetcher from tilequeue.query.pool import DBConnectionPool from tilequeue.query.postgres import make_db_data_fetcher from tilequeue.query.rawr import make_rawr_data_fetcher from tilequeue.query.split import make_split_data_fetcher from tilequeue.process import Source from tilequeue.store import make_s3_tile_key_generator __all__ = [ 'DBConnectionPool', 'make_db_data_fetcher', 'make_fixture_data_fetcher', 'make_data_fetcher', ] def make_data_fetcher(cfg, layer_data, query_cfg, io_pool): db_fetcher = make_db_data_fetcher( cfg.postgresql_conn_info, cfg.template_path, cfg.reload_templates, query_cfg, io_pool) if cfg.yml.get('use-rawr-tiles'): rawr_fetcher = _make_rawr_fetcher( cfg, layer_data, query_cfg, io_pool) group_by_zoom = cfg.yml.get('rawr').get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' return make_split_data_fetcher( group_by_zoom, db_fetcher, rawr_fetcher) else: return db_fetcher class _NullRawrStorage(object): def __init__(self, data_source, table_sources): self.data_source = data_source self.table_sources = table_sources def __call__(self, tile): # returns a "tables" object, which responds to __call__(table_name) # with tuples for that table. data = {} for location in self.data_source(tile): data[location.name] = location.records def _tables(table_name): from tilequeue.query.common import Table source = self.table_sources[table_name] return Table(source, data.get(table_name, [])) return _tables def _make_rawr_fetcher(cfg, layer_data, query_cfg, io_pool): rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' group_by_zoom = rawr_yaml.get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' rawr_source_yaml = rawr_yaml.get('source') assert rawr_source_yaml, 'Missing rawr source config' table_sources = rawr_source_yaml.get('table-sources') assert table_sources, 'Missing definitions of source per table' # map text for table source onto Source objects for tbl, data in table_sources.items(): source_name = data['name'] source_value = data['value'] table_sources[tbl] = Source(source_name, source_value) label_placement_layers = rawr_yaml.get('label-placement-layers', {}) for geom_type, layers in label_placement_layers.items(): assert geom_type in ('point', 'polygon', 'linestring'), \ 'Geom type %r not understood, expecting point, polygon or ' \ 'linestring.' % (geom_type,) label_placement_layers[geom_type] = set(layers) indexes_cfg = rawr_yaml.get('indexes') assert indexes_cfg, 'Missing definitions of table indexes.' # source types are: # s3 - to fetch RAWR tiles from S3 # store - to fetch RAWR tiles from any tilequeue tile source # generate - to generate RAWR tiles directly, rather than trying to load # them from S3. this can be useful for standalone use and # testing. provide a postgresql subkey for database connection # settings. source_type = rawr_source_yaml.get('type') if source_type == 's3': rawr_source_s3_yaml = rawr_source_yaml.get('s3') bucket = rawr_source_s3_yaml.get('bucket') assert bucket, 'Missing rawr source s3 bucket' region = rawr_source_s3_yaml.get('region') assert region, 'Missing rawr source s3 region' prefix = rawr_source_s3_yaml.get('prefix') assert prefix, 'Missing rawr source s3 prefix' extension = rawr_source_s3_yaml.get('extension') assert extension, 'Missing rawr source s3 extension' allow_missing_tiles = rawr_source_s3_yaml.get( 'allow-missing-tiles', False) import boto3 from tilequeue.rawr import RawrS3Source s3_client = boto3.client('s3', region_name=region) tile_key_gen = make_s3_tile_key_generator(rawr_source_s3_yaml) storage = RawrS3Source( s3_client, bucket, prefix, extension, table_sources, tile_key_gen, allow_missing_tiles) elif source_type == 'generate': from raw_tiles.source.conn import ConnectionContextManager from raw_tiles.source.osm import OsmSource postgresql_cfg = rawr_source_yaml.get('postgresql') assert postgresql_cfg, 'Missing rawr postgresql config' conn_ctx = ConnectionContextManager(postgresql_cfg) rawr_osm_source = OsmSource(conn_ctx) storage = _NullRawrStorage(rawr_osm_source, table_sources) elif source_type == 'store': from tilequeue.store import make_store from tilequeue.rawr import RawrStoreSource store_cfg = rawr_source_yaml.get('store') store = make_store(store_cfg, credentials=cfg.subtree('aws credentials')) storage = RawrStoreSource(store, table_sources) else: assert False, 'Source type %r not understood. ' \ 'Options are s3, generate and store.' % (source_type,) # TODO: this needs to be configurable, everywhere! this is a long term # refactor - it's hard-coded in a bunch of places :-( max_z = 16 layers = _make_layer_info(layer_data, cfg.process_yaml_cfg) return make_rawr_data_fetcher( group_by_zoom, max_z, storage, layers, indexes_cfg, label_placement_layers) def _make_layer_info(layer_data, process_yaml_cfg): from tilequeue.query.common import LayerInfo, ShapeType layers = {} functions = _parse_yaml_functions(process_yaml_cfg) for layer_datum in layer_data: name = layer_datum['name'] min_zoom_fn, props_fn = functions[name] shape_types = ShapeType.parse_set(layer_datum['geometry_types']) layer_info = LayerInfo(min_zoom_fn, props_fn, shape_types) layers[name] = layer_info return layers def _parse_yaml_functions(process_yaml_cfg): from tilequeue.command import make_output_calc_mapping from tilequeue.command import make_min_zoom_calc_mapping output_layer_data = make_output_calc_mapping(process_yaml_cfg) min_zoom_layer_data = make_min_zoom_calc_mapping(process_yaml_cfg) keys = set(output_layer_data.keys()) assert keys == set(min_zoom_layer_data.keys()) functions = {} for key in keys:
return functions
min_zoom_fn = min_zoom_layer_data[key] output_fn = output_layer_data[key] functions[key] = (min_zoom_fn, output_fn)
conditional_block
__init__.py
from tilequeue.query.fixture import make_fixture_data_fetcher from tilequeue.query.pool import DBConnectionPool from tilequeue.query.postgres import make_db_data_fetcher from tilequeue.query.rawr import make_rawr_data_fetcher from tilequeue.query.split import make_split_data_fetcher from tilequeue.process import Source from tilequeue.store import make_s3_tile_key_generator __all__ = [ 'DBConnectionPool', 'make_db_data_fetcher', 'make_fixture_data_fetcher', 'make_data_fetcher', ] def make_data_fetcher(cfg, layer_data, query_cfg, io_pool): db_fetcher = make_db_data_fetcher( cfg.postgresql_conn_info, cfg.template_path, cfg.reload_templates, query_cfg, io_pool) if cfg.yml.get('use-rawr-tiles'): rawr_fetcher = _make_rawr_fetcher( cfg, layer_data, query_cfg, io_pool) group_by_zoom = cfg.yml.get('rawr').get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' return make_split_data_fetcher( group_by_zoom, db_fetcher, rawr_fetcher) else: return db_fetcher class _NullRawrStorage(object): def __init__(self, data_source, table_sources): self.data_source = data_source self.table_sources = table_sources def __call__(self, tile): # returns a "tables" object, which responds to __call__(table_name) # with tuples for that table. data = {} for location in self.data_source(tile): data[location.name] = location.records def _tables(table_name): from tilequeue.query.common import Table source = self.table_sources[table_name] return Table(source, data.get(table_name, [])) return _tables def _make_rawr_fetcher(cfg, layer_data, query_cfg, io_pool): rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' group_by_zoom = rawr_yaml.get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' rawr_source_yaml = rawr_yaml.get('source') assert rawr_source_yaml, 'Missing rawr source config' table_sources = rawr_source_yaml.get('table-sources') assert table_sources, 'Missing definitions of source per table' # map text for table source onto Source objects for tbl, data in table_sources.items(): source_name = data['name'] source_value = data['value'] table_sources[tbl] = Source(source_name, source_value) label_placement_layers = rawr_yaml.get('label-placement-layers', {}) for geom_type, layers in label_placement_layers.items(): assert geom_type in ('point', 'polygon', 'linestring'), \ 'Geom type %r not understood, expecting point, polygon or ' \ 'linestring.' % (geom_type,) label_placement_layers[geom_type] = set(layers) indexes_cfg = rawr_yaml.get('indexes') assert indexes_cfg, 'Missing definitions of table indexes.' # source types are: # s3 - to fetch RAWR tiles from S3 # store - to fetch RAWR tiles from any tilequeue tile source # generate - to generate RAWR tiles directly, rather than trying to load # them from S3. this can be useful for standalone use and # testing. provide a postgresql subkey for database connection # settings. source_type = rawr_source_yaml.get('type') if source_type == 's3': rawr_source_s3_yaml = rawr_source_yaml.get('s3') bucket = rawr_source_s3_yaml.get('bucket') assert bucket, 'Missing rawr source s3 bucket' region = rawr_source_s3_yaml.get('region') assert region, 'Missing rawr source s3 region' prefix = rawr_source_s3_yaml.get('prefix') assert prefix, 'Missing rawr source s3 prefix' extension = rawr_source_s3_yaml.get('extension') assert extension, 'Missing rawr source s3 extension' allow_missing_tiles = rawr_source_s3_yaml.get( 'allow-missing-tiles', False) import boto3 from tilequeue.rawr import RawrS3Source s3_client = boto3.client('s3', region_name=region) tile_key_gen = make_s3_tile_key_generator(rawr_source_s3_yaml) storage = RawrS3Source( s3_client, bucket, prefix, extension, table_sources, tile_key_gen, allow_missing_tiles) elif source_type == 'generate': from raw_tiles.source.conn import ConnectionContextManager from raw_tiles.source.osm import OsmSource postgresql_cfg = rawr_source_yaml.get('postgresql') assert postgresql_cfg, 'Missing rawr postgresql config' conn_ctx = ConnectionContextManager(postgresql_cfg) rawr_osm_source = OsmSource(conn_ctx) storage = _NullRawrStorage(rawr_osm_source, table_sources) elif source_type == 'store': from tilequeue.store import make_store from tilequeue.rawr import RawrStoreSource store_cfg = rawr_source_yaml.get('store') store = make_store(store_cfg, credentials=cfg.subtree('aws credentials')) storage = RawrStoreSource(store, table_sources) else: assert False, 'Source type %r not understood. ' \ 'Options are s3, generate and store.' % (source_type,) # TODO: this needs to be configurable, everywhere! this is a long term # refactor - it's hard-coded in a bunch of places :-( max_z = 16 layers = _make_layer_info(layer_data, cfg.process_yaml_cfg) return make_rawr_data_fetcher( group_by_zoom, max_z, storage, layers, indexes_cfg, label_placement_layers) def
(layer_data, process_yaml_cfg): from tilequeue.query.common import LayerInfo, ShapeType layers = {} functions = _parse_yaml_functions(process_yaml_cfg) for layer_datum in layer_data: name = layer_datum['name'] min_zoom_fn, props_fn = functions[name] shape_types = ShapeType.parse_set(layer_datum['geometry_types']) layer_info = LayerInfo(min_zoom_fn, props_fn, shape_types) layers[name] = layer_info return layers def _parse_yaml_functions(process_yaml_cfg): from tilequeue.command import make_output_calc_mapping from tilequeue.command import make_min_zoom_calc_mapping output_layer_data = make_output_calc_mapping(process_yaml_cfg) min_zoom_layer_data = make_min_zoom_calc_mapping(process_yaml_cfg) keys = set(output_layer_data.keys()) assert keys == set(min_zoom_layer_data.keys()) functions = {} for key in keys: min_zoom_fn = min_zoom_layer_data[key] output_fn = output_layer_data[key] functions[key] = (min_zoom_fn, output_fn) return functions
_make_layer_info
identifier_name
__init__.py
from tilequeue.query.fixture import make_fixture_data_fetcher from tilequeue.query.pool import DBConnectionPool from tilequeue.query.postgres import make_db_data_fetcher from tilequeue.query.rawr import make_rawr_data_fetcher from tilequeue.query.split import make_split_data_fetcher from tilequeue.process import Source from tilequeue.store import make_s3_tile_key_generator __all__ = [ 'DBConnectionPool', 'make_db_data_fetcher', 'make_fixture_data_fetcher', 'make_data_fetcher', ] def make_data_fetcher(cfg, layer_data, query_cfg, io_pool): db_fetcher = make_db_data_fetcher( cfg.postgresql_conn_info, cfg.template_path, cfg.reload_templates, query_cfg, io_pool) if cfg.yml.get('use-rawr-tiles'): rawr_fetcher = _make_rawr_fetcher( cfg, layer_data, query_cfg, io_pool) group_by_zoom = cfg.yml.get('rawr').get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' return make_split_data_fetcher( group_by_zoom, db_fetcher, rawr_fetcher) else: return db_fetcher class _NullRawrStorage(object): def __init__(self, data_source, table_sources): self.data_source = data_source self.table_sources = table_sources def __call__(self, tile): # returns a "tables" object, which responds to __call__(table_name) # with tuples for that table. data = {} for location in self.data_source(tile): data[location.name] = location.records def _tables(table_name): from tilequeue.query.common import Table source = self.table_sources[table_name] return Table(source, data.get(table_name, [])) return _tables def _make_rawr_fetcher(cfg, layer_data, query_cfg, io_pool):
def _make_layer_info(layer_data, process_yaml_cfg): from tilequeue.query.common import LayerInfo, ShapeType layers = {} functions = _parse_yaml_functions(process_yaml_cfg) for layer_datum in layer_data: name = layer_datum['name'] min_zoom_fn, props_fn = functions[name] shape_types = ShapeType.parse_set(layer_datum['geometry_types']) layer_info = LayerInfo(min_zoom_fn, props_fn, shape_types) layers[name] = layer_info return layers def _parse_yaml_functions(process_yaml_cfg): from tilequeue.command import make_output_calc_mapping from tilequeue.command import make_min_zoom_calc_mapping output_layer_data = make_output_calc_mapping(process_yaml_cfg) min_zoom_layer_data = make_min_zoom_calc_mapping(process_yaml_cfg) keys = set(output_layer_data.keys()) assert keys == set(min_zoom_layer_data.keys()) functions = {} for key in keys: min_zoom_fn = min_zoom_layer_data[key] output_fn = output_layer_data[key] functions[key] = (min_zoom_fn, output_fn) return functions
rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' group_by_zoom = rawr_yaml.get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' rawr_source_yaml = rawr_yaml.get('source') assert rawr_source_yaml, 'Missing rawr source config' table_sources = rawr_source_yaml.get('table-sources') assert table_sources, 'Missing definitions of source per table' # map text for table source onto Source objects for tbl, data in table_sources.items(): source_name = data['name'] source_value = data['value'] table_sources[tbl] = Source(source_name, source_value) label_placement_layers = rawr_yaml.get('label-placement-layers', {}) for geom_type, layers in label_placement_layers.items(): assert geom_type in ('point', 'polygon', 'linestring'), \ 'Geom type %r not understood, expecting point, polygon or ' \ 'linestring.' % (geom_type,) label_placement_layers[geom_type] = set(layers) indexes_cfg = rawr_yaml.get('indexes') assert indexes_cfg, 'Missing definitions of table indexes.' # source types are: # s3 - to fetch RAWR tiles from S3 # store - to fetch RAWR tiles from any tilequeue tile source # generate - to generate RAWR tiles directly, rather than trying to load # them from S3. this can be useful for standalone use and # testing. provide a postgresql subkey for database connection # settings. source_type = rawr_source_yaml.get('type') if source_type == 's3': rawr_source_s3_yaml = rawr_source_yaml.get('s3') bucket = rawr_source_s3_yaml.get('bucket') assert bucket, 'Missing rawr source s3 bucket' region = rawr_source_s3_yaml.get('region') assert region, 'Missing rawr source s3 region' prefix = rawr_source_s3_yaml.get('prefix') assert prefix, 'Missing rawr source s3 prefix' extension = rawr_source_s3_yaml.get('extension') assert extension, 'Missing rawr source s3 extension' allow_missing_tiles = rawr_source_s3_yaml.get( 'allow-missing-tiles', False) import boto3 from tilequeue.rawr import RawrS3Source s3_client = boto3.client('s3', region_name=region) tile_key_gen = make_s3_tile_key_generator(rawr_source_s3_yaml) storage = RawrS3Source( s3_client, bucket, prefix, extension, table_sources, tile_key_gen, allow_missing_tiles) elif source_type == 'generate': from raw_tiles.source.conn import ConnectionContextManager from raw_tiles.source.osm import OsmSource postgresql_cfg = rawr_source_yaml.get('postgresql') assert postgresql_cfg, 'Missing rawr postgresql config' conn_ctx = ConnectionContextManager(postgresql_cfg) rawr_osm_source = OsmSource(conn_ctx) storage = _NullRawrStorage(rawr_osm_source, table_sources) elif source_type == 'store': from tilequeue.store import make_store from tilequeue.rawr import RawrStoreSource store_cfg = rawr_source_yaml.get('store') store = make_store(store_cfg, credentials=cfg.subtree('aws credentials')) storage = RawrStoreSource(store, table_sources) else: assert False, 'Source type %r not understood. ' \ 'Options are s3, generate and store.' % (source_type,) # TODO: this needs to be configurable, everywhere! this is a long term # refactor - it's hard-coded in a bunch of places :-( max_z = 16 layers = _make_layer_info(layer_data, cfg.process_yaml_cfg) return make_rawr_data_fetcher( group_by_zoom, max_z, storage, layers, indexes_cfg, label_placement_layers)
identifier_body
07-popup.js
var modal = (<Modal type="popup" title="爱过什么女爵的滋味">
<ModalTrigger modal={modal}> <Button amStyle="primary">Popup 窗口</Button> </ModalTrigger> ); ReactDOM.render(modalInstance, mountNode);
<p>为你封了国境<br/>为你赦了罪<br/>为你撤了历史记载<br/>为你涂了装扮<br/>为你喝了醉<br/>为你建了城池围墙<br/>一颗热的心穿着冰冷外衣<br/>一张白的脸漆上多少褪色的情节<br/>在我的空虚身体里面<br/>爱上哪个肤浅的王位<br/>在你的空虚宝座里面<br/>爱过什麽女爵的滋味<br/>为你封了国境</p><p>为你赦了罪<br/>为你撤了历史记载<br/>一颗热的心<br/>穿着冰冷外衣<br/>一张白的脸<br/>漆上多少褪色的情节<br/>在我的空虚身体里面<br/>爱上哪个肤浅的王位<br/>在你的空虚宝座里面<br/>爱过什麽女爵的滋味<br/>在我的空虚身体里面<br/>爱上哪个肤浅的王位<br/>在你的空虚宝座里面<br/>爱过什麽女爵的滋味</p> </Modal>); var modalInstance = (
random_line_split
repl.js
/* * repl.js * Copyright (C) 2015 Kovid Goyal <kovid at kovidgoyal.net> * * Distributed under terms of the BSD license. */ "use strict"; /*jshint node:true */ var fs = require('fs'); var path = require('path'); var vm = require('vm'); var util = require('util'); var utils = require('./utils'); var completelib = require('./completer'); var colored = utils.safe_colored; var RapydScript = (typeof create_rapydscript_compiler === 'function') ? create_rapydscript_compiler() : require('./compiler').create_compiler(); var has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); function create_ctx(baselib, show_js, console) { var ctx = vm.createContext({'console':console, 'show_js': !!show_js, 'RapydScript':RapydScript, 'require':require}); vm.runInContext(baselib, ctx, {'filename':'baselib-plain-pretty.js'}); vm.runInContext('var __name__ = "__repl__";', ctx); return ctx; } var homedir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; var cachedir = expanduser(process.env.XDG_CACHE_HOME || '~/.cache'); function expanduser(x)
function repl_defaults(options) { options = options || {}; if (!options.input) options.input = process.stdin; if (!options.output) options.output = process.stdout; if (options.show_js === undefined) options.show_js = true; if (!options.ps1) options.ps1 = '>>> '; if (!options.ps2) options.ps2 = '... '; if (!options.console) options.console = console; if (!options.readline) options.readline = require('readline'); if (options.terminal === undefined) options.terminal = options.output.isTTY; if (options.histfile === undefined) options.histfile = path.join(cachedir, 'rapydscript-repl.history'); options.colored = (options.terminal) ? colored : (function (string) { return string; }); options.historySize = options.history_size || 1000; return options; } function read_history(options) { if (options.histfile) { try { return fs.readFileSync(options.histfile, 'utf-8').split('\n'); } catch (e) { return []; } } } function write_history(options, history) { if (options.histfile) { history = history.join('\n'); try { return fs.writeFileSync(options.histfile, history, 'utf-8'); } catch (e) {} } } module.exports = function(options) { options = repl_defaults(options); options.completer = completer; var rl = options.readline.createInterface(options); var ps1 = options.colored(options.ps1, 'green'); var ps2 = options.colored(options.ps2, 'yellow'); var ctx = create_ctx(print_ast(RapydScript.parse('(def ():\n yield 1\n)'), true), options.show_js, options.console); var buffer = []; var more = false; var LINE_CONTINUATION_CHARS = ':\\'; var toplevel; var import_dirs = utils.get_import_dirs(); var find_completions = completelib(RapydScript, options); options.console.log(options.colored('Welcome to the RapydScript REPL! Press Ctrl+C then Ctrl+D to quit.', 'green', true)); if (options.show_js) options.console.log(options.colored('Use show_js=False to stop the REPL from showing the compiled JavaScript.', 'green', true)); else options.console.log(options.colored('Use show_js=True to have the REPL show the compiled JavaScript before executing it.', 'green', true)); options.console.log(); function print_ast(ast, keep_baselib) { var output_options = {omit_baselib:!keep_baselib, write_name:false, private_scope:false, beautify:true, keep_docstrings:true}; if (keep_baselib) output_options.baselib_plain = fs.readFileSync(path.join(options.lib_path, 'baselib-plain-pretty.js'), 'utf-8'); var output = new RapydScript.OutputStream(output_options); ast.print(output); return output.get(); } function resetbuffer() { buffer = []; } function completer(line) { return find_completions(line, ctx); } function prompt() { var lw = ''; if (more && buffer.length) { var prev_line = buffer[buffer.length - 1]; if (prev_line.trimRight().substr(prev_line.length - 1) == ':') lw = ' '; prev_line = prev_line.match(/^\s+/); if (prev_line) lw += prev_line; } rl.setPrompt((more) ? ps2 : ps1); if (rl.sync_prompt) rl.prompt(lw); else { rl.prompt(); if (lw) rl.write(lw); } } function runjs(js) { var result; if (vm.runInContext('show_js', ctx)) { options.console.log(options.colored('---------- Compiled JavaScript ---------', 'green', true)); options.console.log(js); options.console.log(options.colored('---------- Running JavaScript ---------', 'green', true)); } try { // Despite what the docs say node does not actually output any errors by itself // so, in case this bug is fixed later, we turn it off explicitly. result = vm.runInContext(js, ctx, {'filename':'<repl>', 'displayErrors':false}); } catch(e) { if (e.stack) options.console.error(e.stack); else options.console.error(e.toString()); } if (result !== undefined) { options.console.log(util.inspect(result, {'colors':options.terminal})); } } function compile_source(source) { var classes = (toplevel) ? toplevel.classes : undefined; var scoped_flags = (toplevel) ? toplevel.scoped_flags: undefined; try { toplevel = RapydScript.parse(source, { 'filename':'<repl>', 'basedir': process.cwd(), 'libdir': options.imp_path, 'import_dirs': import_dirs, 'classes': classes, 'scoped_flags': scoped_flags, }); } catch(e) { if (e.is_eof && e.line == buffer.length && e.col > 0) return true; if (e.message && e.line !== undefined) options.console.log(e.line + ':' + e.col + ':' + e.message); else options.console.log(e.stack || e.toString()); return false; } var output = print_ast(toplevel); if (classes) { var exports = {}; toplevel.exports.forEach(function (name) { exports[name] = true; }); Object.getOwnPropertyNames(classes).forEach(function (name) { if (!has_prop(exports, name) && !has_prop(toplevel.classes, name)) toplevel.classes[name] = classes[name]; }); } scoped_flags = toplevel.scoped_flags; runjs(output); return false; } function push(line) { buffer.push(line); var ll = line.trimRight(); if (ll && LINE_CONTINUATION_CHARS.indexOf(ll.substr(ll.length - 1)) > -1) return true; var source = buffer.join('\n'); if (!source.trim()) { resetbuffer(); return false; } var incomplete = compile_source(source); if (!incomplete) resetbuffer(); return incomplete; } rl.on('line', function(line) { if (more) { // We are in a block var line_is_empty = !line.trimLeft(); if (line_is_empty && buffer.length && !buffer[buffer.length - 1].trimLeft()) { // We have two empty lines, evaluate the block more = push(line.trimLeft()); } else buffer.push(line); } else more = push(line); // Not in a block, evaluate line prompt(); }) .on('close', function() { options.console.log('Bye!'); if (rl.history) write_history(options, rl.history); process.exit(0); }) .on('SIGINT', function() { rl.clearLine(); options.console.log('Keyboard Interrupt'); resetbuffer(); more = false; prompt(); }) .on('SIGCONT', function() { prompt(); }); rl.history = read_history(options); prompt(); };
{ if (!x) return x; if (x === '~') return homedir; if (x.slice(0, 2) != '~/') return x; return path.join(homedir, x.slice(2)); }
identifier_body
repl.js
/* * repl.js * Copyright (C) 2015 Kovid Goyal <kovid at kovidgoyal.net> * * Distributed under terms of the BSD license. */ "use strict"; /*jshint node:true */ var fs = require('fs'); var path = require('path'); var vm = require('vm'); var util = require('util'); var utils = require('./utils'); var completelib = require('./completer'); var colored = utils.safe_colored; var RapydScript = (typeof create_rapydscript_compiler === 'function') ? create_rapydscript_compiler() : require('./compiler').create_compiler(); var has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); function create_ctx(baselib, show_js, console) { var ctx = vm.createContext({'console':console, 'show_js': !!show_js, 'RapydScript':RapydScript, 'require':require}); vm.runInContext(baselib, ctx, {'filename':'baselib-plain-pretty.js'}); vm.runInContext('var __name__ = "__repl__";', ctx); return ctx; } var homedir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; var cachedir = expanduser(process.env.XDG_CACHE_HOME || '~/.cache'); function expanduser(x) { if (!x) return x; if (x === '~') return homedir; if (x.slice(0, 2) != '~/') return x; return path.join(homedir, x.slice(2)); } function repl_defaults(options) { options = options || {}; if (!options.input) options.input = process.stdin; if (!options.output) options.output = process.stdout; if (options.show_js === undefined) options.show_js = true; if (!options.ps1) options.ps1 = '>>> '; if (!options.ps2) options.ps2 = '... '; if (!options.console) options.console = console; if (!options.readline) options.readline = require('readline'); if (options.terminal === undefined) options.terminal = options.output.isTTY; if (options.histfile === undefined) options.histfile = path.join(cachedir, 'rapydscript-repl.history'); options.colored = (options.terminal) ? colored : (function (string) { return string; }); options.historySize = options.history_size || 1000; return options; } function read_history(options) { if (options.histfile) { try { return fs.readFileSync(options.histfile, 'utf-8').split('\n'); } catch (e) { return []; } } } function write_history(options, history) { if (options.histfile) { history = history.join('\n'); try { return fs.writeFileSync(options.histfile, history, 'utf-8'); } catch (e) {} } } module.exports = function(options) { options = repl_defaults(options); options.completer = completer; var rl = options.readline.createInterface(options); var ps1 = options.colored(options.ps1, 'green'); var ps2 = options.colored(options.ps2, 'yellow'); var ctx = create_ctx(print_ast(RapydScript.parse('(def ():\n yield 1\n)'), true), options.show_js, options.console); var buffer = []; var more = false; var LINE_CONTINUATION_CHARS = ':\\'; var toplevel; var import_dirs = utils.get_import_dirs(); var find_completions = completelib(RapydScript, options); options.console.log(options.colored('Welcome to the RapydScript REPL! Press Ctrl+C then Ctrl+D to quit.', 'green', true)); if (options.show_js) options.console.log(options.colored('Use show_js=False to stop the REPL from showing the compiled JavaScript.', 'green', true)); else options.console.log(options.colored('Use show_js=True to have the REPL show the compiled JavaScript before executing it.', 'green', true)); options.console.log(); function print_ast(ast, keep_baselib) { var output_options = {omit_baselib:!keep_baselib, write_name:false, private_scope:false, beautify:true, keep_docstrings:true}; if (keep_baselib) output_options.baselib_plain = fs.readFileSync(path.join(options.lib_path, 'baselib-plain-pretty.js'), 'utf-8'); var output = new RapydScript.OutputStream(output_options);
function resetbuffer() { buffer = []; } function completer(line) { return find_completions(line, ctx); } function prompt() { var lw = ''; if (more && buffer.length) { var prev_line = buffer[buffer.length - 1]; if (prev_line.trimRight().substr(prev_line.length - 1) == ':') lw = ' '; prev_line = prev_line.match(/^\s+/); if (prev_line) lw += prev_line; } rl.setPrompt((more) ? ps2 : ps1); if (rl.sync_prompt) rl.prompt(lw); else { rl.prompt(); if (lw) rl.write(lw); } } function runjs(js) { var result; if (vm.runInContext('show_js', ctx)) { options.console.log(options.colored('---------- Compiled JavaScript ---------', 'green', true)); options.console.log(js); options.console.log(options.colored('---------- Running JavaScript ---------', 'green', true)); } try { // Despite what the docs say node does not actually output any errors by itself // so, in case this bug is fixed later, we turn it off explicitly. result = vm.runInContext(js, ctx, {'filename':'<repl>', 'displayErrors':false}); } catch(e) { if (e.stack) options.console.error(e.stack); else options.console.error(e.toString()); } if (result !== undefined) { options.console.log(util.inspect(result, {'colors':options.terminal})); } } function compile_source(source) { var classes = (toplevel) ? toplevel.classes : undefined; var scoped_flags = (toplevel) ? toplevel.scoped_flags: undefined; try { toplevel = RapydScript.parse(source, { 'filename':'<repl>', 'basedir': process.cwd(), 'libdir': options.imp_path, 'import_dirs': import_dirs, 'classes': classes, 'scoped_flags': scoped_flags, }); } catch(e) { if (e.is_eof && e.line == buffer.length && e.col > 0) return true; if (e.message && e.line !== undefined) options.console.log(e.line + ':' + e.col + ':' + e.message); else options.console.log(e.stack || e.toString()); return false; } var output = print_ast(toplevel); if (classes) { var exports = {}; toplevel.exports.forEach(function (name) { exports[name] = true; }); Object.getOwnPropertyNames(classes).forEach(function (name) { if (!has_prop(exports, name) && !has_prop(toplevel.classes, name)) toplevel.classes[name] = classes[name]; }); } scoped_flags = toplevel.scoped_flags; runjs(output); return false; } function push(line) { buffer.push(line); var ll = line.trimRight(); if (ll && LINE_CONTINUATION_CHARS.indexOf(ll.substr(ll.length - 1)) > -1) return true; var source = buffer.join('\n'); if (!source.trim()) { resetbuffer(); return false; } var incomplete = compile_source(source); if (!incomplete) resetbuffer(); return incomplete; } rl.on('line', function(line) { if (more) { // We are in a block var line_is_empty = !line.trimLeft(); if (line_is_empty && buffer.length && !buffer[buffer.length - 1].trimLeft()) { // We have two empty lines, evaluate the block more = push(line.trimLeft()); } else buffer.push(line); } else more = push(line); // Not in a block, evaluate line prompt(); }) .on('close', function() { options.console.log('Bye!'); if (rl.history) write_history(options, rl.history); process.exit(0); }) .on('SIGINT', function() { rl.clearLine(); options.console.log('Keyboard Interrupt'); resetbuffer(); more = false; prompt(); }) .on('SIGCONT', function() { prompt(); }); rl.history = read_history(options); prompt(); };
ast.print(output); return output.get(); }
random_line_split
repl.js
/* * repl.js * Copyright (C) 2015 Kovid Goyal <kovid at kovidgoyal.net> * * Distributed under terms of the BSD license. */ "use strict"; /*jshint node:true */ var fs = require('fs'); var path = require('path'); var vm = require('vm'); var util = require('util'); var utils = require('./utils'); var completelib = require('./completer'); var colored = utils.safe_colored; var RapydScript = (typeof create_rapydscript_compiler === 'function') ? create_rapydscript_compiler() : require('./compiler').create_compiler(); var has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); function create_ctx(baselib, show_js, console) { var ctx = vm.createContext({'console':console, 'show_js': !!show_js, 'RapydScript':RapydScript, 'require':require}); vm.runInContext(baselib, ctx, {'filename':'baselib-plain-pretty.js'}); vm.runInContext('var __name__ = "__repl__";', ctx); return ctx; } var homedir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; var cachedir = expanduser(process.env.XDG_CACHE_HOME || '~/.cache'); function expanduser(x) { if (!x) return x; if (x === '~') return homedir; if (x.slice(0, 2) != '~/') return x; return path.join(homedir, x.slice(2)); } function repl_defaults(options) { options = options || {}; if (!options.input) options.input = process.stdin; if (!options.output) options.output = process.stdout; if (options.show_js === undefined) options.show_js = true; if (!options.ps1) options.ps1 = '>>> '; if (!options.ps2) options.ps2 = '... '; if (!options.console) options.console = console; if (!options.readline) options.readline = require('readline'); if (options.terminal === undefined) options.terminal = options.output.isTTY; if (options.histfile === undefined) options.histfile = path.join(cachedir, 'rapydscript-repl.history'); options.colored = (options.terminal) ? colored : (function (string) { return string; }); options.historySize = options.history_size || 1000; return options; } function read_history(options) { if (options.histfile) { try { return fs.readFileSync(options.histfile, 'utf-8').split('\n'); } catch (e) { return []; } } } function write_history(options, history) { if (options.histfile) { history = history.join('\n'); try { return fs.writeFileSync(options.histfile, history, 'utf-8'); } catch (e) {} } } module.exports = function(options) { options = repl_defaults(options); options.completer = completer; var rl = options.readline.createInterface(options); var ps1 = options.colored(options.ps1, 'green'); var ps2 = options.colored(options.ps2, 'yellow'); var ctx = create_ctx(print_ast(RapydScript.parse('(def ():\n yield 1\n)'), true), options.show_js, options.console); var buffer = []; var more = false; var LINE_CONTINUATION_CHARS = ':\\'; var toplevel; var import_dirs = utils.get_import_dirs(); var find_completions = completelib(RapydScript, options); options.console.log(options.colored('Welcome to the RapydScript REPL! Press Ctrl+C then Ctrl+D to quit.', 'green', true)); if (options.show_js) options.console.log(options.colored('Use show_js=False to stop the REPL from showing the compiled JavaScript.', 'green', true)); else options.console.log(options.colored('Use show_js=True to have the REPL show the compiled JavaScript before executing it.', 'green', true)); options.console.log(); function print_ast(ast, keep_baselib) { var output_options = {omit_baselib:!keep_baselib, write_name:false, private_scope:false, beautify:true, keep_docstrings:true}; if (keep_baselib) output_options.baselib_plain = fs.readFileSync(path.join(options.lib_path, 'baselib-plain-pretty.js'), 'utf-8'); var output = new RapydScript.OutputStream(output_options); ast.print(output); return output.get(); } function resetbuffer() { buffer = []; } function completer(line) { return find_completions(line, ctx); } function prompt() { var lw = ''; if (more && buffer.length) { var prev_line = buffer[buffer.length - 1]; if (prev_line.trimRight().substr(prev_line.length - 1) == ':') lw = ' '; prev_line = prev_line.match(/^\s+/); if (prev_line) lw += prev_line; } rl.setPrompt((more) ? ps2 : ps1); if (rl.sync_prompt) rl.prompt(lw); else { rl.prompt(); if (lw) rl.write(lw); } } function runjs(js) { var result; if (vm.runInContext('show_js', ctx)) { options.console.log(options.colored('---------- Compiled JavaScript ---------', 'green', true)); options.console.log(js); options.console.log(options.colored('---------- Running JavaScript ---------', 'green', true)); } try { // Despite what the docs say node does not actually output any errors by itself // so, in case this bug is fixed later, we turn it off explicitly. result = vm.runInContext(js, ctx, {'filename':'<repl>', 'displayErrors':false}); } catch(e) { if (e.stack) options.console.error(e.stack); else options.console.error(e.toString()); } if (result !== undefined) { options.console.log(util.inspect(result, {'colors':options.terminal})); } } function compile_source(source) { var classes = (toplevel) ? toplevel.classes : undefined; var scoped_flags = (toplevel) ? toplevel.scoped_flags: undefined; try { toplevel = RapydScript.parse(source, { 'filename':'<repl>', 'basedir': process.cwd(), 'libdir': options.imp_path, 'import_dirs': import_dirs, 'classes': classes, 'scoped_flags': scoped_flags, }); } catch(e) { if (e.is_eof && e.line == buffer.length && e.col > 0) return true; if (e.message && e.line !== undefined) options.console.log(e.line + ':' + e.col + ':' + e.message); else options.console.log(e.stack || e.toString()); return false; } var output = print_ast(toplevel); if (classes) { var exports = {}; toplevel.exports.forEach(function (name) { exports[name] = true; }); Object.getOwnPropertyNames(classes).forEach(function (name) { if (!has_prop(exports, name) && !has_prop(toplevel.classes, name)) toplevel.classes[name] = classes[name]; }); } scoped_flags = toplevel.scoped_flags; runjs(output); return false; } function
(line) { buffer.push(line); var ll = line.trimRight(); if (ll && LINE_CONTINUATION_CHARS.indexOf(ll.substr(ll.length - 1)) > -1) return true; var source = buffer.join('\n'); if (!source.trim()) { resetbuffer(); return false; } var incomplete = compile_source(source); if (!incomplete) resetbuffer(); return incomplete; } rl.on('line', function(line) { if (more) { // We are in a block var line_is_empty = !line.trimLeft(); if (line_is_empty && buffer.length && !buffer[buffer.length - 1].trimLeft()) { // We have two empty lines, evaluate the block more = push(line.trimLeft()); } else buffer.push(line); } else more = push(line); // Not in a block, evaluate line prompt(); }) .on('close', function() { options.console.log('Bye!'); if (rl.history) write_history(options, rl.history); process.exit(0); }) .on('SIGINT', function() { rl.clearLine(); options.console.log('Keyboard Interrupt'); resetbuffer(); more = false; prompt(); }) .on('SIGCONT', function() { prompt(); }); rl.history = read_history(options); prompt(); };
push
identifier_name
repl.js
/* * repl.js * Copyright (C) 2015 Kovid Goyal <kovid at kovidgoyal.net> * * Distributed under terms of the BSD license. */ "use strict"; /*jshint node:true */ var fs = require('fs'); var path = require('path'); var vm = require('vm'); var util = require('util'); var utils = require('./utils'); var completelib = require('./completer'); var colored = utils.safe_colored; var RapydScript = (typeof create_rapydscript_compiler === 'function') ? create_rapydscript_compiler() : require('./compiler').create_compiler(); var has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); function create_ctx(baselib, show_js, console) { var ctx = vm.createContext({'console':console, 'show_js': !!show_js, 'RapydScript':RapydScript, 'require':require}); vm.runInContext(baselib, ctx, {'filename':'baselib-plain-pretty.js'}); vm.runInContext('var __name__ = "__repl__";', ctx); return ctx; } var homedir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; var cachedir = expanduser(process.env.XDG_CACHE_HOME || '~/.cache'); function expanduser(x) { if (!x) return x; if (x === '~') return homedir; if (x.slice(0, 2) != '~/') return x; return path.join(homedir, x.slice(2)); } function repl_defaults(options) { options = options || {}; if (!options.input) options.input = process.stdin; if (!options.output) options.output = process.stdout; if (options.show_js === undefined) options.show_js = true; if (!options.ps1) options.ps1 = '>>> '; if (!options.ps2) options.ps2 = '... '; if (!options.console) options.console = console; if (!options.readline) options.readline = require('readline'); if (options.terminal === undefined) options.terminal = options.output.isTTY; if (options.histfile === undefined) options.histfile = path.join(cachedir, 'rapydscript-repl.history'); options.colored = (options.terminal) ? colored : (function (string) { return string; }); options.historySize = options.history_size || 1000; return options; } function read_history(options) { if (options.histfile) { try { return fs.readFileSync(options.histfile, 'utf-8').split('\n'); } catch (e) { return []; } } } function write_history(options, history) { if (options.histfile) { history = history.join('\n'); try { return fs.writeFileSync(options.histfile, history, 'utf-8'); } catch (e) {} } } module.exports = function(options) { options = repl_defaults(options); options.completer = completer; var rl = options.readline.createInterface(options); var ps1 = options.colored(options.ps1, 'green'); var ps2 = options.colored(options.ps2, 'yellow'); var ctx = create_ctx(print_ast(RapydScript.parse('(def ():\n yield 1\n)'), true), options.show_js, options.console); var buffer = []; var more = false; var LINE_CONTINUATION_CHARS = ':\\'; var toplevel; var import_dirs = utils.get_import_dirs(); var find_completions = completelib(RapydScript, options); options.console.log(options.colored('Welcome to the RapydScript REPL! Press Ctrl+C then Ctrl+D to quit.', 'green', true)); if (options.show_js) options.console.log(options.colored('Use show_js=False to stop the REPL from showing the compiled JavaScript.', 'green', true)); else options.console.log(options.colored('Use show_js=True to have the REPL show the compiled JavaScript before executing it.', 'green', true)); options.console.log(); function print_ast(ast, keep_baselib) { var output_options = {omit_baselib:!keep_baselib, write_name:false, private_scope:false, beautify:true, keep_docstrings:true}; if (keep_baselib) output_options.baselib_plain = fs.readFileSync(path.join(options.lib_path, 'baselib-plain-pretty.js'), 'utf-8'); var output = new RapydScript.OutputStream(output_options); ast.print(output); return output.get(); } function resetbuffer() { buffer = []; } function completer(line) { return find_completions(line, ctx); } function prompt() { var lw = ''; if (more && buffer.length) { var prev_line = buffer[buffer.length - 1]; if (prev_line.trimRight().substr(prev_line.length - 1) == ':') lw = ' '; prev_line = prev_line.match(/^\s+/); if (prev_line) lw += prev_line; } rl.setPrompt((more) ? ps2 : ps1); if (rl.sync_prompt) rl.prompt(lw); else
} function runjs(js) { var result; if (vm.runInContext('show_js', ctx)) { options.console.log(options.colored('---------- Compiled JavaScript ---------', 'green', true)); options.console.log(js); options.console.log(options.colored('---------- Running JavaScript ---------', 'green', true)); } try { // Despite what the docs say node does not actually output any errors by itself // so, in case this bug is fixed later, we turn it off explicitly. result = vm.runInContext(js, ctx, {'filename':'<repl>', 'displayErrors':false}); } catch(e) { if (e.stack) options.console.error(e.stack); else options.console.error(e.toString()); } if (result !== undefined) { options.console.log(util.inspect(result, {'colors':options.terminal})); } } function compile_source(source) { var classes = (toplevel) ? toplevel.classes : undefined; var scoped_flags = (toplevel) ? toplevel.scoped_flags: undefined; try { toplevel = RapydScript.parse(source, { 'filename':'<repl>', 'basedir': process.cwd(), 'libdir': options.imp_path, 'import_dirs': import_dirs, 'classes': classes, 'scoped_flags': scoped_flags, }); } catch(e) { if (e.is_eof && e.line == buffer.length && e.col > 0) return true; if (e.message && e.line !== undefined) options.console.log(e.line + ':' + e.col + ':' + e.message); else options.console.log(e.stack || e.toString()); return false; } var output = print_ast(toplevel); if (classes) { var exports = {}; toplevel.exports.forEach(function (name) { exports[name] = true; }); Object.getOwnPropertyNames(classes).forEach(function (name) { if (!has_prop(exports, name) && !has_prop(toplevel.classes, name)) toplevel.classes[name] = classes[name]; }); } scoped_flags = toplevel.scoped_flags; runjs(output); return false; } function push(line) { buffer.push(line); var ll = line.trimRight(); if (ll && LINE_CONTINUATION_CHARS.indexOf(ll.substr(ll.length - 1)) > -1) return true; var source = buffer.join('\n'); if (!source.trim()) { resetbuffer(); return false; } var incomplete = compile_source(source); if (!incomplete) resetbuffer(); return incomplete; } rl.on('line', function(line) { if (more) { // We are in a block var line_is_empty = !line.trimLeft(); if (line_is_empty && buffer.length && !buffer[buffer.length - 1].trimLeft()) { // We have two empty lines, evaluate the block more = push(line.trimLeft()); } else buffer.push(line); } else more = push(line); // Not in a block, evaluate line prompt(); }) .on('close', function() { options.console.log('Bye!'); if (rl.history) write_history(options, rl.history); process.exit(0); }) .on('SIGINT', function() { rl.clearLine(); options.console.log('Keyboard Interrupt'); resetbuffer(); more = false; prompt(); }) .on('SIGCONT', function() { prompt(); }); rl.history = read_history(options); prompt(); };
{ rl.prompt(); if (lw) rl.write(lw); }
conditional_block
app.py
from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.decorators import method_decorator from ..core.app import SatchlessApp from . import models class OrderApp(SatchlessApp): app_name = 'order' namespace = 'order' order_model = models.Order order_details_templates = [ 'satchless/order/view.html', 'satchless/order/%(order_model)s/view.html' ] order_list_templates = [ 'satchless/order/my_orders.html', 'satchless/order/%(order_model)s/my_orders.html' ] @method_decorator(login_required) def index(self, request):
def details(self, request, order_token): order = self.get_order(request, order_token=order_token) context = self.get_context_data(request, order=order) format_data = { 'order_model': order._meta.model_name } templates = [p % format_data for p in self.order_details_templates] return TemplateResponse(request, templates, context) def get_order(self, request, order_token): if request.user.is_authenticated(): orders = self.order_model.objects.filter(user=request.user) else: orders = self.order_model.objects.filter(user=None) order = get_object_or_404(orders, token=order_token) return order def get_urls(self, prefix=None): prefix = prefix or self.app_name return patterns('', url(r'^$', self.index, name='index'), url(r'^(?P<order_token>[0-9a-zA-Z]+)/$', self.details, name='details'), ) order_app = OrderApp()
orders = self.order_model.objects.filter(user=request.user) context = self.get_context_data(request, orders=orders) format_data = { 'order_model': self.order_model._meta.model_name } templates = [p % format_data for p in self.order_list_templates] return TemplateResponse(request, templates, context)
identifier_body
app.py
from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required
from ..core.app import SatchlessApp from . import models class OrderApp(SatchlessApp): app_name = 'order' namespace = 'order' order_model = models.Order order_details_templates = [ 'satchless/order/view.html', 'satchless/order/%(order_model)s/view.html' ] order_list_templates = [ 'satchless/order/my_orders.html', 'satchless/order/%(order_model)s/my_orders.html' ] @method_decorator(login_required) def index(self, request): orders = self.order_model.objects.filter(user=request.user) context = self.get_context_data(request, orders=orders) format_data = { 'order_model': self.order_model._meta.model_name } templates = [p % format_data for p in self.order_list_templates] return TemplateResponse(request, templates, context) def details(self, request, order_token): order = self.get_order(request, order_token=order_token) context = self.get_context_data(request, order=order) format_data = { 'order_model': order._meta.model_name } templates = [p % format_data for p in self.order_details_templates] return TemplateResponse(request, templates, context) def get_order(self, request, order_token): if request.user.is_authenticated(): orders = self.order_model.objects.filter(user=request.user) else: orders = self.order_model.objects.filter(user=None) order = get_object_or_404(orders, token=order_token) return order def get_urls(self, prefix=None): prefix = prefix or self.app_name return patterns('', url(r'^$', self.index, name='index'), url(r'^(?P<order_token>[0-9a-zA-Z]+)/$', self.details, name='details'), ) order_app = OrderApp()
from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.decorators import method_decorator
random_line_split
app.py
from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.decorators import method_decorator from ..core.app import SatchlessApp from . import models class OrderApp(SatchlessApp): app_name = 'order' namespace = 'order' order_model = models.Order order_details_templates = [ 'satchless/order/view.html', 'satchless/order/%(order_model)s/view.html' ] order_list_templates = [ 'satchless/order/my_orders.html', 'satchless/order/%(order_model)s/my_orders.html' ] @method_decorator(login_required) def index(self, request): orders = self.order_model.objects.filter(user=request.user) context = self.get_context_data(request, orders=orders) format_data = { 'order_model': self.order_model._meta.model_name } templates = [p % format_data for p in self.order_list_templates] return TemplateResponse(request, templates, context) def details(self, request, order_token): order = self.get_order(request, order_token=order_token) context = self.get_context_data(request, order=order) format_data = { 'order_model': order._meta.model_name } templates = [p % format_data for p in self.order_details_templates] return TemplateResponse(request, templates, context) def get_order(self, request, order_token): if request.user.is_authenticated():
else: orders = self.order_model.objects.filter(user=None) order = get_object_or_404(orders, token=order_token) return order def get_urls(self, prefix=None): prefix = prefix or self.app_name return patterns('', url(r'^$', self.index, name='index'), url(r'^(?P<order_token>[0-9a-zA-Z]+)/$', self.details, name='details'), ) order_app = OrderApp()
orders = self.order_model.objects.filter(user=request.user)
conditional_block
app.py
from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.decorators import method_decorator from ..core.app import SatchlessApp from . import models class OrderApp(SatchlessApp): app_name = 'order' namespace = 'order' order_model = models.Order order_details_templates = [ 'satchless/order/view.html', 'satchless/order/%(order_model)s/view.html' ] order_list_templates = [ 'satchless/order/my_orders.html', 'satchless/order/%(order_model)s/my_orders.html' ] @method_decorator(login_required) def index(self, request): orders = self.order_model.objects.filter(user=request.user) context = self.get_context_data(request, orders=orders) format_data = { 'order_model': self.order_model._meta.model_name } templates = [p % format_data for p in self.order_list_templates] return TemplateResponse(request, templates, context) def
(self, request, order_token): order = self.get_order(request, order_token=order_token) context = self.get_context_data(request, order=order) format_data = { 'order_model': order._meta.model_name } templates = [p % format_data for p in self.order_details_templates] return TemplateResponse(request, templates, context) def get_order(self, request, order_token): if request.user.is_authenticated(): orders = self.order_model.objects.filter(user=request.user) else: orders = self.order_model.objects.filter(user=None) order = get_object_or_404(orders, token=order_token) return order def get_urls(self, prefix=None): prefix = prefix or self.app_name return patterns('', url(r'^$', self.index, name='index'), url(r'^(?P<order_token>[0-9a-zA-Z]+)/$', self.details, name='details'), ) order_app = OrderApp()
details
identifier_name
app.js
"use strict";
requirejs.config({ 'baseUrl': 'js/lib', 'paths': { 'app': '../app', 'text': './text', 'jquery': 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min', 'jqueryui': 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min' }, 'config': { 'app/main': { census_url: 'http://api.census.gov/data/2013/acs5?get=B19013_001E,B01003_001E&for=tract:*&in=state:25+county:*' }, 'app/map': { //starting zoom and map centering options map: { center: { lat: 42.3601, lng: -71.0589 }, zoom: 12 }, element: '#map-canvas' }, 'app/features': { //these are the geojson opts used for maps api loadGeoJson opts: { idPropertyName: 'GEOID' } }, //field codes documented here: http://www2.census.gov/geo/tiger/TIGER_DP/2013ACS/Metadata/County_and_Place_Metadata_2013.txt 'app/fields': { INCOME: { key: 'B19013_001E' }, POP: { key: 'B01003_001E' }, SQ_MILE: { calc: function (feature) { return (feature.getProperty('ALAND') * (3.86102e-7)).toFixed(3); } }, DENSITY: { calc: function (feature) { var pop = feature.getProperty('POP'); return pop === 0 ? 0 : Math.round(pop / feature.getProperty('SQ_MILE')); } }, PERSON_FOOD: { calc: function (feature) { var count = feature.getProperty('license_food_count'); return count === 0 ? 'N/A' : Math.round(feature.getProperty('POP') / count); } }, PERSON_LIQUOR: { calc: function (feature) { var count = feature.getProperty('license_liquor_count'); return count === 0 ? 'N/A' : Math.round(feature.getProperty('POP') / count); } }, PERSON_ENT: { calc: function (feature) { var count = feature.getProperty('license_entertainment_count'); return count === 0 ? 'N/A' : Math.round(feature.getProperty('POP') / count); } } }, 'app/layers/license_liquor': { url: 'data/liquor.geojson' }, 'app/layers/license_food': { url: 'data/food.geojson' }, 'app/layers/license_entertainment': { url: 'data/entertainment.geojson' }, 'app/layers/census_geography': { url: 'data/cb_2013_25_017-021-025_tract_500k.geojson' } } }); requirejs(['app/main'], function (app) { app.initialize(); });
random_line_split
before_vm_migrate_destination.py
#!/usr/bin/python import os import sys import grp import pwd import traceback import utils import hooking DEV_MAPPER_PATH = "/dev/mapper" DEV_DIRECTLUN_PATH = '/dev/directlun' def createdirectory(dirpath): # we don't use os.mkdir/chown because we need sudo command = ['/bin/mkdir', '-p', dirpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error mkdir %s, err = %s\n' % (dirpath, err)) sys.exit(2) mode = '755' command = ['/bin/chmod', mode, dirpath] if retcode != 0:
def cloneDeviceNode(srcpath, devpath): """Clone a device node into a temporary private location.""" # we don't use os.remove/mknod/chmod/chown because we need sudo command = ['/bin/rm', '-f', devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error rm -f %s, err = %s\n' % (devpath, err)) sys.exit(2) stat = os.stat(srcpath) major = os.major(stat.st_rdev) minor = os.minor(stat.st_rdev) command = ['/bin/mknod', devpath, 'b', str(major), str(minor)] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error mknod %s, err = %s\n' % (devpath, err)) sys.exit(2) mode = '660' command = ['/bin/chmod', mode, devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error chmod %s to %s, err = %s\n' % (devpath, mode, err)) sys.exit(2) group = grp.getgrnam('qemu') gid = group.gr_gid user = pwd.getpwnam('qemu') uid = user.pw_uid owner = str(uid) + ':' + str(gid) command = ['/bin/chown', owner, devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error chown %s to %s, err = %s\n' % (devpath, owner, err)) sys.exit(2) if os.environ.has_key('directlun'): try: luns = os.environ['directlun'] domxml = hooking.read_domxml() createdirectory(DEV_DIRECTLUN_PATH) for lun in luns.split(','): try: lun, options = lun.split(':') except ValueError: options = '' options = options.split(';') srcpath = DEV_MAPPER_PATH + '/' + lun if not os.path.exists(srcpath): sys.stderr.write('directlun before_vm_migration_destination: device not found %s\n' % srcpath) sys.exit(2) uuid = domxml.getElementsByTagName('uuid')[0] uuid = uuid.childNodes[0].nodeValue devpath = DEV_DIRECTLUN_PATH + '/' + lun + '-' + uuid cloneDeviceNode(srcpath, devpath) hooking.write_domxml(domxml) except: sys.stderr.write('directlun before_vm_migration_destination: [unexpected error]: %s\n' % traceback.format_exc()) sys.exit(2)
sys.stderr.write('directlun: error chmod %s %s, err = %s\n' % (dirpath, mode, err)) sys.exit(2)
conditional_block
before_vm_migrate_destination.py
#!/usr/bin/python import os import sys import grp import pwd import traceback import utils import hooking DEV_MAPPER_PATH = "/dev/mapper" DEV_DIRECTLUN_PATH = '/dev/directlun' def createdirectory(dirpath): # we don't use os.mkdir/chown because we need sudo command = ['/bin/mkdir', '-p', dirpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error mkdir %s, err = %s\n' % (dirpath, err))
sys.exit(2) mode = '755' command = ['/bin/chmod', mode, dirpath] if retcode != 0: sys.stderr.write('directlun: error chmod %s %s, err = %s\n' % (dirpath, mode, err)) sys.exit(2) def cloneDeviceNode(srcpath, devpath): """Clone a device node into a temporary private location.""" # we don't use os.remove/mknod/chmod/chown because we need sudo command = ['/bin/rm', '-f', devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error rm -f %s, err = %s\n' % (devpath, err)) sys.exit(2) stat = os.stat(srcpath) major = os.major(stat.st_rdev) minor = os.minor(stat.st_rdev) command = ['/bin/mknod', devpath, 'b', str(major), str(minor)] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error mknod %s, err = %s\n' % (devpath, err)) sys.exit(2) mode = '660' command = ['/bin/chmod', mode, devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error chmod %s to %s, err = %s\n' % (devpath, mode, err)) sys.exit(2) group = grp.getgrnam('qemu') gid = group.gr_gid user = pwd.getpwnam('qemu') uid = user.pw_uid owner = str(uid) + ':' + str(gid) command = ['/bin/chown', owner, devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error chown %s to %s, err = %s\n' % (devpath, owner, err)) sys.exit(2) if os.environ.has_key('directlun'): try: luns = os.environ['directlun'] domxml = hooking.read_domxml() createdirectory(DEV_DIRECTLUN_PATH) for lun in luns.split(','): try: lun, options = lun.split(':') except ValueError: options = '' options = options.split(';') srcpath = DEV_MAPPER_PATH + '/' + lun if not os.path.exists(srcpath): sys.stderr.write('directlun before_vm_migration_destination: device not found %s\n' % srcpath) sys.exit(2) uuid = domxml.getElementsByTagName('uuid')[0] uuid = uuid.childNodes[0].nodeValue devpath = DEV_DIRECTLUN_PATH + '/' + lun + '-' + uuid cloneDeviceNode(srcpath, devpath) hooking.write_domxml(domxml) except: sys.stderr.write('directlun before_vm_migration_destination: [unexpected error]: %s\n' % traceback.format_exc()) sys.exit(2)
random_line_split
before_vm_migrate_destination.py
#!/usr/bin/python import os import sys import grp import pwd import traceback import utils import hooking DEV_MAPPER_PATH = "/dev/mapper" DEV_DIRECTLUN_PATH = '/dev/directlun' def createdirectory(dirpath): # we don't use os.mkdir/chown because we need sudo
def cloneDeviceNode(srcpath, devpath): """Clone a device node into a temporary private location.""" # we don't use os.remove/mknod/chmod/chown because we need sudo command = ['/bin/rm', '-f', devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error rm -f %s, err = %s\n' % (devpath, err)) sys.exit(2) stat = os.stat(srcpath) major = os.major(stat.st_rdev) minor = os.minor(stat.st_rdev) command = ['/bin/mknod', devpath, 'b', str(major), str(minor)] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error mknod %s, err = %s\n' % (devpath, err)) sys.exit(2) mode = '660' command = ['/bin/chmod', mode, devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error chmod %s to %s, err = %s\n' % (devpath, mode, err)) sys.exit(2) group = grp.getgrnam('qemu') gid = group.gr_gid user = pwd.getpwnam('qemu') uid = user.pw_uid owner = str(uid) + ':' + str(gid) command = ['/bin/chown', owner, devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error chown %s to %s, err = %s\n' % (devpath, owner, err)) sys.exit(2) if os.environ.has_key('directlun'): try: luns = os.environ['directlun'] domxml = hooking.read_domxml() createdirectory(DEV_DIRECTLUN_PATH) for lun in luns.split(','): try: lun, options = lun.split(':') except ValueError: options = '' options = options.split(';') srcpath = DEV_MAPPER_PATH + '/' + lun if not os.path.exists(srcpath): sys.stderr.write('directlun before_vm_migration_destination: device not found %s\n' % srcpath) sys.exit(2) uuid = domxml.getElementsByTagName('uuid')[0] uuid = uuid.childNodes[0].nodeValue devpath = DEV_DIRECTLUN_PATH + '/' + lun + '-' + uuid cloneDeviceNode(srcpath, devpath) hooking.write_domxml(domxml) except: sys.stderr.write('directlun before_vm_migration_destination: [unexpected error]: %s\n' % traceback.format_exc()) sys.exit(2)
command = ['/bin/mkdir', '-p', dirpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error mkdir %s, err = %s\n' % (dirpath, err)) sys.exit(2) mode = '755' command = ['/bin/chmod', mode, dirpath] if retcode != 0: sys.stderr.write('directlun: error chmod %s %s, err = %s\n' % (dirpath, mode, err)) sys.exit(2)
identifier_body
before_vm_migrate_destination.py
#!/usr/bin/python import os import sys import grp import pwd import traceback import utils import hooking DEV_MAPPER_PATH = "/dev/mapper" DEV_DIRECTLUN_PATH = '/dev/directlun' def createdirectory(dirpath): # we don't use os.mkdir/chown because we need sudo command = ['/bin/mkdir', '-p', dirpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error mkdir %s, err = %s\n' % (dirpath, err)) sys.exit(2) mode = '755' command = ['/bin/chmod', mode, dirpath] if retcode != 0: sys.stderr.write('directlun: error chmod %s %s, err = %s\n' % (dirpath, mode, err)) sys.exit(2) def
(srcpath, devpath): """Clone a device node into a temporary private location.""" # we don't use os.remove/mknod/chmod/chown because we need sudo command = ['/bin/rm', '-f', devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error rm -f %s, err = %s\n' % (devpath, err)) sys.exit(2) stat = os.stat(srcpath) major = os.major(stat.st_rdev) minor = os.minor(stat.st_rdev) command = ['/bin/mknod', devpath, 'b', str(major), str(minor)] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error mknod %s, err = %s\n' % (devpath, err)) sys.exit(2) mode = '660' command = ['/bin/chmod', mode, devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error chmod %s to %s, err = %s\n' % (devpath, mode, err)) sys.exit(2) group = grp.getgrnam('qemu') gid = group.gr_gid user = pwd.getpwnam('qemu') uid = user.pw_uid owner = str(uid) + ':' + str(gid) command = ['/bin/chown', owner, devpath] retcode, out, err = utils.execCmd(command, sudo=True, raw=True) if retcode != 0: sys.stderr.write('directlun: error chown %s to %s, err = %s\n' % (devpath, owner, err)) sys.exit(2) if os.environ.has_key('directlun'): try: luns = os.environ['directlun'] domxml = hooking.read_domxml() createdirectory(DEV_DIRECTLUN_PATH) for lun in luns.split(','): try: lun, options = lun.split(':') except ValueError: options = '' options = options.split(';') srcpath = DEV_MAPPER_PATH + '/' + lun if not os.path.exists(srcpath): sys.stderr.write('directlun before_vm_migration_destination: device not found %s\n' % srcpath) sys.exit(2) uuid = domxml.getElementsByTagName('uuid')[0] uuid = uuid.childNodes[0].nodeValue devpath = DEV_DIRECTLUN_PATH + '/' + lun + '-' + uuid cloneDeviceNode(srcpath, devpath) hooking.write_domxml(domxml) except: sys.stderr.write('directlun before_vm_migration_destination: [unexpected error]: %s\n' % traceback.format_exc()) sys.exit(2)
cloneDeviceNode
identifier_name
classConsor_1_1RadioBox.js
var classConsor_1_1RadioBox = [ [ "RadioBox", "classConsor_1_1RadioBox_aae20cff4d62bf98f51a48d77599a3481.html#aae20cff4d62bf98f51a48d77599a3481", null ], [ "~RadioBox", "classConsor_1_1RadioBox_a7e6c1b1b1b6474b2f9af331f135cfe7e.html#a7e6c1b1b1b6474b2f9af331f135cfe7e", null ], [ "AddChoice", "classConsor_1_1RadioBox_ade2eaabbe0ae109c9c813be8e377f40c.html#ade2eaabbe0ae109c9c813be8e377f40c", null ], [ "CanFocus", "classConsor_1_1RadioBox_af6c1e92a0bc75cba40fbf0be7a46ecbf.html#af6c1e92a0bc75cba40fbf0be7a46ecbf", null ], [ "Draw", "classConsor_1_1RadioBox_a01d2e143fb687dc49c84d98f4a63b317.html#a01d2e143fb687dc49c84d98f4a63b317", null ], [ "ForceResize", "classConsor_1_1RadioBox_a3202dbb3efbc14314dfba446e9c2416b.html#a3202dbb3efbc14314dfba446e9c2416b", null ], [ "GetChoice", "classConsor_1_1RadioBox_a36c8226cfac515640201fe8e9631e1a9.html#a36c8226cfac515640201fe8e9631e1a9", null ], [ "GetSize", "classConsor_1_1RadioBox_a67cc2bf06e9a9d16a07dc795d3e4fcf1.html#a67cc2bf06e9a9d16a07dc795d3e4fcf1", null ], [ "HandleInput", "classConsor_1_1RadioBox_a9613819a0ec347925f14fac056c749bd.html#a9613819a0ec347925f14fac056c749bd", null ], [ "OnResize", "classConsor_1_1RadioBox_a9797064782a333895795eb9b6449b9d2.html#a9797064782a333895795eb9b6449b9d2", null ], [ "_Checkboxes", "classConsor_1_1RadioBox_a9e90f4655e491fb99734dfadeb1c46a2.html#a9e90f4655e491fb99734dfadeb1c46a2", null ],
];
[ "_FlowContainer", "classConsor_1_1RadioBox_a7461345288b9f70ef123782c95c76127.html#a7461345288b9f70ef123782c95c76127", null ], [ "OnValueChanged", "classConsor_1_1RadioBox_a3a42be4b48f0f485c5d4a6b92d2f7e3a.html#a3a42be4b48f0f485c5d4a6b92d2f7e3a", null ]
random_line_split
test_driverbase.py
# # Copyright 2015 Red Hat, Inc. # # 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 2 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import sys import inspect import unittest from mock import patch from mock import MagicMock from . import get_driver from . import get_driver_class from . import get_driver_names from .driverbase import VirtDeployDriverBase if sys.version_info[0] == 3: # pragma: no cover builtin_import = 'builtins.__import__' else: # pragma: no cover builtin_import = '__builtin__.__import__' def try_import(spec): def fake_import(name, globals={}, locals={}, fromlist=[], level=0): try: return spec(name, globals, locals, fromlist, level) except ImportError: return MagicMock() return fake_import class TestVirtDeployDriverBase(unittest.TestCase): def _get_driver_methods(self): return inspect.getmembers(VirtDeployDriverBase, inspect.ismethod) def _get_driver_class(self, name):
def _get_driver(self, name): with patch(builtin_import, spec=True, new_callable=try_import): return get_driver(name) def test_base_not_implemented(self): driver = VirtDeployDriverBase() for name, method in self._get_driver_methods(): spec = inspect.getargspec(method) with self.assertRaises(NotImplementedError) as cm: getattr(driver, name)(*(None,) * (len(spec.args) - 1)) self.assertEqual(cm.exception.args[0], name) def test_drivers_interface(self): for driver_name in get_driver_names(): driver = self._get_driver_class(driver_name) for name, method in self._get_driver_methods(): driver_method = getattr(driver, name) self.assertNotEqual(driver_method, method) self.assertEqual(inspect.getargspec(method), inspect.getargspec(driver_method)) def test_get_drivers(self): for driver_name in get_driver_names(): driver = self._get_driver(driver_name) self.assertTrue(isinstance(driver, VirtDeployDriverBase))
with patch(builtin_import, spec=True, new_callable=try_import): return get_driver_class(name)
identifier_body
test_driverbase.py
# # Copyright 2015 Red Hat, Inc. # # 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 2 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import sys import inspect import unittest from mock import patch from mock import MagicMock from . import get_driver from . import get_driver_class from . import get_driver_names from .driverbase import VirtDeployDriverBase if sys.version_info[0] == 3: # pragma: no cover builtin_import = 'builtins.__import__' else: # pragma: no cover builtin_import = '__builtin__.__import__' def try_import(spec): def fake_import(name, globals={}, locals={}, fromlist=[], level=0): try: return spec(name, globals, locals, fromlist, level) except ImportError: return MagicMock() return fake_import class TestVirtDeployDriverBase(unittest.TestCase): def _get_driver_methods(self): return inspect.getmembers(VirtDeployDriverBase, inspect.ismethod) def _get_driver_class(self, name): with patch(builtin_import, spec=True, new_callable=try_import): return get_driver_class(name)
return get_driver(name) def test_base_not_implemented(self): driver = VirtDeployDriverBase() for name, method in self._get_driver_methods(): spec = inspect.getargspec(method) with self.assertRaises(NotImplementedError) as cm: getattr(driver, name)(*(None,) * (len(spec.args) - 1)) self.assertEqual(cm.exception.args[0], name) def test_drivers_interface(self): for driver_name in get_driver_names(): driver = self._get_driver_class(driver_name) for name, method in self._get_driver_methods(): driver_method = getattr(driver, name) self.assertNotEqual(driver_method, method) self.assertEqual(inspect.getargspec(method), inspect.getargspec(driver_method)) def test_get_drivers(self): for driver_name in get_driver_names(): driver = self._get_driver(driver_name) self.assertTrue(isinstance(driver, VirtDeployDriverBase))
def _get_driver(self, name): with patch(builtin_import, spec=True, new_callable=try_import):
random_line_split
test_driverbase.py
# # Copyright 2015 Red Hat, Inc. # # 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 2 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import sys import inspect import unittest from mock import patch from mock import MagicMock from . import get_driver from . import get_driver_class from . import get_driver_names from .driverbase import VirtDeployDriverBase if sys.version_info[0] == 3: # pragma: no cover builtin_import = 'builtins.__import__' else: # pragma: no cover builtin_import = '__builtin__.__import__' def try_import(spec): def fake_import(name, globals={}, locals={}, fromlist=[], level=0): try: return spec(name, globals, locals, fromlist, level) except ImportError: return MagicMock() return fake_import class TestVirtDeployDriverBase(unittest.TestCase): def _get_driver_methods(self): return inspect.getmembers(VirtDeployDriverBase, inspect.ismethod) def _get_driver_class(self, name): with patch(builtin_import, spec=True, new_callable=try_import): return get_driver_class(name) def _get_driver(self, name): with patch(builtin_import, spec=True, new_callable=try_import): return get_driver(name) def test_base_not_implemented(self): driver = VirtDeployDriverBase() for name, method in self._get_driver_methods(): spec = inspect.getargspec(method) with self.assertRaises(NotImplementedError) as cm: getattr(driver, name)(*(None,) * (len(spec.args) - 1)) self.assertEqual(cm.exception.args[0], name) def test_drivers_interface(self): for driver_name in get_driver_names(): driver = self._get_driver_class(driver_name) for name, method in self._get_driver_methods(): driver_method = getattr(driver, name) self.assertNotEqual(driver_method, method) self.assertEqual(inspect.getargspec(method), inspect.getargspec(driver_method)) def
(self): for driver_name in get_driver_names(): driver = self._get_driver(driver_name) self.assertTrue(isinstance(driver, VirtDeployDriverBase))
test_get_drivers
identifier_name
test_driverbase.py
# # Copyright 2015 Red Hat, Inc. # # 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 2 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, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import sys import inspect import unittest from mock import patch from mock import MagicMock from . import get_driver from . import get_driver_class from . import get_driver_names from .driverbase import VirtDeployDriverBase if sys.version_info[0] == 3: # pragma: no cover builtin_import = 'builtins.__import__' else: # pragma: no cover builtin_import = '__builtin__.__import__' def try_import(spec): def fake_import(name, globals={}, locals={}, fromlist=[], level=0): try: return spec(name, globals, locals, fromlist, level) except ImportError: return MagicMock() return fake_import class TestVirtDeployDriverBase(unittest.TestCase): def _get_driver_methods(self): return inspect.getmembers(VirtDeployDriverBase, inspect.ismethod) def _get_driver_class(self, name): with patch(builtin_import, spec=True, new_callable=try_import): return get_driver_class(name) def _get_driver(self, name): with patch(builtin_import, spec=True, new_callable=try_import): return get_driver(name) def test_base_not_implemented(self): driver = VirtDeployDriverBase() for name, method in self._get_driver_methods():
def test_drivers_interface(self): for driver_name in get_driver_names(): driver = self._get_driver_class(driver_name) for name, method in self._get_driver_methods(): driver_method = getattr(driver, name) self.assertNotEqual(driver_method, method) self.assertEqual(inspect.getargspec(method), inspect.getargspec(driver_method)) def test_get_drivers(self): for driver_name in get_driver_names(): driver = self._get_driver(driver_name) self.assertTrue(isinstance(driver, VirtDeployDriverBase))
spec = inspect.getargspec(method) with self.assertRaises(NotImplementedError) as cm: getattr(driver, name)(*(None,) * (len(spec.args) - 1)) self.assertEqual(cm.exception.args[0], name)
conditional_block
converter.py
"""Funções de conversão usada pelo scraper do Itaú.""" import datetime from dateutil.parser import parse from dateutil.relativedelta import relativedelta from decimal import Decimal def date(s): """Converte strings 'DD/MM' em datetime.date. Leva em consideração ano anterior para meses maiores que o mês corrente. """ dt = parse(s, dayfirst=True) # Se o mês do lançamento > mês atual, o lançamento é do ano passado. if dt.month > datetime.date.today().month:
dt = dt.date() return dt def decimal(s): """Converte strings para Decimal('-9876.54'). >>> assert decimal('9.876,54-') == Decimal('-9876.54') >>> assert decimal('9.876,54 D') == Decimal('-9876.54') >>> assert decimal('9.876,54 C') == Decimal('9876.54') >>> assert decimal('R$ 9.876,54') == Decimal('9876.54') >>> assert decimal('R$ -9.876,54') == Decimal('-9876.54') """ s = s.replace('.', '') s = s.replace(',', '.') if s.startswith('R$ '): s = s[3:] if s.endswith('-'): s = s[-1] + s[:-1] elif s.endswith(' D'): s = '-' + s[:-2] elif s.endswith(' C'): s = s[:-2] return Decimal(s) def is_balance(s): """Retorna True quando s é uma entrada de saldo em vez de lançamento.""" return s in ('S A L D O', '(-) SALDO A LIBERAR', 'SALDO FINAL DISPONIVEL', 'SALDO ANTERIOR') def statements(iterable): """Converte dados do extrato de texto para tipos Python. Linhas de saldo são ignoradas. Entrada: (('21/07', 'Lançamento', '9.876,54-'), ...) Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...) """ return ((date(a), b, decimal(c)) for a, b, c in iterable if not is_balance(b)) def card_statements(iterable): """Converte dados do extrato do cartão de texto para tipos Python. Entrada: (('21/07', 'Lançamento', '9.876,54 D'), ...) Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...) """ return ((date(a), b, decimal(c)) for a, b, c in iterable) def card_summary(iterable): """Converte dados do resumo do cartão de texto para tipos Python. Entrada: (('Item do Resumo', 'R$ -9.876,54'), ...) Saída..: (('Item do Resumo', Decimal('-9876.54')), ...) """ return ((a, decimal(b)) for a, b in iterable)
dt += relativedelta(years=-1)
random_line_split
converter.py
"""Funções de conversão usada pelo scraper do Itaú.""" import datetime from dateutil.parser import parse from dateutil.relativedelta import relativedelta from decimal import Decimal def date(s): """Converte strings 'DD/MM' em datetime.date. Leva em consideração ano anterior para meses maiores que o mês corrente. """ dt = parse(s, dayfirst=True) # Se o mês do lançamento > mês atual, o lançamento é do ano passado. if dt.month > datetime.date.today().month: dt += relativedelta(years=-1) dt = dt.date() return dt def decimal(s): """Converte strings para Decimal('-9876.54'). >>> assert decimal('9.876,54-') == Decimal('-9876.54') >>> assert decimal('9.876,54 D') == Decimal('-9876.54') >>> assert decimal('9.876,54 C') == Decimal('9876.54') >>> assert decimal('R$ 9.876,54') == Decimal('9876.54') >>> assert decimal('R$ -9.876,54') == Decimal('-9876.54') """ s = s.replace('.', '') s = s.replace(',', '.') if s.startswith('R$ '): s = s[3:] if s.endswith('-'): s = s[-1] + s[:-1] elif s.endswith(' D'): s = '-' + s[:-2] elif s.endswith(' C'): s = s[:-2] return Decimal(s) def is_balance(s): """Retorna True quando s é uma entrada de saldo em vez de lançamento.""" return s in ('S A L D O', '(-) SALDO A LIBERAR', 'SALDO FINAL DISPONIVEL', 'SALDO ANTERIOR') def statements(iterable): """Converte dados do extrato de texto para tipos Python. Linhas de saldo são ignoradas. Entrada: (('21/07', 'Lançamento', '9.876,54-'), ...) Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...) """ return ((date(a), b, decimal(c)) for a, b, c in iterable if not is_balance(b)) def card_statements(iterable): """Converte dados do extrato do cartão de texto para tipos Python. Entrada: (('21/07', 'Lançamento', '9.876,54 D'), ...) Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...) """ return ((date(a), b, decimal(c)) for a, b, c in iterable) def card_summary(iterable): """Converte dados do r
esumo do cartão de texto para tipos Python. Entrada: (('Item do Resumo', 'R$ -9.876,54'), ...) Saída..: (('Item do Resumo', Decimal('-9876.54')), ...) """ return ((a, decimal(b)) for a, b in iterable)
identifier_body
converter.py
"""Funções de conversão usada pelo scraper do Itaú.""" import datetime from dateutil.parser import parse from dateutil.relativedelta import relativedelta from decimal import Decimal def date(s): """Converte strings 'DD/MM' em datetime.date. Leva em consideração ano anterior para meses maiores que o mês corrente. """ dt = parse(s, dayfirst=True) # Se o mês do lançamento > mês atual, o lançamento é do ano passado. if dt.month > datetime.date.today().month: dt += relativedelta(years=-1) dt = dt.date() return dt def decimal(s): """Converte strings para Decimal('-9876.54'). >>> assert decimal('9.876,54-') == Decimal('-9876.54') >>> assert decimal('9.876,54 D') == Decimal('-9876.54') >>> assert decimal('9.876,54 C') == Decimal('9876.54') >>> assert decimal('R$ 9.876,54') == Decimal('9876.54') >>> assert decimal('R$ -9.876,54') == Decimal('-9876.54') """ s = s.replace('.', '') s = s.replace(',', '.') if s.startswith('R$ '): s = s[3:] if s.endswith('-'): s = s[-1] +
endswith(' D'): s = '-' + s[:-2] elif s.endswith(' C'): s = s[:-2] return Decimal(s) def is_balance(s): """Retorna True quando s é uma entrada de saldo em vez de lançamento.""" return s in ('S A L D O', '(-) SALDO A LIBERAR', 'SALDO FINAL DISPONIVEL', 'SALDO ANTERIOR') def statements(iterable): """Converte dados do extrato de texto para tipos Python. Linhas de saldo são ignoradas. Entrada: (('21/07', 'Lançamento', '9.876,54-'), ...) Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...) """ return ((date(a), b, decimal(c)) for a, b, c in iterable if not is_balance(b)) def card_statements(iterable): """Converte dados do extrato do cartão de texto para tipos Python. Entrada: (('21/07', 'Lançamento', '9.876,54 D'), ...) Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...) """ return ((date(a), b, decimal(c)) for a, b, c in iterable) def card_summary(iterable): """Converte dados do resumo do cartão de texto para tipos Python. Entrada: (('Item do Resumo', 'R$ -9.876,54'), ...) Saída..: (('Item do Resumo', Decimal('-9876.54')), ...) """ return ((a, decimal(b)) for a, b in iterable)
s[:-1] elif s.
conditional_block
converter.py
"""Funções de conversão usada pelo scraper do Itaú.""" import datetime from dateutil.parser import parse from dateutil.relativedelta import relativedelta from decimal import Decimal def date(s): """Converte strings 'DD/MM' em datetime.date. Leva em consideração ano anterior para meses maiores que o mês corrente. """ dt = parse(s, dayfirst=True) # Se o mês do lançamento > mês atual, o lançamento é do ano passado. if dt.month > datetime.date.today().month: dt += relativedelta(years=-1) dt = dt.date() return dt def decimal(s):
Converte strings para Decimal('-9876.54'). >>> assert decimal('9.876,54-') == Decimal('-9876.54') >>> assert decimal('9.876,54 D') == Decimal('-9876.54') >>> assert decimal('9.876,54 C') == Decimal('9876.54') >>> assert decimal('R$ 9.876,54') == Decimal('9876.54') >>> assert decimal('R$ -9.876,54') == Decimal('-9876.54') """ s = s.replace('.', '') s = s.replace(',', '.') if s.startswith('R$ '): s = s[3:] if s.endswith('-'): s = s[-1] + s[:-1] elif s.endswith(' D'): s = '-' + s[:-2] elif s.endswith(' C'): s = s[:-2] return Decimal(s) def is_balance(s): """Retorna True quando s é uma entrada de saldo em vez de lançamento.""" return s in ('S A L D O', '(-) SALDO A LIBERAR', 'SALDO FINAL DISPONIVEL', 'SALDO ANTERIOR') def statements(iterable): """Converte dados do extrato de texto para tipos Python. Linhas de saldo são ignoradas. Entrada: (('21/07', 'Lançamento', '9.876,54-'), ...) Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...) """ return ((date(a), b, decimal(c)) for a, b, c in iterable if not is_balance(b)) def card_statements(iterable): """Converte dados do extrato do cartão de texto para tipos Python. Entrada: (('21/07', 'Lançamento', '9.876,54 D'), ...) Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...) """ return ((date(a), b, decimal(c)) for a, b, c in iterable) def card_summary(iterable): """Converte dados do resumo do cartão de texto para tipos Python. Entrada: (('Item do Resumo', 'R$ -9.876,54'), ...) Saída..: (('Item do Resumo', Decimal('-9876.54')), ...) """ return ((a, decimal(b)) for a, b in iterable)
"""
identifier_name
navigation-control.directive.ts
import { AfterContentInit, Directive, Host, Input } from '@angular/core'; import { NavigationControl } from 'mapbox-gl'; import { MapService } from '../map/map.service'; import { ControlComponent } from './control.component'; @Directive({ selector: '[mglNavigation]', }) export class NavigationControlDirective implements AfterContentInit { /* Init inputs */ @Input() showCompass?: boolean; @Input() showZoom?: boolean; constructor( private MapService: MapService, @Host() private ControlComponent: ControlComponent<NavigationControl> ) {}
() { this.MapService.mapCreated$.subscribe(() => { if (this.ControlComponent.control) { throw new Error('Another control is already set for this control'); } const options: { showCompass?: boolean; showZoom?: boolean } = {}; if (this.showCompass !== undefined) { options.showCompass = this.showCompass; } if (this.showZoom !== undefined) { options.showZoom = this.showZoom; } this.ControlComponent.control = new NavigationControl(options); this.MapService.addControl( this.ControlComponent.control, this.ControlComponent.position ); }); } }
ngAfterContentInit
identifier_name
navigation-control.directive.ts
import { AfterContentInit, Directive, Host, Input } from '@angular/core'; import { NavigationControl } from 'mapbox-gl'; import { MapService } from '../map/map.service'; import { ControlComponent } from './control.component'; @Directive({ selector: '[mglNavigation]', }) export class NavigationControlDirective implements AfterContentInit { /* Init inputs */ @Input() showCompass?: boolean; @Input() showZoom?: boolean; constructor( private MapService: MapService, @Host() private ControlComponent: ControlComponent<NavigationControl> ) {} ngAfterContentInit() { this.MapService.mapCreated$.subscribe(() => { if (this.ControlComponent.control) { throw new Error('Another control is already set for this control'); } const options: { showCompass?: boolean; showZoom?: boolean } = {}; if (this.showCompass !== undefined)
if (this.showZoom !== undefined) { options.showZoom = this.showZoom; } this.ControlComponent.control = new NavigationControl(options); this.MapService.addControl( this.ControlComponent.control, this.ControlComponent.position ); }); } }
{ options.showCompass = this.showCompass; }
conditional_block
navigation-control.directive.ts
import { AfterContentInit, Directive, Host, Input } from '@angular/core';
@Directive({ selector: '[mglNavigation]', }) export class NavigationControlDirective implements AfterContentInit { /* Init inputs */ @Input() showCompass?: boolean; @Input() showZoom?: boolean; constructor( private MapService: MapService, @Host() private ControlComponent: ControlComponent<NavigationControl> ) {} ngAfterContentInit() { this.MapService.mapCreated$.subscribe(() => { if (this.ControlComponent.control) { throw new Error('Another control is already set for this control'); } const options: { showCompass?: boolean; showZoom?: boolean } = {}; if (this.showCompass !== undefined) { options.showCompass = this.showCompass; } if (this.showZoom !== undefined) { options.showZoom = this.showZoom; } this.ControlComponent.control = new NavigationControl(options); this.MapService.addControl( this.ControlComponent.control, this.ControlComponent.position ); }); } }
import { NavigationControl } from 'mapbox-gl'; import { MapService } from '../map/map.service'; import { ControlComponent } from './control.component';
random_line_split
api.service.ts
/** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (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. */ import { HttpClient, HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Elapsed } from './elapsed'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) {} accessNormalEndpoint(): Observable<HttpResponse<Elapsed>> { return this.http.get<Elapsed>('normal', {observe: 'response'}); } accessBenchEndpoint(): Observable<HttpResponse<Elapsed>> { return this.http.get<Elapsed>('bench', {observe: 'response'}); } }
* you may not use this file except in compliance with the License.
random_line_split
api.service.ts
/** * Copyright 2021 Google LLC * * 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. */ import { HttpClient, HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Elapsed } from './elapsed'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) {} accessNormalEndpoint(): Observable<HttpResponse<Elapsed>> { return this.http.get<Elapsed>('normal', {observe: 'response'}); } accessBenchEndpoint(): Observable<HttpResponse<Elapsed>>
}
{ return this.http.get<Elapsed>('bench', {observe: 'response'}); }
identifier_body
api.service.ts
/** * Copyright 2021 Google LLC * * 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. */ import { HttpClient, HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Elapsed } from './elapsed'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) {}
(): Observable<HttpResponse<Elapsed>> { return this.http.get<Elapsed>('normal', {observe: 'response'}); } accessBenchEndpoint(): Observable<HttpResponse<Elapsed>> { return this.http.get<Elapsed>('bench', {observe: 'response'}); } }
accessNormalEndpoint
identifier_name
tools.component.ts
import { Component, HostListener, Input, OnInit } from '@angular/core'; import { Highlights } from '../highlights'; @Component({ selector: 'kirjs-tools', templateUrl: './tools.component.html', styleUrls: ['./tools.component.css'] }) export class ToolsComponent implements OnInit { @Input() game; @Input() highlights; tools = [ { name: 'next', action: function(point, game) { game.moveTo(point); }, init: function() { return this; } }, { name: 'red-maybe', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-transparent cell-2'); }, init: function() { return this; } }, { name: 'black-maybe', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-transparent cell-1'); }, init: function() { return this; } }, { name: 'highlight', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-yellow'); }, init: function() { return this; } }, { name: 'highlight2', action: function(point, game, highlights: Highlights) { highlights.toggle(point, 'highlight-orange'); }, init: function() { return this; } }, { name: 'clear', action: function(point, game, highlights) { highlights.clear(point); }, init: function() { return this; } }, { name: 'clear-all', init: function(game, highlights: Highlights) { highlights.clear(); } }, { name: 'undo', init: function(game, highlights: Highlights) { highlights.undo(); } }, { name: 'redo', init: function(game, highlights: Highlights) { highlights.redo(); } } ]; selectedTool: any; @HostListener('window:keydown', ['$event.keyCode'])
(a: number) { if (a >= 48 && a <= 57) { this.handle(this.tools[a - 49]); } } handle(tool) { const selected = tool.init(this.game, this.highlights); if (selected) { this.selectedTool = tool; } } constructor() { this.selectedTool = this.tools[0]; } ngOnInit() {} }
shortcut
identifier_name
tools.component.ts
import { Component, HostListener, Input, OnInit } from '@angular/core'; import { Highlights } from '../highlights'; @Component({ selector: 'kirjs-tools', templateUrl: './tools.component.html', styleUrls: ['./tools.component.css'] }) export class ToolsComponent implements OnInit { @Input() game; @Input() highlights; tools = [ { name: 'next', action: function(point, game) { game.moveTo(point); }, init: function() { return this; } }, { name: 'red-maybe', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-transparent cell-2'); }, init: function() { return this; } }, { name: 'black-maybe', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-transparent cell-1'); }, init: function() { return this; } }, { name: 'highlight', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-yellow'); }, init: function() { return this; } }, { name: 'highlight2', action: function(point, game, highlights: Highlights) { highlights.toggle(point, 'highlight-orange'); }, init: function() { return this; } }, { name: 'clear', action: function(point, game, highlights) { highlights.clear(point); }, init: function() { return this; } }, { name: 'clear-all', init: function(game, highlights: Highlights) { highlights.clear(); } }, { name: 'undo', init: function(game, highlights: Highlights) { highlights.undo(); } }, { name: 'redo', init: function(game, highlights: Highlights) { highlights.redo(); } } ]; selectedTool: any; @HostListener('window:keydown', ['$event.keyCode']) shortcut(a: number) { if (a >= 48 && a <= 57)
} handle(tool) { const selected = tool.init(this.game, this.highlights); if (selected) { this.selectedTool = tool; } } constructor() { this.selectedTool = this.tools[0]; } ngOnInit() {} }
{ this.handle(this.tools[a - 49]); }
conditional_block
tools.component.ts
import { Component, HostListener, Input, OnInit } from '@angular/core'; import { Highlights } from '../highlights'; @Component({ selector: 'kirjs-tools', templateUrl: './tools.component.html', styleUrls: ['./tools.component.css'] }) export class ToolsComponent implements OnInit { @Input() game; @Input() highlights; tools = [ { name: 'next', action: function(point, game) { game.moveTo(point); }, init: function() { return this; } }, { name: 'red-maybe', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-transparent cell-2'); }, init: function() { return this; } }, { name: 'black-maybe', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-transparent cell-1'); }, init: function() { return this; } }, { name: 'highlight', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-yellow'); }, init: function() { return this; } }, { name: 'highlight2', action: function(point, game, highlights: Highlights) { highlights.toggle(point, 'highlight-orange'); }, init: function() { return this; } }, { name: 'clear', action: function(point, game, highlights) { highlights.clear(point); }, init: function() { return this; } }, { name: 'clear-all', init: function(game, highlights: Highlights) { highlights.clear(); } }, { name: 'undo', init: function(game, highlights: Highlights) { highlights.undo(); } }, { name: 'redo', init: function(game, highlights: Highlights) { highlights.redo(); } } ]; selectedTool: any; @HostListener('window:keydown', ['$event.keyCode']) shortcut(a: number) { if (a >= 48 && a <= 57) { this.handle(this.tools[a - 49]); } } handle(tool) { const selected = tool.init(this.game, this.highlights); if (selected) { this.selectedTool = tool; } } constructor() { this.selectedTool = this.tools[0]; } ngOnInit()
}
{}
identifier_body
tools.component.ts
import { Component, HostListener, Input, OnInit } from '@angular/core'; import { Highlights } from '../highlights'; @Component({ selector: 'kirjs-tools', templateUrl: './tools.component.html', styleUrls: ['./tools.component.css'] }) export class ToolsComponent implements OnInit { @Input() game; @Input() highlights; tools = [ { name: 'next', action: function(point, game) { game.moveTo(point); }, init: function() { return this; } }, { name: 'red-maybe', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-transparent cell-2'); }, init: function() { return this; } }, { name: 'black-maybe', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-transparent cell-1'); }, init: function() { return this; } }, { name: 'highlight', action: function(point, game, highlights) { highlights.toggle(point, 'highlight-yellow');
return this; } }, { name: 'highlight2', action: function(point, game, highlights: Highlights) { highlights.toggle(point, 'highlight-orange'); }, init: function() { return this; } }, { name: 'clear', action: function(point, game, highlights) { highlights.clear(point); }, init: function() { return this; } }, { name: 'clear-all', init: function(game, highlights: Highlights) { highlights.clear(); } }, { name: 'undo', init: function(game, highlights: Highlights) { highlights.undo(); } }, { name: 'redo', init: function(game, highlights: Highlights) { highlights.redo(); } } ]; selectedTool: any; @HostListener('window:keydown', ['$event.keyCode']) shortcut(a: number) { if (a >= 48 && a <= 57) { this.handle(this.tools[a - 49]); } } handle(tool) { const selected = tool.init(this.game, this.highlights); if (selected) { this.selectedTool = tool; } } constructor() { this.selectedTool = this.tools[0]; } ngOnInit() {} }
}, init: function() {
random_line_split
uds.rs
use std::io::{Read, Write}; use std::mem; use std::net::Shutdown; use std::os::unix::prelude::*; use std::path::Path; use libc; use {io, Ready, Poll, PollOpt, Token}; use event::Evented; use sys::unix::{cvt, Io}; use sys::unix::io::{set_nonblock, set_cloexec}; trait MyInto<T> { fn my_into(self) -> T; } impl MyInto<u32> for usize { fn my_into(self) -> u32 { self as u32 } } impl MyInto<usize> for usize { fn my_into(self) -> usize { self } } unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> { let mut addr: libc::sockaddr_un = mem::zeroed(); addr.sun_family = libc::AF_UNIX as libc::sa_family_t; let bytes = path.as_os_str().as_bytes(); if bytes.len() >= addr.sun_path.len() { return Err(io::Error::new(io::ErrorKind::InvalidInput, "path must be shorter than SUN_LEN")) } for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) { *dst = *src as libc::c_char; } // null byte for pathname addresses is already there because we zeroed the // struct let mut len = sun_path_offset() + bytes.len(); match bytes.get(0) { Some(&0) | None =>
Some(_) => len += 1, } Ok((addr, len as libc::socklen_t)) } fn sun_path_offset() -> usize { unsafe { // Work with an actual instance of the type since using a null pointer is UB let addr: libc::sockaddr_un = mem::uninitialized(); let base = &addr as *const _ as usize; let path = &addr.sun_path as *const _ as usize; path - base } } #[derive(Debug)] pub struct UnixSocket { io: Io, } impl UnixSocket { /// Returns a new, unbound, non-blocking Unix domain socket pub fn stream() -> io::Result<UnixSocket> { #[cfg(target_os = "linux")] use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK}; #[cfg(not(target_os = "linux"))] const SOCK_CLOEXEC: libc::c_int = 0; #[cfg(not(target_os = "linux"))] const SOCK_NONBLOCK: libc::c_int = 0; unsafe { if cfg!(target_os = "linux") { let flags = libc::SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK; match cvt(libc::socket(libc::AF_UNIX, flags, 0)) { Ok(fd) => return Ok(UnixSocket::from_raw_fd(fd)), Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} Err(e) => return Err(e), } } let fd = cvt(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0))?; let fd = UnixSocket::from_raw_fd(fd); set_cloexec(fd.as_raw_fd())?; set_nonblock(fd.as_raw_fd())?; Ok(fd) } } /// Connect the socket to the specified address pub fn connect<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; cvt(libc::connect(self.as_raw_fd(), &addr as *const _ as *const _, len))?; Ok(()) } } /// Listen for incoming requests pub fn listen(&self, backlog: usize) -> io::Result<()> { unsafe { cvt(libc::listen(self.as_raw_fd(), backlog as i32))?; Ok(()) } } pub fn accept(&self) -> io::Result<UnixSocket> { unsafe { let fd = cvt(libc::accept(self.as_raw_fd(), 0 as *mut _, 0 as *mut _))?; let fd = Io::from_raw_fd(fd); set_cloexec(fd.as_raw_fd())?; set_nonblock(fd.as_raw_fd())?; Ok(UnixSocket { io: fd }) } } /// Bind the socket to the specified address #[cfg(not(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android")))] pub fn bind<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; cvt(libc::bind(self.as_raw_fd(), &addr as *const _ as *const _, len))?; Ok(()) } } #[cfg(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android"))] pub fn bind<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; let len_i32 = len as i32; cvt(libc::bind(self.as_raw_fd(), &addr as *const _ as *const _, len_i32))?; Ok(()) } } pub fn try_clone(&self) -> io::Result<UnixSocket> { Ok(UnixSocket { io: self.io.try_clone()? }) } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { let how = match how { Shutdown::Read => libc::SHUT_RD, Shutdown::Write => libc::SHUT_WR, Shutdown::Both => libc::SHUT_RDWR, }; unsafe { cvt(libc::shutdown(self.as_raw_fd(), how))?; Ok(()) } } pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> { unsafe { let mut iov = libc::iovec { iov_base: buf.as_mut_ptr() as *mut _, iov_len: buf.len(), }; struct Cmsg { hdr: libc::cmsghdr, data: [libc::c_int; 1], } let mut cmsg: Cmsg = mem::zeroed(); let mut msg: libc::msghdr = mem::zeroed(); msg.msg_iov = &mut iov; msg.msg_iovlen = 1; msg.msg_control = &mut cmsg as *mut _ as *mut _; msg.msg_controllen = mem::size_of_val(&cmsg).my_into(); let bytes = cvt(libc::recvmsg(self.as_raw_fd(), &mut msg, 0))?; const SCM_RIGHTS: libc::c_int = 1; let fd = if cmsg.hdr.cmsg_level == libc::SOL_SOCKET && cmsg.hdr.cmsg_type == SCM_RIGHTS { Some(cmsg.data[0]) } else { None }; Ok((bytes as usize, fd)) } } pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> { unsafe { let mut iov = libc::iovec { iov_base: buf.as_ptr() as *mut _, iov_len: buf.len(), }; struct Cmsg { hdr: libc::cmsghdr, data: [libc::c_int; 1], } let mut cmsg: Cmsg = mem::zeroed(); cmsg.hdr.cmsg_len = mem::size_of_val(&cmsg).my_into(); cmsg.hdr.cmsg_level = libc::SOL_SOCKET; cmsg.hdr.cmsg_type = 1; // SCM_RIGHTS cmsg.data[0] = fd; let mut msg: libc::msghdr = mem::zeroed(); msg.msg_iov = &mut iov; msg.msg_iovlen = 1; msg.msg_control = &mut cmsg as *mut _ as *mut _; msg.msg_controllen = mem::size_of_val(&cmsg).my_into(); let bytes = cvt(libc::sendmsg(self.as_raw_fd(), &msg, 0))?; Ok(bytes as usize) } } } impl Read for UnixSocket { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.io.read(buf) } } impl Write for UnixSocket { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.io.write(buf) } fn flush(&mut self) -> io::Result<()> { self.io.flush() } } impl Evented for UnixSocket { fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.io.register(poll, token, interest, opts) } fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.io.reregister(poll, token, interest, opts) } fn deregister(&self, poll: &Poll) -> io::Result<()> { self.io.deregister(poll) } } impl From<Io> for UnixSocket { fn from(io: Io) -> UnixSocket { UnixSocket { io: io } } } impl FromRawFd for UnixSocket { unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket { UnixSocket { io: Io::from_raw_fd(fd) } } } impl IntoRawFd for UnixSocket { fn into_raw_fd(self) -> RawFd { self.io.into_raw_fd() } } impl AsRawFd for UnixSocket { fn as_raw_fd(&self) -> RawFd { self.io.as_raw_fd() } }
{}
conditional_block
uds.rs
use std::io::{Read, Write}; use std::mem; use std::net::Shutdown; use std::os::unix::prelude::*; use std::path::Path; use libc; use {io, Ready, Poll, PollOpt, Token}; use event::Evented; use sys::unix::{cvt, Io}; use sys::unix::io::{set_nonblock, set_cloexec}; trait MyInto<T> { fn my_into(self) -> T; } impl MyInto<u32> for usize { fn my_into(self) -> u32 { self as u32 } } impl MyInto<usize> for usize { fn my_into(self) -> usize { self } } unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> { let mut addr: libc::sockaddr_un = mem::zeroed(); addr.sun_family = libc::AF_UNIX as libc::sa_family_t; let bytes = path.as_os_str().as_bytes(); if bytes.len() >= addr.sun_path.len() { return Err(io::Error::new(io::ErrorKind::InvalidInput, "path must be shorter than SUN_LEN")) } for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) { *dst = *src as libc::c_char; } // null byte for pathname addresses is already there because we zeroed the // struct let mut len = sun_path_offset() + bytes.len(); match bytes.get(0) { Some(&0) | None => {} Some(_) => len += 1, } Ok((addr, len as libc::socklen_t)) } fn sun_path_offset() -> usize { unsafe { // Work with an actual instance of the type since using a null pointer is UB let addr: libc::sockaddr_un = mem::uninitialized(); let base = &addr as *const _ as usize; let path = &addr.sun_path as *const _ as usize; path - base } } #[derive(Debug)] pub struct UnixSocket { io: Io, } impl UnixSocket { /// Returns a new, unbound, non-blocking Unix domain socket pub fn stream() -> io::Result<UnixSocket> { #[cfg(target_os = "linux")] use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK}; #[cfg(not(target_os = "linux"))] const SOCK_CLOEXEC: libc::c_int = 0; #[cfg(not(target_os = "linux"))] const SOCK_NONBLOCK: libc::c_int = 0; unsafe { if cfg!(target_os = "linux") { let flags = libc::SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK; match cvt(libc::socket(libc::AF_UNIX, flags, 0)) { Ok(fd) => return Ok(UnixSocket::from_raw_fd(fd)), Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} Err(e) => return Err(e), } } let fd = cvt(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0))?; let fd = UnixSocket::from_raw_fd(fd); set_cloexec(fd.as_raw_fd())?; set_nonblock(fd.as_raw_fd())?; Ok(fd) } } /// Connect the socket to the specified address pub fn connect<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; cvt(libc::connect(self.as_raw_fd(), &addr as *const _ as *const _, len))?; Ok(()) } } /// Listen for incoming requests pub fn
(&self, backlog: usize) -> io::Result<()> { unsafe { cvt(libc::listen(self.as_raw_fd(), backlog as i32))?; Ok(()) } } pub fn accept(&self) -> io::Result<UnixSocket> { unsafe { let fd = cvt(libc::accept(self.as_raw_fd(), 0 as *mut _, 0 as *mut _))?; let fd = Io::from_raw_fd(fd); set_cloexec(fd.as_raw_fd())?; set_nonblock(fd.as_raw_fd())?; Ok(UnixSocket { io: fd }) } } /// Bind the socket to the specified address #[cfg(not(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android")))] pub fn bind<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; cvt(libc::bind(self.as_raw_fd(), &addr as *const _ as *const _, len))?; Ok(()) } } #[cfg(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android"))] pub fn bind<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; let len_i32 = len as i32; cvt(libc::bind(self.as_raw_fd(), &addr as *const _ as *const _, len_i32))?; Ok(()) } } pub fn try_clone(&self) -> io::Result<UnixSocket> { Ok(UnixSocket { io: self.io.try_clone()? }) } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { let how = match how { Shutdown::Read => libc::SHUT_RD, Shutdown::Write => libc::SHUT_WR, Shutdown::Both => libc::SHUT_RDWR, }; unsafe { cvt(libc::shutdown(self.as_raw_fd(), how))?; Ok(()) } } pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> { unsafe { let mut iov = libc::iovec { iov_base: buf.as_mut_ptr() as *mut _, iov_len: buf.len(), }; struct Cmsg { hdr: libc::cmsghdr, data: [libc::c_int; 1], } let mut cmsg: Cmsg = mem::zeroed(); let mut msg: libc::msghdr = mem::zeroed(); msg.msg_iov = &mut iov; msg.msg_iovlen = 1; msg.msg_control = &mut cmsg as *mut _ as *mut _; msg.msg_controllen = mem::size_of_val(&cmsg).my_into(); let bytes = cvt(libc::recvmsg(self.as_raw_fd(), &mut msg, 0))?; const SCM_RIGHTS: libc::c_int = 1; let fd = if cmsg.hdr.cmsg_level == libc::SOL_SOCKET && cmsg.hdr.cmsg_type == SCM_RIGHTS { Some(cmsg.data[0]) } else { None }; Ok((bytes as usize, fd)) } } pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> { unsafe { let mut iov = libc::iovec { iov_base: buf.as_ptr() as *mut _, iov_len: buf.len(), }; struct Cmsg { hdr: libc::cmsghdr, data: [libc::c_int; 1], } let mut cmsg: Cmsg = mem::zeroed(); cmsg.hdr.cmsg_len = mem::size_of_val(&cmsg).my_into(); cmsg.hdr.cmsg_level = libc::SOL_SOCKET; cmsg.hdr.cmsg_type = 1; // SCM_RIGHTS cmsg.data[0] = fd; let mut msg: libc::msghdr = mem::zeroed(); msg.msg_iov = &mut iov; msg.msg_iovlen = 1; msg.msg_control = &mut cmsg as *mut _ as *mut _; msg.msg_controllen = mem::size_of_val(&cmsg).my_into(); let bytes = cvt(libc::sendmsg(self.as_raw_fd(), &msg, 0))?; Ok(bytes as usize) } } } impl Read for UnixSocket { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.io.read(buf) } } impl Write for UnixSocket { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.io.write(buf) } fn flush(&mut self) -> io::Result<()> { self.io.flush() } } impl Evented for UnixSocket { fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.io.register(poll, token, interest, opts) } fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.io.reregister(poll, token, interest, opts) } fn deregister(&self, poll: &Poll) -> io::Result<()> { self.io.deregister(poll) } } impl From<Io> for UnixSocket { fn from(io: Io) -> UnixSocket { UnixSocket { io: io } } } impl FromRawFd for UnixSocket { unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket { UnixSocket { io: Io::from_raw_fd(fd) } } } impl IntoRawFd for UnixSocket { fn into_raw_fd(self) -> RawFd { self.io.into_raw_fd() } } impl AsRawFd for UnixSocket { fn as_raw_fd(&self) -> RawFd { self.io.as_raw_fd() } }
listen
identifier_name
uds.rs
use std::io::{Read, Write}; use std::mem; use std::net::Shutdown; use std::os::unix::prelude::*; use std::path::Path; use libc; use {io, Ready, Poll, PollOpt, Token}; use event::Evented; use sys::unix::{cvt, Io}; use sys::unix::io::{set_nonblock, set_cloexec}; trait MyInto<T> { fn my_into(self) -> T; } impl MyInto<u32> for usize { fn my_into(self) -> u32 { self as u32 } } impl MyInto<usize> for usize { fn my_into(self) -> usize { self } } unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> { let mut addr: libc::sockaddr_un = mem::zeroed(); addr.sun_family = libc::AF_UNIX as libc::sa_family_t; let bytes = path.as_os_str().as_bytes(); if bytes.len() >= addr.sun_path.len() { return Err(io::Error::new(io::ErrorKind::InvalidInput, "path must be shorter than SUN_LEN")) } for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) { *dst = *src as libc::c_char; } // null byte for pathname addresses is already there because we zeroed the // struct let mut len = sun_path_offset() + bytes.len(); match bytes.get(0) { Some(&0) | None => {} Some(_) => len += 1, } Ok((addr, len as libc::socklen_t)) } fn sun_path_offset() -> usize { unsafe { // Work with an actual instance of the type since using a null pointer is UB let addr: libc::sockaddr_un = mem::uninitialized(); let base = &addr as *const _ as usize; let path = &addr.sun_path as *const _ as usize; path - base } } #[derive(Debug)] pub struct UnixSocket { io: Io, } impl UnixSocket { /// Returns a new, unbound, non-blocking Unix domain socket pub fn stream() -> io::Result<UnixSocket> { #[cfg(target_os = "linux")] use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK}; #[cfg(not(target_os = "linux"))] const SOCK_CLOEXEC: libc::c_int = 0; #[cfg(not(target_os = "linux"))] const SOCK_NONBLOCK: libc::c_int = 0; unsafe { if cfg!(target_os = "linux") { let flags = libc::SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK; match cvt(libc::socket(libc::AF_UNIX, flags, 0)) { Ok(fd) => return Ok(UnixSocket::from_raw_fd(fd)), Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} Err(e) => return Err(e), } } let fd = cvt(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0))?; let fd = UnixSocket::from_raw_fd(fd); set_cloexec(fd.as_raw_fd())?; set_nonblock(fd.as_raw_fd())?; Ok(fd) } } /// Connect the socket to the specified address pub fn connect<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; cvt(libc::connect(self.as_raw_fd(), &addr as *const _ as *const _, len))?; Ok(()) } } /// Listen for incoming requests pub fn listen(&self, backlog: usize) -> io::Result<()> { unsafe { cvt(libc::listen(self.as_raw_fd(), backlog as i32))?; Ok(())
} } pub fn accept(&self) -> io::Result<UnixSocket> { unsafe { let fd = cvt(libc::accept(self.as_raw_fd(), 0 as *mut _, 0 as *mut _))?; let fd = Io::from_raw_fd(fd); set_cloexec(fd.as_raw_fd())?; set_nonblock(fd.as_raw_fd())?; Ok(UnixSocket { io: fd }) } } /// Bind the socket to the specified address #[cfg(not(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android")))] pub fn bind<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; cvt(libc::bind(self.as_raw_fd(), &addr as *const _ as *const _, len))?; Ok(()) } } #[cfg(all(any(target_arch = "aarch64", target_arch = "x86_64"), target_os = "android"))] pub fn bind<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> { unsafe { let (addr, len) = sockaddr_un(addr.as_ref())?; let len_i32 = len as i32; cvt(libc::bind(self.as_raw_fd(), &addr as *const _ as *const _, len_i32))?; Ok(()) } } pub fn try_clone(&self) -> io::Result<UnixSocket> { Ok(UnixSocket { io: self.io.try_clone()? }) } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { let how = match how { Shutdown::Read => libc::SHUT_RD, Shutdown::Write => libc::SHUT_WR, Shutdown::Both => libc::SHUT_RDWR, }; unsafe { cvt(libc::shutdown(self.as_raw_fd(), how))?; Ok(()) } } pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> { unsafe { let mut iov = libc::iovec { iov_base: buf.as_mut_ptr() as *mut _, iov_len: buf.len(), }; struct Cmsg { hdr: libc::cmsghdr, data: [libc::c_int; 1], } let mut cmsg: Cmsg = mem::zeroed(); let mut msg: libc::msghdr = mem::zeroed(); msg.msg_iov = &mut iov; msg.msg_iovlen = 1; msg.msg_control = &mut cmsg as *mut _ as *mut _; msg.msg_controllen = mem::size_of_val(&cmsg).my_into(); let bytes = cvt(libc::recvmsg(self.as_raw_fd(), &mut msg, 0))?; const SCM_RIGHTS: libc::c_int = 1; let fd = if cmsg.hdr.cmsg_level == libc::SOL_SOCKET && cmsg.hdr.cmsg_type == SCM_RIGHTS { Some(cmsg.data[0]) } else { None }; Ok((bytes as usize, fd)) } } pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> { unsafe { let mut iov = libc::iovec { iov_base: buf.as_ptr() as *mut _, iov_len: buf.len(), }; struct Cmsg { hdr: libc::cmsghdr, data: [libc::c_int; 1], } let mut cmsg: Cmsg = mem::zeroed(); cmsg.hdr.cmsg_len = mem::size_of_val(&cmsg).my_into(); cmsg.hdr.cmsg_level = libc::SOL_SOCKET; cmsg.hdr.cmsg_type = 1; // SCM_RIGHTS cmsg.data[0] = fd; let mut msg: libc::msghdr = mem::zeroed(); msg.msg_iov = &mut iov; msg.msg_iovlen = 1; msg.msg_control = &mut cmsg as *mut _ as *mut _; msg.msg_controllen = mem::size_of_val(&cmsg).my_into(); let bytes = cvt(libc::sendmsg(self.as_raw_fd(), &msg, 0))?; Ok(bytes as usize) } } } impl Read for UnixSocket { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.io.read(buf) } } impl Write for UnixSocket { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.io.write(buf) } fn flush(&mut self) -> io::Result<()> { self.io.flush() } } impl Evented for UnixSocket { fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.io.register(poll, token, interest, opts) } fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.io.reregister(poll, token, interest, opts) } fn deregister(&self, poll: &Poll) -> io::Result<()> { self.io.deregister(poll) } } impl From<Io> for UnixSocket { fn from(io: Io) -> UnixSocket { UnixSocket { io: io } } } impl FromRawFd for UnixSocket { unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket { UnixSocket { io: Io::from_raw_fd(fd) } } } impl IntoRawFd for UnixSocket { fn into_raw_fd(self) -> RawFd { self.io.into_raw_fd() } } impl AsRawFd for UnixSocket { fn as_raw_fd(&self) -> RawFd { self.io.as_raw_fd() } }
random_line_split
index.d.ts
import { FowerPlugin, ResponsiveBoolean } from '@fower/core' declare const _default: () => FowerPlugin export default _default declare module '@fower/atomic-props' { export interface AtomicProps { /** * Set line breaks to normal * * @example * ```css * { * overflow-wrap: normal; * word-break: normal; * } * ``` * * ```tsx * <Box breakNormal></Box> * ``` */ breakNormal?: ResponsiveBoolean /** * set overflow-wrap to break-word
* overflow-wrap: break-word; * } * ``` * * @example * ```tsx * <Box breakWords></Box> * ``` */ breakWords?: ResponsiveBoolean /** * set word-break to break-all * * ```css * { * word-break: break-all; * } * ``` * @example * ```tsx * <Box breakAll></Box> * ``` */ breakAll?: ResponsiveBoolean } }
* * ```css * {
random_line_split
test_public_api.py
"""Test the IPython.kernel public API Authors ------- * MinRK """
# Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import nose.tools as nt from IPython.testing import decorators as dec from IPython.kernel import launcher, connect from IPython import kernel #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- @dec.parametric def test_kms(): for base in ("", "Multi"): KM = base + "KernelManager" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_kcs(): for base in ("", "Blocking"): KM = base + "KernelClient" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_launcher(): for name in launcher.__all__: yield nt.assert_true(name in dir(kernel), name) @dec.parametric def test_connect(): for name in connect.__all__: yield nt.assert_true(name in dir(kernel), name)
#-----------------------------------------------------------------------------
random_line_split
test_public_api.py
"""Test the IPython.kernel public API Authors ------- * MinRK """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import nose.tools as nt from IPython.testing import decorators as dec from IPython.kernel import launcher, connect from IPython import kernel #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- @dec.parametric def test_kms(): for base in ("", "Multi"): KM = base + "KernelManager" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_kcs(): for base in ("", "Blocking"): KM = base + "KernelClient" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_launcher():
@dec.parametric def test_connect(): for name in connect.__all__: yield nt.assert_true(name in dir(kernel), name)
for name in launcher.__all__: yield nt.assert_true(name in dir(kernel), name)
identifier_body
test_public_api.py
"""Test the IPython.kernel public API Authors ------- * MinRK """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import nose.tools as nt from IPython.testing import decorators as dec from IPython.kernel import launcher, connect from IPython import kernel #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- @dec.parametric def test_kms(): for base in ("", "Multi"):
@dec.parametric def test_kcs(): for base in ("", "Blocking"): KM = base + "KernelClient" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_launcher(): for name in launcher.__all__: yield nt.assert_true(name in dir(kernel), name) @dec.parametric def test_connect(): for name in connect.__all__: yield nt.assert_true(name in dir(kernel), name)
KM = base + "KernelManager" yield nt.assert_true(KM in dir(kernel), KM)
conditional_block
test_public_api.py
"""Test the IPython.kernel public API Authors ------- * MinRK """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import nose.tools as nt from IPython.testing import decorators as dec from IPython.kernel import launcher, connect from IPython import kernel #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- @dec.parametric def
(): for base in ("", "Multi"): KM = base + "KernelManager" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_kcs(): for base in ("", "Blocking"): KM = base + "KernelClient" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_launcher(): for name in launcher.__all__: yield nt.assert_true(name in dir(kernel), name) @dec.parametric def test_connect(): for name in connect.__all__: yield nt.assert_true(name in dir(kernel), name)
test_kms
identifier_name
settings.py
""" Django settings for apps project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os from local_settings import SECRET_KEY, DATABASES, DEBUG # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = SECRET_KEY # SECURITY WARNING: don't run with debug turned on in production! DEBUG = DEBUG ALLOWED_HOSTS = [ 'learningdjango.in', 'localhost', '127.0.0.1' ] # Application definition INSTALLED_APPS = [ 'home.apps.HomeConfig', 'polls.apps.PollsConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'apps.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'apps.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = DATABASES # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Media Files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
random_line_split
IncrementalChecker.d.ts
import * as ts from 'typescript'; import { NormalizedMessage } from './NormalizedMessage'; import { CancellationToken } from './CancellationToken'; import * as minimatch from 'minimatch'; import { IncrementalCheckerInterface, IncrementalCheckerParams } from './IncrementalCheckerInterface'; export declare class
implements IncrementalCheckerInterface { private linterConfigs; private files; private linter?; private linterConfig?; private linterExclusions; protected program?: ts.Program; protected programConfig?: ts.ParsedCommandLine; private watcher?; private readonly hasFixedConfig; private readonly typescript; private readonly context; private readonly programConfigFile; private readonly compilerOptions; private readonly createNormalizedMessageFromDiagnostic; private readonly linterConfigFile; private readonly linterAutoFix; private readonly createNormalizedMessageFromRuleFailure; private readonly eslinter; private readonly watchPaths; private readonly workNumber; private readonly workDivision; private readonly vue; private readonly checkSyntacticErrors; private readonly resolveModuleName; private readonly resolveTypeReferenceDirective; constructor({ typescript, context, programConfigFile, compilerOptions, createNormalizedMessageFromDiagnostic, linterConfigFile, linterAutoFix, createNormalizedMessageFromRuleFailure, eslinter, watchPaths, workNumber, workDivision, vue, checkSyntacticErrors, resolveModuleName, resolveTypeReferenceDirective }: IncrementalCheckerParams); static loadProgramConfig(typescript: typeof ts, configFile: string, compilerOptions: object): ts.ParsedCommandLine; private getLinterConfig; private static createProgram; private createLinter; hasLinter(): boolean; hasEsLinter(): boolean; static isFileExcluded(filePath: string, linterExclusions: minimatch.IMinimatch[]): boolean; nextIteration(): void; private loadVueProgram; private loadDefaultProgram; getDiagnostics(cancellationToken: CancellationToken): Promise<NormalizedMessage[]>; getLints(cancellationToken: CancellationToken): NormalizedMessage[]; getEsLints(cancellationToken: CancellationToken): NormalizedMessage[]; }
IncrementalChecker
identifier_name
IncrementalChecker.d.ts
import * as ts from 'typescript'; import { NormalizedMessage } from './NormalizedMessage'; import { CancellationToken } from './CancellationToken'; import * as minimatch from 'minimatch'; import { IncrementalCheckerInterface, IncrementalCheckerParams } from './IncrementalCheckerInterface'; export declare class IncrementalChecker implements IncrementalCheckerInterface { private linterConfigs; private files; private linter?; private linterConfig?; private linterExclusions; protected program?: ts.Program; protected programConfig?: ts.ParsedCommandLine; private watcher?; private readonly hasFixedConfig; private readonly typescript; private readonly context; private readonly programConfigFile; private readonly compilerOptions; private readonly createNormalizedMessageFromDiagnostic; private readonly linterConfigFile; private readonly linterAutoFix; private readonly createNormalizedMessageFromRuleFailure; private readonly eslinter; private readonly watchPaths; private readonly workNumber;
constructor({ typescript, context, programConfigFile, compilerOptions, createNormalizedMessageFromDiagnostic, linterConfigFile, linterAutoFix, createNormalizedMessageFromRuleFailure, eslinter, watchPaths, workNumber, workDivision, vue, checkSyntacticErrors, resolveModuleName, resolveTypeReferenceDirective }: IncrementalCheckerParams); static loadProgramConfig(typescript: typeof ts, configFile: string, compilerOptions: object): ts.ParsedCommandLine; private getLinterConfig; private static createProgram; private createLinter; hasLinter(): boolean; hasEsLinter(): boolean; static isFileExcluded(filePath: string, linterExclusions: minimatch.IMinimatch[]): boolean; nextIteration(): void; private loadVueProgram; private loadDefaultProgram; getDiagnostics(cancellationToken: CancellationToken): Promise<NormalizedMessage[]>; getLints(cancellationToken: CancellationToken): NormalizedMessage[]; getEsLints(cancellationToken: CancellationToken): NormalizedMessage[]; }
private readonly workDivision; private readonly vue; private readonly checkSyntacticErrors; private readonly resolveModuleName; private readonly resolveTypeReferenceDirective;
random_line_split
p_2_1_2_02.rs
// P_2_1_2_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing module color and positions in a grid * * MOUSE * position x : offset x * position y : offset y * left click : random position * * KEYS * 1-3 : different sets of colors * 0 : default * arrow up/down : background module size * arrow left/right : foreground module size * s : save png */ use nannou::prelude::*; use nannou::rand::rngs::StdRng; use nannou::rand::{Rng, SeedableRng}; fn main() { nannou::app(model).run(); } struct Model { tile_count: u32, act_random_seed: u64, module_color_background: Hsva, module_color_foreground: Hsva, module_alpha_background: f32, module_alpha_foreground: f32, module_radius_background: f32, module_radius_foreground: f32, } fn model(app: &App) -> Model { let _window = app .new_window() .size(600, 600) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .key_released(key_released) .build() .unwrap(); let module_alpha_background = 1.0; let module_alpha_foreground = 1.0; Model { tile_count: 20, act_random_seed: 0, module_color_background: hsva(0.0, 0.0, 0.0, module_alpha_background), module_color_foreground: hsva(0.0, 0.0, 1.0, module_alpha_foreground), module_alpha_background, module_alpha_foreground, module_radius_background: 15.0, module_radius_foreground: 7.5, } } fn vie
p: &App, model: &Model, frame: Frame) { let draw = app.draw(); let win = app.window_rect(); draw.background().color(WHITE); let mut rng = StdRng::seed_from_u64(model.act_random_seed); let mx = clamp(win.right() + app.mouse.x, 0.0, win.w()); let my = clamp(win.top() - app.mouse.y, 0.0, win.h()); for grid_y in 0..model.tile_count { for grid_x in 0..model.tile_count { let tile_w = win.w() / model.tile_count as f32; let tile_h = win.h() / model.tile_count as f32; let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32; let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32; let shift_x = rng.gen_range(-mx, mx + 1.0) / 20.0; let shift_y = rng.gen_range(-my, my + 1.0) / 20.0; draw.ellipse() .x_y(pos_x + shift_x, pos_y + shift_y) .radius(model.module_radius_background) .color(model.module_color_background); } } for grid_y in 0..model.tile_count { for grid_x in 0..model.tile_count { let tile_w = win.w() / model.tile_count as f32; let tile_h = win.h() / model.tile_count as f32; let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32; let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32; draw.ellipse() .x_y(pos_x, pos_y) .radius(model.module_radius_foreground) .color(model.module_color_foreground); } } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.act_random_seed = (random_f32() * 100000.0) as u64; } fn key_pressed(app: &App, _model: &mut Model, key: Key) { if key == Key::S { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } } fn key_released(_app: &App, model: &mut Model, key: Key) { match key { Key::Key1 => { if model .module_color_background .eq(&hsva(0.0, 0.0, 0.0, model.module_alpha_background)) { model.module_color_background = hsva(0.758, 0.73, 0.51, model.module_alpha_background); } else { model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background); } } Key::Key2 => { if model .module_color_foreground .eq(&hsva(1.0, 1.0, 1.0, model.module_alpha_foreground)) { model.module_color_foreground = hsva(0.89, 1.0, 0.77, model.module_alpha_foreground); } else { model.module_color_foreground = hsva(1.0, 1.0, 1.0, model.module_alpha_foreground); } } Key::Key3 => { if model.module_alpha_background == 1.0 { model.module_alpha_background = 0.5; model.module_alpha_foreground = 0.5; } else { model.module_alpha_background = 1.0; model.module_alpha_foreground = 1.0; } model.module_color_background.alpha = model.module_alpha_background; model.module_color_foreground.alpha = model.module_alpha_foreground; } Key::Key0 => { model.module_radius_background = 15.0; model.module_radius_foreground = 7.5; model.module_alpha_background = 1.0; model.module_alpha_foreground = 1.0; model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background); model.module_color_foreground = hsva(0.0, 0.0, 1.0, model.module_alpha_foreground); } Key::Up => { model.module_radius_background += 2.0; } Key::Down => { model.module_radius_background = 5.0.max(model.module_radius_background - 2.0); } Key::Left => { model.module_radius_foreground = 2.5.max(model.module_radius_foreground - 2.0); } Key::Right => { model.module_radius_foreground += 2.0; } _other_key => {} } }
w(ap
identifier_name
p_2_1_2_02.rs
// P_2_1_2_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing module color and positions in a grid * * MOUSE * position x : offset x * position y : offset y * left click : random position * * KEYS * 1-3 : different sets of colors * 0 : default * arrow up/down : background module size * arrow left/right : foreground module size * s : save png */ use nannou::prelude::*; use nannou::rand::rngs::StdRng; use nannou::rand::{Rng, SeedableRng}; fn main() { nannou::app(model).run(); } struct Model { tile_count: u32, act_random_seed: u64, module_color_background: Hsva, module_color_foreground: Hsva, module_alpha_background: f32, module_alpha_foreground: f32, module_radius_background: f32, module_radius_foreground: f32, } fn model(app: &App) -> Model { let _window = app .new_window() .size(600, 600) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .key_released(key_released) .build() .unwrap(); let module_alpha_background = 1.0; let module_alpha_foreground = 1.0; Model { tile_count: 20, act_random_seed: 0, module_color_background: hsva(0.0, 0.0, 0.0, module_alpha_background), module_color_foreground: hsva(0.0, 0.0, 1.0, module_alpha_foreground), module_alpha_background, module_alpha_foreground, module_radius_background: 15.0, module_radius_foreground: 7.5, } } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); let win = app.window_rect(); draw.background().color(WHITE); let mut rng = StdRng::seed_from_u64(model.act_random_seed); let mx = clamp(win.right() + app.mouse.x, 0.0, win.w()); let my = clamp(win.top() - app.mouse.y, 0.0, win.h()); for grid_y in 0..model.tile_count { for grid_x in 0..model.tile_count { let tile_w = win.w() / model.tile_count as f32; let tile_h = win.h() / model.tile_count as f32; let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32; let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32; let shift_x = rng.gen_range(-mx, mx + 1.0) / 20.0; let shift_y = rng.gen_range(-my, my + 1.0) / 20.0; draw.ellipse() .x_y(pos_x + shift_x, pos_y + shift_y) .radius(model.module_radius_background) .color(model.module_color_background); } } for grid_y in 0..model.tile_count { for grid_x in 0..model.tile_count { let tile_w = win.w() / model.tile_count as f32; let tile_h = win.h() / model.tile_count as f32; let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32; let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32; draw.ellipse() .x_y(pos_x, pos_y) .radius(model.module_radius_foreground) .color(model.module_color_foreground); } } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.act_random_seed = (random_f32() * 100000.0) as u64; } fn key_pressed(app: &App, _model: &mut Model, key: Key) { if key == Key::S { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } } fn key_released(_app: &App, model: &mut Model, key: Key) { match key { Key::Key1 => { if model .module_color_background .eq(&hsva(0.0, 0.0, 0.0, model.module_alpha_background)) { model.module_color_background = hsva(0.758, 0.73, 0.51, model.module_alpha_background); } else { model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background); } } Key::Key2 => { if model .module_color_foreground .eq(&hsva(1.0, 1.0, 1.0, model.module_alpha_foreground)) { model.module_color_foreground = hsva(0.89, 1.0, 0.77, model.module_alpha_foreground); } else {
} Key::Key3 => { if model.module_alpha_background == 1.0 { model.module_alpha_background = 0.5; model.module_alpha_foreground = 0.5; } else { model.module_alpha_background = 1.0; model.module_alpha_foreground = 1.0; } model.module_color_background.alpha = model.module_alpha_background; model.module_color_foreground.alpha = model.module_alpha_foreground; } Key::Key0 => { model.module_radius_background = 15.0; model.module_radius_foreground = 7.5; model.module_alpha_background = 1.0; model.module_alpha_foreground = 1.0; model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background); model.module_color_foreground = hsva(0.0, 0.0, 1.0, model.module_alpha_foreground); } Key::Up => { model.module_radius_background += 2.0; } Key::Down => { model.module_radius_background = 5.0.max(model.module_radius_background - 2.0); } Key::Left => { model.module_radius_foreground = 2.5.max(model.module_radius_foreground - 2.0); } Key::Right => { model.module_radius_foreground += 2.0; } _other_key => {} } }
model.module_color_foreground = hsva(1.0, 1.0, 1.0, model.module_alpha_foreground); }
conditional_block
p_2_1_2_02.rs
// P_2_1_2_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing module color and positions in a grid * * MOUSE * position x : offset x * position y : offset y * left click : random position * * KEYS * 1-3 : different sets of colors * 0 : default * arrow up/down : background module size * arrow left/right : foreground module size * s : save png */ use nannou::prelude::*; use nannou::rand::rngs::StdRng; use nannou::rand::{Rng, SeedableRng}; fn main() { nannou::app(model).run(); } struct Model { tile_count: u32, act_random_seed: u64, module_color_background: Hsva, module_color_foreground: Hsva, module_alpha_background: f32, module_alpha_foreground: f32, module_radius_background: f32, module_radius_foreground: f32, } fn model(app: &App) -> Model { let _window = app .new_window() .size(600, 600) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .key_released(key_released) .build() .unwrap(); let module_alpha_background = 1.0; let module_alpha_foreground = 1.0; Model { tile_count: 20, act_random_seed: 0, module_color_background: hsva(0.0, 0.0, 0.0, module_alpha_background), module_color_foreground: hsva(0.0, 0.0, 1.0, module_alpha_foreground), module_alpha_background, module_alpha_foreground, module_radius_background: 15.0, module_radius_foreground: 7.5, } } fn view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); let win = app.window_rect(); draw.background().color(WHITE); let mut rng = StdRng::seed_from_u64(model.act_random_seed); let mx = clamp(win.right() + app.mouse.x, 0.0, win.w()); let my = clamp(win.top() - app.mouse.y, 0.0, win.h()); for grid_y in 0..model.tile_count { for grid_x in 0..model.tile_count { let tile_w = win.w() / model.tile_count as f32; let tile_h = win.h() / model.tile_count as f32; let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32; let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32; let shift_x = rng.gen_range(-mx, mx + 1.0) / 20.0; let shift_y = rng.gen_range(-my, my + 1.0) / 20.0; draw.ellipse() .x_y(pos_x + shift_x, pos_y + shift_y) .radius(model.module_radius_background) .color(model.module_color_background); } } for grid_y in 0..model.tile_count { for grid_x in 0..model.tile_count { let tile_w = win.w() / model.tile_count as f32; let tile_h = win.h() / model.tile_count as f32; let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32; let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32; draw.ellipse() .x_y(pos_x, pos_y) .radius(model.module_radius_foreground) .color(model.module_color_foreground); } } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.act_random_seed = (random_f32() * 100000.0) as u64; } fn key_pressed(app: &App, _model: &mut Model, key: Key) { if key == Key::S { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } } fn key_released(_app: &App, model: &mut Model, key: Key) { match key { Key::Key1 => { if model .module_color_background .eq(&hsva(0.0, 0.0, 0.0, model.module_alpha_background)) { model.module_color_background = hsva(0.758, 0.73, 0.51, model.module_alpha_background); } else { model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background); } } Key::Key2 => { if model .module_color_foreground .eq(&hsva(1.0, 1.0, 1.0, model.module_alpha_foreground)) { model.module_color_foreground = hsva(0.89, 1.0, 0.77, model.module_alpha_foreground); } else { model.module_color_foreground = hsva(1.0, 1.0, 1.0, model.module_alpha_foreground); } } Key::Key3 => { if model.module_alpha_background == 1.0 { model.module_alpha_background = 0.5; model.module_alpha_foreground = 0.5; } else { model.module_alpha_background = 1.0; model.module_alpha_foreground = 1.0; } model.module_color_background.alpha = model.module_alpha_background;
} Key::Key0 => { model.module_radius_background = 15.0; model.module_radius_foreground = 7.5; model.module_alpha_background = 1.0; model.module_alpha_foreground = 1.0; model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background); model.module_color_foreground = hsva(0.0, 0.0, 1.0, model.module_alpha_foreground); } Key::Up => { model.module_radius_background += 2.0; } Key::Down => { model.module_radius_background = 5.0.max(model.module_radius_background - 2.0); } Key::Left => { model.module_radius_foreground = 2.5.max(model.module_radius_foreground - 2.0); } Key::Right => { model.module_radius_foreground += 2.0; } _other_key => {} } }
model.module_color_foreground.alpha = model.module_alpha_foreground;
random_line_split
p_2_1_2_02.rs
// P_2_1_2_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * changing module color and positions in a grid * * MOUSE * position x : offset x * position y : offset y * left click : random position * * KEYS * 1-3 : different sets of colors * 0 : default * arrow up/down : background module size * arrow left/right : foreground module size * s : save png */ use nannou::prelude::*; use nannou::rand::rngs::StdRng; use nannou::rand::{Rng, SeedableRng}; fn main() { nannou::app(model).run(); } struct Model { tile_count: u32, act_random_seed: u64, module_color_background: Hsva, module_color_foreground: Hsva, module_alpha_background: f32, module_alpha_foreground: f32, module_radius_background: f32, module_radius_foreground: f32, } fn model(app: &App) -> Model {
n view(app: &App, model: &Model, frame: Frame) { let draw = app.draw(); let win = app.window_rect(); draw.background().color(WHITE); let mut rng = StdRng::seed_from_u64(model.act_random_seed); let mx = clamp(win.right() + app.mouse.x, 0.0, win.w()); let my = clamp(win.top() - app.mouse.y, 0.0, win.h()); for grid_y in 0..model.tile_count { for grid_x in 0..model.tile_count { let tile_w = win.w() / model.tile_count as f32; let tile_h = win.h() / model.tile_count as f32; let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32; let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32; let shift_x = rng.gen_range(-mx, mx + 1.0) / 20.0; let shift_y = rng.gen_range(-my, my + 1.0) / 20.0; draw.ellipse() .x_y(pos_x + shift_x, pos_y + shift_y) .radius(model.module_radius_background) .color(model.module_color_background); } } for grid_y in 0..model.tile_count { for grid_x in 0..model.tile_count { let tile_w = win.w() / model.tile_count as f32; let tile_h = win.h() / model.tile_count as f32; let pos_x = (win.left() + (tile_w / 2.0)) + tile_w * grid_x as f32; let pos_y = (win.top() - (tile_h / 2.0)) - tile_h * grid_y as f32; draw.ellipse() .x_y(pos_x, pos_y) .radius(model.module_radius_foreground) .color(model.module_color_foreground); } } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.act_random_seed = (random_f32() * 100000.0) as u64; } fn key_pressed(app: &App, _model: &mut Model, key: Key) { if key == Key::S { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } } fn key_released(_app: &App, model: &mut Model, key: Key) { match key { Key::Key1 => { if model .module_color_background .eq(&hsva(0.0, 0.0, 0.0, model.module_alpha_background)) { model.module_color_background = hsva(0.758, 0.73, 0.51, model.module_alpha_background); } else { model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background); } } Key::Key2 => { if model .module_color_foreground .eq(&hsva(1.0, 1.0, 1.0, model.module_alpha_foreground)) { model.module_color_foreground = hsva(0.89, 1.0, 0.77, model.module_alpha_foreground); } else { model.module_color_foreground = hsva(1.0, 1.0, 1.0, model.module_alpha_foreground); } } Key::Key3 => { if model.module_alpha_background == 1.0 { model.module_alpha_background = 0.5; model.module_alpha_foreground = 0.5; } else { model.module_alpha_background = 1.0; model.module_alpha_foreground = 1.0; } model.module_color_background.alpha = model.module_alpha_background; model.module_color_foreground.alpha = model.module_alpha_foreground; } Key::Key0 => { model.module_radius_background = 15.0; model.module_radius_foreground = 7.5; model.module_alpha_background = 1.0; model.module_alpha_foreground = 1.0; model.module_color_background = hsva(0.0, 0.0, 0.0, model.module_alpha_background); model.module_color_foreground = hsva(0.0, 0.0, 1.0, model.module_alpha_foreground); } Key::Up => { model.module_radius_background += 2.0; } Key::Down => { model.module_radius_background = 5.0.max(model.module_radius_background - 2.0); } Key::Left => { model.module_radius_foreground = 2.5.max(model.module_radius_foreground - 2.0); } Key::Right => { model.module_radius_foreground += 2.0; } _other_key => {} } }
let _window = app .new_window() .size(600, 600) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .key_released(key_released) .build() .unwrap(); let module_alpha_background = 1.0; let module_alpha_foreground = 1.0; Model { tile_count: 20, act_random_seed: 0, module_color_background: hsva(0.0, 0.0, 0.0, module_alpha_background), module_color_foreground: hsva(0.0, 0.0, 1.0, module_alpha_foreground), module_alpha_background, module_alpha_foreground, module_radius_background: 15.0, module_radius_foreground: 7.5, } } f
identifier_body
bot.js
var config = require("./config.json"); var currentSong, newSong, currentAlbum; const http = require("http"); const LastFmNode = require("lastfm").LastFmNode; const Discord = require("discord.js"); const client = new Discord.Client(); var lastfm = new LastFmNode({ api_key: config.api_key }); function stoppedPlaying(){ console.log("stopped playing."); client.user.setGame(0); currentAlbum = 0; if(config.changeAvatar){ client.user.setAvatar(config.defaultAvatar); } } var trackStream = lastfm.stream(config.username); trackStream.on("nowPlaying", function(track) { if(track.name && track.artist["#text"]){ //console.log(track); if(track["@attr"]){ newSong = track.artist["#text"] + " - " + track.name; if (newSong != currentSong) { if (currentAlbum != track.album["#text"]){ if(track.image[0]["#text"] && config.changeAvatar){ console.log("playing album: "+track.album["#text"]); client.user.setAvatar(track.image[track.image.length-1]["#text"]); currentAlbum = track.album["#text"]; } } console.info("currently playing:", newSong); client.user.setGame("♫ "+newSong); currentSong = newSong; } }else{ stoppedPlaying(); } } }); trackStream.on("stoppedPlaying", function(track) { stoppedPlaying(); }); trackStream.on("error", function(err) { console.log("something went wrong: ",err); }); client.on("ready", () => { console.log(`Logged in as ${client.user.username}!`); trackStream.start(); }); // Script for exiting the process is from https://frankl.in/code/before-exit-scripts-in-node-js let preExit = []; // Add pre-exit script preExit.push(code => { console.log('Whoa! Exit code %d, cleaning up...', code); stoppedPlaying(); }); // Catch CTRL+C process.on('SIGINT', () => { console.log('\nCTRL+C...'); stoppedPlaying(); process.exit(0); }); // Catch uncaught exception process.on('uncaughtException', err => { console.dir(err, {
}); stoppedPlaying(); process.exit(1); }); console.log('Bot on, hit CTRL+C to exit :)'); client.login(config.token);
depth: null
random_line_split
bot.js
var config = require("./config.json"); var currentSong, newSong, currentAlbum; const http = require("http"); const LastFmNode = require("lastfm").LastFmNode; const Discord = require("discord.js"); const client = new Discord.Client(); var lastfm = new LastFmNode({ api_key: config.api_key }); function stoppedPlaying()
var trackStream = lastfm.stream(config.username); trackStream.on("nowPlaying", function(track) { if(track.name && track.artist["#text"]){ //console.log(track); if(track["@attr"]){ newSong = track.artist["#text"] + " - " + track.name; if (newSong != currentSong) { if (currentAlbum != track.album["#text"]){ if(track.image[0]["#text"] && config.changeAvatar){ console.log("playing album: "+track.album["#text"]); client.user.setAvatar(track.image[track.image.length-1]["#text"]); currentAlbum = track.album["#text"]; } } console.info("currently playing:", newSong); client.user.setGame("♫ "+newSong); currentSong = newSong; } }else{ stoppedPlaying(); } } }); trackStream.on("stoppedPlaying", function(track) { stoppedPlaying(); }); trackStream.on("error", function(err) { console.log("something went wrong: ",err); }); client.on("ready", () => { console.log(`Logged in as ${client.user.username}!`); trackStream.start(); }); // Script for exiting the process is from https://frankl.in/code/before-exit-scripts-in-node-js let preExit = []; // Add pre-exit script preExit.push(code => { console.log('Whoa! Exit code %d, cleaning up...', code); stoppedPlaying(); }); // Catch CTRL+C process.on('SIGINT', () => { console.log('\nCTRL+C...'); stoppedPlaying(); process.exit(0); }); // Catch uncaught exception process.on('uncaughtException', err => { console.dir(err, { depth: null }); stoppedPlaying(); process.exit(1); }); console.log('Bot on, hit CTRL+C to exit :)'); client.login(config.token);
{ console.log("stopped playing."); client.user.setGame(0); currentAlbum = 0; if(config.changeAvatar){ client.user.setAvatar(config.defaultAvatar); } }
identifier_body
bot.js
var config = require("./config.json"); var currentSong, newSong, currentAlbum; const http = require("http"); const LastFmNode = require("lastfm").LastFmNode; const Discord = require("discord.js"); const client = new Discord.Client(); var lastfm = new LastFmNode({ api_key: config.api_key }); function
(){ console.log("stopped playing."); client.user.setGame(0); currentAlbum = 0; if(config.changeAvatar){ client.user.setAvatar(config.defaultAvatar); } } var trackStream = lastfm.stream(config.username); trackStream.on("nowPlaying", function(track) { if(track.name && track.artist["#text"]){ //console.log(track); if(track["@attr"]){ newSong = track.artist["#text"] + " - " + track.name; if (newSong != currentSong) { if (currentAlbum != track.album["#text"]){ if(track.image[0]["#text"] && config.changeAvatar){ console.log("playing album: "+track.album["#text"]); client.user.setAvatar(track.image[track.image.length-1]["#text"]); currentAlbum = track.album["#text"]; } } console.info("currently playing:", newSong); client.user.setGame("♫ "+newSong); currentSong = newSong; } }else{ stoppedPlaying(); } } }); trackStream.on("stoppedPlaying", function(track) { stoppedPlaying(); }); trackStream.on("error", function(err) { console.log("something went wrong: ",err); }); client.on("ready", () => { console.log(`Logged in as ${client.user.username}!`); trackStream.start(); }); // Script for exiting the process is from https://frankl.in/code/before-exit-scripts-in-node-js let preExit = []; // Add pre-exit script preExit.push(code => { console.log('Whoa! Exit code %d, cleaning up...', code); stoppedPlaying(); }); // Catch CTRL+C process.on('SIGINT', () => { console.log('\nCTRL+C...'); stoppedPlaying(); process.exit(0); }); // Catch uncaught exception process.on('uncaughtException', err => { console.dir(err, { depth: null }); stoppedPlaying(); process.exit(1); }); console.log('Bot on, hit CTRL+C to exit :)'); client.login(config.token);
stoppedPlaying
identifier_name
bot.js
var config = require("./config.json"); var currentSong, newSong, currentAlbum; const http = require("http"); const LastFmNode = require("lastfm").LastFmNode; const Discord = require("discord.js"); const client = new Discord.Client(); var lastfm = new LastFmNode({ api_key: config.api_key }); function stoppedPlaying(){ console.log("stopped playing."); client.user.setGame(0); currentAlbum = 0; if(config.changeAvatar){ client.user.setAvatar(config.defaultAvatar); } } var trackStream = lastfm.stream(config.username); trackStream.on("nowPlaying", function(track) { if(track.name && track.artist["#text"]){ //console.log(track); if(track["@attr"])
se{ stoppedPlaying(); } } }); trackStream.on("stoppedPlaying", function(track) { stoppedPlaying(); }); trackStream.on("error", function(err) { console.log("something went wrong: ",err); }); client.on("ready", () => { console.log(`Logged in as ${client.user.username}!`); trackStream.start(); }); // Script for exiting the process is from https://frankl.in/code/before-exit-scripts-in-node-js let preExit = []; // Add pre-exit script preExit.push(code => { console.log('Whoa! Exit code %d, cleaning up...', code); stoppedPlaying(); }); // Catch CTRL+C process.on('SIGINT', () => { console.log('\nCTRL+C...'); stoppedPlaying(); process.exit(0); }); // Catch uncaught exception process.on('uncaughtException', err => { console.dir(err, { depth: null }); stoppedPlaying(); process.exit(1); }); console.log('Bot on, hit CTRL+C to exit :)'); client.login(config.token);
{ newSong = track.artist["#text"] + " - " + track.name; if (newSong != currentSong) { if (currentAlbum != track.album["#text"]){ if(track.image[0]["#text"] && config.changeAvatar){ console.log("playing album: "+track.album["#text"]); client.user.setAvatar(track.image[track.image.length-1]["#text"]); currentAlbum = track.album["#text"]; } } console.info("currently playing:", newSong); client.user.setGame("♫ "+newSong); currentSong = newSong; } }el
conditional_block
app.module.ts
import { AppComponent } from './app.component'; import { AuthGuard } from './auth-guard.service'; import { AuthService } from './auth.service'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { PlanService } from './plan.service'; import { RouterModule } from '@angular/router'; import { routes } from './app.routes'; import { AngularFireModule, AuthMethods, AuthProviders } from 'angularfire2'; var firebaseConfig = { apiKey: "AIzaSyAdd3xy0z4sPwgiTUIYfoJ5KzpcHVWAjIE", authDomain: "nc-citizenredistrict.firebaseapp.com", databaseURL: "https://nc-citizenredistrict.firebaseio.com", storageBucket: "nc-citizenredistrict.appspot.com", }; const firebaseAuthConfig = { provider: AuthProviders.Google, method: AuthMethods.Popup }; var r = []; r = routes.map((d) => d.component) as any[]; r.push(AppComponent); @NgModule({ declarations: r, imports: [ AngularFireModule.initializeApp(firebaseConfig, firebaseAuthConfig), BrowserModule, FormsModule, RouterModule, RouterModule.forRoot(routes) ], bootstrap: [ AppComponent ], providers: [ AuthGuard, AuthService, PlanService ] }) export class
{}
AppModule
identifier_name
app.module.ts
import { AppComponent } from './app.component'; import { AuthGuard } from './auth-guard.service'; import { AuthService } from './auth.service'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { PlanService } from './plan.service'; import { RouterModule } from '@angular/router'; import { routes } from './app.routes'; import { AngularFireModule, AuthMethods, AuthProviders } from 'angularfire2'; var firebaseConfig = { apiKey: "AIzaSyAdd3xy0z4sPwgiTUIYfoJ5KzpcHVWAjIE", authDomain: "nc-citizenredistrict.firebaseapp.com", databaseURL: "https://nc-citizenredistrict.firebaseio.com", storageBucket: "nc-citizenredistrict.appspot.com", }; const firebaseAuthConfig = { provider: AuthProviders.Google, method: AuthMethods.Popup }; var r = []; r = routes.map((d) => d.component) as any[];
AngularFireModule.initializeApp(firebaseConfig, firebaseAuthConfig), BrowserModule, FormsModule, RouterModule, RouterModule.forRoot(routes) ], bootstrap: [ AppComponent ], providers: [ AuthGuard, AuthService, PlanService ] }) export class AppModule {}
r.push(AppComponent); @NgModule({ declarations: r, imports: [
random_line_split
convert_fasta2phylip.py
#!/usr/bin/env python3 """Convert FASTA to PHYLIP""" import sys from Bio import SeqIO print("Convert FASTA to PHYLIP") infile = sys.argv[1] outfile = sys.argv[2] sequence_list = [] # To keep order of sequence sequence_dict = {} for record in SeqIO.parse(open(infile, "rU"), "fasta"): tab = record.id.split(" ") sequence = str(record.seq).replace(" ", "") # print sequence, len(sequence) sequence_list.append(tab[0]) sequence_dict[tab[0]] = sequence if "U" in sequence: print(tab[0]) sys.exit() print("Number of sequences:", len(sequence_dict)) # Test length of the alignment: alignment_length = 0 for gene in sequence_dict: if (alignment_length != 0) and (len(sequence_dict[gene]) != alignment_length): print("Error in alignment length, exit on error !!!") sys.exit() else: alignment_length = len(sequence_dict[gene]) number_of_seq = len(sequence_dict) print("Number of sequences:\t"+str(number_of_seq)) print("Alignment length:\t"+str(alignment_length)) print("Ratio =\t"+str(alignment_length/3)) if alignment_length%3 != 0:
if len(sys.argv) > 3: name_length = int(sys.argv[3]) # Write alignment in Phylip format phyfile = open(outfile, "w") phyfile.write(str(number_of_seq)+"\t"+str(alignment_length)+"\n") for gene in sequence_list: if len(gene) > name_length: gene_name = gene[0:name_length].replace(" ", "") if gene_name[-1] == "_": gene_name = gene_name[0:-1] # elif gene_name[-2] == "_": # gene_name = gene_name[0:-2] else: gene_name = gene phyfile.write(gene_name+" "+sequence_dict[gene]+"\n") phyfile.close()
print("Warning: Hum, your alignment didn't code for nucleotides") # Length of gene id, can be changed by passing a third argument name_length = 50
random_line_split
convert_fasta2phylip.py
#!/usr/bin/env python3 """Convert FASTA to PHYLIP""" import sys from Bio import SeqIO print("Convert FASTA to PHYLIP") infile = sys.argv[1] outfile = sys.argv[2] sequence_list = [] # To keep order of sequence sequence_dict = {} for record in SeqIO.parse(open(infile, "rU"), "fasta"): tab = record.id.split(" ") sequence = str(record.seq).replace(" ", "") # print sequence, len(sequence) sequence_list.append(tab[0]) sequence_dict[tab[0]] = sequence if "U" in sequence: print(tab[0]) sys.exit() print("Number of sequences:", len(sequence_dict)) # Test length of the alignment: alignment_length = 0 for gene in sequence_dict: if (alignment_length != 0) and (len(sequence_dict[gene]) != alignment_length): print("Error in alignment length, exit on error !!!") sys.exit() else: alignment_length = len(sequence_dict[gene]) number_of_seq = len(sequence_dict) print("Number of sequences:\t"+str(number_of_seq)) print("Alignment length:\t"+str(alignment_length)) print("Ratio =\t"+str(alignment_length/3)) if alignment_length%3 != 0:
# Length of gene id, can be changed by passing a third argument name_length = 50 if len(sys.argv) > 3: name_length = int(sys.argv[3]) # Write alignment in Phylip format phyfile = open(outfile, "w") phyfile.write(str(number_of_seq)+"\t"+str(alignment_length)+"\n") for gene in sequence_list: if len(gene) > name_length: gene_name = gene[0:name_length].replace(" ", "") if gene_name[-1] == "_": gene_name = gene_name[0:-1] # elif gene_name[-2] == "_": # gene_name = gene_name[0:-2] else: gene_name = gene phyfile.write(gene_name+" "+sequence_dict[gene]+"\n") phyfile.close()
print("Warning: Hum, your alignment didn't code for nucleotides")
conditional_block
stat.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::{File, TempDir}; pub fn main() { let dir = TempDir::new_in(&Path::new("."), "").unwrap(); let path = dir.path().join("file"); { match File::create(&path) { Err(..) => unreachable!(), Ok(f) => { let mut f = f; for _ in range(0u, 1000) { f.write([0]); } } } } assert!(path.exists()); assert_eq!(path.stat().unwrap().size, 1000);
}
random_line_split
stat.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::{File, TempDir}; pub fn
() { let dir = TempDir::new_in(&Path::new("."), "").unwrap(); let path = dir.path().join("file"); { match File::create(&path) { Err(..) => unreachable!(), Ok(f) => { let mut f = f; for _ in range(0u, 1000) { f.write([0]); } } } } assert!(path.exists()); assert_eq!(path.stat().unwrap().size, 1000); }
main
identifier_name
stat.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io::{File, TempDir}; pub fn main()
{ let dir = TempDir::new_in(&Path::new("."), "").unwrap(); let path = dir.path().join("file"); { match File::create(&path) { Err(..) => unreachable!(), Ok(f) => { let mut f = f; for _ in range(0u, 1000) { f.write([0]); } } } } assert!(path.exists()); assert_eq!(path.stat().unwrap().size, 1000); }
identifier_body