relative path in BAT script
You can get all the required file properties by using the code below:
FOR %%? IN (file_to_be_queried) DO (
ECHO File Name Only : %%~n?
ECHO File Extension : %%~x?
ECHO Name in 8.3 notation : %%~sn?
ECHO File Attributes : %%~a?
ECHO Located on Drive : %%~d?
ECHO File Size : %%~z?
ECHO Last-Modified Date : %%~t?
ECHO Parent Folder : %%~dp?
ECHO Fully Qualified Path : %%~f?
ECHO FQP in 8.3 notation : %%~sf?
ECHO Location in the PATH : %%~dp$PATH:?
)
Visual Studio breakpoints not being hit
In my case I had a string of length 70kb. Compiler did not thrown any error. But Debugger failed to hit the break point. After spending 3 hours and scratching my hair I found the cause for not hitting the break point. After removing 70kb data break point worked as normal.
How to set a timer in android
I believe the way to do this on the android is that you need a background service to be running. In that background application, create the timer. When the timer "ticks" (set the interval for how long you want to wait), launch your activity which you want to start.
http://developer.android.com/guide/topics/fundamentals.html (<-- this article explains the relationship between activities, services, intents and other core fundamentals of Android development)
Count a list of cells with the same background color
The worksheet formula, =CELL("color",D3)
returns 1
if the cell is formatted with color for negative values (else returns 0
).
You can solve this with a bit of VBA. Insert this into a VBA code module:
Function CellColor(xlRange As Excel.Range)
CellColor = xlRange.Cells(1, 1).Interior.ColorIndex
End Function
Then use the function =CellColor(D3)
to display the .ColorIndex
of D3
jQuery Mobile: document ready vs. page events
While you use .on(), it's basically a live query that you are using.
On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.
The use of live queries is common in forms where we enter data (account or posts or even comments).
Change the class from factor to numeric of many columns in a data frame
You have to be careful while changing factors to numeric. Here is a line of code that would change a set of columns from factor to numeric. I am assuming here that the columns to be changed to numeric are 1, 3, 4 and 5 respectively. You could change it accordingly
cols = c(1, 3, 4, 5);
df[,cols] = apply(df[,cols], 2, function(x) as.numeric(as.character(x)));
Defined Edges With CSS3 Filter Blur
Insert the image inside a with position: relative;
and overflow: hidden;
HTML
<div><img src="#"></div>
CSS
div {
position: relative;
overflow: hidden;
}
img {
filter: blur(5px);
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
}
This also works on variable sizes elements, like dynamic div's.
What's the difference between console.dir and console.log?
Following Felix Klings advice I tried it out in my chrome browser.
console.dir([1,2])
gives the following output:
Array[2]
0: 1
1: 2
length: 2
__proto__: Array[0]
While console.log([1,2])
gives the following output:
[1, 2]
So I believe console.dir()
should be used to get more information like prototype etc in arrays and objects.
How to reverse MD5 to get the original string?
Its not possible thats the whole point of hashing. You can however bruteforce by going through all possibilities (using all possible digits characters in every possible order) and hashing them and checking for a collision.
for more information on hashing and MD5 etc see: http://en.wikipedia.org/wiki/MD5 , http://en.wikipedia.org/wiki/Hash_function , http://en.wikipedia.org/wiki/Cryptographic_hash_function and http://onin.com/hhh/hhhexpl.html
I myself created my own app to do this, its open source you can check the link: http://sourceforge.net/projects/jpassrecovery/ and of course the source. Here is the source for easy access it has a basic implementation in the comments:
Bruter.java:
import java.util.ArrayList;
public class Bruter {
public ArrayList<String> characters = new ArrayList<>();
public boolean found = false;
public int maxLength;
public int minLength;
public int count;
long starttime, endtime;
public int minutes, seconds, hours, days;
public char[] specialCharacters = {'~', '`', '!', '@', '#', '$', '%', '^',
'&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '[', ']', '|', '\\',
';', ':', '\'', '"', '<', '.', ',', '>', '/', '?', ' '};
public boolean done = false;
public boolean paused = false;
public boolean isFound() {
return found;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
public boolean isPaused() {
return paused;
}
public void setFound(boolean found) {
this.found = found;
}
public synchronized void setEndtime(long endtime) {
this.endtime = endtime;
}
public int getCounter() {
return count;
}
public long getRemainder() {
return getNumberOfPossibilities() - count;
}
public long getNumberOfPossibilities() {
long possibilities = 0;
for (int i = minLength; i <= maxLength; i++) {
possibilities += (long) Math.pow(characters.size(), i);
}
return possibilities;
}
public void addExtendedSet() {
for (char c = (char) 0; c <= (char) 31; c++) {
characters.add(String.valueOf(c));
}
}
public void addStandardCharacterSet() {
for (char c = (char) 32; c <= (char) 127; c++) {
characters.add(String.valueOf(c));
}
}
public void addLowerCaseLetters() {
for (char c = 'a'; c <= 'z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addDigits() {
for (int c = 0; c <= 9; c++) {
characters.add(String.valueOf(c));
}
}
public void addUpperCaseLetters() {
for (char c = 'A'; c <= 'Z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addSpecialCharacters() {
for (char c : specialCharacters) {
characters.add(String.valueOf(c));
}
}
public void setMaxLength(int i) {
maxLength = i;
}
public void setMinLength(int i) {
minLength = i;
}
public int getPerSecond() {
int i;
try {
i = (int) (getCounter() / calculateTimeDifference());
} catch (Exception ex) {
return 0;
}
return i;
}
public String calculateTimeElapsed() {
long timeTaken = calculateTimeDifference();
seconds = (int) timeTaken;
if (seconds > 60) {
minutes = (int) (seconds / 60);
if (minutes * 60 > seconds) {
minutes = minutes - 1;
}
if (minutes > 60) {
hours = (int) minutes / 60;
if (hours * 60 > minutes) {
hours = hours - 1;
}
}
if (hours > 24) {
days = (int) hours / 24;
if (days * 24 > hours) {
days = days - 1;
}
}
seconds -= (minutes * 60);
minutes -= (hours * 60);
hours -= (days * 24);
days -= (hours * 24);
}
return "Time elapsed: " + days + "days " + hours + "h " + minutes + "min " + seconds + "s";
}
private long calculateTimeDifference() {
long timeTaken = (long) ((endtime - starttime) * (1 * Math.pow(10, -9)));
return timeTaken;
}
public boolean excludeChars(String s) {
char[] arrayChars = s.toCharArray();
for (int i = 0; i < arrayChars.length; i++) {
characters.remove(arrayChars[i] + "");
}
if (characters.size() < maxLength) {
return false;
} else {
return true;
}
}
public int getMaxLength() {
return maxLength;
}
public int getMinLength() {
return minLength;
}
public void setIsDone(Boolean b) {
done = b;
}
public boolean isDone() {
return done;
}
}
HashBruter.java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.swing.JOptionPane;
public class HashBruter extends Bruter {
/*
* public static void main(String[] args) {
*
* final HashBruter hb = new HashBruter();
*
* hb.setMaxLength(5); hb.setMinLength(1);
*
* hb.addSpecialCharacters(); hb.addUpperCaseLetters();
* hb.addLowerCaseLetters(); hb.addDigits();
*
* hb.setType("sha-512");
*
* hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
*
* Thread thread = new Thread(new Runnable() {
*
* @Override public void run() { hb.tryBruteForce(); } });
*
* thread.start();
*
* while (!hb.isFound()) { System.out.println("Hash: " +
* hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
* hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
* hb.getCounter()); System.out.println("Estimated hashes left: " +
* hb.getRemainder()); }
*
* System.out.println("Found " + hb.getType() + " hash collision: " +
* hb.getGeneratedHash() + " password is: " + hb.getPassword());
*
* }
*/
public String hash, generatedHash, password;
public String type;
public String getType() {
return type;
}
public String getPassword() {
return password;
}
public void setHash(String p) {
hash = p;
}
public void setType(String digestType) {
type = digestType;
}
public String getGeneratedHash() {
return generatedHash;
}
public void tryBruteForce() {
starttime = System.nanoTime();
for (int size = minLength; size <= maxLength; size++) {
if (found == true || done == true) {
break;
} else {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
generateAllPossibleCombinations("", size);
}
}
done = true;
}
private void generateAllPossibleCombinations(String baseString, int length) {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
if (found == false || done == false) {
if (baseString.length() == length) {
if(type.equalsIgnoreCase("crc32")) {
generatedHash = generateCRC32(baseString);
} else if(type.equalsIgnoreCase("adler32")) {
generatedHash = generateAdler32(baseString);
} else if(type.equalsIgnoreCase("crc16")) {
generatedHash=generateCRC16(baseString);
} else if(type.equalsIgnoreCase("crc64")) {
generatedHash=generateCRC64(baseString.getBytes());
}
else {
generatedHash = generateHash(baseString.toCharArray());
}
password = baseString;
if (hash.equals(generatedHash)) {
password = baseString;
found = true;
done = true;
}
count++;
} else if (baseString.length() < length) {
for (int n = 0; n < characters.size(); n++) {
generateAllPossibleCombinations(baseString + characters.get(n), length);
}
}
}
}
private String generateHash(char[] passwordChar) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(type);
} catch (NoSuchAlgorithmException e1) {
JOptionPane.showMessageDialog(null, "No such algorithm for hashes exists", "Error", JOptionPane.ERROR_MESSAGE);
}
String passwordString = new String(passwordChar);
byte[] passwordByte = passwordString.getBytes();
md.update(passwordByte, 0, passwordByte.length);
byte[] encodedPassword = md.digest();
String encodedPasswordInString = toHexString(encodedPassword);
return encodedPasswordInString;
}
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
}
return buf.toString();
}
private String generateCRC32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new CRC32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
private String generateAdler32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new Adler32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
/*************************************************************************
* Compilation: javac CRC16.java
* Execution: java CRC16 s
*
* Reads in a string s as a command-line argument, and prints out
* its 16-bit Cyclic Redundancy Check (CRC16). Uses a lookup table.
*
* Reference: http://www.gelato.unsw.edu.au/lxr/source/lib/crc16.c
*
* % java CRC16 123456789
* CRC16 = bb3d
*
* Uses irreducible polynomial: 1 + x^2 + x^15 + x^16
*
*
*************************************************************************/
private String generateCRC16(String baseString) {
int[] table = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040,
};
byte[] bytes = baseString.getBytes();
int crc = 0x0000;
for (byte b : bytes) {
crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
}
return Integer.toHexString(crc);
}
/*******************************************************************************
* Copyright (c) 2009, 2012 Mountainminds GmbH & Co. KG and Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marc R. Hoffmann - initial API and implementation
*
*******************************************************************************/
/**
* CRC64 checksum calculator based on the polynom specified in ISO 3309. The
* implementation is based on the following publications:
*
* <ul>
* <li>http://en.wikipedia.org/wiki/Cyclic_redundancy_check</li>
* <li>http://www.geocities.com/SiliconValley/Pines/8659/crc.htm</li>
* </ul>
*/
private static final long POLY64REV = 0xd800000000000000L;
private static final long[] LOOKUPTABLE;
static {
LOOKUPTABLE = new long[0x100];
for (int i = 0; i < 0x100; i++) {
long v = i;
for (int j = 0; j < 8; j++) {
if ((v & 1) == 1) {
v = (v >>> 1) ^ POLY64REV;
} else {
v = (v >>> 1);
}
}
LOOKUPTABLE[i] = v;
}
}
/**
* Calculates the CRC64 checksum for the given data array.
*
* @param data
* data to calculate checksum for
* @return checksum value
*/
public static String generateCRC64(final byte[] data) {
long sum = 0;
for (int i = 0; i < data.length; i++) {
final int lookupidx = ((int) sum ^ data[i]) & 0xff;
sum = (sum >>> 8) ^ LOOKUPTABLE[lookupidx];
}
return String.valueOf(sum);
}
}
you would use it like:
final HashBruter hb = new HashBruter();
hb.setMaxLength(5); hb.setMinLength(1);
hb.addSpecialCharacters(); hb.addUpperCaseLetters();
hb.addLowerCaseLetters(); hb.addDigits();
hb.setType("sha-512");
hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
Thread thread = new Thread(new Runnable() {
@Override public void run() { hb.tryBruteForce(); } });
thread.start();
while (!hb.isFound()) { System.out.println("Hash: " +
hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
hb.getCounter()); System.out.println("Estimated hashes left: " +
hb.getRemainder()); }
System.out.println("Found " + hb.getType() + " hash collision: " +
hb.getGeneratedHash() + " password is: " + hb.getPassword());
Authentication issue when debugging in VS2013 - iis express
You could also modify the project properties for your web project, choose "Web" from left tabs, then change the Servers drop down to "Local IIS". Create a new virtual directory and use IIS manager to setup your site/app pool as desired.
I prefer this method, as you would typically have a local IIS v-directory (or site) to test locally. You won't affect any other sites this way either.
Undo scaffolding in Rails
You can undo whatever you did with
rails generate xxx
By
rails destroy xxx
For example this applies generators to migration, scaffold, model...etc
Maven: Failed to read artifact descriptor
I had the same problem for a while and despite doing mvn -U clean install
the problem was not getting solved!
I finally solved the problem by deleting the whole .m2
folder and then restarted my IDE and the problem was gone!
So sometimes the problem would rise because of some incompatibilities or problems in your local maven repository.
Jquery to get the id of selected value from dropdown
If you are trying to get the id, then please update your code like
html += '<option id = "' + n.id + "' value="' + i + '">' + n.names + '</option>';
To retrieve id,
$('option:selected').attr("id")
To retrieve Value
$('option:selected').val()
in Javascript
var e = document.getElementById("jobSel");
var job = e.options[e.selectedIndex].value;
Class has no initializers Swift
In my case I have declared a Bool
like this:
var isActivityOpen: Bool
i.e. I declared it without unwrapping so, This is how I solved the (no initializer) error :
var isActivityOpen: Bool!
Play/pause HTML 5 video using JQuery
I also made it work like this:
$(window).scroll(function() {
if($(window).scrollTop() > 0)
document.querySelector('#video').pause();
else
document.querySelector('#video').play();
});
Sending XML data using HTTP POST with PHP
you can use cURL library for posting data:
http://www.php.net/curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);
where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects
How to center a <p> element inside a <div> container?
Centered and middled content ?
Do it this way :
<table style="width:100%">
<tr>
<td valign="middle" align="center">Table once ruled centering</td>
</tr>
</table>
I fiddled it here
Ha, let me guess .. you want DIVs ..
just make your first outter DIV behave like a table-cell then style it with vertical align:middle;
<div>
<p>I want this paragraph to be at the center, but I can't.</p>
</div>
div {
width:500px;
height:100px;
background-color:aqua;
text-align:center;
/* there it is */
display:table-cell;
vertical-align:middle;
}
jsfiddle.net/9Mk64/
Find objects between two dates MongoDB
db.collection.find({"createdDate":{$gte:new ISODate("2017-04-14T23:59:59Z"),$lte:new ISODate("2017-04-15T23:59:59Z")}}).count();
Replace collection
with name of collection you want to execute query
How to use `replace` of directive definition?
As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.
First result:
<span myd1="">directive template1</span>
Second result:
<div myd2=""><span>directive template2</span></div>
Can I access a form in the controller?
Definitely you can't access form in scope bec. it is not created. The DOM from html template is loaded little bit slowly like controller constructor.
the solution is to watch until DOM loaded and all the scope defined!
in controller:
$timeout(function(){
console.log('customerForm:', $scope.customerForm);
// everything else what you need
});
How to write palindrome in JavaScript
function palindrome(str) {
var len = str.length;
var mid = Math.floor(len/2);
for ( var i = 0; i < mid; i++ ) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
palindrome
will return if specified word is palindrome, based on boolean
value (true/false)
UPDATE:
I opened bounty on this question due to performance and I've done research and here are the results:
If we are dealing with very large amount of data like
var abc = "asdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfd";
for ( var i = 0; i < 10; i++ ) {
abc += abc; // making string even more larger
}
function reverse(s) { // using this method for second half of string to be embedded
return s.split("").reverse().join("");
}
abc += reverse(abc); // adding second half string to make string true palindrome
In this example palindrome is True, just to note
Posted palindrome function gives us time from 180 to 210 Milliseconds (in current example), and the function posted below
with string == string.split('').reverse().join('')
method gives us 980 to 1010 Milliseconds.
Machine Details:
System: Ubuntu 13.10
OS Type: 32 Bit
RAM: 2 Gb
CPU: 3.4 Ghz*2
Browser: Firefox 27.0.1
Change New Google Recaptcha (v2) Width
This is my work around:
1) Add a wrapper div to the recaptcha div.
<div id="recaptcha-wrapper"><div class="g-recaptcha" data-sitekey="..."></div></div>
2) Add javascript/jquery code.
$(function(){
// global variables
captchaResized = false;
captchaWidth = 304;
captchaHeight = 78;
captchaWrapper = $('#recaptcha-wrapper');
captchaElements = $('#rc-imageselect, .g-recaptcha');
resizeCaptcha();
$(window).on('resize', function() {
resizeCaptcha();
});
});
function resizeCaptcha() {
if (captchaWrapper.width() >= captchaWidth) {
if (captchaResized) {
captchaElements.css('transform', '').css('-webkit-transform', '').css('-ms-transform', '').css('-o-transform', '').css('transform-origin', '').css('-webkit-transform-origin', '').css('-ms-transform-origin', '').css('-o-transform-origin', '');
captchaWrapper.height(captchaHeight);
captchaResized = false;
}
} else {
var scale = (1 - (captchaWidth - captchaWrapper.width()) * (0.05/15));
captchaElements.css('transform', 'scale('+scale+')').css('-webkit-transform', 'scale('+scale+')').css('-ms-transform', 'scale('+scale+')').css('-o-transform', 'scale('+scale+')').css('transform-origin', '0 0').css('-webkit-transform-origin', '0 0').css('-ms-transform-origin', '0 0').css('-o-transform-origin', '0 0');
captchaWrapper.height(captchaHeight * scale);
if (captchaResized == false) captchaResized = true;
}
}
3) Optional: add some styling if needed.
#recaptcha-wrapper {
text-align:center;
margin-bottom:15px;
}
.g-recaptcha {
display:inline-block;
}
Regex pattern for checking if a string starts with a certain substring?
For the extension method fans:
public static bool RegexStartsWith(this string str, params string[] patterns)
{
return patterns.Any(pattern =>
Regex.Match(str, "^("+pattern+")").Success);
}
Usage
var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = " does this start with space or tab?".RegexStartsWith(@"\s");
td widths, not working?
Note that adjusting the width of a column in the thead will affect the whole table
<table>
<thead>
<tr width="25">
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tr>
<td>Joe</td>
<td>[email protected]</td>
</tr>
</table>
In my case, the width on the thead > tr was overriding the width on table > tr > td directly.
How can I pass data from Flask to JavaScript in a template?
Using a data attribute on an HTML element avoids having to use inline scripting, which in turn means you can use stricter CSP rules for increased security.
Specify a data attribute like so:
<div id="mydiv" data-geocode='{{ geocode|tojson }}'>...</div>
Then access it in a static JavaScript file like so:
// Raw JavaScript
var geocode = JSON.parse(document.getElementById("mydiv").dataset.geocode);
// jQuery
var geocode = JSON.parse($("#mydiv").data("geocode"));
Mongoose: Get full list of users
you can also do it by async function to get all the users
await User.find({},(err,users)=>{
if (err){
return res.status(422).send(err)
}
if (!users){
return res.status(422).send({error:"No data in the collection"})
}
res.send({Allusers:users})
})
How to style components using makeStyles and still have lifecycle methods in Material UI?
I used withStyles
instead of makeStyle
EX :
import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";
const useStyles = theme => ({
root: {
flexGrow: 1,
},
});
class App extends Component {
render() {
const { classes } = this.props;
return(
<div className={classes.root}>
Test
</div>
)
}
}
export default withStyles(useStyles)(App)
proper way to sudo over ssh
The best way is ssh -t user@server "sudo <scriptname>"
, for example ssh -t user@server "sudo reboot"
.
It will prompt for password for user first and then root(since we are running the script or command with root privilege.
I hope it helped and cleared your doubt.
Check if value is in select list with JQuery
Why not use a filter?
var thevalue = 'foo';
var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;
Loose comparisons work because exists > 0 is true, exists == 0 is false, so you can just use
if(exists){
// it is in the dropdown
}
Or combine it:
if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
// found
}
Or where each select dropdown has the select-boxes class this will give you a jquery object of the select(s) which contain the value:
var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();
FragmentActivity to Fragment
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
Listing only directories in UNIX
If I have this directory:
ls -l
lrwxrwxrwx 1 nagios nagios 11 août 2 18:46 conf_nagios -> /etc/icinga
-rw------- 1 nagios nagios 724930 août 15 21:00 dead.letter
-rw-r--r-- 1 nagios nagios 12312 août 23 00:13 icinga.log
-rw-r--r-- 1 nagios nagios 8323 août 23 00:12 icinga.log.gz
drwxr-xr-x 2 nagios nagios 4096 août 23 16:36 tmp
To get all directories, use -L to resolve links:
ls -lL | grep '^d'
drwxr-xr-x 5 nagios nagios 4096 août 15 21:22 conf_nagios
drwxr-xr-x 2 nagios nagios 4096 août 23 16:41 tmp
Without -L:
ls -l | grep '^d'
drwxr-xr-x 2 nagios nagios 4096 août 23 16:41 tmp
conf_nagios directory is missing.
Equal height rows in CSS Grid Layout
Short Answer
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
- Set the container to
grid-auto-rows: 1fr
How it works
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the fr
unit
...
When the available space is infinite (which happens when the grid
container’s width or height is indefinite), flex-sized (fr
) grid tracks are
sized to their contents while retaining their respective proportions.
The used size of each flex-sized grid track is computed by determining
the max-content
size of each flex-sized grid track and dividing that
size by the respective flex factor to determine a “hypothetical 1fr
size”.
The maximum of those is used as the resolved 1fr
length (the
flex fraction), which is then multiplied by each grid track’s flex
factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
Why flexbox isn't an option
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
6. Flex Lines
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
How do I measure a time interval in C?
Here's a header file I wrote to do some simple performance profiling (using manual timers):
#ifndef __ZENTIMER_H__
#define __ZENTIMER_H__
#ifdef ENABLE_ZENTIMER
#include <stdio.h>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#elif HAVE_INTTYPES_H
#include <inttypes.h>
#else
typedef unsigned char uint8_t;
typedef unsigned long int uint32_t;
typedef unsigned long long uint64_t;
#endif
#ifdef __cplusplus
extern "C" {
#pragma }
#endif /* __cplusplus */
#define ZTIME_USEC_PER_SEC 1000000
/* ztime_t represents usec */
typedef uint64_t ztime_t;
#ifdef WIN32
static uint64_t ztimer_freq = 0;
#endif
static void
ztime (ztime_t *ztimep)
{
#ifdef WIN32
QueryPerformanceCounter ((LARGE_INTEGER *) ztimep);
#else
struct timeval tv;
gettimeofday (&tv, NULL);
*ztimep = ((uint64_t) tv.tv_sec * ZTIME_USEC_PER_SEC) + tv.tv_usec;
#endif
}
enum {
ZTIMER_INACTIVE = 0,
ZTIMER_ACTIVE = (1 << 0),
ZTIMER_PAUSED = (1 << 1),
};
typedef struct {
ztime_t start;
ztime_t stop;
int state;
} ztimer_t;
#define ZTIMER_INITIALIZER { 0, 0, 0 }
/* default timer */
static ztimer_t __ztimer = ZTIMER_INITIALIZER;
static void
ZenTimerStart (ztimer_t *ztimer)
{
ztimer = ztimer ? ztimer : &__ztimer;
ztimer->state = ZTIMER_ACTIVE;
ztime (&ztimer->start);
}
static void
ZenTimerStop (ztimer_t *ztimer)
{
ztimer = ztimer ? ztimer : &__ztimer;
ztime (&ztimer->stop);
ztimer->state = ZTIMER_INACTIVE;
}
static void
ZenTimerPause (ztimer_t *ztimer)
{
ztimer = ztimer ? ztimer : &__ztimer;
ztime (&ztimer->stop);
ztimer->state |= ZTIMER_PAUSED;
}
static void
ZenTimerResume (ztimer_t *ztimer)
{
ztime_t now, delta;
ztimer = ztimer ? ztimer : &__ztimer;
/* unpause */
ztimer->state &= ~ZTIMER_PAUSED;
ztime (&now);
/* calculate time since paused */
delta = now - ztimer->stop;
/* adjust start time to account for time elapsed since paused */
ztimer->start += delta;
}
static double
ZenTimerElapsed (ztimer_t *ztimer, uint64_t *usec)
{
#ifdef WIN32
static uint64_t freq = 0;
ztime_t delta, stop;
if (freq == 0)
QueryPerformanceFrequency ((LARGE_INTEGER *) &freq);
#else
#define freq ZTIME_USEC_PER_SEC
ztime_t delta, stop;
#endif
ztimer = ztimer ? ztimer : &__ztimer;
if (ztimer->state != ZTIMER_ACTIVE)
stop = ztimer->stop;
else
ztime (&stop);
delta = stop - ztimer->start;
if (usec != NULL)
*usec = (uint64_t) (delta * ((double) ZTIME_USEC_PER_SEC / (double) freq));
return (double) delta / (double) freq;
}
static void
ZenTimerReport (ztimer_t *ztimer, const char *oper)
{
fprintf (stderr, "ZenTimer: %s took %.6f seconds\n", oper, ZenTimerElapsed (ztimer, NULL));
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#else /* ! ENABLE_ZENTIMER */
#define ZenTimerStart(ztimerp)
#define ZenTimerStop(ztimerp)
#define ZenTimerPause(ztimerp)
#define ZenTimerResume(ztimerp)
#define ZenTimerElapsed(ztimerp, usec)
#define ZenTimerReport(ztimerp, oper)
#endif /* ENABLE_ZENTIMER */
#endif /* __ZENTIMER_H__ */
The ztime()
function is the main logic you need — it gets the current time and stores it in a 64bit uint measured in microseconds. You can then later do simple math to find out the elapsed time.
The ZenTimer*()
functions are just helper functions to take a pointer to a simple timer struct, ztimer_t
, which records the start time and the end time. The ZenTimerPause()
/ZenTimerResume()
functions allow you to, well, pause and resume the timer in case you want to print out some debugging information that you don't want timed, for example.
You can find a copy of the original header file at http://www.gnome.org/~fejj/code/zentimer.h in the off chance that I messed up the html escaping of <'s or something. It's licensed under MIT/X11 so feel free to copy it into any project you do.
Minimum 6 characters regex expression
Something along the lines of this?
<asp:TextBox id="txtUsername" runat="server" />
<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Field not valid!"
ControlToValidate="txtUsername"
ValidationExpression="[0-9a-zA-Z]{6,}" />
Show space, tab, CRLF characters in editor of Visual Studio
Edit > Advanced > View White Space. The keyboard shortcut is CTRL+R, CTRL+W. The command is called Edit.ViewWhiteSpace
.
It works in all Visual Studio versions at least since Visual Studio 2010, the current one being Visual Studio 2019 (at time of writing). In Visual Studio 2013, you can also use CTRL+E, S or CTRL+E, CTRL+S.
By default, end of line markers are not visualized. This functionality is provided by the End of the Line extension.
How to solve java.lang.NullPointerException error?
This error occures when you try to refer to a null object instance. I can`t tell you what causes this error by your given information, but you can debug it easily in your IDE.
I strongly recommend you that use exception handling to avoid unexpected program behavior.
Clear screen in shell
Here's how to make your very own cls
or clear
command that will work without explicitly calling any function!
We'll take advantage of the fact that the python console calls repr()
to display objects on screen. This is especially useful if you have your own customized python shell (with the -i
option for example) and you have a pre-loading script for it. This is what you need:
import os
class ScreenCleaner:
def __repr__(self):
os.system('cls') # This actually clears the screen
return '' # Because that's what repr() likes
cls = ScreenCleaner()
Use clear
instead of cls
if you're on linux (in both the os
command and the variable name)!
Now if you just write cls
or clear
in the console - it will clear it! Not even cls()
or clear()
- just the raw variable. This is because python will call repr(cls)
to print it out, which will in turn trigger our __repr__
function.
Let's test it out:
>>> df;sag
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'df' is not defined
>>> sglknas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sglknas' is not defined
>>> lksnldn
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'lksnldn' is not defined
>>> cls
And the screen is clear!
To clarify - the code above needs to either be imported in the console like this
from somefile import cls
Or pre load directly with something like:
python -i my_pre_loaded_classes.py
How do I remove/delete a folder that is not empty?
I'd like to add a "pure pathlib" approach:
from pathlib import Path
from typing import Union
def del_dir(target: Union[Path, str], only_if_empty: bool = False):
"""
Delete a given directory and its subdirectories.
:param target: The directory to delete
:param only_if_empty: Raise RuntimeError if any file is found in the tree
"""
target = Path(target).expanduser()
assert target.is_dir()
for p in sorted(target.glob('**/*'), reverse=True):
if not p.exists():
continue
p.chmod(0o666)
if p.is_dir():
p.rmdir()
else:
if only_if_empty:
raise RuntimeError(f'{p.parent} is not empty!')
p.unlink()
target.rmdir()
This relies on the fact that Path
is orderable, and longer paths will always sort after shorter paths, just like str
. Therefore, directories will come before files. If we reverse the sort, files will then come before their respective containers, so we can simply unlink/rmdir them one by one with one pass.
Benefits:
- It's NOT relying on external binaries: everything uses Python's batteries-included modules (Python >= 3.6)
- Which means that it does not need to repeatedly start a new subprocess to do unlinking
- It's quite fast & simple; you don't have to implement your own recursion
- It's cross-platform (at least, that's what
pathlib
promises in Python 3.6; no operation above stated to not run on Windows)
- If needed, one can do a very granular logging, e.g., log each deletion as it happens.
Pandas - How to flatten a hierarchical index in columns
The easiest and most intuitive solution for me was to combine the column names using get_level_values. This prevents duplicate column names when you do more than one aggregation on the same column:
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
df.columns = level_one + level_two
If you want a separator between columns, you can do this. This will return the same thing as Seiji Armstrong's comment on the accepted answer that only includes underscores for columns with values in both index levels:
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
column_separator = ['_' if x != '' else '' for x in level_two]
df.columns = level_one + column_separator + level_two
I know this does the same thing as Andy Hayden's great answer above, but I think it is a bit more intuitive this way and is easier to remember (so I don't have to keep referring to this thread), especially for novice pandas users.
This method is also more extensible in the case where you may have 3 column levels.
level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
level_three = df.columns.get_level_values(2).astype(str)
df.columns = level_one + level_two + level_three
What is PEP8's E128: continuation line under-indented for visual indent?
This goes also for statements like this (auto-formatted by PyCharm):
return combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
Which will give the same style-warning. In order to get rid of it I had to rewrite it to:
return \
combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
C# get string from textbox
if in string:
string yourVar = yourTextBoxname.Text;
if in numbers:
int yourVar = int.Parse(yourTextBoxname.Text);
JSON for List of int
Assuming your ints are 0, 375, 668,5 and 6:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [
0,
375,
668,
5,
6
]
}
I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/
Making PHP var_dump() values display one line per value
I didn't wanna stop using var_dump($variable);die();
and using pre
tags and loops seems overkill to me, so since I am looking at the dump in a browser, I just right click the page and choose Inspect (I use Chrome). The Elements section of the Developer Tools show the variable in a very readable format.
pyplot axes labels for subplots
Wen-wei Liao's answer is good if you are not trying to export vector graphics or that you have set up your matplotlib backends to ignore colorless axes; otherwise the hidden axes would show up in the exported graphic.
My answer suplabel
here is similar to the fig.suptitle
which uses the fig.text
function. Therefore there is no axes artist being created and made colorless.
However, if you try to call it multiple times you will get text added on top of each other (as fig.suptitle
does too). Wen-wei Liao's answer doesn't, because fig.add_subplot(111)
will return the same Axes object if it is already created.
My function can also be called after the plots have been created.
def suplabel(axis,label,label_prop=None,
labelpad=5,
ha='center',va='center'):
''' Add super ylabel or xlabel to the figure
Similar to matplotlib.suptitle
axis - string: "x" or "y"
label - string
label_prop - keyword dictionary for Text
labelpad - padding from the axis (default: 5)
ha - horizontal alignment (default: "center")
va - vertical alignment (default: "center")
'''
fig = pylab.gcf()
xmin = []
ymin = []
for ax in fig.axes:
xmin.append(ax.get_position().xmin)
ymin.append(ax.get_position().ymin)
xmin,ymin = min(xmin),min(ymin)
dpi = fig.dpi
if axis.lower() == "y":
rotation=90.
x = xmin-float(labelpad)/dpi
y = 0.5
elif axis.lower() == 'x':
rotation = 0.
x = 0.5
y = ymin - float(labelpad)/dpi
else:
raise Exception("Unexpected axis: x or y")
if label_prop is None:
label_prop = dict()
pylab.text(x,y,label,rotation=rotation,
transform=fig.transFigure,
ha=ha,va=va,
**label_prop)
Procedure expects parameter which was not supplied
If Template is not set (i.e. ==null), this error will be raised, too.
More comments:
If you know the parameter value by the time you add parameters, you can also use AddWithValue
The EXEC is not required. You can reference the @template parameter in the SELECT directly.
How to check if a process id (PID) exists
You have two ways:
Lets start by looking for a specific application in my laptop:
[root@pinky:~]# ps fax | grep mozilla
3358 ? S 0:00 \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2 S+ 0:00 \_ grep mozilla
All examples now will look for PID 3358.
First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:
[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358
So your code will be:
if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
kill $PID
fi
Second way: Just look for something in the /proc/$PID
directory. I am using "exe" in this example, but you can use anything else.
[root@pinky:~]# ls -l /proc/3358/exe
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash
So your code will be:
if [ -f /proc/$PID/exe ]; then
kill $PID
fi
BTW: whats wrong with kill -9 $PID || true
?
EDIT:
After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.
TypeError: argument of type 'NoneType' is not iterable
The python error says that wordInput
is not an iterable -> it is of NoneType.
If you print wordInput
before the offending line, you will see that wordInput
is None
.
Since wordInput
is None
, that means that the argument passed to the function is also None
. In this case word
. You assign the result of pickEasy
to word
.
The problem is that your pickEasy
function does not return anything. In Python, a method that didn't return anything returns a NoneType.
I think you wanted to return a word
, so this will suffice:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
How to calculate the difference between two dates using PHP?
View Hours and Minuts and Seconds..
$date1 = "2008-11-01 22:45:00";
$date2 = "2009-12-04 13:44:01";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
$minuts = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
$seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));
printf("%d years, %d months, %d days, %d hours, %d minuts\n, %d seconds\n", $years, $months, $days, $hours, $minuts, $seconds);
Java: how to convert HashMap<String, Object> to array
You may try this too.
public static String[][] getArrayFromHash(Hashtable<String,String> data){
String[][] str = null;
{
Object[] keys = data.keySet().toArray();
Object[] values = data.values().toArray();
str = new String[keys.length][values.length];
for(int i=0;i<keys.length;i++) {
str[0][i] = (String)keys[i];
str[1][i] = (String)values[i];
}
}
return str;
}
Here I am using String as return type. You may change it to required return type by you.
Multiple input in JOptionPane.showInputDialog
Yes. You know that you can put any Object
into the Object
parameter of most JOptionPane.showXXX methods
, and often that Object
happens to be a JPanel
.
In your situation, perhaps you could use a JPanel
that has several JTextFields
in it:
import javax.swing.*;
public class JOptionPaneMultiInput {
public static void main(String[] args) {
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("x:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("y:"));
myPanel.add(yField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("x value: " + xField.getText());
System.out.println("y value: " + yField.getText());
}
}
}
momentJS date string add 5 days
To get an actual working example going that returns what one would expect:
var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
var thing = new_date.add(5, 'days').format('DD/MM/YYYY');
window.console.log(thing)
How to get content body from a httpclient call?
The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await
with Task'1.Result
, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.
I've rewritten your function and function call, which should fix your issue:
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
And your final function call:
Task<string> result = GetResponseString(text);
var finalResult = result.Result;
Or even better:
var finalResult = await GetResponseString(text);
difference between throw and throw new Exception()
One other point that I didn't see anyone make:
If you don't do anything in your catch {} block, having a try...catch is pointless. I see this all the time:
try
{
//Code here
}
catch
{
throw;
}
Or worse:
try
{
//Code here
}
catch(Exception ex)
{
throw ex;
}
Worst yet:
try
{
//Code here
}
catch(Exception ex)
{
throw new System.Exception(ex.Message);
}
Get the client's IP address in socket.io
For latest socket.io version use
socket.request.connection.remoteAddress
For example:
var socket = io.listen(server);
socket.on('connection', function (client) {
var client_ip_address = socket.request.connection.remoteAddress;
}
beware that the code below returns the Server's IP, not the Client's IP
var address = socket.handshake.address;
console.log('New connection from ' + address.address + ':' + address.port);
How do I hide an element when printing a web page?
You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):
<div id="printOption">
<a href="javascript:void();"
onclick="document.getElementById('printOption').style.visibility = 'hidden';
document.print();
return true;">
Print
</a>
</div>
The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).
The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption
ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.
Where is a log file with logs from a container?
Here is the location for
Windows 10 + WSL 2 (Ubuntu 20.04), Docker version 20.10.2, build 2291f61
Lets say
DOCKER_ARTIFACTS == \\wsl$\docker-desktop-data\version-pack-data\community\docker
Location of container logs can be found in
DOCKER_ARTIFACTS\containers\[Your_container_ID]\[Your_container_ID]-json.log
Here is an example
CSS word-wrapping in div
It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the
overflow-x: scroll;
What happens if you remove that?
Random date in C#
private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}
For better performance if this will be called repeatedly, create the start
and gen
(and maybe even range
) variables outside of the function.
How to check if a folder exists
Using java.nio.file.Files
:
Path path = ...;
if (Files.exists(path)) {
// ...
}
You can optionally pass this method LinkOption
values:
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
There's also a method notExists
:
if (Files.notExists(path)) {
How to check if a function exists on a SQL database
I've found you can use a very non verbose and straightforward approach to checking for the existence various SQL Server objects this way:
IF OBJECTPROPERTY (object_id('schemaname.scalarfuncname'), 'IsScalarFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.tablefuncname'), 'IsTableFunction') = 1
IF OBJECTPROPERTY (object_id('schemaname.procname'), 'IsProcedure') = 1
This is based on the OBJECTPROPERTY function which is available in SQL 2005+. The MSDN article can be found here.
The OBJECTPROPERTY function uses the following signature:
OBJECTPROPERTY ( id , property )
You pass a literal value into the property parameter, designating the type of object you are looking for. There's a massive list of values you can supply.
How to export database schema in Oracle to a dump file
It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
Why do we use volatile keyword?
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you
know, I can be changed by some XYZ
that you're not even aware of. That
XYZ could be anything. Maybe some
alien outside this planet called
program. Maybe some lightning, some
form of interrupt, volcanoes, etc can
mutate me. Maybe. You never know who
is going to change me! So O you
ignorant, stop playing an all-knowing
god, and don't dare touch the code
where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the
implementation to avoid aggressive
optimization involving the object
because the value of the object might
be changed by means undetectable by an
implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
How to Change color of Button in Android when Clicked?
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- default -->
<item
android:state_pressed="false"
android:state_focused="false">
<shape
android:innerRadiusRatio="1"
android:shape="rectangle" >
<solid android:color="#00a3e2" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
</item>
<!-- button focused -->
<item
android:state_pressed="false"
android:state_focused="true">
<shape
android:innerRadiusRatio="1"
android:shape="rectangle" >
<solid android:color="#5a97f5" />
<padding
android:bottom="5dp"
android:left="10dp"
android:right="10dp"
android:top="5dp" />
</shape></item>
<!-- button pressed -->
<item
android:state_pressed="true"
android:state_focused="false">
<shape
android:innerRadiusRatio="1"
android:shape="rectangle" >
<solid android:color="#478df9"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape></item>
</selector>
Add text to Existing PDF using Python
I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:
- read your PDF using
PdfFileReader()
, we'll call this input
- create a new pdf containing your text to add using ReportLab, save this as a string object
- read the string object using
PdfFileReader()
, we'll call this text
- create a new PDF object using
PdfFileWriter()
, we'll call this output
- iterate through input and apply
.mergePage(*text*.getPage(0))
for each page you want the text added to, then use output.addPage()
to add the modified pages to a new document
This works well for simple text additions. See PyPDF's sample for watermarking a document.
Here is some code to answer the question below:
packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
<do something with canvas>
can.save()
packet.seek(0)
input = PdfFileReader(packet)
From here you can merge the pages of the input file with another document.
How can I read user input from the console?
I'm not sure what your problem is (since you haven't told us), but I'm guessing at
a = Console.Read();
This will only read one character from your Console.
You can change your program to this. To make it more robust, accept more than 1 char input, and validate that the input is actually a number:
double a, b;
Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
if (double.TryParse(Console.ReadLine(), out a)) {
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
} else {
//user gave an illegal input. Handle it here.
}
Convert RGB values to Integer
To get individual colour values you can use Color like following for pixel(x,y).
import java.awt.Color;
import java.awt.image.BufferedImage;
Color c = new Color(buffOriginalImage.getRGB(x,y));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
The above will give you the integer values of Red, Green and Blue in range of 0 to 255.
To set the values from RGB you can do so by:
Color myColour = new Color(red, green, blue);
int rgb = myColour.getRGB();
//Change the pixel at (x,y) ti rgb value
image.setRGB(x, y, rgb);
Please be advised that the above changes the value of a single pixel. So if you need to change the value entire image you may need to iterate over the image using two for loops.
Border Height on CSS
No, there isn't. The border will always be as tall as the element.
You can achieve the same effect by wrapping the contents of the cell in a <span>
, and applying height/border styles to that. Or by drawing a short vertical line in an 1 pixel wide PNG which is the correct height, and applying it as a background to the cell:
background:url(line.png) bottom right no-repeat;
Update Rows in SSIS OLEDB Destination
You can't do a bulk-update in SSIS within a dataflow task with the OOB components.
The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.
Stage data
Set based updates
You'll get much better performance with a pattern like this versus using the OLE DB Command
transformation for anything but trivial amounts of data.
If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.
Else clause on Python while statement
The else
clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break
or return
out of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
what does this mean ? image/png;base64?
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
How to restart Jenkins manually?
Sometimes there will be some stale Jenkins processes, so ps -ef | grep jenkins
kill all of them. Restart as described in previous answers, and it will be clean.
ps -ef | grep jenkins
sudo kill -kill <pid>
How to add System.Windows.Interactivity to project?
If you are working with MVVM Light you have to use the System.Windows.Interactivity Version 4.0
(the NuGet .dll wont work) that you can find under :
PathToProjectFolder\Software\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll
Just add this .dll manually as Reference and it should be fine.
How to create cron job using PHP?
why you not use curl?
logically, if you execute php file, you will execute that by url on your browser.
its very simple if you run curl
while(true)
{
sleep(60); // sleep for 60 sec = 1 minute
$s = curl_init();
curl_setopt($s,CURLOPT_URL, $your_php_url_to_cron);
curl_exec($s);
curl_getinfo($s,CURLINFO_HTTP_CODE);
curl_close($s);
}
How to clear the cache of nginx?
Please take note that proxy_cache_bypass can give you a world of hurt if your app doesn't return a cacheable response for that specific request where you trigger it.
If for example your app sends a cookie with every first request, then a script which triggers proxy_pass_bypass via curl will probably get that cookie in the answer, and nginx will not use that response to refresh the cached item.
mappedBy reference an unknown target entity property
I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.
If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany
annotation with the 'mappedBy
' property, it also means that the other side holding the @ManyToOne
annotation with the @JoinColumn
is the 'owner' of this bi-directional relationship.
Also, mappedBy
takes in the instance name (mCustomer
in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).
BONUS :
Also, look into the orphanRemoval
property of @OneToMany
annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.
Docker error : no space left on device
Your cgroups have the cpuset
controller enabled. This controller is mostly useful in NUMA environment where it allows to finely specify which CPU/memory bank your tasks are allowed to run.
By default the mandatory cpuset.mems
and cpuset.cpus
are not set which means that there is "no space left" for your task, hence the error.
The easiest way to fix this is to enable cgroup.clone_children
to 1 in the root cgroup. In your case, it should be
echo 1 > /sys/fs/cgroup/docker/cgroup.clone_children
It will basically instruct the system to automatically initialize container's cpuset.mems
and cpuset.cpus
from their parent cgroup.
Read text from response
This article gives a good overview of using the HttpWebResponse object:How to use HttpWebResponse
Relevant bits below:
HttpWebResponse webresponse;
webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(),enc);
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
return Response;
Read values into a shell variable from a pipe
read
won't read from a pipe (or possibly the result is lost because the pipe creates a subshell). You can, however, use a here string in Bash:
$ read a b c <<< $(echo 1 2 3)
$ echo $a $b $c
1 2 3
But see @chepner's answer for information about lastpipe
.
Get the key corresponding to the minimum value within a dictionary
to create an orderable class you have to override 6 special functions, so that it would be called by the min() function
these methods are__lt__ , __le__, __gt__, __ge__, __eq__ , __ne__
in order they are less than, less than or equal, greater than, greater than or equal, equal, not equal.
for example you should implement __lt__
as follows:
def __lt__(self, other):
return self.comparable_value < other.comparable_value
then you can use the min function as follows:
minValue = min(yourList, key=(lambda k: yourList[k]))
this worked for me.
How to fix "Headers already sent" error in PHP
Instead of the below line
//header("Location:".ADMIN_URL."/index.php");
write
echo("<script>location.href = '".ADMIN_URL."/index.php?msg=$msg';</script>");
or
?><script><?php echo("location.href = '".ADMIN_URL."/index.php?msg=$msg';");?></script><?php
It'll definitely solve your problem.
I faced the same problem but I solved through writing header location in the above way.
What is difference between mutable and immutable String in java
String in Java is immutable. However what does it mean to be mutable in programming context is the first question. Consider following class,
public class Dimension {
private int height;
private int width;
public Dimenstion() {
}
public void setSize(int height, int width) {
this.height = height;
this.width = width;
}
public getHeight() {
return height;
}
public getWidth() {
return width;
}
}
Now after creating the instance of Dimension
we can always update it's attributes. Note that if any of the attribute, in other sense state, can be updated for instance of the class then it is said to be mutable. We can always do following,
Dimension d = new Dimension();
d.setSize(10, 20);// Dimension changed
d.setSize(10, 200);// Dimension changed
d.setSize(100, 200);// Dimension changed
Let's see in different ways we can create a String in Java.
String str1 = "Hey!";
String str2 = "Jack";
String str3 = new String("Hey Jack!");
String str4 = new String(new char[] {'H', 'e', 'y', '!'});
String str5 = str1 + str2;
str1 = "Hi !";
// ...
So,
str1
and str2
are String literals which gets created in String constant pool
str3
, str4
and str5
are String Objects which are placed in Heap memory
str1 = "Hi!";
creates "Hi!"
in String constant pool and it's totally different reference than "Hey!"
which str1
referencing earlier.
Here we are creating the String literal or String Object. Both are different, I would suggest you to read following post to understand more about it.
In any String declaration, one thing is common, that it does not modify but it gets created or shifted to other.
String str = "Good"; // Create the String literal in String pool
str = str + " Morning"; // Create String with concatenation of str + "Morning"
|_____________________|
|- Step 1 : Concatenate "Good" and " Morning" with StringBuilder
|- Step 2 : assign reference of created "Good Morning" String Object to str
How String became immutable ?
It's non changing behaviour, means, the value once assigned can not be updated in any other way. String class internally holds data in character array. Moreover, class is created to be immutable. Take a look at this strategy for defining immutable class.
Shifting the reference does not mean you changed it's value. It would be mutable if you can update the character array which is behind the scene in String class. But in reality that array will be initialized once and throughout the program it remains the same.
Why StringBuffer is mutable ?
As you already guessed, StringBuffer class is mutable itself as you can update it's state directly. Similar to String it also holds value in character array and you can manipulate that array by different methods i.e. append, delete, insert etc. which directly changes the character value array.
Touch move getting stuck Ignored attempt to cancel a touchmove
I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.
My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this
function onTouchStart() {
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
}
function onTouchEnd() {
window.removeEventListener("touchmove", handleTouchMove, {
passive: true
});
}
function handleTouchMove(e) {
e.preventDefault();
}
For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:
let stopScrolling = false;
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
function handleTouchMove(e) {
if (!stopScrolling) {
return;
}
e.preventDefault();
}
function onTouchStart() {
stopScrolling = true;
}
function onTouchEnd() {
stopScrolling = false;
}
I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!
How do I exclude Weekend days in a SQL Server query?
The answer depends on your server's week-start set up, so it's either
SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (7,1)
if Sunday is the first day of the week for your server
or
SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (6,7)
if Monday is the first day of the week for your server
Comment if you've got any questions :-)
Change Oracle port from port 8080
From Start | Run open a command window.
Assuming your environmental variables are set correctly start with the following:
C:\>sqlplus /nolog
SQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008
Copyright (c) 1982, 2005, Oracle. All rights reserved.
SQL> connect
Enter user-name: system
Enter password: <enter password if will not be visible>
Connected.
SQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port]
PL/SQL procedure successfully completed.
SQL>quit
then open browser and use 3010 port.
How to use a Java8 lambda to sort a stream in reverse order?
This can easily be done using Java 8 and the use of a reversed Comparator.
I have created a list of files from a directory, which I display unsorted, sorted and reverse sorted using a simple Comparator for the sort and then calling reversed() on it to get the reversed version of that Comparator.
See code below:
package test;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
public static void main(String... args) {
File directory = new File("C:/Media");
File[] files = directory.listFiles();
List<File> filesList = Arrays.asList(files);
Comparator<File> comparator = Comparator.comparingLong(File::lastModified);
Comparator<File> reverseComparator = comparator.reversed();
List<File> forwardOrder = filesList.stream().sorted(comparator).collect(Collectors.toList());
List<File> reverseOrder = filesList.stream().sorted(reverseComparator).collect(Collectors.toList());
System.out.println("*** Unsorted ***");
filesList.forEach(SortTest::processFile);
System.out.println("*** Sort ***");
forwardOrder.forEach(SortTest::processFile);
System.out.println("*** Reverse Sort ***");
reverseOrder.forEach(SortTest::processFile);
}
private static void processFile(File file) {
try {
if (file.isFile()) {
System.out.println(file.getCanonicalPath() + " - " + new Date(file.lastModified()));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
How to determine MIME type of file in android?
I tried to use standard methods to determine the mime type, but I cannot retain the file extension using MimeTypeMap.getFileExtensionFromUrl(uri.getPath())
. This method returned me an empty string. So I made a non-trivial solution to retain the file extension.
Here is the method returning the file extension:
private String getExtension(String fileName){
char[] arrayOfFilename = fileName.toCharArray();
for(int i = arrayOfFilename.length-1; i > 0; i--){
if(arrayOfFilename[i] == '.'){
return fileName.substring(i+1, fileName.length());
}
}
return "";
}
And having retained the file extension, it is possible to get mime type like below:
public String getMimeType(File file) {
String mimeType = "";
String extension = getExtension(file.getName());
if (MimeTypeMap.getSingleton().hasExtension(extension)) {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return mimeType;
}
Drop a temporary table if it exists
What you asked for is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Ruby Array find_first object?
Do you need the object itself or do you just need to know if there is an object that satisfies.
If the former then yes: use find:
found_object = my_array.find { |e| e.satisfies_condition? }
otherwise you can use any?
found_it = my_array.any? { |e| e.satisfies_condition? }
The latter will bail with "true" when it finds one that satisfies the condition.
The former will do the same, but return the object.
Switch between python 2.7 and python 3.5 on Mac OS X
Similar to John Wilkey's answer I would run python2 by finding which python
, something like using /usr/bin/python
and then creating an alias in .bash_profile
:
alias python2="/usr/bin/python"
I can now run python3 by calling python
and python2 by calling python2
.
How to access cookies in AngularJS?
Add angular cookie lib : angular-cookies.js
You can use $cookies or $cookieStore parameter to the respective controller
Main controller add this inject 'ngCookies':
angular.module("myApp", ['ngCookies']);
Use Cookies in your controller like this way:
app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) {
//store cookies
$cookies.putObject('final_total_price', $rootScope.fn_pro_per);
//Get cookies
$cookies.getObject('final_total_price'); }
Adding a module (Specifically pymorph) to Spyder (Python IDE)
Ok, no one has answered this yet but I managed to figure it out and get it working after also posting on the spyder discussion boards. For any libraries that you want to add that aren't included in the default search path of spyder, you need to go into Tools and add a path to each library via the PYTHONPATH manager. You'll then need to update the module names list from the same menu and restart spyder before the changes take effect.
PHP - Debugging Curl
You can enable the CURLOPT_VERBOSE
option:
curl_setopt($curlhandle, CURLOPT_VERBOSE, true);
When CURLOPT_VERBOSE
is set, output is written to STDERR or the file specified using CURLOPT_STDERR
. The output is very informative.
You can also use tcpdump or wireshark to watch the network traffic.
How to use forEach in vueJs?
You can also use .map() as:
var list=[];
response.data.message.map(function(value, key) {
list.push(value);
});
Create an instance of a class from a string
I've used this method successfully:
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)
You'll need to cast the returned object to your desired object type.
What is Ruby's double-colon `::`?
module Amimal
module Herbivorous
EATER="plants"
end
end
Amimal::Herbivorous::EATER => "plants"
:: Is used to create a scope . In order to access Constant EATER from 2 modules we need to scope the modules to reach up to the constant
C# importing class into another class doesn't work
using
is for namespaces only - if both classes are in the same namespace just drop the using
.
You have to reference the assembly created in the first step when you compile the .exe:
csc /t:library /out:MyClass.dll MyClass.cs
csc /reference:MyClass.dll /t:exe /out:MyProgram.exe MyMainClass.cs
You can make things simpler if you just compile the files together:
csc /t:exe /out:MyProgram.exe MyMainClass.cs MyClass.cs
or
csc /t:exe /out:MyProgram.exe *.cs
EDIT:
Here's how the files should look like:
MyClass.cs:
namespace MyNamespace {
public class MyClass {
void stuff() {
}
}
}
MyMainClass.cs:
using System;
namespace MyNamespace {
public class MyMainClass {
static void Main() {
MyClass test = new MyClass();
}
}
}
IntelliJ does not show project folders
As I had the same issue and none of the above worked for me, this is what I did! I know it is a grumpy solution but at least it finally worked! I am not sure why only this method worked. It should be some weird cache in my PC?
- I did close IntelliJ
- I did completely remove the
.idea
folder from my project
- I did move the folder
demo-project
to demo-project-temp
- I did create a new empty folder
demo-project
- I did open this empty folder with intelliJ
- I did move all the content
demo-project-temp
. Don't forget to also move the hidden files
- Press right click "Synchronize" to your project
- You should see all the files and folders now!
- Now you can also safely remove the folder
demo-project-temp
. If you are on linux or MAC do it with rmdir demo-project-temp
just to make sure that your folder is empty
Could pandas use column as index?
You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.
Here is my solution:
Firstly, import pandas as pd:
import pandas as pd
Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.
df = pd.read_excel('testexcel.xlsx', index_col=0)
At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd
.
For visual inspection, read the dataframe using df.head()
which will print the following output
Now you can fetch the values of the desired columns of the dataframe and print it
Why is there no tuple comprehension in Python?
Tuples cannot efficiently be appended like a list.
So a tuple comprehension would need to use a list internally and then convert to a tuple.
That would be the same as what you do now : tuple( [ comprehension ] )
SQL Server Profiler - How to filter trace to only display events from one database?
By experiment I was able to observe this:
When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!
In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.
The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)
Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below
SELECT *
FROM master..sysdatabases
WHERE name like '%your_db_name%' -- Remove this line to see all databases
ORDER BY dbid
Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000
Eclipse won't compile/run java file
Your project has to have a builder set for it. If there is not one Eclipse will default to Ant. Which you can use you have to create an Ant build file, which you can Google how to do. It is rather involved though. This is not required to run locally in Eclipse though. If your class is run-able. It looks like yours is, but we can not see all of it.
If you look at your project build path do you have an output folder selected? If you check that folder have the compiled class files been put there? If not the something is not set in Eclpise for it to know to compile. You might check to see if auto build is set for your project.
Powershell equivalent of bash ampersand (&) for forking/running background processes
From PowerShell Core 6.0 you are able to write &
at end of command and it will be equivalent to running you pipeline in background in current working directory.
It's not equivalent to &
in bash, it's just a nicer syntax for current PowerShell jobs feature. It returns a job object so you can use all other command that you would use for jobs. For example Receive-Job
:
C:\utils> ping google.com &
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
35 Job35 BackgroundJob Running True localhost Microsoft.PowerShell.M...
C:\utils> Receive-Job 35
Pinging google.com [172.217.16.14] with 32 bytes of data:
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55
Ping statistics for 172.217.16.14:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 10ms, Maximum = 11ms, Average = 10ms
C:\utils>
If you want to execute couple of statements in background you can combine &
call operator, { }
script block and this new &
background operator like here:
& { cd .\SomeDir\; .\SomeLongRunningOperation.bat; cd ..; } &
Here's some more info from documentation pages:
from What's New in PowerShell Core 6.0:
Support backgrounding of pipelines with ampersand (&) (#3360)
Putting &
at the end of a pipeline causes the pipeline to be run as a PowerShell job. When a pipeline is backgrounded, a job object is returned. Once the pipeline is running as a job, all of the standard *-Job
cmdlets can be used to manage the job. Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so Copy-Item $foo $bar &
just works. The job is also run in the current directory instead of the user's home directory. For more information about PowerShell jobs, see about_Jobs.
from about_operators / Ampersand background operator &:
Ampersand background operator &
Runs the pipeline before it in a PowerShell job. The ampersand background operator acts similarly to the UNIX "ampersand operator" which famously runs the command before it as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with Start-Job
. The following command contains basic usage of the ampersand background operator.
Get-Process -Name pwsh &
This is functionally equivalent to the following usage of Start-Job
.
Start-Job -ScriptBlock {Get-Process -Name pwsh}
Since it's functionally equivalent to using Start-Job
, the ampersand background operator returns a Job
object just like Start-Job does
. This means that you are able to use Receive-Job
and Remove-Job
just as you would if you had used Start-Job
to start the job.
$job = Get-Process -Name pwsh &
Receive-Job $job
Output
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
0 0.00 221.16 25.90 6988 988 pwsh
0 0.00 140.12 29.87 14845 845 pwsh
0 0.00 85.51 0.91 19639 988 pwsh
$job = Get-Process -Name pwsh &
Remove-Job $job
For more information on PowerShell jobs, see about_Jobs.
Greyscale Background Css Images
Here you go:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<style type="text/css">
div {
border: 1px solid black;
padding: 5px;
margin: 5px;
width: 600px;
height: 600px;
float: left;
color: white;
}
.grayscale {
background: url(yourimagehere.jpg);
-moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
-o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
-webkit-filter: grayscale(100%);
filter: gray;
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
}
.nongrayscale {
background: url(yourimagehere.jpg);
}
</style>
</head>
<body>
<div class="nongrayscale">
this is a non-grayscale of the bg image
</div>
<div class="grayscale">
this is a grayscale of the bg image
</div>
</body>
</html>
Tested it in FireFox, Chrome and IE. I've also attached an image to show my results of my implementation of this.
EDIT: Also, if you want the image to just toggle back and forth with jQuery, here's the page source for that...I've included the web link to jQuery and and image that's online so you should just be able to copy/paste to test it out:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style type="text/css">
div {
border: 1px solid black;
padding: 5px;
margin: 5px;
width: 600px;
height: 600px;
float: left;
color: white;
}
.grayscale {
background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
-moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
-o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
-webkit-filter: grayscale(100%);
filter: gray;
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
}
.nongrayscale {
background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$("#image").mouseover(function () {
$(".nongrayscale").removeClass().fadeTo(400,0.8).addClass("grayscale").fadeTo(400, 1);
});
$("#image").mouseout(function () {
$(".grayscale").removeClass().fadeTo(400, 0.8).addClass("nongrayscale").fadeTo(400, 1);
});
});
</script>
</head>
<body>
<div id="image" class="nongrayscale">
rollover this image to toggle grayscale
</div>
</body>
</html>
EDIT 2 (For IE10-11 Users): The solution above will not work with the changes Microsoft has made to the browser as of late, so here's an updated solution that will allow you to grayscale (or desaturate) your images.
_x000D_
_x000D_
<svg>_x000D_
<defs>_x000D_
<filter xmlns="http://www.w3.org/2000/svg" id="desaturate">_x000D_
<feColorMatrix type="saturate" values="0" />_x000D_
</filter>_x000D_
</defs>_x000D_
<image xlink:href="http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg" width="600" height="600" filter="url(#desaturate)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_
Finding the index of elements based on a condition using python list comprehension
Another way:
>>> [i for i in range(len(a)) if a[i] > 2]
[2, 5]
In general, remember that while find
is a ready-cooked function, list comprehensions are a general, and thus very powerful solution. Nothing prevents you from writing a find
function in Python and use it later as you wish. I.e.:
>>> def find_indices(lst, condition):
... return [i for i, elem in enumerate(lst) if condition(elem)]
...
>>> find_indices(a, lambda e: e > 2)
[2, 5]
Note that I'm using lists here to mimic Matlab. It would be more Pythonic to use generators and iterators.
How to activate an Anaconda environment
Though @Simba had a good answer at the time, a lot has changed in the conda env since 4.6. Conda activate (env-name)
overthrew source activate (env-name)
for good but not without it own challenges. conda activate
oftentimes forces your environment to base and makes you see something like this:
and throwing loads of error back at you. This can also be because auto_activate_base
is set to True.
You can check this by using the following command
conda config --set auto_activate_base False
source ~/.bashrc
And to reactivate use this
conda config --set auto_activate_base True
source ~/.bashrc
Replace a string in a file with nodejs
On Linux or Mac, keep is simple and just use sed with the shell. No external libraries required. The following code works on Linux.
const shell = require('child_process').execSync
shell(`sed -i "s!oldString!newString!g" ./yourFile.js`)
The sed syntax is a little different on Mac. I can't test it right now, but I believe you just need to add an empty string after the "-i":
const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)
The "g" after the final "!" makes sed replace all instances on a line. Remove it, and only the first occurrence per line will be replaced.
log4j: Log output of a specific class to a specific appender
Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern
it will create 0 byte file and not write anything:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false"/>
<param name="maxFileSize" value="1GB"/>
<param name="maxBackupIndex" value="2"/>
<param name="file" value="/tmp/bd.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<logger name="com.example.mypackage" additivity="false">
<level value="debug"/>
<appender-ref ref="bdfile"/>
</logger>
<root>
<priority value="info"/>
<appender-ref ref="bdfile"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration>
Simple way to unzip a .zip file using zlib
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
Add a summary row with totals
Try to use union all
as below
SELECT [Type], [Total Sales] From Before
union all
SELECT 'Total', Sum([Total Sales]) From Before
if you have problem with ordering, as i-one suggested try this:
select [Type], [Total Sales]
from (SELECT [Type], [Total Sales], 0 [Key]
From Before
union all
SELECT 'Total', Sum([Total Sales]), 1 From Before) sq
order by [Key], Type
How to get child process from parent process
For the case when the process tree of interest has more than 2 levels (e.g. Chromium spawns 4-level deep process tree), pgrep
isn't of much use. As others have mentioned above, procfs files contain all the information about processes and one just needs to read them. I built a CLI tool called Procpath which does exactly this. It reads all /proc/N/stat
files, represents the contents as a JSON tree and expose it to JSONPath queries.
To get all descendant process' comma-separated PIDs of a non-root process (for the root it's ..stat.pid
) it's:
$ procpath query -d, "..children[?(@.stat.pid == 24243)]..pid"
24243,24259,24284,24289,24260,24262,24333,24337,24439,24570,24592,24606,...
split string only on first instance - java
This works:
public class Split
{
public static void main(String...args)
{
String a = "%abcdef&Ghijk%xyz";
String b[] = a.split("%", 2);
System.out.println("Value = "+b[1]);
}
}
Disable password authentication for SSH
In file /etc/ssh/sshd_config
# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication no
Uncomment the second line, and, if needed, change yes to no.
Then run
service ssh restart
SQL LEFT-JOIN on 2 fields for MySQL
Let's try this way:
select
a.ip,
a.os,
a.hostname,
a.port,
a.protocol,
b.state
from a
left join b
on a.ip = b.ip
and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/
So, in where
clause you can filter result set by column from right table only on this way:
...
where b.somecolumn <> (=) null
Codeigniter displays a blank page instead of error messages
check if error_reporting is ON at server or not, if that id off you wont get any errors and just blank page. if you are on a shared server then you can enable error reporting via htaccess. In codeIgniter add following in your htaccess
php_flag display_errors On
and set
error_reporting(E_ERROR); ## or what ever setting desired in php
hope it will work for you
How do I convert a javascript object array to a string array of the object attribute I want?
If your array of objects is items
, you can do:
_x000D_
_x000D_
var items = [{_x000D_
id: 1,_x000D_
name: 'john'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'jane'_x000D_
}, {_x000D_
id: 2000,_x000D_
name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_
Documentation: map()
How to normalize a vector in MATLAB efficiently? Any related built-in function?
I took Mr. Fooz's code and also added Arlen's solution too and here are the timings that I've gotten for Octave:
clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; for i=1:N, V1 = V/norm(V); end; toc % 7.0 s
tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 6.4 s
tic; for i=1:N, V3 = V/sqrt(V'*V); end; toc % 5.5 s
tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 6.6 s
tic; for i=1:N, V1 = V/norm(V); end; toc % 7.1 s
tic; for i=1:N, d = 1/norm(V); V1 = V*d;end; toc % 4.7 s
Then, because of something I'm currently looking at, I tested out this code for ensuring that each row sums to 1:
clc; clear all;
m = 2048;
V = rand(m);
N = 100;
tic; for i=1:N, V1 = V ./ (sum(V,2)*ones(1,m)); end; toc % 8.2 s
tic; for i=1:N, V2 = bsxfun(@rdivide, V, sum(V,2)); end; toc % 5.8 s
tic; for i=1:N, V3 = bsxfun(@rdivide, V, V*ones(m,1)); end; toc % 5.7 s
tic; for i=1:N, V4 = V ./ (V*ones(m,m)); end; toc % 77.5 s
tic; for i=1:N, d = 1./sum(V,2);V5 = bsxfun(@times, V, d); end; toc % 2.83 s
tic; for i=1:N, d = 1./(V*ones(m,1));V6 = bsxfun(@times, V, d);end; toc % 2.75 s
tic; for i=1:N, V1 = V ./ (sum(V,2)*ones(1,m)); end; toc % 8.2 s
Can I set state inside a useEffect hook
? 1. Can I set state inside a useEffect hook?
In principle, you can set state freely where you need it - including inside useEffect
and even during rendering. Just make sure to avoid infinite loops by settting Hook deps
properly and/or state conditionally.
? 2. Lets say I have some state that is dependent on some other state. Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?
You just described the classic use case for useReducer
:
useReducer
is usually preferable to useState
when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. (React docs)
When setting a state variable depends on the current value of another state variable, you might want to try replacing them both with useReducer
.
[...] When you find yourself writing setSomething(something => ...)
, it’s a good time to consider using a reducer instead. (Dan Abramov, Overreacted blog)
_x000D_
_x000D_
let MyComponent = () => {_x000D_
let [state, dispatch] = useReducer(reducer, { a: 1, b: 2 });_x000D_
_x000D_
useEffect(() => {_x000D_
console.log("Some effect with B");_x000D_
}, [state.b]);_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<p>A: {state.a}, B: {state.b}</p>_x000D_
<button onClick={() => dispatch({ type: "SET_A", payload: 5 })}>_x000D_
Set A to 5 and Check B_x000D_
</button>_x000D_
<button onClick={() => dispatch({ type: "INCREMENT_B" })}>_x000D_
Increment B_x000D_
</button>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
// B depends on A. If B >= A, then reset B to 1._x000D_
function reducer(state, { type, payload }) {_x000D_
const someCondition = state.b >= state.a;_x000D_
_x000D_
if (type === "SET_A")_x000D_
return someCondition ? { a: payload, b: 1 } : { ...state, a: payload };_x000D_
else if (type === "INCREMENT_B") return { ...state, b: state.b + 1 };_x000D_
return state;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect } = React</script>
_x000D_
_x000D_
_x000D_
? 3. Will the effects cascade such that, when I click the button, the first effect will fire, causing b to change, causing the second effect to fire, before the next render?
useEffect
always runs after the render is committed and DOM changes are applied. The first effect fires, changes b
and causes a re-render. After this render has completed, second effect will run due to b
changes.
_x000D_
_x000D_
let MyComponent = props => {_x000D_
console.log("render");_x000D_
let [a, setA] = useState(1);_x000D_
let [b, setB] = useState(2);_x000D_
_x000D_
let isFirstRender = useRef(true);_x000D_
_x000D_
useEffect(() => {_x000D_
console.log("useEffect a, value:", a);_x000D_
if (isFirstRender.current) isFirstRender.current = false;_x000D_
else setB(3);_x000D_
return () => {_x000D_
console.log("unmount useEffect a, value:", a);_x000D_
};_x000D_
}, [a]);_x000D_
useEffect(() => {_x000D_
console.log("useEffect b, value:", b);_x000D_
return () => {_x000D_
console.log("unmount useEffect b, value:", b);_x000D_
};_x000D_
}, [b]);_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<p>a: {a}, b: {b}</p>_x000D_
<button_x000D_
onClick={() => {_x000D_
console.log("Clicked!");_x000D_
setA(5);_x000D_
}}_x000D_
>_x000D_
click me_x000D_
</button>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_
? 4. Are there any performance downsides to structuring code like this?
Yes. By wrapping the state change of b
in a separate useEffect
for a
, the browser has an additional layout/paint phase - these effects are potentially visible for the user. If there is no way you want give useReducer
a try, you could change b
state together with a
directly:
_x000D_
_x000D_
let MyComponent = () => {_x000D_
console.log("render");_x000D_
let [a, setA] = useState(1);_x000D_
let [b, setB] = useState(2);_x000D_
_x000D_
useEffect(() => {_x000D_
console.log("useEffect b, value:", b);_x000D_
return () => {_x000D_
console.log("unmount useEffect b, value:", b);_x000D_
};_x000D_
}, [b]);_x000D_
_x000D_
const handleClick = () => {_x000D_
console.log("Clicked!");_x000D_
setA(5);_x000D_
b >= 5 ? setB(1) : setB(b + 1);_x000D_
};_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<p>_x000D_
a: {a}, b: {b}_x000D_
</p>_x000D_
<button onClick={handleClick}>click me</button>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_
Correct use of flush() in JPA/Hibernate
Probably the exact details of em.flush()
are implementation-dependent.
In general anyway, JPA providers like Hibernate can cache the SQL instructions they are supposed to send to the database, often until you actually commit the transaction.
For example, you call em.persist()
, Hibernate remembers it has to make a database INSERT, but does not actually execute the instruction until you commit the transaction. Afaik, this is mainly done for performance reasons.
In some cases anyway you want the SQL instructions to be executed immediately; generally when you need the result of some side effects, like an autogenerated key, or a database trigger.
What em.flush()
does is to empty the internal SQL instructions cache, and execute it immediately to the database.
Bottom line: no harm is done, only you could have a (minor) performance hit since you are overriding the JPA provider decisions as regards the best timing to send SQL instructions to the database.
Is it possible to set transparency in CSS3 box-shadow?
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
_x000D_
_x000D_
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_
How can I increase a scrollbar's width using CSS?
Yes.
If the scrollbar is not the browser scrollbar, then it will be built of regular HTML elements (probably div
s and span
s) and can thus be styled (or will be Flash, Java, etc and can be customized as per those environments).
The specifics depend on the DOM structure used.
How to properly add include directories with CMake
I had the same problem.
My project directory was like this:
--project
---Classes
----Application
-----.h and .c files
----OtherFolders
--main.cpp
And what I used to include the files in all those folders:
file(GLOB source_files
"*.h"
"*.cpp"
"Classes/*/*.cpp"
"Classes/*/*.h"
)
add_executable(Server ${source_files})
And it totally worked.
JOIN queries vs multiple queries
This question is old, but is missing some benchmarks. I benchmarked JOIN against its 2 competitors:
- N+1 queries
- 2 queries, the second one using a
WHERE IN(...)
or equivalent
The result is clear: on MySQL, JOIN
is much faster. N+1 queries can drop the performance of an application drastically:
That is, unless you select a lot of records that point to a very small number of distinct, foreign records. Here is a benchmark for the extreme case:
This is very unlikely to happen in a typical application, unless you're joining a -to-many relationship, in which case the foreign key is on the other table, and you're duplicating the main table data many times.
Takeaway:
- For *-to-one relationships, always use
JOIN
- For *-to-many relationships, a second query might be faster
See my article on Medium for more information.
Your project path contains non-ASCII characters android studio
I created a symbol link like described by Clézio before. However, I had to specify a suitable encoding (e.g chcp 65001) in command line before.
chcp 65001
mklink /D "C:\android-sdk" "C:\Users\René\AppData\Local\Android\sdk"
If you have your SDK installed under Path C:\Users[USER]\AppData... you may have to run command line with administrativ priviledges.
SQL Server date format yyyymmdd
Assuming your "date" column is not actually a date.
Select convert(varchar(8),cast('12/24/2016' as date),112)
or
Select format(cast('12/24/2016' as date),'yyyyMMdd')
Returns
20161224
How to get unique values in an array
Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains
and unique
_x000D_
_x000D_
Array.prototype.contains = function(v) {_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
if (this[i] === v) return true;_x000D_
}_x000D_
return false;_x000D_
};_x000D_
_x000D_
Array.prototype.unique = function() {_x000D_
var arr = [];_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
if (!arr.contains(this[i])) {_x000D_
arr.push(this[i]);_x000D_
}_x000D_
}_x000D_
return arr;_x000D_
}_x000D_
_x000D_
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];_x000D_
var uniques = duplicates.unique(); // result = [1,3,4,2,8]_x000D_
_x000D_
console.log(uniques);
_x000D_
_x000D_
_x000D_
For more reliability, you can replace contains
with MDN's indexOf
shim and check if each element's indexOf
is equal to -1: documentation
How do you add an ActionListener onto a JButton in Java
Two ways:
1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this);
Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e)
. However, doing this for multiple buttons can be confusing, because the actionPerformed
method will have to check the source of each event (e.getSource()
) to see which button it came from.
2. Use anonymous inner classes:
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
Later, you'll have to define selectionButtonPressed()
.
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed()
if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()
).
What does the NS prefix mean?
When NeXT were defining the NextStep API (as opposed to the NEXTSTEP operating system), they used the prefix NX, as in NXConstantString. When they were writing the OpenStep specification with Sun (not to be confused with the OPENSTEP operating system) they used the NS prefix, as in NSObject.
Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
You can fix this by upgrading your project to .NET Framework 4.7.2. This was answered by Alex Ghiondea - MSFT. Please go upvote him as he truly deserves it!
This is documented as a known issue in .NET Framework 4.7.1.
As a workaround you can add these targets to your project. They will
remove the DesignFacadesToFilter from the list of references passed to
SGEN (and add them back once SGEN is done)
<Target Name="RemoveDesignTimeFacadesBeforeSGen" BeforeTargets="GenerateSerializationAssemblies">
<ItemGroup>
<DesignFacadesToFilter Include="System.IO.Compression.ZipFile" />
<_FilterOutFromReferencePath Include="@(_DesignTimeFacadeAssemblies_Names->'%(OriginalIdentity)')"
Condition="'@(DesignFacadesToFilter)' == '@(_DesignTimeFacadeAssemblies_Names)' and '%(Identity)' != ''" />
<ReferencePath Remove="@(_FilterOutFromReferencePath)" />
</ItemGroup>
<Message Importance="normal" Text="Removing DesignTimeFacades from ReferencePath before running SGen." /> </Target>
<Target Name="ReAddDesignTimeFacadesBeforeSGen" AfterTargets="GenerateSerializationAssemblies">
<ItemGroup>
<ReferencePath Include="@(_FilterOutFromReferencePath)" />
</ItemGroup>
<Message Importance="normal" Text="Adding back DesignTimeFacades from ReferencePath now that SGen has ran." />
</Target>
Another option (machine wide) is to add the following binding redirect
to sgen.exe.config:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.IO.Compression.ZipFile" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime> This will only work on machines with .NET Framework 4.7.1. installed. Once .NET Framework 4.7.2 is installed on that machine, this workaround should be removed.
How to call codeigniter controller function from view
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
What do >> and << mean in Python?
The other case involving print >>obj, "Hello World"
is the "print chevron" syntax for the print
statement in Python 2 (removed in Python 3, replaced by the file
argument of the print()
function). Instead of writing to standard output, the output is passed to the obj.write()
method. A typical example would be file objects having a write()
method. See the answer to a more recent question: Double greater-than sign in Python.
filedialog, tkinter and opening files
The exception you get is telling you filedialog
is not in your namespace.
filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
How to close a window using jQuery
You can only use the window.close
function when you have opened the window using window.open()
, so I use the following function:
function close_window(url){
var newWindow = window.open('', '_self', ''); //open the current window
window.close(url);
}