Programs & Examples On #Tmail

element not interactable exception in selenium web automation

If it's working in the debug, then wait must be the proper solution.
I will suggest to use the explicit wait, as given below:

WebDriverWait wait = new WebDriverWait(new ChromeDriver(), 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#Passwd")));

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

I had the same problem, then I did this two steps:

  • Enable "Allow less secure apps" on your google account security policy.
  • Restart your local servers.

Passing bash variable to jq

I resolved this issue by escaping the inner double quotes

projectID=$(cat file.json | jq -r ".resource[] | select(.username==\"$EMAILID\") | .id")

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

Change your code from:

render() {
    return (
      <ol>
        {this.props.results.map((result) => (
          <li>{result.text}</li>
        ))}
      </ol>
    );
}

To:

render() {
    return (
      <ol>
        {this.props.results.map((result) => (
          <li key={result.id}>{result.text}</li>
        ))}
      </ol>
    );
}

Then solved.

Failed to authenticate on SMTP server error using gmail

I had the same issue, but when I ran the following command, it was ok:

php artisan config:cache

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

i was facing this problem and i checked all the answers and nothing worked for me, but then i reset mail.php and didn't touch it and set the mail server from .env file and it worked perfectly, hope this will save the time for someone :).

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?

Without any SMTP server sending mail,use this code for sending mail....

click below for mail sending code

Click here

listen guys first you can do this less secure your gmail account after send mail with your gmail account

You can use this php.ini setting

;smtp = smtp.gmail.com
;smtp-port = 25
;sendmail_from = my gmail is here

And sendmail.ini settings

smtp_server = smtp.gmail.com
smtp_port = 465
smtp_ssl = auto
auth_username = my gmail is here
auth_password = password
hostname = localhost

you can try this changes and i hope this code sent mail....

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?

To list the globally installed composer packages:

composer global show -i

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

You have to loop through every cell in the range "D3:D6" and construct your To string. Simply assigning it to a variant will not solve the purpose. EmailTo becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To string

Is this what you are trying? (TRIED AND TESTED)

Option Explicit

Sub Mail_workbook_Outlook_1()
     'Working in 2000-2010
     'This example send the last saved version of the Activeworkbook
    Dim OutApp As Object
    Dim OutMail As Object
    Dim emailRng As Range, cl As Range
    Dim sTo As String

    Set emailRng = Worksheets("Selections").Range("D3:D6")

    For Each cl In emailRng 
        sTo = sTo & ";" & cl.Value
    Next

    sTo = Mid(sTo, 2)

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

    On Error Resume Next
    With OutMail
        .To = sTo
        .CC = "[email protected];[email protected]"
        .BCC = ""
        .Subject = "RMA #" & Worksheets("RMA").Range("E1")
        .Body = "Attached to this email is RMA #" & _
        Worksheets("RMA").Range("E1") & _
        ". Please follow the instructions for your department included in this form."
        .Attachments.Add ActiveWorkbook.FullName
         'You can add other files also like this
         '.Attachments.Add ("C:\test.txt")

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Sending email with PHP from an SMTP server

The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.

  1. mail() uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.
  2. mail() uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.
  3. Mailing libraries use direct connections. Libs are easier to set up. I used SwiftMailer and it perfectly sends mail from Gmail account. I think that PHPMailer is pretty good too.

No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail() function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer class or interface with abstract send() method. Inherit two classes MyPhpMailer and MySwiftMailer. Implement send() method in appropriate ways.

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)

Something I noticed was that I had "other_database" and "Other_Database" in my databases. That caused this problem as I actually had same reference in other database which caused this mysterious error!

CSS - center two images in css side by side

Flexbox can do this with just two css rules on a surrounding div.

_x000D_
_x000D_
.social-media{_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using CSS for a fade-in effect on page load

Looking forward to Web Animations in 2020.

_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        transform: `translateY(${el.getBoundingClientRect().top}px)`
      },
    ], {
      duration: durationInMs,
      easing: 'ease-in',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeIn(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        opacity: '0.5',
        offset: 0.5
      },
      {
        opacity: '1',
        offset: 1
      }
    ], {
      duration: durationInMs,
      easing: 'linear',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeInSections() {
  for (const section of document.getElementsByTagName('section')) {
    await fadeIn(section, 200);
  }
}

window.addEventListener('load', async() => {
  await moveToPosition(document.getElementById('headerContent'), 500);
  await fadeInSections();
  await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
  height: 100vh;
}

header {
  height: 20%;
}

.text-center {
  text-align: center;
}

.leading-none {
  line-height: 1;
}

.leading-3 {
  line-height: .75rem;
}

.leading-2 {
  line-height: .25rem;
}

.bg-black {
  background-color: rgba(0, 0, 0, 1);
}

.bg-gray-50 {
  background-color: rgba(249, 250, 251, 1);
}

.pt-12 {
  padding-top: 3rem;
}

.pt-2 {
  padding-top: 0.5rem;
}

.text-lightGray {
  color: lightGray;
}

.container {
  display: flex;
  /* or inline-flex */
  justify-content: space-between;
}

.container section {
  padding: 0.5rem;
}

.opacity-0 {
  opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="Web site created using create-snowpack-app" />
  <link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>

<body>
  <header class="bg-gray-50">
    <div id="headerContent">
      <h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
      <p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
    </div>
  </header>
  <div class="container">
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 1</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 2</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>

    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 3</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
  </div>
  <footer class="opacity-0">
    <h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
    <p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
  </footer>
</body>

</html>
_x000D_
_x000D_
_x000D_

Must issue a STARTTLS command first

smtp port and socketFactory has to be change

    String to = "[email protected]";
    String subject = "subject"
    String msg ="email text...."
    final String from ="[email protected]"
    final  String password ="senderPassword"


    Properties props = new Properties();  
    props.setProperty("mail.transport.protocol", "smtp");     
    props.setProperty("mail.host", "smtp.gmail.com");  
    props.put("mail.smtp.auth", "true");  
    props.put("mail.smtp.port", "465");  
    props.put("mail.debug", "true");  
    props.put("mail.smtp.socketFactory.port", "465");  
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  
    props.put("mail.smtp.socketFactory.fallback", "false");  
    Session session = Session.getDefaultInstance(props,  
    new javax.mail.Authenticator() {
       protected PasswordAuthentication getPasswordAuthentication() {  
       return new PasswordAuthentication(from,password);  
   }  
   });  

   //session.setDebug(true);  
   Transport transport = session.getTransport();  
   InternetAddress addressFrom = new InternetAddress(from);  

   MimeMessage message = new MimeMessage(session);  
   message.setSender(addressFrom);  
   message.setSubject(subject);  
   message.setContent(msg, "text/plain");  
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  

   transport.connect();  
   Transport.send(message);  
   transport.close();
   }  

hope it will work for you..

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

send email by smtp

public void EmailSend(string subject, string host, string from, string to, string body, int port, string username, string password, bool enableSsl)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient smtpServer = new SmtpClient(host);
            mail.Subject = subject;
            mail.From = new MailAddress(from);
            mail.To.Add(to);
            mail.Body = body;
            smtpServer.Port = port;
            smtpServer.Credentials = new NetworkCredential(username, password);
            smtpServer.EnableSsl = enableSsl;
            smtpServer.Send(mail);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

How do I remove link underlining in my HTML email?

I see this has been answered; however, I feel this link provides appropriate information for what formatting is supported in various email clients.

http://www.campaignmonitor.com/css/

It's worth noting that GMail and Outlook are two of the pickiest to format HTML email for.

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

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

Add below code in your client code :

static {
    Security.insertProviderAt(new BouncyCastleProvider(),1);
 }

with this there is no need to add any entry in java.security file.

php mail setup in xampp

Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.

In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.

You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.

"SMTP Error: Could not authenticate" in PHPMailer

If you still face error in sending email, with the same error message. Try this:

$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';

just Before the line:

$send = $mail->Send();

or in other sense, before calling the Send() Function.

Tested and Working.

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

Pretty simple...you could put all of them in a cell using the concatenate function:

=CONCATENATE(A1, ", ", A2, ", ", and so on)

Invalid length for a Base-64 char array

I'm not Reputable enough to upvote or comment yet, but LukeH's answer was spot on for me.

As AES encryption is the standard to use now, it produces a base64 string (at least all the encrypt/decrypt implementations I've seen). This string has a length in multiples of 4 (string.length % 4 = 0)

The strings I was getting contained + and = on the beginning or end, and when you just concatenate that into a URL's querystring, it will look right (for instance, in an email you generate), but when the the link is followed and the .NET page recieves it and puts it into this.Page.Request.QueryString, those special characters will be gone and your string length will not be in a multiple of 4.

As the are special characters at the FRONT of the string (ex: +), as well as = at the end, you can't just add some = to make up the difference as you are altering the cypher text in a way that doesn't match what was actually in the original querystring.

So, wrapping the cypher text with HttpUtility.URLEncode (not HtmlEncode) transforms the non-alphanumeric characters in a way that ensures .NET parses them back into their original state when it is intepreted into the querystring collection.

The good thing is, we only need to do the URLEncode when generating the querystring for the URL. On the incoming side, it's automatically translated back into the original string value.

Here's some example code

string cryptostring = MyAESEncrypt(MySecretString);
string URL = WebFunctions.ToAbsoluteUrl("~/ResetPassword.aspx?RPC=" + HttpUtility.UrlEncode(cryptostring));

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

The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files

SET xyz=%~1

Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).

But, This simple tilde syntax will not work for other variables that were not passed in as parameters

For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.

@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%

If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows

@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%

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

select email from mytable group by email having count(*) >1

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

Just add text-align: center; to your <ul>. Problem solved.

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

Even though this question is closed, I'd like to post a counter solution, but now using Simple Java Mail (Open Source JavaMail smtp wrapper):

final Email email = new Email();

String host = "smtp.gmail.com";
Integer port = 587;
String from = "username";
String pass = "password";
String[] to = {"[email protected]"};

email.setFromAddress("", from);
email.setSubject("sending in a group");
for( int i=0; i < to.length; i++ ) {
    email.addRecipient("", to[i], RecipientType.TO);
}
email.setText("Welcome to JavaMail");

new Mailer(host, port, from, pass).sendMail(email);
// you could also still use your mail session instead
new Mailer(session).sendMail(email);

What is the difference between Sessions and Cookies in PHP?

Cookie

  • is a small amount of data saved in the browser (client-side)

  • can be set from PHP with setcookie and then will be sent to the client's browser (HTTP response header Set-cookie)

  • can be set directly client-side in Javascript: document.cookie = 'foo=bar';

  • if no expiration date is set, by default, it will expire when the browser is closed.
    Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';. Close the tab, reopen the same website, open the Console, do document.cookie: you will see foo=bar is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie is empty.

  • you can also set a precise expiration date other than "deleted when browser is closed".

  • the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:

    enter image description here

  • can be read client-side with document.cookie

  • can be read server-side with $_COOKIE['foo']

  • Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):

    from bottle import get, run, request, response
    @get('/')
    def index():
        if request.get_cookie("visited"):
            return "Welcome back! Nice to see you again"
        else:
            response.set_cookie("visited", "yes")
            return "Hello there! Nice to meet you"
    run(host='localhost', port=8080, debug=True, reloader=True)
    

Session

  • is some data relative to a browser session saved server-side

  • each server-side language may implement it in a different way

  • in PHP, when session_start(); is called:

    • a random ID is generated by the server, e.g. jo96fme9ko0f85cdglb3hl6ah6
    • a file is saved on the server, containing the data: e.g. /var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
    • the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/:

      enter image description here

      (it can also be be sent via the URL instead of cookie but not the default behaviour)

    • you can see the session ID on client-side with document.cookie:

      enter image description here

  • the PHPSESSID cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.

  • can be set/read in PHP with $_SESSION

  • the client-side does not see the session data but only the ID: do this in index.php:

    <?php
    session_start();
    $_SESSION["abc"]="def";
    ?>
    

    The only thing that is seen on client-side is (as mentioned above) the session ID:

    enter image description here

  • because of this, session is useful to store data that you don't want to be seen or modified by the client

  • you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie

INSERT with SELECT

Of course you can.

One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).

So be careful.

Here is the syntax of the command:

INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;

Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:

SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;

This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).

How to 'foreach' a column in a DataTable using C#?

Something like this:

 DataTable dt = new DataTable();

 // For each row, print the values of each column.
    foreach(DataRow row in dt .Rows)
    {
        foreach(DataColumn column in dt .Columns)
        {
            Console.WriteLine(row[column]);
        }
    }

http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx

How to start anonymous thread class

The entire new expression is an object reference, so methods can be invoked on it:

public class A {
    public static void main(String[] arg)
    {
        new Thread()
        {
            public void run() {
                System.out.println("blah");
            }
        }.start();
    }
}

gcloud command not found - while installing Google Cloud SDK

You just have to execute this command as root

$ curl https://sdk.cloud.google.com | bash

Restart the terminal and that's it. Now all commands should be executed as root

Import Excel Data into PostgreSQL 9.3

The typical answer is this:

  1. In Excel, File/Save As, select CSV, save your current sheet.

  2. transfer to a holding directory on the Pg server the postgres user can access

  3. in PostgreSQL:

    COPY mytable FROM '/path/to/csv/file' WITH CSV HEADER; -- must be superuser
    

But there are other ways to do this too. PostgreSQL is an amazingly programmable database. These include:

  1. Write a module in pl/javaU, pl/perlU, or other untrusted language to access file, parse it, and manage the structure.

  2. Use CSV and the fdw_file to access it as a pseudo-table

  3. Use DBILink and DBD::Excel

  4. Write your own foreign data wrapper for reading Excel files.

The possibilities are literally endless....

Remove file from SVN repository without deleting local copy

Rename your file, commit the changes including the "deleted" file, and don't include the new (renamed) file.

Rename your file back.

Change image size via parent div

Actually using 100% will not make the image bigger if the image is smaller than the div size you specified. You need to set one of the dimensions, height or width in order to have all images fill the space. In my experience it's better to have the height set so each row is the same size, then all items wrap to next line properly. This will produce an output similar to fotolia.com (stock image website)

with css:

parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 42px;
}

without:

<div style="height:42px;width:42px">
    <img style="height:42px" src="http://someimage.jpg">
</div>

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

Java, How do I get current index/key in "for each" loop

In Java, you can't, as foreach was meant to hide the iterator. You must do the normal For loop in order to get the current iteration.

How do I give ASP.NET permission to write to a folder in Windows 7?

My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...

@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

Broadcast Receivers timeout after 10 seconds. Possibly your doing an asynchronous call (wrong) from a broadcast receiver and 4.3 actually detects it.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Apologies in advance for this lo-tech suggestion, but another option, which finally worked for me after battling NuGet for several hours, is to re-create a new empty project, Web API in my case, and just copy the guts of your old, now-broken project into the new one. Took me about 15 minutes.

What is the difference between atan and atan2 in C++?

atan(x) Returns the principal value of the arc tangent of x, expressed in radians.

atan2(y,x) Returns the principal value of the arc tangent of y/x, expressed in radians.

Notice that because of the sign ambiguity, a function cannot determine with certainty in which quadrant the angle falls only by its tangent value (atan alone). You can use atan2 if you need to determine the quadrant.

In Python, how do you convert seconds since epoch to a `datetime` object?

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

"This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038"

See also Issue1646728

py2exe - generate single executable file

As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.

Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.

I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.

Can anyone explain python's relative imports?

You are importing from package "sub". start.py is not itself in a package even if there is a __init__.py present.

You would need to start your program from one directory over parent.py:

./start.py

./pkg/__init__.py
./pkg/parent.py
./pkg/sub/__init__.py
./pkg/sub/relative.py

With start.py:

import pkg.sub.relative

Now pkg is the top level package and your relative import should work.


If you want to stick with your current layout you can just use import parent. Because you use start.py to launch your interpreter, the directory where start.py is located is in your python path. parent.py lives there as a separate module.

You can also safely delete the top level __init__.py, if you don't import anything into a script further up the directory tree.

How to return a part of an array in Ruby?

Ruby 2.6 Beginless/Endless Ranges

(..1)
# or
(...1)

(1..)
# or
(1...)

[1,2,3,4,5,6][..3]
=> [1, 2, 3, 4]

[1,2,3,4,5,6][...3]
 => [1, 2, 3]

ROLES = %w[superadmin manager admin contact user]
ROLES[ROLES.index('admin')..]
=> ["admin", "contact", "user"]

How to solve ADB device unauthorized in Android ADB host device?

  • Get the public key from the client phone (adb host)

    cat /data/.android/adbkey.pub

  • copy the above public key to the target phone's /data/misc/adb/adb_keys location. (you may need to stop the adb daemon first with stop adbd)

    cat /data/misc/adb/adb_keys

verify both cat outputs match.

try restarting adb daemon on target start adbd or just reboot them.

If you are having problems reading or writing to ADB KEYS in above steps, try setting environment variable ADB_KEYS_PATH with a temporary path (eg: /data/local/tmp). Refer to that link it goes into more details

    "On the host, the user public/private key pair is automatically generated,
    if it does not exist, when the adb daemon starts and is stored in
    $HOME/.android/adb_key(.pub) or in $ANDROID_SDK_HOME on windows. If needed,
    the ADB_KEYS_PATH env variable may be set to a :-separated (; under
    Windows) list of private keys, e.g. company-wide or vendor keys.

    On the device, vendors public keys are installed at build time in
    /adb_keys. User-installed keys are stored in /data/misc/adb/adb_keys"

How can I adjust DIV width to contents

EDIT2- Yea auto fills the DOM SOZ!

#img_box{        
    width:90%;
    height:90%;
    min-width: 400px;
    min-height: 400px;
}

check out this fiddle

http://jsfiddle.net/ppumkin/4qjXv/2/

http://jsfiddle.net/ppumkin/4qjXv/3/

and this page

http://www.webmasterworld.com/css/3828593.htm

Removed original answer because it was wrong.

The width is ok- but the height resets to 0

so

 min-height: 400px;

Align image in center and middle within div

I've tried many approaches but only this one works for multiple inline elements inside a container div. Here is code to align everything in div at middle.

CSS

.divContainer
{
    vertical-align: middle;
    text-align: center; <!-- If you want horizontal center alignment -->
}
.divContainer > *
{
    vertical-align: middle;
}

HTML

<div class="divContainer">
    <span>Middle Text</span>
    <img src="test.png"/>
</div>

Sample code is here: https://jsfiddle.net/yogendrasinh/2vq0c68m/

Using VBA to get extended file attributes

'vb.net
'Extended file stributes
'visual basic .net sample 

Dim sFile As Object
        Dim oShell = CreateObject("Shell.Application")
        Dim oDir = oShell.Namespace("c:\temp")

        For i = 0 To 34
            TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(oDir, i) & vbCrLf
            For Each sFile In oDir.Items
                TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(sFile, i) & vbCrLf
            Next
            TextBox1.Text = TextBox1.Text & vbCrLf
        Next

How do you get the index of the current iteration of a foreach loop?

I wasn't sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even.

string[] names = { "one", "two", "three" };
var oddOrEvenByName = names
    .Select((name, index) => new KeyValuePair<string, int>(name, index % 2))
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list.

Get the latest record with filter in Django

last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

New answer: Use DiffUtil for all RecyclerView updates. This will help with both performance and the bug above. See Here

Previous answer: This worked for me. The key is to not use notifyDataSetChanged() and to do the right things in the correct order:

public void setItems(ArrayList<Article> newArticles) {
    //get the current items
    int currentSize = articles.size();
    //remove the current items
    articles.clear();
    //add all the new items
    articles.addAll(newArticles);
    //tell the recycler view that all the old items are gone
    notifyItemRangeRemoved(0, currentSize);
    //tell the recycler view how many new items we added
    notifyItemRangeInserted(0, newArticles.size());
}

trying to align html button at the center of the my page

There are multiple ways to fix the same. PFB two of them -

1st Way using position: fixed - position: fixed; positions relative to the viewport, which means it always stays in the same place even if the page is scrolled. Adding the left and top value to 50% will place it into the middle of the screen.

 button {
   position: fixed;
   left: 50%;
   top:50%;
 }

2nd Way using margin: auto -margin: 0 auto; for horizontal centering, but margin: auto; has refused to work for vertical centering… until now! But actually absolute centering only requires a declared height and these styles:

button {
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 40px;
}

Align the form to the center in Bootstrap 4

You need to use the various Bootstrap 4 centering methods...

  • Use text-center for inline elements.
  • Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="[email protected]">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
                </div>
            </div>
        </div>
    </div>
</section>

grep a file, but show several surrounding lines?

You can use option -A (after) and -B (before) in your grep command try grep -nri -A 5 -B 5 .

Disable a Button

in order for this to work:

yourButton.isEnabled = false

you need to create an outlet in addition to your UI button.

How to build and run Maven projects after importing into Eclipse IDE

When you add dependency in pom.xml , do a maven clean , and then maven build , it will add the jars into you project.

You can search dependency artifacts at http://mvnrepository.com/

And if it doesn't add jars it should give you errors which will mean that it is not able to fetch the jar, that could be due to broken repository or connection problems.

Well sometimes if it is one or two jars, better download them and add to build path , but with a lot of dependencies use maven.

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Perform the following steps:

  1. Start the Registry Editor by typing regedit in the Run window.
  2. Select the following key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
  3. In the Security menu, click Permissions.
  4. Grant Full Permission to the account which is being used for making connections.
  5. Quit the Registry Editor.

TypeError: module.__init__() takes at most 2 arguments (3 given)

You may also do the following in Python 3.6.1

from Object import Object as Parent

and your class definition to:

class Visitor(Parent):

How to parse JSON and access results

If your $result variable is a string json like, you must use json_decode function to parse it as an object or array:

$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);

OUTPUT

Array
(
    [Cancelled] => 
    [MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
    [Queued] => 
    [SMSError] => 2
    [SMSIncomingMessages] => 
    [Sent] => 
    [SentDateTime] => /Date(-62135578800000-0500)/
)

Now you can work with $json variable as an array:

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff

References:

Copy files to network computers on windows command line

Below command will work in command prompt:

copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y

To Copy all files:

copy c:\folder\*.* \\dest-machine\destfolder /Z /Y

Running code in main thread from another thread

public void mainWork() {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            //Add Your Code Here
        }
    });
}

This can also work in a service class with no issue.

Java: Identifier expected

Try it like this instead, move your myclass items inside a main method:

    class UserInput {
      public void name() {
        System.out.println("This is a test.");
      }
    }

    public class MyClass {

        public static void main( String args[] )
        {
            UserInput input = new UserInput();
            input.name();
        }

    }

Iterating through a JSON object

I would solve this problem more like this

import json
import urllib2

def last_song(user, limit):
    # Assembling strings with "foo" + str(bar) + "baz" + ... generally isn't 
    # as nice as using real string formatting. It can seem simpler at first, 
    # but leaves you less happy in the long run.
    url = 'http://gsuser.com/lastSong/%s/%d/' % (user, limit)

    # urllib.urlopen is deprecated in favour of urllib2.urlopen
    site = urllib2.urlopen(url)

    # The json module has a function load for loading from file-like objects, 
    # like the one you get from `urllib2.urlopen`. You don't need to turn 
    # your data into a string and use loads and you definitely don't need to 
    # use readlines or readline (there is seldom if ever reason to use a 
    # file-like object's readline(s) methods.)
    songs = json.load(site)

    # I don't know why "lastSong" stuff returns something like this, but 
    # your json thing was a JSON array of two JSON objects. This will 
    # deserialise as a list of two dicts, with each item representing 
    # each of those two songs.
    #
    # Since each of the songs is represented by a dict, it will iterate 
    # over its keys (like any other Python dict). 
    baby, feel_good = songs

    # Rather than printing in a function, it's usually better to 
    # return the string then let the caller do whatever with it. 
    # You said you wanted to make the output pretty but you didn't 
    # mention *how*, so here's an example of a prettyish representation
    # from the song information given.
    return "%(SongName)s by %(ArtistName)s - listen at %(link)s" % baby

Can I extend a class using more than 1 class in PHP?

Classes are not meant to be just collections of methods. A class is supposed to represent an abstract concept, with both state (fields) and behaviour (methods) which changes the state. Using inheritance just to get some desired behaviour sounds like bad OO design, and exactly the reason why many languages disallow multiple inheritance: in order to prevent "spaghetti inheritance", i.e. extending 3 classes because each has a method you need, and ending up with a class that inherits 100 method and 20 fields, yet only ever uses 5 of them.

How to change the style of alert box?

I don't think you could change the style of browsers' default alert boxes.

You need to create your own or use a simple and customizable library like xdialog. Following is a example to customize the alert box. More demos can be found here.

_x000D_
_x000D_
function show_alert() {_x000D_
    xdialog.alert("Hello! I am an alert box!");_x000D_
}
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.css"/>_x000D_
    <script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.js"></script>_x000D_
    _x000D_
    <style>_x000D_
        .xd-content .xd-body .xd-body-inner {_x000D_
            max-height: unset;_x000D_
        }_x000D_
        .xd-content .xd-body p {_x000D_
            color: #f0f;_x000D_
            text-shadow: 0 0 5px rgba(0, 0, 0, 0.75);_x000D_
        }_x000D_
        .xd-content .xd-button.xd-ok {_x000D_
            background: #734caf;_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
<body>_x000D_
    <input type="button" onclick="show_alert()" value="Show alert box" />_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to convert a 3D point into 2D perspective projection?

I'm not sure at what level you're asking this question. It sounds as if you've found the formulas online, and are just trying to understand what it does. On that reading of your question I offer:

  • Imagine a ray from the viewer (at point V) directly towards the center of the projection plane (call it C).
  • Imagine a second ray from the viewer to a point in the image (P) which also intersects the projection plane at some point (Q)
  • The viewer and the two points of intersection on the view plane form a triangle (VCQ); the sides are the two rays and the line between the points in the plane.
  • The formulas are using this triangle to find the coordinates of Q, which is where the projected pixel will go

make bootstrap twitter dialog modal draggable

i did this:

$("#myModal").modal({}).draggable();

and it make my very standard/basic modal draggable.

not sure how/why it worked, but it did.

Why does viewWillAppear not get called when an app comes back from the background?

Use Notification Center in the viewDidLoad: method of your ViewController to call a method and from there do what you were supposed to do in your viewWillAppear: method. Calling viewWillAppear: directly is not a good option.

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"view did load");

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(applicationIsActive:) 
        name:UIApplicationDidBecomeActiveNotification 
        object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(applicationEnteredForeground:) 
        name:UIApplicationWillEnterForegroundNotification
        object:nil];
}

- (void)applicationIsActive:(NSNotification *)notification {
    NSLog(@"Application Did Become Active");
}

- (void)applicationEnteredForeground:(NSNotification *)notification {
    NSLog(@"Application Entered Foreground");
}

Getting A File's Mime Type In Java

Because there's so many answers linking to libraries, or non-portable code; I thought I'd share an alternative way by simply checking the magic bytes of the stream or file that you want to know the type of, as I've shown here : https://stackoverflow.com/a/65667558/3225638

It uses native java, but requires you to define in the enum the types you would want to handle/detect beforehand, but you'd only have to do it once.

How to get numeric position of alphabets in java?

char letter;
for(int i=0; i<text.length(); i++)
{
    letter = text.charAt(i);
    if(letter>='A' && letter<='Z')
        System.out.println((int)letter - 'A'+1);
    if(letter>='a' && letter<= 'z')
        System.out.println((int)letter - 'a'+1);
}

How to deal with SQL column names that look like SQL keywords?

You can put your column name in bracket like:

Select  [from] from < ur_tablename>

Or

Put in a temprary table then use as you like.
Example:

Declare @temp_table table(temp_from varchar(max))

Insert into @temp_table
Select * from your_tablename

Here I just assume that your_tablename contains only one column (i.e. from).

How can I remove text within parentheses with a regex?

Java code:

Pattern pattern1 = Pattern.compile("(\\_\\(.*?\\))");
System.out.println(fileName.replace(matcher1.group(1), ""));

How to format a QString?

You can use QString.arg like this

QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"

This method is preferred over sprintf because:

Changing the position of the string without having to change the ordering of substitution, e.g.

// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");

Or, changing the type of the arguments doesn't require changing the format string, e.g.

// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));

As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.

One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.

UPDATE: Examples are updated thanks to Frank Osterfeld.

UPDATE: Examples are updated thanks to alexisdm.

What's the scope of a variable initialized in an if statement?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

How do I use Comparator to define a custom sort order?

I will do something like this:

List<String> order = List.of("Red", "Green", "Magenta", "Silver");

Comparator.comparing(Car::getColor(), Comparator.comparingInt(c -> order.indexOf(c)))

All credits go to @Sean Patrick Floyd :)

Using RegEX To Prefix And Append In Notepad++

Why don't you use the Notepad++ multiline editing capabilities?

Hold down Alt while selecting text (using your usual click-and-drag approach) to select text across multiple lines. This is sometimes also referred to as column editing.

You could place the cursor at the beginning of the file, Press (and hold) Alt, Shift and then just keep pressing the down-arrow or PageDown to select the lines that you want to prepend with some text :-) Easy. Multiline editing is a very useful feature of Notepad++. It's also possible in Visual Studio, in the same manner, and also in Eclipse by switching to Block Selection Mode by pressing Alt+Shift+A and then use mouse to select text across lines.

Directory-tree listing in Python

Here is a one line Pythonic version:

import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]

This code lists the full path of all files and directories in the given directory name.

Join two sql queries

Try this:

select Activity, SUM(Incomes.Amount) as "Total Amount 2009", SUM(Incomes2008.Amount) 
as "Total Amount 2008" from
Activities, Incomes, Incomes2008
where Activities.UnitName = ?  AND
Incomes.ActivityId = Activities.ActivityID  AND
Incomes2008.ActivityId = Activities.ActivityID GROUP BY
Activity ORDER BY Activity;

Basically you have to JOIN Incomes2008 table with the output of your first query.

What is the meaning of prepended double colon "::"?

Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. :: works a lot like the filesystem directory separator '/', when searching your path for a program you'd like to run. Consider:

/path/to/executable

This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...

::std::cout

...is equally explicit in the C++ namespace "tree".

Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH environment variable, so if PATH=/usr/bin:/usr/local/bin, and you were "in" /tmp, then...

X11/xterm

...would happily run /tmp/X11/xterm if found, else /usr/bin/X11/xterm, else /usr/local/bin/X11/xterm. Similarly, say you were in a namespace called X, and had a "using namespace Y" in effect, then...

std::cout

...could be found in any of ::X::std::cout, ::std::cout, ::Y::std::cout, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std", nor anything called "cout", so in practice using only std::cout is fine.

Noteworthy differences:

1) shells tend to use the first match using the ordering in PATH, whereas C++ gives a compiler error when you've been ambiguous.

2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put . in the PATH.

3) C++ always searches the global namespace (like having / implicitly your PATH).

General discussion on namespaces and explicitness of symbols

Using absolute ::abc::def::... "paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.

As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std:: that are less "unique" than cout, that programmers might use for something completely different in their code (e.g. merge, includes, fill, generate, exchange, queue, toupper, max). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespaces: the worst thing you can do in this space is allow using namespaces in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.

So, a leading :: is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....

How to use a FolderBrowserDialog from a WPF application

I realize this is an old question, but here is an approach which might be slightly more elegant (and may or may not have been available before)...

using System;
using System.Windows;
using System.Windows.Forms;

// ...

/// <summary>
///     Utilities for easier integration with WinForms.
/// </summary>
public static class WinFormsCompatibility {

    /// <summary>
    ///     Gets a handle of the given <paramref name="window"/> and wraps it into <see cref="IWin32Window"/>,
    ///     so it can be consumed by WinForms code, such as <see cref="FolderBrowserDialog"/>.
    /// </summary>
    /// <param name="window">
    ///     The WPF window whose handle to get.
    /// </param>
    /// <returns>
    ///     The handle of <paramref name="window"/> is returned as <see cref="IWin32Window.Handle"/>.
    /// </returns>
    public static IWin32Window GetIWin32Window(this Window window) {
        return new Win32Window(new System.Windows.Interop.WindowInteropHelper(window).Handle);
    }

    /// <summary>
    ///     Implementation detail of <see cref="GetIWin32Window"/>.
    /// </summary>
    class Win32Window : IWin32Window { // NOTE: This is System.Windows.Forms.IWin32Window, not System.Windows.Interop.IWin32Window!

        public Win32Window(IntPtr handle) {
            Handle = handle; // C# 6 "read-only" automatic property.
        }

        public IntPtr Handle { get; }

    }

}

Then, from your WPF window, you can simply...

public partial class MainWindow : Window {

    void Button_Click(object sender, RoutedEventArgs e) {
        using (var dialog = new FolderBrowserDialog()) {
            if (dialog.ShowDialog(this.GetIWin32Window()) == System.Windows.Forms.DialogResult.OK) {
                // Use dialog.SelectedPath.
            }
        }
    }

}

Actually, does it matter?

I'm not sure if it matters in this case, but generally, you should tell Windows what is your window hierarchy, so if a parent window is clicked while child window is modal, Windows can provide a visual (and possibly audible) clue to the user.

Also, it ensures the "right" window is on top when there are multiple modal windows (not that I'm advocating such UI design). I've seen UIs designed by a certain multi-billion dollar corporation (which shell remain unnamed), that hanged simply because one modal dialog got "stuck" underneath another, and user had no clue it was even there, let alone how to close it.

matplotlib colorbar for scatter

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

How does this work for you?

import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()

Image Example

Install Visual Studio 2013 on Windows 7

Fake IE10 to install Visual Studio 2013

Visual Studio 2013 requires Internet Explorer 10. If you try to install it on Windows 7 with IE8 you get the following error This version of Visual Studio requires Internet Explorer 10”. The value that the VS 2013 installer checks is svcVersion in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorerkey on 32-bit Windows and HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer on 64-bit Windows. Any value >= 10.0.0.0 makes the installer happy.

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"

How to view method information in Android Studio?

Android Studio 1.2.2 has moved the setting into the General subfolder of Editor settings.


enter image description here

Custom Adapter for List View

Google has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html @CommonsWare has written a good explanation of the patterns used in the above example http://commonsware.com/Android/excerpt.pdf

Java Reflection: How to get the name of a variable?

update @Marcel Jackwerth's answer for general.

and only working with class attribute, not working with method variable.

    /**
     * get variable name as string
     * only work with class attributes
     * not work with method variable
     *
     * @param headClass variable name space
     * @param vars      object variable
     * @throws IllegalAccessException
     */
    public static void printFieldNames(Object headClass, Object... vars) throws IllegalAccessException {
        List<Object> fooList = Arrays.asList(vars);
        for (Field field : headClass.getClass().getFields()) {
            if (fooList.contains(field.get(headClass))) {
                System.out.println(field.getGenericType() + " " + field.getName() + " = " + field.get(headClass));
            }
        }
    }

Iterate through dictionary values?

You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items(). Then you have both directly in variables and don't need a lookup at all:

for key, value in PIX0.items():
    NUM = input("What is the Resolution of %s?"  % key)
    if NUM == value:

You can of course use that both ways then.

Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

How to read if a checkbox is checked in PHP?

$is_checked = isset($_POST['your_checkbox_name']) &&
              $_POST['your_checkbox_name'] == 'on';

Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.

How do I change the color of radio buttons?

A quick fix would be to overlay the radio button input style using :after, however it's probably a better practice to create your own custom toolkit.

_x000D_
_x000D_
    input[type='radio']:after {_x000D_
        width: 15px;_x000D_
        height: 15px;_x000D_
        border-radius: 15px;_x000D_
        top: -2px;_x000D_
        left: -1px;_x000D_
        position: relative;_x000D_
        background-color: #d1d3d1;_x000D_
        content: '';_x000D_
        display: inline-block;_x000D_
        visibility: visible;_x000D_
        border: 2px solid white;_x000D_
    }_x000D_
_x000D_
    input[type='radio']:checked:after {_x000D_
        width: 15px;_x000D_
        height: 15px;_x000D_
        border-radius: 15px;_x000D_
        top: -2px;_x000D_
        left: -1px;_x000D_
        position: relative;_x000D_
        background-color: #ffa500;_x000D_
        content: '';_x000D_
        display: inline-block;_x000D_
        visibility: visible;_x000D_
        border: 2px solid white;_x000D_
    }
_x000D_
<input type='radio' name="gender"/>_x000D_
<input type='radio' name="gender"/>
_x000D_
_x000D_
_x000D_

What is "pom" packaging in maven?

I suggest to see the classic example at: http://maven.apache.org/guides/getting-started/index.html#How_do_I_build_more_than_one_project_at_once

Here my-webapp is web project, which depends on the code at my-app project. So to bundle two projects in one, we have top level pom.xml which mentions which are the projects (modules as per maven terminology) to be bundled finally. Such top level pom.xml can use pom packaging.

my-webapp can have war packaging and can have dependency on my-app. my-app can have jar packaging.

PostgreSQL "DESCRIBE TABLE"

In addition to the PostgreSQL way (\d 'something' or \dt 'table' or \ds 'sequence' and so on)

The SQL standard way, as shown here:

select column_name, data_type, character_maximum_length, column_default, is_nullable
from INFORMATION_SCHEMA.COLUMNS where table_name = '<name of table>';

It's supported by many db engines.

How to access component methods from “outside” in ReactJS?

Another way so easy:

function outside:

function funx(functionEvents, params) {
  console.log("events of funx function: ", functionEvents);
  console.log("this of component: ", this);
  console.log("params: ", params);
  thisFunction.persist();
}

Bind it:

constructor(props) {
   super(props);
    this.state = {};
    this.funxBinded = funx.bind(this);
  }
}

Please see complete tutorial here: How to use "this" of a React Component from outside?

Example for boost shared_mutex (multiple reads/one write)?

1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.

boost::shared_mutex _access;
void reader()
{
  boost::shared_lock< boost::shared_mutex > lock(_access);
  // do work here, without anyone having exclusive access
}

void conditional_writer()
{
  boost::upgrade_lock< boost::shared_mutex > lock(_access);
  // do work here, without anyone having exclusive access

  if (something) {
    boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
    // do work here, but now you have exclusive access
  }

  // do more work here, without anyone having exclusive access
}

void unconditional_writer()
{
  boost::unique_lock< boost::shared_mutex > lock(_access);
  // do work here, with exclusive access
}

Also Note, unlike a shared_lock, only a single thread can acquire an upgrade_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution.

RegEx for matching UK Postcodes

Have a look at the python code on this page:

http://www.brunningonline.net/simon/blog/archives/001292.html

I've got some postcode parsing to do. The requirement is pretty simple; I have to parse a postcode into an outcode and (optional) incode. The good new is that I don't have to perform any validation - I just have to chop up what I've been provided with in a vaguely intelligent manner. I can't assume much about my import in terms of formatting, i.e. case and embedded spaces. But this isn't the bad news; the bad news is that I have to do it all in RPG. :-(

Nevertheless, I threw a little Python function together to clarify my thinking.

I've used it to process postcodes for me.

How to convert milliseconds into a readable date?

You can use datejs and convert in different formate. I have tested some formate and working fine.

var d = new Date(1469433907836);

d.toLocaleString()     // 7/25/2016, 1:35:07 PM
d.toLocaleDateString() // 7/25/2016
d.toDateString()       // Mon Jul 25 2016
d.toTimeString()       // 13:35:07 GMT+0530 (India Standard Time)
d.toLocaleTimeString() // 1:35:07 PM
d.toISOString();       // 2016-07-25T08:05:07.836Z
d.toJSON();            // 2016-07-25T08:05:07.836Z
d.toString();          // Mon Jul 25 2016 13:35:07 GMT+0530 (India Standard Time)
d.toUTCString();       // Mon, 25 Jul 2016 08:05:07 GMT

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

As of SQL 2014, this can be accomplished via inline index creation:

CREATE TABLE MyTable(
    a int NOT NULL
    ,b smallint NOT NULL
    ,c smallint NOT NULL
    ,d smallint NOT NULL
    ,e smallint NOT NULL

    -- This creates a primary key
    ,CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (a)

    -- This creates a unique nonclustered index on columns b and c
    ,CONSTRAINT IX_MyTable1 UNIQUE (b, c)

    -- This creates a standard non-clustered index on (d, e)
    ,INDEX IX_MyTable4 NONCLUSTERED (d, e)
);
GO

Prior to SQL 2014, CREATE/ALTER TABLE only accepted CONSTRAINTs to be added, not indexes. The fact that primary key and unique constraints are implemented in terms of an index is a side effect.

Yahoo Finance API

Yahoo is very easy to use and provides customized data. Use the following page to learn more.

finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv

WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.

Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv

How do I convert a Swift Array to a String?

for any Element type

extension Array {

    func joined(glue:()->Element)->[Element]{
        var result:[Element] = [];
        result.reserveCapacity(count * 2);
        let last = count - 1;
        for (ix,item) in enumerated() {
            result.append(item);
            guard ix < last else{ continue }
            result.append(glue());
        }
        return result;
    }
}

How can I close a dropdown on click outside?

This is the Angular Bootstrap DropDowns button sample with close outside of component.

without use bootstrap.js

// .html
<div class="mx-3 dropdown" [class.show]="isTestButton">
  <button class="btn dropdown-toggle"
          (click)="isTestButton = !isTestButton">
    <span>Month</span>
  </button>
  <div class="dropdown-menu" [class.show]="isTestButton">
    <button class="btn dropdown-item">Month</button>
    <button class="btn dropdown-item">Week</button>
  </div>
</div>

// .ts
import { Component, ElementRef, HostListener } from "@angular/core";

@Component({
  selector: "app-test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent {

  isTestButton = false;

  constructor(private eleRef: ElementRef) {
  }


  @HostListener("document:click", ["$event"])
  docEvent($e: MouseEvent) {
    if (!this.isTestButton) {
      return;
    }
    const paths: Array<HTMLElement> = $e["path"];
    if (!paths.some(p => p === this.eleRef.nativeElement)) {
      this.isTestButton = false;
    }
  }
}

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

ImportError: No module named site on Windows

For Windows 10 (follow up on @slckin answer), this can be set through the command line with:

setx PYTHONHOME "C:\Python27"
setx PYTHONPATH "C:\Python27\Lib"
setx PATH "%PYTHONHOME%;%PATH%"

Impact of Xcode build options "Enable bitcode" Yes/No

From the docs

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Bitcode will allow apple to optimise the app without you having to submit another build. But, you can only enable this feature if all frameworks and apps in the app bundle have this feature enabled. Having it helps, but not having it should not have any negative impact.

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required.

  • Are there any performance impacts if I enable / disable it?

The App Store and operating system optimize the installation of iOS and watchOS apps by tailoring app delivery to the capabilities of the user’s particular device, with minimal footprint. This optimization, called app thinning, lets you create apps that use the most device features, occupy minimum disk space, and accommodate future updates that can be applied by Apple. Faster downloads and more space for other apps and content provides a better user experience.

There should not be any performance impacts.

How to change root logging level programmatically for logback

Try this:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);

Note that you can also tell logback to periodically scan your config file like this:

<configuration scan="true" scanPeriod="30 seconds" > 
  ...
</configuration> 

How do I protect javascript files?

Good question with a simple answer: you can't!

Javascript is a client-side programming language, therefore it works on the client's machine, so you can't actually hide anything from the client.
Obfuscating your code is a good solution, but it's not enough, because, although it is hard, someone could decipher your code and "steal" your script.
There are a few ways of making your code hard to be stolen, but as i said nothing is bullet-proof.

Off the top of my head, one idea is to restrict access to your external js files from outside the page you embed your code in. In that case, if you have

<script type="text/javascript" src="myJs.js"></script>

and someone tries to access the myJs.js file in browser, he shouldn't be granted any access to the script source.
For example, if your page is written in php, you can include the script via the include function and let the script decide if it's safe" to return it's source.
In this example, you'll need the external "js" (written in php) file myJs.php :

<?php
    $URL = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    if ($URL != "my-domain.com/my-page.php")
    die("/\*sry, no acces rights\*/");
?>
// your obfuscated script goes here

that would be included in your main page my-page.php :

<script type="text/javascript">
    <?php include "myJs.php"; ?>;
</script> 

This way, only the browser could see the js file contents.

Another interesting idea is that at the end of your script, you delete the contents of your dom script element, so that after the browser evaluates your code, the code disappears :

<script id="erasable" type="text/javascript">
    //your code goes here
    document.getElementById('erasable').innerHTML = "";
</script>

These are all just simple hacks that cannot, and I can't stress this enough : cannot, fully protect your js code, but they can sure piss off someone who is trying to "steal" your code.

Update:

I recently came across a very interesting article written by Patrick Weid on how to hide your js code, and he reveals a different approach: you can encode your source code into an image! Sure, that's not bullet proof either, but it's another fence that you could build around your code.
The idea behind this approach is that most browsers can use the canvas element to do pixel manipulation on images. And since the canvas pixel is represented by 4 values (rgba), each pixel can have a value in the range of 0-255. That means that you can store a character (actual it's ascii code) in every pixel. The rest of the encoding/decoding is trivial.
Thanks, Patrick!

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

Optional args in MATLAB functions

There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

% Function that takes two arguments, X & Y, followed by a variable 
% number of additional arguments
function varlist(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})
   end

A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

If you are already extending from ActionBarActivity and you are trying to get the action bar from a fragment:

ActionBar mActionBar = (ActionBarActivity)getActivity()).getSupportActionBar();

Java equivalent to C# extension methods

It looks like there is some small chance that Defender Methods (i.e. default methods) might make it into Java 8. However, as far as I understand them, they only allow the author of an interface to retroactively extend it, not arbitrary users.

Defender Methods + Interface Injection would then be able to fully implement C#-style extension methods, but AFAICS, Interface Injection isn't even on the Java 8 road-map yet.

How to keep the local file or the remote file during merge using Git and the command line?

git checkout {branch-name} -- {file-name}

This will use the file from the branch of choice.

I like this because posh-git autocomplete works great with this. It also removes any ambiguity as to which branch is remote and which is local. And --theirs didn't work for me anyways.

SQLAlchemy default DateTime

DateTime doesn't have a default key as an input. The default key should be an input to the Column function. Try this:

import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Test(Base):
    __tablename__ = 'test'

    id = Column(Integer, primary_key=True)
    created_date = Column(DateTime, default=datetime.datetime.utcnow)

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Free easy way to draw graphs and charts in C++?

Honestly, I was in the same boat as you. I've got a C++ Library that I wanted to connect to a graphing utility. I ended up using Boost Python and matplotlib. It was the best one that I could find.

As a side note: I was also wary of licensing. matplotlib and the boost libraries can be integrated into proprietary applications.

Here's an example of the code that I used:

#include <boost/python.hpp>
#include <pygtk/pygtk.h>
#include <gtkmm.h>

using namespace boost::python;
using namespace std;

// This is called in the idle loop.
bool update(object *axes, object *canvas) {
    static object random_integers = object(handle<>(PyImport_ImportModule("numpy.random"))).attr("random_integers");
    axes->attr("scatter")(random_integers(0,1000,1000), random_integers(0,1000,1000));
    axes->attr("set_xlim")(0,1000);
    axes->attr("set_ylim")(0,1000);
    canvas->attr("draw")();
    return true;
}

int main() {
    try {
        // Python startup code
        Py_Initialize();
        PyRun_SimpleString("import signal");
        PyRun_SimpleString("signal.signal(signal.SIGINT, signal.SIG_DFL)");

        // Normal Gtk startup code
        Gtk::Main kit(0,0);

        // Get the python Figure and FigureCanvas types.
        object Figure = object(handle<>(PyImport_ImportModule("matplotlib.figure"))).attr("Figure");
        object FigureCanvas = object(handle<>(PyImport_ImportModule("matplotlib.backends.backend_gtkagg"))).attr("FigureCanvasGTKAgg");

        // Instantiate a canvas
        object figure = Figure();
        object canvas = FigureCanvas(figure);
        object axes = figure.attr("add_subplot")(111);
        axes.attr("hold")(false);

        // Create our window.
        Gtk::Window window;
        window.set_title("Engineering Sample");
        window.set_default_size(1000, 600);

        // Grab the Gtk::DrawingArea from the canvas.
        Gtk::DrawingArea *plot = Glib::wrap(GTK_DRAWING_AREA(pygobject_get(canvas.ptr())));

        // Add the plot to the window.
        window.add(*plot);
        window.show_all();

        // On the idle loop, we'll call update(axes, canvas).
        Glib::signal_idle().connect(sigc::bind(&update, &axes, &canvas));

        // And start the Gtk event loop.
        Gtk::Main::run(window);

    } catch( error_already_set ) {
        PyErr_Print();
    }
}

How to copy files from host to Docker container?

There are good answers, but too specific. I find out docker ps is good way to get container id you're interested in. Then do

mount | grep <id>

to see where the volume is mounted. That's

/var/lib/docker/devicemapper/mnt/<id>/rootfs/

for me, but it might be a different path depending on the OS and configuration. Now simply copy files to that path.

Using -v is not always practical.

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

How to format a phone number with jQuery

Don't forget to ensure you are working with purely integers.

var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
    DATA
        .replace( /[^\d]/g, '' )
        .replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
    return DATA;
});

Declare variable MySQL trigger

All DECLAREs need to be at the top. ie.

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    DECLARE m_projects_id integer;
    DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;

    SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");

    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO m_projects_id;
            IF done THEN
                LEAVE ins_loop;
            END IF;
            INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
            VALUES (NEW.id, m_projects_id, now(), now(), 20);
        END LOOP;
    CLOSE cur;
END//

How do you access a website running on localhost from iPhone browser

Accessing localhost from the iPhone will simply do a loopback / try to connect to itself (If it supports that?).

What you need to do is find the IP of your desktop machine (e.g. If Windows, go to the Command Prompt and type ipconfig or go to Network and Sharing Centre and look up connection status.

Once you have your ip, simply visit that from your browser e.g. http://192.168.0.102.

You may need to open up port 80 (or whatever port your website is running on) in the inbound security of your firewall if you are running one.

Note: don't forget the app's port if what you want is to debug the app in your iPhone's browser like: http://192.168.0.102:3000. In this example 3000 is the default port used by ReactJS.

Join a list of items with different types as string in Python

How come no-one seems to like repr?
python 3.7.2:

>>> int_list = [1, 2, 3, 4, 5]
>>> print(repr(int_list))
[1, 2, 3, 4, 5]
>>> 

Take care though, it's an explicit representation. An example shows:

#Print repr(object) backwards
>>> print(repr(int_list)[::-1])
]5 ,4 ,3 ,2 ,1[
>>> 

more info at pydocs-repr

How can I initialize an ArrayList with all zeroes in Java?

The 60 you're passing is just the initial capacity for internal storage. It's a hint on how big you think it might be, yet of course it's not limited by that. If you need to preset values you'll have to set them yourself, e.g.:

for (int i = 0; i < 60; i++) {
    list.add(0);
}

How to output only captured groups with sed?

you can use grep

grep -Eow "[0-9]+" file

Getting a list of values from a list of dicts

Get key values from list of dictionaries in python?

  1. Get key values from list of dictionaries in python?

Ex:

data = 
[{'obj1':[{'cpu_percentage':'15%','ram':3,'memory_percentage':'66%'}]},
{'obj2': [{'cpu_percentage':'0','ram':4,'memory_percentage':'35%'}]}]

for d in data:

  for key,value in d.items(): 

      z ={key: {'cpu_percentage': d['cpu_percentage'],'memory_percentage': d['memory_percentage']} for d in value} 
      print(z)

Output:

{'obj1': {'cpu_percentage': '15%', 'memory_percentage': '66%'}}
{'obj2': {'cpu_percentage': '0', 'memory_percentage': '35%'}}

How to append in a json file in Python?

Assuming you have a test.json file with the following content:

{"67790": {"1": {"kwh": 319.4}}}

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

import json

a_dict = {'new_key': 'new_value'}

with open('test.json') as f:
    data = json.load(f)

data.update(a_dict)

with open('test.json', 'w') as f:
    json.dump(data, f)

Then, in test.json, you'll have:

{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}

Hope this is what you wanted.

Checking if an object is a given type in Swift

Why not to use something like this

fileprivate enum types {
    case typeString
    case typeInt
    case typeDouble
    case typeUnknown
}

fileprivate func typeOfAny(variable: Any) -> types {
    if variable is String {return types.typeString}
    if variable is Int {return types.typeInt}
    if variable is Double {return types.typeDouble}
    return types.typeUnknown
}

in Swift 3.

How to query a CLOB column in Oracle

When getting the substring of a CLOB column and using a query tool that has size/buffer restrictions sometimes you would need to set the BUFFER to a larger size. For example while using SQL Plus use the SET BUFFER 10000 to set it to 10000 as the default is 4000.

Running the DBMS_LOB.substr command you can also specify the amount of characters you want to return and the offset from which. So using DBMS_LOB.substr(column, 3000) might restrict it to a small enough amount for the buffer.

See oracle documentation for more info on the substr command


    DBMS_LOB.SUBSTR (
       lob_loc     IN    CLOB   CHARACTER SET ANY_CS,
       amount      IN    INTEGER := 32767,
       offset      IN    INTEGER := 1)
      RETURN VARCHAR2 CHARACTER SET lob_loc%CHARSET;

Add one day to date in javascript

Note that Date.getDate only returns the day of the month. You can add a day by calling Date.setDate and appending 1.

// Create new Date instance
var date = new Date()

// Add a day
date.setDate(date.getDate() + 1)

JavaScript will automatically update the month and year for you.

EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.

Foreach loop, determine which is the last iteration of the loop

We can check last item in loop.

foreach (Item result in Model.Results)
{
    if (result==Model.Results.Last())
    {
        // do something different with the last item
    }
}

Creating a simple XML file using python

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

How do you round a number to two decimal places in C#?

Here's some examples:

decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00

You might also want to look at bankers rounding / round-to-even with the following overload:

Math.Round(a, 2, MidpointRounding.ToEven);

There's more information on it here.

Firebase FCM force onTokenRefresh() to be called

The onTokenRefresh() method is going to be called whenever a new token is generated. Upon app install, it will be generated immediately (as you have found to be the case). It will also be called when the token has changed.

According to the FirebaseCloudMessaging guide:

You can target notifications to a single, specific device. On initial startup of your app, the FCM SDK generates a registration token for the client app instance.

Screenshot

Source Link: https://firebase.google.com/docs/notifications/android/console-device#access_the_registration_token

This means that the token registration is per app. It sounds like you would like to utilize the token after a user is logged in. What I would suggest is that you save the token in the onTokenRefresh() method to internal storage or shared preferences. Then, retrieve the token from storage after a user logs in and register the token with your server as needed.

If you would like to manually force the onTokenRefresh(), you can create an IntentService and delete the token instance. Then, when you call getToken, the onTokenRefresh() method will be called again.

Example Code:

public class DeleteTokenService extends IntentService
{
    public static final String TAG = DeleteTokenService.class.getSimpleName();

    public DeleteTokenService()
    {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        try
        {
            // Check for current token
            String originalToken = getTokenFromPrefs();
            Log.d(TAG, "Token before deletion: " + originalToken);

            // Resets Instance ID and revokes all tokens.
            FirebaseInstanceId.getInstance().deleteInstanceId();

            // Clear current saved token
            saveTokenToPrefs("");

            // Check for success of empty token
            String tokenCheck = getTokenFromPrefs();
            Log.d(TAG, "Token deleted. Proof: " + tokenCheck);

            // Now manually call onTokenRefresh()
            Log.d(TAG, "Getting new token");
            FirebaseInstanceId.getInstance().getToken();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void saveTokenToPrefs(String _token)
    {
        // Access Shared Preferences
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();

        // Save to SharedPreferences
        editor.putString("registration_id", _token);
        editor.apply();
    }

    private String getTokenFromPrefs()
    {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        return preferences.getString("registration_id", null);
    }
}

EDIT

FirebaseInstanceIdService

public class FirebaseInstanceIdService extends Service

This class is deprecated. In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.

onTokenRefresh() is deprecated. Use onNewToken() in MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Log.e("NEW_TOKEN",s);
    }

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    }
} 

C++: Where to initialize variables in constructor

See Should my constructors use "initialization lists" or "assignment"?

Briefly: in your specific case, it does not change anything. But:

  • for class/struct members with constructors, it may be more efficient to use option 1.
  • only option 1 allows you to initialize reference members.
  • only option 1 allows you to initialize const members
  • only option 1 allows you to initialize base classes using their constructor
  • only option 2 allows you to initialize array or structs that do not have a constructor.

My guess for why option 2 is more common is that option 1 is not well-known, neither are its advantages. Option 2's syntax feels more natural to the new C++ programmer.

Zero-pad digits in string

First of all, your description is misleading. Double is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:

$s = sprintf('%02d', $digit);

For more information, refer to the documentation of sprintf.

What is the difference between docker-compose ports vs expose

I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:

Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.

This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.

"SyntaxError: Unexpected token < in JSON at position 0"

In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues. So, it was returning the HTML from the redirected page instead of the api JSON. I added an exclusion in a web.config file for the api path.

I was not getting this error when developing locally because the Site and API were on different ports. There is probably a better way to do this ... but it worked.

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <!-- ignore static files -->
        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>

        <!--remaining all other url's point to index.html file -->
        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>

        </rules>
        </rewrite>
    </system.webServer>
</configuration>

Git copy changes from one branch to another

This is 2 step process

  • git checkout BranchB ( destination branch is BranchB, so we need the head on this branch)
  • git merge BranchA (it will merge BranchB with BranchA. Here you have merged code in branch B)

If you want to push your branch code to remote repo then do

  • git push origin master (it will push your BranchB code to remote repo)

Access localhost from the internet

use your ip address or a service like noip.com if you need something more practical. Then eventually configure your router properly so incoming connection will be forwarded to the machine with the server running.

Viewing my IIS hosted site on other machines on my network

Very Late Answer but I will highlight some point as I had to deal with it years ago setting up my IIS site across network

  1. Both your machines should be connected to the same network (same wireless network is fine)
  2. Access your remote machine via IP 168.192.x.x or via http://his-pc-name (do not forget the http part)
  3. This will server the default IIS page on the remote machine (same that is served through localhost). If you want to server another site, [you have to make that default] first1.

Make sure your IIS is working fine on remote machine by checking localhost which should served the default site. Also make sure your firewall is configured to allow connection via port 80 or you can just disable firewall for the time being for testing purposes.

Run a command over SSH with JSch

Note that Charity Leschinski's answer may have a bit of an issue when there is some delay in the response. eg:
lparstat 1 5 returns one response line and works,
lparstat 5 1 should return 5 lines, but only returns the first

I've put the command output while inside another ... I'm sure there is a better way, I had to do this as a quick fix

        while (commandOutput.available() > 0) {
            while (readByte != 0xffffffff) {
                outputBuffer.append((char) readByte);
                readByte = commandOutput.read();
            }
            try {Thread.sleep(1000);} catch (Exception ee) {}
        }

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The only solution that worked for me and $.each was definitely causing the error. so i used for loop and it's not throwing error anymore.

Example code

     $.ajax({
            type: 'GET',
            url: 'https://example.com/api',
            data: { get_param: 'value' },
            success: function (data) {
                for (var i = 0; i < data.length; ++i) {
                    console.log(data[i].NameGerman);
                }
            }
        });

React JSX: selecting "selected" on selected <select> option

I have a simple solution is following the HTML basic.

<input
  type="select"
  defaultValue=""
  >
  <option value="" disabled className="text-hide">Please select</option>
  <option>value1</option>
  <option>value1</option>
</input>

.text-hide is a bootstrap's class, if you not using bootstrap, here you are:

.text-hide {
  font: 0/0 a;
  color: transparent;
  text-shadow: none;
  background-color: transparent;
  border: 0;
}

Git 'fatal: Unable to write new index file'

In my case, the disk ran out of space, so I had to delete files from the hard drive to make space.

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

If you are simply outputting the value of that model property, you don't need the DisplayFor html helper, just call it directly with the proper string formatting.

Audit Date: @Model.AuditDate.Value.ToString("d")

Should output

Audit Date: 1/21/2015

Lastly, your audit date could be null, so you should do the conditional check before you attempt to format a nullable value.

@if (item.AuditDate!= null) { @Model.AuditDate.Value.ToString("d")}

Googling the error that you are getting provides this answer, which shows that the error is from using the word Model in your Html helpers. For instance, using @Html.DisplayFor(Model=>Model.someProperty). Change these to use something else other than Model, for instance: @Html.DisplayFor(x=>x.someProperty) or change the capital M to a lowercase m in these helpers.

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

jQuery Event : Detect changes to the html/text of a div

Use MutationObserver as seen in this snippet provided by Mozilla, and adapted from this blog post

Alternatively, you can use the JQuery example seen in this link

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

Android Studio suddenly cannot resolve symbols

I tried cleaning the project and then invalidating the cache, neither of which worked. What worked for me was to comment out all my dependencies in build.gradle (app), then sync, then uncomment the dependencies again, then sync again. Bob's your uncle.

Angular HttpClient "Http failure during parsing"

You can specify that the data to be returned is not JSON using responseType.

In your example, you can use a responseType string value of text, like this:

return this.http.post(
    'http://10.0.1.19/login',
    {email, password},
    {responseType: 'text'})

The full list of options for responseType is:

  • json (the default)
  • text
  • arraybuffer
  • blob

See the docs for more information.

ScrollIntoView() causing the whole page to move

I had this problem too, and spent many hours trying to deal with it. I hope my resolution may still help some people.

My fix ended up being:

  • For Chrome: changing .scrollIntoView() to .scrollIntoView({block: 'nearest'}) (thanks to @jfrohn).
  • For Firefox: apply overflow: -moz-hidden-unscrollable; on the container element that shifts.
  • Not tested in other browsers.

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

You're using an array of objects. Can you use a two dimensional array instead?

http://www.datatables.net/examples/data_sources/js_array.html

See this jsfiddle: http://jsfiddle.net/QhYse/

I used an array like this and it worked fine:

var data = [
    ["UpdateBootProfile","PASS","00:00:00",[]] ,
    ["NRB Boot","PASS","00:00:50.5000000",[{"TestName":"TOTAL_TURN_ON_TIME","Result":"PASS","Value":"50.5","LowerLimit":"NaN","UpperLimit":"NaN","ComparisonType":"nctLOG","Units":"SECONDS"}]] ,
    ["NvMgrCommit","PASS","00:00:00",[]] ,
    ["SyncNvToEFS","PASS","00:00:01.2500000",[]]
];

Edit to include array of objects

There's a possible solution from this question: jQuery DataTables fnrender with objects

This jsfiddle http://jsfiddle.net/j2C7j/ uses an array of objects. To not get the error I had to pad it with 3 blank values - less than optimal, I know. You may find a better way with fnRender, please post if you do.

var data = [
   ["","","", {"Name":"UpdateBootProfile","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]} ]

];

$(function() {
        var testsTable = $('#tests').dataTable({
                bJQueryUI: true,
                aaData: data,
                aoColumns: [
                        { mData: 'Name', "fnRender": function( oObj ) { return oObj.aData[3].Name}},
                        { mData: 'Result' ,"fnRender": function( oObj ) { return oObj.aData[3].Result }},
                        { mData: 'ExecutionTime',"fnRender": function( oObj ) { return oObj.aData[3].ExecutionTime } }
                ]
        });
});

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

Add spaces between the characters of a string in Java?

Iterate over the characters of the String and while storing in a new array/string you can append one space before appending each character.

Something like this :

StringBuilder result = new StringBuilder();

for(int i = 0 ; i < str.length(); i++)
{
   result = result.append(str.charAt(i));
   if(i == str.length()-1)
      break;
   result = result.append(' ');
}

return (result.toString());

Invoking a jQuery function after .each() has completed

I found a lot of responses dealing with arrays but not with a json object. My solution was simply to iterate through the object once while incrementing a counter and then when iterating through the object to perform your code you can increment a second counter. Then you simply compare the two counters together and get your solution. I know it's a little clunky but I haven't found a more elegant solution so far. This is my example code:

var flag1 = flag2 = 0;

$.each( object, function ( i, v ) { flag1++; });

$.each( object, function ( ky, val ) {

     /*
        Your code here
     */
     flag2++;
});

if(flag1 === flag2) {
   your function to call at the end of the iteration
}

Like I said, it's not the most elegant, but it works and it works well and I haven't found a better solution just yet.

Cheers, JP

Using app.config in .Net Core

I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.

Breaking this down to a simple answer for .Net core 3.1:

  • add/ensure nuget package: System.Configuration.ConfigurationManager to project
  • add your app.config(xml) to project.

If it is a MSTest project:

  • rename file in project to testhost.dll.config

    OR

  • Use post-build command provided by DeepSpace101

How to Generate a random number of fixed length using JavaScript?

parseInt(Math.random().toString().slice(2,Math.min(length+2, 18)), 10); // 18 -> due to max digits in Math.random

Update: This method has few flaws: - Sometimes the number of digits might be lesser if its left padded with zeroes.

How to get second-highest salary employees in a table

select 
    max(salary) 
from 
    emp_demo_table 
where 
    salary < (select max(salary) from emp_demo_table)

Hope this solves the query in simplest of terms.

Thanks

Adding 'serial' to existing column in Postgres

Look at the following commands (especially the commented block).

DROP TABLE foo;
DROP TABLE bar;

CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);

INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;

-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a;    -- 8.2 or later

SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5);  -- replace 5 by SELECT MAX result

INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');

SELECT * FROM foo;
SELECT * FROM bar;

Efficiently getting all divisors of a given number

//DIVISORS IN TIME COMPLEXITY sqrt(n)

#include<bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
    ll int n;
    cin >> n;

    for(ll i = 2;  i <= sqrt(n); i++)
    {
        if (n%i==0)
        {
            if (n/i!=i)
                cout << i << endl << n/i<< endl;
            else
                cout << i << endl;
        }
    }
}

PHP fwrite new line

Use PHP_EOL which produces \r\n or \n

$data = 'my data' . PHP_EOL . 'my data';
$fp = fopen('my_file', 'a');
fwrite($fp, $data);
fclose($fp);

// File output

my data
my data

error TS2339: Property 'x' does not exist on type 'Y'

I'm no expert in Typescript, but I think the main problem is the way of accessing data. Seeing how you described your Images interface, you can define any key as a String.

When accessing a property, the "dot" syntax (images.main) supposes, I think, that it already exists. I had such problems without Typescript, in "vanilla" Javascript, where I tried to access data as:

return json.property[0].index

where index was a variable. But it interpreted index, resulting in a:

cannot find property "index" of json.property[0]

And I had to find a workaround using your syntax:

return json.property[0][index]

It may be your only option there. But, once again, I'm no Typescript expert, if anyone knows a better solution / explaination about what happens, feel free to correct me.

How to get a view table query (code) in SQL Server 2008 Management Studio

Use sp_helptext before the view_name. Example:

sp_helptext Example_1

Hence you will get the query:

CREATE VIEW dbo.Example_1
AS
SELECT       a, b, c
FROM         dbo.table_name JOIN blah blah blah
WHERE        blah blah blah

sp_helptext will give stored procedures.

Want to upgrade project from Angular v5 to Angular v6

Upgrade from Angular v6 to Angular v7

Version 7 of Angular has been released Official Angular blog link. Visit official angular update guide https://update.angular.io for detailed information. These steps will work for basic angular 6 apps using Angular Material.

ng update @angular/cli 
ng update @angular/core
ng update @angular/material

Upgrade from Angular v5 to Angular v6

Version 6 of Angular has been released Official Angular blog link. I have mentioned general upgrade steps below, but before and after the update you need to make changes in your code to make it workable in v6, for that detailed information visit official website https://update.angular.io .

Upgrade Steps (largely taken from the official Angular Update Guide for a basic Angular app using Angular Material):

  1. Make sure NodeJS version is 8.9+ if not update it.

  2. Update Angular cli globally and locally, and migrate the old configuration .angular-cli.json to the new angular.json format by running the following:

    npm install -g @angular/cli  
    npm install @angular/cli  
    ng update @angular/cli
    
  3. Update all of your Angular framework packages to v6,and the correct version of RxJS and TypeScript by running the following:

    ng update @angular/core
    
  4. Update Angular Material to the latest version by running the following:

    ng update @angular/material
    
  5. RxJS v6 has major changes from v5, v6 brings backwards compatibility package rxjs-compat that will keep your applications working, but you should refactor TypeScript code so that it doesn't depend on rxjs-compat. To refactor TypeScript code run following:

    npm install -g rxjs-tslint   
    rxjs-5-to-6-migrate -p src/tsconfig.app.json
    

    Note: Once all of your dependencies have updated to RxJS 6, remove rxjs- compat as it increases bundle size. please see this RxJS Upgrade Guide for more info.

    npm uninstall rxjs-compat
    
  6. Done run ng serve to check it.
    If you get errors in build refer https://update.angular.io for detailed info.

Upgrade from Angular v5 to Angular 6.0.0-rc.5

  1. Upgrade rxjs to 6.0.0-beta.0, please see this RxJS Upgrade Guide for more info. RxJS v6 has breaking change hence first make your code compatible to latest RxJS version.

  2. Update NodeJS version to 8.9+ (this is required by angular cli 6 version)

  3. Update Angular cli global package to next version.

    npm uninstall -g @angular/cli
    npm cache verify
    

    if npm version is < 5 then use npm cache clean

    npm install -g @angular/cli@next
    
  4. Change angular packages versions in package.json file to ^6.0.0-rc.5

    "dependencies": {
      "@angular/animations": "^6.0.0-rc.5",
      "@angular/cdk": "^6.0.0-rc.12",
      "@angular/common": "^6.0.0-rc.5",
      "@angular/compiler": "^6.0.0-rc.5",
      "@angular/core": "^6.0.0-rc.5",
      "@angular/forms": "^6.0.0-rc.5",
      "@angular/http": "^6.0.0-rc.5",
      "@angular/material": "^6.0.0-rc.12",
      "@angular/platform-browser": "^6.0.0-rc.5",
      "@angular/platform-browser-dynamic": "^6.0.0-rc.5",
      "@angular/router": "^6.0.0-rc.5",
      "core-js": "^2.5.5",
      "karma-jasmine": "^1.1.1",
      "rxjs": "^6.0.0-uncanny-rc.7",
      "rxjs-compat": "^6.0.0-uncanny-rc.7",
      "zone.js": "^0.8.26"
    },
    "devDependencies": {
      "@angular-devkit/build-angular": "~0.5.0",
      "@angular/cli": "^6.0.0-rc.5",
      "@angular/compiler-cli": "^6.0.0-rc.5",
      "@types/jasmine": "2.5.38",
      "@types/node": "~8.9.4",
      "codelyzer": "~4.1.0",
      "jasmine-core": "~2.5.2",
      "jasmine-spec-reporter": "~3.2.0",
      "karma": "~1.4.1",
      "karma-chrome-launcher": "~2.0.0",
      "karma-cli": "~1.0.1",
      "karma-coverage-istanbul-reporter": "^0.2.0",
      "karma-jasmine": "~1.1.0",
      "karma-jasmine-html-reporter": "^0.2.2",
      "postcss-loader": "^2.1.4",
      "protractor": "~5.1.0",
      "ts-node": "~5.0.0",
      "tslint": "~5.9.1",
      "typescript": "^2.7.2"
    }
    
  5. Next update Angular cli local package to next version and install above mentioned packages.

    rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows 
    Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
    npm install --save-dev @angular/cli@next
    npm install 
    
  6. The Angular CLI configuration format has been changed from angular cli 6.0.0-rc.2 version, and your existing configuration can be updated automatically by running the following command. It will remove old config file .angular-cli.json and will write new angular.json file.

    ng update @angular/cli --migrate-only --from=1.7.4

Note :- If you get following error "The Angular Compiler requires TypeScript >=2.7.2 and <2.8.0 but 2.8.3 was found instead". run following command :

npm install [email protected]

How can I get query string values in JavaScript?

function getUrlVar(key){
    var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); 
    return result && unescape(result[1]) || ""; 
}

https://gist.github.com/1771618

Why use argparse rather than optparse?

At first I was as reluctant as @fmark to switch from optparse to argparse, because:

  1. I thought the difference was not that huge.
  2. Quite some VPS still provides Python 2.6 by default.

Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)

Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.

Which Ruby version am I really running?

The ruby version 1.8.7 seems to be your system ruby.

Normally you can choose the ruby version you'd like, if you are using rvm with following. Simple change into your directory in a new terminal and type in:

rvm use 2.0.0

You can find more details about rvm here: http://rvm.io Open the website and scroll down, you will see a few helpful links. "Setting up default rubies" for example could help you.

Update: To set the ruby as default:

rvm use 2.0.0 --default

Can I have multiple Xcode versions installed?

Install Multiple Versions Of Xcode using the Xcode-Install Ruby Gem

You can do this whole process a lot easier if you use the xcode-install RubyGem.

If you already have a working installation of the Xcode CommandLineTools and Ruby (I'd suggest using Homebrew for installing Ruby) but I think it works with the Ruby supplied by macOS as well if you install the Gem either using sudo or as a user install. (Details on the GitHub page) Basically:

    $ gem install xcode-install
    $ xcversion list
    6.0.1
    6.1
    6.1.1
    6.2 (installed)
    6.3
    $ xcversion install 8
    ######################################################################## 100.0%
    Please authenticate for Xcode installation...

    Xcode 8
    Build version 6D570

To select a version as active, you'll run:
$ xcversion select 8

To select a version as active and change the symlink at /Applications/Xcode, you'll run:
$ xcversion select 8 --symlink

xcode-install can also manage your local simulators using the simulators command.

Read the instructions on the GitHub Project page for more info.

Changing the color of a clicked table row using jQuery

I'm not an expert in JQuery but I have the same scenario and I able to accomplis like this:

$("#data tr").click(function(){
   $(this).addClass("selected").siblings().removeClass("selected"); 
});

Style:

<style type="text/css">

.selected {
    background: red;
}

</style> 

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

How to initialize all members of an array to the same value?

#include<stdio.h>
int main(){
int i,a[50];
for (i=0;i<50;i++){
    a[i]=5;// set value 5 to all the array index
}
for (i=0;i<50;i++)
printf("%d\n",a[i]);
   return 0;
}

It will give the o/p 5 5 5 5 5 5 ...... till the size of whole array

Best way to find os name and version in Unix/Linux platform

I prepared following commands to find concise information about a Linux system:

clear
echo "\n----------OS Information------------"
hostnamectl | grep "Static hostname:"
hostnamectl | tail -n 3
echo "\n----------Memory Information------------"
cat /proc/meminfo | grep MemTotal
echo "\n----------CPU Information------------"
echo -n "Number of core(s): "
cat /proc/cpuinfo | grep "processor" | wc -l
cat /proc/cpuinfo | grep "model name" | head -n 1
echo "\n----------Disk Information------------"
echo -n "Total Size: "
df -h --total | tail -n 1| awk '{print $2}'
echo -n "Used: "
df -h --total | tail -n 1| awk '{print $3}'
echo -n "Available: "
df -h --total | tail -n 1| awk '{print $4}'
echo "\n-------------------------------------\n"

Copy and paste in an sh file like info.sh and then run it using command sh info.sh

How do I programmatically set device orientation in iOS 7?

For iOS 7 & 8:

Objective-C:

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

Swift 3+:

let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")

I call it in - viewDidAppear:.

Location of the mongodb database on mac

Thanks @Mark, I keep forgetting this again and again. After installing MongoDB with Homebrew:

  • The databases are stored in the /usr/local/var/mongodb/ directory
  • The mongod.conf file is here: /usr/local/etc/mongod.conf
  • The mongo logs can be found at /usr/local/var/log/mongodb/
  • The mongo binaries are here: /usr/local/Cellar/mongodb/[version]/bin

Automatically deleting related rows in Laravel (Eloquent ORM)

I would iterate through the collection detaching everything before deleting the object itself.

here's an example:

try {
        $user = User::findOrFail($id);
        if ($user->has('photos')) {
            foreach ($user->photos as $photo) {

                $user->photos()->detach($photo);
            }
        }
        $user->delete();
        return 'User deleted';
    } catch (Exception $e) {
        dd($e);
    }

I know it is not automatic but it is very simple.

Another simple approach would be to provide the model with a method. Like this:

public function detach(){
       try {
            
            if ($this->has('photos')) {
                foreach ($this->photos as $photo) {
    
                    $this->photos()->detach($photo);
                }
            }
           
        } catch (Exception $e) {
            dd($e);
        }
}

Then you can simply call this where you need:

$user->detach();
$user->delete();

Image resizing in React Native

This worked for me,

image: {
    width: 200,
    height:220,
    resizeMode: 'cover'
}

You can also set your resizeMode: 'contain'. I defined the style for my network images as:

<Image 
   source={{uri:rowData.banner_path}}
   style={{
     width: 80,
     height: 80,
     marginRight: 10,
     marginBottom: 12,
     marginTop: 12}}
/>

If you are using flex, use it in all the components of parent View, else it is redundant with height: 200, width: 220.

regular expression to validate datetime format (MM/DD/YYYY)

It's long, but great:

new RegExp(/(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/);

for each inside a for each - Java

So you really want:

for each tweet
    unless tweet is in db
        insert tweet

If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.

What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.

Bootstrap modal z-index

ok, so if you are using bootstrap-rtl.css, what you can do is go to the following class .modal-backdrop and remove the z-index attribute. after that all should be fine

How to install libusb in Ubuntu

First,

sudo apt-get install libusb-1.0-0-dev

updatedb && locate libusb.h.

Second, replace <libusb.h> with <libusb-1.0/libusb.h>.

update:

don't need to change any file.just add this to your Makefile.

`pkg-config libusb-1.0 --libs --cflags`

its result is that -I/usr/include/libusb-1.0 -lusb-1.0

check / uncheck checkbox using jquery?

For jQuery 1.6+ :

.attr() is deprecated for properties; use the new .prop() function instead as:

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it

For jQuery < 1.6:

To check/uncheck a checkbox, use the attribute checked and alter that. With jQuery you can do:

$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it

Cause you know, in HTML, it would look something like:

<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->

However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.

#1292 - Incorrect date value: '0000-00-00'

After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.

It's incorrect to use zeros in date or in datetime, just put null instead of zeros.

Compiling php with curl, where is curl installed?

php curl lib is just a wrapper of cUrl, so, first of all, you should install cUrl. Download the cUrl source to your linux server. Then, use the follow commands to install:

tar zxvf cUrl_src_taz
cd cUrl_src_taz
./configure --prefix=/curl/install/home
make
make test    (optional)
make install
ln -s  /curl/install/home/bin/curl-config /usr/bin/curl-config

Then, copy the head files in the "/curl/install/home/include/" to "/usr/local/include". After all above steps done, the php curl extension configuration could find the original curl, and you can use the standard php extension method to install php curl.
Hope it helps you, :)

How to combine two byte arrays

The simplest method (inline, assuming a and b are two given arrays):

byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);

This, of course, works with more than two summands and uses a concatenation charset, defined somewhere in your code:

static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;

Or, in more simple form, without this charset:

byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");

But you need to suppress UnsupportedEncodingException which is unlikely to be thrown.


The fastest method:

public static byte[] concat(byte[] a, byte[] b) {
    int lenA = a.length;
    int lenB = b.length;
    byte[] c = Arrays.copyOf(a, lenA + lenB);
    System.arraycopy(b, 0, c, lenA, lenB);
    return c;
}

Not able to pip install pickle in python 3.6

import pickle

intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()

Test your pickle quickly. pickle is a part of standard python library and available by default.

How does JavaScript .prototype work?

what is the exact purpose of this ".prototype" property?

The interface to standard classes become extensible. For example, you are using the Array class and you also need to add a custom serializer for all your array objects. Would you spend time coding up a subclass, or use composition or ... The prototype property solves this by letting the users control the exact set of members/methods available to a class.

Think of prototypes as an extra vtable-pointer. When some members are missing from the original class, the prototype is looked up at runtime.

How to make a owl carousel with arrows instead of next previous

If you're using Owl Carousel 2, then you should use the following:

$(".category-wrapper").owlCarousel({
     items : 4,
     loop  : true,
     margin : 30,
     nav    : true,
     smartSpeed :900,
     navText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"]
   });

JavaScript equivalent of PHP’s die

You can use return false; This will terminate your script.

Get table column names in MySQL?

The MySQL function describe table should get you where you want to go (put your table name in for "table"). You'll have to parse the output some, but it's pretty easy. As I recall, if you execute that query, the PHP query result accessing functions that would normally give you a key-value pair will have the column names as the keys. But it's been a while since I used PHP so don't hold me to that. :)

Apply CSS rules to a nested class inside a div

You use

#main_text .title {
  /* Properties */
}

If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, and not children of children, e.g.:

#main_text > .title {
  /* Properties */
}

Either will work in this case, but the first is more typically used.

how to calculate percentage in python

This is because (100/500) is an integer expression yielding 0.

Try

per = 100.0 * tota / 500

there's no need for the float() call, since using a floating-point literal (100.0) will make the entire expression floating-point anyway.

How can I make an image transparent on Android?

For 20% transparency, this worked for me:

Button bu = (Button)findViewById(R.id.button1);
bu.getBackground().setAlpha(204);

In oracle, how do I change my session to display UTF8?

Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:

NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.

Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:

export NLS_LANG=AMERICAN_AMERICA.UTF8

Oracle gets a big fat F for usability.

Is there a combination of "LIKE" and "IN" in SQL?

I know this is very late, but I had a similar situation. I needed a "Like In" operator for a set of stored procedures I have, which accept many parameters and then uses those parameters to aggregate data from multiple RDBMS systems, thus no RDBMS-specific tricks would work, however the stored procedure and any functions will run on MS SQL Server, so we can use T-SQL for the functionality of generating the full SQL statements for each RDBMS, but the output needs to be fairly RDBMS-independent.

This is what I've come up with for the moment to turn a delimited string (such as a parameter coming into a stored procedure) into a block of SQL. I call it "Lichen" for "LIKE IN". Get it?

Lichen.sql

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =======================================================================
-- Lichen - Scalar Valued Function
-- Returns nvarchar(512) of "LIKE IN" results.  See further documentation.
-- CREATOR: Norman David Cooke
-- CREATED: 2020-02-05
-- UPDATED:
-- =======================================================================
CREATE OR ALTER FUNCTION Lichen 
(
    -- Add the parameters for the function here
    @leadingAnd bit = 1,
    @delimiter nchar(1) = ';',
    @colIdentifier nvarchar(64),
    @argString nvarchar(256)
)
RETURNS nvarchar(512)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @result nvarchar(512)

    -- set delimiter to detect (add more here to detect a delimiter if one isn't provided)
    DECLARE @delimit nchar(1) = ';'
    IF NOT @delimiter = @delimit 
        SET @delimit = @delimiter


    -- check to see if we have any delimiters in the input pattern
    IF CHARINDEX(@delimit, @argString) > 1  -- check for the like in delimiter
    BEGIN  -- begin 'like in' branch having found a delimiter
        -- set up a table variable and string_split the provided pattern into it.
        DECLARE @lichenTable TABLE ([id] [int] IDENTITY(1,1) NOT NULL, line NVARCHAR(32))
        INSERT INTO @lichenTable SELECT * FROM STRING_SPLIT(@argString, ';')

        -- setup loop iterators and determine how many rows were inserted into lichen table
        DECLARE @loopCount int = 1
        DECLARE @lineCount int 
        SELECT @lineCount = COUNT(*) from @lichenTable

        -- select the temp table (to see whats inside for debug)
        --select * from @lichenTable

        -- BEGIN AND wrapper block for 'LIKE IN' if bit is set
        IF @leadingAnd = 1
            SET @result = ' AND ('
        ELSE
            SET @result = ' ('

        -- loop through temp table to build multiple "LIKE 'x' OR" blocks inside the outer AND wrapper block
        WHILE ((@loopCount IS NOT NULL) AND (@loopCount <= @lineCount))
        BEGIN -- begin loop through @lichenTable
            IF (@loopcount = 1) -- the first loop does not get the OR in front
                SELECT @result = CONCAT(@result, ' ', @colIdentifier, ' LIKE ''', line, '''') FROM @lichenTable WHERE id = @loopCount
            ELSE  -- but all subsequent loops do
                SELECT @result = CONCAT(@result, ' OR ', @colIdentifier, ' LIKE ''', line, '''') FROM @lichenTable WHERE id = @loopCount
            SET @loopcount = @loopCount + 1     -- increment loop
        END -- end loop through @lichenTable

        -- set final parens after lichenTable loop
        SET @result = CONCAT(@result, ' )')
    END  -- end 'like in' branch having found a delimiter
    ELSE -- no delimiter was provided
    BEGIN   -- begin "no delimiter found" branch
        IF @leadingAnd = 1 
            SET @result = CONCAT(' AND ', @colIdentifier, ' LIKE ''' + @argString + '''')
        ELSE
            SET @result = CONCAT(' ', @colIdentifier, ' LIKE ''' + @argString + '''')
    END     -- end "no delimiter found" branch

    -- Return the result of the function
    RETURN @result
END  -- end lichen function

GO

The delimiter detection is possibly planned, but for now it defaults to a semicolon so you can just put default in there. There are probably bugs in this. The @leadingAnd parameter is just a bit value to determine if you want a leading "AND" put in front of the block so it fits in nicely with other WHERE clause additions.

Example Usage (with delimiter in argString)

SELECT [dbo].[Lichen] (
   default        -- @leadingAND, bit, default: 1
  ,default        -- @delimiter, nchar(1), default: ';'
  ,'foo.bar'      -- @colIdentifier, nvarchar(64), this is the column identifier
  ,'01%;02%;%03%' -- @argString, nvarchar(256), this is the input string to parse "LIKE IN" from
)
GO

Will return a nvarchar(512) containing:

 AND ( foo.bar LIKE '01%' OR foo.bar LIKE '02%' OR foo.bar LIKE '%03%' ) 

It will also skip the block if the input does not contain a delimiter:

Example Usage (without delimiter in argString)

SELECT [dbo].[Lichen] (
   default        -- @leadingAND, bit, default: 1
  ,default        -- @delimiter, nchar(1), default: ';'
  ,'foo.bar'      -- @colIdentifier, nvarchar(64), this is the column identifier
  ,'01%'          -- @argString, nvarchar(256), this is the input string to parse "LIKE IN" from
)
GO

Will return a nvarchar(512) containing:

 AND foo.bar LIKE '01%'

I'm going to continue work on this, so if I've overlooked something (glaringly obvious or otherwise) please feel free to comment or reach out.

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

OK, just change your code to something like this:

<script>
function submit() {
   return confirm('Do you really want to submit the form?');
}
</script>

<form onsubmit="return submit(this);">
   <input type="image" src="xxx" border="0" name="submit" onclick="show_alert();"
      alt="PayPal - The safer, easier way to pay online!" value="Submit">
</form>

Also this is the code in run, just I make it easier to see how it works, just run the code below to see the result:

_x000D_
_x000D_
function submitForm() {_x000D_
  return confirm('Do you really want to submit the form?');_x000D_
}
_x000D_
<form onsubmit="return submitForm(this);">_x000D_
  <input type="text" border="0" name="submit" />_x000D_
  <button value="submit">submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to convert an Array to a Set in Java

In Java 10:

String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));

Set.copyOf returns an unmodifiable Set containing the elements of the given Collection.

 The given Collection must not be null, and it must not contain any null elements.

How to use an image for the background in tkinter?

A simple tkinter code for Python 3 for setting background image .

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop

How to highlight a current menu item?

My solution to this problem, use route.current in the angular template.

As you have the /tasks route to highlight in your menu, you can add your own property menuItem to the routes declared by your module:

$routeProvider.
  when('/tasks', {
    menuItem: 'TASKS',
    templateUrl: 'my-templates/tasks.html',
    controller: 'TasksController'
  );

Then in your template tasks.htmlyou can use following ng-class directive:

<a href="app.html#/tasks" 
    ng-class="{active : route.current.menuItem === 'TASKS'}">Tasks</a>

In my opinion, this is much cleaner than all proposed solutions.

Add string in a certain position in Python

This seems very easy:

>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6

However if you like something like a function do as this:

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

How to loop over grouped Pandas dataframe?

Here is an example of iterating over a pd.DataFrame grouped by the column atable. For this sample, "create" statements for an SQL database are generated within the for loop:

import pandas as pd

df1 = pd.DataFrame({
    'atable':     ['Users', 'Users', 'Domains', 'Domains', 'Locks'],
    'column':     ['col_1', 'col_2', 'col_a', 'col_b', 'col'],
    'column_type':['varchar', 'varchar', 'int', 'varchar', 'varchar'],
    'is_null':    ['No', 'No', 'Yes', 'No', 'Yes'],
})

df1_grouped = df1.groupby('atable')

# iterate over each group
for group_name, df_group in df1_grouped:
    print('\nCREATE TABLE {}('.format(group_name))

    for row_index, row in df_group.iterrows():
        col = row['column']
        column_type = row['column_type']
        is_null = 'NOT NULL' if row['is_null'] == 'NO' else ''
        print('\t{} {} {},'.format(col, column_type, is_null))

    print(");")

get specific row from spark dataframe

The getrows() function below should get the specific rows you want.

For completeness, I have written down the full code in order to reproduce the output.

# Create SparkSession
from pyspark.sql import SparkSession
spark = SparkSession.builder.master('local').appName('scratch').getOrCreate()

# Create the dataframe
df = spark.createDataFrame([("a", 1), ("b", 2), ("c", 3)], ["letter", "name"])

# Function to get rows at `rownums`
def getrows(df, rownums=None):
    return df.rdd.zipWithIndex().filter(lambda x: x[1] in rownums).map(lambda x: x[0])

# Get rows at positions 0 and 2.
getrows(df, rownums=[0, 2]).collect()

# Output:
#> [(Row(letter='a', name=1)), (Row(letter='c', name=3))]

Git push requires username and password

You need to perform two steps -

  1. git remote remove origin
  2. git remote add origin [email protected]:NuggetAI/nugget.git

Notice the Git URL is a SSH URL and not an HTTPS URL... Which you can select from here:

Enter image description here

How to check if a variable is an integer in JavaScript?

function isInteger(argument) { return argument == ~~argument; }

Usage:

isInteger(1);     // true<br>
isInteger(0.1);   // false<br>
isInteger("1");   // true<br>
isInteger("0.1"); // false<br>

or:

function isInteger(argument) { return argument == argument + 0 && argument == ~~argument; }

Usage:

isInteger(1);     // true<br>
isInteger(0.1);   // false<br>
isInteger("1");   // false<br>
isInteger("0.1"); // false<br>

intellij incorrectly saying no beans of type found for autowired repository

Putting @Component or @configuration in your bean config file seems to work, ie something like:

@Configuration
public class MyApplicationContext {
    @Bean
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");
    }
}

@Component
public class MyApplicationContext {
    @Bean
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");
    }
}

Inheritance and init method in Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

For .Net 4 use:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

printf with std::string?

It's compiling because printf isn't type safe, since it uses variable arguments in the C sense1. printf has no option for std::string, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.

The easiest way to fix this, since you're using C++, is printing it normally with std::cout, since std::string supports that through operator overloading:

std::cout << "Follow this command: " << myString;

If, for some reason, you need to extract the C-style string, you can use the c_str() method of std::string to get a const char * that is null-terminated. Using your example:

#include <iostream>
#include <string>
#include <stdio.h>

int main()
{
    using namespace std;

    string myString = "Press ENTER to quit program!";
    cout << "Come up and C++ me some time." << endl;
    printf("Follow this command: %s", myString.c_str()); //note the use of c_str
    cin.get();

    return 0;
}

If you want a function that is like printf, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format.


[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf, that means a string with encoded type information like %d meaning int. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.

How to access the request body when POSTing using Node.js and Express?

I'm absolutely new to JS and ES, but what seems to work for me is just this:

JSON.stringify(req.body)

Let me know if there's anything wrong with it!

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

TOMCAT - HTTP Status 404

  1. Click on Window > Show view > Server or right click on the server in "Servers" view, select "Properties".
  2. In the "General" panel, click on the "Switch Location" button.
  3. The "Location: [workspace metadata]" should replace by something else.
  4. Open the Overview screen for the server by double clicking it.
  5. In the Server locations tab , select "Use Tomcat location".
  6. Save the configurations and restart the Server.

You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.

server Locations in eclipse view

Find character position and update file name

If you're working with actual files (as opposed to some sort of string data), how about the following?

$files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }

(or use _.+$ if you want to cut everything from the first underscore.)

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

I found this PostgreSQL documentation helpful: http://www.postgresql.org/docs/8.0/interactive/functions-conditional.html.

In my case, I sought plain SQL to concatenate a field with brackets around it, if the field is not empty.

select itemid, 
  CASE 
    itemdescription WHEN '' THEN itemname 
    ELSE itemname || ' (' || itemdescription || ')' 
  END 
from items;

Check whether a cell contains a substring

I like Rink.Attendant.6 answer. I actually want to check for multiple strings and did it this way:

First the situation: Names that can be home builders or community names and I need to bucket the builders as one group. To do this I am looking for the word "builder" or "construction", etc. So -

=IF(OR(COUNTIF(A1,"*builder*"),COUNTIF(A1,"*builder*")),"Builder","Community")

'Static readonly' vs. 'const'

const:

  1. value should be given upon declaration
  2. compile time constant

readonly:

  1. value can be given upon declaration or during runtime using constructors.The value may vary depend upon the constructor used.
  2. run time constant

How to recover Git objects damaged by hard disk failure?

Here are two functions that may help if your backup is corrupted, or you have a few partially corrupted backups as well (this may happen if you backup the corrupted objects).

Run both in the repo you're trying to recover.

Standard warning: only use if you're really desperate and you have backed up your (corrupted) repo. This might not resolve anything, but at least should highlight the level of corruption.

fsck_rm_corrupted() {
    corrupted='a'
    while [ "$corrupted" ]; do
        corrupted=$(                                  \
        git fsck --full --no-dangling 2>&1 >/dev/null \
            | grep 'stored in'                          \
            | sed -r 's:.*(\.git/.*)\).*:\1:'           \
        )
        echo "$corrupted"
        rm -f "$corrupted"
    done
}

if [ -z "$1" ]  || [ ! -d "$1" ]; then
    echo "'$1' is not a directory. Please provide the directory of the git repo"
    exit 1
fi

pushd "$1" >/dev/null
fsck_rm_corrupted
popd >/dev/null

and

unpack_rm_corrupted() {
    corrupted='a'
    while [ "$corrupted" ]; do
        corrupted=$(                                  \
        git unpack-objects -r < "$1" 2>&1 >/dev/null \
            | grep 'stored in'                          \
            | sed -r 's:.*(\.git/.*)\).*:\1:'           \
        )
        echo "$corrupted"
        rm -f "$corrupted"
    done
}

if [ -z "$1" ]  || [ ! -d "$1" ]; then
    echo "'$1' is not a directory. Please provide the directory of the git repo"
    exit 1
fi

for p in $1/objects/pack/pack-*.pack; do
    echo "$p"
    unpack_rm_corrupted "$p"
done

Excel telling me my blank cells aren't blank

'Select non blank cells
Selection.SpecialCells(xlCellTypeConstants, 23).Select
' REplace tehse blank look like cells to something uniqu
Selection.Replace What:="", Replacement:="TOBEDELETED", LookAt:=xlWhole, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
'now replace this uique text to nothing and voila all will disappear
Selection.Replace What:="TOBEDELETED", Replacement:="", LookAt:=xlWhole, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

What is hashCode used for? Is it unique?

This is from the msdn article here:

https://blogs.msdn.microsoft.com/tomarcher/2006/05/10/are-hash-codes-unique/

"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."

So just use a hash algorithm suitable to your data size and it will have unique hashcodes.

Difference between UTF-8 and UTF-16?

Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.

Other than sharing same unicode number for given character, each one is their own format.

UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...

UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.

Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.

Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.

Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )

So, people use UTF-8 where ever possible.

Format specifier %02x

%02x means print at least 2 digits, prepend it with 0's if there's less. In your case it's 7 digits, so you get no extra 0 in front.

Also, %x is for int, but you have a long. Try %08lx instead.

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

how to clear JTable

I think you meant that you want to clear all the cells in the jTable and make it just like a new blank jTable. For an example, if your table is myTable, you can do following.

DefaultTableModel model = new DefaultTableModel();
myTable.setModel(model);

How to update the value of a key in a dictionary in Python?

Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.

>>> books = {}
>>> books['book'] = 3       
>>> books['book'] -= 1   
>>> books   
{'book': 2}   

In your case:

book_shop[ch1] -= 1

XmlSerializer: remove unnecessary xsi and xsd namespaces

There is an alternative - you can provide a member of type XmlSerializerNamespaces in the type to be serialized. Decorate it with the XmlNamespaceDeclarations attribute. Add the namespace prefixes and URIs to that member. Then, any serialization that does not explicitly provide an XmlSerializerNamespaces will use the namespace prefix+URI pairs you have put into your type.

Example code, suppose this is your type:

[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
  [XmlAttribute] 
  public bool Known;
  [XmlElement]
  public string Name;
  [XmlNamespaceDeclarations]
  public XmlSerializerNamespaces xmlns;
}

You can do this:

var p = new Person
  { 
      Name = "Charley",
      Known = false, 
      xmlns = new XmlSerializerNamespaces()
  }
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");

And that will mean that any serialization of that instance that does not specify its own set of prefix+URI pairs will use the "p" prefix for the "urn:mycompany.2009" namespace. It will also omit the xsi and xsd namespaces.

The difference here is that you are adding the XmlSerializerNamespaces to the type itself, rather than employing it explicitly on a call to XmlSerializer.Serialize(). This means that if an instance of your type is serialized by code you do not own (for example in a webservices stack), and that code does not explicitly provide a XmlSerializerNamespaces, that serializer will use the namespaces provided in the instance.

How to stop a function

This will end the function, and you can even customize the "Error" message:

import sys

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        sys.exit("The player doesn't want to play again") #Right here 

How to bind inverse boolean properties in WPF?

I had an inversion problem, but a neat solution.

Motivation was that the XAML designer would show an empty control e.g. when there was no datacontext / no MyValues (itemssource).

Initial code: hide control when MyValues is empty. Improved code: show control when MyValues is NOT null or empty.

Ofcourse the problem is how to express '1 or more items', which is the opposite of 0 items.

<ListBox ItemsSource={Binding MyValues}">
  <ListBox.Style x:Uid="F404D7B2-B7D3-11E7-A5A7-97680265A416">
    <Style TargetType="{x:Type ListBox}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding MyValues.Count}">
          <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ListBox.Style>
</ListBox>

I solved it by adding:

<DataTrigger Binding="{Binding MyValues.Count, FallbackValue=0, TargetNullValue=0}">

Ergo setting the default for the binding. Ofcourse this doesn't work for all kinds of inverse problems, but helped me out with clean code.

Configuring RollingFileAppender in log4j

I'm suspicious of the ActiveFileName property. According to the log4j javadoc, there isn't such a property on the TimeBasedRollingPolicy class. (No setActiveFileName or getActiveFileName methods.)

I don't know what specifying an unknown property would do, but it is possible that it will cause the containing object to be abandoned, and that could lead to the warnings that you saw.

Try leaving it out and seeing what happens.

How can I nullify css property?

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

height: auto;