Have a look at using FileInfo.Name Property
something like
string[] files = Directory.GetFiles(dir);
for (int iFile = 0; iFile < files.Length; iFile++)
string fn = new FileInfo(files[iFile]).Name;
Also have a look at using DirectoryInfo Class and FileInfo Class
If you would like to do your filtering in LINQ, you can do it like this:
var ext = new List<string> { "jpg", "gif", "png" };
var myFiles = Directory
.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(s => ext.Contains(Path.GetExtension(s).TrimStart(".").ToLowerInvariant()));
Now ext
contains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.
You can use LINQ Union method:
dir.GetFiles("*.txt").Union(dir.GetFiles("*.jpg")).ToArray();
You need to keep an array of the google.maps.Marker
objects to hide (or remove or run other operations on them).
In the global scope:
var gmarkers = [];
Then push the markers on that array as you create them:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
title: locations[i].title,
icon: icon,
map:map
});
// Push your newly created marker into the array:
gmarkers.push(marker);
Then to remove them:
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
working example (toggles the markers)
code snippet:
var gmarkers = [];_x000D_
var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);_x000D_
var styles = [{_x000D_
stylers: [{_x000D_
hue: "black"_x000D_
}, {_x000D_
saturation: -90_x000D_
}]_x000D_
}, {_x000D_
featureType: "road",_x000D_
elementType: "geometry",_x000D_
stylers: [{_x000D_
lightness: 100_x000D_
}, {_x000D_
visibility: "simplified"_x000D_
}]_x000D_
}, {_x000D_
featureType: "road",_x000D_
elementType: "labels",_x000D_
stylers: [{_x000D_
visibility: "on"_x000D_
}]_x000D_
}];_x000D_
_x000D_
var styledMap = new google.maps.StyledMapType(styles, {_x000D_
name: "Campus"_x000D_
});_x000D_
var mapOptions = {_x000D_
center: RoseHulman,_x000D_
zoom: 15,_x000D_
mapTypeControl: true,_x000D_
zoomControl: true,_x000D_
zoomControlOptions: {_x000D_
style: google.maps.ZoomControlStyle.SMALL_x000D_
},_x000D_
mapTypeControlOptions: {_x000D_
mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID],_x000D_
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU_x000D_
},_x000D_
scrollwheel: false,_x000D_
streetViewControl: true,_x000D_
_x000D_
};_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map'), mapOptions);_x000D_
map.mapTypes.set('map_style', styledMap);_x000D_
map.setMapTypeId('map_style');_x000D_
_x000D_
var infowindow = new google.maps.InfoWindow({_x000D_
maxWidth: 300,_x000D_
infoBoxClearance: new google.maps.Size(1, 1),_x000D_
disableAutoPan: false_x000D_
});_x000D_
_x000D_
var marker, i, icon, image;_x000D_
_x000D_
var locations = [{_x000D_
"id": "1",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Alpha Tau Omega Fraternity",_x000D_
"description": "<p>Alpha Tau Omega house</p>",_x000D_
"longitude": "-87.321133",_x000D_
"latitude": "39.484092"_x000D_
}, {_x000D_
"id": "2",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment Commons",_x000D_
"description": "<p>The commons area of the apartment-style residential complex</p>",_x000D_
"longitude": "-87.329282",_x000D_
"latitude": "39.483599"_x000D_
}, {_x000D_
"id": "3",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment East",_x000D_
"description": "<p>Apartment East</p>",_x000D_
"longitude": "-87.328809",_x000D_
"latitude": "39.483748"_x000D_
}, {_x000D_
"id": "4",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Apartment West",_x000D_
"description": "<p>Apartment West</p>",_x000D_
"longitude": "-87.329732",_x000D_
"latitude": "39.483429"_x000D_
}, {_x000D_
"id": "5",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Baur-Sames-Bogart (BSB) Hall",_x000D_
"description": "<p>Baur-Sames-Bogart Hall</p>",_x000D_
"longitude": "-87.325714",_x000D_
"latitude": "39.482382"_x000D_
}, {_x000D_
"id": "6",_x000D_
"category": "6",_x000D_
"campus_location": "D3",_x000D_
"title": "Blumberg Hall",_x000D_
"description": "<p>Blumberg Hall</p>",_x000D_
"longitude": "-87.328321",_x000D_
"latitude": "39.483388"_x000D_
}, {_x000D_
"id": "7",_x000D_
"category": "1",_x000D_
"campus_location": "E1",_x000D_
"title": "The Branam Innovation Center",_x000D_
"description": "<p>The Branam Innovation Center</p>",_x000D_
"longitude": "-87.322614",_x000D_
"latitude": "39.48494"_x000D_
}, {_x000D_
"id": "8",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Chi Omega Sorority",_x000D_
"description": "<p>Chi Omega house</p>",_x000D_
"longitude": "-87.319905",_x000D_
"latitude": "39.482071"_x000D_
}, {_x000D_
"id": "9",_x000D_
"category": "3",_x000D_
"campus_location": "D1",_x000D_
"title": "Cook Stadium/Phil Brown Field",_x000D_
"description": "<p>Cook Stadium at Phil Brown Field</p>",_x000D_
"longitude": "-87.325258",_x000D_
"latitude": "39.485007"_x000D_
}, {_x000D_
"id": "10",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Crapo Hall",_x000D_
"description": "<p>Crapo Hall</p>",_x000D_
"longitude": "-87.324368",_x000D_
"latitude": "39.483709"_x000D_
}, {_x000D_
"id": "11",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Delta Delta Delta Sorority",_x000D_
"description": "<p>Delta Delta Delta</p>",_x000D_
"longitude": "-87.317477",_x000D_
"latitude": "39.482951"_x000D_
}, {_x000D_
"id": "12",_x000D_
"category": "6",_x000D_
"campus_location": "D2",_x000D_
"title": "Deming Hall",_x000D_
"description": "<p>Deming Hall</p>",_x000D_
"longitude": "-87.325822",_x000D_
"latitude": "39.483421"_x000D_
}, {_x000D_
"id": "13",_x000D_
"category": "5",_x000D_
"campus_location": "F1",_x000D_
"title": "Facilities Operations",_x000D_
"description": "<p>Facilities Operations</p>",_x000D_
"longitude": "-87.321782",_x000D_
"latitude": "39.484916"_x000D_
}, {_x000D_
"id": "14",_x000D_
"category": "2",_x000D_
"campus_location": "E3",_x000D_
"title": "Flame of the Millennium",_x000D_
"description": "<p>Flame of Millennium sculpture</p>",_x000D_
"longitude": "-87.323306",_x000D_
"latitude": "39.481978"_x000D_
}, {_x000D_
"id": "15",_x000D_
"category": "5",_x000D_
"campus_location": "E2",_x000D_
"title": "Hadley Hall",_x000D_
"description": "<p>Hadley Hall</p>",_x000D_
"longitude": "-87.324046",_x000D_
"latitude": "39.482887"_x000D_
}, {_x000D_
"id": "16",_x000D_
"category": "2",_x000D_
"campus_location": "F2",_x000D_
"title": "Hatfield Hall",_x000D_
"description": "<p>Hatfield Hall</p>",_x000D_
"longitude": "-87.322340",_x000D_
"latitude": "39.482146"_x000D_
}, {_x000D_
"id": "17",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Hulman Memorial Union",_x000D_
"description": "<p>Hulman Memorial Union</p>",_x000D_
"longitude": "-87.32698",_x000D_
"latitude": "39.483574"_x000D_
}, {_x000D_
"id": "18",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "John T. Myers Center for Technological Research with Industry",_x000D_
"description": "<p>John T. Myers Center for Technological Research With Industry</p>",_x000D_
"longitude": "-87.322984",_x000D_
"latitude": "39.484063"_x000D_
}, {_x000D_
"id": "19",_x000D_
"category": "6",_x000D_
"campus_location": "A2",_x000D_
"title": "Lakeside Hall",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.330612",_x000D_
"latitude": "39.482804"_x000D_
}, {_x000D_
"id": "20",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Lambda Chi Alpha Fraternity",_x000D_
"description": "<p>Lambda Chi Alpha</p>",_x000D_
"longitude": "-87.320999",_x000D_
"latitude": "39.48305"_x000D_
}, {_x000D_
"id": "21",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Logan Library",_x000D_
"description": "<p>Logan Library</p>",_x000D_
"longitude": "-87.324851",_x000D_
"latitude": "39.483408"_x000D_
}, {_x000D_
"id": "22",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Mees Hall",_x000D_
"description": "<p>Mees Hall</p>",_x000D_
"longitude": "-87.32778",_x000D_
"latitude": "39.483533"_x000D_
}, {_x000D_
"id": "23",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "Moench Hall",_x000D_
"description": "<p>Moench Hall</p>",_x000D_
"longitude": "-87.323695",_x000D_
"latitude": "39.483471"_x000D_
}, {_x000D_
"id": "24",_x000D_
"category": "1",_x000D_
"campus_location": "G4",_x000D_
"title": "Oakley Observatory",_x000D_
"description": "<p>Oakley Observatory</p>",_x000D_
"longitude": "-87.31616",_x000D_
"latitude": "39.483789"_x000D_
}, {_x000D_
"id": "25",_x000D_
"category": "1",_x000D_
"campus_location": "D2",_x000D_
"title": "Olin Hall and Olin Advanced Learning Center",_x000D_
"description": "<p>Olin Hall</p>",_x000D_
"longitude": "-87.324550",_x000D_
"latitude": "39.482796"_x000D_
}, {_x000D_
"id": "26",_x000D_
"category": "6",_x000D_
"campus_location": "C3",_x000D_
"title": "Percopo Hall",_x000D_
"description": "<p>Percopo Hall</p>",_x000D_
"longitude": "-87.328182",_x000D_
"latitude": "39.482121"_x000D_
}, {_x000D_
"id": "27",_x000D_
"category": "6",_x000D_
"campus_location": "G3",_x000D_
"title": "Public Safety Office",_x000D_
"description": "<p>The Office of Public Safety</p>",_x000D_
"longitude": "-87.320377",_x000D_
"latitude": "39.48191"_x000D_
}, {_x000D_
"id": "28",_x000D_
"category": "1",_x000D_
"campus_location": "E2",_x000D_
"title": "Rotz Mechanical Engineering Lab",_x000D_
"description": "<p>Rotz Lab</p>",_x000D_
"longitude": "-87.323247",_x000D_
"latitude": "39.483711"_x000D_
}, {_x000D_
"id": "28",_x000D_
"category": "6",_x000D_
"campus_location": "C2",_x000D_
"title": "Scharpenberg Hall",_x000D_
"description": "<p>Scharpenberg Hall</p>",_x000D_
"longitude": "-87.328139",_x000D_
"latitude": "39.483582"_x000D_
}, {_x000D_
"id": "29",_x000D_
"category": "6",_x000D_
"campus_location": "G2",_x000D_
"title": "Sigma Nu Fraternity",_x000D_
"description": "<p>The Sigma Nu house</p>",_x000D_
"longitude": "-87.31999",_x000D_
"latitude": "39.48374"_x000D_
}, {_x000D_
"id": "30",_x000D_
"category": "6",_x000D_
"campus_location": "E4",_x000D_
"title": "South Campus / Rose-Hulman Ventures",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.330623",_x000D_
"latitude": "39.417646"_x000D_
}, {_x000D_
"id": "31",_x000D_
"category": "6",_x000D_
"campus_location": "C3",_x000D_
"title": "Speed Hall",_x000D_
"description": "<p>Speed Hall</p>",_x000D_
"longitude": "-87.326632",_x000D_
"latitude": "39.482121"_x000D_
}, {_x000D_
"id": "32",_x000D_
"category": "3",_x000D_
"campus_location": "C1",_x000D_
"title": "Sports and Recreation Center",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.3272",_x000D_
"latitude": "39.484874"_x000D_
}, {_x000D_
"id": "33",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Triangle Fraternity",_x000D_
"description": "<p>Triangle fraternity</p>",_x000D_
"longitude": "-87.32113",_x000D_
"latitude": "39.483659"_x000D_
}, {_x000D_
"id": "34",_x000D_
"category": "6",_x000D_
"campus_location": "B3",_x000D_
"title": "White Chapel",_x000D_
"description": "<p>The White Chapel</p>",_x000D_
"longitude": "-87.329367",_x000D_
"latitude": "39.482481"_x000D_
}, {_x000D_
"id": "35",_x000D_
"category": "6",_x000D_
"campus_location": "F2",_x000D_
"title": "Women's Fraternity Housing",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320753",_x000D_
"latitude": "39.482401"_x000D_
}, {_x000D_
"id": "36",_x000D_
"category": "3",_x000D_
"campus_location": "E1",_x000D_
"title": "Intramural Fields",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.321267",_x000D_
"latitude": "39.485934"_x000D_
}, {_x000D_
"id": "37",_x000D_
"category": "3",_x000D_
"campus_location": "A3",_x000D_
"title": "James Rendel Soccer Field",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.332135",_x000D_
"latitude": "39.480933"_x000D_
}, {_x000D_
"id": "38",_x000D_
"category": "3",_x000D_
"campus_location": "B2",_x000D_
"title": "Art Nehf Field",_x000D_
"description": "<p>Art Nehf Field</p>",_x000D_
"longitude": "-87.330923",_x000D_
"latitude": "39.48022"_x000D_
}, {_x000D_
"id": "39",_x000D_
"category": "3",_x000D_
"campus_location": "B2",_x000D_
"title": "Women's Softball Field",_x000D_
"description": "<p></p>",_x000D_
"longitude": "-87.329904",_x000D_
"latitude": "39.480278"_x000D_
}, {_x000D_
"id": "40",_x000D_
"category": "3",_x000D_
"campus_location": "D1",_x000D_
"title": "Joy Hulbert Tennis Courts",_x000D_
"description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>",_x000D_
"longitude": "-87.323767",_x000D_
"latitude": "39.485595"_x000D_
}, {_x000D_
"id": "41",_x000D_
"category": "6",_x000D_
"campus_location": "B2",_x000D_
"title": "Speed Lake",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.328134",_x000D_
"latitude": "39.482779"_x000D_
}, {_x000D_
"id": "42",_x000D_
"category": "5",_x000D_
"campus_location": "F1",_x000D_
"title": "Recycling Center",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320098",_x000D_
"latitude": "39.484593"_x000D_
}, {_x000D_
"id": "43",_x000D_
"category": "1",_x000D_
"campus_location": "F3",_x000D_
"title": "Army ROTC",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.321342",_x000D_
"latitude": "39.481992"_x000D_
}, {_x000D_
"id": "44",_x000D_
"category": "2",_x000D_
"campus_location": " ",_x000D_
"title": "Self Made Man",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.326272",_x000D_
"latitude": "39.484481"_x000D_
}, {_x000D_
"id": "P1",_x000D_
"category": "4",_x000D_
"title": "Percopo Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.328756",_x000D_
"latitude": "39.481587"_x000D_
}, {_x000D_
"id": "P2",_x000D_
"category": "4",_x000D_
"title": "Speed Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.327361",_x000D_
"latitude": "39.481694"_x000D_
}, {_x000D_
"id": "P3",_x000D_
"category": "4",_x000D_
"title": "Main Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.326245",_x000D_
"latitude": "39.481446"_x000D_
}, {_x000D_
"id": "P4",_x000D_
"category": "4",_x000D_
"title": "Lakeside Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.330848",_x000D_
"latitude": "39.483284"_x000D_
}, {_x000D_
"id": "P5",_x000D_
"category": "4",_x000D_
"title": "Hatfield Hall Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.321417",_x000D_
"latitude": "39.482398"_x000D_
}, {_x000D_
"id": "P6",_x000D_
"category": "4",_x000D_
"title": "Women's Fraternity Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.320977",_x000D_
"latitude": "39.482315"_x000D_
}, {_x000D_
"id": "P7",_x000D_
"category": "4",_x000D_
"title": "Myers and Facilities Parking",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.322243",_x000D_
"latitude": "39.48417"_x000D_
}, {_x000D_
"id": "P8",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.323241",_x000D_
"latitude": "39.484758"_x000D_
}, {_x000D_
"id": "P9",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.323617",_x000D_
"latitude": "39.484311"_x000D_
}, {_x000D_
"id": "P10",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.325714",_x000D_
"latitude": "39.484584"_x000D_
}, {_x000D_
"id": "P11",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.32778",_x000D_
"latitude": "39.484145"_x000D_
}, {_x000D_
"id": "P12",_x000D_
"category": "4",_x000D_
"title": "",_x000D_
"description": "",_x000D_
"image": "",_x000D_
"longitude": "-87.329035",_x000D_
"latitude": "39.4848"_x000D_
}];_x000D_
_x000D_
for (i = 0; i < locations.length; i++) {_x000D_
_x000D_
var marker = new google.maps.Marker({_x000D_
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),_x000D_
title: locations[i].title,_x000D_
map: map_x000D_
});_x000D_
gmarkers.push(marker);_x000D_
google.maps.event.addListener(marker, 'click', (function(marker, i) {_x000D_
return function() {_x000D_
if (locations[i].description !== "" || locations[i].title !== "") {_x000D_
infowindow.setContent('<div class="content" id="content-' + locations[i].id +_x000D_
'" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' +_x000D_
'<hr class="grey" />' +_x000D_
hasImage(locations[i]) +_x000D_
locations[i].description) + '</div>';_x000D_
infowindow.open(map, marker);_x000D_
}_x000D_
}_x000D_
})(marker, i));_x000D_
}_x000D_
_x000D_
function toggleMarkers() {_x000D_
for (i = 0; i < gmarkers.length; i++) {_x000D_
if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);_x000D_
else gmarkers[i].setMap(map);_x000D_
}_x000D_
}_x000D_
_x000D_
function hasImage(location) {_x000D_
return '';_x000D_
}
_x000D_
html,_x000D_
body,_x000D_
#map {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>_x000D_
<div id="controls">_x000D_
<input type="button" value="Toggle All Markers" onClick="toggleMarkers()" />_x000D_
</div>_x000D_
<div id="map"></div>
_x000D_
Although I already wrote an overview of different kinds of popups, most people just need an Alert.
class ViewController: UIViewController {
@IBAction func showAlertButtonTapped(_ sender: UIButton) {
// create the alert
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
My fuller answer is here.
In newer hibernate jars, you can find the required jpa file under "hibernate-search-5.8.0.Final\dist\lib\provided\hibernate-jpa-2.1-api-1.0.0.Final". You have to add this jar file into your project java build path. This will most probably solve the issue.
I have a site that is all .htm and was told by a computer "know it all" to change to .html because it would help google rank.. saved time and $
Since the methods used in other answers seems quite complicated for such easy task, here is a new answer:
Instead of a ListedColormap
, which produces a discrete colormap, you may use a LinearSegmentedColormap
. This can easily be created from a list using the from_list
method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
x,y,c = zip(*np.random.rand(30,3)*4-2)
norm=plt.Normalize(-2,2)
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["red","violet","blue"])
plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
More generally, if you have a list of values (e.g. [-2., -1, 2]
) and corresponding colors, (e.g. ["red","violet","blue"]
), such that the n
th value should correspond to the n
th color, you can normalize the values and supply them as tuples to the from_list
method.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
x,y,c = zip(*np.random.rand(30,3)*4-2)
cvals = [-2., -1, 2]
colors = ["red","violet","blue"]
norm=plt.Normalize(min(cvals),max(cvals))
tuples = list(zip(map(norm,cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
As mentioned elsewhere, you can just iterate over the array and it will produce all results in order across all dimensions. However, if you want to know the indices as well, then how about using this - http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
then doing something like:
var dimensionLengthRanges = Enumerable.Range(0, myArray.Rank).Select(x => Enumerable.Range(0, myArray.GetLength(x)));
var indicesCombinations = dimensionLengthRanges.CartesianProduct();
foreach (var indices in indicesCombinations)
{
Console.WriteLine("[{0}] = {1}", string.Join(",", indices), myArray.GetValue(indices.ToArray()));
}
I had the same error, after 15 min of debugging. Turns out all it needs is a sudo
:)
Check out Create a Docker group to get rid of the sudo prefix.
To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.
Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.
if (process.env.SHOULD_SEND) {
mailer.send();
} else {
console.log("this won't be reached with values like false and 0");
}
Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.
db.connect({
debug: process.env.NODE_ENV === 'development'
});
Firestore now has two functions that allow you to update an array without re-writing the entire thing.
Link: https://firebase.google.com/docs/firestore/manage-data/add-data, specifically https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
Update elements in an array
If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present. arrayRemove() removes all instances of each given element.
If I get your question correctly, you could do something like this.
>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()
which would give you something like
Or as a line plot,
>>> plt.plot(*zip(*testList2))
>>> plt.show()
EDIT - If you want to add a title and labels for the axis, you could do something like
>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()
which would give you
if you want to hide a whole div from the view in another screen size. You can follow bellow code as an example.
div.disabled{
display: none;
}
About Android Studio Gradle plugin version and Required Gradle version, you can see more detailed answer here: What is real Android Studio Gradle Version?
For each version of this Gradle plugin, it requires a minimum Gradle version as listed on below table
(Reference page:gradle-plugin#updating-gradle).
When you update Android Studio, you may receive a prompt to also update Gradle to the latest available version.
For example, Android Gradle Plugin version 3.1.0+ requires a minimal gradle version 4.4.
You can be configured via Android Studio File -> Project Structure -> Project. See below:
Or you can manually modify the file gradle/wrapper/gradle-wrapper.properties
. For example:
distributionUrl = https\://services.gradle.org/distributions/gradle-4.6-all.zip
java.lang.StringBuilder. Use int constructor to create an initial size.
open android location setting programmatically using alert dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(YourActivity.this);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.show();
This worked for me. Its tedious to set all the colour options for a series, especially if it's dynamic
plotOptions: {
column: {
colorByPoint: true
}
}
'a' in x
and a quick search reveals some nice information about it: http://docs.python.org/3/tutorial/datastructures.html#dictionaries
I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.
Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).
Use the code
x = seq(0,100,5) #this means (starting number, ending number, interval)
the output will be
[1] 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
[17] 80 85 90 95 100
To replace anything that starts with "text" until the last character:
text.+(.*)$
Example
text hsjh sdjh sd jhsjhsdjhsdj hsd ^ last character
text.+(\ 123)
Example
text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e ^ ^ From here To here
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;
Note that casting the result won't do it. Because first division is done as per precedence rule.
double d = (double)(5 / 20); //produces 0.0
I do not think there is any problem with casting as such you are thinking about.
Simple Steps...
ALTER TABLE t_name1 ADD FOREIGN KEY (column_name) REFERENCES t_name2(column_name)
Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
Edit:
Ok, I understand your confusion so let me elaborate:
Case 1:
if (myDict.Contains(someKey))
someVal = myDict[someKey];
In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it
Case 2:
myDict.TryGetValue(somekey, out someVal)
In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.
Also very late, but here is an answer from Karvy1 that worked well for me if you don't have pandas >=0.25 version: https://stackoverflow.com/a/52511166/10740287
For the example above you may write:
data = [(row.subject, row.trial_num, sample) for row in df.itertuples() for sample in row.samples]
data = pd.DataFrame(data, columns=['subject', 'trial_num', 'samples'])
Speed test:
%timeit data = pd.DataFrame([(row.subject, row.trial_num, sample) for row in df.itertuples() for sample in row.samples], columns=['subject', 'trial_num', 'samples'])
1.33 ms ± 74.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit data = df.set_index(['subject', 'trial_num'])['samples'].apply(pd.Series).stack().reset_index()
4.9 ms ± 189 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit data = pd.DataFrame({col:np.repeat(df[col].values, df['samples'].str.len())for col in df.columns.drop('samples')}).assign(**{'samples':np.concatenate(df['samples'].values)})
1.38 ms ± 25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
UPDATE TABLE
SET EndDate = CAST('2017-12-31' AS DATE)
WHERE Id = '123'
Instead of using KO's internal functions and dealing with JQuery's blanket event handler removal, a much better idea is using with
or template
bindings. When you do this, ko re-creates that part of DOM and so it automatically gets cleaned. This is also recommended way, see here: https://stackoverflow.com/a/15069509/207661.
import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);
Update
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.
Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences
method of the Context
class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.
(1) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
(2) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE
is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
. In MODE_WORLD_READABLE
other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE
other applications also have write permissions for the created file.
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor
object has to be used. Editor
is a nested interface in the SharedPreference
class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also supports methods like remove()
and clear()
to delete the preference values from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences()
method of the activity. The getPreference
method uses the getSharedPreferences()
method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also the same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference
. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
Talking about efficiency:
document.getElementById( 'elemtId' ).style.display = 'none';
What jQuery does with its .show()
and .hide()
methods is, that it remembers the last state of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.
This may be overkill, but it seemed to work for me:
#!/bin/sh
rm -rfv "$HOME/.vscode"
rm -rfv "$HOME/Library/Application Support/Code"
rm -rfv "$HOME/Library/Caches/com.microsoft.VSCode"
rm -rfv "$HOME/Library/Saved Application State/com.microsoft.VSCode.savedState"
After I ran that, and restarted VSC, it showed the the "Welcome" screen, which I took to mean that it was starting from scratch.
You can't get the file size of local files with javascript in a standard way using a web browser.
But if the file is accessible from a remote path, you might be able to send a HEAD request using Javascript, and read the Content-length header, depending on the webserver
In Express 4.x you can use req.hostname
, which returns the domain name, without port. i.e.:
// Host: "example.com:3000"
req.hostname
// => "example.com"
As mentioned by other here:
Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don't have to have them in Python.
That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.
Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC's for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework. Here you don't subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!
Make sure enable this settings from iOS 9:
App Transport Security Settings in Info.plist to ensure loading image from URL so that it will allow download image and set it.
And write this code:
NSURL *url = [[NSURL alloc]initWithString:@"http://feelgrafix.com/data/images/images-1.jpg"];
NSData *data =[NSData dataWithContentsOfURL:url];
quickViewImage.image = [UIImage imageWithData:data];
The other name of sklearn in anaconda is scikit-learn. simply open your anaconda navigator, go to the environments, select your environment, for example tensorflow or whatever you want to work with, search for scikit_learn in the list of uninstalled packages, apply it and then you can import sklearn in your jupyter.
I think you could also do something like this:
Create and .aspx page, and put this at the end of the OnLoad method, or call it manually.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htmlTW = new HtmlTextWriter(sw);
this.Render(htmlTW);
I'm not sure if there are any potential issues with this, but it looks like it would work. This way, you could use a full featured .aspx page, instead of the MailDefinition class which only supports Text replacements.
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
Though I am 3/4 of a month late, you still execute the following after your where clauses are defined... $this->db->get("tbl_name");
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find
... earlier):
<script type="text/javascript">
$(document).ready(function(){
$("select[showChoices]").each(function(){
$(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'> </span>");
doShowSelected($(this).attr('id'));//shows initial selections
}).change(function(){
doShowSelected($(this).attr('id'));//as user makes new selections
});
});
function doShowSelected(inId){
var aryVals=$("#"+inId).val();
var selText="";
for(var i=0; i<aryVals.length; i++){
var o="#"+inId+" option[value='"+aryVals[i]+"']";
selText+=$(o).text()+"<br>";
}
$("#spn"+inId).html(selText);
}
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
<option selected="selected" value=1>opt 1</option>
<option selected="selected" value=2>opt 2</option>
<option value=3>opt 3</option>
<option value=4>opt 4</option>
</select>
try this css:
/* Show in default resolution screen*/
#container2 {
width: 960px;
position: relative;
margin:0 auto;
line-height: 1.4em;
}
/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */
@media only screen and (max-width: 479px){
#container2 { width: 90%; }
}
Here the demo: http://jsfiddle.net/ongisnade/CG9WN/
Normally you need to have the same number of columns when you're using set based operators so Kangkan's answer is correct.
SAS SQL has specific operator to handle that scenario:
SAS(R) 9.3 SQL Procedure User's Guide
CORRESPONDING (CORR) Keyword
The CORRESPONDING keyword is used only when a set operator is specified. CORR causes PROC SQL to match the columns in table expressions by name and not by ordinal position. Columns that do not match by name are excluded from the result table, except for the OUTER UNION operator.
SELECT * FROM tabA
OUTER UNION CORR
SELECT * FROM tabB;
For:
+---+---+
| a | b |
+---+---+
| 1 | X |
| 2 | Y |
+---+---+
OUTER UNION CORR
+---+---+
| b | d |
+---+---+
| U | 1 |
+---+---+
<=>
+----+----+---+
| a | b | d |
+----+----+---+
| 1 | X | |
| 2 | Y | |
| | U | 1 |
+----+----+---+
U-SQL supports similar concept:
OUTER
requires the BY NAME clause and the ON list. As opposed to the other set expressions, the output schema of the OUTER UNION includes both the matching columns and the non-matching columns from both sides. This creates a situation where each row coming from one of the sides has "missing columns" that are present only on the other side. For such columns, default values are supplied for the "missing cells". The default values are null for nullable types and the .Net default value for the non-nullable types (e.g., 0 for int).
BY NAME
is required when used with OUTER. The clause indicates that the union is matching up values not based on position but by name of the columns. If the BY NAME clause is not specified, the matching is done positionally.
If the ON clause includes the “*” symbol (it may be specified as the last or the only member of the list), then extra name matches beyond those in the ON clause are allowed, and the result’s columns include all matching columns in the order they are present in the left argument.
And code:
@result =
SELECT * FROM @left
OUTER UNION BY NAME ON (*)
SELECT * FROM @right;
EDIT:
The concept of outer union is supported by KQL:
kind:
inner - The result has the subset of columns that are common to all of the input tables.
outer - The result has all the columns that occur in any of the inputs. Cells that were not defined by an input row are set to null.
Example:
let t1 = datatable(col1:long, col2:string)
[1, "a",
2, "b",
3, "c"];
let t2 = datatable(col3:long)
[1,3];
t1 | union kind=outer t2;
Output:
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| 1 | a | |
| 2 | b | |
| 3 | c | |
| | | 1 |
| | | 3 |
+------+------+------+
A simple example would be an app that collects input data from the user and then uses Ajax to upload said data to a database. Here's a simplified example (haven't run it - may have syntax errors):
export default class Task extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
name: "",
age: "",
country: ""
};
}
componentDidUpdate() {
this._commitAutoSave();
}
_changeName = (e) => {
this.setState({name: e.target.value});
}
_changeAge = (e) => {
this.setState({age: e.target.value});
}
_changeCountry = (e) => {
this.setState({country: e.target.value});
}
_commitAutoSave = () => {
Ajax.postJSON('/someAPI/json/autosave', {
name: this.state.name,
age: this.state.age,
country: this.state.country
});
}
render() {
let {name, age, country} = this.state;
return (
<form>
<input type="text" value={name} onChange={this._changeName} />
<input type="text" value={age} onChange={this._changeAge} />
<input type="text" value={country} onChange={this._changeCountry} />
</form>
);
}
}
So whenever the component has a state
change it will autosave the data. There are other ways to implement it too. The componentDidUpdate
is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied. It's probably most useful on complex renders
and state
or DOM changes or when you need something to be the absolutely last thing to be executed.
The example above is rather simple though, but probably proves the point. An improvement could be to limit the amount of times the autosave can execute (e.g max every 10 seconds) because right now it will run on every key-stroke.
I made a demo on this fiddle as well to demonstrate.
For more info, refer to the official docs:
componentDidUpdate()
is invoked immediately after updating occurs. This method is not called for the initial render.Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
I've run a benchmark today and came up with interesting result. Among these three:
var count1 = typeof(TestEnum).GetFields().Length;
var count2 = Enum.GetNames(typeof(TestEnum)).Length;
var count3 = Enum.GetValues(typeof(TestEnum)).Length;
GetNames(enum) is by far the fastest!
| Method | Mean | Error | StdDev |
|--------------- |---------- |--------- |--------- |
| DeclaredFields | 94.12 ns | 0.878 ns | 0.778 ns |
| GetNames | 47.15 ns | 0.554 ns | 0.491 ns |
| GetValues | 671.30 ns | 5.667 ns | 4.732 ns |
str="abcdef"
str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">
Hope it helps. :)
Use a real iterator.
Iterator<Object> it = map.keySet().iterator();
while (it.hasNext())
{
it.next();
if (something)
it.remove();
}
Actually, you might need to iterate over the entrySet()
instead of the keySet()
to make that work.
Input these code to your SCRATCHPAD and see the action.
var str=String("Blah-Blah1_2,oo0.01&zz%kick").replace(/[^\w-]/ig, '');
You need to create a header with a proper formatted User agent String, it server to communicate client-server.
You can check your own user agent Here.
Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0
I found this module very simple to use, in one line of code it randomly generates a User agent string.
from user_agent import generate_user_agent, generate_navigator
from pprint import pprint
print(generate_user_agent())
# 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.3; Win64; x64)'
print(generate_user_agent(os=('mac', 'linux')))
# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:36.0) Gecko/20100101 Firefox/36.0'
pprint(generate_navigator())
# {'app_code_name': 'Mozilla',
# 'app_name': 'Netscape',
# 'appversion': '5.0',
# 'name': 'firefox',
# 'os': 'linux',
# 'oscpu': 'Linux i686 on x86_64',
# 'platform': 'Linux i686 on x86_64',
# 'user_agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',
# 'version': '41.0'}
pprint(generate_navigator_js())
# {'appCodeName': 'Mozilla',
# 'appName': 'Netscape',
# 'appVersion': '38.0',
# 'platform': 'MacIntel',
# 'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:38.0) Gecko/20100101 Firefox/38.0'}
I wanted to create a new enumerable object or list and be able to add to it.
This comment changes everything. You can't add to a generic IEnumerable<T>
. If you want to stay with the interfaces in System.Collections.Generic
, you need to use a class that implements ICollection<T>
like List<T>
.
If you want to view the progress of the dump try this:
pv -i 1 -p -t -e /path/to/sql/dump | mysql -u USERNAME -p DATABASE_NAME
You'll of course need 'pv' installed. This command works only on *nix.
try:
var url = '/Home/Index/' + e.value;
window.location = window.location.host + url;
That should get you where you want.
It's a bit late but I think your issue may be that you've created a zero-length array, rather than an array of length 1.
A string is a series of characters followed by a string terminator ('\0'
). An empty string (""
) consists of no characters followed by a single string terminator character - i.e. one character in total.
So I would try the following:
string[1] = ""
Note that this behaviour is not the emulated by strlen
, which does not count the terminator as part of the string length.
I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.
I think your best bet is to store it as a CHAR(60)
as it is always 60 chars long
So, this is a code snippet to help better understand this topic.
Printing Tokens
Task: Given a sentence, s, print each word of the sentence in a new line.
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//logic to print the tokens of the sentence.
for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
printf("%s\n",p);
}
Input: How is that
Result:
How
is
that
Explanation: So here, "strtok()" function is used and it's iterated using for loop to print the tokens in separate lines.
The function will take parameters as 'string' and 'break-point' and break the string at those break-points and form tokens. Now, those tokens are stored in 'p' and are used further for printing.
The ONESHELL directive allows to write multiple line recipes to be executed in the same shell invocation.
all: foo
SOURCE_FILES = $(shell find . -name '*.c')
.ONESHELL:
foo: ${SOURCE_FILES}
FILES=()
for F in $^; do
FILES+=($${F})
done
gcc "$${FILES[@]}" -o $@
There is a drawback though : special prefix characters (‘@’, ‘-’, and ‘+’) are interpreted differently.
https://www.gnu.org/software/make/manual/html_node/One-Shell.html
Use PHP basename()
(PHP 4, PHP 5)
var_dump(basename('test.php', '.php'));
Outputs: string(4) "test"
This is an easy way to do it:
String formato = String.format("%.2f");
It sets the precision to 2 digits.
If you only want to print, use it this way:
System.out.printf("%.2f",123.234);
Actually you can pass a parameter ( http://docs.angularjs.org/api/ng.filter:filter ) and don't need a custom function just for this. If you rewrite your HTML as below it'll work:
<div ng:app>
<div ng-controller="HelloCntl">
<ul>
<li ng-repeat="friend in friends | filter:{name:'!Adam'}">
<span>{{friend.name}}</span>
<span>{{friend.phone}}</span>
</li>
</ul>
</div>
</div>
Well, the last time someone asked this silly question, the answer was:
someString.equals("null")
This "fix" only hides the bigger problem of how null
becomes "null"
in the first place, though.
I prefer not to alter the df
.
An option is to retrieve the index
of the start
and end
dates:
import numpy as np
import pandas as pd
#Dummy DataFrame
df = pd.DataFrame(np.random.random((30, 3)))
df['date'] = pd.date_range('2017-1-1', periods=30, freq='D')
#Get the index of the start and end dates respectively
start = df[df['date']=='2017-01-07'].index[0]
end = df[df['date']=='2017-01-14'].index[0]
#Show the sliced df (from 2017-01-07 to 2017-01-14)
df.loc[start:end]
which results in:
0 1 2 date
6 0.5 0.8 0.8 2017-01-07
7 0.0 0.7 0.3 2017-01-08
8 0.8 0.9 0.0 2017-01-09
9 0.0 0.2 1.0 2017-01-10
10 0.6 0.1 0.9 2017-01-11
11 0.5 0.3 0.9 2017-01-12
12 0.5 0.4 0.3 2017-01-13
13 0.4 0.9 0.9 2017-01-14
From http://www.epochconverter.com/
SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
My bad, SELECT unix_timestamp(time) Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD. More on using timestamps with MySQL:
http://www.epochconverter.com/programming/mysql-from-unixtime.php
Some times, local config command won't show the proxy but it wont allow git push due to proxy. Run the following commands within the directory and see.
#git config --local --list
But the following commands displays the proxy set to local repository:
#git config http.proxy
#git config https.proxy
If the above command displays any proxy then clear it by running the following commands:
#git config https.proxy ""
#git config https.proxy ""
What about a helper function like this:
function makeDir($path)
{
$ret = mkdir($path); // use @mkdir if you want to suppress warnings/errors
return $ret === true || is_dir($path);
}
It will return true
if the directory was successfully created or already exists, and false
if the directory couldn't be created.
A better alternative is this (shouldn't give any warnings):
function makeDir($path)
{
return is_dir($path) || mkdir($path);
}
Compilr seems to be going in that direction: http://compilr.com/teachers
This can dedupe the duplicated values in c1
:
select * from foo
minus
select f1.* from foo f1, foo f2
where f1.c1 = f2.c1 and f1.c2 > f2.c2
Here is a demo code where there is pagination + Filtering with AngularJS :
https://codepen.io/lamjaguar/pen/yOrVym
JS :
var app=angular.module('myApp', []);
// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html
app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.q = '';
$scope.getData = function () {
// needed for the pagination calc
// https://docs.angularjs.org/api/ng/filter/filter
return $filter('filter')($scope.data, $scope.q)
/*
// manual filter
// if u used this, remove the filter from html, remove above line and replace data with getData()
var arr = [];
if($scope.q == '') {
arr = $scope.data;
} else {
for(var ea in $scope.data) {
if($scope.data[ea].indexOf($scope.q) > -1) {
arr.push( $scope.data[ea] );
}
}
}
return arr;
*/
}
$scope.numberOfPages=function(){
return Math.ceil($scope.getData().length/$scope.pageSize);
}
for (var i=0; i<65; i++) {
$scope.data.push("Item "+i);
}
// A watch to bring us back to the
// first pagination after each
// filtering
$scope.$watch('q', function(newValue,oldValue){ if(oldValue!=newValue){
$scope.currentPage = 0;
}
},true);
}]);
//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
HTML :
<div ng-app="myApp" ng-controller="MyCtrl">
<input ng-model="q" id="search" class="form-control" placeholder="Filter text">
<select ng-model="pageSize" id="pageSize" class="form-control">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<ul>
<li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
{{item}}
</li>
</ul>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button> {{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
An OutputStream
is one where you write data to. If some module exposes an OutputStream
, the expectation is that there is something reading at the other end.
Something that exposes an InputStream
, on the other hand, is indicating that you will need to listen to this stream, and there will be data that you can read.
So it is possible to connect an InputStream
to an OutputStream
InputStream----read---> intermediateBytes[n] ----write----> OutputStream
As someone metioned, this is what the copy()
method from IOUtils lets you do. It does not make sense to go the other way... hopefully this makes some sense
UPDATE:
Of course the more I think of this, the more I can see how this actually would be a requirement. I know some of the comments mentioned Piped
input/ouput streams, but there is another possibility.
If the output stream that is exposed is a ByteArrayOutputStream
, then you can always get the full contents by calling the toByteArray()
method. Then you can create an input stream wrapper by using the ByteArrayInputStream
sub-class. These two are pseudo-streams, they both basically just wrap an array of bytes. Using the streams this way, therefore, is technically possible, but to me it is still very strange...
From $ man curl
:
--cert-type <type>
(SSL) Tells curl what certificate type the provided certificate
is in. PEM, DER and ENG are recognized types. If not specified,
PEM is assumed.
If this option is used several times, the last one will be used.
--cacert <CA certificate>
(SSL) Tells curl to use the specified certificate file to verify
the peer. The file may contain multiple CA certificates. The
certificate(s) must be in PEM format. Normally curl is built to
use a default file for this, so this option is typically used to
alter that default file.
ZBar
Pre-requisites:
choco install zbar
pip install pyzbar
To decode:
from PIL import Image
from pyzbar import pyzbar
img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)
Alternatively, you can also try using ZBarLight
by setting it up as mentioned here:
https://pypi.org/project/zbarlight/
For Mac OS X Yosemite I was able to use the open command.
Usage: open [-e] [-t] [-f] [-W] [-R] [-n] [-g] [-h] [-b <bundle identifier>] [-a <application>] [filenames] [--args arguments]
Help: Open opens files from a shell.
By default, opens each file using the default application for that file.
If the file is in the form of a URL, the file will be opened as a URL.
Options:
-a Opens with the specified application.
-b Opens with the specified application bundle identifier.
-e Opens with TextEdit.
-t Opens with default text editor.
-f Reads input from standard input and opens with TextEdit.
-F --fresh Launches the app fresh, that is, without restoring windows. Saved persistent state is lost, excluding Untitled documents.
-R, --reveal Selects in the Finder instead of opening.
-W, --wait-apps Blocks until the used applications are closed (even if they were already running).
--args All remaining arguments are passed in argv to the application's main() function instead of opened.
-n, --new Open a new instance of the application even if one is already running.
-j, --hide Launches the app hidden.
-g, --background Does not bring the application to the foreground.
-h, --header Searches header file locations for headers matching the given filenames, and opens them.
This worked for me:
open eclipse.app --args clean
Using ES6 destructuring: (avoiding mutation off the original array)
const newArr = [item, ...oldArr]
ITNOA
You can use C++ function for doing this.
std::string repeat(const std::string& input, size_t num)
{
std::ostringstream os;
std::fill_n(std::ostream_iterator<std::string>(os), num, input);
return os.str();
}
If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
?var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);??????
You can call tail +[line number] [file]
and pipe it to grep -n
which shows the line number:
tail +[line number] [file] | grep -n /regex/
The only problem with this method is the line numbers reported by grep -n
will be [line number] - 1
less than the actual line number in [file]
.
For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.
In Views
person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()
In Template
{{ person.get_gender_display }}
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
I see this question is a bit old, but I decided to give an answer anyway for those who find this question by searching.
The standard way to represent 2D/3D transformations nowadays is by using homogeneous coordinates. [x,y,w] for 2D, and [x,y,z,w] for 3D. Since you have three axes in 3D as well as translation, that information fits perfectly in a 4x4 transformation matrix. I will use column-major matrix notation in this explanation. All matrices are 4x4 unless noted otherwise.
The stages from 3D points and to a rasterized point, line or polygon looks like this:
This stage is the actual projection, because z isn't used as a component in the position any more.
This calculates the field-of view. Whether tan takes radians or degrees is irrelevant, but angle must match. Notice that the result reaches infinity as angle nears 180 degrees. This is a singularity, as it is impossible to have a focal point that wide. If you want numerical stability, keep angle less or equal to 179 degrees.
fov = 1.0 / tan(angle/2.0)
Also notice that 1.0 / tan(45) = 1. Someone else here suggested to just divide by z. The result here is clear. You would get a 90 degree FOV and an aspect ratio of 1:1. Using homogeneous coordinates like this has several other advantages as well; we can for example perform clipping against the near and far planes without treating it as a special case.
This is the layout of the clip matrix. aspectRatio is Width/Height. So the FOV for the x component is scaled based on FOV for y. Far and near are coefficients which are the distances for the near and far clipping planes.
[fov * aspectRatio][ 0 ][ 0 ][ 0 ]
[ 0 ][ fov ][ 0 ][ 0 ]
[ 0 ][ 0 ][(far+near)/(far-near) ][ 1 ]
[ 0 ][ 0 ][(2*near*far)/(near-far)][ 0 ]
After clipping, this is the final transformation to get our screen coordinates.
new_x = (x * Width ) / (2.0 * w) + halfWidth;
new_y = (y * Height) / (2.0 * w) + halfHeight;
#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>
struct Vector
{
Vector() : x(0),y(0),z(0),w(1){}
Vector(float a, float b, float c) : x(a),y(b),z(c),w(1){}
/* Assume proper operator overloads here, with vectors and scalars */
float Length() const
{
return std::sqrt(x*x + y*y + z*z);
}
Vector Unit() const
{
const float epsilon = 1e-6;
float mag = Length();
if(mag < epsilon){
std::out_of_range e("");
throw e;
}
return *this / mag;
}
};
inline float Dot(const Vector& v1, const Vector& v2)
{
return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}
class Matrix
{
public:
Matrix() : data(16)
{
Identity();
}
void Identity()
{
std::fill(data.begin(), data.end(), float(0));
data[0] = data[5] = data[10] = data[15] = 1.0f;
}
float& operator[](size_t index)
{
if(index >= 16){
std::out_of_range e("");
throw e;
}
return data[index];
}
Matrix operator*(const Matrix& m) const
{
Matrix dst;
int col;
for(int y=0; y<4; ++y){
col = y*4;
for(int x=0; x<4; ++x){
for(int i=0; i<4; ++i){
dst[x+col] += m[i+col]*data[x+i*4];
}
}
}
return dst;
}
Matrix& operator*=(const Matrix& m)
{
*this = (*this) * m;
return *this;
}
/* The interesting stuff */
void SetupClipMatrix(float fov, float aspectRatio, float near, float far)
{
Identity();
float f = 1.0f / std::tan(fov * 0.5f);
data[0] = f*aspectRatio;
data[5] = f;
data[10] = (far+near) / (far-near);
data[11] = 1.0f; /* this 'plugs' the old z into w */
data[14] = (2.0f*near*far) / (near-far);
data[15] = 0.0f;
}
std::vector<float> data;
};
inline Vector operator*(const Vector& v, const Matrix& m)
{
Vector dst;
dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8 ] + v.w*m[12];
dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9 ] + v.w*m[13];
dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
return dst;
}
typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip(int width, int height, float near, float far, const VecArr& vertex)
{
float halfWidth = (float)width * 0.5f;
float halfHeight = (float)height * 0.5f;
float aspect = (float)width / (float)height;
Vector v;
Matrix clipMatrix;
VecArr dst;
clipMatrix.SetupClipMatrix(60.0f * (M_PI / 180.0f), aspect, near, far);
/* Here, after the perspective divide, you perform Sutherland-Hodgeman clipping
by checking if the x, y and z components are inside the range of [-w, w].
One checks each vector component seperately against each plane. Per-vertex
data like colours, normals and texture coordinates need to be linearly
interpolated for clipped edges to reflect the change. If the edge (v0,v1)
is tested against the positive x plane, and v1 is outside, the interpolant
becomes: (v1.x - w) / (v1.x - v0.x)
I skip this stage all together to be brief.
*/
for(VecArr::iterator i=vertex.begin(); i!=vertex.end(); ++i){
v = (*i) * clipMatrix;
v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
dst.push_back(v);
}
/* TODO: Clipping here */
for(VecArr::iterator i=dst.begin(); i!=dst.end(); ++i){
i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
}
return dst;
}
If you still ponder about this, the OpenGL specification is a really nice reference for the maths involved. The DevMaster forums at http://www.devmaster.net/ have a lot of nice articles related to software rasterizers as well.
If you run GPEdit.MSC you can go to Computer Configuration -> Windows Settings -> Scripts, and add startup /shutdown scripts. These can be simple batch files, or even full blown EXEs. Also you can adjust user configurations for logon and logoff scripts in this same tool. This tool is not available in WIndows XP Home.
You can create a single script that calls all the others.
Put the following into a batch file:
@echo off
echo.>"%~dp0all.sql"
for %%i in ("%~dp0"*.sql) do echo @"%%~fi" >> "%~dp0all.sql"
When you run that batch file it will create a new script named all.sql
in the same directory where the batch file is located. It will look for all files with the extension .sql
in the same directory where the batch file is located.
You can then run all scripts by using sqlplus user/pwd @all.sql
(or extend the batch file to call sqlplus
after creating the all.sql
script)
For Python3 I needed to do this:
python3 -m pip install MySQL
How about this? Just give it a thought-
import java.util.ArrayList;
class Solution
{
public static void main (String[] args){
ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");
int i[] = {1,3,5};
for (int j = 0; j < i.length; j++) {
List_Of_Array.remove(i[j]-j);
}
System.out.println(List_Of_Array);
}
}
And the output was-
[A, C, E, G, H]
Javascript has a ternary operator you could use:
var i = result ? 1 : 0;
If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.
$scope.login = function () {
$scope.btntext = "Please wait...!";
$http({
method: "POST",
url: '/Home/userlogin', // link UserLogin with HomeController
data: $scope.user
}).then(function (response) {
console.log("Result value is : " + parseInt(response));
data = response.data;
$scope.btntext = 'Login';
if (data == 1) {
window.location.href = '/Home/dashboard';
}
else {
alert(data);
}
}, function (error) {
alert("Failed Login");
});
The above snipit works for a login page.
You don't have to specify the size of an array when you instantiate it.
You can still declare the array and instantiate it later. For instance:
string[] myArray;
...
myArray = new string[size];
A character encoding is a way to encode characters so that they fit in memory. That is, if the charset is ISO-8859-15, the euro symbol, €, will be encoded as 0xa4, and in UTF-8, it will be 0xe282ac.
The collation is how to compare characters, in latin9, there are letters as e é è ê f
, if sorted by their binary representation, it will go e f é ê è
but if the collation is set to, for example, French, you'll have them in the order you thought they would be, which is all of e é è ê
are equal, and then f
.
you can use regular expressions to identify the last comma (,) and replace it with " " as follow:
if(fieldName.endsWith(","))
{
fieldName = fieldName.replace(/,([^,]*)$/," ");
}
In Solution Explorer, please select files you want to copied to output directory and assign two properties: - Build action = Content - Copy to Output Directory = Copy Always
This will do the trick.
The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent).
In your example you can either choose to use your top level shell to perform the piping like so:
find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep'
In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep.
This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat.
If you for some reason would like to invoke agrep multiple times, you can do:
find . -name 'file_*' -follow -type f \
-printf "zcat %p | agrep -dEOE 'grep'\n" | sh
This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed. (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.)
In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep.
The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin:
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.
You can try to search in preferences (android studio IDE > preferences). In aptana studio it works like this making smaller: CMD and -, use CMD shift and =. Works?
The method suggested by @roe and @MohitNanda work, but if the right div is set as float:right;
, then it must come first in the HTML source. This breaks the left-to-right read order, which could be confusing if the page is displayed with styles turned off. If that's the case, it might be better to use a wrapper div and absolute positioning:
<div id="wrap" style="position:relative;">
<div id="left" style="margin-right:201px;border:1px solid red;">left</div>
<div id="right" style="position:absolute;width:200px;right:0;top:0;border:1px solid blue;">right</div>
</div>
Demonstrated:
left rightEdit: Hmm, interesting. The preview window shows the correctly formatted divs, but the rendered post item does not. Sorry then, you'll have to try it for yourself.
In your main.py
:
from user import Class
where Class
is the name of the class you want to import.
If you want to call a method of Class
, you can call it using:
Class.method
Note that there should be an empty __init__.py
file in the same directory.
Using Process.Start:
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("example.txt");
}
}
The URL file://[servername]/[sharename]
should open an explorer window to the shared folder on the network.
You can easily make lists of lists
list1 <- list(a = 2, b = 3)
list2 <- list(c = "a", d = "b")
mylist <- list(list1, list2)
mylist is now a list that contains two lists. To access list1 you can use mylist[[1]]
. If you want to be able to something like mylist$list1
then you need to do somethingl like
mylist <- list(list1 = list1, list2 = list2)
# Now you can do the following
mylist$list1
Edit: To reply to your edit. Just use double bracket indexing
a <- list_all[[1]]
a[[1]]
#[1] 1
a[[2]]
#[1] 2
I had the same problem. At least I could solve it with this:
sudo yum install gcc gcc-c++
Hope it solves your problem too.
foreach loop is faster than array_merge to append values to an existing array, so choose the loop instead if you want to add an array to the end of another.
// Create an array of arrays
$chars = [];
for ($i = 0; $i < 15000; $i++) {
$chars[] = array_fill(0, 10, 'a');
}
// test array_merge
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
$new = array_merge($new, $splitArray);
}
echo microtime(true) - $start; // => 14.61776 sec
// test foreach
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
foreach ($splitArray as $value) {
$new[] = $value;
}
}
echo microtime(true) - $start; // => 0.00900101 sec
// ==> 1600 times faster
If you have an issue, you need to locate your pg_hba.conf
. The command is:
find / -name 'pg_hba.conf' 2>/dev/null
and after that change the configuration file:
Postgresql 9.3
Postgresql 9.4
The next step is: Restarting your db instance:
service postgresql-9.3 restart
If you have any problems, you need to set password again:
ALTER USER db_user with password 'db_password';
Especially for the older Git versions, most of the suggestions won't work that well. If that's the case, I'd put a separate .gitignore in the directory where I want the content to be included regardless of other settings and allow there what is needed.
For example: /.gitignore
# ignore all .dll files
*.dll
/dependency_files/.gitignore
# include everything
!*
So everything in /dependency_files (even .dll files) are included just fine.
I just barely ran into this problem when trying to display a loading spinner while I waited for a function to complete. Because I was appending the spinner into the HTML, the spinner would be duplicated each time the button was clicked, if you're not against defining a variable on the global scale, then this worked well for me.
var hasCardButtonBeenClicked = '';
$(".js-mela-card-button").on("click", function(){
if(!hasCardButtonBeenClicked){
hasCardButtonBeenClicked = true;
$(this).append('<i class="fa fa-circle-o-notch fa-spin" style="margin-left: 3px; font-size: 15px;" aria-hidden="true"></i>');
}
});
Notice, all I'm doing is declaring a variable, and as long as its value is null, the actions following the click will occur and then subsequently set the variables value to "true" (it could be any value, as long as it's not empty), further disabling the button until the browser is refreshed or the variable is set to null.
Looking back it probably would have made more sense to just set the hasCardButtonBeenClicked variable to "false" to begin with, and then alternate between "true" and "false" as needed.
You should do this instead:
for i in myList:
# etc.
That is, remove the range()
part. The range()
function is used to generate a sequence of numbers, and it receives as parameters the limits to generate the range, it won't work to pass a list as parameter. For iterating over the list, just write the loop as shown above.
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
model.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
y_pred=model.predict(test_x,batch_size=15)
cm =confusion_matrix(test_y.argmax(axis=1), y_pred.argmax(axis=1))
index = ['neutral','happy','sad']
columns = ['neutral','happy','sad']
cm_df = pd.DataFrame(cm,columns,index)
plt.figure(figsize=(10,6))
sns.heatmap(cm_df, annot=True)
To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified all '.lib' files & there names for current project.
So, Developer has to specify external dependencies for Project as below..
1. Select Project in Solution explorer.
2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".
3. Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".
For some reason using python3 I had to escape the "\"-sign
somestring.replace('\\n', '')
Hope this helps someone else!
If you've populated the form with an instance and not with POST data (as the suggested answer requires), you can access the data using {{ form.instance.my_field_name }}.
It looks as if you are using the URL.toString
result as the argument to the FileReader
constructor. URL.toString
is a bit broken, and instead you should generally use url.toURI().toString()
. In any case, the string is not a file path.
Instead, you should either:
URL
to ServicesLoader
and let it call openStream
or similar.Class.getResourceAsStream
and just pass the stream over, possibly inside an InputSource
. (Remember to check for nulls as the API is a bit messy.)you can try
$(function()
{
$(window).bind('load', function()
{
// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...
});
});
i had the same problem and this code worked for me. how it works for you too!
In general, I break lines before operators, and indent the subsequent lines:
Map<long parameterization> longMap
= new HashMap<ditto>();
String longString = "some long text"
+ " some more long text";
To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.
EDIT 2020-09-21: Since 3.4.0, Mockito supports mocking static methods, API is still incubating and is likely to change, in particular around stubbing and verification. It requires the mockito-inline
artifact. And you don't need to prepare the test or use any specific runner. All you need to do is :
@Test
public void name() {
try (MockedStatic<LoggerFactory> integerMock = mockStatic(LoggerFactory.class)) {
final Logger logger = mock(Logger.class);
integerMock.when(() -> LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
new Controller().log();
verify(logger).warn(any());
}
}
The two inportant aspect in this code, is that you need to scope when the static mock applies, i.e. within this try block. And you need to call the stubbing and verification api from the MockedStatic
object.
@Mick, try to prepare the owner of the static field too, eg :
@PrepareForTest({GoodbyeController.class, LoggerFactory.class})
EDIT1 : I just crafted a small example. First the controller :
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Controller {
Logger logger = LoggerFactory.getLogger(Controller.class);
public void log() { logger.warn("yup"); }
}
Then the test :
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Controller.class, LoggerFactory.class})
public class ControllerTest {
@Test
public void name() throws Exception {
mockStatic(LoggerFactory.class);
Logger logger = mock(Logger.class);
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
new Controller().log();
verify(logger).warn(anyString());
}
}
Note the imports ! Noteworthy libs in the classpath : Mockito, PowerMock, JUnit, logback-core, logback-clasic, slf4j
EDIT2 : As it seems to be a popular question, I'd like to point out that if these log messages are that important and require to be tested, i.e. they are feature / business part of the system then introducing a real dependency that make clear theses logs are features would be a so much better in the whole system design, instead of relying on static code of a standard and technical classes of a logger.
For this matter I would recommend to craft something like= a Reporter
class with methods such as reportIncorrectUseOfYAndZForActionX
or reportProgressStartedForActionX
. This would have the benefit of making the feature visible for anyone reading the code. But it will also help to achieve tests, change the implementations details of this particular feature.
Hence you wouldn't need static mocking tools like PowerMock. In my opinion static code can be fine, but as soon as the test demands to verify or to mock static behavior it is necessary to refactor and introduce clear dependencies.
First off, RangeToHTML
. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.
On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.
For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
' Only send the visible cells in the selection.
Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng)
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.
The error occurred when I unknowingly tried plotting the image path instead of the image.
My code :
import cv2 as cv
from matplotlib import pyplot as plt
import pytesseract
from resizeimage import resizeimage
img = cv.imread("D:\TemplateMatch\\fitting.png") ------>"THIS IS THE WRONG USAGE"
#cv.rectangle(img,(29,2496),(604,2992),(255,0,0),5)
plt.imshow(img)
Correction:
img = cv.imread("fitting.png")
--->THIS IS THE RIGHT USAGE"
In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:
$.ajax(
'https://foo.bar.com,
{
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: successFunc
}
);
The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:
An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT
You can try the Boost Tokenizer library, in particular the Escaped List Separator
A local variable is only accessible from within the block of it's initialization. Also a local variable begins with a lower case letter (a-z) or underscore (_).
And instance variable is an instance of self
and begins with a @
Also an instance variable belongs to the object itself. Instance variables are the ones that you perform methods on i.e. .send
etc
example:
@user = User.all
The @user
is the instance variable
And Uninitialized instance variables have a value of Nil
A quick answer:
mvn -fn test
Works with nested project builds.
There are also these 'ways':
>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}
Field[] field = model.getClass().getDeclaredFields();
for(int j=0 ; j<field.length ; j++){
String name = field[j].getName();
name = name.substring(0,1).toUpperCase()+name.substring(1);
String type = field[j].getGenericType().toString();
if(type.equals("class java.lang.String")){
Method m = model.getClass().getMethod("get"+name);
String value = (String) m.invoke(model);
if(value == null){
... something to do...
}
}
return Json(data,JsonRequestBehavior.AllowGet);
I will recommend to use an alternative method using seaborn
which more powerful tool for data plotting. You can use seaborn scatterplot
and define colum 3 as hue
and size
.
Working code:
import pandas as pd
import seaborn as sns
import numpy as np
#creating sample data
sample_data={'col_name_1':np.random.rand(20),
'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")
I know this is an old post but i want to share my experience.
HTML:
<input type="text" placeholder="Username or E-Mail" required data-required-message="E-Mail or Username is Required!">
Javascript (jQuery):
$('input[required]').on('invalid', function() {
this.setCustomValidity($(this).data("required-message"));
});
This is a very simple sample. I hope this can help to anyone.
Try this:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :
https://gist.github.com/smalot/6183152
Hope it helps everone
It's more complicated than the language you used to write your project. Getting it configured right is harder than actual programming.
CATALINA_HOME
vs CATALINA_BASE
If you're running multiple instances, then you need both variables, otherwise only CATALINA_HOME
.
In other words: CATALINA_HOME
is required and CATALINA_BASE
is optional.
CATALINA_HOME
represents the root of your Tomcat installation.
Optionally, Tomcat may be configured for multiple instances by defining
$CATALINA_BASE
for each instance. If multiple instances are not configured,$CATALINA_BASE
is the same as$CATALINA_HOME
.
See: Apache Tomcat 7 - Introduction
Running with separate CATALINA_HOME
and CATALINA_BASE
is documented in RUNNING.txt which say:
The
CATALINA_HOME
andCATALINA_BASE
environment variables are used to specify the location of Apache Tomcat and the location of its active configuration, respectively.You cannot configure
CATALINA_HOME
andCATALINA_BASE
variables in thesetenv
script, because they are used to find that file.
For example:
(4.1) Tomcat can be started by executing one of the following commands:
%CATALINA_HOME%\bin\startup.bat (Windows) $CATALINA_HOME/bin/startup.sh (Unix)
or
%CATALINA_HOME%\bin\catalina.bat start (Windows) $CATALINA_HOME/bin/catalina.sh start (Unix)
In many circumstances, it is desirable to have a single copy of a Tomcat binary distribution shared among multiple users on the same server. To make this possible, you can set the
CATALINA_BASE
environment variable to the directory that contains the files for your 'personal' Tomcat instance.When running with a separate
CATALINA_HOME
andCATALINA_BASE
, the files and directories are split as following:In
CATALINA_BASE
:
bin
- Only: setenv.sh (*nix) or setenv.bat (Windows), tomcat-juli.jarconf
- Server configuration files (including server.xml)lib
- Libraries and classes, as explained belowlogs
- Log and output fileswebapps
- Automatically loaded web applicationswork
- Temporary working directories for web applicationstemp
- Directory used by the JVM for temporary files>In
CATALINA_HOME
:
bin
- Startup and shutdown scriptslib
- Libraries and classes, as explained belowendorsed
- Libraries that override standard "Endorsed Standards". By default it's absent.
The easiest way to check what's your CATALINA_BASE
and CATALINA_HOME
is by running startup.sh
, for example:
$ /usr/share/tomcat7/bin/startup.sh
Using CATALINA_BASE: /usr/share/tomcat7
Using CATALINA_HOME: /usr/share/tomcat7
You may also check where the Tomcat files are installed, by dpkg
tool as below (Debian/Ubuntu):
dpkg -L tomcat7-common
i got the same error, but with no relation to Hibernate. I got scared here from all frightening suggestions, which i guess relevant in case of Hibernate and lazy loading... However, in my case i got the error since in an inner class i had no getters/setters, so the BeanSerializer could not serialize the data...
Adding getters & setters resolved the problem.
Other way is using concat() function:
import pandas as pd
In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))
In [604]: df
Out[604]:
col1 col2
0 a 0
1 b 1
2 c 2
In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]:
col1 col2
0 a 0
1 b 1
2 c 2
3 a 0
4 b 1
5 c 2
6 a 0
7 b 1
8 c 2
In [606]: pd.concat([df]*3)
Out[606]:
col1 col2
0 a 0
1 b 1
2 c 2
0 a 0
1 b 1
2 c 2
0 a 0
1 b 1
2 c 2
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
<form method = 'post' action = '' id = 'theForm'>
...
</form>
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data
above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET
super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success
function is called, and any and all output produced by the PHP script will be stored in the variable html
.
...
success: function(html) {
alert(html);
}
...
I came across this question while exploring suggested solutions for a similar problem; I presume that for future reference it may be worthwhile to update the available list of answer with a solution utilising the broom
package.
x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
require(broom)
glance(fit)
>> glance(fit)
r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC deviance df.residual
1 0.5442762 0.5396729 1.502943 118.2368 1.3719e-18 2 -183.4527 372.9055 380.7508 223.6251 99
I find the glance
function is useful as it neatly summarises the key values. The results are stored as a data.frame
which makes further manipulation easy:
>> class(glance(fit))
[1] "data.frame"
public static string FromSqlType(string sqlTypeString)
{
if (! Enum.TryParse(sqlTypeString, out Enums.SQLType typeCode))
{
throw new Exception("sql type not found");
}
switch (typeCode)
{
case Enums.SQLType.varbinary:
case Enums.SQLType.binary:
case Enums.SQLType.filestream:
case Enums.SQLType.image:
case Enums.SQLType.rowversion:
case Enums.SQLType.timestamp://?
return "byte[]";
case Enums.SQLType.tinyint:
return "byte";
case Enums.SQLType.varchar:
case Enums.SQLType.nvarchar:
case Enums.SQLType.nchar:
case Enums.SQLType.text:
case Enums.SQLType.ntext:
case Enums.SQLType.xml:
return "string";
case Enums.SQLType.@char:
return "char";
case Enums.SQLType.bigint:
return "long";
case Enums.SQLType.bit:
return "bool";
case Enums.SQLType.smalldatetime:
case Enums.SQLType.datetime:
case Enums.SQLType.date:
case Enums.SQLType.datetime2:
return "DateTime";
case Enums.SQLType.datetimeoffset:
return "DateTimeOffset";
case Enums.SQLType.@decimal:
case Enums.SQLType.money:
case Enums.SQLType.numeric:
case Enums.SQLType.smallmoney:
return "decimal";
case Enums.SQLType.@float:
return "double";
case Enums.SQLType.@int:
return "int";
case Enums.SQLType.real:
return "Single";
case Enums.SQLType.smallint:
return "short";
case Enums.SQLType.uniqueidentifier:
return "Guid";
case Enums.SQLType.sql_variant:
return "object";
case Enums.SQLType.time:
return "TimeSpan";
default:
throw new Exception("none equal type");
}
}
public enum SQLType
{
varbinary,//(1)
binary,//(1)
image,
varchar,
@char,
nvarchar,//(1)
nchar,//(1)
text,
ntext,
uniqueidentifier,
rowversion,
bit,
tinyint,
smallint,
@int,
bigint,
smallmoney,
money,
numeric,
@decimal,
real,
@float,
smalldatetime,
datetime,
sql_variant,
table,
cursor,
timestamp,
xml,
date,
datetime2,
datetimeoffset,
filestream,
time,
}
recyclerList.setOnScrollListener(new RecyclerView.OnScrollListener()
{
@Override
public void onScrolled(RecyclerView recyclerView, int dx,int dy)
{
super.onScrolled(recyclerView, dx, dy);
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView,int newState)
{
int totalItemCount = layoutManager.getItemCount();
int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
if (totalItemCount> 1)
{
if (lastVisibleItem >= totalItemCount - 1)
{
// End has been reached
// do something
}
}
}
});
There's actually a pretty good implementation of a class decorator here:
https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py
I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like isinstance
checks.
It has an added benefit: it's not uncommon for the __init__
statement in a custom django Form to make modifications or additions to self.fields
so it's better for changes to self.fields
to happen after all of __init__
has run for the class in question.
Very clever.
However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.
Here is the simplest example that has the key lines of code:
import numpy as np
import matplotlib.pyplot as plt
H = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
plt.imshow(H, interpolation='none')
plt.show()
You only need one INSERT:
INSERT INTO table4 ( name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id
INNER JOIN table3 n ON p.Id = n.Id
If your are not in a session you can just nextval('you_sequence_name') and it's just fine.
The problem is that the keys provided in the loop do not refer to the index of the file.
for (var i in this.files) {
console.log(i);
}
The output of the above code is:
0
length
item
But what was expected was:
0
1
2
etc...
Then the error occurs when the browser tries to execute, for example:
window.URL.createObjectURL(this.files["length"])
I suggest implementation based on the following code:
var files = this.files;
for (var i = 0; i < files.length; i++) {
var file = files[i],
src = (window.URL || window.webkitURL).createObjectURL(file);
...
}
I hope this can help someone.
Greetings!
One option would be to read the data from the registry. MSDN Article On The Topic: http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.localmachine(v=vs.71).aspx)
The processors, I believe can be located here, HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor
private void determineNumberOfProcessCores()
{
RegistryKey rk = Registry.LocalMachine;
String[] subKeys = rk.OpenSubKey("HARDWARE").OpenSubKey("DESCRIPTION").OpenSubKey("System").OpenSubKey("CentralProcessor").GetSubKeyNames();
textBox1.Text = "Total number of cores:" + subKeys.Length.ToString();
}
I am reasonably sure the registry entry will be there on most systems.
Though I would throw my $0.02 in.
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
In case when you probing TCP ports with intention to listen on it, it’s better to actually call listen. The approach with tring to connect don’t 'see' client ports of established connections, because nobody listen on its. But these ports cannot be used to listen on its.
import socket
def check_port(port, rais=True):
""" True -- it's possible to listen on this port for TCP/IPv4 or TCP/IPv6
connections. False -- otherwise.
"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', port))
sock.listen(5)
sock.close()
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sock.bind(('::1', port))
sock.listen(5)
sock.close()
except socket.error as e:
return False
if rais:
raise RuntimeError(
"The server is already running on port {0}".format(port))
return True
As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.
Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :
> x <- factor(sample(4:8,10,replace=T))
> x
[1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
[1] 6 4 8 6 7 6 8 5 8 4
To show it works.
The timings :
> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
user system elapsed
0.11 0.00 0.11
> system.time(as.numeric(levels(x))[x])
user system elapsed
0 0 0
It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.
It's just about the remainders. Let me show you how
10 % 5=0
9 % 5=4 (because the remainder of 9 when divided by 5 is 4)
8 % 5=3
7 % 5=2
6 % 5=1
5 % 5=0 (because it is fully divisible by 5)
Now we should remember one thing, mod means remainder so
4 % 5=4
but why 4? because 5 X 0 = 0 so 0 is the nearest multiple which is less than 4 hence 4-0=4
I find my solution adequate for the retrieval of the location.
var executingAssembly = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName;
A Grid is a hardware and software infrastructure that clusters and integrates high-end computers, networks, databases, and scientific instruments from multiple sources to form a virtual supercomputer on which users can work collaboratively within virtual organisations
Grid is Mostly free used by academic research etc.
Clouds are a large pool of easily usable and accessible virtualized resources (such as hardware, development platforms and/or services). These resources can be dynamically reconfigured to adjust to a variable load (scale), allowing also for an optimum resource utilization. This pool of resources is typically exploited by a pay peruse model in which guarantees are offered by the Infrastructure Provider by customized service level agreements.
Cloud is not free. It is a service, provided by different service providers and they charge according to your work done.
Yes there is using the following code will allow you to apply a blurring effect to the specified image and also it will allow you to choose the amount of blurring.
img {
-webkit-filter: blur(10px);
filter: blur(10px);
}
dotPeek is a great (free) tool to show this information.
If you are having a few issues getting hold of Reflector then this is a good alternative.
Snippets of code from other answers work, but it is not always obvious where to place them in the code, especially if you are using an AlertDialog.Builder
and followed the official dialog tutorial because it doesn't use final AlertDialog ...
or alertDialog.show()
.
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Is preferable to
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
Because SOFT_INPUT_STATE_ALWAYS_VISIBLE will hide the keyboard if the focus switches away from the EditText, where SHOW_FORCED will keep the keyboard displayed until it is explicitly dismissed, even if the user returns to the homescreen or displays the recent apps.
Below is working code for an AlertDialog created using a custom layout with an EditText defined in XML. It also sets the keyboard to have a "go" key and allows it to trigger the positive button.
alert_dialog.xml:
<RelativeLayout
android:id="@+id/dialogRelativeLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<!-- android:imeOptions="actionGo" sets the keyboard to have a "go" key instead of a "new line" key. -->
<!-- android:inputType="textUri" disables spell check in the EditText and changes the "go" key from a check mark to an arrow. -->
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:imeOptions="actionGo"
android:inputType="textUri"/>
</RelativeLayout>
AlertDialog.java:
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
public class CreateDialog extends AppCompatDialogFragment {
// The public interface is used to send information back to the activity that called CreateDialog.
public interface CreateDialogListener {
void onCreateDialogCancel(DialogFragment dialog);
void onCreateDialogOK(DialogFragment dialog);
}
CreateDialogListener mListener;
// Check to make sure that the activity that called CreateDialog implements both listeners.
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (CreateDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement CreateDialogListener.");
}
}
// onCreateDialog requires @NonNull.
@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
LayoutInflater customDialogInflater = getActivity().getLayoutInflater();
// Setup dialogBuilder.
alertDialogBuilder.setTitle(R.string.title);
alertDialogBuilder.setView(customDialogInflater.inflate(R.layout.alert_dialog, null));
alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mListener.onCreateDialogCancel(CreateDialog.this);
}
});
alertDialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mListener.onCreateDialogOK(CreateDialog.this);
}
});
// Assign the resulting built dialog to an AlertDialog.
final AlertDialog alertDialog = alertDialogBuilder.create();
// Show the keyboard when the dialog is displayed on the screen.
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// We need to show alertDialog before we can setOnKeyListener below.
alertDialog.show();
EditText editText = (EditText) alertDialog.findViewById(R.id.editText);
// Allow the "enter" key on the keyboard to execute "OK".
editText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button, select the PositiveButton "OK".
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
// Trigger the create listener.
mListener.onCreateDialogOK(CreateDialog.this);
// Manually dismiss alertDialog.
alertDialog.dismiss();
// Consume the event.
return true;
} else {
// If any other key was pressed, do not consume the event.
return false;
}
}
});
// onCreateDialog requires the return of an AlertDialog.
return alertDialog;
}
}
There are a few misunderstandings in the discussion above.
First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.
As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION @transaction
Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)
This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.
As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.
you can disable or set date and time for log setting.
System > Configuration > Advanced > System > Log Cleaning
Use runlike from git repository https://github.com/lavie/runlike
To install runlike
pip install runlike
As it accept container id as an argument so to extract container id use following command
docker ps -a -q
You are good to use runlike to extract complete docker run command with following command
runlike <docker container ID>
If you want to keep the row with the lowest id
value:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MIN(n.id)
FROM NAMES n
GROUP BY n.name) x)
If you want the id
value that is the highest:
DELETE FROM NAMES
WHERE id NOT IN (SELECT *
FROM (SELECT MAX(n.id)
FROM NAMES n
GROUP BY n.name) x)
The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.
Merge this:
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
With this answer:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
An IntPtr is an integer which is the same size as a pointer.
You can use IntPtr to store a pointer value in a non-pointer type. This feature is important in .NET since using pointers is highly error prone and therefore illegal in most contexts. By allowing the pointer value to be stored in a "safe" data type, plumbing between unsafe code segments may be implemented in safer high-level code -- or even in a .NET language that doesn't directly support pointers.
The size of IntPtr is platform-specific, but this detail rarely needs to be considered, since the system will automatically use the correct size.
The name "IntPtr" is confusing -- something like Handle
might have been more appropriate. My initial guess was that "IntPtr" was a pointer to an integer. The MSDN documentation of IntPtr goes into somewhat cryptic detail without ever providing much insight about the meaning of the name.
An IntPtr
is a pointer with two limitations:
In other words, an IntPtr
is just like a void*
-- but with the extra feature that it can (but shouldn't) be used for basic pointer arithmetic.
In order to dereference an IntPtr
, you can either cast it to a true pointer (an operation which can only be performed in "unsafe" contexts) or you can pass it to a helper routine such as those provided by the InteropServices.Marshal
class. Using the Marshal
class gives the illusion of safety since it doesn't require you to be in an explicit "unsafe" context. However, it doesn't remove the risk of crashing which is inherent in using pointers.
i had a similar situation and i used the below code for getting this worked..
Aspose.Cells.LoadOptions loadOptions = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.CSV);
Workbook workbook = new Workbook(fstream, loadOptions);
Worksheet worksheet = workbook.Worksheets[0];
dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDisplayRange.RowCount, worksheet.Cells.MaxDisplayRange.ColumnCount, true);
DataTable dtCloned = dt.Clone();
ArrayList myAL = new ArrayList();
foreach (DataColumn column in dtCloned.Columns)
{
if (column.DataType == Type.GetType("System.DateTime"))
{
column.DataType = typeof(String);
myAL.Add(column.ColumnName);
}
}
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
foreach (string colName in myAL)
{
dtCloned.Columns[colName].Convert(val => DateTime.Parse(Convert.ToString(val)).ToString("MMMM dd, yyyy"));
}
/*******************************/
public static class MyExtension
{
public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
{
foreach (DataRow row in column.Table.Rows)
{
row[column] = conversion(row[column]);
}
}
}
Hope this helps some1 thx_joxin
as System environment Variable:
Windows:
Start -> type "envi" select environment variables and add a new:
Name: spring_profiles_active
Value: dev
(or whatever yours is)
Linux: add following line to /etc/environment under PATH:
spring_profiles_active=prod
(or whatever profile is)
then also export spring_profiles_active=prod
so you have it in the runtime now.
There is a W3C specification defining possible date strings that should be parseable by any browser (including Firefox and Safari):
Year:
YYYY (e.g., 1997)
Year and month:
YYYY-MM (e.g., 1997-07)
Complete date:
YYYY-MM-DD (e.g., 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (e.g., 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (e.g., 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (e.g., 1997-07-16T19:20:30.45+01:00)
where
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
According to YYYY-MM-DDThh:mmTZD
, the example 2010-07-15 11:54:21
has to be converted to either 2010-07-15T11:54:21Z
or 2010-07-15T11:54:21+02:00
(or with any other timezone).
Here is a short example showing the results of each variant:
const oldDateString = '2010-07-15 11:54:21'
const newDateStringWithoutTZD = '2010-07-15T11:54:21Z'
const newDateStringWithTZD = '2010-07-15T11:54:21+02:00'
document.getElementById('oldDateString').innerHTML = (new Date(oldDateString)).toString()
document.getElementById('newDateStringWithoutTZD').innerHTML = (new Date(newDateStringWithoutTZD)).toString()
document.getElementById('newDateStringWithTZD').innerHTML = (new Date(newDateStringWithTZD)).toString()
_x000D_
div {
padding: 10px;
}
_x000D_
<div>
<strong>Old Date String</strong>
<br>
<span id="oldDateString"></span>
</div>
<div>
<strong>New Date String (without Timezone)</strong>
<br>
<span id="newDateStringWithoutTZD"></span>
</div>
<div>
<strong>New Date String (with Timezone)</strong>
<br>
<span id="newDateStringWithTZD"></span>
</div>
_x000D_
There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type
(or :nth-child
-- either would work in this case.)
Smallest viewport:
@media (max-width:$smallest-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(2n) {
background: #fff;
}
}
Medium viewport:
@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
background: #fff;
}
}
Largest viewport:
@media (min-width:$mid-breakpoint) and (max-width:9999px) {
.row div {
background: #eee;
}
.row div:nth-of-type(6n+4),
.row div:nth-of-type(6n+5),
.row div:nth-of-type(6n+6) {
background: #fff;
}
}
Working fiddle here
This article is clearly explained, how to install MySqli with EachApache. This works for me too.
To install mysqli using EachApache:
Login to WHM as 'root' user.
Either search for "EasyApache" or go to Software > EasyApache
Scroll down and select a build option (Previously Saved Config)
Click Start "Start customizing based on profile"
Select the version of Apache and click "Next Step".
Select the version of PHP and click "Next Step".
Chose additional options within the "Short Options List"
Select "Exhaustive Options List" and look for "MySQL Improved extension"
Click "Save and Build"
Given a sample dataframe df
as:
a,b
1,2
2,3
3,4
4,5
what you want is:
df['a'] = df['a'].apply(lambda x: x + 1)
that returns:
a b
0 2 2
1 3 3
2 4 4
3 5 5
Try with auto increment:
CREATE TABLE IF NOT EXISTS `my_table` (
`number` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`money` int(11) NOT NULL,
PRIMARY KEY (`number`,`name`)
) ENGINE=MyISAM;
I find this way more readable:
$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";
Not that I have anything against arrays...
Hiya demo http://jsfiddle.net/LYTbc/
this is a reference to the DOM element, so you can wrap it directly.
attr
api: http://api.jquery.com/attr/
The .attr() method gets the attribute value for only the first element in the matched set.
have a nice one, cheers!
code
$(document).ready(function () {
$(".inputs").click(function () {
alert(this.id);
alert(" or " + $(this).attr("id"));
});
});?
This will work for a multiple row df having the dataframe as df with the same name of the columns in the df as the db.
tuples = list(df.itertuples(index=False, name=None))
columns_list = df.columns.tolist()
marks = ['?' for _ in columns_list]
columns_list = f'({(",".join(columns_list))})'
marks = f'({(",".join(marks))})'
table_name = 'whateveryouwant'
c.executemany(f'INSERT OR REPLACE INTO {table_name}{columns_list} VALUES {marks}', tuples)
conn.commit()
You can use an svg. Make the container/wrapper position relative, put the svg first as staticly positioned and then put absolutely positioned content (top: 0; left:0; right:0; bottom:0;)
Example with 16:9 proportions:
image.svg: (can be inlined in src)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 9" width="16" height="9"/>
CSS:
.container {
position: relative;
}
.content {
position: absolute;
top:0; left:0; right:0; bottom:0;
}
HTML:
<div class="container">
<img style="width: 100%" src="image.svg" />
<div class="content"></div>
</div>
Note that inline svg doesn't seem to work, but you can urlencode the svg and embed it in img src attribute like this:
<img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2016%209%22%20width%3D%2216%22%20height%3D%229%22%2F%3E" style="width: 100%;" />
Try to use the new '@supports' feature, here is one good hack that you might like:
* UPDATE!!! * Microsoft Edge and Safari 9 both added support for the @supports feature in Fall 2015, Firefox also -- so here is my updated version for you:
/* Chrome 29+ (Only) */
@supports (-webkit-appearance:none) and (not (overflow:-webkit-marquee))
and (not (-ms-ime-align:auto)) and (not (-moz-appearance:none)) {
.selector { color:red; }
}
More info on this here (the reverse... Safari but not Chrome): [ is there a css hack for safari only NOT chrome? ]
The previous CSS Hack [before Edge and Safari 9 or newer Firefox versions]:
/* Chrome 28+ (now also Microsoft Edge, Firefox, and Safari 9+) */
@supports (-webkit-appearance:none) { .selector { color:red; } }
This worked for (only) chrome, version 28 and newer.
(The above chrome 28+ hack was not one of my creations. I found this on the web and since it was so good I sent it to BrowserHacks.com recently, there are others coming.)
August 17th, 2014 update: As I mentioned, I have been working on reaching more versions of chrome (and many other browsers), and here is one I crafted that handles chrome 35 and newer.
/* Chrome 35+ */
_::content, _:future, .selector:not(*:root) { color:red; }
In the comments below it was mentioned by @BoltClock about future, past, not... etc... We can in fact use them to go a little farther back in Chrome history.
So then this is one that also works but not 'Chrome-only' which is why I did not put it here. You still have to separate it by a Safari-only hack to complete the process. I have created css hacks to do this however, not to worry. Here are a few of them, starting with the simplest:
/* Chrome 26+, Safari 6.1+ */
_:past, .selector:not(*:root) { color:red; }
Or instead, this one which goes back to Chrome 22 and newer, but Safari as well...
/* Chrome 22+, Safari 6.1+ */
@media screen and (-webkit-min-device-pixel-ratio:0)
and (min-resolution:.001dpcm),
screen and(-webkit-min-device-pixel-ratio:0)
{
.selector { color:red; }
}
The block of Chrome versions 22-28 (more complicated but works nicely) are also possible to target via a combination I worked out:
/* Chrome 22-28 (Only!) */
@media screen and(-webkit-min-device-pixel-ratio:0)
{
.selector {-chrome-:only(;
color:red;
);}
}
Now follow up with this next couple I also created that targets Safari 6.1+ (only) in order to still separate Chrome and Safari. Updated to include Safari 8
/* Safari 6.1-7.0 */
@media screen and (-webkit-min-device-pixel-ratio:0) and (min-color-index:0)
{
.selector {(; color:blue; );}
}
/* Safari 7.1+ */
_::-webkit-full-page-media, _:future, :root .selector { color:blue; }
So if you put one of the Chrome+Safari hacks above, and then the Safari 6.1-7 and 8 hacks in your styles sequentially, you will have Chrome items in red, and Safari items in blue.
If you still want to group only by one column (as I wanted) you can nest the query:
select c1, count(*) from (select distinct c1, c2 from t) group by c1
Thanks for the info, think I see the problem. This is a bug in hive-go
that only shows up when you add a host. The last lines of it are:
app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);
When you add the host on the first line, it is crashing when it calls app.address().port
.
The problem is the potentially asynchronous nature of .listen()
. Really it should be doing that console.log
call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.
Try this:
app.listen(3001, 'localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
if you are on windows then you can do a right click from the folder where you want to use git bash and select "GIT BASH HERE".
Yes using Option Explicit
is a good habit. Using .Select
however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet
which might not be what you actually wanted.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
Else
Exit For
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
NOTE
If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10
If you want to copy all rows which have data then use this code.
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
Hope this is what you wanted?
Sid
The traditional approach is full of boilerplate code and clumsy resource handling. That's why I made the Spyglass framework. To demonstrate how it works, here's an example showing how to make a custom view that displays a String title.
Step 1: Create a custom view class.
public class CustomView extends FrameLayout {
private TextView titleView;
public CustomView(Context context) {
super(context);
init(null, 0, 0);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr, 0);
}
@RequiresApi(21)
public CustomView(
Context context,
AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs, defStyleAttr, defStyleRes);
}
public void setTitle(String title) {
titleView.setText(title);
}
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
}
}
Step 2: Define a string attribute in the values/attrs.xml
resource file:
<resources>
<declare-styleable name="CustomView">
<attr name="title" format="string"/>
</declare-styleable>
</resources>
Step 3: Apply the @StringHandler
annotation to the setTitle
method to tell the Spyglass framework to route the attribute value to this method when the view is inflated.
@HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
titleView.setText(title);
}
Now that your class has a Spyglass annotation, the Spyglass framework will detect it at compile-time and automatically generate the CustomView_SpyglassCompanion
class.
Step 4: Use the generated class in the custom view's init
method:
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
CustomView_SpyglassCompanion
.builder()
.withTarget(this)
.withContext(getContext())
.withAttributeSet(attrs)
.withDefaultStyleAttribute(defStyleAttr)
.withDefaultStyleResource(defStyleRes)
.build()
.callTargetMethodsNow();
}
That's it. Now when you instantiate the class from XML, the Spyglass companion interprets the attributes and makes the required method call. For example, if we inflate the following layout then setTitle
will be called with "Hello, World!"
as the argument.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:width="match_parent"
android:height="match_parent">
<com.example.CustomView
android:width="match_parent"
android:height="match_parent"
app:title="Hello, World!"/>
</FrameLayout>
The framework isn't limited to string resources has lots of different annotations for handling other resource types. It also has annotations for defining default values and for passing in placeholder values if your methods have multiple parameters.
Have a look at the Github repo for more information and examples.
You have to dot source
them:
. .\build_funtions.ps1
. .\build_builddefs.ps1
Note the extra .
This heyscriptingguy
article should be of help - How to Reuse Windows PowerShell Functions in Scripts
In my case, after I delete all certification created by Xcode and downloaded. Let xcode 8.1 manage certification of app, It works well!!! Hope this can help someone.
The following article perhaps goes into some more detail as to which is a better choice; throw 'An error'
or throw new Error('An error')
:
http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/
It suggests that the latter (new Error()
) is more reliable, since browsers like Internet Explorer and Safari (unsure of versions) don't correctly report the message when using the former.
Doing so will cause an error to be thrown, but not all browsers respond the way you’d expect. Firefox, Opera, and Chrome each display an “uncaught exception” message and then include the message string. Safari and Internet Explorer simply throw an “uncaught exception” error and don’t provide the message string at all. Clearly, this is suboptimal from a debugging point of view.
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
See Time Complexity. The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely unlikely. The average time complexity is of course O(1).
The best method would be to check and take a look at the hashs of the objects you are using. The CPython Dict uses int PyObject_Hash (PyObject *o) which is the equivalent of hash(o)
.
After a quick check, I have not yet managed to find two tuples that hash to the same value, which would indicate that the lookup is O(1)
l = []
for x in range(0, 50):
for y in range(0, 50):
if hash((x,y)) in l:
print "Fail: ", (x,y)
l.append(hash((x,y)))
print "Test Finished"
CodePad (Available for 24 hours)
Here's another option for those not using heatmap.2
(aheatmap
is good!)
Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:
breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)
function array2xml($array, $xml = false){
if($xml === false){
$xml = new SimpleXMLElement('<?xml version=\'1.0\' encoding=\'utf-8\'?><'.key($array).'/>');
$array = $array[key($array)];
}
foreach($array as $key => $value){
if(is_array($value)){
$this->array2xml($value, $xml->addChild($key));
}else{
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}
Is the file really a symbolic link? If not, the usual test for existence is -r
or -e
.
See man test
.
I had a weird issue when an incorrect entry in MANIFEST.MF was causing loading failure. This was when I was trying to launch a very simply scala program:
Incorrect:
Main-Class: jarek.ResourceCache
Class-Path: D:/lang/scala/lib/scala-library.jar
Correct:
Main-Class: jarek.ResourceCache
Class-Path: file:///D:/lang/scala/lib/scala-library.jar
With an incorrect version, I was getting a cryptic message, the same the OP did. Probably it should say something like malformed url exception while parsing manifest file.
Using an absolute path in the manifest file is what IntelliJ uses to provide a long classpath for a program.
CSS Flexbox is well supported these days. Go here for a good tutorial on flexbox.
This works fine in all newer browsers:
#container {_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.block {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
background-color: #cccccc;_x000D_
margin: 10px; _x000D_
}
_x000D_
<div id="container">_x000D_
<div class="block">1</div> _x000D_
<div class="block">2</div> _x000D_
<div class="block">3</div> _x000D_
<div class="block">4</div> _x000D_
<div class="block">5</div> _x000D_
</div>
_x000D_
Some may ask why not use display: inline-block? For simple things it is fine, but if you got complex code within the blocks, the layout may not be correctly centered anymore. Flexbox is more stable than float left.
The fields of your object have in turn their fields, some of which do not implement Serializable
. In your case the offending class is TransformGroup
. How to solve it?
Serializable
transient
To resolve this error:
ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name
Just run this PL/SQL
command for extended tablespace size automatically on-demand:
alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;
I get this error in import big dump file, just run this command without stopping import routine or restarting the database.
Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.
More info: alter_autoextend_on
If you are using React, then with latest version of react hooks, you could use this.
// Usage
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
I try to use a union to combine two queries to format the returns you want:
SELECT recordid, startdate, enddate FROM tmp
Where enddate is null
UNION
SELECT recordid, MIN(startdate), MAX(enddate) FROM tmp GROUP BY recordid
But I have no idea if the Union would have great impact on the performance
In new update android studio 2.2 facing rendering issue then follow this steps.
I fixed it - in styles.xml file I changed
"Theme.AppCompat.Light.DarkActionBar"
to
"Base.Theme.AppCompat.Light.DarkActionBar"
It's some kind of hack I came across a long time ago to solve similar rendering problems in previous Android Studio versions.
that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on
this line at your code
{<td><span onClick={this.toggle()}>Details</span></td>}
you need to make onClick
refer to this.toggle
not calling it
to fix the issue do this
{<td><span onClick={this.toggle}>Details</span></td>}
At least 8 = {8,}
:
str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
If you would like to preserve the image as inline you can put vertical-align: top
or vertical-align: bottom
on it. By default it is aligned on the baseline hence the few pixels beneath it.
My solution for a Date/Time parameter:
=CDate(Today())
The trick is to convert back to a DateTime as recommend Perhentian.
This is a variation to the answer provided by @Metrics and edited by @Max Ghenis...
l <- sapply(iris, function(x) is.factor(x))
m <- iris[,l]
n <- sapply( m, function(x) { y <- summary(x)/length(x)
len <- length(y[y<0.005 | y>0.995])
cbind(len,t(y))} )
drop_cols_df <- data.frame(var = names(l[l]),
status = ifelse(as.vector(t(n[1,]))==0,"NODROP","DROP" ),
level1 = as.vector(t(n[2,])),
level2 = as.vector(t(n[3,])))
Here, after identifying factor variables, the second sapply
computes what percent of records belong to each level / category of the variable. Then it identifies number of levels over 99.5% or below 0.5% incidence rate (my arbitrary thresholds).
It then goes on to return the number of valid levels and the incidence rate of each level in each categorical variable.
Variables with zero levels crossing the thresholds should not be dropped, while the other should be dropped from the linear model.
The last data frame makes viewing the results easy. It's hard coded for this data set since all factor variables are binomial. This data frame can be made generic easily enough.
String.prototype.replaceSome = function() {
var replaceWith = Array.prototype.pop.apply(arguments),
i = 0,
r = this,
l = arguments.length;
for (;i<l;i++) {
r = r.replace(arguments[i],replaceWith);
}
return r;
}
/* replaceSome method for strings it takes as ,much arguments as we want and replaces all of them with the last argument we specified 2013 CopyRights saved for: Max Ahmed this is an example:
var string = "[hello i want to 'replace x' with eat]";
var replaced = string.replaceSome("]","[","'replace x' with","");
document.write(string + "<br>" + replaced); // returns hello i want to eat (without brackets)
*/
jsFiddle: http://jsfiddle.net/CPj89/
I was getting this from webpack lazy loading like this
import Loader from 'some-loader-component';
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
fallback: Loader, // warning
});
render() {
return <WishlistPageComponent />;
}
// changed to this then it's suddenly fine
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
fallback: '', // all good
});
As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.
public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
{
return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
}
Button won't submit form on its own.It is a simple button which is used to perform some operation by using javascript whereas Submit is a kind of button which by default submit the form whenever user clicks on submit button.
<label for="myInputID">myLabel</label><input type="checkbox" id="myInputID" name="myInputID />
So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.
The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.
This helped me change my code, and I now have it working. - Thanks for your comments.
My implementation ended up looking like this;
I require my routes in the app.js:
var express = require('express')
, site = require('./site')
, wiki = require('./wiki');
And I add my routes like this:
app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);
I have two files called wiki.js and site.js in the root of my app, containing this:
exports.edit = function(req, res) {
var wiki_entry = req.params.id;
res.render('wiki/edit', {
title: 'Editing Wiki',
wiki: wiki_entry
})
}
Try using the type
attribute selector to find buttons (maybe this'll fix it too):
input[type=button]
{
background-color: #E3E1B8;
}
input[type=button]:hover
{
background-color: #46000D
}
Laravel supports aliases on tables and columns with AS
. Try
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();
Let's see it in action with an awesome tinker
tool
$ php artisan tinker [1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');}); // NULL [2] > DB::table('really_long_table_name')->insert(['id' => null]); // true [3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get(); // array( // 0 => object(stdClass)( // 'uid' => '1' // ) // )
You need to give relative
or absolute
or fixed
positioning to your container (#shop
) and set its zIndex
to say 100.
You also need to give say relative
positioning to your elements with the class content
and lower zIndex
say 97.
Do the above-mentioned with your images too and set their zIndex
to 91.
And then position your button higher by setting its position to absolute
and zIndex
to 95
See the DEMO
HTML
<div id="shop">
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
</div>
CSS
#shop{
background-image: url("images/shop_bg.png");
background-repeat: repeat-x;
height:121px;
width: 984px;
margin-left: 20px;
margin-top: 13px;
position:relative;
z-index:100
}
#shop .content{
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
z-index:97
}
img{
position:relative;
z-index:91
}
.span{
width:70px;
height:40px;
border:1px solid red;
position:absolute;
z-index:95;
right:60px;
bottom:-20px;
}
You may be forgetting something. Before #include <iostream>
, write #include <stdafx.h>
and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."