Check synchronously if file/directory exists in Node.js
The path
module does not provide a synchronous version of path.exists
so you have to trick around with the fs
module.
Fastest thing I can imagine is using fs.realpathSync
which will throw an error that you have to catch, so you need to make your own wrapper function with a try/catch.
Is there a vr (vertical rule) in html?
I find it easy to make an image of a line, and then insert it into the code as a "rule", setting the width and/or height as needed. These have all been horizontal-rule images, but there's nothing stopping me (or you) from using a "vertical-rule" image.
This is cool for many reasons; you can use different lines, colors, or patterns easily as "rules", and since they would have no text, even if you had done it the "normal" way using hr in HTML, it shouldn't impact SEO or other stuff like that. And the image file would/should be very tiny (1 or 2KB at most).
Odd behavior when Java converts int to byte?
here is a very mechanical method without the distracting theories:
- Convert the number into binary representation (use a calculator ok?)
- Only copy the rightmost 8 bits (LSB) and discard the rest.
- From the result of step#2, if the leftmost bit is 0, then use a calculator to convert the number to decimal. This is your answer.
- Else (if the leftmost bit is 1) your answer is negative. Leave all rightmost zeros and the first non-zero bit unchanged. And reversed the rest, that is, replace 1's by 0's and 0's by 1's. Then use a calculator to convert to decimal and append a negative sign to indicate the value is negative.
This more practical method is in accordance to the much theoretical answers above. So, those still reading those Java books saying to use modulo, this is definitely wrong since the 4 steps I outlined above is definitely not a modulo operation.
How to locate and insert a value in a text box (input) using Python Selenium?
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
Angularjs action on click of button
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
Read lines from a text file but skip the first two lines
That whole Open <file path> For Input As <some number>
thing is so 1990s. It's also slow and very error-prone.
In your VBA editor, Select References from the Tools menu and look for "Microsoft Scripting Runtime" (scrrun.dll) which should be available on pretty much any XP or Vista machine. It it's there, select it. Now you have access to a (to me at least) rather more robust solution:
With New Scripting.FileSystemObject
With .OpenTextFile(sFilename, ForReading)
If Not .AtEndOfStream Then .SkipLine
If Not .AtEndOfStream Then .SkipLine
Do Until .AtEndOfStream
DoSomethingImportantTo .ReadLine
Loop
End With
End With
Can one class extend two classes?
Also, instead of inner classes, you can use your 2 or more classes as fields.
For example:
Class Man{
private Phone ownPhone;
private DeviceInfo info;
//sets; gets
}
Class Phone{
private String phoneType;
private Long phoneNumber;
//sets; gets
}
Class DeviceInfo{
String phoneModel;
String cellPhoneOs;
String osVersion;
String phoneRam;
//sets; gets
}
So, here you have a man who can have some Phone with its number and type, also you have DeviceInfo for that Phone.
Also, it's possible is better to use DeviceInfo as a field into Phone class, like
class Phone {
DeviceInfo info;
String phoneNumber;
Stryng phoneType;
//sets; gets
}
NuGet auto package restore does not work with MSBuild
MSBuild 15 has a /t:restore option that does this. it comes with Visual Studio 2017.
If you want to use this, you also have to use the new PackageReference, which means replacing the packages.config
file with elements like this (do this in *.csproj):
<ItemGroup>
<!-- ... -->
<PackageReference Include="Contoso.Utility.UsefulStuff" Version="3.6.0" />
<!-- ... -->
</ItemGroup>
There is an automated migration to this format if you right click on 'References' (it might not show up if you just opened visual studio, rebuild or open up the 'Manage NuGet packages for solution' window and it will start appearing).
launch sms application with an intent
Use
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");
How many bytes in a JavaScript string?
UTF-8 encodes characters using 1 to 4 bytes per code point. As CMS pointed out in the accepted answer, JavaScript will store each character internally using 16 bits (2 bytes).
If you parse each character in the string via a loop and count the number of bytes used per code point, and then multiply the total count by 2, you should have JavaScript's memory usage in bytes for that UTF-8 encoded string. Perhaps something like this:
getStringMemorySize = function( _string ) {
"use strict";
var codePoint
, accum = 0
;
for( var stringIndex = 0, endOfString = _string.length; stringIndex < endOfString; stringIndex++ ) {
codePoint = _string.charCodeAt( stringIndex );
if( codePoint < 0x100 ) {
accum += 1;
continue;
}
if( codePoint < 0x10000 ) {
accum += 2;
continue;
}
if( codePoint < 0x1000000 ) {
accum += 3;
} else {
accum += 4;
}
}
return accum * 2;
}
Examples:
getStringMemorySize( 'I' ); // 2
getStringMemorySize( '?' ); // 4
getStringMemorySize( '' ); // 8
getStringMemorySize( 'I?' ); // 14
Bash if statement with multiple conditions throws an error
Please try following
if ([ $dateR -ge 234 ] && [ $dateR -lt 238 ]) || ([ $dateR -ge 834 ] && [ $dateR -lt 838 ]) || ([ $dateR -ge 1434 ] && [ $dateR -lt 1438 ]) || ([ $dateR -ge 2034 ] && [ $dateR -lt 2038 ]) ;
then
echo "WORKING"
else
echo "Out of range!"
Get next element in foreach loop
You could get the keys of the array before the foreach, then use a counter to check the next element, something like:
//$arr is the array you wish to cycle through
$keys = array_keys($arr);
$num_keys = count($keys);
$i = 1;
foreach ($arr as $a)
{
if ($i < $num_keys && $arr[$keys[$i]] == $a)
{
// we have a match
}
$i++;
}
This will work for both simple arrays, such as array(1,2,3)
, and keyed arrays such as array('first'=>1, 'second'=>2, 'thrid'=>3)
.
How can I get query string values in JavaScript?
ES2015 (ES6)
getQueryStringParams = query => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
};
Without jQuery
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
With an URL like ?topic=123&name=query+string
, the following will return:
qs["topic"]; // 123
qs["name"]; // query string
qs["nothere"]; // undefined (object)
Google method
Tearing Google's code I found the method they use: getUrlParameters
function (b) {
var c = typeof b === "undefined";
if (a !== h && c) return a;
for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
var l = b[f][p]("=");
if (l !== -1) {
var q = b[f][I](0, l),
l = b[f][I](l + 1),
l = l[Ca](/\+/g, " ");
try {
d[q] = e(l)
} catch (A) {}
}
}
c && (a = d);
return d
}
It is obfuscated, but it is understandable. It does not work because some variables are undefined.
They start to look for parameters on the url from ?
and also from the hash #
. Then for each parameter they split in the equal sign b[f][p]("=")
(which looks like indexOf
, they use the position of the char to get the key/value). Having it split they check whether the parameter has a value or not, if it has then they store the value of d
, otherwise they just continue.
In the end the object d
is returned, handling escaping and the +
sign. This object is just like mine, it has the same behavior.
My method as a jQuery plugin
(function($) {
$.QueryString = (function(paramsArray) {
let params = {};
for (let i = 0; i < paramsArray.length; ++i)
{
let param = paramsArray[i]
.split('=', 2);
if (param.length !== 2)
continue;
params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
}
return params;
})(window.location.search.substr(1).split('&'))
})(jQuery);
Usage
//Get a param
$.QueryString.param
//-or-
$.QueryString["param"]
//This outputs something like...
//"val"
//Get all params as object
$.QueryString
//This outputs something like...
//Object { param: "val", param2: "val" }
//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)
$.QueryString.param = "newvalue"
//This doesn't output anything, it just updates the $.QueryString object
//Convert object into string suitable for url a querystring (Requires jQuery)
$.param($.QueryString)
//This outputs something like...
//"param=newvalue¶m2=val"
//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
//-or-
history.pushState({}, '', "?" + $.param($.QueryString));
Preparation code: methods declaration
Split test code
var qs = window.GetQueryString(query);
var search = qs["q"];
var value = qs["value"];
var undef = qs["undefinedstring"];
Regex test code
var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");
Testing in Firefox 4.0 x86 on Windows Server 2008 R2 / 7 x64
- Split method: 144,780 ±2.17% fastest
- Regex method: 13,891 ±0.85% | 90% slower
How to decide when to use Node.js?
The most important reasons to start your next project using Node ...
- All the coolest dudes are into it ... so it must be fun.
- You can hangout at the cooler and have lots of Node adventures to brag about.
- You're a penny pincher when it comes to cloud hosting costs.
- Been there done that with Rails
- You hate IIS deployments
- Your old IT job is getting rather dull and you wish you were in a shiny new Start Up.
What to expect ...
- You'll feel safe and secure with Express without all the server bloatware you never needed.
- Runs like a rocket and scales well.
- You dream it. You installed it. The node package repo npmjs.org is the largest ecosystem of open source libraries in the world.
- Your brain will get time warped in the land of nested callbacks ...
- ... until you learn to keep your Promises.
- Sequelize and Passport are your new API friends.
- Debugging mostly async code will get umm ... interesting .
- Time for all Noders to master Typescript.
Who uses it?
- PayPal, Netflix, Walmart, LinkedIn, Groupon, Uber, GoDaddy, Dow Jones
- Here's why they switched to Node.
Using the Jersey client to do a POST operation
If you need to do a file upload, you'll need to use MediaType.MULTIPART_FORM_DATA_TYPE.
Looks like MultivaluedMap cannot be used with that so here's a solution with FormDataMultiPart.
InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);
FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
Test only if variable is not null in if statement
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
How to get whole and decimal part of a number?
Just a new simple solution, for those of you who want to get the Integer part and Decimal part splitted as two integer separated values:
5.25 -> Int part: 5; Decimal part: 25
$num = 5.25;
$int_part = intval($num);
$dec_part = $num * 100 % 100;
This way is not involving string based functions, and is preventing accuracy problems which may arise in other math operations (such as having 0.49999999999999 instead of 0.5).
Haven't tested thoroughly with extreme values, but it works fine for me for price calculations.
But, watch out! Now from -5.25 you get: Integer part: -5; Decimal part: -25
In case you want to get always positive numbers, simply add abs()
before the calculations:
$num = -5.25;
$num = abs($num);
$int_part = intval($num);
$dec_part = $num * 100 % 100;
Finally, bonus snippet for printing prices with 2 decimals:
$message = sprintf("Your price: %d.%02d Eur", $int_part, $dec_part);
...so that you avoid getting 5.5 instead of 5.05. ;)
How does the JPA @SequenceGenerator annotation work
Even though this question is very old and I stumbled upon it for my own issues with JPA 2.0 and Oracle sequences.
Want to share my research on some of the things -
Relationship between @SequenceGenerator(allocationSize) of GenerationType.SEQUENCE and INCREMENT BY in database sequence definition
Make sure @SequenceGenerator(allocationSize) is set to same value as INCREMENT BY in Database sequence definition to avoid problems (the same applies to the initial value).
For example, if we define the sequence in database with a INCREMENT BY value of 20, set the allocationsize in SequenceGenerator also to 20. In this case the JPA will not make a call to database until it reaches the next 20 mark while it increments each value by 1 internally. This saves database calls to get the next sequence number each time.
The side effect of this is - Whenever the application is redeployed or the server is restarted in between, it'll call database to get the next batch and you'll see jumps in the sequence values. Also we need to make sure the database definition and the application setting to be in-sync which may not be possible all the time as both of them are managed by different groups and you can quickly lose control of. If database value is less than the allocationsize, you'll see PrimaryKey constraint errors due to duplicate values of Id. If the database value is higher than the allocationsize, you'll see jumps in the values of Id.
If the database sequence INCREMENT BY is set to 1 (which is what DBAs generally do), set the allocationSize as also 1 so that they are in-sync but the JPA calls database to get next sequence number each time.
If you don't want the call to database each time, use GenerationType.IDENTITY strategy and have the @Id value set by database trigger. With GenerationType.IDENTITY as soon as we call em.persist the object is saved to DB and a value to id is assigned to the returned object so we don't have to do a em.merge or em.flush. (This may be JPA provider specific..Not sure)
Another important thing -
JPA 2.0 automatically runs ALTER SEQUENCE command to sync the allocationSize and INCREMENT BY in database sequence. As mostly we use a different Schema name(Application user name) rather than the actual Schema where the sequence exists and the application user name will not have ALTER SEQUENCE privileges, you might see the below warning in the logs -
000004c1 Runtime W CWWJP9991W: openjpa.Runtime: Warn: Unable
to cache sequence values for sequence "RECORD_ID_SEQ". Your
application does not have permission to run an ALTER SEQUENCE command.
Ensure that it has the appropriate permission to run an ALTER SEQUENCE
command.
As the JPA could not alter the sequence, JPA calls database everytime to get next sequence number irrespective of the value of @SequenceGenerator.allocationSize. This might be a unwanted consequence which we need to be aware of.
To let JPA not to run this command, set this value - in persistence.xml. This ensures that JPA will not try to run ALTER SEQUENCE command. It writes a different warning though -
00000094 Runtime W CWWJP9991W: openjpa.Runtime: Warn: The
property "openjpa.jdbc.DBDictionary=disableAlterSeqenceIncrementBy" is
set to true. This means that the 'ALTER SEQUENCE...INCREMENT BY' SQL
statement will not be executed for sequence "RECORD_ID_SEQ". OpenJPA
executes this command to ensure that the sequence's INCREMENT BY value
defined in the database matches the allocationSize which is defined in
the entity's sequence. With this SQL statement disabled, it is the
responsibility of the user to ensure that the entity's sequence
definition matches the sequence defined in the database.
As noted in the warning, important here is we need to make sure @SequenceGenerator.allocationSize and INCREMENT BY in database sequence definition are in sync including the default value of @SequenceGenerator(allocationSize) which is 50. Otherwise it'll cause errors.
Checking if a variable is an integer
In case you don't need to convert zero values, I find the methods to_i
and to_f
to be extremely useful since they will convert the string to either a zero value (if not convertible or zero) or the actual Integer
or Float
value.
"0014.56".to_i # => 14
"0014.56".to_f # => 14.56
"0.0".to_f # => 0.0
"not_an_int".to_f # 0
"not_a_float".to_f # 0.0
"0014.56".to_f ? "I'm a float" : "I'm not a float or the 0.0 float"
# => I'm a float
"not a float" ? "I'm a float" : "I'm not a float or the 0.0 float"
# => "I'm not a float or the 0.0 float"
EDIT2 : be careful, the 0
integer value is not falsey it's truthy (!!0 #=> true
) (thanks @prettycoder)
EDIT
Ah just found out about the dark cases... seems to only happen if the number is in first position though
"12blah".to_i => 12
File to import not found or unreadable: compass
Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.
Before you can do @import 'compass';
, you should:
Install Compass as a Ruby gem:
gem install compass
After that, you should use Compass's own command line tool to compile your SASS code:
cd path/to/your/project/
compass compile
Note that Compass reqiures a configuration file called config.rb
. You should create it for Compass to work.
The minimal config.rb
can be as simple as this:
css_dir = "css"
sass_dir = "sass"
And your SASS code should reside in sass/
.
Instead of creating a configuration file manually, you can create an empty Compass project with compass create <project-name>
and then copy your SASS code inside it.
Note that if you want to use Compass extensions, you will have to:
- require them from the
config.rb
;
- import them from your SASS file.
More info here: http://compass-style.org/help/
How to use sed to remove the last n lines of a file
To truncate very large files truly in-place we have truncate
command.
It doesn't know about lines, but tail
+ wc
can convert lines to bytes:
file=bigone.log
lines=3
truncate -s -$(tail -$lines $file | wc -c) $file
There is an obvious race condition if the file is written at the same time.
In this case it may be better to use head
- it counts bytes from the beginning of file (mind disk IO), so we will always truncate on line boundary (possibly more lines than expected if file is actively written):
truncate -s $(head -n -$lines $file | wc -c) $file
Handy one-liner if you fail login attempt putting password in place of username:
truncate -s $(head -n -5 /var/log/secure | wc -c) /var/log/secure
How do I correct the character encoding of a file?
If you see question marks in the file or if the accents are already lost, going back to utf8 will not help your cause. e.g. if café became cafe - changing encoding alone will not help (and you'll need original data).
Can you paste some text here, that'll help us answer for sure.
A url resource that is a dot (%2E)
It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of .
or ..
is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments .
and ..
”, without clarifying whether they match .
and ..
before or after pct-encoding.
Personally I find Firefox's interpretation that %2E
does not mean .
most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only .
or ..
.
I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F
, %00
and %5C
sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.
Routing HTTP Error 404.0 0x80070002
Just found that lines below must be added to web.config
file, now everything works fine on production server too.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>
</system.webServer>
<xsl:variable> Print out value of XSL variable using <xsl:value-of>
Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:
<xsl:template match="class">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
subexists: <xsl:value-of select="$subexists" />
</xsl:template>
And if you need the variable to have "global" scope then declare it outside of the template:
<xsl:variable name="subexists">
<xsl:choose>
<xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
<xsl:otherwise>false</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:template match="class">
subexists: <xsl:value-of select="$subexists" />
</xsl:template>
How do I block or restrict special characters from input fields with jquery?
just the numbers:
$('input.time').keydown(function(e) { if(e.keyCode>=48 &&
e.keyCode<=57) {
return true; } else {
return false; } });
or for time including ":"
$('input.time').keydown(function(e) { if(e.keyCode>=48 &&
e.keyCode<=58) {
return true; } else {
return false; } });
also including delete and backspace:
$('input.time').keydown(function(e) { if((e.keyCode>=46 &&
e.keyCode<=58) || e.keyCode==8) { return true; } else {
return false; } });
unfortuneatly not getting it to work on a iMAC
How to put comments in Django templates
This way can be helpful if you want to comment some Django Template format Code.
{#% include 'file.html' %#}
(Right Way)
Following code still executes if commented with HTML Comment.
<!-- {% include 'file.html' %} -->
(Wrong Way)
The result of a query cannot be enumerated more than once
if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this
ex:-
repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();
try like this
C++ template constructor
template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;
the above helpers let you work with types as values.
class A {
template<class T>
A( tag<T> );
};
the tag<T>
type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:
auto a = A(tag<int>{});
You can pass in more than one type:
class A {
template<class T, class U, class V>
A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});
PHP Email sending BCC
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
How to read a .xlsx file using the pandas Library in iPython?
I usually create a dictionary containing a DataFrame
for every sheet:
xl_file = pd.ExcelFile(file_name)
dfs = {sheet_name: xl_file.parse(sheet_name)
for sheet_name in xl_file.sheet_names}
Update: In pandas version 0.21.0+ you will get this behavior more cleanly by passing sheet_name=None
to read_excel
:
dfs = pd.read_excel(file_name, sheet_name=None)
In 0.20 and prior, this was sheetname
rather than sheet_name
(this is now deprecated in favor of the above):
dfs = pd.read_excel(file_name, sheetname=None)
Are global variables bad?
My professor used to say something like: using global variables are okay if you use them correctly. I don't think I ever got good at using them correctly, so I rarely used them at all.
How to convert interface{} to string?
To expand on what Peter said:
Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.
Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.
How to Get JSON Array Within JSON Object?
JSONObject jsonObject =new JSONObject(jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length;i++){
JSONObject json = jsonArray.getJSONObject(i);
String id = json.getString("id");
String name=json.getString("name");
JSONArray ingArray = json.getJSONArray("Ingredients") // here you are going to get ingredients
for(int j=0;j<ingArray.length;j++){
JSONObject ingredObject= ingArray.getJSONObject(j);
String ingName = ingredObject.getString("name");//so you are going to get ingredient name
Log.e("name",ingName); // you will get
}
}
Javascript how to split newline
Try initializing the ks
variable inside your submit function.
(function($){
$(document).ready(function(){
$('#data').submit(function(e){
var ks = $('#keywords').val().split("\n");
e.preventDefault();
alert(ks[0]);
$.each(ks, function(k){
alert(k);
});
});
});
})(jQuery);
How to push JSON object in to array using javascript
can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data
var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
console.log("\n The details of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);
my_json = feed;
console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
data.push(my_json);
});
How to check SQL Server version
Following are possible ways to see the version:
Method 1: Connect to the instance of SQL Server, and then run the following query:
Select @@version
An example of the output of this query is as follows:
Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009
10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Express
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )
Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.
Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG
and ERRORLOG.n
files. The entries may resemble the following:
2011-03-27 22:31:33.50 Server Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )
As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.
Method 4: Connect to the instance of SQL Server, and then run the following query:
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
Note This query works with any instance of SQL Server 2000 or of a later version
JSON date to Java date?
Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).
So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
produces a format that can parse both "2013-03-11T01:38:18.309Z"
and "2013-03-11T01:38:18.309+0000"
and will give you the same result.
Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.
I actually have more trouble on the JavaScript side to deal with both formats.
HTTP 415 unsupported media type error when calling Web API 2 endpoint
SOLVED
After banging my head on the wall for a couple days with this issue, it was looking like the problem had something to do with the content type negotiation between the client and server. I dug deeper into that using Fiddler to check the request details coming from the client app, here's a screenshot of the raw request as captured by fiddler:
What's obviously missing there is the Content-Type
header, even though I was setting it as seen in the code sample in my original post. I thought it was strange that the Content-Type
never came through even though I was setting it, so I had another look at my other (working) code calling a different Web API service, the only difference was that I happened to be setting the req.ContentType
property prior to writing to the request body in that case. I made that change to this new code and that did it, the Content-Type
was now showing up and I got the expected success response from the web service. The new code from my .NET client now looks like this:
req.Method = "POST"
req.ContentType = "application/json"
lstrPagingJSON = JsonSerializer(Of Paging)(lPaging)
bytData = Encoding.UTF8.GetBytes(lstrPagingJSON)
req.ContentLength = bytData.Length
reqStream = req.GetRequestStream()
reqStream.Write(bytData, 0, bytData.Length)
reqStream.Close()
'// Content-Type was being set here, causing the problem
'req.ContentType = "application/json"
That's all it was, the ContentType
property just needed to be set prior to writing to the request body
I believe this behavior is because once content is written to the body it is streamed to the service endpoint being called, any other attributes pertaining to the request need to be set prior to that. Please correct me if I'm wrong or if this needs more detail.
Cannot ping AWS EC2 instance
I will like to mention some rare ISP induced problems. Occasionally following happends to me with BSNL. its one of those wierd problems that takes hours out of your daily life. In such case one might raise the issue with ISP or change ISP.
- Amazon instance can be accessed from browser (all open ports)
- Same cannot be pinged from console
- ssh / telnet doesnot works either.
Avoiding "resource is out of sync with the filesystem"
I was not able to resolve this error by either refresh or by turning on "native polling" workspace feature. Turned out my project was also opened in two instances of eclipse. Once I closed the other instance, the error went away. So make sure your project is only opened at one place if you are seeing this error.
How to create a new database after initally installing oracle database 11g Express Edition?
"How do I create an initial database ?"
You created a database when you installed XE. At some point the installation process prompted you to enter a password for the SYSTEM account. Use that to connect to the XE database using the SQL commandline on the application menu.
The XE documentation is online and pretty helpful. Find it here.
It's worth mentioning that 11g XE has several limitations, one of which is only one database per server. So using the pre-installed database is the sensible option.
(HTML) Download a PDF file instead of opening them in browser when clicked
Without html5 attribute one can achieve this by using php:
Create php file named download.php with this code:
<?php
ob_start();
$file = "yourPDF.pdf"
if (file_exists($file))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit();
}
Now if you want to automatically start downloading pdf write this javascript:
<script>window.location = "download.php";</script>
If you want this to work on a link, use this...
<a href='javascript:window.location = "download.php"'>
Download it!
</a>
Word count from a txt file program
If you are using graphLab, you can use this function. It is really powerfull
products['word_count'] = graphlab.text_analytics.count_words(your_text)
How to implode array with key and value without foreach in PHP
For create mysql where conditions from array
$sWheres = array('item1' => 'object1',
'item2' => 'object2',
'item3' => 1,
'item4' => array(4,5),
'item5' => array('object3','object4'));
$sWhere = '';
if(!empty($sWheres)){
$sWhereConditions = array();
foreach ($sWheres as $key => $value){
if(!empty($value)){
if(is_array($value)){
$value = array_filter($value); // For remove blank values from array
if(!empty($value)){
array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'
$sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));
}
}else{
$sWhereConditions[] = sprintf("%s='%s'", $key, $value);
}
}
}
if(!empty($sWhereConditions)){
$sWhere .= "(".implode(' AND ', $sWhereConditions).")";
}
}
echo $sWhere; // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))
How to unmount a busy device
Check for exported NFS file systems with exportfs -v. If found, remove with exportfs -d share:/directory. These don't show up in the fuser/lsof listing, and can prevent umount from succeeding.
Child inside parent with min-height: 100% not inheriting height
The best way to achieve this nowadays is to use display: flex;
. However you might run into an issue when trying to support IE11. According to https://caniuse.com using flexbox :
IE 11 does not vertically align items correctly when min-height is used
Internet Explorer compatible solution
The solution is to use display: table;
on the parent and display: table-row;
on the child both with height: 100%;
as a replacement for min-height: 100%;
.
Most of the solutions listed here use display:
table
, table-row
and/or table-cell
, but they don't replicate the same behaviour as min-height: 100%;
, which is:
- Inherit the computed height of the parent (as opposed to inheriting its
height
property);
- Allow the parent's height to exceed its
min-height
;
While using this solution, the behaviour is the same and the property min-height
is not needed which allows to get around the bug.
Explanation
The reason why it works is because, unlike most elements, elements using display:
table
and table-row
will always be as tall as their content. This makes their height
property behave similarly to min-height
.
Solution in action
_x000D_
_x000D_
html, body {_x000D_
height: 100px;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
#containment {_x000D_
display: table;_x000D_
height: 100%;_x000D_
background: pink;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#containment-shadow-left {_x000D_
display: table-row;_x000D_
height: 100%;_x000D_
background: aqua;_x000D_
}_x000D_
_x000D_
#content {_x000D_
padding: 15px;_x000D_
}_x000D_
_x000D_
#demo {_x000D_
display: none;_x000D_
background-color: red;_x000D_
height: 200px;_x000D_
}_x000D_
_x000D_
#demo-checkbox:checked ~ #demo {_x000D_
display: block;_x000D_
}
_x000D_
<div id="containment">_x000D_
<div id="containment-shadow-left">_x000D_
<div id="content">_x000D_
<input id="demo-checkbox" type="checkbox">_x000D_
<label for="demo-checkbox">Click here for overflow demo</label>_x000D_
<div id="demo">This is taller than #containment</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
JSON: why are forward slashes escaped?
PHP escapes forward slashes by default which is probably why this appears so commonly. I'm not sure why, but possibly because embedding the string "</script>"
inside a <script>
tag is considered unsafe.
This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES
flag but most developers will not use this since the original result is already valid JSON.
Adding a newline into a string in C#
as others have said new line char will give you a new line in a text file in windows.
try the following:
using System;
using System.IO;
static class Program
{
static void Main()
{
WriteToFile
(
@"C:\test.txt",
"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@",
"@"
);
/*
output in test.txt in windows =
fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
*/
}
public static void WriteToFile(string filename, string text, string newLineDelim)
{
bool equal = Environment.NewLine == "\r\n";
//Environment.NewLine == \r\n = True
Console.WriteLine("Environment.NewLine == \\r\\n = {0}", equal);
//replace newLineDelim with newLineDelim + a new line
//trim to get rid of any new lines chars at the end of the file
string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();
using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))
{
sw.Write(filetext);
}
}
}
DataTable: How to get item value with row name and column name? (VB)
For i = 0 To dt.Rows.Count - 1
ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)
Next
How to call a vue.js function on page load
You need to do something like this (If you want to call the method on page load):
new Vue({
// ...
methods:{
getUnits: function() {...}
},
created: function(){
this.getUnits()
}
});
Calling remove in foreach loop in Java
- Try this 2. and change the condition to "WINTER" and you will wonder:
public static void main(String[] args) {
Season.add("Frühling");
Season.add("Sommer");
Season.add("Herbst");
Season.add("WINTER");
for (String s : Season) {
if(!s.equals("Sommer")) {
System.out.println(s);
continue;
}
Season.remove("Frühling");
}
}
What is the difference between using constructor vs getInitialState in React / React Native?
These days we don't have to call the constructor inside the component - we can directly call state={something:""}
, otherwise previously first we have do declare constructor with super()
to inherit every thing from React.Component
class
then inside constructor we initialize our state.
If using React.createClass
then define initialize state with the getInitialState
method.
Fixed header, footer with scrollable content
It works fine for me using a CSS grid. Initially fix the container and then give overflow-y: auto;
for the centre content which has to get scrolled i.e other than header and footer.
_x000D_
_x000D_
.container{
height: 100%;
left: 0;
position: fixed;
top: 0;
width: 100%;
display: grid;
grid-template-rows: 5em auto 3em;
}
header{
grid-row: 1;
background-color: rgb(148, 142, 142);
justify-self: center;
align-self: center;
width: 100%;
}
.body{
grid-row: 2;
overflow-y: auto;
}
footer{
grid-row: 3;
background: rgb(110, 112, 112);
}
_x000D_
<div class="container">
<header><h1>Header</h1></header>
<div class="body">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<footer><h3>Footer</h3></footer>
</div>
_x000D_
_x000D_
_x000D_
Deserializing JSON Object Array with Json.net
Slight modification to what was stated above. My Json format, which validates was
{
mycollection:{[
{
property0:value,
property1:value,
},
{
property0:value,
property1:value,
}
]
}
}
Using AlexDev's response, I did this Looping each child, creating reader from it
public partial class myModel
{
public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}
public class myModelList {
[JsonConverter(typeof(myModelConverter))]
public List<myModel> model { get; set; }
}
class myModelConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Children()) //mod here
{
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(child.CreateReader(), newObject); //mod here
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
How to create a pivot query in sql server without aggregate function
Check this out as well: using xml path
and pivot
SQLFIDDLE DEMO
| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
| Asset | 205 | 142 | 421 |
| Equity | 365 | 214 | 163 |
| Profit | 524 | 421 | 325 |
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period)
FROM demo c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT account, ' + @cols + ' from
(
select account
, value
, period
from demo
) x
pivot
(
max(value)
for period in (' + @cols + ')
) p '
execute(@query)
Managing large binary files with Git
I would use submodules (as Pat Notz) or two distinct repositories. If you modify your binary files too often, then I would try to minimize the impact of the huge repository cleaning the history:
I had a very similar problem several months ago: ~21 GB of MP3 files, unclassified (bad names, bad id3's, don't know if I like that MP3 file or not...), and replicated on three computers.
I used an external hard disk drive with the main Git repository, and I cloned it into each computer. Then, I started to classify them in the habitual way (pushing, pulling, merging... deleting and renaming many times).
At the end, I had only ~6 GB of MP3 files and ~83 GB in the .git directory. I used git-write-tree
and git-commit-tree
to create a new commit, without commit ancestors, and started a new branch pointing to that commit. The "git log" for that branch only showed one commit.
Then, I deleted the old branch, kept only the new branch, deleted the ref-logs, and run "git prune": after that, my .git folders weighted only ~6 GB...
You could "purge" the huge repository from time to time in the same way: Your "git clone"'s will be faster.
Excel VBA - select a dynamic cell range
So it depends on how you want to pick the incrementer, but this should work:
Range("A1:" & Cells(1, i).Address).Select
Where i
is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)
If you want the beginning to be dynamic as well, you can try this:
Sub SelectCols()
Dim Col1 As Integer
Dim Col2 As Integer
Col1 = 2
Col2 = 4
Range(Cells(1, Col1), Cells(1, Col2)).Select
End Sub
How to use the ConfigurationManager.AppSettings
Your web.config
file should have this structure:
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="..." />
</connectionStrings>
</configuration>
Then, to create a SQL connection using the connection string named MyConnectionString
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
If you'd prefer to keep your connection strings in the AppSettings
section of your configuration file, it would look like this:
<configuration>
<appSettings>
<add key="MyConnectionString" value="..." />
</appSettings>
</configuration>
And then your SqlConnection constructor would look like this:
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);
Removing MySQL 5.7 Completely
You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo rm -rf /var/lib/mysql
I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!
Easy way to test an LDAP User's Credentials
ldapwhoami -vvv -h <hostname> -p <port> -D <binddn> -x -w <passwd>
, where binddn
is the DN of the person whose credentials you are authenticating.
On success (i.e., valid credentials), you get Result: Success (0)
. On failure, you get ldap_bind: Invalid credentials (49)
.
Search text in fields in every table of a MySQL database
Here is my solution for this
DROP PROCEDURE IF EXISTS findAll;
CREATE PROCEDURE `findAll`( IN `tableName` VARCHAR( 28 ) , IN `search` TEXT )
BEGIN
DECLARE finished INT DEFAULT FALSE ;
DECLARE columnName VARCHAR ( 28 ) ;
DECLARE stmtFields TEXT ;
DECLARE columnNames CURSOR FOR
SELECT DISTINCT `COLUMN_NAME` FROM `information_schema`.`COLUMNS`
WHERE `TABLE_NAME` = tableName ORDER BY `ORDINAL_POSITION` ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = TRUE;
SET stmtFields = '' ;
OPEN columnNames ;
readColumns: LOOP
FETCH columnNames INTO columnName ;
IF finished THEN
LEAVE readColumns ;
END IF;
SET stmtFields = CONCAT(
stmtFields , IF ( LENGTH( stmtFields ) > 0 , ' OR' , '' ) ,
' `', tableName ,'`.`' , columnName , '` REGEXP "' , search , '"'
) ;
END LOOP;
SET @stmtQuery := CONCAT ( 'SELECT * FROM `' , tableName , '` WHERE ' , stmtFields ) ;
PREPARE stmt FROM @stmtQuery ;
EXECUTE stmt ;
CLOSE columnNames ;
END;
Smart way to truncate long strings
I like using .slice() The first argument is the starting index and the second is the ending index. Everything in between is what you get back.
var long = "hello there! Good day to ya."
// hello there! Good day to ya.
var short = long.slice(0, 5)
// hello
How to set border on jPanel?
JPanel jPanel = new JPanel();
jPanel.setBorder(BorderFactory.createLineBorder(Color.black));
Here not only jPanel, you can add border to any Jcomponent
SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application
First off: My problem isn't the exact same as yours, but this post is the first thing that comes up in google for the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error at the time I wrote this. The solution may be useful to people searching for this error as I did not find this specific solution anywhere online.
In my case, I used Xampp/Apache and PHP sqlsrv to try to connect to an MSSQL database using Windows Authentication and received the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error you described. I finally found the problem to be the Apache service itself running under the user "LOCAL SERVICE" instead of the user account I was logged in as. In other words, it literally was using an anonymous account. The solution was to go into services.msc, right click the Apache service, go to Properties, go to the Log On tab, and enter the credentials for the user. This falls in line with your problem related to SPN's as your SPN's are set up to run from a specific user on the domain. So if the correct SPN is not running, windows authentication will default to the wrong user (likely the "LOCAL SERVICE" user) and give you the Anonymous error.
Here's where it's different from your problem. None of the computers on the local network are on a Domain, they are only on a Workgroup. To use Windows Authentication with a Workgroup, both the computer with the server (in my case MSSQL Server) and the computer with the service requesting data (in my case Apache) needed to have a user with an identical name and identical password.
To summarize, The Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
error in both our cases seems to be caused by a service not running and/or not on the right user. Ensuring the right SPN or other Service is running and under the correct user should solve the anonymous part of the problem.
How do I call ::CreateProcess in c++ to launch a Windows executable?
Something like this:
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
500.21 Bad module "ManagedPipelineHandler" in its module list
I discovered that the order of adding roles and features is important.
On a fresh system I activate the role "application server" and there check explicitly .net, web server support and finally process activation service
Then automatically a dialogue comes up that the role "Web server" needs to be added also.
Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server
Supported by SQL Server 2005 and later versions
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)
+ ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
* See Microsoft's documentation to understand what the 101
and 108
style codes above mean.
Supported by SQL Server 2012 and later versions
SELECT FORMAT(GETDATE() , 'MM/dd/yyyy HH:mm:ss')
Result
Both of the above methods will return:
10/16/2013 17:00:20
How to delete a folder in C++?
void remove_dir(char *path)
{
struct dirent *entry = NULL;
DIR *dir = NULL;
dir = opendir(path);
while(entry = readdir(dir))
{
DIR *sub_dir = NULL;
FILE *file = NULL;
char abs_path[100] = {0};
if(*(entry->d_name) != '.')
{
sprintf(abs_path, "%s/%s", path, entry->d_name);
if(sub_dir = opendir(abs_path))
{
closedir(sub_dir);
remove_dir(abs_path);
}
else
{
if(file = fopen(abs_path, "r"))
{
fclose(file);
remove(abs_path);
}
}
}
}
remove(path);
}
How to slice an array in Bash
See the Parameter Expansion section in the Bash man
page. A[@]
returns the contents of the array, :1:2
takes a slice of length 2, starting at index 1.
A=( foo bar "a b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}") # slice to the end of the array
echo "${B[@]}" # bar a b c
echo "${B[1]}" # a b c
echo "${C[@]}" # bar a b c 42
echo "${C[@]: -2:2}" # a b c 42 # The space before the - is necesssary
Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.
ansible: lineinfile for several lines?
It's not ideal, but you're allowed multiple calls to lineinfile
. Using that with insert_after
, you can get the result you want:
- name: Set first line at EOF (1/3)
lineinfile: dest=/path/to/file regexp="^string 1" line="string 1"
- name: Set second line after first (2/3)
lineinfile: dest=/path/to/file regexp="^string 2" line="string 2" insertafter="^string 1"
- name: Set third line after second (3/3)
lineinfile: dest=/path/to/file regexp="^string 3" line="string 3" insertafter="^string 2"
Random number generator only generating one random number
There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.
public String GenerateRandom(Random oRandom, int iLongitudPin)
{
String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
int iLength = sCharacters.Length;
char cCharacter;
int iLongitudNuevaCadena = iLongitudPin;
String sRandomResult = "";
for (int i = 0; i < iLongitudNuevaCadena; i++)
{
cCharacter = sCharacters[oRandom.Next(iLength)];
sRandomResult += cCharacter.ToString();
}
return (sRandomResult);
}
How to select label for="XYZ" in CSS?
If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:
itemSelected(id: number){
console.log('label contains', document.querySelector("label[for='" + id + "']"));
}
Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array
Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0
) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE
).
Since your integer array cannot contain a value larger than Integer.MAX_VALUE
and smaller than Integer.MIN_VALUE
your code works across all edge cases.
Can we use JSch for SSH key-based communication?
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
Set HTML element's style property in javascript
For me, this works:
function transferAllStyles(elemFrom, elemTo)
{
var prop;
for (prop in elemFrom.style)
if (typeof prop == "string")
try { elemTo.style[prop] = elemFrom.style[prop]; }
catch (ex) { /* don't care */ }
}
Get PHP class property by string
What you're asking about is called Variable Variables. All you need to do is store your string in a variable and access it like so:
$Class = 'MyCustomClass';
$Property = 'Name';
$List = array('Name');
$Object = new $Class();
// All of these will echo the same property
echo $Object->$Property; // Evaluates to $Object->Name
echo $Object->{$List[0]}; // Use if your variable is in an array
.NET HashTable Vs Dictionary - Can the Dictionary be as fast?
Differences between Hashtable and Dictionary
Dictionary:
- Dictionary returns error if we try to find a key which does not exist.
- Dictionary faster than a Hashtable because there is no boxing and unboxing.
- Dictionary is a generic type which means we can use it with any data type.
Hashtable:
- Hashtable returns null if we try to find a key which does not exist.
- Hashtable slower than dictionary because it requires boxing and unboxing.
- Hashtable is not a generic type,
Setting the number of map tasks and reduce tasks
The number of map tasks for a given job is driven by the number of input splits and not by the mapred.map.tasks parameter. For each input split a map task is spawned. So, over the lifetime of a mapreduce job the number of map tasks is equal to the number of input splits. mapred.map.tasks is just a hint to the InputFormat for the number of maps.
In your example Hadoop has determined there are 24 input splits and will spawn 24 map tasks in total. But, you can control how many map tasks can be executed in parallel by each of the task tracker.
Also, removing a space after -D might solve the problem for reduce.
For more information on the number of map and reduce tasks, please look at the below url
https://cwiki.apache.org/confluence/display/HADOOP2/HowManyMapsAndReduces
Is it safe to clean docker/overlay2/
I used "docker system prune -a" it cleaned all files under volumes and overlay2
[root@jasontest volumes]# docker system prune -a
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all images without at least one container associated to them
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Images:
untagged: ubuntu:12.04
untagged: ubuntu@sha256:18305429afa14ea462f810146ba44d4363ae76e4c8dfc38288cf73aa07485005
deleted: sha256:5b117edd0b767986092e9f721ba2364951b0a271f53f1f41aff9dd1861c2d4fe
deleted: sha256:8c7f3d7534c80107e3a4155989c3be30b431624c61973d142822b12b0001ece8
deleted: sha256:969d5a4e73ab4e4b89222136eeef2b09e711653b38266ef99d4e7a1f6ea984f4
deleted: sha256:871522beabc173098da87018264cf3e63481628c5080bd728b90f268793d9840
deleted: sha256:f13e8e542cae571644e2f4af25668fadfe094c0854176a725ebf4fdec7dae981
deleted: sha256:58bcc73dcf4050a4955916a0dcb7e5f9c331bf547d31e22052f1b5fa16cf63f8
untagged: osixia/openldap:1.2.1
untagged: osixia/openldap@sha256:6ceb347feb37d421fcabd80f73e3dc6578022d59220cab717172ea69c38582ec
deleted: sha256:a562f6fd60c7ef2adbea30d6271af8058c859804b2f36c270055344739c06d64
deleted: sha256:90efa8a88d923fb1723bea8f1082d4741b588f7fbcf3359f38e8583efa53827d
deleted: sha256:8d77930b93c88d2cdfdab0880f3f0b6b8be191c23b04c61fa1a6960cbeef3fe6
deleted: sha256:dd9f76264bf3efd36f11c6231a0e1801c80d6b4ca698cd6fa2ff66dbd44c3683
deleted: sha256:00efc4fb5e8a8e3ce0cb0047e4c697646c88b68388221a6bd7aa697529267554
deleted: sha256:e64e6259fd63679a3b9ac25728f250c3afe49dbe457a1a80550b7f1ccf68458a
deleted: sha256:da7d34d626d2758a01afe816a9434e85dffbafbd96eb04b62ec69029dae9665d
deleted: sha256:b132dace06fa7e22346de5ca1ae0c2bf9acfb49fe9dbec4290a127b80380fe5a
deleted: sha256:d626a8ad97a1f9c1f2c4db3814751ada64f60aed927764a3f994fcd88363b659
untagged: centos:centos7
untagged: centos@sha256:2671f7a3eea36ce43609e9fe7435ade83094291055f1c96d9d1d1d7c0b986a5d
deleted: sha256:ff426288ea903fcf8d91aca97460c613348f7a27195606b45f19ae91776ca23d
deleted: sha256:e15afa4858b655f8a5da4c4a41e05b908229f6fab8543434db79207478511ff7
Total reclaimed space: 533.3MB
[root@jasontest volumes]# ls -alth
total 32K
-rw------- 1 root root 32K May 23 21:14 metadata.db
drwx------ 2 root root 4.0K May 23 21:14 .
drwx--x--x 14 root root 4.0K May 21 20:26 ..
Android Canvas.drawText
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
Difference between getAttribute() and getParameter()
It is crucial to know that attributes are not parameters.
The return type for attributes is an Object, whereas the return type for a parameter is a String. When calling the getAttribute(String name)
method, bear in mind that the attributes must be cast.
Additionally, there is no servlet specific attributes, and there are no session parameters.
This post is written with the purpose to connect on @Bozho's response, as additional information that can be useful for other people.
How to use timeit module
If you want to compare two blocks of code / functions quickly you could do:
import timeit
start_time = timeit.default_timer()
func1()
print(timeit.default_timer() - start_time)
start_time = timeit.default_timer()
func2()
print(timeit.default_timer() - start_time)
Watermark / hint text / placeholder TextBox
I decided to solve this via a Behavior. It uses a Hint
property to define the text to display (could also be an object, if you prefer) and a Value
property to evaluate wether the hint should be visible or not.
The Behavior is declared as follows:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
using System.Windows.Media;
public class HintBehavior : Behavior<ContentControl>
{
public static readonly DependencyProperty HintProperty = DependencyProperty
.Register("Hint", typeof (string), typeof (HintBehavior)
//, new FrameworkPropertyMetadata(null, OnHintChanged)
);
public string Hint
{
get { return (string) GetValue(HintProperty); }
set { SetValue(HintProperty, value); }
}
public static readonly DependencyProperty ValueProperty = DependencyProperty
.Register("Value", typeof (object), typeof (HintBehavior)
, new FrameworkPropertyMetadata(null, OnValueChanged));
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var visible = e.NewValue == null;
d.SetValue(VisibilityProperty, visible ? Visibility.Visible : Visibility.Collapsed);
}
public object Value
{
get { return GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty VisibilityProperty = DependencyProperty
.Register("Visibility", typeof (Visibility), typeof (HintBehavior)
, new FrameworkPropertyMetadata(Visibility.Visible
//, new PropertyChangedCallback(OnVisibilityChanged)
));
public Visibility Visibility
{
get { return (Visibility) GetValue(VisibilityProperty); }
set { SetValue(VisibilityProperty, value); }
}
public static readonly DependencyProperty ForegroundProperty = DependencyProperty
.Register("Foreground", typeof (Brush), typeof (HintBehavior)
, new FrameworkPropertyMetadata(new SolidColorBrush(Colors.DarkGray)
//, new PropertyChangedCallback(OnForegroundChanged)
));
public Brush Foreground
{
get { return (Brush) GetValue(ForegroundProperty); }
set { SetValue(ForegroundProperty, value); }
}
public static readonly DependencyProperty MarginProperty = DependencyProperty
.Register("Margin", typeof (Thickness), typeof (HintBehavior)
, new FrameworkPropertyMetadata(new Thickness(4, 5, 0, 0)
//, new PropertyChangedCallback(OnMarginChanged)
));
public Thickness Margin
{
get { return (Thickness) GetValue(MarginProperty); }
set { SetValue(MarginProperty, value); }
}
private static ResourceDictionary _hintBehaviorResources;
public static ResourceDictionary HintBehaviorResources
{
get
{
if (_hintBehaviorResources == null)
{
var res = new ResourceDictionary
{
Source = new Uri("/Mayflower.Client.Core;component/Behaviors/HintBehaviorResources.xaml",
UriKind.RelativeOrAbsolute)
};
_hintBehaviorResources = res;
}
return _hintBehaviorResources;
}
}
protected override void OnAttached()
{
base.OnAttached();
var t = (ControlTemplate) HintBehaviorResources["HintBehaviorWrapper"];
AssociatedObject.Template = t;
AssociatedObject.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
AssociatedObject.Loaded -= OnLoaded;
var label = (Label) AssociatedObject.Template.FindName("PART_HintLabel", AssociatedObject);
label.DataContext = this;
//label.Content = "Hello...";
label.SetBinding(UIElement.VisibilityProperty, new Binding("Visibility") {Source = this, Mode = BindingMode.OneWay});
label.SetBinding(ContentControl.ContentProperty, new Binding("Hint") {Source = this, Mode = BindingMode.OneWay});
label.SetBinding(Control.ForegroundProperty, new Binding("Foreground") {Source = this, Mode = BindingMode.OneWay});
label.SetBinding(FrameworkElement.MarginProperty, new Binding("Margin") {Source = this, Mode = BindingMode.OneWay});
}
}
It wraps the target with it's own template, adding to it a label:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ControlTemplate x:Key="HintBehaviorWrapper" TargetType="{x:Type ContentControl}">
<Grid>
<ContentPresenter Content="{TemplateBinding Content}" />
<Label x:Name="PART_HintLabel" IsHitTestVisible="False" Padding="0" />
</Grid>
</ControlTemplate>
</ResourceDictionary>
To use it, just add it as a behavior and bind your values (in my case I add it in a ControlTemplate, hence the binding):
<ContentControl>
<i:Interaction.Behaviors>
<behaviors:HintBehavior Value="{Binding Property, RelativeSource={RelativeSource TemplatedParent}}"
Hint="{Binding Hint, RelativeSource={RelativeSource TemplatedParent}}" />
</i:Interaction.Behaviors>
<TextBox ... />
</ContentControl>
I would love feedback if this is considered a clean solution. It does not require static dictionaries and hence has no memory leak.
Invoke or BeginInvoke cannot be called on a control until the window handle has been created
It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:
This means that InvokeRequired can
return false if Invoke is not required
(the call occurs on the same thread),
or if the control was created on a
different thread but the control's
handle has not yet been created.
In the case where the control's handle
has not yet been created, you should
not simply call properties, methods,
or events on the control. This might
cause the control's handle to be
created on the background thread,
isolating the control on a thread
without a message pump and making the
application unstable.
You can protect against this case by
also checking the value of
IsHandleCreated when InvokeRequired
returns false on a background thread.
If the control handle has not yet been
created, you must wait until it has
been created before calling Invoke or
BeginInvoke. Typically, this happens
only if a background thread is created
in the constructor of the primary form
for the application (as in
Application.Run(new MainForm()),
before the form has been shown or
Application.Run has been called.
Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)
Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:
public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
if (uiElement == null)
{
throw new ArgumentNullException("uiElement");
}
if (uiElement.InvokeRequired)
{
if (forceSynchronous)
{
uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
}
else
{
uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
}
}
else
{
if (uiElement.IsDisposed)
{
throw new ObjectDisposedException("Control is already disposed.");
}
updater();
}
}
Consider the case where we're calling SafeInvoke
from the non-gui thread for a control whose handle has not been created.
uiElement
is not null, so we check uiElement.InvokeRequired
. Per the MSDN docs (bolded) InvokeRequired
will return false
because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else
condition where we check IsDisposed
or immediately proceed to call the submitted action... from the background thread!
At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?
JAX-WS - Adding SOAP Headers
Adding an object to header we use the examples used here,yet i will complete
ObjectFactory objectFactory = new ObjectFactory();
CabeceraCR cabeceraCR =objectFactory.createCabeceraCR();
cabeceraCR.setUsuario("xxxxx");
cabeceraCR.setClave("xxxxx");
With object factory we create the object asked to pass on the header. The to add to the header
WSBindingProvider bp = (WSBindingProvider)wsXXXXXXSoap;
bp.setOutboundHeaders(
// Sets a simple string value as a header
Headers.create(jaxbContext,objectFactory.createCabeceraCR(cabeceraCR))
);
We used the WSBindingProvider to add the header. The object will have some error if used directly so we use the method
objectFactory.createCabeceraCR(cabeceraCR)
This method will create a JAXBElement like this on the object Factory
@XmlElementDecl(namespace = "http://www.creditreport.ec/", name = "CabeceraCR")
public JAXBElement<CabeceraCR> createCabeceraCR(CabeceraCR value) {
return new JAXBElement<CabeceraCR>(_CabeceraCR_QNAME, CabeceraCR.class, null, value);
}
And the jaxbContext we obtained like this:
jaxbContext = (JAXBRIContext) JAXBContext.newInstance(CabeceraCR.class.getPackage().getName());
This will add the object to the header.
Min and max value of input in angular4 application
You can write a directive to listen the change event on the input and reset the value to the min value if it is too low. StackBlitz
@HostListener('change') onChange() {
const min = +this.elementRef.nativeElement.getAttribute('min');
if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
this.renderer2.setProperty(
this.elementRef.nativeElement,
'value',
min + ''
);
}
}
Also listen for the ngModelChange event to do the same when the form value is set.
@HostListener('ngModelChange', ['$event'])
onModelChange(value: number) {
const min = +this.elementRef.nativeElement.getAttribute('min');
if (this.valueIsLessThanMin(min, value)) {
const formControl = this.formControlName
? this.formControlName.control
: this.formControlDirective.control;
if (formControl) {
if (formControl.updateOn === 'change') {
console.warn(
`minValueDirective: form control ${this.formControlName.name} is set to update on change
this can cause issues with min update values.`
);
}
formControl.reset(min);
}
}
}
Full code:
import {
Directive,
ElementRef,
HostListener,
Optional,
Renderer2,
Self
} from "@angular/core";
import { FormControlDirective, FormControlName } from "@angular/forms";
@Directive({
// tslint:disable-next-line: directive-selector
selector: "input[minValue][min][type=number]"
})
export class MinValueDirective {
@HostListener("change") onChange() {
const min = +this.elementRef.nativeElement.getAttribute("min");
if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
this.renderer2.setProperty(
this.elementRef.nativeElement,
"value",
min + ""
);
}
}
// if input is a form control validate on model change
@HostListener("ngModelChange", ["$event"])
onModelChange(value: number) {
const min = +this.elementRef.nativeElement.getAttribute("min");
if (this.valueIsLessThanMin(min, value)) {
const formControl = this.formControlName
? this.formControlName.control
: this.formControlDirective.control;
if (formControl) {
if (formControl.updateOn === "change") {
console.warn(
`minValueDirective: form control ${
this.formControlName.name
} is set to update on change
this can cause issues with min update values.`
);
}
formControl.reset(min);
}
}
}
constructor(
private elementRef: ElementRef<HTMLInputElement>,
private renderer2: Renderer2,
@Optional() @Self() private formControlName: FormControlName,
@Optional() @Self() private formControlDirective: FormControlDirective
) {}
private valueIsLessThanMin(min: any, value: number): boolean {
return typeof min === "number" && value && value < min;
}
}
Make sure to use this with the form control set to updateOn blur or the user won't be able to enter a +1 digit number if the first digit is below the min value.
this.formGroup = this.formBuilder.group({
test: [
null,
{
updateOn: 'blur',
validators: [Validators.min(5)]
}
]
});
NoClassDefFoundError - Eclipse and Android
Sometimes it will happen due to not including jar, which you have dependency, with "uses-libary" tag in your AndroidManifest.xml.
Also, make sure it should be inside "application" tag.
Regards,
Ravi
No module named pkg_resources
just reinstall your setuptools
by :
$ sudo wget https://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz#md5=7df2a529a074f613b509fb44feefefe74e
$ tar -zxvf setuptools-0.6c11.tar.gz
$ cd setuptools-0.6c11/
$ sudo python setup.py build
$ sudo python setup.py install
$ sudo pip install --upgrade setuptools
then everything will be fine.
How to compare strings in C conditional preprocessor-directives
#define USER_IS(c0,c1,c2,c3,c4,c5,c6,c7,c8,c9)\
ch0==c0 && ch1==c1 && ch2==c2 && ch3==c3 && ch4==c4 && ch5==c5 && ch6==c6 && ch7==c7 ;
#define ch0 'j'
#define ch1 'a'
#define ch2 'c'
#define ch3 'k'
#if USER_IS('j','a','c','k',0,0,0,0)
#define USER_VS "queen"
#elif USER_IS('q','u','e','e','n',0,0,0)
#define USER_VS "jack"
#endif
it basically a fixed length static char array initialized manually
instead of a variable length static char array initialized automatically always ending with a terminating null char
qmake: could not find a Qt installation of ''
You could check path to qmake using which qmake
.
Consider install qt4-default
or qt5-default
depends what version of qt you want use.
You could also use qtchooser - a wrapper used to select between Qt development binary versions.
Difference between HashMap, LinkedHashMap and TreeMap
HashMap:
- Order not maintains
- Faster than LinkedHashMap
- Used for store heap of objects
LinkedHashMap:
- LinkedHashMap insertion order will be maintained
- Slower than HashMap and faster than TreeMap
- If you want to maintain an insertion order use this.
TreeMap:
- TreeMap is a tree-based mapping
- TreeMap will follow the natural ordering of key
- Slower than HashMap and LinkedHashMap
- Use TreeMap when you need to maintain natural(default) ordering
The name 'InitializeComponent' does not exist in the current context
I've had this (although it was very much my fault and was caused after I copied and pasted some code in); it can occur when the namespace doesn't match between the XAML and code behind
EG
<UserControl x:Class="DockPanel.TreeView" />
and the code behind is
namespace NotDockPanel
C - function inside struct
You can pass the struct pointer to function as function argument.
It called pass by reference.
If you modify something inside that pointer, the others will be updated to.
Try like this:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
};
pno AddClient(client_t *client)
{
/* this will change the original client value */
client.password = "secret";
}
int main()
{
client_t client;
//code ..
AddClient(&client);
}
How to download a folder from github?
You have to download the whole project with either "Clone to desktop" button that will use native github program or "Download as zip".
And then search that folder in downloaded project.
VBA, if a string contains a certain letter
Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.
If InStr(myString, "A") > 0 Then
InStr MSDN Website
For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.
Left(oldStr, InStr(oldStr, "A"))
When is "java.io.IOException:Connection reset by peer" thrown?
For me useful code witch help me was http://rox-xmlrpc.sourceforge.net/niotut/src/NioServer.java
// The remote forcibly closed the connection, cancel
// the selection key and close the channel.
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// Clear out our read buffer so it's ready for new data
this.readBuffer.clear();
// Attempt to read off the channel
int numRead;
try {
numRead = socketChannel.read(this.readBuffer);
} catch (IOException e) {
// The remote forcibly closed the connection, cancel
// the selection key and close the channel.
key.cancel();
socketChannel.close();
return;
}
if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
key.channel().close();
key.cancel();
return;
}
...
How to scroll table's "tbody" independent of "thead"?
I saw this post about a month ago when I was having similar problems. I needed y-axis scrolling for a table inside of a ui dialog (yes, you heard me right). I was lucky, in that a working solution presented itself fairly quickly. However, it wasn't long before the solution took on a life of its own, but more on that later.
The problem with just setting the top level elements (thead, tfoot, and tbody) to display block, is that browser synchronization of the column sizes between the various components is quickly lost and everything packs to the smallest permissible size. Setting the widths of the columns seems like the best course of action, but without setting the widths of all the internal table components to match the total of these columns, even with a fixed table layout, there is a slight divergence between the headers and body when a scroll bar is present.
The solution for me was to set all the widths, check if a scroll bar was present, and then take the scaled widths the browser had actually decided on, and copy those to the header and footer adjusting the last column width for the size of the scroll bar. Doing this provides some fluidity to the column widths. If changes to the table's width occur, most major browsers will auto-scale the tbody column widths accordingly. All that's left is to set the header and footer column widths from their respective tbody sizes.
$table.find("> thead,> tfoot").find("> tr:first-child")
.each(function(i,e) {
$(e).children().each(function(i,e) {
if (i != column_scaled_widths.length - 1) {
$(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()));
} else {
$(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()) + $.position.scrollbarWidth());
}
});
});
This fiddle illustrates these notions: http://jsfiddle.net/borgboyone/gbkbhngq/.
Note that a table wrapper or additional tables are not needed for y-axis scrolling alone. (X-axis scrolling does require a wrapping table.) Synchronization between the column sizes for the body and header will still be lost if the minimum pack size for either the header or body columns is encountered. A mechanism for minimum widths should be provided if resizing is an option or small table widths are expected.
The ultimate culmination from this starting point is fully realized here: http://borgboyone.github.io/jquery-ui-table/
A.
How to undo 'git reset'?
Old question, and the posted answers work great. I'll chime in with another option though.
git reset ORIG_HEAD
ORIG_HEAD
references the commit that HEAD
previously referenced.
Eloquent Collection: Counting and Detect Empty
When using ->get()
you cannot simply use any of the below:
if (empty($result)) { }
if (!$result) { }
if ($result) { }
Because if you dd($result);
you'll notice an instance of Illuminate\Support\Collection
is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... }
which will always return true.
To determine if there are any results you can do any of the following:
if ($result->first()) { }
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }
You could also use ->first()
instead of ->get()
on the query builder which will return an instance of the first found model, or null
otherwise. This is useful if you need or are expecting only one result from the database.
$result = Model::where(...)->first();
if ($result) { ... }
Notes / References
Bonus Information
The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you’re working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all()
->first()
->lists()
and others). Those methods also exist on the Collection
object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing var_dump(User::all())
and experimenting to see what classes it's actually returning (with help of get_class(...)
). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.
Easiest way to make lua script wait/pause/sleep/block for a few seconds?
I agree with John on wrapping the sleep function.
You could also use this wrapped sleep function to implement a pause function in lua (which would simply sleep then check to see if a certain condition has changed every so often). An alternative is to use hooks.
I'm not exactly sure what you mean with your third bulletpoint (don't commands usually complete before the next is executed?) but hooks may be able to help with this also.
See:
Question: How can I end a Lua thread cleanly?
for an example of using hooks.
How to display HTML in TextView?
It has been suggested through various answers to use the Html framework class as suggested here, but unfortunately this class has different behavior in different versions of Android and various unaddressed bugs, as demonstrated in issues 214637, 14778, 235128 and 75953.
You may therefore want to use a compatibility library to standardize and backport the Html class across Android versions which includes more callbacks for elements and styling:
Github project HtmlCompat
While it is similar to the framework's Html class, some signature changes were required to allow more callbacks. Here's the sample from the GitHub page:
Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0);
// You may want to provide an ImageGetter, TagHandler and SpanCallback:
//Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0,
// imageGetter, tagHandler, spanCallback);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(fromHtml);
PHP header() redirect with POST variables
If you don't want to use sessions, the only thing you can do is POST to the same page. Which IMO is the best solution anyway.
// form.php
<?php
if (!empty($_POST['submit'])) {
// validate
if ($allGood) {
// put data into database or whatever needs to be done
header('Location: nextpage.php');
exit;
}
}
?>
<form action="form.php">
<input name="foo" value="<?php if (!empty($_POST['foo'])) echo htmlentities($_POST['foo']); ?>">
...
</form>
This can be made more elegant, but you get the idea...
How to print a query string with parameter values when using Hibernate
Log4JDBC is a nice solution which prints the exact SQL going to the database with parameters in place rather than the most popular answer here which does not do this. One major convenience of this is that you can copy the SQL straight to your DB front-end and execute as is.
http://log4jdbc.sourceforge.net/
https://code.google.com/p/log4jdbc-remix/
The latter also outputs a tabular representation of query results.
Sample Output showing generated SQL with params in place together with result set table from query:
5. insert into ENQUIRY_APPLICANT_DETAILS (ID, INCLUDED_IN_QUOTE, APPLICANT_ID, TERRITORY_ID, ENQUIRY_ID, ELIGIBLE_FOR_COVER) values (7, 1, 11, 1, 2, 0)
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |ID |CREATED |DELETED |CODESET_ID |NAME |POSITION |PREFIX |
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |2 |null |null |1 |Country 2 |1 |60 |
10 Oct 2013 16:21:22 4953 [main] INFO jdbc.resultsettable - |---|--------|--------|-----------|----------|---------|-------|
Update 2016
Most recently I have now been using log4jdbc-log4j2 (https://code.google.com/archive/p/log4jdbc-log4j2/ ) with SLF4j and logback. Maven dependencies required for my set-up are as below:
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>$logback.version}</version>
</dependency>
The Driver and DB Urls then look like:
database.driver.class=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
database.url=jdbc:log4jdbc:hsqldb:mem:db_name #Hsql
#database.url=jdbc:log4jdbc:mysql://localhost:3306/db_name
My logback.xml configuration file looks like the below: this outputs all SQL statements with parameters plus the resultset tables for all queries.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="jdbc.audit" level="ERROR" />
<logger name="jdbc.connection" level="ERROR" />
<logger name="jdbc.sqltiming" level="ERROR" />
<logger name="jdbc.resultset" level="ERROR" />
<!-- UNCOMMENT THE BELOW TO HIDE THE RESULT SET TABLE OUTPUT -->
<!--<logger name="jdbc.resultsettable" level="ERROR" /> -->
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Finally, I had to create a file named log4jdbc.log4j2.properties at the root of the classpath e.g. src/test/resources or src/main/resources in a Mevn project. This file has one line which is the below:
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
The above will depend on your logging library. See the docs at https://code.google.com/archive/p/log4jdbc-log4j2 for further info
Sample Output:
10:44:29.400 [main] DEBUG jdbc.sqlonly - org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
5. select memberrole0_.member_id as member_i2_12_0_, memberrole0_.id as id1_12_0_, memberrole0_.id
as id1_12_1_, memberrole0_.member_id as member_i2_12_1_, memberrole0_.role_id as role_id3_12_1_,
role1_.id as id1_17_2_, role1_.name as name2_17_2_ from member_roles memberrole0_ left outer
join roles role1_ on memberrole0_.role_id=role1_.id where memberrole0_.member_id=104
10:44:29.402 [main] INFO jdbc.resultsettable -
|----------|---|---|----------|--------|---|-----|
|member_id |id |id |member_id |role_id |id |name |
|----------|---|---|----------|--------|---|-----|
|----------|---|---|----------|--------|---|-----|
add an onclick event to a div
Assign the onclick like this:
divTag.onclick = printWorking;
The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking
).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>
, but this is generally not recommended.
How to iterate std::set?
One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth
element normal way will not work.
example:
std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";
std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
if(index==k) break;
cout<<*itr++<<" ";
index++;
}
Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other
encoding hints are given.
To define a source code encoding, a magic comment must
be placed into the source files either as first or second
line in the file, such as:
# coding=
Add back button to action bar
Use this to show back button and move to previous activity,
final ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.back_dark);
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
How do I install a plugin for vim?
I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.
Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).
Removing body margin in CSS
This should help you get rid of body margins and default top margin of <h1>
tag
body{
margin: 0px;
padding: 0px;
}
h1 {
margin-top: 0px;
}
How to submit an HTML form without redirection
Place a hidden iFrame
at the bottom of your page and target
it in your form:
<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm" target="hiddenFrame"> ... </form>
Quick and easy. Keep in mind that while the target
attribute is still widely supported (and supported in HTML5), it was deprecated in HTML 4.01.
So you really should be using Ajax to future-proof.
Case insensitive comparison NSString
Alternate solution for swift:
To make both UpperCase:
e.g:
if ("ABcd".uppercased() == "abcD".uppercased()){
}
or to make both LowerCase:
e.g:
if ("ABcd".lowercased() == "abcD".lowercased()){
}
Replace given value in vector
Why the fuss?
replace(haystack, haystack %in% needles, replacements)
Demo:
haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")
replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"
How to add elements to a list in R (loop)
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
How to refer environment variable in POM.xml?
I was struggling with the same thing, running a shell script that set variables, then wanting to use the variables in the shared-pom. The goal was to have environment variables replace strings in my project files using the com.google.code.maven-replacer-plugin.
Using ${env.foo}
or ${env.FOO}
didn't work for me. Maven just wasn't finding the variable. What worked was passing the variable in as a command-line parameter in Maven. Here's the setup:
Set the variable in the shell script. If you're launching Maven in a sub-script, make sure the variable is getting set, e.g. using source ./maven_script.sh
to call it from the parent script.
In shared-pom, create a command-line param that grabs the environment variable:
<plugin>
...
<executions>
<executions>
...
<execution>
...
<configuration>
<param>${foo}</param> <!-- Note this is *not* ${env.foo} -->
</configuration>
In com.google.code.maven-replacer-plugin, make the replacement value ${foo}
.
In my shell script that calls maven, add this to the command: -Dfoo=$foo
Copy all the lines to clipboard
There wasn't a concept of "clipboard" in Bill Joy's vi so I don't think there is a built-in way to do it.
gVim's automatic copy-anything-highlighted-to-the-clipboard feature is easiest or use an external program via :!
For Cygwin's vim I use
:%!putclip
u
Maybe Ubuntu has a CLI app like putclip??
Sending data through POST request from a node.js server to a node.js server
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?
) as the request body.
This requires Content-Type
and Content-Length
headers, so the receiving server knows how to interpret the incoming data. (*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded
for the traditional format that a standard HTML form would use.
It's easy to send JSON (application/json
) in exactly the same manner; just JSON.stringify()
the data beforehand.
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
The bottom line is: The server must be able to interpret the content type in question. It could be text/plain
or anything else; there is no need to convert data if the receiving server understands it as it is.
Add a charset parameter (e.g. application/json; charset=Windows-1252
) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
Iterate over each line in a string in PHP
Potential memory issues with strtok
:
Since one of the suggested solutions uses strtok
, unfortunately it doesn't point out a potential memory issue (though it claims to be memory efficient). When using strtok
according to the manual, the:
Note that only the first call to strtok uses the string argument.
Every subsequent call to strtok only needs the token to use, as it
keeps track of where it is in the current string.
It does this by loading the file into memory. If you're using large files, you need to flush them if you're done looping through the file.
<?php
function process($str) {
$line = strtok($str, PHP_EOL);
/*do something with the first line here...*/
while ($line !== FALSE) {
// get the next line
$line = strtok(PHP_EOL);
/*do something with the rest of the lines here...*/
}
//the bit that frees up memory
strtok('', '');
}
If you're only concerned with physical files (eg. datamining):
According to the manual, for the file upload part you can use the file
command:
//Create the array
$lines = file( $some_file );
foreach ( $lines as $line ) {
//do something here.
}
How to convert a color integer to a hex String in Android?
I believe i have found the answer, This code converts the integer to a hex string an removes the alpha.
Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);
Note only use this code if you are sure that removing the alpha would not affect anything.
Calling stored procedure with return value
The version of EnterpriseLibrary on my machine had other parameters.
This was working:
SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
retval.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add(retval);
db.ExecuteNonQuery(cmd);
object o = cmd.Parameters["@ReturnValue"].Value;
Sibling package imports
You need to look to see how the import statements are written in the related code. If examples/example_one.py
uses the following import statement:
import api.api
...then it expects the root directory of the project to be in the system path.
The easiest way to support this without any hacks (as you put it) would be to run the examples from the top level directory, like this:
PYTHONPATH=$PYTHONPATH:. python examples/example_one.py
How to use OKHTTP to make a post request?
You should check tutorials on lynda.com. Here is an example of how to encode the parameters, make HTTP request and then parse response to json object.
public JSONObject getJSONFromUrl(String str_url, List<NameValuePair> params) {
String reply_str = null;
BufferedReader reader = null;
try {
URL url = new URL(str_url);
OkHttpClient client = new OkHttpClient();
HttpURLConnection con = client.open(url);
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(getEncodedParams(params));
writer.flush();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reply_str = sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
// try parse the string to a JSON object. There are better ways to parse data.
try {
jObj = new JSONObject(reply_str);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
//in this case it's NameValuePair, but you can use any container
public String getEncodedParams(List<NameValuePair> params) {
StringBuilder sb = new StringBuilder();
for (NameValuePair nvp : params) {
String key = nvp.getName();
String param_value = nvp.getValue();
String value = null;
try {
value = URLEncoder.encode(param_value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}
Python unittest passing arguments
Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:
- which of the dozen identical USB cards should I use for this test now?
- which server should I use for this test now?
- which XXX should I use?
For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.
Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)
import os
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
self.var1 = os.environ["VAR1"]
self.var2 = os.environ["VAR2"]
def test_01(self):
print("var1: {}, var2: {}".format(self.var1, self.var2))
Then from the command line (tested on Linux)
$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
ASP.Net Download file to client browser
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
How to install MinGW-w64 and MSYS2?
Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).
Anyways, if you're already planning on using MSYS2, there's no need for that installer.
Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).
After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit
or MSYS2 32-bit
in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu
, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).
Install a toolchain
a) for 32-bit:
pacman -S mingw-w64-i686-gcc
b) for 64-bit:
pacman -S mingw-w64-x86_64-gcc
install any libraries/tools you may need. You can search the repositories by doing
pacman -Ss name_of_something_i_want_to_install
e.g.
pacman -Ss gsl
and install using
pacman -S package_name_of_something_i_want_to_install
e.g.
pacman -S mingw-w64-x86_64-gsl
and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!
Open a MinGW-w64 shell:
a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"
b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"
Verify that the compiler is working by doing
gcc -v
If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin
or <MSYS2 root>/mingw64/bin
to your PATH
.
How to use shell commands in Makefile
With:
FILES = $(shell ls)
indented underneath all
like that, it's a build command. So this expands $(shell ls)
, then tries to run the command FILES ...
.
If FILES
is supposed to be a make
variable, these variables need to be assigned outside the recipe portion, e.g.:
FILES = $(shell ls)
all:
echo $(FILES)
Of course, that means that FILES
will be set to "output from ls
" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ...
to avoid this, for efficiency and/or correctness.1)
If FILES
is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:
all:
FILES="$(shell ls)"
However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:
FILES="$(shell ls)"; echo $$FILES
This is all a bit silly since the shell will expand *
(and other shell glob expressions) for you in the first place, so you can just:
echo *
as your shell command.
Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls
is not completely reliable (some details depend on file names and sometimes even the version of ls
; some versions of ls
attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard)
and $(subst ...)
to accomplish everything inside make
itself (avoiding any "weird characters in file name" issues). (In sh
scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0
to avoid tripping over blanks, newlines, control characters, and so on.)
1The GNU Make documentation notes further that POSIX make added ::=
assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make
variants support ::=
assignment, although GNU make does today, with the same meaning as :=
, i.e., do the assignment right now with expansion.
Note that VAR := $(shell command args...)
can also be spelled VAR != command args...
in several make
variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell)
so using VAR != command args...
is superior in both being shorter and working in more variants.
I can’t find the Android keytool
Ok I did this in Windows 7 32-bit system.
step 1: go to - C:\Program Files\Java\jdk1.6.0_26\bin - and run jarsigner.exe first ( double click)
step2: locate debug.keystore, in my case it was - C:\Users\MyPcName\.android
step3: open command prompt and go to dir - C:\Program Files\Java\jdk1.6.0_26\bin and give the following command:
keytool -list -keystore "C:\Users\MyPcName\.android\debug.keystore"
step4: it will ask for Keystore password now.
( which I am figuring out... :-? )
update: OK in my case password was ´ android ´.
- (I am using Eclipse for android, so I found it here)
Follow the steps in eclipse:
Windows>preferences>android>build>..
( Look in `default Debug Keystore´ field.)
Command to change the keystore password (look here): Keystore change passwords
Visualizing decision tree in scikit-learn
Scikit learn recently introduced the plot_tree
method to make this very easy (new in version 0.21 (May 2019)). Documentation here.
Here's the minimum code you need:
from sklearn import tree
plt.figure(figsize=(40,20)) # customize according to the size of your tree
_ = tree.plot_tree(your_model_name, feature_names = X.columns)
plt.show()
plot_tree
supports some arguments to beautify the tree. For example:
from sklearn import tree
plt.figure(figsize=(40,20))
_ = tree.plot_tree(your_model_name, feature_names = X.columns,
filled=True, fontsize=6, rounded = True)
plt.show()
If you want to save the picture to a file, add the following line before plt.show()
:
plt.savefig('filename.png')
If you want to view the rules in text format, there's an answer here. It's more intuitive to read.
Notepad++ - How can I replace blank lines
As of NP++ V6.2.3 (nor sure about older versions) simply:
- Go menu -> Edit -> Line operations
- Choose "Remove Empty Lines" or "Remove Empty Lines (Containing white spaces)" according to your needs.
Hope this helps to achieve goal in simple and yet fast way:)
Pandas: drop a level from a multi-level column index?
Another way to do this is to reassign df
based on a cross section of df
, using the .xs method.
>>> df
a
b c
0 1 2
1 3 4
>>> df = df.xs('a', axis=1, drop_level=True)
# 'a' : key on which to get cross section
# axis=1 : get cross section of column
# drop_level=True : returns cross section without the multilevel index
>>> df
b c
0 1 2
1 3 4
Chrome extension id - how to find it
As Alex Gray points out in a comment above, "all of the corresponding IDs are actually on the extensions page within the browser".
However, you must click the Developer Mode checkbox at top of Extensions page to see them.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
Strip first and last character from C string
The most efficient way:
//Note destroys the original string by removing it's last char
// Do not pass in a string literal.
char * getAllButFirstAndLast(char *input)
{
int len = strlen(input);
if(len > 0)
input++;//Go past the first char
if(len > 1)
input[len - 2] = '\0';//Replace the last char with a null termination
return input;
}
//...
//Call it like so
char str[512];
strcpy(str, "hello world");
char *pMod = getAllButFirstAndLast(str);
The safest way:
void getAllButFirstAndLast(const char *input, char *output)
{
int len = strlen(input);
if(len > 0)
strcpy(output, ++input);
if(len > 1)
output[len - 2] = '\0';
}
//...
//Call it like so
char mod[512];
getAllButFirstAndLast("hello world", mod);
The second way is less efficient but it is safer because you can pass in string literals into input. You could also use strdup for the second way if you didn't want to implement it yourself.
Insert data using Entity Framework model
I'm using EF6, and I find something strange,
Suppose Customer has constructor with parameter ,
if I use new Customer(id, "name")
, and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name") );
db.SaveChanges();
}
It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,
But if I add the curly brackets, use new Customer(id, "name"){}
and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name"){} );
db.SaveChanges();
}
the data will then actually BE Inserted,
seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.
Tool to compare directories (Windows 7)
The tool that richardtz suggests is excellent.
Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.
You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge
How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one
Make an update object with the property names including the necessary dot path. ("somekey."+ from OP's example), and then use that do the update.
//the modification that's requested
updateReq = {
param2 : "val2_new",
param3 : "val3_new"
}
//build a renamed version of the update request
var update = {};
for(var field in updateReq){
update["somekey."+field] = updateReq[field];
}
//apply the update without modifying fields not originally in the update
db.collection.update({._id:...},{$set:update},{upsert:true},function(err,result){...});
How to validate date with format "mm/dd/yyyy" in JavaScript?
function fdate_validate(vi)
{
var parts =vi.split('/');
var result;
var mydate = new Date(parts[2],parts[1]-1,parts[0]);
if (parts[2] == mydate.getYear() && parts[1]-1 == mydate.getMonth() && parts[0] == mydate.getDate() )
{result=0;}
else
{result=1;}
return(result);
}
Fastest check if row exists in PostgreSQL
I would like to propose another thought to specifically address your sentence: "So I want to check if a single row from the batch exists in the table because then I know they all were inserted."
You are making things efficient by inserting in "batches" but then doing existence checks one record at a time? This seems counter intuitive to me. So when you say "inserts are always done in batches" I take it you mean you are inserting multiple records with one insert statement. You need to realize that Postgres is ACID compliant. If you are inserting multiple records (a batch of data) with one insert statement, there is no need to check if some were inserted or not. The statement either passes or it will fail. All records will be inserted or none.
On the other hand, if your C# code is simply doing a "set" separate insert statements, for example, in a loop, and in your mind, this is a "batch" .. then you should not in fact describe it as "inserts are always done in batches". The fact that you expect that part of what you call a "batch", may actually not be inserted, and hence feel the need for a check, strongly suggests this is the case, in which case you have a more fundamental problem. You need change your paradigm to actually insert multiple records with one insert, and forego checking if the individual records made it.
Consider this example:
CREATE TABLE temp_test (
id SERIAL PRIMARY KEY,
sometext TEXT,
userid INT,
somethingtomakeitfail INT unique
)
-- insert a batch of 3 rows
;;
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 1, 1),
('bar', 2, 2),
('baz', 3, 3)
;;
-- inspect the data of what we inserted
SELECT * FROM temp_test
;;
-- this entire statement will fail .. no need to check which one made it
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 2, 4),
('bar', 2, 5),
('baz', 3, 3) -- <<--(deliberately simulate a failure)
;;
-- check it ... everything is the same from the last successful insert ..
-- no need to check which records from the 2nd insert may have made it in
SELECT * FROM temp_test
This is in fact the paradigm for any ACID compliant DB .. not just Postgresql. In other words you are better off if you fix your "batch" concept and avoid having to do any row by row checks in the first place.
Cell spacing in UICollectionView
Swift 3 Version
Simply create a UICollectionViewFlowLayout subclass and paste this method.
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let answer = super.layoutAttributesForElements(in: rect) else { return nil }
for i in 1..<answer.count {
let currentAttributes = answer[i]
let previousAttributes = answer[i - 1]
let maximumSpacing: CGFloat = 8
let origin = previousAttributes.frame.maxX
if (origin + maximumSpacing + currentAttributes.frame.size.width < self.collectionViewContentSize.width && currentAttributes.frame.origin.x > previousAttributes.frame.origin.x) {
var frame = currentAttributes.frame
frame.origin.x = origin + maximumSpacing
currentAttributes.frame = frame
}
}
return answer
}
Java: get greatest common divisor
I used this method that I created when I was 14 years old.
public static int gcd (int a, int b) {
int s = 1;
int ia = Math.abs(a);//<-- turns to absolute value
int ib = Math.abs(b);
if (a == b) {
s = a;
}else {
while (ib != ia) {
if (ib > ia) {
s = ib - ia;
ib = s;
}else {
s = ia - ib;
ia = s;
}
}
}
return s;
}
Where is Maven's settings.xml located on Mac OS?
->It is located in $MAVEN_HOME/conf/settings.xml...
where $MAVEN_HOME is your environmental variable of Maven that you have downloaded.
Else you can do like this also..
->Path to Maven can also be found from /etc/bashrc file in mac.
Get Path to Maven from that file and in that Maven directory you can find conf/ directory inside that directory you can find settings.xml of maven