Programs & Examples On #Gold parser

GOLD is a parsing system targeting multiple programming language.

What's the algorithm to calculate aspect ratio?

Here is a version of James Farey's best rational approximation algorithm with adjustable level of fuzziness ported to javascript from the aspect ratio calculation code originally written in python.

The method takes a float (width/height) and an upper limit for the fraction numerator/denominator.

In the example below I am setting an upper limit of 50 because I need 1035x582 (1.77835051546) to be treated as 16:9 (1.77777777778) rather than 345:194 which you get with the plain gcd algorithm listed in other answers.

<html>
<body>
<script type="text/javascript">
function aspect_ratio(val, lim) {

    var lower = [0, 1];
    var upper = [1, 0];

    while (true) {
        var mediant = [lower[0] + upper[0], lower[1] + upper[1]];

        if (val * mediant[1] > mediant[0]) {
            if (lim < mediant[1]) {
                return upper;
            }
            lower = mediant;
        } else if (val * mediant[1] == mediant[0]) {
            if (lim >= mediant[1]) {
                return mediant;
            }
            if (lower[1] < upper[1]) {
                return lower;
            }
            return upper;
        } else {
            if (lim < mediant[1]) {
                return lower;
            }
            upper = mediant;
        }
    }
}

document.write (aspect_ratio(800 / 600, 50) +"<br/>");
document.write (aspect_ratio(1035 / 582, 50) + "<br/>");
document.write (aspect_ratio(2560 / 1440, 50) + "<br/>");

    </script>
</body></html>

The result:

 4,3  // (1.33333333333) (800 x 600)
 16,9 // (1.77777777778) (2560.0 x 1440)
 16,9 // (1.77835051546) (1035.0 x 582)

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

List to array conversion to use ravel() function

I wanted a way to do this without using an extra module. First turn list to string, then append to an array:

dataset_list = ''.join(input_list)
dataset_array = []
for item in dataset_list.split(';'): # comma, or other
    dataset_array.append(item)

Dismissing a Presented View Controller

I think Apple are covering their backs a little here for a potentially kludgy piece of API.

  [self dismissViewControllerAnimated:NO completion:nil]

Is actually a bit of a fiddle. Although you can - legitimately - call this on the presented view controller, all it does is forward the message on to the presenting view controller. If you want to do anything over and above just dismissing the VC, you will need to know this, and you need to treat it much the same way as a delegate method - as that's pretty much what it is, a baked-in somewhat inflexible delegate method.

Perhaps they've come across loads of bad code by people not really understanding how this is put together, hence their caution.

But of course, if all you need to do is dismiss the thing, go ahead.

My own approach is a compromise, at least it reminds me what is going on:

  [[self presentingViewController] dismissViewControllerAnimated:NO completion:nil]

[Swift]

  self.presentingViewController?.dismiss(animated: false, completion:nil)

How to change target build on Android project?

The file default.properties is by default read only, changing that worked for me.

Best way to do a split pane in HTML

You can do it with jQuery UI without another JavaScript library. Just add a function to the .resizable resize event to adjust the width of the other div.

$("#left_pane").resizable({
  handles: 'e', // 'East' side of div draggable
  resize: function() {
    $("#right_pane").outerWidth( $("#container").innerWidth() - $("#left_pane").outerWidth() );
  }
});

Here's the complete JSFiddle.

PHP : send mail in localhost

I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.

<?php
include 'nav.php';
/*
    Download PhpMailer from the following link:
    https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
    Extract the PHPMailer-master folder into your xampp->htdocs folder
    Make changes in the following code and its done :-)

    You will receive the mail with the name Root User.
    To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
    And change the name here: 
    public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some   //other folder
ini_set("SMTP","ssl://smtp.gmail.com"); 
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP();  // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject  = "Eventbook";
$mail->Body     = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo  //Fill in the document.location thing
'<script type="text/javascript">
                        if(confirm("Your mail has been sent"))
                        document.location = "/";
        </script>';
}
?>

Oracle: Import CSV file

An alternative solution is using an external table: http://www.orafaq.com/node/848

Use this when you have to do this import very often and very fast.

How to customize listview using baseadapter

public class ListElementAdapter extends BaseAdapter{

    String[] data;
    Context context;
    LayoutInflater layoutInflater;


    public ListElementAdapter(String[] data, Context context) {
        super();
        this.data = data;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return data.length;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        convertView= layoutInflater.inflate(R.layout.item, null);

        TextView txt=(TextView)convertView.findViewById(R.id.text);

        txt.setText(data[position]);



        return convertView;
    }
}

Just call ListElementAdapter in your Main Activity and set Adapter to ListView.

How do I make a Git commit in the past?

This is an old question but I recently stumbled upon it.

git commit --date='2021-01-01 12:12:00' -m "message" worked properly and verified it on GitHub.

Send File Attachment from Form Using phpMailer and PHP

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

c# dictionary one key many values

Take a look at MultiValueDictionary from Microsoft.

Example Code:

MultiValueDictionary<string, string> Parameters = new MultiValueDictionary<string, string>();

Parameters.Add("Malik", "Ali");
Parameters.Add("Malik", "Hamza");
Parameters.Add("Malik", "Danish");

//Parameters["Malik"] now contains the values Ali, Hamza, and Danish

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

In my case, everything was working properly then suddenly stopped worked because I think Resharper altered some changes which caused the problem. My project was divided into the data layer, service and presentation layer. I had Entity framework installed and referenced in my data layer but still the error didn't go away. Uninstalling and reinstalling didn't work either. Finally, I solved it by making the data layer the Startup project, making migration, updating the database and changing the Startup project back to my presentation layer.

Modify request parameter with servlet filter

As you've noted HttpServletRequest does not have a setParameter method. This is deliberate, since the class represents the request as it came from the client, and modifying the parameter would not represent that.

One solution is to use the HttpServletRequestWrapper class, which allows you to wrap one request with another. You can subclass that, and override the getParameter method to return your sanitized value. You can then pass that wrapped request to chain.doFilter instead of the original request.

It's a bit ugly, but that's what the servlet API says you should do. If you try to pass anything else to doFilter, some servlet containers will complain that you have violated the spec, and will refuse to handle it.

A more elegant solution is more work - modify the original servlet/JSP that processes the parameter, so that it expects a request attribute instead of a parameter. The filter examines the parameter, sanitizes it, and sets the attribute (using request.setAttribute) with the sanitized value. No subclassing, no spoofing, but does require you to modify other parts of your application.

What is the technology behind wechat, whatsapp and other messenger apps?

WhatsApp has chosen Erlang a language built for writing scalable applications that are designed to withstand errors. Erlang uses an abstraction called the Actor model for it's concurrency - http://en.wikipedia.org/wiki/Actor_(programming_language) Instead of the more traditional shared memory approach, actors communicate by sending each other messages. Actors unlike threads are designed to be lightweight. Actors could be on the same machine or on different machines and the message passing abstractions works for both. A simple implementation of WhatsApp could be: Each user/device is represented as an actor. This actor is responsible for handling the inbox of the user, how it gets serialized to disk, the messages that the user sends and the messages that the user receives. Let's assume that Alice and Bob are friends on WhatsApp. So there is an an Alice actor and a Bob actor.

Let's trace a series of messages flowing back and forth:

Alice decides to message Bob. Alice's phone establishes a connection to the WhatsApp server and it is established that this connection is definitely from Alice's phone. Alice now sends via TCP the following message: "For Bob: A giant monster is attacking the Golden Gate Bridge". One of the WhatsApp front end server deserializes this message and delivers this message to the actor called Alice.

Alice the actor decides to serialize this and store it in a file called "Alice's Sent Messages", stored on a replicated file system to prevent data loss due to unpredictable monster rampage. Alice the actor then decides to forward this message to Bob the actor by passing it a message "Msg1 from Alice: A giant monster is attacking the Golden Gate Bridge". Alice the actor can retry with exponential back-off till Bob the actor acknowledges receiving the message.

Bob the actor eventually receives the message from (2) and decides to store this message in a file called "Bob's Inbox". Once it has stored this message durably Bob the actor will acknowledge receiving the message by sending Alice the actor a message of it's own saying "I received Msg1". Alice the actor can now stop it's retry efforts. Bob the actor then checks to see if Bob's phone has an active connection to the server. It does and so Bob the actor streams this message to the device via TCP.

Bob sees this message and replies with "For Alice: Let's create giant robots to fight them". This is now received by Bob the actor as outlined in Step 1. Bob the actor then repeats Step 2 and 3 to make sure Alice eventually receives the idea that will save mankind.

WhatsApp actually uses the XMPP protocol instead of the vastly superior protocol that I outlined above, but you get the point.

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

Where is Maven's settings.xml located on Mac OS?

I found it under /usr/share/java/maven-3.0.3/conf , 10.8.2

type checking in javascript

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

Why .NET String is immutable?

There are five common ways by which a class data store data that cannot be modified outside the storing class' control:

  1. As value-type primitives
  2. By holding a freely-shareable reference to class object whose properties of interest are all immutable
  3. By holding a reference to a mutable class object that will never be exposed to anything that might mutate any properties of interest
  4. As a struct, whether "mutable" or "immutable", all of whose fields are of types #1-#4 (not #5).
  5. By holding the only extant copy of a reference to an object whose properties can only be mutated via that reference.

Because strings are of variable length, they cannot be value-type primitives, nor can their character data be stored in a struct. Among the remaining choices, the only one which wouldn't require that strings' character data be stored in some kind of immutable object would be #5. While it would be possible to design a framework around option #5, that choice would require that any code which wanted a copy of a string that couldn't be changed outside its control would have to make a private copy for itself. While it hardly be impossible to do that, the amount of extra code required to do that, and the amount of extra run-time processing necessary to make defensive copies of everything, would far outweigh the slight benefits that could come from having string be mutable, especially given that there is a mutable string type (System.Text.StringBuilder) which accomplishes 99% of what could be accomplished with a mutable string.

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

I have tried all the above mentioned options but can not find the solution to this problem . Then I got its solution.... This error is flashed when we are trying to open mysql with out stating the service. Follow the bellow mentioned steps..
STEP 1
Open cmd prompt
to start the service type
mysqld --console this will start the mysql service
enter image description here
STEP 2 dont close this cmd prompt
now open new cmd prompt and type
mysql -u root -p
then enter ur password
enter image description here

Sort Go map values by keys

According to the Go spec, the order of iteration over a map is undefined, and may vary between runs of the program. In practice, not only is it undefined, it's actually intentionally randomized. This is because it used to be predictable, and the Go language developers didn't want people relying on unspecified behavior, so they intentionally randomized it so that relying on this behavior was impossible.

What you'll have to do, then, is pull the keys into a slice, sort them, and then range over the slice like this:

var m map[keyType]valueType
keys := sliceOfKeys(m) // you'll have to implement this
for _, k := range keys {
    v := m[k]
    // k is the key and v is the value; do your computation here
}

Creating an empty list in Python

Here is how you can test which piece of code is faster:

% python -mtimeit  "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop

% python -mtimeit  "l=list()"
1000000 loops, best of 3: 0.297 usec per loop

However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.

Readability is very subjective. I prefer [], but some very knowledgable people, like Alex Martelli, prefer list() because it is pronounceable.

Create a branch in Git from another branch

For creating a branch from another one can use this syntax as well:

git push origin refs/heads/<sourceBranch>:refs/heads/<targetBranch>

It is a little shorter than "git checkout -b " + "git push origin "

What is the best way to remove the first element from an array?

An alternative ugly method:

   String[] a ={"BLAH00001","DIK-11","DIK-2","MAN5"};
   String[] k=Arrays.toString(a).split(", ",2)[1].split("]")[0].split(", ");

Fill remaining vertical space - only CSS

You can use CSS Flexbox instead another display value, The Flexbox Layout (Flexible Box) module aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic.

Example

/* CONTAINER */
#wrapper
{
   width:300px;
   height:300px;
    display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox; /* TWEENER - IE 10 */
    display: -webkit-flex; /* NEW - Chrome */
    display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
    -ms-flex-direction: column;
    -moz-flex-direction: column;
    -webkit-flex-direction: column;
    flex-direction: column;
}

/* SOME ITEM CHILD ELEMENTS */
#first
{
   width:300px;
    height: 200px;
   background-color:#F5DEB3;

}

#second
{
   width:300px;
   background-color: #9ACD32;
    -webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1; /* OLD - Firefox 19- */
    -webkit-flex: 1; /* Chrome */
    -ms-flex: 1; /* IE 10 */
    flex: 1; /* NEW, */
}

jsfiddle Example

If you want to have full support for old browsers like IE9 or below, you will have to use a polyfills like flexy, this polyfill enable support for Flexbox model but only for 2012 spec of flexbox model.

Recently I found another polyfill to help you with Internet Explorer 8 & 9 or any older browser that not have support for flexbox model, I still have not tried it but I leave the link here

You can find a usefull and complete Guide to Flexbox model by Chris Coyer here

Jquery: How to check if the element has certain css class/style

Or, if you need to access the element that has that property and it does not use an id, you could go this route:

$("img").each(function () {
        if ($(this).css("float") == "left") { $(this).addClass("left"); }
        if ($(this).css("float") == "right") { $(this).addClass("right"); }
    })

Bootstrap 3 - How to load content in modal body via AJAX?

I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.

The JS part:

$('[data-toggle="ajaxModal"]').on('click',
              function(e) {
                $('#ajaxModal').remove();
                e.preventDefault();
                var $this = $(this)
                  , $remote = $this.data('remote') || $this.attr('href')
                  , $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
                $('body').append($modal);
                $modal.modal({backdrop: 'static', keyboard: false});
                $modal.load($remote);
              }
            );

Finally, in the remote content, you need to put the entire structure to work.

<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
            <a href="#" class="btn btn-primary">Button</a>
            <a href="#" class="btn btn-primary">Another button...</a>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

How best to determine if an argument is not sent to the JavaScript function

In ES6 (ES2015) you can use Default parameters

_x000D_
_x000D_
function Test(arg1 = 'Hello', arg2 = 'World!'){_x000D_
  alert(arg1 + ' ' +arg2);_x000D_
}_x000D_
_x000D_
Test('Hello', 'World!'); // Hello World!_x000D_
Test('Hello'); // Hello World!_x000D_
Test(); // Hello World!
_x000D_
_x000D_
_x000D_

AppStore - App status is ready for sale, but not in app store

We published it today after having 'Release this version'. It took 15 minutes to show on the App Store.

This is due to App Store will sync the data across servers.

Codeigniter LIKE with wildcard(%)

  $this->db->like('title', 'match', 'before'); 
 // Produces: WHERE title LIKE '%match' 

 $this->db->like('title', 'match', 'after'); 
// Produces: WHERE title LIKE 'match%' 

$this->db->like('title', 'match', 'both'); 
// Produces: WHERE title LIKE '%match%'

HTML table: keep the same width for columns

well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.

Is there a way to make a DIV unselectable?

Use

onselectstart="return false"

it prevents copying your content.

How to connect TFS in Visual Studio code

I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).

This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.

Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.

Azure_Repo_Settings

Then under Tfvc: Location you can paste the location of the executable.

Location_Settings

For 2017 it'll be

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Or for 2019 (Preview)

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.

Git_URL

After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone pasted my repo:

Git_Repo

Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen

Team_Button

Then chose the new method of authentication

New_Method

Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).

Enter_Code_Screen

Click Continue

Continue_Button

Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.

Bottom_Bar

Cheers!

How can I access the MySQL command line with XAMPP for Windows?

I had the same issue. Fistly, thats what i have :

  1. win 10
  2. xampp
  3. git bash

and i have done this to fix my problem :

  1. go to search box(PC)
  2. tape this environnement variable
  3. go to 'path' click 'edit'
  4. add this "%systemDrive%\xampp\mysql\bin\" C:\xampp\mysql\bin\
  5. click ok
  6. go to Git Bash and right click it and open it and run as administrator
  7. right this on your Git Bash winpty mysql -u root if your password is empty or winpty mysql -u root -p if you do have a password

How can I get key's value from dictionary in Swift?

From Apple Docs

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

https://developer.apple.com/documentation/swift/dictionary

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

HTML combo box with option to type an entry

Before datalist (see note below), you would supply an additional input element for people to type in their own option.

_x000D_
_x000D_
<select name="example">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="-">Other</option>
</select>

<input type="text" name="other">
_x000D_
_x000D_
_x000D_

This mechanism works in all browsers and requires no JavaScript.

You could use a little JavaScript to be clever about only showing the input if the "Other" option was selected.

datalist Element

The datalist element is intended to provide a better mechanism for this concept. In some browsers, e.g. iOS Safari < 12.2, this was not supported or the implementation had issues. Check the Can I Use page to see current datalist support.

_x000D_
_x000D_
<input type="text" name="example" list="exampleList">
<datalist id="exampleList">
  <option value="A">  
  <option value="B">
</datalist>
_x000D_
_x000D_
_x000D_

nvm keeps "forgetting" node in new terminal session

I'm using ZSH so I had to modify ~/.zshrc with the lines concerning NVM in that order:

[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
source ~/.nvm/nvm.sh

Disabling enter key for form

For a non-javascript solution, try putting a <button disabled>Submit</button> into your form, positioned before any other submit buttons/inputs. I suggest immediately after the <form> opening tag (and using CSS to hide it, accesskey='-1' to get it out of the tab sequence, etc)

AFAICT, user agents look for the first submit button when ENTER is hit in an input, and if that button is disabled will then stop looking for another.

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

https://www.w3.org/TR/html5/forms.html#implicit-submission

However, I do know that Safari 10 MacOS misbehaves here, submitting the form even if the default button is disabled.

So, if you can assume javascript, insert <button onclick="return false;">Submit</button> instead. On ENTER, the onclick handler will get called, and since it returns false the submission process stops. Browsers I've tested this with won't even do the browser-validation thing (focussing the first invalid form control, displaying an error message, etc).

How do I disable text selection with CSS or JavaScript?

Try this CSS code for cross-browser compatibility.

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

Cleanest way to reset forms

component.html (What you named you form)

<form [formGroup]="contactForm">

(add click event (click)="clearForm())

<button (click)="onSubmit()" (click)="clearForm()" type="submit" class="btn waves-light" mdbWavesEffect>Send<i class="fa fa-paper-plane-o ml-1"></i></button>

component.ts

 clearForm() {
             this.contactForm.reset();
            }

view all code: https://ewebdesigns.com.au/angular-6-contact-form/ How to add a contact form with firebase

Better way to find last used row

You should use a with statement to qualify both your Rows and Columns counts. This will prevent any errors while working with older pre 2007 and newer 2007 Excel Workbooks.

Last Column

With Sheets("Sheet2")
    .Cells(1, .Columns.Count).End(xlToLeft).Column
End With 

Last Row

With Sheets("Sheet2")
    .Range("A" & .Rows.Count).End(xlUp).Row
End With 

Or

With Sheets("Sheet2")
    .Cells(.Rows.Count, 1).End(xlUp).Row
End With 

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to generate a simple popup using jQuery

Simple popup window by using html5 and javascript.

html:-

    <dialog id="window">  
     <h3>Sample Dialog!</h3>  
     <p>Lorem ipsum dolor sit amet</p>  
     <button id="exit">Close Dialog</button>
    </dialog>  

  <button id="show">Show Dialog</button> 

JavaScript:-

   (function() {  

            var dialog = document.getElementById('window');  
            document.getElementById('show').onclick = function() {  
                dialog.show();  
            };  
            document.getElementById('exit').onclick = function() {  
                dialog.close();  
            };
        })();

'POCO' definition

"Plain Old C# Object"

Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.

EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.

TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties.

See below for an example of each.

Example of a POCO:

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}

Example of something that isn’t a POCO:

public class PersonComponent : System.ComponentModel.Component
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public string Name { get; set; }

    public int Age { get; set; }
}

The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is not just a plain old object anymore.

html5 - canvas element - Multiple layers

I understand that the Q does not want to use a library, but I will offer this for others coming from Google searches. @EricRowell mentioned a good plugin, but, there is also another plugin you can try, html2canvas.

In our case we are using layered transparent PNG's with z-index as a "product builder" widget. Html2canvas worked brilliantly to boil the stack down without pushing images, nor using complexities, workarounds, and the "non-responsive" canvas itself. We were not able to do this smoothly/sane with the vanilla canvas+JS.

First use z-index on absolute divs to generate layered content within a relative positioned wrapper. Then pipe the wrapper through html2canvas to get a rendered canvas, which you may leave as-is, or output as an image so that a client may save it.

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

Is it possible to play music during calls so that the partner can hear it ? Android

Yes it is possible in Sony ericssion xylophone w20 .I have got this phone in 2010.but yet this type of phone I have not seen.

Creating a JSON array in C#

You're close. This should do the trick:

new {items = new [] {
    new {name = "command" , index = "X", optional = "0"}, 
    new {name = "command" , index = "X", optional = "0"}
}}

If your source was an enumerable of some sort, you might want to do this:

new {items = source.Select(item => new 
{
    name = item.Name, index = item.Index, options = item.Optional
})};

What is the C# Using block and why should I use it?

From MSDN:

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed.

Service Temporarily Unavailable Magento?

Now in new version magento2 on Generate error Service Temporarily Unavailable.

Remove maintenance.flag

From this path which is changed magento2/var/maintenance.flag.

Also

$ rm maintenance.flag

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Complementing the above answers and also "Parroting" from the Windows Dev Center documentation,

The Winsock2.h header file internally includes core elements from the Windows.h header file, so there is not usually an #include line for the Windows.h header file in Winsock applications. If an #include line is needed for the Windows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, the Windows.h header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in the Winsock.h header file will conflict with the declarations in the Winsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents the Winsock.h from being included by the Windows.h header ..

PHP - Session destroy after closing browser

Use the following code to destroy the session:

 <?php
    session_start();
    unset($_SESSION['sessionvariable']);
    header("Location:index.php");
    ?>

Tesseract OCR simple example

I was able to get it to work by following these instructions.

  • Download the sample code Tesseract sample code

  • Unzip it to a new location

  • Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)

  • Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to) NuGet Tesseract

  • Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs: Console.Write("Press any key to continue . . . "); Console.ReadKey(true);

  • Run (hit F5)

  • You should get this windows console output enter image description here

Using Eloquent ORM in Laravel to perform search of database using LIKE

You're able to do database finds using LIKE with this syntax:

Model::where('column', 'LIKE', '%value%')->get();

How do I manage MongoDB connections in a Node.js web application?

You should create a connection as service then reuse it when need.

// db.service.js
import { MongoClient } from "mongodb";
import database from "../config/database";

const dbService = {
  db: undefined,
  connect: callback => {
    MongoClient.connect(database.uri, function(err, data) {
      if (err) {
        MongoClient.close();
        callback(err);
      }
      dbService.db = data;
      console.log("Connected to database");
      callback(null);
    });
  }
};

export default dbService;

my App.js sample

// App Start
dbService.connect(err => {
  if (err) {
    console.log("Error: ", err);
    process.exit(1);
  }

  server.listen(config.port, () => {
    console.log(`Api runnning at ${config.port}`);
  });
});

and use it wherever you want with

import dbService from "db.service.js"
const db = dbService.db

WorksheetFunction.CountA - not working post upgrade to Office 2010

This answer from another forum solved the problem.

(substitute your own range for the "I:I" shown here)

Re: CountA not working in VBA

Should be:

Nonblank = Application.WorksheetFunction.CountA(Range("I:I"))

You have to refer to ranges in the vba format, not the in-excel format.

Abstract methods in Java

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

abstract class AbstractObject {
   public abstract void method();
}

class ImplementingObject extends AbstractObject {
  public void method() {
    doSomething();
  }
}

So, it's exactly as the error states: your abstract method can not have a body.

There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.

A very simple example would be shapes:

You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.

(This is taken from the site I linked above)

abstract class GraphicObject {
    int x, y;
    ...
    void moveTo(int newX, int newY) {
        ...
    }
    abstract void draw();
    abstract void resize();
}

class Circle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}

How to write a foreach in SQL Server?

This generally (almost always) performs better than a cursor and is simpler:

DECLARE @PractitionerList TABLE(PracticionerID INT)
DECLARE @PracticionerID INT
    
INSERT @PractitionerList(PracticionerID)
SELECT PracticionerID
FROM Practitioner
    
WHILE(1 = 1)
BEGIN
            
    SET @PracticionerID = NULL
    SELECT TOP(1) @PracticionerID = PracticionerID
    FROM @PractitionerList
    
    IF @PracticionerID IS NULL
        BREAK
            
    PRINT 'DO STUFF'
    
    DELETE TOP(1) FROM @PractitionerList
    
END

Command to run a .bat file

There are many possibilities to solve this task.

1. RUN the batch file with full path

The easiest solution is running the batch file with full path.

"F:\- Big Packets -\kitterengine\Common\Template.bat"

Once end of batch file Template.bat is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.

The current directory for the batch file Template.bat is the current directory of the current process. In case of Template.bat requires that the directory of this batch file is the current directory, the batch file Template.bat should contain after @echo off as second line the following command line:

cd /D "%~dp0"

Run in a command prompt window cd /? for getting displayed the help of this command explaining parameter /D ... change to specified directory also on a different drive.

Run in a command prompt window call /? for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0 ... drive and path of argument 0 which is the name of the batch file.

2. CALL the batch file with full path

Another solution is calling the batch file with full path.

call "F:\- Big Packets -\kitterengine\Common\Template.bat"

The difference to first solution is that after end of batch file Template.bat is reached the batch processing continues in batch script containing this command line.

For the current directory read above.

3. Change directory and RUN batch file with one command line

There are 3 operators for running multiple commands on one command line: &, && and ||.
For details see answer on Single line with multiple commands using Windows batch file

I suggest for this task the && operator.

cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat

As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat is successful.

4. Change directory and CALL batch file with one command line

This command line changes the directory and on success calls the batch file.

cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat

The difference to third solution is the return to current batch script on exiting processing of Template.bat.

5. Change directory and CALL batch file with keeping current environment with one command line

The four solutions above change the current directory and it is unknown what Template.bat does regarding

  1. current directory
  2. environment variables
  3. command extensions state
  4. delayed expansion state

In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat changes on environment for itself, it is advisable to use setlocal and endlocal.

Run in a command prompt window setlocal /? and endlocal /? for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.

setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal

Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.


ONE MORE NOTE

If batch file Template.bat contains the command exit without parameter /B and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat contains exit /B or goto :EOF instead of just exit if there is exit used at all in this batch file.

adb connection over tcp not working now

Try to do port forwarding,

adb forward tcp:<PC port> tcp:<device port>.

like:

adb forward tcp:5555 tcp:5555.

sounds like 5555 port is captured so use other one. As I know 7612 is empty

[Edit]

C:\Users\m>adb forward tcp:7612 tcp:7612

C:\Users\m>adb tcpip 7612
restarting in TCP mode port: 7612

C:\Users\m>adb connect 192.168.1.12
connected to 192.168.1.12:7612

Be sure that you connect to the right IP address. (You can download Network Info 2 to check your IP)

Conditional WHERE clause in SQL Server

To answer the underlying question of how to use a CASE expression in the WHERE clause:

First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...] and expect to get 'Frank', FALSE in the result set.

Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name; or WHERE 'Frank';. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';

That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!

Here:

WHERE 
    DateDropped = 0
    AND CASE
            WHEN @JobsOnHold  = 1 AND DateAppr >= 0 THEN 'True'
            WHEN DateAppr != 0 THEN 'True'
            ELSE 'False'
        END = 'True'

Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True' or 'False' = 'True'.

Note that there's nothing special about 'False' and 'True'. You can use 0 and 1 if you'd rather, too.

You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.

insert datetime value in sql database with c#

The following should work and is my recommendation (parameterized query):

DateTime dateTimeVariable = //some DateTime value, e.g. DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();

HTTP headers in Websockets client API

Updated 2x

Short answer: No, only the path and protocol field can be specified.

Longer answer:

There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.

The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor:

var ws = new WebSocket("ws://example.com/path", "protocol");
var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);

The above results in the following headers:

Sec-WebSocket-Protocol: protocol

and

Sec-WebSocket-Protocol: protocol1, protocol2

A common pattern for achieving WebSocket authentication/authorization is to implement a ticketing system where the page hosting the WebSocket client requests a ticket from the server and then passes this ticket during WebSocket connection setup either in the URL/query string, in the protocol field, or required as the first message after the connection is established. The server then only allows the connection to continue if the ticket is valid (exists, has not been already used, client IP encoded in ticket matches, timestamp in ticket is recent, etc). Here is a summary of WebSocket security information: https://devcenter.heroku.com/articles/websocket-security

Basic authentication was formerly an option but this has been deprecated and modern browsers don't send the header even if it is specified.

Basic Auth Info (Deprecated - No longer functional):

NOTE: the following information is no longer accurate in any modern browsers.

The Authorization header is generated from the username and password (or just username) field of the WebSocket URI:

var ws = new WebSocket("ws://username:[email protected]")

The above results in the following header with the string "username:password" base64 encoded:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

I have tested basic auth in Chrome 55 and Firefox 50 and verified that the basic auth info is indeed negotiated with the server (this may not work in Safari).

Thanks to Dmitry Frank's for the basic auth answer

Printing object properties in Powershell

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.

Add column to SQL Server

Add new column to Table with default value.

ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE

Making macOS Installer Packages which are Developer ID ready

Our example project has two build targets: HelloWorld.app and Helper.app. We make a component package for each and combine them into a product archive.

A component package contains payload to be installed by the OS X Installer. Although a component package can be installed on its own, it is typically incorporated into a product archive.

Our tools: pkgbuild, productbuild, and pkgutil

After a successful "Build and Archive" open $BUILT_PRODUCTS_DIR in the Terminal.

$ cd ~/Library/Developer/Xcode/DerivedData/.../InstallationBuildProductsLocation
$ pkgbuild --analyze --root ./HelloWorld.app HelloWorldAppComponents.plist
$ pkgbuild --analyze --root ./Helper.app HelperAppComponents.plist

This give us the component-plist, you find the value description in the "Component Property List" section. pkgbuild -root generates the component packages, if you don't need to change any of the default properties you can omit the --component-plist parameter in the following command.

productbuild --synthesize results in a Distribution Definition.

$ pkgbuild --root ./HelloWorld.app \
    --component-plist HelloWorldAppComponents.plist \
    HelloWorld.pkg
$ pkgbuild --root ./Helper.app \
    --component-plist HelperAppComponents.plist \
    Helper.pkg
$ productbuild --synthesize \
    --package HelloWorld.pkg --package Helper.pkg \
    Distribution.xml 

In the Distribution.xml you can change things like title, background, welcome, readme, license, and so on. You turn your component packages and distribution definition with this command into a product archive:

$ productbuild --distribution ./Distribution.xml \
    --package-path . \
    ./Installer.pkg

I recommend to take a look at iTunes Installers Distribution.xml to see what is possible. You can extract "Install iTunes.pkg" with:

$ pkgutil --expand "Install iTunes.pkg" "Install iTunes"

Lets put it together

I usually have a folder named Package in my project which includes things like Distribution.xml, component-plists, resources and scripts.

Add a Run Script Build Phase named "Generate Package", which is set to Run script only when installing:

VERSION=$(defaults read "${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}/Contents/Info" CFBundleVersion)

PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
TMP1_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp1.pkg"
TMP2_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp2"
TMP3_ARCHIVE="${BUILT_PRODUCTS_DIR}/$PACKAGE_NAME-tmp3.pkg"
ARCHIVE_FILENAME="${BUILT_PRODUCTS_DIR}/${PACKAGE_NAME}.pkg"

pkgbuild --root "${INSTALL_ROOT}" \
    --component-plist "./Package/HelloWorldAppComponents.plist" \
    --scripts "./Package/Scripts" \
    --identifier "com.test.pkg.HelloWorld" \
    --version "$VERSION" \
    --install-location "/" \
    "${BUILT_PRODUCTS_DIR}/HelloWorld.pkg"
pkgbuild --root "${BUILT_PRODUCTS_DIR}/Helper.app" \
    --component-plist "./Package/HelperAppComponents.plist" \
    --identifier "com.test.pkg.Helper" \
    --version "$VERSION" \
    --install-location "/" \
    "${BUILT_PRODUCTS_DIR}/Helper.pkg"
productbuild --distribution "./Package/Distribution.xml"  \
    --package-path "${BUILT_PRODUCTS_DIR}" \
    --resources "./Package/Resources" \
    "${TMP1_ARCHIVE}"

pkgutil --expand "${TMP1_ARCHIVE}" "${TMP2_ARCHIVE}"
    
# Patches and Workarounds

pkgutil --flatten "${TMP2_ARCHIVE}" "${TMP3_ARCHIVE}"

productsign --sign "Developer ID Installer: John Doe" \
    "${TMP3_ARCHIVE}" "${ARCHIVE_FILENAME}"

If you don't have to change the package after it's generated with productbuild you could get rid of the pkgutil --expand and pkgutil --flatten steps. Also you could use the --sign paramenter on productbuild instead of running productsign.

Sign an OS X Installer

Packages are signed with the Developer ID Installer certificate which you can download from Developer Certificate Utility.

They signing is done with the --sign "Developer ID Installer: John Doe" parameter of pkgbuild, productbuild or productsign.

Note that if you are going to create a signed product archive using productbuild, there is no reason to sign the component packages.

Developer Certificate Utility

All the way: Copy Package into Xcode Archive

To copy something into the Xcode Archive we can't use the Run Script Build Phase. For this we need to use a Scheme Action.

Edit Scheme and expand Archive. Then click post-actions and add a New Run Script Action:

In Xcode 6:

#!/bin/bash

PACKAGES="${ARCHIVE_PATH}/Packages"
  
PACKAGE_NAME=`echo "$PRODUCT_NAME" | sed "s/ /_/g"`
ARCHIVE_FILENAME="$PACKAGE_NAME.pkg"
PKG="${OBJROOT}/../BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"

if [ -f "${PKG}" ]; then
    mkdir "${PACKAGES}"
    cp -r "${PKG}" "${PACKAGES}"
fi

In Xcode 5, use this value for PKG instead:

PKG="${OBJROOT}/ArchiveIntermediates/${TARGET_NAME}/BuildProductsPath/${CONFIGURATION}/${ARCHIVE_FILENAME}"

In case your version control doesn't store Xcode Scheme information I suggest to add this as shell script to your project so you can simple restore the action by dragging the script from the workspace into the post-action.

Scripting

There are two different kinds of scripting: JavaScript in Distribution Definition Files and Shell Scripts.

The best documentation about Shell Scripts I found in WhiteBox - PackageMaker How-to, but read this with caution because it refers to the old package format.

Apple Silicon

In order for the package to run as arm64, the Distribution file has to specify in its hostArchitectures section that it supports arm64 in addition to x86_64:

<options hostArchitectures="arm64,x86_64" />

Additional Reading

Known Issues and Workarounds

Destination Select Pane

The user is presented with the destination select option with only a single choice - "Install for all users of this computer". The option appears visually selected, but the user needs to click on it in order to proceed with the installation, causing some confusion.

Example showing the installer bug

Apples Documentation recommends to use <domains enable_anywhere ... /> but this triggers the new more buggy Destination Select Pane which Apple doesn't use in any of their Packages.

Using the deprecate <options rootVolumeOnly="true" /> give you the old Destination Select Pane. Example showing old Destination Select Pane


You want to install items into the current user’s home folder.

Short answer: DO NOT TRY IT!

Long answer: REALLY; DO NOT TRY IT! Read Installer Problems and Solutions. You know what I did even after reading this? I was stupid enough to try it. Telling myself I'm sure that they fixed the issues in 10.7 or 10.8.

First of all I saw from time to time the above mentioned Destination Select Pane Bug. That should have stopped me, but I ignored it. If you don't want to spend the week after you released your software answering support e-mails that they have to click once the nice blue selection DO NOT use this.

You are now thinking that your users are smart enough to figure the panel out, aren't you? Well here is another thing about home folder installation, THEY DON'T WORK!

I tested it for two weeks on around 10 different machines with different OS versions and what not, and it never failed. So I shipped it. Within an hour of the release I heart back from users who just couldn't install it. The logs hinted to permission issues you are not gonna be able to fix.

So let's repeat it one more time: We do not use the Installer for home folder installations!


RTFD for Welcome, Read-me, License and Conclusion is not accepted by productbuild.

Installer supported since the beginning RTFD files to make pretty Welcome screens with images, but productbuild doesn't accept them.

Workarounds: Use a dummy rtf file and replace it in the package by after productbuild is done.

Note: You can also have Retina images inside the RTFD file. Use multi-image tiff files for this: tiffutil -cat Welcome.tif Welcome_2x.tif -out FinalWelcome.tif. More details.


Starting an application when the installation is done with a BundlePostInstallScriptPath script:

#!/bin/bash

LOGGED_IN_USER_ID=`id -u "${USER}"`

if [ "${COMMAND_LINE_INSTALL}" = "" ]
then
    /bin/launchctl asuser "${LOGGED_IN_USER_ID}" /usr/bin/open -g PATH_OR_BUNDLE_ID
fi

exit 0

It is important to run the app as logged in user, not as the installer user. This is done with launchctl asuser uid path. Also we only run it when it is not a command line installation, done with installer tool or Apple Remote Desktop.


Data binding for TextBox

We can use following code

textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

Where

  • "Text" – the property of textbox
  • model – the model object enter code here
  • "Name" – the value of model which to bind the textbox.

How do I get IntelliJ to recognize common Python modules?

Another possible fix (solved my problem)

You might have configured the environment properly but for some reason it broke along the way. In this case go to:

file > project settings > modules

Deploy the list of SDKs and look for a red line with [invalid] at the end. If you find one, you have to recreate a python sdk.

It is likely that your previously working SDK is there too, but not red. Delete it.

Now you can click on the new button and add your favorite python virtualenv. And it should work now.

How does one use glide to download an image into a bitmap?

I'm not familiar enough with Glide, but it looks like if you know the target size, you can use something like this:

Bitmap theBitmap = Glide.
        with(this).
        load("http://....").
        asBitmap().
        into(100, 100). // Width and height
        get();

It looks like you can pass -1,-1, and get a full size image (purely based on tests, can't see it documented).

Note into(int,int) returns a FutureTarget<Bitmap>, so you have to wrap this in a try-catch block covering ExecutionException and InterruptedException. Here's a more complete example implementation, tested and working:

class SomeActivity extends Activity {

    private Bitmap theBitmap = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // onCreate stuff ...
        final ImageView image = (ImageView) findViewById(R.id.imageView);

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                Looper.prepare();
                try {
                    theBitmap = Glide.
                        with(SomeActivity.this).
                        load("https://www.google.es/images/srpr/logo11w.png").
                        asBitmap().
                        into(-1,-1).
                        get();
                 } catch (final ExecutionException e) {
                     Log.e(TAG, e.getMessage());
                 } catch (final InterruptedException e) {
                     Log.e(TAG, e.getMessage());
                 }
                 return null;
            }
            @Override
            protected void onPostExecute(Void dummy) {
                if (null != theBitmap) {
                    // The full bitmap should be available here
                    image.setImageBitmap(theBitmap);
                    Log.d(TAG, "Image loaded");
                };
            }
        }.execute();
    }
}

Following Monkeyless' suggestion in the comment below (and this appears to be the official way too), you can use a SimpleTarget, optionally coupled with override(int,int) to simplify the code considerably. However, in this case the exact size must be provided (anything below 1 isn't accepted):

Glide
    .with(getApplicationContext())
    .load("https://www.google.es/images/srpr/logo11w.png")
    .asBitmap()
    .into(new SimpleTarget<Bitmap>(100,100) {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
            image.setImageBitmap(resource); // Possibly runOnUiThread()
        }
    });

as suggested by @hennry if you required the same image then use new SimpleTarget<Bitmap>()

Is there a kind of Firebug or JavaScript console debug for Android?

I installed console add-on of the firefox (https://addons.mozilla.org/en-US/android/addon/console/) on my firefox browser on android and it worked quite well. Helped me debug my angular2 app.

HTML5 Canvas: Zooming

Canvas zoom and pan

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<canvas id="myCanvas" width="" height=""_x000D_
style="border:1px solid #d3d3d3;">_x000D_
Your browser does not support the canvas element._x000D_
</canvas>_x000D_
_x000D_
<script>_x000D_
console.log("canvas")_x000D_
var ox=0,oy=0,px=0,py=0,scx=1,scy=1;_x000D_
var canvas = document.getElementById("myCanvas");_x000D_
canvas.onmousedown=(e)=>{px=e.x;py=e.y;canvas.onmousemove=(e)=>{ox-=(e.x-px);oy-=(e.y-py);px=e.x;py=e.y;} } _x000D_
_x000D_
canvas.onmouseup=()=>{canvas.onmousemove=null;}_x000D_
canvas.onwheel =(e)=>{let bfzx,bfzy,afzx,afzy;[bfzx,bfzy]=StoW(e.x,e.y);scx-=10*scx/e.deltaY;scy-=10*scy/e.deltaY;_x000D_
[afzx,afzy]=StoW(e.x,e.y);_x000D_
ox+=(bfzx-afzx);_x000D_
oy+=(bfzy-afzy);_x000D_
}_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
function draw(){_x000D_
window.requestAnimationFrame(draw);_x000D_
ctx.clearRect(0,0,canvas.width,canvas.height);_x000D_
for(let i=0;i<=100;i+=10){_x000D_
let sx=0,sy=i;_x000D_
let ex=100,ey=i;_x000D_
[sx,sy]=WtoS(sx,sy);_x000D_
[ex,ey]=WtoS(ex,ey);_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(sx, sy);_x000D_
ctx.lineTo(ex, ey);_x000D_
ctx.stroke();_x000D_
}_x000D_
for(let i=0;i<=100;i+=10){_x000D_
let sx=i,sy=0;_x000D_
let ex=i,ey=100;_x000D_
[sx,sy]=WtoS(sx,sy);_x000D_
[ex,ey]=WtoS(ex,ey);_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(sx, sy);_x000D_
ctx.lineTo(ex, ey);_x000D_
ctx.stroke();_x000D_
}_x000D_
}_x000D_
draw()_x000D_
function WtoS(wx,wy){_x000D_
let sx=(wx-ox)*scx;_x000D_
let sy=(wy-oy)*scy;_x000D_
return[sx,sy];_x000D_
}_x000D_
function StoW(sx,sy){_x000D_
let wx=sx/scx+ox;_x000D_
let wy=sy/scy+oy;_x000D_
return[wx,wy];_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

how to read certain columns from Excel using Pandas - Python

You can use column indices (letters) like this:

import pandas as pd
import numpy as np
file_loc = "path.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")
print(df)

[Corresponding documentation][1]:

usecolsint, str, list-like, or callable default None

  • If None, then parse all columns.
  • If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.
  • If list of int, then indicates list of column numbers to be parsed.
  • If list of string, then indicates list of column names to be parsed.

    New in version 0.24.0.

  • If callable, then evaluate each column name against it and parse the column if the callable returns True.

Returns a subset of the columns according to behavior above.

New in version 0.24.0.

Is it possible to disable the network in iOS Simulator?

If you have at least 2 wifi networks to connect is a very simple way is to use a bug in iOS simulator:

  1. quit from simulator (cmd-q) if it is open
  2. connect your Mac to one wifi (it may be not connected to internet, no matters)
  3. launch simulator (menu: xCode->Open Developer Tool->iOs Simulator) and wait while it is loaded
  4. switch wifi network to other one
  5. profit

The bug is that simulator tries to use a network (IP?) which is not connected already.

Until you relaunched simulator- it will have no internet (even if that first wifi network you connected had internet connection), so you can run (cmd-R) and stop (cmd-.) project(s) to use simulator without connection, but your Mac will be connected.

Then, if you'll need to run simulator connected- just quit and launch it.

How to make a div with a circular shape?

Use a border-radius property of 50%.

So for example:

.example-div {

    border-radius: 50%

}

What algorithms compute directions from point A to point B on a map?

I have worked on routing for a few years, with a recent burst of activity prompted by the needs of my clients, and I've found that A* is easily fast enough; there is really no need to look for optimisations or more complex algorithms. Routing over an enormous graph is not a problem.

But the speed depends on having the entire routing network, by which I mean the directed graph of arcs and nodes representing route segments and junctions respectively, in memory. The main time overhead is the time taken to create this network. Some rough figures based on an ordinary laptop running Windows, and routing over the whole of Spain: time taken to create the network: 10-15 seconds; time taken to calculate a route: too short to measure.

The other important thing is to be able to re-use the network for as many routing calculations as you like. If your algorithm has marked the nodes in some way to record the best route (total cost to current node, and best arc to it) - as it has to in A* - you have to reset or clear out this old information. Rather than going through hundreds of thousands of nodes, it's easier to use a generation number system. Mark each node with the generation number of its data; increment the generation number when you calculate a new route; any node with an older generation number is stale and its information can be ignored.

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyVersion

Where other assemblies that reference your assembly will look. If this number changes, other assemblies have to update their references to your assembly! Only update this version, if it breaks backward compatibility. The AssemblyVersion is required.

I use the format: major.minor. This would result in:

[assembly: AssemblyVersion("1.0")]

If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.

AssemblyFileVersion

Used for deployment. You can increase this number for every deployment. It is used by setup programs. Use it to mark assemblies that have the same AssemblyVersion, but are generated from different builds.

In Windows, it can be viewed in the file properties.

The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.

I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:

[assembly: AssemblyFileVersion("1.3.2.254")]

Be aware that System.Version names these parts as major.minor.build.revision!

AssemblyInformationalVersion

The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.

The AssemblyInformationalVersion is optional. If not given, the AssemblyFileVersion is used.

I use the format: major.minor[.patch] [revision as string]. This would result in:

[assembly: AssemblyInformationalVersion("1.0 RC1")]

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

Oracle date to string conversion

Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL

Array initialization in Perl

If I understand you, perhaps you don't need an array of zeroes; rather, you need a hash. The hash keys will be the values in the other array and the hash values will be the number of times the value exists in the other array:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my %tallies;
$tallies{$_} ++ for @other_array;

print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;    

Output:

0 => 3
1 => 1
2 => 2
3 => 3
4 => 1

To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples:

my @zeroes = (0) x 5;            # (0,0,0,0,0)

my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
                                 # This works because in scalar context
                                 # an array evaluates to its size.

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

In my case, when laravel generated the .env configuration file, laravel also generated two uncommented "DB_HOST" lines at line 11 and 12, delete the one that says "mysql" and uncomment (if yours it's commented) the other one (the one with the localhost ip 127.0.0.1) and it worked. (In my case).

Have a great day

Converting String to Int with Swift

//  To convert user input (i.e string) to int for calculation.I did this , and it works.


    let num:Int? = Int(firstTextField.text!);

    let sum:Int = num!-2

    print(sum);

Add floating point value to android resources/values

As described in this link http://droidista.blogspot.in/2012/04/adding-float-value-to-your-resources.html

Declare in dimen.xml

<item name="my_float_value" type="dimen" format="float">9.52</item>

Referencing from xml

@dimen/my_float_value

Referencing from java

TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();

Rails 4 - Strong Parameters - Nested Objects

If it is Rails 5, because of new hash notation: params.permit(:name, groundtruth: [:type, coordinates:[]]) will work fine.

Postgres integer arrays as parameters?

You can always use a properly formatted string. The trick is the formatting.

command.Parameters.Add("@array_parameter", string.Format("{{{0}}}", string.Join(",", array));

Note that if your array is an array of strings, then you'll need to use array.Select(value => string.Format("\"{0}\", value)) or the equivalent. I use this style for an array of an enumerated type in PostgreSQL, because there's no automatic conversion from the array.

In my case, my enumerated type has some values like 'value1', 'value2', 'value3', and my C# enumeration has matching values. In my case, the final SQL query ends up looking something like (E'{"value1","value2"}'), and this works.

Iterate through 2 dimensional array

These functions should work.

// First, cache your array dimensions so you don't have to
//  access them during each iteration of your for loops.
int rowLength = array.length,       // array width (# of columns)
    colLength = array[0].length;    // array height (# of rows)

//     This is your function:
// Prints array elements row by row
var rowString = "";
for(int x = 0; x < rowLength; x++){     // x is the column's index
    for(int y = 0; y < colLength; y++){ // y is the row's index
        rowString += array[x][y];
    } System.out.println(rowString)
}

//      This is the one you want:
// Prints array elements column by column
var colString = "";
for(int y = 0; y < colLength; y++){      // y is the row's index
    for(int x = 0; x < rowLength; x++){  // x is the column's index
        colString += array[x][y];
    } System.out.println(colString)
}

In the first block, the inner loop iterates over each item in the row before moving to the next column.

In the second block (the one you want), the inner loop iterates over all the columns before moving to the next row.

tl;dr: Essentially, the for() loops in both functions are switched. That's it.

I hope this helps you to understand the logic behind iterating over 2-dimensional arrays.

Also, this works whether you have a string[,] or string[][]

How to connect to SQL Server database from JavaScript in the browser?

Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};... connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN"; worked, so I carried on experimenting for my in-house testing and learning purposes.

Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \ as \\ :)
After some dead-ends with server=server1;instanceName=dev in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"

Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true v Integrated Security = SSPI v Trusted_Connection=Yes - see Difference between Integrated Security = True and Integrated Security = SSPI

Beware that RecordCount will come back as -1 if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3); (3=adOpenStatic) and this gives a valid rs.RecordCount

What's the u prefix in a Python string?

You're right, see 3.1.3. Unicode Strings.

It's been the syntax since Python 2.0.

Python 3 made them redundant, as the default string type is Unicode. Versions 3.0 through 3.2 removed them, but they were re-added in 3.3+ for compatibility with Python 2 to aide the 2 to 3 transition.

Excel: How to check if a cell is empty with VBA?

You could use IsEmpty() function like this:

...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...

you could also use following:

If ActiveCell.Value = vbNullString Then ...

React Native: How to select the next TextInput after pressing the "next" keyboard button?

Really annoying that RN doesn't have some sort of Tabindex system.

A functional component, for my use case, I have an array of string IDs for inputs which I iterate through and show one text input each. The following code will automatically jump the user through all of them, stopping the keyboard from disappearing/reappearing between fields and dismissing it at the end, also showing the appropriate "action" button on the keyboard.

Typescript, Native Base.

_x000D_
_x000D_
const stringFieldIDs = [
  'q1', 'q2', 'q3'
];

export default () => {
  const stringFieldRefs = stringFieldIDs.map(() => useRef < any > ());

  const basicStringField = (id: string, ind: number) => {
    const posInd = stringFieldIDs.indexOf(id);
    const isLast = posInd === stringFieldIDs.length - 1;

    return ( <
      Input blurOnSubmit = {
        isLast
      }
      ref = {
        stringFieldRefs[posInd]
      }
      returnKeyType = {
        isLast ? 'done' : 'next'
      }
      onSubmitEditing = {
        isLast ?
        undefined :
          () => stringFieldRefs[posInd + 1].current._root.focus()
      }
      />
    );
  };

  return stringFieldIDs.map(basicStringField);
};
_x000D_
_x000D_
_x000D_

How to change the URI (URL) for a remote Git repository?

  1. remove origin using command on gitbash git remote rm origin
  2. And now add new Origin using gitbash git remote add origin (Copy HTTP URL from your project repository in bit bucket) done

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

Open popup and refresh parent page on close popup

In my case I opened a pop up window on click on linkbutton in parent page. To refresh parent on closing child using

window.opener.location.reload();

in child window caused re open the child window (Might be because of View State I guess. Correct me If I m wrong). So I decided not to reload page in parent and load the the page again assigning same url to it.

To avoid popup opening again after closing pop up window this might help,

window.onunload = function(){
    window.opener.location = window.opener.location;};

Arduino Tools > Serial Port greyed out

So I did with sudo usermod -a -G dialout <my-username>.

You need to log out after you add yourself to a group so those changes are applied. Just log out and log in again and the menu should be available.

What's the difference between deadlock and livelock?

Livelock

A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result.

As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work. This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphonse moves to his right, while Gaston moves to his left. They're still blocking each other, and so on...

The main difference between livelock and deadlock is that threads are not going to be blocked, instead they will try to respond to each other continuously.

In this image, both circles (threads or processes) will try to give space to the other by moving left and right. But they can't move any further.

enter image description here

Perl: Use s/ (replace) and return new string

print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;

Best PHP IDE for Mac? (Preferably free!)

PDT eclipse from ZEND has a mac version (PDT all-in-one).

I've been using it for about 3 months and it's pretty solid and has debugging capabilities with xdebug (debug howto) and zend debugger.

Python Create unix timestamp five minutes in the future

def expiration_time():
    import datetime,calendar
    timestamp = calendar.timegm(datetime.datetime.now().timetuple())
    returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
    return returnValue

How to get 30 days prior to current date?

I use date.js. It handles this easily and takes care of all the leap-year nastiness.

JSON to PHP Array using file_get_contents

You JSON is not a valid string as P. Galbraith has told you above.

and here is the solution for it.

<?php 
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "<pre>";
print_r($data);
echo "</pre>";
?>

Use this code it will work for you.

Check if a string contains another string

You wouldn't really want to do this given the existing Instr/InstrRev functions but there are times when it is handy to use EVALUATE to return the result of Excel worksheet functions within VBA

Option Explicit

Public Sub test()

    Debug.Print ContainsSubString("bc", "abc,d")

End Sub
Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'substring = string to test for; testString = string to search
    ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")

End Function

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

Well that is Because of

you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.

look this. Try and u will be able to resolve this

public static String decrypt(String encryptedData) throws Exception {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
    System.out.println("This is Data to be Decrypted" + decordedValue);
    return decordedValue;
}

hope that will help.

How can I trigger an onchange event manually?

MDN suggests that there's a much cleaner way of doing this in modern browsers:

// Assuming we're listening for e.g. a 'change' event on `element`

// Create a new 'change' event
var event = new Event('change');

// Dispatch it.
element.dispatchEvent(event);

Check if a temporary table exists and delete if it exists before creating a temporary table

When you change a column in a temp table, you must drop the table before running the query again. (Yes, it is annoying. Just what you have to do.)

I have always assumed this is because the "invalid column" check is done by parser before the query is run, so it is based on the columns in the table before it is dropped..... and that is what pnbs also said.

How do I update the password for Git?

There is such a confusion on this question, as there is way too much complexity in this question. First MacOS vs. Win10. Then the different auth mechanisms.

I will start a consolidated answer here and probably need some help, if I do not get help, I will keep working on the answer until it is complete, but that will take time.

Windows 10: |

|-- Run this command. You will be prompted on next push/pull to enter username and password:
|      git config --global credential.helper wincred (Thanks to @Andrew Pye)

` MacOS:

|
|-- Using git config to store username and password:
|  git config --global --add user.password
|
|---- first time entry
|  git config --global --add user.password <new_pass>
|
|---- password update
|  git config --global --unset user.password
|  git config --global --add user.password <new_pass>
|
|-- Using keychain:
|  git config --global credential.helper osxkeychain
|
|---- first time entry
|  Terminal will ask you for the username and password. Just enter it, it will be 
|  stored in keychain from then on.
|
|---- password update
|  Open keychain, delete the entry for the repository you are trying to use. 
|  (git remote -v will show you)
|  On next use of git push or something that needs permissions, git will ask for 
|  the credentials, as it can not find them in the keychain anymore.
`

Python coding standards/best practices

I follow it extremely rigorously. The only god before PEP-8 is existing code bases.

Get resultset from oracle stored procedure

FYI as of Oracle 12c, you can do this:

CREATE OR REPLACE PROCEDURE testproc(n number)
AS
  cur SYS_REFCURSOR;
BEGIN
    OPEN cur FOR SELECT object_id,object_name from all_objects where rownum < n;
    DBMS_SQL.RETURN_RESULT(cur);
END;
/

EXEC testproc(3);

OBJECT_ID OBJECT_NAME                                                                                                                     
---------- ------------
100 ORA$BASE                                                                                                                        
116 DUAL                                                                                                                            

This was supposed to get closer to other databases, and ease migrations. But it's not perfect to me, for instance SQL developer won't display it nicely as a normal SELECT.

I prefer the output of pipeline functions, but they need more boilerplate to code.

more info: https://oracle-base.com/articles/12c/implicit-statement-results-12cr1

how to parse json using groovy

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link

What is an HttpHandler in ASP.NET

An HttpHandler (or IHttpHandler) is basically anything that is responsible for serving content. An ASP.NET page (aspx) is a type of handler.

You might write your own, for example, to serve images etc from a database rather than from the web-server itself, or to write a simple POX service (rather than SOAP/WCF/etc)

Bootstrap button drop-down inside responsive table not visible because of scroll

I'd took a different approach, I had detached the element from the parent and set it with position absolute by jQuery

Working JS fidle: http://jsfiddle.net/s270Lyrd/

enter image description here

The JS solution I am using.

//fix menu overflow under the responsive table 
// hide menu on click... (This is a must because when we open a menu )
$(document).click(function (event) {
    //hide all our dropdowns
    $('.dropdown-menu[data-parent]').hide();

});
$(document).on('click', '.table-responsive [data-toggle="dropdown"]', function () {
    // if the button is inside a modal
    if ($('body').hasClass('modal-open')) {
        throw new Error("This solution is not working inside a responsive table inside a modal, you need to find out a way to calculate the modal Z-index and add it to the element")
        return true;
    }

    $buttonGroup = $(this).parent();
    if (!$buttonGroup.attr('data-attachedUl')) {
        var ts = +new Date;
        $ul = $(this).siblings('ul');
        $ul.attr('data-parent', ts);
        $buttonGroup.attr('data-attachedUl', ts);
        $(window).resize(function () {
            $ul.css('display', 'none').data('top');
        });
    } else {
        $ul = $('[data-parent=' + $buttonGroup.attr('data-attachedUl') + ']');
    }
    if (!$buttonGroup.hasClass('open')) {
        $ul.css('display', 'none');
        return;
    }
    dropDownFixPosition($(this).parent(), $ul);
    function dropDownFixPosition(button, dropdown) {
        var dropDownTop = button.offset().top + button.outerHeight();
        dropdown.css('top', dropDownTop + "px");
        dropdown.css('left', button.offset().left + "px");
        dropdown.css('position', "absolute");

        dropdown.css('width', dropdown.width());
        dropdown.css('heigt', dropdown.height());
        dropdown.css('display', 'block');
        dropdown.appendTo('body');
    }
});

How to give a pattern for new line in grep?

You can use this way...

grep -P '^\s$' file
  • -P is used for Perl regular expressions (an extension to POSIX grep).
  • \s match the white space characters; if followed by *, it matches an empty line also.
  • ^ matches the beginning of the line. $ matches the end of the line.

How do I get a UTC Timestamp in JavaScript?

I am amazed at how complex this question has become.

These are all identical, and their integer values all === EPOCH time :D

console.log((new Date()).getTime() / 1000, new Date().valueOf() / 1000, (new Date() - new Date().getTimezoneOffset() * 60 * 1000) / 1000);

Do not believe me, checkout: http://www.epochconverter.com/

In javascript, how do you search an array for a substring match

I've created a simple to use library (ss-search) which is designed to handle objects, but could also work in your case:

search(windowArray.map(x => ({ key: x }), ["key"], "SEARCH_TEXT").map(x => x.key)

The advantage of using this search function is that it will normalize the text before executing the search to return more accurate results.

smtp configuration for php mail

But now it is not working and I contacted our hosting team then they told me to use smtp

Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.

Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.

Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).

C.

Why can't C# interfaces contain fields?

The short answer is yes, every implementing type will have to create its own backing variable. This is because an interface is analogous to a contract. All it can do is specify particular publicly accessible pieces of code that an implementing type must make available; it cannot contain any code itself.

Consider this scenario using what you suggest:

public interface InterfaceOne
{
    int myBackingVariable;

    int MyProperty { get { return myBackingVariable; } }
}

public interface InterfaceTwo
{
    int myBackingVariable;

    int MyProperty { get { return myBackingVariable; } }
}

public class MyClass : InterfaceOne, InterfaceTwo { }

We have a couple of problems here:

  • Because all members of an interface are--by definition--public, our backing variable is now exposed to anyone using the interface
  • Which myBackingVariable will MyClass use?

The most common approach taken is to declare the interface and a barebones abstract class that implements it. This allows you the flexibility of either inheriting from the abstract class and getting the implementation for free, or explicitly implementing the interface and being allowed to inherit from another class. It works something like this:

public interface IMyInterface
{
    int MyProperty { get; set; }
}

public abstract class MyInterfaceBase : IMyInterface
{
    int myProperty;

    public int MyProperty
    {
        get { return myProperty; }
        set { myProperty = value; }
    }
}

'JSON' is undefined error in JavaScript in Internet Explorer

<!DOCTYPE html>

Otherwise IE8 is not acting right. Also you should use:

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

How to display pandas DataFrame of floats using a format string for columns?

If you do not want to change the display format permanently, and perhaps apply a new format later on, I personally favour the use of a resource manager (the with statement in Python). In your case you could do something like this:

with pd.option_context('display.float_format', '${:0.2f}'.format):
   print(df)

If you happen to need a different format further down in your code, you can change it by varying just the format in the snippet above.

A keyboard shortcut to comment/uncomment the select text in Android Studio

if you are findind keyboard shortcuts for Fix doc comment like this:

/**
 * ...
 */

you can do it by useing Live Template(setting - editor - Live Templates - add)

/**
 * $comment$
 */

Uncaught TypeError: Cannot set property 'value' of null

I knew that i am too late for this answer, but i hope this will help to other who are facing and who will face.

As you have written h_url is global var like var = h_url; so you can use that variable anywhere in your file.

  • h_url=document.getElementById("u").value; Here h_url contain value of your search box text value whatever user has typed.

  • document.getElementById("u"); This is the identifier of your form field with some specific ID.

  • Your Search Field without id

    <input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />

  • Alter Search Field with id

    <input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />

  • When you click on submit that will try to fetch value from document.getElementById("u").value; which is syntactically right but you haven't define id so that will return null.

  • So, Just make sure while you use form fields first define that ID and do other task letter.

I hope this helps you and never get Cannot set property 'value' of null Error.

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

PHP function ssh2_connect is not working

I have solved this on ubuntu 16.4 PHP 7.0.27-0+deb9u and nginx

sudo apt install php-ssh2 

How to read one single line of csv data in Python?

The simple way to get any row in csv file

import csv
csvfile = open('some.csv','rb')
csvFileArray = []
for row in csv.reader(csvfile, delimiter = '.'):
    csvFileArray.append(row)
print(csvFileArray[0])

How to scroll to an element in jQuery?

If you're simply trying to scroll to the specified element, you can use the scrollIntoView method of the Element. Here's an example :

$target.get(0).scrollIntoView();

How to get absolute value from double - c-language

Use fabs() (in math.h) to get absolute-value for double:

double d1 = fabs(-3.8951);

Authenticated HTTP proxy with Java

You're almost there, you just have to append:

-Dhttp.proxyUser=someUserName
-Dhttp.proxyPassword=somePassword

Matplotlib-Animation "No MovieWriters Available"

For fellow googlers using Anaconda, install the ffmpeg package:

conda install -c conda-forge ffmpeg

This works on Windows too.

(Original answer used menpo package owner but as mentioned by @harsh their version is a little behind at time of writing)

Using Position Relative/Absolute within a TD?

Contents of table cell, variable height, could be more than 60px;

<div style="position: absolute; bottom: 0px;">
    Notice
</div>

Multiple inputs with same name through POST in php

For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.

The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval] (string or int) which then allows you to refer to an existing record.

How does numpy.histogram() work?

Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()

enter image description here

This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.

How to adjust text font size to fit textview

I wrote a short helper class that makes a textview fit within a certain width and adds ellipsize "..." at the end if the minimum textsize cannot be achieved.

Keep in mind that it only makes the text smaller until it fits or until the minimum text size is reached. To test with large sizes, set the textsize to a large number before calling the help method.

It takes Pixels, so if you are using values from dimen, you can call it like this:


float minTextSizePx = getResources().getDimensionPixelSize(R.dimen.min_text_size);
float maxTextWidthPx = getResources().getDimensionPixelSize(R.dimen.max_text_width);
WidgetUtils.fitText(textView, text, minTextSizePx, maxTextWidthPx);

This is the class I use:


public class WidgetUtils {

    public static void fitText(TextView textView, String text, float minTextSizePx, float maxWidthPx) {
        textView.setEllipsize(null);
        int size = (int)textView.getTextSize();
        while (true) {
            Rect bounds = new Rect();
            Paint textPaint = textView.getPaint();
            textPaint.getTextBounds(text, 0, text.length(), bounds);
            if(bounds.width() < maxWidthPx){
                break;
            }
            if (size <= minTextSizePx) {
                textView.setEllipsize(TextUtils.TruncateAt.END);
                break;
            }
            size -= 1;
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
        }
    }
}

How to erase the file contents of text file in Python?

You cannot "erase" from a file in-place unless you need to erase the end. Either be content with an overwrite of an "empty" value, or read the parts of the file you care about and write it to another file.

Hibernate Union alternatives

I too have been through this pain - if the query is dynamically generated (e.g. Hibernate Criteria) then I couldn't find a practical way to do it.

The good news for me was that I was only investigating union to solve a performance problem when using an 'or' in an Oracle database.

The solution Patrick posted (combining the results programmatically using a set) while ugly (especially since I wanted to do results paging as well) was adequate for me.

React: "this" is undefined inside a component function

in my case this was the solution = () => {}

methodName = (params) => {
//your code here with this.something
}

How to display a gif fullscreen for a webpage background?

if you're happy using it as a background image and CSS3 then background-size: cover; would do the trick

Django model "doesn't declare an explicit app_label"

I get the same error and I don´t know how to figure out this problem. It took me many hours to notice that I have a init.py at the same direcory as the manage.py from django.

Before:

|-- myproject
  |-- __init__.py
  |-- manage.py
  |-- myproject
    |-- ...
  |-- app1
    |-- models.py
  |-- app2
    |-- models.py

After:

|-- myproject
  |-- manage.py
  |-- myproject
    |-- ...
  |-- app1
    |-- models.py
  |-- app2
    |-- models.py

It is quite confused that you get this "doesn't declare an explicit app_label" error. But deleting this init file solved my problem.

Embedding JavaScript engine into .NET

I know I'm opening up an old thread but I've done a lot of work on smnet (spidermonkey-dotnet). In the recent years. It's main development focus has been seamless embedding of .net objects into the spidermonkey engine. It supports a wide variety of conversions from js values to .net objects. Some of those including delegates and events.

Just saying it might be worth checking into now that there's some steady development on it :). I do keep the SVN repo up to date with bug fixes and new features. The source and project solution files are configured to successfully build on download. If there are any problems using it, feel free to open a discussion.

I do understand the desire to have a managed javascript solution, but of all the managed javascript's I've used they're all very lacking in some key features that help make them both robust and easy to work with. I myself am waiting on IronJS to mature a little. While I wait, I have fun playing with spidermonkey-dotnet =)

spidermonkey-dotnet project and download page

Edit: created documentation wiki page this afternoon.

How can I scale the content of an iframe?

Kip's solution should work on Opera and Safari if you change the CSS to:

<style>
    #wrap { width: 600px; height: 390px; padding: 0; overflow: hidden; }
    #frame { width: 800px; height: 520px; border: 1px solid black; }
    #frame {
        -ms-zoom: 0.75;
        -moz-transform: scale(0.75);
        -moz-transform-origin: 0 0;
        -o-transform: scale(0.75);
        -o-transform-origin: 0 0;
        -webkit-transform: scale(0.75);
        -webkit-transform-origin: 0 0;
    }
</style>

You might also want to specify overflow: hidden on #frame to prevent scrollbars.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

It if helps someone, ours was an issue with missing certificate. Environment is Windows Server 2016 Standard with .Net 4.6.

There is a self hosted WCF service https URI, for which Service.Open() would execute without errors. Another thread would keep accessing https://OurIp:443/OurService?wsdl to ensure that the service was available. Accessing the WSDL used to fail with:

The underlying connection was closed: An unexpected error occurred on a send.

Using ServicePointManager.SecurityProtocol with applicable settings did not work. Playing with server roles and features did not help either. Then stepped in Jaise George, the SE, resolving the issue in a couple of minutes. Jaise installed a self signed certificate in the IIS, poofing the issue. This is what he did to address the issue:

(1) Open IIS manager (inetmgr) (2) Click on the server node in the left panel, and double click "Server certificates". (3) Click on "Create Self-Signed Certificate" on the right panel and type in anything you want for the friendly name. (4) Click on “Default Web site” in the left panel, click "Bindings" on the right panel, click "Add", select "https", select the certificate you just created, and click "OK" (5) Access the https URL, it should be accessible.

How can I add a Google search box to my website?

No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!

<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>

_x000D_
_x000D_
    function search() {_x000D_
    var Blah = document.getElementById("Blah").value;_x000D_
    location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
    }
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
_x000D_
_x000D_

Get UTC time in seconds

I bet this is what was intended as a result.

$ date -u --date=@1404372514
Thu Jul  3 07:28:34 UTC 2014

keycode and charcode

It is a conditional statement.

If browser supprts e.keyCode then take e.keyCode else e.charCode.

It is similar to

var code = event.keyCode || event.charCode

event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.

event.charCode: Returns the Unicode value of a character key pressed during a keypress event.

How to remove decimal part from a number in C#

Well 12 and 12.00 have exactly the same representation as double values. Are you trying to end up with a double or something else? (For example, you could cast to int, if you were convinced the value would be in the right range, and if the truncation effect is what you want.)

You might want to look at these methods too:

How to reload the current state?

I found this to be the shortest working way to refresh with ui-router:

$state.go($state.current, {}, {reload: true}); //second parameter is for $stateParams

Update for newer versions:

$state.reload();

Which is an alias for:

$state.transitionTo($state.current, $stateParams, { 
  reload: true, inherit: false, notify: true
});

Documentation: https://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state#methods_reload

byte[] to file in Java

You can try Cactoos:

new LengthOf(new TeeInput(array, new File("a.txt"))).value();

More details: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html

Background image jumps when address bar hides iOS/Android/Mobile Chrome

For those who would like to listen to the actual inner height and vertical scroll of the window while the Chrome mobile browser is transition the URL bar from shown to hidden and vice versa, the only solution that I found is to set an interval function, and measure the discrepancy of the window.innerHeight with its previous value.

This introduces this code:

_x000D_
_x000D_
var innerHeight = window.innerHeight;_x000D_
window.setInterval(function ()_x000D_
{_x000D_
  var newInnerHeight = window.innerHeight;_x000D_
  if (newInnerHeight !== innerHeight)_x000D_
  {_x000D_
    var newScrollY = window.scrollY + newInnerHeight - innerHeight;_x000D_
    // ... do whatever you want with this new scrollY_x000D_
    innerHeight = newInnerHeight;_x000D_
  }_x000D_
}, 1000 / 60);
_x000D_
_x000D_
_x000D_

I hope that this will be handy. Does anyone knows a better solution?

How to use hex color values

Swift 2.0:

Make an extension of UIColor.

extension UIColor {
    convenience init(hexString:String) {
        let hexString:NSString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        let scanner            = NSScanner(string: hexString as String)
        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }

        var color:UInt32 = 0
        scanner.scanHexInt(&color)

        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask

        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:1)
    }

    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
        return NSString(format:"#%06x", rgb) as String
    }

}

Usage:

//Hex to Color
    let countPartColor =  UIColor(hexString: "E43038")

//Color to Hex
let colorHexString =  UIColor(red: 228, green: 48, blue: 56, alpha: 1.0).toHexString()

Calculating the area under a curve given a set of coordinates, without knowing the function

You can use Simpsons rule or the Trapezium rule to calculate the area under a graph given a table of y-values at a regular interval.

Python script that calculates Simpsons rule:

def integrate(y_vals, h):
    i = 1
    total = y_vals[0] + y_vals[-1]
    for y in y_vals[1:-1]:
        if i % 2 == 0:
            total += 2 * y
        else:
            total += 4 * y
        i += 1
    return total * (h / 3.0)

h is the offset (or gap) between y values, and y_vals is an array of well, y values.

Example (In same file as above function):

y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)

'Property does not exist on type 'never'

This seems to be similar to this issue: False "Property does not exist on type 'never'" when changing value inside callback with strictNullChecks, which is closed as a duplicate of this issue (discussion): Trade-offs in Control Flow Analysis.

That discussion is pretty long, if you can't find a good solution there you can try this:

if (instance == null) {
    console.log('Instance is null or undefined');
} else {
    console.log(instance!.name); // ok now
}

Failed to locate the winutils binary in the hadoop binary path

The statement java.io.IOException: Could not locate executable null\bin\winutils.exe

explains that the null is received when expanding or replacing an Environment Variable. If you see the Source in Shell.Java in Common Package you will find that HADOOP_HOME variable is not getting set and you are receiving null in place of that and hence the error.

So, HADOOP_HOME needs to be set for this properly or the variable hadoop.home.dir property.

Hope this helps.

Thanks, Kamleshwar.

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

This also happens to me when an UI label or other UI element is referenced by two variables in the view controller class and I delete one of the variable.

jquery getting post action url

Try this ocde;;

var formAction = $("#signup").attr('action');

Working with Enums in android

Android's preferred approach is int constants enforced with @IntDef:

public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;

@Retention(RetentionPolicy.SOURCE)
@IntDef ({GENDER_MALE, GENDER_FEMALE})
public @interface Gender{}

// Example usage...
void exampleFunc(@Gender int gender) {
  switch(gender) {
  case GENDER_MALE:

     break;
  case GENDER_FEMALE:
     // TODO
     break;
  }
}

Docs: https://developer.android.com/studio/write/annotations.html#enum-annotations

Check if element exists in jQuery

your elemId as its name suggests, is an Id attribute, these are all you can do to check if it exists:

Vanilla JavaScript: in case you have more advanced selectors:

//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}

if(document.querySelector("#elemId")){}

//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}

jQuery:

if(jQuery("#elemId").length){}

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

[A1].End(xlUp)
[A1].End(xlDown)
[A1].End(xlToLeft)
[A1].End(xlToRight)

is the VBA equivalent of being in Cell A1 and pressing Ctrl + Any arrow key. It will continue to travel in that direction until it hits the last cell of data, or if you use this command to move from a cell that is the last cell of data it will travel until it hits the next cell containing data.

If you wanted to find that last "used" cell in Column A, you could go to A65536 (for example, in an XL93-97 workbook) and press Ctrl + Up to "snap" to the last used cell. Or in VBA you would write:

Range("A65536").End(xlUp) which again can be re-written as Range("A" & Rows.Count).End(xlUp) for compatibility reasons across workbooks with different numbers of rows.

How/when to use ng-click to call a route?

Here's a great tip that nobody mentioned. In the controller that the function is within, you need to include the location provider:

app.controller('SlideController', ['$scope', '$location',function($scope, $location){ 
$scope.goNext = function (hash) { 
$location.path(hash);
 }

;]);

 <!--the code to call it from within the partial:---> <div ng-click='goNext("/page2")'>next page</div>

What is the difference between char array and char pointer in C?

From APUE, Section 5.14 :

char    good_template[] = "/tmp/dirXXXXXX"; /* right way */
char    *bad_template = "/tmp/dirXXXXXX";   /* wrong way*/

... For the first template, the name is allocated on the stack, because we use an array variable. For the second name, however, we use a pointer. In this case, only the memory for the pointer itself resides on the stack; the compiler arranges for the string to be stored in the read-only segment of the executable. When the mkstemp function tries to modify the string, a segmentation fault occurs.

The quoted text matches @Ciro Santilli 's explanation.

How to Replace dot (.) in a string in Java

Use Apache Commons Lang:

String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);

or with standalone JDK:

String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);

How to force Selenium WebDriver to click on element which is not currently visible?

I just solve this error while using capybara in ror project by adding:

Capybara.ignore_elements = true

to features/support/env.rb.

From an array of objects, extract value of a property as array

Yes, but it relies on an ES5 feature of JavaScript. This means it will not work in IE8 or older.

var result = objArray.map(function(a) {return a.foo;});

On ES6 compatible JS interpreters you can use an arrow function for brevity:

var result = objArray.map(a => a.foo);

Array.prototype.map documentation

Simple bubble sort c#

int[] array = new int[10] { 13, 2, 5, 8, 23, 90, 41, 4, 77, 61 };

for (int i = 10; i > 0; i--)
{
    for (int j = 0; j < 9; j++)
    {
        if (array[j] > array[j + 1])
        {
            int temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
}

How to 'insert if not exists' in MySQL?

Any simple constraint should do the job, if an exception is acceptable. Examples :

  • primary key if not surrogate
  • unique constraint on a column
  • multi-column unique constraint

Sorry is this seems deceptively simple. I know it looks bad confronted to the link you share with us. ;-(

But I neverleless give this answer, because it seem to fill your need. (If not, it may trigger your updating your requirements, which would be "a Good Thing"(TM) also).

Edited: If an insert would break the database unique constraint, an exception is throw at the database level, relayed by the driver. It will certainly stop your script, with a failure. It must be possible in PHP to adress that case ...

mysql SELECT IF statement with OR

Presumably this would work:

IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment

Execute PowerShell Script from C# with Commandline Arguments

I have another solution. I just want to test if executing a PowerShell script succeeds, because perhaps somebody might change the policy. As the argument, I just specify the path of the script to be executed.

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();

string output = process.StandardOutput.ReadToEnd();
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));

string errors = process.StandardError.ReadToEnd();
Assert.IsTrue(string.IsNullOrEmpty(errors));

With the contents of the script being:

$someVariable = "StringToBeVerifiedInAUnitTest"
$someVariable

Capturing TAB key in text box

Even if you capture the keydown/keyup event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.

In Firefox you can call the preventDefault() method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a preventDefault method on its event object that works in IE and FF.

<body>
<input type="text" id="myInput">
<script type="text/javascript">
    var myInput = document.getElementById("myInput");
    if(myInput.addEventListener ) {
        myInput.addEventListener('keydown',this.keyHandler,false);
    } else if(myInput.attachEvent ) {
        myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
    }

    function keyHandler(e) {
        var TABKEY = 9;
        if(e.keyCode == TABKEY) {
            this.value += "    ";
            if(e.preventDefault) {
                e.preventDefault();
            }
            return false;
        }
    }
</script>
</body>

Firebase TIMESTAMP to date and Time

In fact, it only work to me when used

firebase.database.ServerValue.TIMESTAMP

With one 'database' more on namespace.

How to get just the responsive grid from Bootstrap 3?

Go to http://getbootstrap.com/customize/ and toggle just what you want from the BS3 framework and then click "Compile and Download" and you'll get the CSS and JS that you chose.

Bootstrap Customizer

Open up the CSS and remove all but the grid. They include some normalize stuff too. And you'll need to adjust all the styles on your site to box-sizing: border-box - http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

With block equivalent in C#?

Most simple syntax would be:

{
    var where = new MyObject();
    where.property = "xxx";
    where.SomeFunction("yyy");
}

{
    var where = new MyObject();
    where.property = "zzz";
    where.SomeFunction("uuu");
}

Actually extra code-blocks like that are very handy if you want to re-use variable names.

Code formatting shortcuts in Android Studio for Operation Systems

Check Keyboard Commands given in the Android Studio Tips & Trick documentation:

Enter image description here

What's the purpose of the LEA instruction?

The LEA (Load Effective Address) instruction is a way of obtaining the address which arises from any of the Intel processor's memory addressing modes.

That is to say, if we have a data move like this:

MOV EAX, <MEM-OPERAND>

it moves the contents of the designated memory location into the target register.

If we replace the MOV by LEA, then the address of the memory location is calculated in exactly the same way by the <MEM-OPERAND> addressing expression. But instead of the contents of the memory location, we get the location itself into the destination.

LEA is not a specific arithmetic instruction; it is a way of intercepting the effective address arising from any one of the processor's memory addressing modes.

For instance, we can use LEA on just a simple direct address. No arithmetic is involved at all:

MOV EAX, GLOBALVAR   ; fetch the value of GLOBALVAR into EAX
LEA EAX, GLOBALVAR   ; fetch the address of GLOBALVAR into EAX.

This is valid; we can test it at the Linux prompt:

$ as
LEA 0, %eax
$ objdump -d a.out

a.out:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <.text>:
   0:   8d 04 25 00 00 00 00    lea    0x0,%eax

Here, there is no addition of a scaled value, and no offset. Zero is moved into EAX. We could do that using MOV with an immediate operand also.

This is the reason why people who think that the brackets in LEA are superfluous are severely mistaken; the brackets are not LEA syntax but are part of the addressing mode.

LEA is real at the hardware level. The generated instruction encodes the actual addressing mode and the processor carries it out to the point of calculating the address. Then it moves that address to the destination instead of generating a memory reference. (Since the address calculation of an addressing mode in any other instruction has no effect on CPU flags, LEA has no effect on CPU flags.)

Contrast with loading the value from address zero:

$ as
movl 0, %eax
$ objdump -d a.out | grep mov
   0:   8b 04 25 00 00 00 00    mov    0x0,%eax

It's a very similar encoding, see? Just the 8d of LEA has changed to 8b.

Of course, this LEA encoding is longer than moving an immediate zero into EAX:

$ as
movl $0, %eax
$ objdump -d a.out | grep mov
   0:   b8 00 00 00 00          mov    $0x0,%eax

There is no reason for LEA to exclude this possibility though just because there is a shorter alternative; it's just combining in an orthogonal way with the available addressing modes.

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

If you use an actuall version there is a "setup_xampp.bat/.sh" script in the root directory. The path has to be absolute but the script changes all needed paths to your current location.

Fatal error: unexpectedly found nil while unwrapping an Optional values

I was having the same issue and the reason for it was because I was trying to load a UIImage with the wrong name. Double-check .setImage(UIImage(named: "-name-" calls and make sure the name is correct.

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You need to start your Apache Server normally you should have an xampp icon in the info-section from the taskbar, with this tool you can start the apache server as wel as the mysql database (if you need it)

Spring Boot - Cannot determine embedded database driver class for database type NONE

I faced this exception while I was doing APIs for ElasticSearch using Spring Data. I did the following and it worked.

@SpringDataApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

Heatmap in matplotlib with pcolor?

The python seaborn module is based on matplotlib, and produces a very nice heatmap.

Below is an implementation with seaborn, designed for the ipython/jupyter notebook.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# import the data directly into a pandas dataframe
nba = pd.read_csv("http://datasets.flowingdata.com/ppg2008.csv", index_col='Name  ')
# remove index title
nba.index.name = ""
# normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# relabel columns
labels = ['Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 
          'Free throws attempts', 'Free throws percentage','Three-pointers made', 'Three-point attempt', 'Three-point percentage', 
          'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
nba_norm.columns = labels
# set appropriate font and dpi
sns.set(font_scale=1.2)
sns.set_style({"savefig.dpi": 100})
# plot it out
ax = sns.heatmap(nba_norm, cmap=plt.cm.Blues, linewidths=.1)
# set the x-axis labels on the top
ax.xaxis.tick_top()
# rotate the x-axis labels
plt.xticks(rotation=90)
# get figure (usually obtained via "fig,ax=plt.subplots()" with matplotlib)
fig = ax.get_figure()
# specify dimensions and save
fig.set_size_inches(15, 20)
fig.savefig("nba.png")

The output looks like this: seaborn nba heatmap I used the matplotlib Blues color map, but personally find the default colors quite beautiful. I used matplotlib to rotate the x-axis labels, as I couldn't find the seaborn syntax. As noted by grexor, it was necessary to specify the dimensions (fig.set_size_inches) by trial and error, which I found a bit frustrating.

As noted by Paul H, you can easily add the values to heat maps (annot=True), but in this case I didn't think it improved the figure. Several code snippets were taken from the excellent answer by joelotz.

Location of the android sdk has not been setup in the preferences in mac os?

i was facing the same problem. the solution is...Copy the link http://dl-ssl.google.com/android/eclipse/ then in eclipse go to

Help > Install New Software > Add(work with) > past the link on locations > ok > select all > next

this will solve your problem.

ImportError: No module named six

on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve

ImportError: No module named six

when launching Wammu

If it's occurred for python3 program, six come with

pip3 install six

and if you don't have pip3:

apt install python3-pip

with sudo under Ubuntu!

Using multiprocessing.Process with a maximum number of simultaneous processes

I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # simulate a time-consuming task by sleeping
    time.sleep(5)
    # `release` will add 1 to `sema`, allowing other 
    # processes blocked on it to continue
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        # once 20 processes are running, the following `acquire` call
        # will block the main process since `sema` has been reduced
        # to 0. This loop will continue only after one or more 
        # previously created processes complete.
        sema.acquire()
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The following code is more structured since it acquires and releases sema in the same function. However, it will consume too much resources if total_task_num is very large:

from multiprocessing import Process
from multiprocessing import Semaphore
import time

def f(name, sema):
    print('process {} starting doing business'.format(name))
    # `sema` is acquired and released in the same
    # block of code here, making code more readable,
    # but may lead to problem.
    sema.acquire()
    time.sleep(5)
    sema.release()

if __name__ == '__main__':
    concurrency = 20
    total_task_num = 1000
    sema = Semaphore(concurrency)
    all_processes = []
    for i in range(total_task_num):
        p = Process(target=f, args=(i, sema))
        all_processes.append(p)
        # the following line won't block after 20 processes
        # have been created and running, instead it will carry 
        # on until all 1000 processes are created.
        p.start()

    # inside main process, wait for all processes to finish
    for p in all_processes:
        p.join()

The above code will create total_task_num processes but only concurrency processes will be running while other processes are blocked, consuming precious system resources.

What does the ^ (XOR) operator do?

One thing that other answers don't mention here is XOR with negative numbers -

 a  |  b  | a ^ b
----|-----|------
 0  |  0  |  0
 0  |  1  |  1
 1  |  0  |  1
 1  |  1  |  0

While you could easily understand how XOR will work using the above functional table, it doesn't tell how it will work on negative numbers.


How XOR works with Negative Numbers :

Since this question is also tagged as python, I will be answering it with that in mind. The XOR ( ^ ) is an logical operator that will return 1 when the bits are different and 0 elsewhere.

A negative number is stored in binary as two's complement. In 2's complement, The leftmost bit position is reserved for the sign of the value (positive or negative) and doesn't contribute towards the value of number.

In, Python, negative numbers are written with a leading one instead of a leading zero. So if you are using only 8 bits for your two's-complement numbers, then you treat patterns from 00000000 to 01111111 as the whole numbers from 0 to 127, and reserve 1xxxxxxx for writing negative numbers.

With that in mind, lets understand how XOR works on negative number with an example. Lets consider the expression - ( -5 ^ -3 ) .

  • The binary representation of -5 can be considered as 1000...101 and
  • Binary representation of -3 can be considered as 1000...011.

Here, ... denotes all 0s, the number of which depends on bits used for representation (32-bit, 64-bit, etc). The 1 at the MSB ( Most Significant Bit ) denotes that the number represented by the binary representation is negative. The XOR operation will be done on all bits as usual.

XOR Operation :

      -5   :  10000101          |
     ^                          | 
      -3   :  10000011          |  
    ===================         |
    Result :  00000110  =  6    |
________________________________|


     ? -5 ^ -3 = 6

Since, the MSB becomes 0 after the XOR operation, so the resultant number we get is a positive number. Similarly, for all negative numbers, we consider their representation in binary format using 2's complement (one of most commonly used) and do simple XOR on their binary representation.

The MSB bit of result will denote the sign and the rest of the bits will denote the value of the final result.

The following table could be useful in determining the sign of result.

  a   |   b   | a ^ b
------|-------|------
  +   |   +   |   +
  +   |   -   |   -
  -   |   +   |   -
  -   |   -   |   +

The basic rules of XOR remains same for negative XOR operations as well, but how the operation really works in negative numbers could be useful for someone someday .

Deserialize JSON string to c# object

I believe you are looking for this:

string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

Wait for a void async method

If you can change the signature of your function to async Task then you can use the code presented here

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

Traverse all the Nodes of a JSON Object Tree with JavaScript

             var localdata = [{''}]// Your json array
              for (var j = 0; j < localdata.length; j++) 
               {$(localdata).each(function(index,item)
                {
                 $('#tbl').append('<tr><td>' + item.FirstName +'</td></tr>);
                 }

Fitting a density curve to a histogram in R

If I understand your question correctly, then you probably want a density estimate along with the histogram:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE)            # prob=TRUE for probabilities not counts
lines(density(X))             # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted")   # add another "smoother" density

Edit a long while later:

Here is a slightly more dressed-up version:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2) 

along with the graph it produces:

enter image description here

Creating a copy of a database in PostgreSQL

What's the correct way to copy entire database (its structure and data) to a new one in pgAdmin?

Answer:

CREATE DATABASE newdb WITH TEMPLATE originaldb;

Tried and tested.

Return file in ASP.Net Core Web API

Here is a simplistic example of streaming a file:

using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
    var path = "<Get the file path using the ID>";
    var stream = File.OpenRead(path);
    return new FileStreamResult(stream, "application/octet-stream");
}

Note:

Be sure to use FileStreamResult from Microsoft.AspNetCore.Mvc and not from System.Web.Mvc.

Multiple Python versions on the same machine?

Package Managers - user-level

For a package manager that can install and manage multiple versions of python, these are good choices:

  • pyenv - only able to install and manage versions of python
  • asdf - able to install and manage many different languages

The advantages to these package managers is that it may be easier to set them up and install multiple versions of python with them than it is to install python from source. They also provide commands for easily changing the available python version(s) using shims and setting the python version per-directory.

This disadvantage is that, by default, they are installed at the user-level (inside your home directory) and require a little bit of user-level configuration - you'll need to edit your ~/.profile and ~/.bashrc or similar files. This means that it is not easy to use them to install multiple python versions globally for all users. In order to do this, you can install from source alongside the OS's existing python version.


Installation from source - system-wide

You'll need root privileges for this method.

See the official python documentation for building from source for additional considerations and options.

/usr/local is the designated location for a system administrator to install shared (system-wide) software, so it's subdirectories are a good place to download the python source and install. See section 4.9 of the Linux Foundation's File Hierarchy Standard.

Install any build dependencies. On Debian-based systems, use:

apt update
apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev libbz2-dev

Choose which python version you want to install. See the Python Source Releases page for a listing.

Download and unzip file in /usr/local/src, replacing X.X.X below with the python version (i.e. 3.8.2).

cd /usr/local/src
wget https://www.python.org/ftp/python/X.X.X/Python-X.X.X.tgz
tar vzxf Python-X.X.X.tgz

Before building and installing, set the CFLAGS environment variable with C compiler flags necessary (see GNU's make documentation). This is usually not necessary for general use, but if, for example, you were going to create a uWSGI plugin with this python version, you might want to set the flags, -fPIC, with the following:

export CFLAGS='-fPIC'

Change the working directory to the unzipped python source directory, and configure the build. You'll probably want to use the --enable-optimizations option on the ./configure command for profile guided optimization. Use --prefix=/usr/local to install to the proper subdirectories (/usr/local/bin, /usr/local/lib, etc.).

cd Python-X.X.X
./configure --enable-optimizations --prefix=/usr/local

Build the project with make and install with make altinstall to avoid overriding any files when installing multiple versions. See the warning on this page of the python build documentation.

make -j 4
make altinstall

Then you should be able to run your new python and pip versions with pythonX.X and pipX.X (i.e python3.8 and pip3.8). Note that if the minor version of your new installation is the same as the OS's version (for example if you were installing python3.8.4 and the OS used python3.8.2), then you would need to specify the entire path (/usr/local/bin/pythonX.X) or set an alias to use this version.

How to select specific columns in laravel eloquent

use App\Table;
// ...
Table::where('id',1)->get('name','surname');

if no where

Table::all('name','surname');

How can I get the name of an object in Python?

Objects do not necessarily have names in Python, so you can't get the name.

It's not unusual for objects to have a __name__ attribute in those cases that they do have a name, but this is not a part of standard Python, and most built in types do not have one.

When you create a variable, like the x, y, z above then those names just act as "pointers" or "references" to the objects. The object itself does not know what name you are using for it, and you can not easily (if at all) get the names of all references to that object.

Update: However, functions do have a __name__ (unless they are lambdas) so, in that case you can do:

dict([(t.__name__, t) for t in fun_list])

Copy/Paste from Excel to a web page

Digging this up, in case anyone comes across it in the future. I used the above code as intended, but then ran into an issue displaying the table after it had been submitted to a database. It's much easier once you've stored the data to use PHP to replace the new lines and tabs in your query. You may perform the replace upon submission, $_POST[request] would be the name of your textarea:

$postrequest = trim($_POST[request]);
$dirty = array("\n", "\t");
$clean = array('</tr><tr><td>', '</td><td>');
$request = str_replace($dirty, $clean, $postrequest);

Now just insert $request into your database, and it will be stored as an HTML table.

How do you use youtube-dl to download live streams (that are live)?

There is no need to pass anything to ffmpeg you can just grab the desired format, in this example, it was the "95" format.

So once you know that it is the 95, you just type:

youtube-dl -f 95  https://www.youtube.com/watch\?v\=6aXR-SL5L2o

that is to say:

youtube-dl -f <format number> <url>

It will begin generating on the working directory a <somename>.<probably mp4>.part which is the partially downloaded file, let it go and just press <Ctrl-C> to stop the capture.

The file will still be named <something>.part, rename it to <whatever>.mp4 and there it is...

The ffmpeg code:

ffmpeg -i $(youtube-dl -f <format number> -g <url>) -copy <file_name>.ts

also worked for me, but sound and video got out of sync, using just youtube-dl seemed to yield a better result although it too uses ffmpeg.

The downside of this approach is that you cannot watch the video while downloading, well you can open yet another FF or Chrome, but it seems that mplayer cannot process the video output till youtube-dl/ffmpeg are running.

Generate list of all possible permutations of a string

In ruby:

str = "a"
100_000_000.times {puts str.next!}

It is quite fast, but it is going to take some time =). Of course, you can start at "aaaaaaaa" if the short strings aren't interesting to you.

I might have misinterpreted the actual question though - in one of the posts it sounded as if you just needed a bruteforce library of strings, but in the main question it sounds like you need to permutate a particular string.

Your problem is somewhat similar to this one: http://beust.com/weblog/archives/000491.html (list all integers in which none of the digits repeat themselves, which resulted in a whole lot of languages solving it, with the ocaml guy using permutations, and some java guy using yet another solution).

How to keep a git branch in sync with master

Yeah I agree with your approach. To merge mobiledevicesupport into master you can use

git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport

Similarly you can also merge master in mobiledevicesupport.

Q. If cross merging is an issue or not.

A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example: After last sync, following commits happen to these branches

Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E

Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,

git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.

Now, there are two types of merging possible

  1. Fast forward merge
  2. True merge (Requires manual effort)

Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.

So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.

Play audio file from the assets directory

this works for me:

public static class eSound_Def
{
  private static Android.Media.MediaPlayer mpBeep;

  public static void InitSounds( Android.Content.Res.AssetManager Assets )
  {
    mpBeep = new Android.Media.MediaPlayer();

    InitSound_Beep( Assets );
  }

  private static void InitSound_Beep( Android.Content.Res.AssetManager Assets )
  {
    Android.Content.Res.AssetFileDescriptor AFD;

    AFD = Assets.OpenFd( "Sounds/beep-06.mp3" );
    mpBeep.SetDataSource( AFD.FileDescriptor, AFD.StartOffset, AFD.Length );
    AFD.Close();

    mpBeep.Prepare();
    mpBeep.SetVolume( 1f, 1f );
    mpBeep.Looping = false;
  }

  public static void PlaySound_Beep()
  {
    if (mpBeep.IsPlaying == true) 
    {
      mpBeep.Stop();
      mpBeep.Reset();
      InitSound_Beep(); 
    }
    mpBeep.Start();
  }
}

In main activity, on create:

protected override void OnCreate( Bundle savedInstanceState )
{
  base.OnCreate( savedInstanceState );
  SetContentView( Resource.Layout.lmain_activity );
  ...
  eSound_Def.InitSounds( Assets );
  ...
}

how to use in code (on button click):

private void bButton_Click( object sender, EventArgs e )
{
  eSound_Def.PlaySound_Beep();
}

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I was working with spring boot jpa and fixed by implementing @EnableTransactionManagement

Attached file may help you.

What are the git concepts of HEAD, master, origin?

I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.

HEAD: the current commit your repo is on. Most of the time HEAD points to the latest commit in your current branch, but that doesn't have to be the case. HEAD really just means "what is my repo currently pointing at".

In the event that the commit HEAD refers to is not the tip of any branch, this is called a "detached head".

master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.

origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.

HEAD is an official notion in git. HEAD always has a well-defined meaning. master and origin are common names usually used in git, but they don't have to be.

How do I create a list of random numbers without duplicates?

You can first create a list of numbers from a to b, where a and b are respectively the smallest and greatest numbers in your list, then shuffle it with Fisher-Yates algorithm or using the Python's random.shuffle method.

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

just run mongod in terminal on the base folder if everything has been set up like installing mongo db and the client for it like mongoose. After running the command run the project file that you are working on and then the error shouldn't appear.

T-SQL: How to Select Values in Value List that are NOT IN the Table?

This Should work with all SQL versions.

SELECT  E.AccessCode ,
        CASE WHEN C.AccessCode IS NOT NULL THEN 'Exist'
             ELSE 'Not Exist'
        END AS [Status]
FROM    ( SELECT    '60552' AS AccessCode
          UNION ALL
          SELECT    '80630'
          UNION ALL
          SELECT    '1611'
          UNION ALL
          SELECT    '0000'
        ) AS E
        LEFT OUTER JOIN dbo.Credentials C ON E.AccessCode = c.AccessCode

How do I print out the contents of a vector?

Just copy the container to the console.

std::vector<int> v{1,2,3,4};
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " " ));

Should output :

1 2 3 4