Programs & Examples On #Tmail

element not interactable exception in selenium web automation

Please try selecting the password field like this.

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement passwordElement = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#Passwd")));
    passwordElement.click();
  passwordElement.clear();
     passwordElement.sendKeys("123");

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I had the same problem, changing my gmail password fixed the issue, and also don't forget to enable less secure app on on your gmail account

Passing bash variable to jq

Little unrelated but I will still put it here, For other practical purposes shell variables can be used as -

value=10
jq  '."key" = "'"$value"'"' file.json

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

I fixed it by add a property to renderSeparator Component,the code is here:

_renderSeparator(sectionID,rowID){
    return (
        <View style={styles.separatorLine} key={"sectionID_"+sectionID+"_rowID_"+rowID}></View>
    );
}

The key words of this warning is "unique", sectionID + rowID return a unique value in ListView.

Failed to authenticate on SMTP server error using gmail

Did you turn on the "Allow less secure apps" on? go to this link

https://myaccount.google.com/security#connectedapps

Take a look at the Sign-in & security -> Apps with account access menu.

You must turn the option "Allow less secure apps" ON.

If is still doesn't work try one of these:

And change your .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=xxxxxx
MAIL_ENCRYPTION=tls

because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.

Expected response code 220 but got code "", with message "" in Laravel

if you are using Swift Mailer: please ensure that your $transport variable is similar to the below, based on tests i have done, that error results from ssl and port misconfiguration. note: you must include 'ssl' or 'tls' in the transport variable.

EXAMPLE CODE:

// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
  ->setUsername([email protected])
  ->setPassword(password)
;

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create a message
$message = (new Swift_Message('News Letter Subscription'))
  ->setFrom(['[email protected]' => 'A Name'])
  ->setTo(['[email protected]' => 'A Name'])
  ->setBody('your message body')
  ;

// Send the message
$result = $mailer->send($message);

535-5.7.8 Username and Password not accepted

If you still cannot solve the problem after you turn on the less secure apps. The other possible reason which might cause this error is you are not using gmail account.

-    : user_name  =>  '[email protected]' ,  # It can not be used since it is not a gmail address 
+    : user_name  =>  '[email protected]' ,  # since it's a gmail address

Refer to here.

Also, bear in mind that it might take some times to enable the less secure apps. I have to do it several times (before it works, every time I access the link it will shows that it is off) and wait for a while until it really work.

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

Here are the steps for send email from localhost by wamp server with Sendmail.

  1. First, you need to download Sendmail zip file link
  2. Extract the zip file and put it on C:\wamp
  3. Now, you need to edit Sendmail.ini on C:\wamp\sendmail\sendmail.ini
smtp_server=smtp.gmail.com 
smtp_port=465
[email protected]
auth_password=your_password
  1. Access your email account. Click the Gear Tool > Settings > Forwarding and POP/IMAP > IMAP access. Click "Enable IMAP", then save your changes
  2. Run your WAMP Server. Enable ssl_module under Apache Module.
  3. Next, enable php_openssl and php_sockets under PHP.
  4. ** Now the important part open php.ini file on "C:\wamp\bin\php\php5.5.12\php.ini" and "C:\wamp\bin\apache\apache2.4.9\bin\php.ini" set sendmail_path **

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

  1. Restart Wamp Server.

It will surely be worked.

Change HTML email body font type and size in VBA

I did a little research and was able to write this code:

strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>We have completed our main aliasing process for today.  All assigned firms are complete.  Please feel free to respond with any questions.<p>Thank you.</BODY>"

apparently by setting the "font-size=11pt" instead of setting the font size <font size=5>, It allows you to select a specific font size like you normally would in a text editor, as opposed to selecting a value from 1-7 like my code was originally.

This link from simpLE MAn gave me some good info.

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

Paste Excel range in Outlook

First off, RangeToHTML. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.

On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.

For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.

Sub Mail_Selection_Range_Outlook_Body()

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

Calling one Bash script from another Script passing it arguments with quotes and spaces

You need to use : "$@" (WITH the quotes) or "${@}" (same, but also telling the shell where the variable name starts and ends).

(and do NOT use : $@, or "$*", or $*).

ex:

#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
   echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@"   #invokes testscript2 with the same arguments we received

I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :

'./testscript2' "$@"  #only makes sense if "/path/to/testscript2" containes spaces?

./testscript2 '"some thing" "another"' "$var" "$var2"  #3 args to testscript2

Please give me the exact thing you are trying to do

edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'

You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...

You could maybe "simplify" by having:

#testscript1

#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
   theargs="${theargs} '$i'"
done

salt 'remote host' cmd.run "./testscript2 ${theargs}"

if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by

echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$  #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

How to get list of all installed packages along with version in composer?

You can run composer show -i (short for --installed).

In the latest version just use composer show.

The -i options has been deprecated.

You can also use the global instalation of composer: composer global show

How to send email to multiple recipients with addresses stored in Excel?

Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :

                Dim Splitter() As String
                Splitter = Split(AddrMail, ";")
                For Each Dest In Splitter
                    .Recipients.Add (Trim(Dest))
                Next

Sending email with PHP from an SMTP server

I created a lightweight SMTP Email sender for PHP if anybody needs it here is the URL

https://github.com/jerryurenaa/EZMAIL

Tested in both environments production and development.

I hope it helps new folks looking for a simple solution.

Exception: Serialization of 'Closure' is not allowed

You have to disable Globals

 /**
 * @backupGlobals disabled
 */

javascript filter array of objects

For those who want to filter from an array of objects using any key:

_x000D_
_x000D_
function filterItems(items, searchVal) {_x000D_
  return items.filter((item) => Object.values(item).includes(searchVal));_x000D_
}_x000D_
let data = [_x000D_
  { "name": "apple", "type": "fruit", "id": 123234 },_x000D_
  { "name": "cat", "type": "animal", "id": 98989 },_x000D_
  { "name": "something", "type": "other", "id": 656565 }]_x000D_
_x000D_
_x000D_
console.log("Filtered by name: ", filterItems(data, "apple"));_x000D_
console.log("Filtered by type: ", filterItems(data, "animal"));_x000D_
console.log("Filtered by id: ", filterItems(data, 656565));
_x000D_
_x000D_
_x000D_

filter from an array of the JSON objects:**

ERROR: Error 1005: Can't create table (errno: 121)

If you want to fix quickly, Forward Engineer again and check "Generate DROP SCHEMA" option and proceed.

I assume the database doesn't contain data, so dropping it won't affect.

CSS - center two images in css side by side

I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:

in html code:

<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>

The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.

in css code:

/* h6: set presentation of images */
h6
  {
  font-family: "Franklin Gothic Demi", serif;
  font-size: 1.0em;
  font-weight: normal;
  line-height: 1.25em;
  text-align: center;
  }

The text items set the look of the caption text, and the text-align property centers both the images and the caption text.

Using CSS for a fade-in effect on page load

You can use the onload="" HTML attribute and use JavaScript to adjust the opacity style of your element.

Leave your CSS as you proposed. Edit your HTML code to:

<body onload="document.getElementById(test).style.opacity='1'">
    <div id="test">
        <p>?This is a test</p>
    </div>
</body>

This also works to fade-in the complete page when finished loading:

HTML:

<body onload="document.body.style.opacity='1'">
</body>

CSS:

body{ 
    opacity: 0;
    transition: opacity 2s;
    -webkit-transition: opacity 2s; /* Safari */
}

Check the W3Schools website: transitions and an article for changing styles with JavaScript.

Must issue a STARTTLS command first

Adding

props.put("mail.smtp.starttls.enable", "true");

solved my problem ;)

My problem was :

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.example.sendmail.SendEmailExample2.main(SendEmailExample2.java:53)

Why do I get "'property cannot be assigned" when sending an SMTP email?

Initialize the MailMessage with sender and reciever's email addresses. It should be something like

string from = "[email protected]";  //Senders email   
string to = "[email protected]";  //Receiver's email  
MailMessage msg = new MailMessage(from, to); 

Read the full code snippet of how to send emails in c#

How do I remove link underlining in my HTML email?

Code like the lines below worked for me in Gmail Web client. A non-underlined black link showed up in the email. I didn't use the nested span tag.

<table>
  <tbody>
    <tr>
        <td>
            <a href="http://hexinpeter.com" style="text-decoration: none; color: #000000 !important;">Peter Blog</a>
        </td>
    </tr>
  </tbody>
</table>

Note: Gmail will strip off any incorrect inline styles. E.g. code like the line below will have its inline styles all stripped off.

<a href="http://hexinpeter.com" style="font-family:; text-decoration: none; color: #000000 !important;">Peter Blog</a>

select unique rows based on single distinct column

Quick one in TSQL

SELECT a.*
FROM emails a
INNER JOIN 
  (SELECT email,
    MIN(id) as id
  FROM emails 
  GROUP BY email 
) AS b
  ON a.email = b.email 
  AND a.id = b.id;

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

I faced the same issue. Tried adding the US_export_policy.jar and local_policy.jar in the java security folder first but the issue persisted. Then added the below in java_opts inside tomcat setenv.shfile and it worked.

-Djdk.tls.ephemeralDHKeySize=2048

Please check this link for further info

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

"SMTP Error: Could not authenticate" in PHPMailer

SMTP Error: could not authenticate I had the same problem. The following troubleshooting steps helped me.

  • I turned off two-factor authentication in my gmail account.
  • I allowed less secure apps to access my gmail account. To get it working, I had to go to myaccount.google.com -> Sign-in & security -> Apps with account access, and turn Allow less secure apps to ON (near the bottom of the page).
  • At this step, when I tried to register a user, I would get the same error. Google would sent me a warning message that someone has my password and the login was blocked.
  • Gmail will then provide you with options. You either click whether the activity was yours or not yours. Click the option that the activity was yours.
  • Try registration again. It should now work.

How to send 100,000 emails weekly?

People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.

Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.

Here's a summary of what we found...

AuthSMTP

  • Cheapest around
  • No analysis/reporting
  • No tracking for opens/clicks
  • Had slight hesitation on some sends

Postmark

  • Very cheap, but not as cheap as AuthSMTP
  • Beautiful cpanel but no tracking on opens/clicks
  • Send-level activity tracking so you can open a single email that was sent and look at how it looked and the delivery data.
  • Have to use API. Sending by SMTP was recently introduced but it's buggy. For instance, we noticed that quotes (") in the subject line are stripped.
  • Cannot send any attachment you want. Must be on approved list of file types and under a certain size. (10 MB I think)
  • Requires a set list of from names/addresses.

JangoSMTP

  • Expensive in relation to the others – more than 10 times in some cases
  • Ugly cpanel but great tracking on opens/clicks with email-level detail
  • Had hesitation, at times, when sending. On two occasions, sends took an hour to be delivered
  • Requires a set list of from name/addresses.

SendGrid

  • Not quite a cheap as AuthSMTP but still very cheap. Many customers can exist on 200 free sends per day.
  • Decent cpanel but no in-depth detail on open/click tracking
  • Lots of API options. Options (open/click tracking, etc) can be custom defined on an email-by-email basis. Inbound (reply) email can be posted to our HTTP end point.
  • Absolutely zero hesitation on sends. Every email sent landed in the inbox almost immediately.
  • Can send from any from name/address.

Conclusion

SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.

Append same text to every cell in a column in Excel

See if this works for you.

  • All your data is in column A (beginning at row 1).
  • In column B, row 1, enter =A1&","
  • This will make cell B1 equal A1 with a comma appended.
  • Now select cell B1 and drag from the bottom right of cell down through all your rows (this copies the formula and uses the corresponding column A value.)
  • Select the newly appended data, copy it and paste it where you need using Paste -> By Value

That's It!

Invalid length for a Base-64 char array

The encrypted string had two special characters, + and =.

'+' sign was giving the error, so below solution worked well:

//replace + sign

encryted_string = encryted_string.Replace("+", "%2b");

//`%2b` is HTTP encoded string for **+** sign

OR

//encode special charactes 

encryted_string = HttpUtility.UrlEncode(encryted_string);

//then pass it to the decryption process
...

Removing double quotes from variables in batch file creates problems with CMD environment

@echo off

Setlocal enabledelayedexpansion

Set 1=%1

Set 1=!1:"=!

Echo !1!

Echo "!1!"

Set 1=

Demonstrates with or without quotes reguardless of whether original parameter has quotes or not.

And if you want to test the existence of a parameter which may or may not be in quotes, put this line before the echos above:

If '%1'=='' goto yoursub

But if checking for existence of a file that may or may not have quotes then it's:

If EXIST "!1!" goto othersub

Note the use of single quotes and double quotes are different.

Find rows that have the same value on a column in MySQL

Thanks guys :-) I used the below because I only cared about those two columns and not so much about the rest. Worked great

  select email, login_id from table
    group by email, login_id
    having COUNT(email) > 1

How can I center <ul> <li> into div

I have been looking for the same case and tried all answers by change the width of <li>.
Unfortunately all were failed to get the same distance on left and right of the <ul> box.

The closest match is this answer but it needs to adjust the change of width with padding

.container ul {
    ...
    padding: 10px 25px;
}

.container li {
  ...
  width: 100px;
}

See the result below, all distance between <li> also to the <ul> box are the same. enter image description here

You may check it on this jsFiddle:
http://jsfiddle.net/qwbexxog/14/

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

An easy route would be to have the gmail account configured/enabled for POP3 access. This would allow you to send out via normal SMTP through the gmail servers.

Then you'd just send through smtp.gmail.com (on port 587)

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

Reverse order of foreach list items

Walking Backwards

If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

$index = count($accounts);

while($index) {
  echo sprintf("<li>%s</li>", $accounts[--$index]);
}

The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.

Reversing the Array

You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:

$accounts = Array(
  '@jonathansampson',
  '@f12devtools',
  '@ieanswers'
);

foreach ( array_reverse($accounts) as $account ) {
  echo sprintf("<li>%s</li>", $account);
}

How to run shell script on host from docker container?

As Marcus reminds, docker is basically process isolation. Starting with docker 1.8, you can copy files both ways between the host and the container, see the doc of docker cp

https://docs.docker.com/reference/commandline/cp/

Once a file is copied, you can run it locally

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Although a bit late, I've come across this question while searching the solution for the same problem, so I hope it can be of any help...

Found myself in the same darkness than you. Just found this article, which explains some new hints introduced in NetBeans 7.4, including this one:

https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new

The reason why it has been added is because superglobals usually are filled with user input, which shouldn't ever be blindly trusted. Instead, some kind of filtering should be done, and that's what the hint suggests. Filter the superglobal value in case it has some poisoned content.

For instance, where I had:

$_SERVER['SERVER_NAME']

I've put instead:

filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING)

You have the filter_input and filters doc here:

http://www.php.net/manual/en/function.filter-input.php

http://www.php.net/manual/en/filter.filters.php

Bootstrap Element 100% Width

The container class is intentionally not 100% width. It is different fixed widths depending on the width of the viewport.

If you want to work with the full width of the screen, use .container-fluid:

Bootstrap 3:

<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-6"></div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
      <div class="col-lg-8"></div>
      <div class="col-lg-4"></div>
    </div>
    <div class="row">
      <div class="col-lg-12"></div>
    </div>
  </div>
</body>

Bootstrap 2:

<body>
  <div class="row">
    <div class="span6"></div>
    <div class="span6"></div>
  </div>
  <div class="row">
    <div class="span8"></div>
    <div class="span4"></div>
  </div>
  <div class="row">
    <div class="span12"></div>
  </div>
</body>

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

You can add function to:

c:\Users\David\Documents\WindowsPowerShell\profile.ps1

An the function will be available.

Why use double indirection? or Why use pointers to pointers?

For instance if you want random access to noncontiguous data.

p -> [p0, p1, p2, ...]  
p0 -> data1
p1 -> data2

-- in C

T ** p = (T **) malloc(sizeof(T*) * n);
p[0] = (T*) malloc(sizeof(T));
p[1] = (T*) malloc(sizeof(T));

You store a pointer p that points to an array of pointers. Each pointer points to a piece of data.

If sizeof(T) is big it may not be possible to allocate a contiguous block (ie using malloc) of sizeof(T) * n bytes.

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • What is "Signal 15 received"

    This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

    If you need a quick cheatsheet of signal numbers, open a bash shell and:

    $ kill -l
     1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
     5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
     9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
    13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
    17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
    21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
    25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
    29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
    35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
    39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
    43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
    47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
    51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
    55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
    59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
    63) SIGRTMAX-1  64) SIGRTMAX    
    

    You can determine the sender by using an appropriate signal handler like:

    #include <signal.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    void sigterm_handler(int signal, siginfo_t *info, void *_unused)
    {
      fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
          info->si_pid);
      exit(0);
    }
    
    int main (void)
    {
      struct sigaction action = {
        .sa_handler = NULL,
        .sa_sigaction = sigterm_handler,
        .sa_mask = 0,
        .sa_flags = SA_SIGINFO,
        .sa_restorer = NULL
      };
    
      sigaction(SIGTERM, &action, NULL);
      sleep(60);
    
      return 0;
    }
    

    Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

    How do you get the length of a string?

    same way you do it in javascript:

    "something".length

    how to stop a running script in Matlab

    One solution I adopted--for use with java code, but the concept is the same with mexFunctions, just messier--is to return a FutureValue and then loop while FutureValue.finished() or whatever returns true. The actual code executes in another thread/process. Wrapping a try,catch around that and a FutureValue.cancel() in the catch block works for me.

    In the case of mex functions, you will need to return somesort of pointer (as an int) that points to a struct/object that has all the data you need (native thread handler, bool for complete etc). In the case of a built in mexFunction, your mexFunction will most likely need to call that mexFunction in the separate thread. Mex functions are just DLLs/shared objects after all.

    PseudoCode

    FV = mexLongProcessInAnotherThread();
    try
      while ~mexIsDone(FV);
        java.lang.Thread.sleep(100); %pause has a memory leak
        drawnow; %allow stdout/err from mex to display in command window
      end
    catch
      mexCancel(FV);
    end
    

    ng-repeat :filter by single field

    Specify the property in filter, of object on which you want to apply filter:

    //Suppose Object
    var users = [{
      "firstname": "XYZ",
      "lastname": "ABC",
      "Address": "HOUSE NO-1, Example Street, Example Town"
    },
    {
      "firstname": "QWE",
      "lastname": "YUIKJH",
      "Address": "HOUSE NO-11, Example Street1, Example Town1"
    }]
    

    But you want to apply filter only on firstname

    <input type = "text" ng-model = "first_name_model"/>
    <div ng-repeat="user in users| filter:{ firstname: first_name_model}">
    

    Difference between using Throwable and Exception in a try catch

    The first one catches all subclasses of Throwable (this includes Exception and Error), the second one catches all subclasses of Exception.

    Error is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception is programmatically recoverable. Its subclass RuntimeException indicates a programming error and is usually not to be caught as well.

    npm install error from the terminal

    I had this problem when trying to run 'npm install' in a Terminal window which had been opened before installing Node.js.

    Opening a new Terminal window (i.e. bash session) worked. (Presumably this provided the correct environment variables for npm to run correctly.)

    How can I scroll up more (increase the scroll buffer) in iTerm2?

    There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal or you can just pump up number of lines that you want to have in history in the same place.

    load external URL into modal jquery ui dialog

    var page = "http://somurl.com/asom.php.aspx";
    
    var $dialog = $('<div></div>')
                   .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                   .dialog({
                       autoOpen: false,
                       modal: true,
                       height: 625,
                       width: 500,
                       title: "Some title"
                   });
    $dialog.dialog('open');
    

    Use this inside a function. This is great if you really want to load an external URL as an IFRAME. Also make sure that in you custom jqueryUI you have the dialog.

    Insert/Update/Delete with function in SQL Server

    Functions in SQL Server, as in mathematics, can not be used to modify the database. They are intended to be read only and can help developer to implement command-query separation. In other words, asking a question should not change the answer. When your program needs to modify the database use a stored procedure instead.

    Rotating a view in Android

    @Ichorus's answer is correct for views, but if you want to draw rotated rectangles or text, you can do the following in your onDraw (or onDispatchDraw) callback for your view:

    (note that theta is the angle from the x axis of the desired rotation, pivot is the Point that represents the point around which we want the rectangle to rotate, and horizontalRect is the rect's position "before" it was rotated)

    canvas.save();
    canvas.rotate(theta, pivot.x, pivot.y);
    canvas.drawRect(horizontalRect, paint);
    canvas.restore();
    

    jQuery checkbox event handling

    I have try the code from first answer, it not working but I have play around and this work for me

    $('#vip').change(function(){
        if ($(this).is(':checked')) {
            alert('checked');
        } else {
            alert('uncheck');
        }
    });
    

    PHP Foreach Arrays and objects

    Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:

    foreach ($arr as $item) {
        echo $item->sm_id;
    }
    

    In this example each of our values in the $arr will be accessed in order as $item. So we can print our values directly off of that. We could also include the index if we wanted:

    foreach ($arr as $index => $item) {
        echo "Item at index {$index} has sm_id value {$item->sm_id}";
    }
    

    Can Python test the membership of multiple values in a list?

    Another way to do it:

    >>> set(['a','b']).issubset( ['b','a','foo','bar'] )
    True
    

    WAMP Server doesn't load localhost

    Change the port 80 to port 8080 and restart all services and access like localhost:8080/

    It will work fine.

    Pipe to/from the clipboard in Bash script

    xsel on Debian/Ubuntu/Mint

    # append to clipboard:
    cat 'the file with content' | xsel -ib
    
    # or type in the happy face :) and ...
    echo 'the happy face :) and content' | xsel -ib
    
    # show clipboard
    xsel -b
    
    # Get more info:
    man xsel
    

    Install

    sudo apt-get install xsel
    

    Linq style "For Each"

    There isn't anything built-in, but you can easily create your own extension method to do it:

    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (action == null) throw new ArgumentNullException("action");
    
        foreach (T item in source)
        {
            action(item);
        }
    }
    

    how to set image from url for imageView

    if you are making a RecyclerView and using an adapter, what worked for me was:

    @Override
    public void onBindViewHolder(ADAPTERVIEWHOLDER holder, int position) {
        MODEL model = LIST.get(position);
        holder.TEXTVIEW.setText(service.getTitle());
        holder.TEXTVIEW.setText(service.getDesc());
    
        Context context = holder.IMAGEVIEW.getContext();
        Picasso.with(context).load(model.getImage()).into(holder.IMAGEVIEW);
    }
    

    Is there a standard function to check for null, undefined, or blank variables in JavaScript?

    function isEmpty(value){
      return (value == null || value.length === 0);
    }
    

    This will return true for

    undefined  // Because undefined == null
    
    null
    
    []
    
    ""
    

    and zero argument functions since a function's length is the number of declared parameters it takes.

    To disallow the latter category, you might want to just check for blank strings

    function isEmpty(value){
      return (value == null || value === '');
    }
    

    Find which version of package is installed with pip

    As of pip 1.3, there is a pip show command.

    $ pip show Jinja2
    ---
    Name: Jinja2
    Version: 2.7.3
    Location: /path/to/virtualenv/lib/python2.7/site-packages
    Requires: markupsafe
    

    In older versions, pip freeze and grep should do the job nicely.

    $ pip freeze | grep Jinja2
    Jinja2==2.7.3
    

    What is the use of <<<EOD in PHP?

    That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

    The HTML in your example will be:

        <tr>
          <td>TEST</td>
        </tr>
    

    Read the PHP documentation that explains it.

    Access to Image from origin 'null' has been blocked by CORS policy

    A solution to this is to serve your code, and make it run on a server, you could use web server for chrome to easily serve your pages.

    Is there an easy way to reload css without reloading the page?

    There is absolutely no need to use jQuery for this. The following JavaScript function will reload all your CSS files:

    function reloadCss()
    {
        var links = document.getElementsByTagName("link");
        for (var cl in links)
        {
            var link = links[cl];
            if (link.rel === "stylesheet")
                link.href += "";
        }
    }
    

    Creating an XmlNode/XmlElement in C# without an XmlDocument?

    Why not consider creating your data class(es) as just a subclassed XmlDocument, then you get all of that for free. You don't need to serialize or create any off-doc nodes at all, and you get structure you want.

    If you want to make it more sophisticated, write a base class that is a subclass of XmlDocument, then give it basic accessors, and you're set.

    Here's a generic type I put together for a project...

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using System.IO;
    
    namespace FWFWLib {
        public abstract class ContainerDoc : XmlDocument {
    
            protected XmlElement root = null;
            protected const string XPATH_BASE = "/$DATA_TYPE$";
            protected const string XPATH_SINGLE_FIELD = "/$DATA_TYPE$/$FIELD_NAME$";
    
            protected const string DOC_DATE_FORMAT = "yyyyMMdd";
            protected const string DOC_TIME_FORMAT = "HHmmssfff";
            protected const string DOC_DATE_TIME_FORMAT = DOC_DATE_FORMAT + DOC_TIME_FORMAT;
    
            protected readonly string datatypeName = "containerDoc";
            protected readonly string execid = System.Guid.NewGuid().ToString().Replace( "-", "" );
    
            #region startup and teardown
            public ContainerDoc( string execid, string datatypeName ) {
                root = this.DocumentElement;
                this.datatypeName = datatypeName;
                this.execid = execid;
                if( null == datatypeName || "" == datatypeName.Trim() ) {
                    throw new InvalidDataException( "Data type name can not be blank" );
                }
                Init();
            }
    
            public ContainerDoc( string datatypeName ) {
                root = this.DocumentElement;
                this.datatypeName = datatypeName;
                if( null == datatypeName || "" == datatypeName.Trim() ) {
                    throw new InvalidDataException( "Data type name can not be blank" );
                }
                Init();
            }
    
            private ContainerDoc() { /*...*/ }
    
            protected virtual void Init() {
                string basexpath = XPATH_BASE.Replace( "$DATA_TYPE$", datatypeName );
                root = (XmlElement)this.SelectSingleNode( basexpath );
                if( null == root ) {
                    root = this.CreateElement( datatypeName );
                    this.AppendChild( root );
                }
                SetFieldValue( "createdate", DateTime.Now.ToString( DOC_DATE_FORMAT ) );
                SetFieldValue( "createtime", DateTime.Now.ToString( DOC_TIME_FORMAT ) );
            }
            #endregion
    
            #region setting/getting data fields
            public virtual void SetFieldValue( string fieldname, object val ) {
                if( null == fieldname || "" == fieldname.Trim() ) {
                    return;
                }
                fieldname = fieldname.Replace( " ", "_" ).ToLower();
                string xpath = XPATH_SINGLE_FIELD.Replace( "$FIELD_NAME$", fieldname ).Replace( "$DATA_TYPE$", datatypeName );
                XmlNode node = this.SelectSingleNode( xpath );
                if( null != node ) {
                    if( null != val ) {
                        node.InnerText = val.ToString();
                    }
                } else {
                    node = this.CreateElement( fieldname );
                    if( null != val ) {
                        node.InnerText = val.ToString();
                    }
                    root.AppendChild( node );
                }
            }
    
            public virtual string FieldValue( string fieldname ) {
                if( null == fieldname ) {
                    fieldname = "";
                }
                fieldname = fieldname.ToLower().Trim();
                string rtn = "";
                XmlNode node = this.SelectSingleNode( XPATH_SINGLE_FIELD.Replace( "$FIELD_NAME$", fieldname ).Replace( "$DATA_TYPE$", datatypeName ) );
                if( null != node ) {
                    rtn = node.InnerText;
                }
                return rtn.Trim();
            }
    
            public virtual string ToXml() {
                return this.OuterXml;
            }
    
            public override string ToString() {
                return ToXml();
            }
            #endregion
    
            #region io
            public void WriteTo( string filename ) {
                TextWriter tw = new StreamWriter( filename );
                tw.WriteLine( this.OuterXml );
                tw.Close();
                tw.Dispose();
            }
    
            public void WriteTo( Stream strm ) {
                TextWriter tw = new StreamWriter( strm );
                tw.WriteLine( this.OuterXml );
                tw.Close();
                tw.Dispose();
            }
    
            public void WriteTo( TextWriter writer ) {
                writer.WriteLine( this.OuterXml );
            }
            #endregion
    
        }
    }
    

    SQL Server: Error converting data type nvarchar to numeric

    You might need to revise the data in the column, but anyway you can do one of the following:-

    1- check if it is numeric then convert it else put another value like 0

    Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
    THEN CONVERT(DECIMAL(18,2),COLUMNA) 
    ELSE 0 END AS COLUMNA
    

    2- select only numeric values from the column

    SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
    where Isnumeric(COLUMNA) = 1
    

    Command line .cmd/.bat script, how to get directory of running script

    Raymond Chen has a few ideas:

    https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573

    Quoted here in full because MSDN archives tend to be somewhat unreliable:

    The easy way is to use the %CD% pseudo-variable. It expands to the current working directory.

    set OLDDIR=%CD%
    .. do stuff ..
    chdir /d %OLDDIR% &rem restore current directory

    (Of course, directory save/restore could more easily have been done with pushd/popd, but that's not the point here.)

    The %CD% trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.

    set _=%CD%\curfile.txt
    cd ... some other directory ...
    somecommand args %_% args

    (I like to use %_% as my scratch environment variable.)

    Type SET /? to see the other pseudo-variables provided by the command processor.

    Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):

    http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741

    This covers the use of %~dp0:

    If you want to know where the batch file lives: %~dp0

    %0 is the name of the batch file. ~dp gives you the drive and path of the specified argument.

    Getting fb.me URL

    You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com

    What is difference between functional and imperative programming languages?

    • Imperative Languages:

    • Efficient execution

    • Complex semantics

    • Complex syntax

    • Concurrency is programmer designed

    • Complex testing, has no referential transparency, has side effects

    • Has state

    • Functional Languages:

    • Simple semantics

    • Simple syntax

    • Less efficient execution

    • Programs can automatically be made concurrent

    • Simple testing, has referential transparency, has no side effects

    • Has no state

    jQuery ID starts with

    Here you go:

    $('td[id^="' + value +'"]')
    

    so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

    Note that the quotes are mandatory: [id^="...."].

    Source: http://api.jquery.com/attribute-starts-with-selector/

    Represent space and tab in XML tag

    For me, to make it work I need to encode hex value of space within CDATA xml element, so that post parsing it adds up just as in the htm webgae & when viewed in browser just displays a space!. ( all above ideas & answers are useful )

    <my-xml-element><![CDATA[&#x20;]]></my-xml-element>
    

    Add an object to a python list

    You need to create a copy of the list before you modify its contents. A quick shortcut to duplicate a list is this:

    mylist[:]
    

    Example:

    >>> first = [1,2,3]
    >>> second = first[:]
    >>> second.append(4)
    >>> first
    [1, 2, 3]
    >>> second
    [1, 2, 3, 4]
    

    And to show the default behavior that would modify the orignal list (since a name in Python is just a reference to the underlying object):

    >>> first = [1,2,3]
    >>> second = first
    >>> second.append(4)
    >>> first
    [1, 2, 3, 4]
    >>> second
    [1, 2, 3, 4]
    

    Note that this only works for lists. If you need to duplicate the contents of a dictionary, you must use copy.deepcopy() as suggested by others.

    HTML Text with tags to formatted text in an Excel cell

    I know this thread is ancient, but after assigning the innerHTML, ExecWB worked for me:

    _x000D_
    _x000D_
    .ExecWB 17, 0_x000D_
    'Select all contents in browser_x000D_
    .ExecWB 12, 2_x000D_
    'Copy them
    _x000D_
    _x000D_
    _x000D_

    And then just paste the contents into Excel. Since these methods are prone to runtime errors, but work fine after one or two tries in debug mode, you might have to tell Excel to try again if it runs into an error. I solved this by adding this error handler to the sub, and it works fine:

    _x000D_
    _x000D_
    Sub ApplyHTML()_x000D_
      On Error GoTo ErrorHandler_x000D_
        ..._x000D_
      Exit Sub_x000D_
    _x000D_
    ErrorHandler:_x000D_
        Resume _x000D_
        'I.e. re-run the line of code that caused the error_x000D_
    Exit Sub_x000D_
         _x000D_
    End Sub
    _x000D_
    _x000D_
    _x000D_

    How can I convert an Int to a CString?

    If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

    CString str;
    _itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
    str.ReleaseBuffer();
    

    it should be slightly faster since it doesn't need to parse an input format.

    how to use DEXtoJar

    1. Download dex2jar https://code.google.com/p/dex2jar/downloads/list
    2. Run dex2jar on apk d2j-dex2jar.sh someApk.apk
    3. open jar file in JD GUI http://jd.benow.ca/

    Follow this guide: https://code.google.com/p/dex2jar/wiki/UserGuide

    --Update 10/11/2016--

    Found this ClassyShark from Google's github pretty easy to view code from APK.

    https://github.com/google/android-classyshark

    // make sure that you downloaded release https://github.com/pxb1988/dex2jar/releases (for the ppl who coldnt find this link in /dex2jar/downloads/list

    Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

    Try the below,

    1. Close android studio
    2. Then delete .iml , .idea files
    3. Open again the android studio
    4. Sync with Gradle.

    mongodb how to get max value from collections

    Folks you can see what the optimizer is doing by running a plan. The generic format of looking into a plan is from the MongoDB documentation . i.e. Cursor.plan(). If you really want to dig deeper you can do a cursor.plan(true) for more details.

    Having said that if you have an index, your db.col.find().sort({"field":-1}).limit(1) will read one index entry - even if the index is default ascending and you wanted the max entry and one value from the collection.

    In other words the suggestions from @yogesh is correct.

    Thanks - Sumit

    How can I declare and use Boolean variables in a shell script?

    This is a speed test about different ways to test "Boolean" values in Bash:

    #!/bin/bash
    rounds=100000
    
    b=true # For true; b=false for false
    type -a true
    time for i in $(seq $rounds); do command $b; done
    time for i in $(seq $rounds); do $b; done
    time for i in $(seq $rounds); do [ "$b" == true ]; done
    time for i in $(seq $rounds); do test "$b" == true; done
    time for i in $(seq $rounds); do [[ $b == true ]]; done
    
    b=x; # Or any non-null string for true; b='' for false
    time for i in $(seq $rounds); do [ "$b" ]; done
    time for i in $(seq $rounds); do [[ $b ]]; done
    
    b=1 # Or any non-zero integer for true; b=0 for false
    time for i in $(seq $rounds); do ((b)); done
    

    It would print something like

    true is a shell builtin
    true is /bin/true
    
    real    0m0,815s
    user    0m0,767s
    sys     0m0,029s
    
    real    0m0,562s
    user    0m0,509s
    sys     0m0,022s
    
    real    0m0,829s
    user    0m0,782s
    sys     0m0,008s
    
    real    0m0,782s
    user    0m0,730s
    sys     0m0,015s
    
    real    0m0,402s
    user    0m0,391s
    sys     0m0,006s
    
    real    0m0,668s
    user    0m0,633s
    sys     0m0,008s
    
    real    0m0,344s
    user    0m0,311s
    sys     0m0,016s
    
    real    0m0,367s
    user    0m0,347s
    sys     0m0,017s
    

    Calculating a 2D Vector's Cross Product

    Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus the scalar returned is the Z value of the 3D cross product vector).

    Note that the magnitude of the vector resulting from 3D cross product is also equal to the area of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors.

    Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the "give me a perpendicular vector" sense.

    Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another.

    Hope this helps...

    Can I find events bound on an element with jQuery?

    You can now simply get a list of event listeners bound to an object by using the javascript function getEventListeners().

    For example type the following in the dev tools console:

    // Get all event listners bound to the document object
    getEventListeners(document);
    

    Drop all data in a pandas dataframe

    If your goal is to drop the dataframe, then you need to pass all columns. For me: the best way is to pass a list comprehension to the columns kwarg. This will then work regardless of the different columns in a df.

    import pandas as pd
    
    web_stats = {'Day': [1, 2, 3, 4, 2, 6],
                 'Visitors': [43, 43, 34, 23, 43, 23],
                 'Bounce_Rate': [3, 2, 4, 3, 5, 5]}
    df = pd.DataFrame(web_stats)
    
    df.drop(columns=[i for i in check_df.columns])
    

    $http.get(...).success is not a function

    The .success syntax was correct up to Angular v1.4.3.

    For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

    Using the then() method, attach a callback function to the returned promise.

    Something like this:

    app.controller('MainCtrl', function ($scope, $http){
       $http({
          method: 'GET',
          url: 'api/url-api'
       }).then(function (response){
    
       },function (error){
    
       });
    }
    

    See reference here.

    Shortcut methods are also available.

    $http.get('api/url-api').then(successCallback, errorCallback);
    
    function successCallback(response){
        //success code
    }
    function errorCallback(error){
        //error code
    }
    

    The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

    The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

    C++: Rounding up to the nearest multiple of a number

    float roundUp(float number, float fixedBase) {
        if (fixedBase != 0 && number != 0) {
            float sign = number > 0 ? 1 : -1;
            number *= sign;
            number /= fixedBase;
            int fixedPoint = (int) ceil(number);
            number = fixedPoint * fixedBase;
            number *= sign;
        }
        return number;
    }
    

    This works for any float number or base (e.g. you can round -4 to the nearest 6.75). In essence it is converting to fixed point, rounding there, then converting back. It handles negatives by rounding AWAY from 0. It also handles a negative round to value by essentially turning the function into roundDown.

    An int specific version looks like:

    int roundUp(int number, int fixedBase) {
        if (fixedBase != 0 && number != 0) {
            int sign = number > 0 ? 1 : -1;
            int baseSign = fixedBase > 0 ? 1 : 0;
            number *= sign;
            int fixedPoint = (number + baseSign * (fixedBase - 1)) / fixedBase;
            number = fixedPoint * fixedBase;
            number *= sign;
        }
        return number;
    }
    

    Which is more or less plinth's answer, with the added negative input support.

    Drop data frame columns by name

    DF <- data.frame(
      x=1:10,
      y=10:1,
      z=rep(5,10),
      a=11:20
    )
    DF
    

    Output:

        x  y z  a
    1   1 10 5 11
    2   2  9 5 12
    3   3  8 5 13
    4   4  7 5 14
    5   5  6 5 15
    6   6  5 5 16
    7   7  4 5 17
    8   8  3 5 18
    9   9  2 5 19
    10 10  1 5 20
    

    DF[c("a","x")] <- list(NULL)
    

    Output:

            y z
        1  10 5
        2   9 5
        3   8 5
        4   7 5
        5   6 5
        6   5 5
        7   4 5
        8   3 5    
        9   2 5
        10  1 5
    

    What's a decent SFTP command-line client for windows?

    LFTP is great, however it is Linux only. You can find the Windows port here. Never tried though.

    Achtunq, it uses Cygwin, but everything is included in the bundle.

    How to multiply a BigDecimal by an integer in Java

    First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

    Second, it takes another BigDecimal as the argument, not an int.

    If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

    How to lay out Views in RelativeLayout programmatically?

    From what I've been able to piece together, you have to add the view using LayoutParams.

    LinearLayout linearLayout = new LinearLayout(this);
    
    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    
    parentView.addView(linearLayout, relativeParams);
    

    All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

    TextView tv1 = new TextView(this);
    tv1.setId(1);
    TextView tv2 = new TextView(this);
    tv2.setId(2);
    

    Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

    How to beautify JSON in Python?

    Try underscore-cli:

    cat myfile.json | underscore print --color
    

    It's a pretty nifty tool that can elegantly do a lot of manipulation of structured data, execute js snippets, fill templates, etc. It's ridiculously well documented, polished, and ready for serious use. And I wrote it. :)

    what is the difference between XSD and WSDL

    XSD is to validate the document, and contains metadata about the XML whereas WSDL is to describe the webservice location and operations.

    grep using a character vector with multiple patterns

    This should work:

    grep(pattern = 'A1|A9|A6', x = myfile$Letter)
    

    Or even more simply:

    library(data.table)
    myfile$Letter %like% 'A1|A9|A6'
    

    Regular Expression for password validation

    There seems to be a lot of confusion here. The answers I see so far don't correctly enforce the 1+ number/1+ lowercase/1+ uppercase rule, meaning that passwords like abc123, 123XYZ, or AB*&^# would still be accepted. Preventing all-lowercase, all-caps, or all-digits is not enough; you have to enforce the presence of at least one of each.

    Try the following:

    ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$
    

    If you also want to require at least one special character (which is probably a good idea), try this:

    ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$
    

    The .{8,15} can be made more restrictive if you wish (for example, you could change it to \S{8,15} to disallow whitespace), but remember that doing so will reduce the strength of your password scheme.

    I've tested this pattern and it works as expected. Tested on ReFiddle here: http://refiddle.com/110


    Edit: One small note, the easiest way to do this is with 3 separate regexes and the string's Length property. It's also easier to read and maintain, so do it that way if you have the option. If this is for validation rules in markup, though, you're probably stuck with a single regex.

    Calculate difference in keys contained in two Python dictionaries

    There is an other question in stackoverflow about this argument and i have to admit that there is a simple solution explained: the datadiff library of python helps printing the difference between two dictionaries.

    How to make g++ search for header files in a specific directory?

    it's simple, use the "-B" option to add .h files' dir to search path.

    E.g. g++ -B /header_file.h your.cpp -o bin/your_command

    How to stop a JavaScript for loop?

    The logic is incorrect. It would always return the result of last element in the array.

    remIndex = -1;
    
    for (i = 0; i < remSize.length; i++) {      
        if (remSize[i].size == remData.size) {
            remIndex = i
            break;
        }
    }
    

    WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

    An other way of CASE:

    SELECT *  
    FROM MyTable
    WHERE 1 = CASE WHEN @myParm = value1 AND MyColumn IS NULL     THEN 1 
                   WHEN @myParm = value2 AND MyColumn IS NOT NULL THEN 1 
                   WHEN @myParm = value3                          THEN 1 
              END
    

    How to set image to fit width of the page using jsPDF?

            var width = doc.internal.pageSize.width;    
            var height = doc.internal.pageSize.height;
    

    How do I programmatically click a link with javascript?

    You could just redirect them to another page. Actually making it literally click a link and travel to it seems unnessacary, but I don't know the whole story.

    Try-catch block in Jenkins pipeline script

    try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

    This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

    JPA eager fetch does not join

    "mxc" is right. fetchType just specifies when the relation should be resolved.

    To optimize eager loading by using an outer join you have to add

    @Fetch(FetchMode.JOIN)
    

    to your field. This is a hibernate specific annotation.

    Log4net rolling daily filename with date in the file name

    I moved configuration to code to enable easy modification from CI using system variable. I used this code for file name and result is 'Log_03-23-2020.log'

                log4net.Repository.ILoggerRepository repository = LogManager.GetRepository(Assembly.GetEntryAssembly());
                Hierarchy hierarchy = (Hierarchy)repository;
                PatternLayout patternLayout = new PatternLayout();
                patternLayout.ConversionPattern = "%date %level - %message%newline%exception";
                patternLayout.ActivateOptions();
    
                RollingFileAppender roller = new RollingFileAppender();
                roller.AppendToFile = true;
                roller.File = "Log_";
                roller.DatePattern = "MM-dd-yyyy'.log'";
                roller.Layout = patternLayout;
                roller.MaxFileSize = 1024*1024*10;
                roller.MaxSizeRollBackups = 10;
                roller.StaticLogFileName = false;
                roller.RollingStyle = RollingFileAppender.RollingMode.Composite;
                roller.ActivateOptions();
                hierarchy.Root.AddAppender(roller);
    
    

    adding line break

    The correct answer is to use Environment.NewLine, as you've noted. It is environment specific and provides clarity over "\r\n" (but in reality makes no difference).

    foreach (var item in FirmNameList) 
    {
        if (FirmNames != "")
        {
            FirmNames += ", " + Environment.NewLine;
        }
        FirmNames += item; 
    } 
    

    Clear Cache in Android Application programmatically

    I am not sure but I sow this code too. this cod will work faster and in my mind its simple too. just get your apps cache directory and delete all files in directory

    public boolean clearCache() {
        try {
    
            // create an array object of File type for referencing of cache files   
            File[] files = getBaseContext().getCacheDir().listFiles();
    
            // use a for etch loop to delete files one by one
            for (File file : files) {
    
                 /* you can use just [ file.delete() ] function of class File
                  * or use if for being sure if file deleted
                  * here if file dose not delete returns false and condition will
                  * will be true and it ends operation of function by return 
                  * false then we will find that all files are not delete
                  */
                 if (!file.delete()) {
                     return false;         // not success
                 }
            }
    
            // if for loop completes and process not ended it returns true   
            return true;      // success of deleting files
    
        } catch (Exception e) {}
    
        // try stops deleting cache files
        return false;       // not success 
    }
    

    It gets all of cache files in File array by getBaseContext().getCacheDir().listFiles() and then deletes one by one in a loop by file.delet() method

    JavaScript naming conventions

    I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.

    Java error: Only a type can be imported. XYZ resolves to a package

    If you spell the class name wrong or the class isn't on the classpath, the JSP processor will say it "resolves to a package" rather than that it doesn't exist. This was driving me crazy today as I kept not seeing a typo I'd made.

    SQL JOIN vs IN performance?

    Funny you mention that, I did a blog post on this very subject.

    See Oracle vs MySQL vs SQL Server: Aggregation vs Joins

    Short answer: you have to test it and individual databases vary a lot.

    How do I remove  from the beginning of a file?

    Use Total Commander to search for all BOMed files:

    Elegant way to search for UTF-8 files with BOM?

    • Open these files in some proper editor (that recognizes BOM) like Eclipse.

    • Change the file's encoding to ISO (right click, properties).

    • Cut  from the beginning of the file, save

    • Change the file's encoding back to UTF-8

    ...and do not even think about using n...d again!

    What is the use of join() in Python threading?

    There are a few reasons for the main thread (or any other thread) to join other threads

    1. A thread may have created or holding (locking) some resources. The join-calling thread may be able to clear the resources on its behalf

    2. join() is a natural blocking call for the join-calling thread to continue after the called thread has terminated.

    If a python program does not join other threads, the python interpreter will still join non-daemon threads on its behalf.

    Class name does not name a type in C++

    The preprocessor inserts the contents of the files A.h and B.h exactly where the include statement occurs (this is really just copy/paste). When the compiler then parses A.cpp, it finds the declaration of class A before it knows about class B. This causes the error you see. There are two ways to solve this:

    1. Include B.h in A.h. It is generally a good idea to include header files in the files where they are needed. If you rely on indirect inclusion though another header, or a special order of includes in the compilation unit (cpp-file), this will only confuse you and others as the project gets bigger.
    2. If you use member variable of type B in class A, the compiler needs to know the exact and complete declaration of B, because it needs to create the memory-layout for A. If, on the other hand, you were using a pointer or reference to B, then a forward declaration would suffice, because the memory the compiler needs to reserve for a pointer or reference is independent of the class definition. This would look like this:

      class B; // forward declaration        
      class A {
      public:
          A(int id);
      private:
          int _id;
          B & _b;
      };
      

      This is very useful to avoid circular dependencies among headers.

    I hope this helps.

    Binding an enum to a WinForms combo box, and then setting it

    comboBox1.SelectedItem = MyEnum.Something;
    

    should work just fine ... How can you tell that SelectedItem is null?

    Eclipse error: R cannot be resolved to a variable

    In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.

    AngularJS: Service vs provider vs factory

    As pointed out by several people here correctly a factory, provider, service, and even value and constant are versions of the same thing. You can dissect the more general provider into all of them. Like so:

    enter image description here

    Here's the article this image is from:

    http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

    Windows batch file file download from a URL

    Downloading files in PURE BATCH... Without any JScript, VBScript, Powershell, etc... Only pure Batch!

    Some people are saying it's not possible of downloading files with a batch script without using any JScript or VBScript, etc... But they are definitely wrong!

    Here is a simple method that seems to work pretty well for downloading files in your batch scripts. It should be working on almost any file's URL. It is even possible to use a proxy server if you need it.

    For downloading files, we can use BITSADMIN.EXE from the Windows system. There is no need for downloading/installing anything or using any JScript or VBScript, etc. Bitsadmin.exe is present on most Windows versions, probably from XP to Windows 10.

    Enjoy!


    USAGE:

    You can use the BITSADMIN command directly, like this:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND "http://example.com/File.zip" "C:\Downloads\File.zip"

    Proxy Server:
    For connecting using a proxy, use this command before downloading.
    bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080"

    Click this LINK if you want more info about BITSadmin.exe


    TROUBLESHOOTING:
    If you get this error: "Unable to connect to BITS - 0x80070422"
    Make sure the windows service "Background Intelligent Transfer Service (BITS)" is enabled and try again. (It should be enabled by default.)


    CUSTOM FUNCTIONS
    Call :DOWNLOAD_FILE "URL"
    Call :DOWNLOAD_PROXY_ON "SERVER:PORT"
    Call :DOWNLOAD_PROXY_OFF

    I made these 3 functions for simplifying the bitsadmin commands. It's easier to use and remember. It can be particularly useful if you are using it multiple times in your scripts.

    PLEASE NOTE...
    Before using these functions, you will first need to copy them from CUSTOM_FUNCTIONS.CMD to the end of your script. There is also a complete example: DOWNLOAD-EXAMPLE.CMD

    :DOWNLOAD_FILE "URL"
    The main function, will download files from URL.

    :DOWNLOAD_PROXY_ON "SERVER:PORT"
    (Optional) You can use this function if you need to use a proxy server.
    Calling the :DOWNLOAD_PROXY_OFF function will disable the proxy server.

    EXAMPLE:
    CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"
    CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:\Downloads\File.zip"
    CALL :DOWNLOAD_PROXY_OFF


    CUSTOM_FUNCTIONS.CMD

    :DOWNLOAD_FILE
        rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
        bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
    GOTO :EOF
    
    :DOWNLOAD_PROXY_ON
        rem FUNCTION FOR USING A PROXY SERVER:
        bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
    GOTO :EOF
    
    :DOWNLOAD_PROXY_OFF
        rem FUNCTION FOR STOP USING A PROXY SERVER:
        bitsadmin /setproxysettings mydownloadjob NO_PROXY
    GOTO :EOF
    

    DOWNLOAD-EXAMPLE.CMD

    @ECHO OFF
    SETLOCAL
    
    rem FOR DOWNLOADING FILES, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
    rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.
    
    
    :SETUP
    
    rem URL (5MB TEST FILE):
    SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"
    
    rem SAVE IN CUSTOM LOCATION:
    rem SET "SAVING_TO=C:\Folder\5MB.zip"
    
    rem SAVE IN THE CURRENT DIRECTORY
    SET "SAVING_TO=5MB.zip"
    SET "SAVING_TO=%~dp0%SAVING_TO%"
    
    :MAIN
    
    ECHO.
    ECHO DOWNLOAD SCRIPT EXAMPLE
    ECHO.
    ECHO FILE URL: "%FILE_URL%"
    ECHO SAVING TO:  "%SAVING_TO%"
    ECHO.
    
    rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
    rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"
     
    rem THE MAIN DOWNLOAD COMMAND:
    CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"
    
    rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
    rem CALL :DOWNLOAD_PROXY_OFF
    
    :RESULT
    ECHO.
    IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
    IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
    ECHO.
    
    :EXIT_SCRIPT
    PAUSE
    EXIT /B
    
    
    
    
    rem FUNCTIONS SECTION
    
    
    :DOWNLOAD_FILE
        rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
        bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
    GOTO :EOF
    
    :DOWNLOAD_PROXY_ON
        rem FUNCTION FOR USING A PROXY SERVER:
        bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
    GOTO :EOF
    
    :DOWNLOAD_PROXY_OFF
        rem FUNCTION FOR STOP USING A PROXY SERVER:
        bitsadmin /setproxysettings mydownloadjob NO_PROXY
    GOTO :EOF
    

    gcc error: wrong ELF class: ELFCLASS64

    It turns out the compiler version I was using did not match the compiled version done with the coreset.o.

    One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.

    npm can't find package.json

    Generate package.json without having it ask any questions. I ran the below comment in Mac and Windows under the directory that I would like to create package.json and it works

    $ npm init -y
    
    Wrote to C:\workspace\package.json:
    
    {
      "name": "workspace",
      "version": "1.0.0",
      "description": "",
      "main": "builder.js",
      "dependencies": {
        "jasmine-spec-reporter": "^4.2.1",
        "selenium-webdriver": "^4.0.0-alpha.5"
      },
      "devDependencies": {},
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }
    

    Setting a checkbox as checked with Vue.js

    In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

    <input
      type="checkbox"
      v-model="toggle"
      true-value="yes"
      false-value="no"
    >
    

    POST string to ASP.NET Web Api application - returns null

    You seem to have used some [Authorize] attribute on your Web API controller action and I don't see how this is relevant to your question.

    So, let's get into practice. Here's a how a trivial Web API controller might look like:

    public class TestController : ApiController
    {
        public string Post([FromBody] string value)
        {
            return value;
        }
    }
    

    and a consumer for that matter:

    class Program
    {
        static void Main()
        {
            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                var data = "=Short test...";
                var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
                Console.WriteLine(result);
            }
        }
    }
    

    You will undoubtedly notice the [FromBody] decoration of the Web API controller attribute as well as the = prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.

    As far as the [Authorize] attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post that I wrote on this topic interesting to get you started.

    And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.

    Convert a row of a data frame to vector

    Here is a dplyr based option:

    newV = df %>% slice(1) %>% unlist(use.names = FALSE)
    
    # or slightly different:
    newV = df %>% slice(1) %>% unlist() %>% unname()
    

    Flask-SQLAlchemy how to delete all rows in a single table

    DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:

    num_rows_deleted = db.session.query(Model).delete()
    

    Also, don't forget that the deletion won't take effect until you commit, as in this snippet:

    try:
        num_rows_deleted = db.session.query(Model).delete()
        db.session.commit()
    except:
        db.session.rollback()
    

    IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

    Many JavaScript libraries (especially non-recent ones) do not handle IE9 well because it breaks with IE8 in the handling of a lot of things.

    JS code that sniffs for IE will fail quite frequently in IE9, unless such code is rewritten to handle IE9 specifically.

    Before the JS code is updated, you should use the "X-UA-Compatible" meta tag to force your web page into IE8 mode.

    EDIT: Can't believe that, 3 years later and we're onto IE11, and there are still up-votes for this. :-) Many JS libraries should now at least support IE9 natively and most support IE10, so it is unlikely that you'll need the meta tag these days, unless you don't intend to upgrade your JS library. But beware that IE10 changes things regarding to cross-domain scripting and some CDN-based library code breaks. Check your library version. For example, Dojo 1.9 on the CDN will break on IE10, but 1.9.1 solves it.

    EDIT 2: You REALLY need to get your acts together now. We are now in mid-2014!!! I am STILL getting up-votes for this! Revise your sites to get rid of old-IE hard-coded dependencies!

    Sigh... If I had known that this would be by far my most popular answer, I'd probably have spent more time polishing it...

    EDIT 3: It is now almost 2016. Upvotes still ticking up... I guess there are lots of legacy code out there... One day our programs will out-live us...

    Removing input background colour for Chrome autocomplete?

    This is my solution, I used transition and transition delay therefore I can have a transparent background on my input fields.

    input:-webkit-autofill,
    input:-webkit-autofill:hover,
    input:-webkit-autofill:focus,
    input:-webkit-autofill:active {
        -webkit-transition: "color 9999s ease-out, background-color 9999s ease-out";
        -webkit-transition-delay: 9999s;
    }
    

    JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

    The JWT aud (Audience) Claim

    According to RFC 7519:

    The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

    The Audience (aud) claim as defined by the spec is generic, and is application specific. The intended use is to identify intended recipients of the token. What a recipient means is application specific. An audience value is either a list of strings, or it can be a single string if there is only one aud claim. The creator of the token does not enforce that aud is validated correctly, the responsibility is the recipient's to determine whether the token should be used.

    Whatever the value is, when a recipient is validating the JWT and it wishes to validate that the token was intended to be used for its purposes, it MUST determine what value in aud identifies itself, and the token should only validate if the recipient's declared ID is present in the aud claim. It does not matter if this is a URL or some other application specific string. For example, if my system decides to identify itself in aud with the string: api3.app.com, then it should only accept the JWT if the aud claim contains api3.app.com in its list of audience values.

    Of course, recipients may choose to disregard aud, so this is only useful if a recipient would like positive validation that the token was created for it specifically.

    My interpretation based on the specification is that the aud claim is useful to create purpose-built JWTs that are only valid for certain purposes. For one system, this may mean you would like a token to be valid for some features but not for others. You could issue tokens that are restricted to only a certain "audience", while still using the same keys and validation algorithm.

    Since in the typical case a JWT is generated by a trusted service, and used by other trusted systems (systems which do not want to use invalid tokens), these systems simply need to coordinate the values they will be using.

    Of course, aud is completely optional and can be ignored if your use case doesn't warrant it. If you don't want to restrict tokens to being used by specific audiences, or none of your systems actually will validate the aud token, then it is useless.

    Example: Access vs. Refresh Tokens

    One contrived (yet simple) example I can think of is perhaps we want to use JWTs for access and refresh tokens without having to implement separate encryption keys and algorithms, but simply want to ensure that access tokens will not validate as refresh tokens, or vice-versa.

    By using aud, we can specify a claim of refresh for refresh tokens and a claim of access for access tokens upon creating these tokens. When a request is made to get a new access token from a refresh token, we need to validate that the refresh token was a genuine refresh token. The aud validation as described above will tell us whether the token was actually a valid refresh token by looking specifically for a claim of refresh in aud.

    OAuth Client ID vs. JWT aud Claim

    The OAuth Client ID is completely unrelated, and has no direct correlation to JWT aud claims. From the perspective of OAuth, the tokens are opaque objects.

    The application which accepts these tokens is responsible for parsing and validating the meaning of these tokens. I don't see much value in specifying OAuth Client ID within a JWT aud claim.

    How do I keep two side-by-side divs the same height?

    I just wanted to add to the great Flexbox solution described by Pavlo, that, in my case, I had two lists/columns of data that I wanted to display side-by-side with just a little spacing between, horizontally-centered inside an enclosing div. By nesting another div within the first (leftmost) flex:1 div and floating it right, I got just what I wanted. I couldn't find any other way to do this with consistent success at all viewport widths:

    <div style="display:flex">
        <div style="flex:1;padding-right:15px">
            <div style="float:right">
                [My Left-hand list of stuff]
            </div>
        </div>
    
        <div style="flex:1;padding-left:15px">
                [My Right-hand list of stuff]
        </div>
    </div>
    

    How to do 3 table JOIN in UPDATE query?

    Yes, you can do a 3 table join for an update statement. Here is an example :

        UPDATE customer_table c 
    
          JOIN  
              employee_table e
              ON c.city_id = e.city_id  
          JOIN 
              anyother_ table a
              ON a.someID = e.someID
    
        SET c.active = "Yes"
    
        WHERE c.city = "New york";
    

    PHP "php://input" vs $_POST

    If post data is malformed, $_POST will not contain anything. Yet, php://input will have the malformed string.

    For example there is some ajax applications, that do not form correct post key-value sequence for uploading a file, and just dump all the file as post data, without variable names or anything. $_POST will be empty, $_FILES empty also, and php://input will contain exact file, written as a string.

    How to get primary key column in Oracle?

    Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;
    

    (This will list the primary key and then)

    Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 
    

    (This will give you the column, here PK_XYZ is the primay key name)

    jQuery checkbox check/uncheck

    Use prop() instead of attr() to set the value of checked. Also use :checkbox in find method instead of input and be specific.

    Live Demo

    $("#news_list tr").click(function() {
        var ele = $(this).find('input');
        if(ele.is(':checked')){
            ele.prop('checked', false);
            $(this).removeClass('admin_checked');
        }else{
            ele.prop('checked', true);
            $(this).addClass('admin_checked');
        }
    });
    

    Use prop instead of attr for properties like checked

    As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method

    Configuring diff tool with .gitconfig

    Adding one of the blocks below works for me to use KDiff3 for my Windows and Linux development environments. It makes for a nice consistent cross-platform diff and merge tool.

    Linux

    [difftool "kdiff3"]
        path = /usr/bin/kdiff3
        trustExitCode = false
    [difftool]
        prompt = false
    [diff]
        tool = kdiff3
    [mergetool "kdiff3"]
        path = /usr/bin/kdiff3
        trustExitCode = false
    [mergetool]
        keepBackup = false
    [merge]
        tool = kdiff3
    

    Windows

    [difftool "kdiff3"]
        path = C:/Progra~1/KDiff3/kdiff3.exe
        trustExitCode = false
    [difftool]
        prompt = false
    [diff]
        tool = kdiff3
    [mergetool "kdiff3"]
        path = C:/Progra~1/KDiff3/kdiff3.exe
        trustExitCode = false
    [mergetool]
        keepBackup = false
    [merge]
        tool = kdiff3
    

    jquery ajax get responsetext from http url

    You simply must rewrite it like that:

    var response = '';
    $.ajax({ type: "GET",   
             url: "http://www.google.de",   
             async: false,
             success : function(text)
             {
                 response = text;
             }
    });
    
    alert(response);
    

    Xcode 4 - build output directory

    Keep derived data but use the DSTROOT to specify the destination.

    Use DEPLOYMENT_LOCATION to force deployment.

    Use the undocumented DWARF_DSYM_FOLDER_PATH to copy the dSYM over too.

    This allows you to use derived data location from xcodebuild and not have to do wacky stuff to find the app.

    xcodebuild -sdk "iphoneos" -workspace Foo.xcworkspace -scheme Foo -configuration "Debug" DEPLOYMENT_LOCATION=YES DSTROOT=tmp DWARF_DSYM_FOLDER_PATH=tmp build
    

    Required attribute HTML5

    A small note on custom attributes: HTML5 allows all kind of custom attributes, as long as they are prefixed with the particle data-, i.e. data-my-attribute="true".

    Should I use != or <> for not equal in T-SQL?

    Technically they function the same if you’re using SQL Server AKA T-SQL. If you're using it in stored procedures there is no performance reason to use one over the other. It then comes down to personal preference. I prefer to use <> as it is ANSI compliant.

    You can find links to the various ANSI standards at...

    http://en.wikipedia.org/wiki/SQL

    how do I get eclipse to use a different compiler version for Java?

    Just to clarify, do you have JAVA_HOME set as a system variable or set in Eclipse classpath variables? I'm pretty sure (but not totally sure!) that the system variable is used by the command line compiler (and Ant), but that Eclipse modifies this accroding to the JDK used

    JavaScript: Upload file

    Pure JS

    You can use fetch optionally with await-try-catch

    let photo = document.getElementById("image-file").files[0];
    let formData = new FormData();
         
    formData.append("photo", photo);
    fetch('/upload/image', {method: "POST", body: formData});
    

    _x000D_
    _x000D_
    async function SavePhoto(inp) 
    {
        let user = { name:'john', age:34 };
        let formData = new FormData();
        let photo = inp.files[0];      
             
        formData.append("photo", photo);
        formData.append("user", JSON.stringify(user)); 
        
        const ctrl = new AbortController()    // timeout
        setTimeout(() => ctrl.abort(), 5000);
        
        try {
           let r = await fetch('/upload/image', 
             {method: "POST", body: formData, signal: ctrl.signal}); 
           console.log('HTTP response code:',r.status); 
        } catch(e) {
           console.log('Huston we have problem...:', e);
        }
        
    }
    _x000D_
    <input id="image-file" type="file" onchange="SavePhoto(this)" >
    <br><br>
    Before selecting the file open chrome console > network tab to see the request details.
    <br><br>
    <small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
    
    <br><br>
    (in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
    _x000D_
    _x000D_
    _x000D_

    Old school approach - xhr

    let photo = document.getElementById("image-file").files[0];  // file from input
    let req = new XMLHttpRequest();
    let formData = new FormData();
    
    formData.append("photo", photo);                                
    req.open("POST", '/upload/image');
    req.send(formData);
    

    _x000D_
    _x000D_
    function SavePhoto(e) 
    {
        let user = { name:'john', age:34 };
        let xhr = new XMLHttpRequest();
        let formData = new FormData();
        let photo = e.files[0];      
        
        formData.append("user", JSON.stringify(user));   
        formData.append("photo", photo);
        
        xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
        xhr.timeout = 5000;
        xhr.open("POST", '/upload/image'); 
        xhr.send(formData);
    }
    _x000D_
    <input id="image-file" type="file" onchange="SavePhoto(this)" >
    <br><br>
    Choose file and open chrome console > network tab to see the request details.
    <br><br>
    <small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
    
    <br><br>
    (the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
    _x000D_
    _x000D_
    _x000D_

    SUMMARY

    • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
    • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
    • Instead of /upload/image you can use full address like http://.../upload/image.
    • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
    • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
    • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
    • This solutions should work on all major browsers.

    Java - Including variables within strings?

    You can always use String.format(....). i.e.,

    String string = String.format("A String %s %2d", aStringVar, anIntVar);
    

    I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.

    WPF Datagrid Get Selected Cell Value

    I'm extending the solution by Rushi to following (which solved the puzzle for me)

    var cellInfo = Grid1.SelectedCells[0];
    var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;
    

    Disable copy constructor

    If you don't mind multiple inheritance (it is not that bad, after all), you may write simple class with private copy constructor and assignment operator and additionally subclass it:

    class NonAssignable {
    private:
        NonAssignable(NonAssignable const&);
        NonAssignable& operator=(NonAssignable const&);
    public:
        NonAssignable() {}
    };
    
    class SymbolIndexer: public Indexer, public NonAssignable {
    };
    

    For GCC this gives the following error message:

    test.h: In copy constructor ‘SymbolIndexer::SymbolIndexer(const SymbolIndexer&)’:
    test.h: error: ‘NonAssignable::NonAssignable(const NonAssignable&)’ is private
    

    I'm not very sure for this to work in every compiler, though. There is a related question, but with no answer yet.

    UPD:

    In C++11 you may also write NonAssignable class as follows:

    class NonAssignable {
    public:
        NonAssignable(NonAssignable const&) = delete;
        NonAssignable& operator=(NonAssignable const&) = delete;
        NonAssignable() {}
    };
    

    The delete keyword prevents members from being default-constructed, so they cannot be used further in a derived class's default-constructed members. Trying to assign gives the following error in GCC:

    test.cpp: error: use of deleted function
              ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
    test.cpp: note: ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
              is implicitly deleted because the default definition would
              be ill-formed:
    

    UPD:

    Boost already has a class just for the same purpose, I guess it's even implemented in similar way. The class is called boost::noncopyable and is meant to be used as in the following:

    #include <boost/core/noncopyable.hpp>
    
    class SymbolIndexer: public Indexer, private boost::noncopyable {
    };
    

    I'd recommend sticking to the Boost's solution if your project policy allows it. See also another boost::noncopyable-related question for more information.

    SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

    You didn't bind all your bindings here

    $sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
    ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
    
    $st = $conn->prepare( $sql );
    $st->bindValue( ":art", $art, PDO::PARAM_INT );
    

    You've declared a binding called :numRows but you never actually bind anything to it.

    UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

    Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

    In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

    What is python's site-packages directory?

    site-packages is the target directory of manually built Python packages. When you build and install Python packages from source (using distutils, probably by executing python setup.py install), you will find the installed modules in site-packages by default.

    There are standard locations:

    • Unix (pure)1: prefix/lib/pythonX.Y/site-packages
    • Unix (non-pure): exec-prefix/lib/pythonX.Y/site-packages
    • Windows: prefix\Lib\site-packages

    1 Pure means that the module uses only Python code. Non-pure can contain C/C++ code as well.

    site-packages is by default part of the Python search path, so modules installed there can be imported easily afterwards.


    Useful reading

    Disable vertical scroll bar on div overflow: auto

    Add the following:

    body{
    overflow-y:hidden;
    }
    

    in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

    Example to get last article or any other element:

    document.querySelector("article:last-child")
    

    Determine whether an array contains a value

    I prefer simplicity:

    var days = [1, 2, 3, 4, 5];
    if ( 2 in days ) {console.log('weekday');}
    

    Check if a string is not NULL or EMPTY

    You don't necessarily have to use the [string]:: prefix. This works in the same way:

    if ($version)
    {
        $request += "/" + $version
    }
    

    A variable that is null or empty string evaluates to false.

    How to iterate over a column vector in Matlab?

    for i=1:length(list)
      elm = list(i);
      //do something with elm.
    

    Can I use Objective-C blocks as properties?

    @property (nonatomic, copy) void (^simpleBlock)(void);
    @property (nonatomic, copy) BOOL (^blockWithParamter)(NSString *input);
    

    If you are going to be repeating the same block in several places use a type def

    typedef void(^MyCompletionBlock)(BOOL success, NSError *error);
    @property (nonatomic) MyCompletionBlock completion;
    

    Can I have multiple :before pseudo-elements for the same element?

    I've resolved this using:

    .element:before {
        font-family: "Font Awesome 5 Free" , "CircularStd";
        content: "\f017" " Date";
    }
    

    Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

    jQuery and TinyMCE: textarea value doesn't submit

    I just hide() the tinymce and submit form, the changed value of textarea missing. So I added this:

    $("textarea[id='id_answer']").change(function(){
        var editor_id = $(this).attr('id');
        var editor = tinymce.get(editor_id);
        editor.setContent($(this).val()).save();
    });
    

    It works for me.

    Bootstrap 3: How do you align column content to bottom of row

    When working with bootsrap usually face three main problems:

    1. How to place the content of the column to the bottom?
    2. How to create a multi-row gallery of columns of equal height in one .row?
    3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

    To solve first two problems download this small plugin https://github.com/codekipple/conformity

    The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

    Common code

    <style>
        [class*=col-] {position: relative}
        .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
        .row-centered {text-align:center}   
        .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
    </style>
    
    <script src="assets/conformity/conformity.js"></script>
    <script>
        $(document).ready(function () {
            $('.row-conformity > [class*=col-]').conformity();
            $(window).on('resize', function() {
                $('.row-conformity > [class*=col-]').conformity();
            });
        });
    </script>
    

    1. Aligning content of the column to the bottom

    <div class="row row-conformity">
        <div class="col-sm-3">
            I<br>create<br>highest<br>column
        </div>
        <div class="col-sm-3">
            <div class="to-bottom">
                I am on the bottom
            </div>
        </div>
    </div>
    

    2. Gallery of columns of equal height

    <div class="row row-conformity">
        <div class="col-sm-4">We all have equal height</div>
        <div class="col-sm-4">...</div>
        <div class="col-sm-4">...</div>
        <div class="col-sm-4">...</div>
        <div class="col-sm-4">...</div>
        <div class="col-sm-4">...</div>
    </div>
    

    3. Horizontal alignment of columns to the center (less than 12 col units)

    <div class="row row-centered">
        <div class="col-sm-3">...</div>
        <div class="col-sm-4">...</div>
    </div>
    

    All classes can work together

    <div class="row row-conformity row-centered">
        ...
    </div>
    

    Python concatenate text files

    If you have a lot of files in the directory then glob2 might be a better option to generate a list of filenames rather than writing them by hand.

    import glob2
    
    filenames = glob2.glob('*.txt')  # list of all .txt files in the directory
    
    with open('outfile.txt', 'w') as f:
        for file in filenames:
            with open(file) as infile:
                f.write(infile.read()+'\n')
    

    How to set downloading file name in ASP.NET Web API

    You need to set the Content-Disposition header on the HttpResponseMessage:

    HttpResponseMessage response = new HttpResponseMessage();
    response.StatusCode = HttpStatusCode.OK;
    response.Content = new StreamContent(result);
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "foo.txt"
    };
    

    How to concatenate strings in windows batch file for loop?

    In batch you could do it like this:

    @echo off
    
    setlocal EnableDelayedExpansion
    
    set "string_list=str1 str2 str3 ... str10"
    
    for %%s in (%string_list%) do (
      set "var=%%sxyz"
      svn co "!var!"
    )
    

    If you don't need the variable !var! elsewhere in the loop, you could simplify that to

    @echo off
    
    setlocal
    
    set "string_list=str1 str2 str3 ... str10"
    
    for %%s in (%string_list%) do svn co "%%sxyz"
    

    However, like C.B. I'd prefer PowerShell if at all possible:

    $string_list = 'str1', 'str2', 'str3', ... 'str10'
    
    $string_list | ForEach-Object {
      $var = "${_}xyz"   # alternatively: $var = $_ + 'xyz'
      svn co $var
    }
    

    Again, this could be simplified if you don't need $var elsewhere in the loop:

    $string_list = 'str1', 'str2', 'str3', ... 'str10'
    $string_list | ForEach-Object { svn co "${_}xyz" }
    

    How to add a jar in External Libraries in android studio

    In Android Studio version 3.0 or more I have used bellow like :

    1. Create libs to the app directory if not exist folder like
    • Set Project view in upper left corner
    • Go to project
    • Go to app
    • click on apps->New->Directory
    • name the folder libs
    • paste the jar to the libs folder
    • directory will look like bellow image

    enter image description here

    1. In build.gradle add these lines

      // Add this line if was not added before.
      implementation fileTree(dir: 'libs', include: ['*.jar'])
      
      implementation files('libs/com.ibm.icu_3.4.4.1.jar')
      

    Get properties and values from unknown object

    This example trims all the string properties of an object.

    public static void TrimModelProperties(Type type, object obj)
    {
        var propertyInfoArray = type.GetProperties(
                                        BindingFlags.Public | 
                                        BindingFlags.Instance);
        foreach (var propertyInfo in propertyInfoArray)
        {
            var propValue = propertyInfo.GetValue(obj, null);
            if (propValue == null) 
                continue;
            if (propValue.GetType().Name == "String")
                propertyInfo.SetValue(
                                 obj, 
                                 ((string)propValue).Trim(), 
                                 null);
        }
    }
    

    HTML Agility pack - parsing tables

    How about something like: Using HTML Agility Pack

    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
    foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
        Console.WriteLine("Found: " + table.Id);
        foreach (HtmlNode row in table.SelectNodes("tr")) {
            Console.WriteLine("row");
            foreach (HtmlNode cell in row.SelectNodes("th|td")) {
                Console.WriteLine("cell: " + cell.InnerText);
            }
        }
    }
    

    Note that you can make it prettier with LINQ-to-Objects if you want:

    var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
                from row in table.SelectNodes("tr").Cast<HtmlNode>()
                from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
                select new {Table = table.Id, CellText = cell.InnerText};
    
    foreach(var cell in query) {
        Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
    }
    

    How to save a PNG image server-side, from a base64 data string

    Well your solution above depends on the image being a jpeg file. For a general solution i used

    $img = $_POST['image'];
    $img = substr(explode(";",$img)[1], 7);
    file_put_contents('img.png', base64_decode($img));
    

    JavaScript property access: dot notation vs. brackets?

    Bracket notation can use variables, so it is useful in two instances where dot notation will not work:

    1) When the property names are dynamically determined (when the exact names are not known until runtime).

    2) When using a for..in loop to go through all the properties of an object.

    source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

    How is a non-breaking space represented in a JavaScript string?

    That entity is converted to the char it represents when the browser renders the page. JS (jQuery) reads the rendered page, thus it will not encounter such a text sequence. The only way it could encounter such a thing is if you're double encoding entities.

    How to Automatically Start a Download in PHP?

    A clean example.

    <?php
        header('Content-Type: application/download');
        header('Content-Disposition: attachment; filename="example.txt"');
        header("Content-Length: " . filesize("example.txt"));
    
        $fp = fopen("example.txt", "r");
        fpassthru($fp);
        fclose($fp);
    ?>
    

    How to convert a DataFrame back to normal RDD in pyspark?

    @dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

    Try this:

    rdd = df.rdd.map(tuple)
    

    or

    rdd = df.rdd.map(list)
    

    Property 'map' does not exist on type 'Observable<Response>'

    Angular 9:

     forkJoin([
      this.http.get().pipe(
        catchError((error) => {
          return of([]);
        })
      ),
      this.http.get().pipe(
        catchError((error) => {
          return of([]);
        })
      ),
    

    What is the difference between procedural programming and functional programming?

    None of the answers here show idiomatic functional programming. The recursive factorial answer is great for representing recursion in FP, but the majority of code is not recursive so I don't think that answer is fully representative.

    Say you have an arrays of strings, and each string represents an integer like "5" or "-200". You want to check this input array of strings against your internal test case (Using integer comparison). Both solutions are shown below

    Procedural

    arr_equal(a : [Int], b : [Str]) -> Bool {
        if(a.len != b.len) {
            return false;
        }
    
        bool ret = true;
        for( int i = 0; i < a.len /* Optimized with && ret*/; i++ ) {
            int a_int = a[i];
            int b_int = parseInt(b[i]);
            ret &= a_int == b_int;  
        }
        return ret;
    }
    

    Functional

    eq = i, j => i == j # This is usually a built-in
    toInt = i => parseInt(i) # Of course, parseInt === toInt here, but this is for visualization
    
    arr_equal(a : [Int], b : [Str]) -> Bool =
        zip(a, b.map(toInt)) # Combines into [Int, Int]
       .map(eq)
       .reduce(true, (i, j) => i && j) # Start with true, and continuously && it with each value
    

    While pure functional languages are generally research languages (As the real-world likes free side-effects), real-world procedural languages will use the much simpler functional syntax when appropriate.

    This is usually implemented with an external library like Lodash, or available built-in with newer languages like Rust. The heavy lifting of functional programming is done with functions/concepts like map, filter, reduce, currying, partial, the last three of which you can look up for further understanding.

    Addendum

    In order to be used in the wild, the compiler will normally have to work out how to convert the functional version into the procedural version internally, as function call overhead is too high. Recursive cases such as the factorial shown will use tricks such as tail call to remove O(n) memory usage. The fact that there are no side effects allows functional compilers to implement the && ret optimization even when the .reduce is done last. Using Lodash in JS, obviously does not allow for any optimization, so it is a hit to performance (Which isn't usually a concern with web development). Languages like Rust will optimize internally (And have functions such as try_fold to assist && ret optimization).

    Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

    In my case the problem was about permissions. I use Ubuntu 19.04 When running Android Studio in root user it would prompt my phone about permission requirements. But with normal user it won't do this.

    So the problem was about adb not having enough permission. I made my user owner of Android folder on home directory.

    sudo chown -R orkhan ~/Android

    How do I create a custom Error in JavaScript?

    This is fastest way to do it:

        let thisVar = false
    
        if (thisVar === false) {
                throw new Error("thisVar is false. It should be true.")
        }
    

    HTTP Basic Authentication - what's the expected web browser experience?

    Have you tried ?

    curl somesite.com --user username:password
    

    How to import JSON File into a TypeScript file?

    Here is complete answer for Angular 6+ based on @ryanrain answer:

    From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.

    Let's suppose you add your json files into "your-json-dir" directory:

    1. add "your-json-dir" into angular.json file (:

      "assets": [ "src/assets", "src/your-json-dir" ]

    2. create or edit typings.d.ts file (at your project root) and add the following content:

      declare module "*.json" { const value: any; export default value; }

      This will allow import of ".json" modules without typescript error.

    3. in your controller/service/anything else file, simply import the file by using this relative path:

      import * as myJson from 'your-json-dir/your-json-file.json';

    Embedding VLC plugin on HTML page

    I found this piece of code somewhere in the web. Maybe it helps you and I give you an update so far I accomodated it for the same purpose... Maybe I don't.... who the futt knows... with all the nogodders and dobedders in here :-/

    function runVLC(target, stream)
    {
    var support=true
    var addr='rtsp://' + window.location.hostname + stream
    if ($.browser.msie){
    $(target).html('<object type = "application/x-vlc-plugin"' + 'version =  
    "VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' + 
    'events = "true"' + 'id = "vlc"></object>')
    }
    else if ($.browser.mozilla || $.browser.webkit){
    $(target).html('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' + 
    'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' + 
    'width="660" height="372"' + 
    'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' + 
    'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' + 
    'branding="false"' + 'controls="false"' + 'aspectRatio="16:9"' + 
    'target="whatever.mp4"></embed>')
    }
    else{
    support=false
    $(target).empty().html('<div id = "dialog_error">Error: browser not supported!</div>')
    }
    if (support){
    var vlc = document.getElementById('vlc')
    if (vlc){
    var opt = new Array(':network-caching=300')
    try{
    var id = vlc.playlist.add(addr, '', opt)
    vlc.playlist.playItem(id)
    }
    catch (e){
    $(target).empty().html('<div id = "dialog_error">Error: ' + e + '<br>URL: ' + addr + 
    '</div>')
    }
    }
    }
    }
    /* $(target + ' object').css({'width': '100%', 'height': '100%'}) */
    

    Greets

    Gee

    I reduce the whole crap now to:

    function runvlc(){
    var target=$('body')
    var error=$('#dialog_error')
    var support=true
    var addr='rtsp://../html/media/video/TESTCARD.MP4'
    if (navigator.userAgent.toLowerCase().indexOf("msie")!=-1){
    target.append('<object type = "application/x-vlc-plugin"' + 'version = "
    VideoLAN.VLCPlugin.2"' + 'classid = "clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921"' + 
    'events = "true"' + 'id = "vlc"></object>')
    }
    else if (navigator.userAgent.toLowerCase().indexOf("msie")==-1){
    target.append('<embed type = "application/x-vlc-plugin"' + 'class="vlc_plugin"' + 
    'pluginspage="http://www.videolan.org"' + 'version="VideoLAN.VLCPlugin.2" ' + 
    'width="660" height="372"' + 
    'id="vlc"' + 'autoplay="true"' + 'allowfullscreen="false"' + 'windowless="true"' + 
    'mute="false"' + 'loop="true"' + '<toolbar="false"' + 'bgcolor="#111111"' + 
    'branding="false"' + 
    'controls="false"' + 'aspectRatio="16:9"' + 'target="whatever.mp4">
    </embed>')
    }
    else{
    support=false
    error.empty().html('Error: browser not supported!')
    error.show()
    if (support){
    var vlc=document.getElementById('vlc')
    if (vlc){
    var options=new Array(':network-caching=300') /* set additional vlc--options */
    try{ /* error handling */
    var id = vlc.playlist.add(addr,'',options)
    vlc.playlist.playItem(id)
    }
    catch (e){
    error.empty().html('Error: ' + e + '<br>URL: ' + addr + '')
    error.show()
    }
    }
    }
    }
    };
    

    Didn't get it to work in ie as well... 2b continued...

    Greets

    Gee

    Undefined index with $_POST

    When you say:

    $user = $_POST["username"];
    

    You're asking the PHP interpreter to assign $user the value of the $_POST array that has a key (or index) of username. If it doesn't exist, PHP throws a fit.

    Use isset($_POST['user']) to check for the existence of that variable:

    if (isset($_POST['user'])) {
      $user = $_POST["username"];
      ...
    

    Beamer: How to show images as step-by-step images

    I found a solution to my problem, by using the visble-command.

    EDITED:

    \visible<2->{
       \textbf{Some text}
       \begin{figure}[ht]
           \includegraphics[width=5cm]{./path/to/image}
        \end{figure}
     }
    

    How to run different python versions in cmd

    Python 3.3 introduces Python Launcher for Windows that is installed into c:\Windows\ as py.exe and pyw.exe by the installer. The installer also creates associations with .py and .pyw. Then add #!python3 or #!python2 as the first lline. No need to add anything to the PATH environment variable.

    Update: Just install Python 3.3 from the official python.org/download. It will add also the launcher. Then add the first line to your script that has the .py extension. Then you can launch the script by simply typing the scriptname.py on the cmd line, od more explicitly by py scriptname.py, and also by double clicking on the scipt icon.

    The py.exe looks for C:\PythonXX\python.exe where XX is related to the installed versions of Python at the computer. Say, you have Python 2.7.6 installed into C:\Python27, and Python 3.3.3 installed into C:\Python33. The first line in the script will be used by the Python launcher to choose one of the installed versions. The default (i.e. without telling the version explicitly) is to use the highest version of Python 2 that is available on the computer.

    How do I type a TAB character in PowerShell?

    TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

    From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

    JPA - Returning an auto generated id after persist()

    You could also use GenerationType.TABLE instead of IDENTITY which is only available after the insert.

    Check if textbox has empty value

    if ( $("#txt").val().length > 0 )
    {
      // do something
    }
    

    Your method fails when there is more than 1 space character inside the textbox.

    How do I remove newlines from a text file?

    You can edit the file in vim:

    $ vim inputfile
    :%s/\n//g
    

    Django. Override save for model

    Check the model's pk field. If it is None, then it is a new object.

    class Model(model.Model):
        image=models.ImageField(upload_to='folder')
        thumb=models.ImageField(upload_to='folder')
        description=models.CharField()
    
    
        def save(self, *args, **kwargs):
            if 'form' in kwargs:
                form=kwargs['form']
            else:
                form=None
    
            if self.pk is None and form is not None and 'image' in form.changed_data:
                small=rescale_image(self.image,width=100,height=100)
                self.image_small=SimpleUploadedFile(name,small_pic)
            super(Model, self).save(*args, **kwargs)
    

    Edit: I've added a check for 'image' in form.changed_data. This assumes that you're using the admin site to update your images. You'll also have to override the default save_model method as indicated below.

    class ModelAdmin(admin.ModelAdmin):
        def save_model(self, request, obj, form, change):
            obj.save(form=form)
    

    Check whether IIS is installed or not?

    The quickest way to check is just to write "inetmgr" at run (By pressing Win + R) as a command, if a manager window is appeared then it's installed otherwise it isn't.

    Attaching click event to a JQuery object not yet added to the DOM

    Does using .live work for you?

    $("#my-button").live("click", function(){ alert("yay!"); }); 
    

    http://api.jquery.com/live/

    EDIT

    As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

    http://api.jquery.com/on/

    Android ImageView Fixing Image Size

    Fix ImageView's size with dp or fill_parent and set android:scaleType to fitXY.

    How can I nullify css property?

    To get rid of the fixed height property you can set it to the default value:

    height: auto;
    

    How can I get the external SD card path for Android 4.0+?

    Here's how I get the list of SD-card paths (excluding the primary external storage) :

      /**
       * returns a list of all available sd cards paths, or null if not found.
       * 
       * @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
       */
      @TargetApi(Build.VERSION_CODES.HONEYCOMB)
      public static List<String> getSdCardPaths(final Context context,final boolean includePrimaryExternalStorage)
        {
        final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
        if(externalCacheDirs==null||externalCacheDirs.length==0)
          return null;
        if(externalCacheDirs.length==1)
          {
          if(externalCacheDirs[0]==null)
            return null;
          final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
          if(!Environment.MEDIA_MOUNTED.equals(storageState))
            return null;
          if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
            return null;
          }
        final List<String> result=new ArrayList<>();
        if(includePrimaryExternalStorage||externalCacheDirs.length==1)
          result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
        for(int i=1;i<externalCacheDirs.length;++i)
          {
          final File file=externalCacheDirs[i];
          if(file==null)
            continue;
          final String storageState=EnvironmentCompat.getStorageState(file);
          if(Environment.MEDIA_MOUNTED.equals(storageState))
            result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
          }
        if(result.isEmpty())
          return null;
        return result;
        }
    
      /** Given any file/folder inside an sd card, this will return the path of the sd card */
      private static String getRootOfInnerSdCardFolder(File file)
        {
        if(file==null)
          return null;
        final long totalSpace=file.getTotalSpace();
        while(true)
          {
          final File parentFile=file.getParentFile();
          if(parentFile==null||parentFile.getTotalSpace()!=totalSpace||!parentFile.canRead())
            return file.getAbsolutePath();
          file=parentFile;
          }
        }
    

    Regex for Mobile Number Validation

    This regex is very short and sweet for working.

    /^([+]\d{2})?\d{10}$/

    Ex: +910123456789 or 0123456789

    -> /^ and $/ is for starting and ending
    -> The ? mark is used for conditional formatting where before question mark is available or not it will work
    -> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
    -> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length

    This is how this regex for mobile number is working.
    + sign is used for world wide matching of number.

    if you want to add the space between than you can use the

    [ ]

    here the square bracket represents the character sequence and a space is character for searching in regex.
    for the space separated digit you can use this regex

    /^([+]\d{2}[ ])?\d{10}$/

    Ex: +91 0123456789

    Thanks ask any question if you have.

    CURL to access a page that requires a login from a different page

    My answer is a mod of some prior answers from @JoeMills and @user.

    1. Get a cURL command to log into server:

      • Load login page for website and open Network pane of Developer Tools
        • In firefox, right click page, choose 'Inspect Element (Q)' and click on Network tab
      • Go to login form, enter username, password and log in
      • After you have logged in, go back to Network pane and scroll to the top to find the POST entry. Right click and choose Copy -> Copy as CURL
      • Paste this to a text editor and try this in command prompt to see if it works
        • Its possible that some sites have hardening that will block this type of login spoofing that would require more steps below to bypass.
    2. Modify cURL command to be able to save session cookie after login

      • Remove the entry -H 'Cookie: <somestuff>'
      • Add after curl at beginning -c login_cookie.txt
      • Try running this updated curl command and you should get a new file 'login_cookie.txt' in the same folder
    3. Call a new web page using this new cookie that requires you to be logged in

      • curl -b login_cookie.txt <url_that_requires_log_in>

    I have tried this on Ubuntu 20.04 and it works like a charm.

    How to get a path to a resource in a Java JAR file

    I spent a while messing around with this problem, because no solution I found actually worked, strangely enough! The working directory is frequently not the directory of the JAR, especially if a JAR (or any program, for that matter) is run from the Start Menu under Windows. So here is what I did, and it works for .class files run from outside a JAR just as well as it works for a JAR. (I only tested it under Windows 7.)

    try {
        //Attempt to get the path of the actual JAR file, because the working directory is frequently not where the file is.
        //Example: file:/D:/all/Java/TitanWaterworks/TitanWaterworks-en.jar!/TitanWaterworks.class
        //Another example: /D:/all/Java/TitanWaterworks/TitanWaterworks.class
        PROGRAM_DIRECTORY = getClass().getClassLoader().getResource("TitanWaterworks.class").getPath(); // Gets the path of the class or jar.
    
        //Find the last ! and cut it off at that location. If this isn't being run from a jar, there is no !, so it'll cause an exception, which is fine.
        try {
            PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(0, PROGRAM_DIRECTORY.lastIndexOf('!'));
        } catch (Exception e) { }
    
        //Find the last / and cut it off at that location.
        PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(0, PROGRAM_DIRECTORY.lastIndexOf('/') + 1);
        //If it starts with /, cut it off.
        if (PROGRAM_DIRECTORY.startsWith("/")) PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(1, PROGRAM_DIRECTORY.length());
        //If it starts with file:/, cut that off, too.
        if (PROGRAM_DIRECTORY.startsWith("file:/")) PROGRAM_DIRECTORY = PROGRAM_DIRECTORY.substring(6, PROGRAM_DIRECTORY.length());
    } catch (Exception e) {
        PROGRAM_DIRECTORY = ""; //Current working directory instead.
    }
    

    How to run a PowerShell script

    In case you want to run a PowerShell script with Windows Task Scheduler, please follow the steps below:

    1. Create a task

    2. Set Program/Script to Powershell.exe

    3. Set Arguments to -File "C:\xxx.ps1"

    It's from another answer, How do I execute a PowerShell script automatically using Windows task scheduler?.

    Google Maps API v3 adding an InfoWindow to each marker

    The only way I could finally get this to work was by creating an array in JavaScript. The array elements reference the various info-windows (one info-window is created for each marker on the map). Each array element contains the unique text for its appropriate map marker. I defined the JavaScript event for each info-window based on the array element. And when the event fires, I use the "this" keyword to reference the array element to reference the appropriate value to display.

    var map = new google.maps.Map(document.getElementById('map-div'), mapOptions);
    zipcircle = [];
    for (var zip in zipmap) {
        var circleoptions = {
            strokeOpacity: 0.8,
            strokeWeight: 1,
            fillOpacity: 0.35,
            map: map,
            center: zipmap[zip].center,
            radius: 100
        };
        zipcircle[zipmap[zip].zipkey] = new google.maps.Circle(circleoptions);
        zipcircle[zipmap[zip].zipkey].infowindowtext = zipmap[zip].popuptext;
        zipcircle[zipmap[zip].zipkey].infowindow = new google.maps.InfoWindow();
        google.maps.event.addListener(zipcircle[zipmap[zip].zipkey], 'click', function() {
            this.infowindow.setContent(this.infowindowtext);
            this.infowindow.open(map, this);
        });
    }
    

    I need a Nodejs scheduler that allows for tasks at different intervals

    I think the best ranking is

    1.node-schedule

    2.later

    3.crontab

    and the sample of node-schedule is below:

    var schedule = require("node-schedule");
    var rule = new schedule.RecurrenceRule();
    //rule.minute = 40;
    rule.second = 10;
    var jj = schedule.scheduleJob(rule, function(){
        console.log("execute jj");
    });
    

    Maybe you can find the answer from node modules.

    What to do about Eclipse's "No repository found containing: ..." error messages?

    Some of the above solutions worked to resolve some of my errors... it seems that after a while update connections just get corrupted and there is no silver-bullet. Managing updates through the marketplace (Help > Marketplace > 'show updates') allowed me to narrow down the packages with failed dependencies.

    Here's what I tried (taken from posts above):

    1. switching https to http for software sites
    2. running Eclipse as administrator
    3. 'disabling' obviously outdated software sites
    4. 'enabling' all software sites
    5. adding backslashes to the end of software site urls
    6. uninstalling and re-installing troublesome software

    I was still left with some Mylyn wikitext errors despite trying the suggestions here

    Eclipse IDE for JavaScript and Web Developers

    Version: 2019-09 R (4.13.0) Build id: 20190917-1200

    Convert string with comma to integer

    I would do using String#tr :

    "1,112".tr(',','').to_i # => 1112
    

    "The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

    I found that changing my compiler to LLVM 6.0 in the Build Options was enough for me (xcode 6.1)

    enter image description here

    Sorting JSON by values

    Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.

    $scope.sortMyData = function (a, b)
    {
      var retVal = 0, key;
      for (var i = 0; i < $scope.sortKeys.length; i++)
      {
        if (retVal !== 0)
        {
          break;
        }
        else
        {
          key = $scope.sortKeys[i];
          if ('asc' === key.direction)
          {
            retVal = (a[key.field] < b[key.field]) ? -1 : (a[key.field] > b[key.field]) ? 1 : 0;
          }
          else
          {
            retVal = (a[key.field] < b[key.field]) ? 1 : (a[key.field] > b[key.field]) ? -1 : 0;
          }
        }
      }
      return retVal;
    };
    

    Can't access to HttpContext.Current

    Have you included the System.Web assembly in the application?

    using System.Web;
    

    If not, try specifying the System.Web namespace, for example:

     System.Web.HttpContext.Current
    

    Why do I need 'b' to encode a string with Base64?

    base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z, a-z, 0-9, +, /* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.

    Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax.

    If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)

    In your second example:

    >>> encoded = base64.b64encode('data to be encoded')
    

    All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with

    >>> encoded = 'data to be encoded'.encode('ascii')
    

    Or simpler:

    >>> encoded = b'data to be encoded'
    

    Which would be the same thing in this case.


    * Most base64 flavours may also include a = at the end as padding. In addition, some base64 variants may use characters other than + and /. See the Variants summary table at Wikipedia for an overview.

    How to set the size of a column in a Bootstrap responsive table

    you can use the following Bootstrap class with

    <tr class="w-25">
    
    </tr>
    

    for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/

    Xcode 6 iPhone Simulator Application Support location

    In Swift 4 or Swift 5 you can use NSHomeDirectory().

    The easiest way in Xcode 10 (or Xcode 11) is to pause your app (like when it hits a breakpoint) and run this line in the debugger console:

    po NSHomeDirectory()
    

    po stands for print object and prints most things

    MD5 is 128 bits but why is it 32 characters?

    Those are hexidecimal digits, not characters. One digit = 4 bits.

    Update Tkinter Label from variable

    Maybe I'm not understanding the question but here is my simple solution that works -

    # I want to Display total heads bent this machine so I define a label -
    TotalHeadsLabel3 = Label(leftFrame)
    TotalHeadsLabel3.config(font=Helv12,fg='blue',text="Total heads " + str(TotalHeads))
    TotalHeadsLabel3.pack(side=TOP)
    
    # I update the int variable adding the quantity bent -
    TotalHeads = TotalHeads + headQtyBent # update ready to write to file & display
    TotalHeadsLabel3.config(text="Total Heads "+str(TotalHeads)) # update label with new qty
    

    I agree that labels are not automatically updated but can easily be updated with the

    <label name>.config(text="<new text>" + str(<variable name>))
    

    That just needs to be included in your code after the variable is updated.

    Correct set of dependencies for using Jackson mapper

    The package names in Jackson 2.x got changed to com.fasterxml1 from org.codehaus2. So if you just need ObjectMapper, I think Jackson 1.X can satisfy with your needs.

    Output Django queryset as JSON

    For a efficient solution, you can use .values() function to get a list of dict objects and then dump it to json response by using i.e. JsonResponse (remember to set safe=False).

    Once you have your desired queryset object, transform it to JSON response like this:

    ...
    data = list(queryset.values())
    return JsonResponse(data, safe=False)
    

    You can specify field names in .values() function in order to return only wanted fields (the example above will return all model fields in json objects).

    Can I run javascript before the whole page is loaded?

    Not only can you, but you have to make a special effort not to if you don't want to. :-)

    When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

    That's the default behavior, but you have a few options for delaying script execution:

    1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

      <script type="module" src="./my-code.js"></script>
      <!-- Or -->
      <script type="module">
      // Your code here
      </script>
      

      The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

      This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

    2. Use the defer attribute on a classic script tag:

      <script defer src="./my-code.js"></script>
      

      As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

    3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

    4. Put the script tag at the end of the document, just prior to the closing </body> tag:

      <!doctype html>
      <html>
      <!-- ... -->
      <body>
      <!-- The document's HTML goes here -->
      <script type="module" src="./my-code.js"></script><!-- Or inline script -->
      </body>
      </html>
      

      That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

      It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

    The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

    enter image description here

    Here's an example of the default behavior, a raw script tag:

    _x000D_
    _x000D_
    .found {_x000D_
        color: green;_x000D_
    }
    _x000D_
    <p>Paragraph 1</p>_x000D_
    <script>_x000D_
        if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
            NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
        }_x000D_
        document.querySelectorAll("p").forEach(p => {_x000D_
            p.classList.add("found");_x000D_
        });_x000D_
    </script>_x000D_
    <p>Paragraph 2</p>
    _x000D_
    _x000D_
    _x000D_

    (See my answer here for details around that NodeList code.)

    When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

    In contrast, here's a type="module" script:

    _x000D_
    _x000D_
    .found {_x000D_
        color: green;_x000D_
    }
    _x000D_
    <p>Paragraph 1</p>_x000D_
    <script type="module">_x000D_
        document.querySelectorAll("p").forEach(p => {_x000D_
            p.classList.add("found");_x000D_
        });_x000D_
    </script>_x000D_
    <p>Paragraph 2</p>
    _x000D_
    _x000D_
    _x000D_

    Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

    (There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

    In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

    JSON to TypeScript class instance?

    What is actually the most robust and elegant automated solution for deserializing JSON to TypeScript runtime class instances?

    Using property decorators with ReflectDecorators to record runtime-accessible type information that can be used during a deserialization process provides a surprisingly clean and widely adaptable approach, that also fits into existing code beautifully. It is also fully automatable, and works for nested objects as well.

    An implementation of this idea is TypedJSON, which I created precisely for this task:

    @JsonObject
    class Foo {
        @JsonMember
        name: string;
    
        getName(): string { return this.name };
    }
    
    var foo = TypedJSON.parse('{"name": "John Doe"}', Foo);
    
    foo instanceof Foo; // true
    foo.getName(); // "John Doe"
    

    Type.GetType("namespace.a.b.ClassName") returns null

    When I have only the class name I use this:

    Type obj = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => String.Equals(t.Name, _viewModelName, StringComparison.Ordinal)).First();
    

    increment date by one month

    I use this way:-

     $occDate='2014-01-28';
     $forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
    //Output:- $forOdNextMonth=02
    
    
    /*****************more example****************/
    $occDate='2014-12-28';
    
    $forOdNextMonth= date('m', strtotime("+1 month", strtotime($occDate)));
    //Output:- $forOdNextMonth=01
    
    //***********************wrong way**********************************//
    $forOdNextMonth= date('m', strtotime("+1 month", $occDate));
      //Output:- $forOdNextMonth=02; //instead of $forOdNextMonth=01;
    //******************************************************************//
    

    How to specify HTTP error code?

    From what I saw in Express 4.0 this works for me. This is example of authentication required middleware.

    function apiDemandLoggedIn(req, res, next) {
    
        // if user is authenticated in the session, carry on
        console.log('isAuth', req.isAuthenticated(), req.user);
        if (req.isAuthenticated())
            return next();
    
        // If not return 401 response which means unauthroized.
        var err = new Error();
        err.status = 401;
        next(err);
    }
    

    How to clear File Input

    I have done something like this and it's working for me

    $('#fileInput').val(null); 
    

    I don't have "Dynamic Web Project" option in Eclipse new Project wizard

    Make sure to check dynamic web app in "other section" i.e File>New>Other>Web or type in "dynamic web app" in your wizard filter. If dynamic web app is not there then follow following steps:

    1. On Eclipse Menu Select HELP > INSTALL NEW SOFTWARE
    2. In work with test box simply type in your eclipse version, which is oxygen in my case
    3. Once you type in yur version something like this "Oxygen - http://download.eclipse.org/releases/oxygen"will be recommended to you in drop down
    4. If you do not get any recommendation then simply copy " http://download.eclipse.org/releases/your-version" and paste it. Make sure to edit your-version.
    5. After you Enter the address and press enter bunch of new softwares will be listed just ubderneath work with text box.
    6. Scroll, find and Expand WEB, XML, Java EE .... tab
    7. Select only these three options: Eclipse Java EE Developer Tools, Eclipse Java Web Developer Tools,Eclipse Web Developer Tools
    8. Next, next and finish!

    How can I create a dropdown menu from a List in Tkinter?

    To create a "drop down menu" you can use OptionMenu in tkinter

    Example of a basic OptionMenu:

    from Tkinter import *
    
    master = Tk()
    
    variable = StringVar(master)
    variable.set("one") # default value
    
    w = OptionMenu(master, variable, "one", "two", "three")
    w.pack()
    
    mainloop()
    

    More information (including the script above) can be found here.


    Creating an OptionMenu of the months from a list would be as simple as:

    from tkinter import *
    
    OPTIONS = [
    "Jan",
    "Feb",
    "Mar"
    ] #etc
    
    master = Tk()
    
    variable = StringVar(master)
    variable.set(OPTIONS[0]) # default value
    
    w = OptionMenu(master, variable, *OPTIONS)
    w.pack()
    
    mainloop()
    

    In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

    from tkinter import *
    
    OPTIONS = [
    "Jan",
    "Feb",
    "Mar"
    ] #etc
    
    master = Tk()
    
    variable = StringVar(master)
    variable.set(OPTIONS[0]) # default value
    
    w = OptionMenu(master, variable, *OPTIONS)
    w.pack()
    
    def ok():
        print ("value is:" + variable.get())
    
    button = Button(master, text="OK", command=ok)
    button.pack()
    
    mainloop()
    

    I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

    How to disable text selection using jQuery?

    If you use jQuery UI, there is a method for that, but it can only handle mouse selection (i.e. CTRL+A is still working):

    $('.your-element').disableSelection(); // deprecated in jQuery UI 1.9
    

    The code is realy simple, if you don't want to use jQuery UI :

    $(el).attr('unselectable','on')
         .css({'-moz-user-select':'-moz-none',
               '-moz-user-select':'none',
               '-o-user-select':'none',
               '-khtml-user-select':'none', /* you could also put this in a class */
               '-webkit-user-select':'none',/* and add the CSS class here instead */
               '-ms-user-select':'none',
               'user-select':'none'
         }).bind('selectstart', function(){ return false; });
    

    Is it possible to open a Windows Explorer window from PowerShell?

    I wanted to write this as a comment but I do not have 50 reputation.

    All of the answers in this thread are essentially to use Invoke-Item or to use explorer.exe directly; however, this isn't completely synonymous with "open containing folder", so in terms of opening an Explorer window as the question states, if we wanted to apply the answer to a particular file the question still hasn't really been answered.

    e.g.,

    Invoke-Item C:\Users\Foo\bar.txt
    explorer.exe C:\Users\Foo\bar.html
    

    ^ those two commands would result in Notepad.exe or Firefox.exe being invoked on the two files respectively, not an explorer.exe window on C:\Users\Foo\ (the containing directory).

    Whereas if one was issuing this command from powershell, this would be no big deal (less typing anyway), if one is scripting and needs to "open containing folder" on a variable, it becomes a matter of string matching to extract the directory from the full path to the file.

    Is there no simple command "Open-Containing-Folder" such that a variable could be substituted?

    e.g.,

    $foo = "C:\Users\Foo\foo.txt"    
    [some code] $fooPath
    # opens C:\Users\Foo\ and not the default program for .txt file extension
    

    How to find and replace with regex in excel

    Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

    To answer your question:

    1. Copy the data from Excel and paste into Google Sheets
    2. Use the find and replace dialog with regex
    3. Copy the data from Google Sheets and paste back into Excel

    How do I set the selected item in a comboBox to match my string using C#?

    I've used an extension method:

    public static void SelectItemByValue(this ComboBox cbo, string value)
    {
        for(int i=0; i < cbo.Items.Count; i++)
        {
            var prop = cbo.Items[i].GetType().GetProperty(cbo.ValueMember);
            if (prop!=null && prop.GetValue(cbo.Items[i], null).ToString() == value)
            {
                 cbo.SelectedIndex = i;
                 break;
            }
        } 
    }
    

    Then just consume the method:

    ddl.SelectItemByValue(value);
    

    How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

    Run the below command to resolve this issue.

    It worked for me.

    chmod 600 ~/.ssh/id_rsa
    

    One line ftp server in python

    The answers above were all assuming your Python distribution would have some third-party libraries in order to achieve the "one liner python ftpd" goal, but that is not the case of what @zio was asking. Also, SimpleHTTPServer involves web broswer for downloading files, it's not quick enough.

    Python can't do ftpd by itself, but you can use netcat, nc:

    nc is basically a built-in tool from any UNIX-like systems (even embedded systems), so it's perfect for "quick and temporary way to transfer files".

    Step 1, on the receiver side, run:

    nc -l 12345 | tar -xf -
    

    this will listen on port 12345, waiting for data.

    Step 2, on the sender side:

    tar -cf - ALL_FILES_YOU_WANT_TO_SEND ... | nc $RECEIVER_IP 12345
    

    You can also put pv in the middle to monitor the progress of transferring:

    tar -cf - ALL_FILES_YOU_WANT_TO_SEND ...| pv | nc $RECEIVER_IP 12345
    

    After the transferring is finished, both sides of nc will quit automatically, and job done.

    How to reverse an animation on mouse out after hover

    I think that if you have a to, you must use a from. I would think of something like :

    @keyframe in {
        from: transform: rotate(0deg);
        to: transform: rotate(360deg);
    }
    
    @keyframe out {
        from: transform: rotate(360deg);
        to: transform: rotate(0deg);
    }
    

    Of course must have checked it already, but I found strange that you only use the transform property since CSS3 is not fully implemented everywhere. Maybe it would work better with the following considerations :

    • Chrome uses @-webkit-keyframes, no particuliar version needed
    • Safari uses @-webkit-keyframes since version 5+
    • Firefox uses @keyframes since version 16 (v5-15 used @-moz-keyframes)
    • Opera uses @-webkit-keyframes version 15-22 (only v12 used @-o-keyframes)
    • Internet Explorer uses @keyframes since version 10+

    EDIT :

    I came up with that fiddle :

    http://jsfiddle.net/JjHNG/35/

    Using minimal code. Is it approaching what you were expecting ?

    Generate .pem file used to set up Apple Push Notifications

    it is very simple after exporting the Cert.p12 and key.p12, Please find below command for the generating 'apns' .pem file.

    https://www.sslshopper.com/ssl-converter.html ?

    command to create apns-dev.pem from Cert.pem and Key.pem
    ?    
    
    openssl rsa -in Key.pem -out apns-dev-key-noenc.pem
    ?    
    
    cat Cert.pem apns-dev-key-noenc.pem > apns-dev.pem
    

    Above command is useful for both Sandbox and Production.

    Converting 'ArrayList<String> to 'String[]' in Java

    You can use Iterator<String> to iterate the elements of the ArrayList<String>:

    ArrayList<String> list = new ArrayList<>();
    String[] array = new String[list.size()];
    int i = 0;
    for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
        array[i] = iterator.next();
    }
    

    Now you can retrive elements from String[] using any Loop.

    How to align checkboxes and their labels consistently cross-browsers

    try vertical-align: middle

    also your code seems like it should be:

    _x000D_
    _x000D_
    <form>_x000D_
        <div>_x000D_
            <input id="blah" type="checkbox"><label for="blah">Label text</label>_x000D_
        </div>_x000D_
    </form>
    _x000D_
    _x000D_
    _x000D_

    Use FontAwesome or Glyphicons with css :before

    What you are describing is actually what FontAwesome is doing already. They apply the FontAwesome font-family to the ::before pseudo element of any element that has a class that starts with "icon-".

    [class^="icon-"]:before,
    [class*=" icon-"]:before {
      font-family: FontAwesome;
      font-weight: normal;
      font-style: normal;
      display: inline-block;
      text-decoration: inherit;
    }
    

    Then they use the pseudo element ::before to place the icon in the element with the class. I just went to http://fortawesome.github.com/Font-Awesome/ and inspected the code to find this:

    .icon-cut:before {
      content: "\f0c4";
    }
    

    So if you are looking to add the icon again, you could use the ::after element to achieve this. Or for your second part of your question, you could use the ::after pseudo element to insert the bullet character to look like a list item. Then use absolute positioning to place it to the left, or something similar.

    i:after{ content: '\2022';}
    

    get next sequence value from database using hibernate

    Interesting it works for you. When I tried your solution an error came up, saying that "Type mismatch: cannot convert from SQLQuery to Query". --> Therefore my solution looks like:

    SQLQuery query = session.createSQLQuery("select nextval('SEQUENCE_NAME')");
    Long nextValue = ((BigInteger)query.uniqueResult()).longValue();
    

    With that solution I didn't run into performance problems.

    And don't forget to reset your value, if you just wanted to know for information purposes.

        --nextValue;
        query = session.createSQLQuery("select setval('SEQUENCE_NAME'," + nextValue + ")");
    

    Get the current URL with JavaScript?

    location.origin+location.pathname+location.search+location.hash;
    

    and

    location.href
    

    does the same.

    Python loop for inside lambda

    Since a for loop is a statement (as is print, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys.stdout along with the join method.

    x = lambda x: sys.stdout.write("\n".join(x) + "\n")
    

    How to check if any fields in a form are empty in php

    Specify POST method in form
    <form name="registrationform" action="register.php" method="post">
    
    
    your form code
    
    </form>
    

    Enable/disable buttons with Angular

    Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.

    HTML

      <button  (click)="currentLesson = '1'"
             [disabled]="currentLesson !== '1'" class="primair">
               Start lesson</button>
      <button (click)="currentLesson = '2'"
             [disabled]="currentLesson !== '2'" class="primair">
               Start lesson</button>
     .....//so on
    

    Typescript

    currentLesson:string;
    
      classes = [
    {
      name: 'string',
      level: 'string',
      code: 'number',
      currentLesson: '1'
    }]
    
    constructor(){
      this.currentLesson=this.classes[0].currentLesson
    }
    

    DEMO

    Putting everything in a loop:

    HTML

    <div *ngFor="let class of classes; let i = index">
       <button [disabled]="currentLesson !== i + 1" class="primair">
               Start lesson {{i +  1}}</button>
    </div>
    

    Typescript

    currentLesson:string;
    
    classes = [
    {
      name: 'Lesson1',
      level: 1,
      code: 1,
    },{
      name: 'Lesson2',
      level: 1,
      code: 2,
    },
    {
      name: 'Lesson3',
      level: 2,
      code: 3,
    }]
    

    DEMO

    PHP foreach with Nested Array?

    As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

    public function parent(){
    
        return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
    }
    
    
    public function children()
    {
    
        return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
    }
    

    and if you want to have all of children IDs as an Array , This approach is fine and working for me :

    public function allChildren()
    {
        $allChildren = [];
        if ($this->has_branch) {
    
            foreach ($this->children as $child) {
    
                $subChildren = $child->allChildren();
    
                if (count($subChildren) == 1) {
                    $allChildren  [] = $subChildren[0];
                } else if (count($subChildren) > 1) {
                    $allChildren += $subChildren;
                }
            }
        }
        $allChildren  [] = $this->id;//adds self Id to children Id list
    
        return $allChildren; 
    }
    

    the allChildren() returns , all of childrens as a simple Array .

    Passing multiple parameters with $.ajax url

    Why are you combining GET and POST? Use one or the other.

    $.ajax({
        type: 'post',
        data: {
            timestamp: timestamp,
            uid: uid
            ...
        }
    });
    

    php:

    $uid =$_POST['uid'];
    

    Or, just format your request properly (you're missing the ampersands for the get parameters).

    url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,
    

    cmake and libpthread

    @Manuel was part way there. You can add the compiler option as well, like this:

    If you have CMake 3.1.0+, this becomes even easier:

    set(THREADS_PREFER_PTHREAD_FLAG ON)
    find_package(Threads REQUIRED)
    target_link_libraries(my_app PRIVATE Threads::Threads)
    

    If you are using CMake 2.8.12+, you can simplify this to:

    find_package(Threads REQUIRED)
    if(THREADS_HAVE_PTHREAD_ARG)
      target_compile_options(my_app PUBLIC "-pthread")
    endif()
    if(CMAKE_THREAD_LIBS_INIT)
      target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
    endif()
    

    Older CMake versions may require:

    find_package(Threads REQUIRED)
    if(THREADS_HAVE_PTHREAD_ARG)
      set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
      set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
    endif()
    if(CMAKE_THREAD_LIBS_INIT)
      target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
    endif()
    

    If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.

    Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

    Let uses a more immediate block level limited scope whereas var is function scope or global scope typically.

    It seems let was chosen most likely because it is found in so many other languages to define variables, such as BASIC, and many others.

    How to make a node.js application run permanently?

    I hope this will help you.

    At the command line, install forever:

    npm install forever -g
    

    Create an example file:

    sudo nano server.js 
    

    You can edit the file and get results directly in your browser.
    You can use filezilla or any editor to edit the file. Run this command to run the file:

    forever start --minUptime 1 --spinSleepTime 1000 -w server.js
    

    enter image description here

    Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

    In my case, I have solved this way:

    $scope.MyObject = // get from database or other sources;
    $scope.MyObject.Date = new Date($scope.MyObject.Date);
    

    and input type date is ok

    how to set radio option checked onload with jQuery

    I think you can assume, that name is unique and all radio in group has the same name. Then you can use jQuery support like that:

    $("[name=gender]").val(["Male"]);
    

    Note: Passing array is important.

    Conditioned version:

    if (!$("[name=gender]:checked").length) {
        $("[name=gender]").val(["Male"]);
    }
    

    How to Read and Write from the Serial Port

    Note that usage of a SerialPort.DataReceived event is optional. You can set proper timeout using SerialPort.ReadTimeout and continuously call SerialPort.Read() after you wrote something to a port until you get a full response.

    Moreover you can use SerialPort.BaseStream property to extract an underlying Stream instance. The benefit of using a Stream is that you can easily utilize various decorators with it:

    var port = new SerialPort();
    // LoggingStream inherits Stream, implements IDisposable, needen abstract methods and 
    // overrides needen virtual methods. 
    Stream portStream = new LoggingStream(port.BaseStream);
    portStream.Write(...); // Logs write buffer.
    portStream.Read(...); // Logs read buffer.
    

    For more information check:

    rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

    I am using Rails REE (2.3.4) for a legacy system we have. After upgrading to El Capitan, running script/console enerated an error and my app would no longer start (using pow):

    $ script/console
    Loading development environment (Rails 2.3.4)
    /blah-blah/gems/activerecord-2.3.4/lib/active_record/connection_adapters/abstract/connection_specification.rb:76:in establish_connection:RuntimeError: Please install the mysql2 adapter: gem install activerecord-mysql2-adapter (dlopen(/blah-blah/gems/mysql2-0.2.19b4/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.18.dylib
      Referenced from: /blah-blah/gems/mysql2-0.2.19b4/lib/mysql2/mysql2.bundle
      Reason: image not found - /blah-blah/gems/mysql2-0.2.19b4/lib/mysql2/mysql2.bundle)
    


    From this very thread, above, I determined that I needed to issue this command in terminal:
    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
    This command produced an error: "ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted". I have never seen that error before.

    After quite a bit of digging, I found this article: http://www.macworld.com/article/2986118/security/how-to-modify-system-integrity-protection-in-el-capitan.html and followed the instructions to turn SIP (El Capitan's new System Integrity Protection) off. After turning SIP off, and after rebooting, the ln command worked fine. Then I turned SIP off. Now all is fine. My app runs again using pow and no error running script/console. I hope this helps you.

    Python Pandas Replacing Header with Top Row

    --another way to do this

    
    df.columns = df.iloc[0]
    df = df.reindex(df.index.drop(0)).reset_index(drop=True)
    df.columns.name = None
    
        Sample Number  Group Number  Sample Name  Group Name
    0             1.0           1.0          s_1         g_1
    1             2.0           1.0          s_2         g_1
    2             3.0           1.0          s_3         g_1
    3             4.0           2.0          s_4         g_2
    
    

    If you like it hit up arrow. Thanks

    Default visibility for C# classes and members (fields, methods, etc.)?

    From MSDN:

    Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


    Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

    Default Nested Member Accessibility & Allowed Accessibility Modifiers

    Source: Accessibility Levels (C# Reference) (December 6th, 2017)

    Send an Array with an HTTP Get

    That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

    While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

    Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

    foo=value1&foo=value2&foo=value3
    
    String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]
    

    The request.getParameter("foo") will also work on it, but it'll return only the first value.

    String foo = request.getParameter("foo"); // value1
    

    And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

    foo[]=value1&foo[]=value2&foo[]=value3
    
    $foo = $_GET["foo"]; // [value1, value2, value3]
    echo is_array($foo); // true
    

    In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

    $foo = $_GET["foo"]; // value1
    echo is_array($foo); // false
    

    Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

    String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]
    

    How can I concatenate two arrays in Java?

    Please forgive me for adding yet another version to this already long list. I looked at every answer and decided that I really wanted a version with just one parameter in the signature. I also added some argument checking to benefit from early failure with sensible info in case of unexpected input.

    @SuppressWarnings("unchecked")
    public static <T> T[] concat(T[]... inputArrays) {
      if(inputArrays.length < 2) {
        throw new IllegalArgumentException("inputArrays must contain at least 2 arrays");
      }
    
      for(int i = 0; i < inputArrays.length; i++) {
        if(inputArrays[i] == null) {
          throw new IllegalArgumentException("inputArrays[" + i + "] is null");
        }
      }
    
      int totalLength = 0;
    
      for(T[] array : inputArrays) {
        totalLength += array.length;
      }
    
      T[] result = (T[]) Array.newInstance(inputArrays[0].getClass().getComponentType(), totalLength);
    
      int offset = 0;
    
      for(T[] array : inputArrays) {
        System.arraycopy(array, 0, result, offset, array.length);
    
        offset += array.length;
      }
    
      return result;
    }