Programs & Examples On #Visualstategroup

Change the Bootstrap Modal effect

A riot.js solution:

My riot.js Example nests the animated-modal tag inside an order profile tag.

Note, this assumes jquery and riot.js is loaded before.

animated-modal tag contents:

<a id='{ opts.el }' href="" class='pull-right'>edit</a>

    <div class="modal animated" id="{ opts.el }-modal" tabindex="-1" role="dialog" aria-labelledby="animatedModal">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <button onclick={ cancelForm } id='{ opts.el }-cancel-1' type="button" class="close" ><span>&times;</span></button>
            <h4 class="modal-title" id="animatedModal">{ opts.title }</h4>
          </div>
          <div class="modal-body">
              <yield/>
          </div>
          <div class="modal-footer">
            <button onclick={ cancelForm } id='{ opts.el }-cancel-2' onclick={ cancelForm } type="button" class="btn btn-default">Close</button>
            <button onclick={ saveForm } type="button" class="btn btn-primary">Save changes</button>
          </div>

        </div>
      </div>
    </div>

    <script>
    var self = this
    self.modalBtn = `#${opts.el}`
    self.modal = `#${opts.el}-modal`
    self.animateInClass = opts.animatein || 'fadeIn'
    self.animateOutClass = opts.animateout || 'fadeOut'
    self.closeModalBtn = `#${ opts.el }-cancel-1, #${ opts.el }-cancel-2`
    self.animationsStr = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend'

    this.on('mount',function(){
        self.initModal()
        self.update()
    })

    this.initModal = function(){
        modal = $(self.modal)
        modalBtn = $(self.modalBtn)
        closeModalBtn = `#${ opts.el }-cancel-1`

        modalBtn.click(function(){
            $(self.modal).addClass(self.animateInClass)
            $(self.modal).modal('show') 
        })

        $(self.modal).on('show.bs.modal',function(){
            $(self.closeModalBtn).one('click',function(){
                $(self.modal).removeClass(self.animateInClass).addClass(self.animateOutClass)

                $(self.modal).on(self.animationsStr,function(){
                    $(self.modal).modal('hide') 
                })
            })
        })

        $(self.modal).on('hidden.bs.modal',function(evt){
            $(self.modal).removeClass(self.animateOutClass)
            $(self.modal).off(self.animationsStr)
            $(self.closeModalBtn).off('click')
        })
    }

    this.cancelForm = function(e){
        this.parent.cancelForm()
    }

    this.showEdit = function(e){
        this.parent.showEdit()
    }

    this.saveForm = function(e){
        this.parent.saveForm()
    }

    dashboard_v2.bus.on('closeModal',function(){
        try{
            $(`#${ opts.el }-cancel-1`).trigger('click')
        }catch(e){}

    })
</script>

And the Profile Tag to nest in:

profile tag contents:

<div class="row">
        <div class="col-md-12">
            <div class="eshop-product-body">

                <animated-modal>
                    title='Order Edit'
                    el='order-modal-1'>

                    <div class="row">
                        <div class="col-md-6 col-md-offset-3">
                            <form id='profile-form'>
                                <div class="form-group">
                                    <label>Organization</label>
                                    <input id='organization' type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
                                </div>

                                <div class="form-group">
                                    <label>Contact</label>
                                    <input id='contact' type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
                                </div>

                                <div class="form-group">
                                    <label>Phone</label>
                                    <input id='phone' type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
                                </div>

                                <div class="form-group">
                                    <label>Email</label>
                                    <input id='email' type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
                                </div>
                            </form>
                        </div>
                    </div>

                </animated-modal>

                <h3>Profile</h3>

                <ul class='profile-list'>
                    <li>Organization: { opts.data.profile.organization }</li>
                    <li>Contact: { opts.data.profile.contact_full_name }</li>
                    <li>Phone: { opts.data.profile.phone_number }</li>
                    <li>Email: { opts.data.profile.email }</li>
                </ul>
            </div>
        </div>
    </div>

    <script>
        var self = this     

        this.on('mount',function(){

        })

        this.cancelForm = function(e){

        }

        this.showEdit = function(e){

        }

        this.saveForm = function(e){

        }
    </script>

How to play YouTube video in my Android application?

I didn't want to have to have the YouTube app present on the device so I used this tutorial:

http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html

...to produce this code in my app:

WebView mWebView; 

@Override
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.video_webview);
    mWebView=(WebView)findViewById(R.id.videoview);

    //build your own src link with your video ID
    String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
        }
    });
    WebSettings ws = mWebView.getSettings();
    ws.setJavaScriptEnabled(true);
    mWebView.loadData(videoStr, "text/html", "utf-8");

}

//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:background="#000000"
    android:id="@+id/bmp_programme_ll"
    android:orientation="vertical" >

   <WebView
    android:id="@+id/videoview" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />  
</LinearLayout>     

This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.

Which terminal command to get just IP address and nothing else?

Here is my version, in which you can pass a list of interfaces, ordered by priority:

getIpFromInterface()
{
    interface=$1
    ifconfig ${interface}  > /dev/null 2>&1 && ifconfig ${interface} | awk -F'inet ' '{ print $2 }' | awk '{ print $1 }' | grep .
}

getCurrentIpAddress(){
    IFLIST=(${@:-${IFLIST[@]}})
    for currentInterface in ${IFLIST[@]}
    do
        IP=$(getIpFromInterface  $currentInterface)
        [[ -z "$IP" ]] && continue
    echo ${IP/*:}
    return
    done
}

IFLIST=(tap0 en1 en0)
getCurrentIpAddress $@

So if I'm connected with VPN, Wifi and ethernet, my VPN address (on interface tap0) will be returned. The script works on both linux and osx, and can take arguments if you want to override IFLIST

Note that if you want to use IPV6, you'll have to replace 'inet ' by 'inet6'.

Sending private messages to user

To send a message to a user you first need a User instance representing the user you want to send the message to.


Obtaining a User instance

  • You can obtain a User instance from a message the user sent by doing message.autor
  • You can obtain a User instance from a user id with client.fetchUser

Once you got a user instance you can send the message with .send

Examples

client.on('message', (msg) => {
 if (!msg.author.bot) msg.author.send('ok ' + msg.author.id);
});
client.fetchUser('487904509670337509', false).then((user) => {
 user.send('heloo');
});

Can I create links with 'target="_blank"' in Markdown?

I ran into this problem when trying to implement markdown using PHP.

Since the user generated links created with markdown need to open in a new tab but site links need to stay in tab I changed markdown to only generate links that open in a new tab. So not all links on the page link out, just the ones that use markdown.

In markdown I changed all the link output to be <a target='_blank' href="..."> which was easy enough using find/replace.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

Today I faced the same issue consistently, whenever I exit the eclipse. While trying the above solution provided by TS.xy, the below steps got rid of this issue for now.

  1. Switch to new workspace and close the Eclipse.
  2. Open the Eclipse with new workspace and after that switch to the actual workspace(in which exception occurs).
  3. Actual workspace loaded with all my previous projects.
  4. Now exiting the Eclipse, does not result in that exception.

Hope that this step may work for someone.

How do I get the number of elements in a list?

While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a length property:

class slist(list):
    @property
    def length(self):
        return len(self)

You can use it like so:

>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Essentially, it's exactly identical to a list object, with the added benefit of having an OOP-friendly length property.

As always, your mileage may vary.

Run CSS3 animation only once (at page loading)

It can be done with a little bit of extra overhead.

Simply wrap your link in a div, and separate the animation.

the html ..

<div class="animateOnce">
    <a class="animateOnHover">me!</a>
</div>

.. and the css ..

.animateOnce {
    animation: splash 1s normal forwards ease-in-out;
}

.animateOnHover:hover {
    animation: hover 1s infinite alternate ease-in-out;
}

"unmappable character for encoding" warning in Java

Use the "\uxxxx" escape format.

According to Wikipedia, the copyright symbol is unicode U+00A9 so your line should read:

String copyright = "\u00a9 2003-2008 My Company. All rights reserved.";

creating array without declaring the size - java

You might be looking for a List? Either LinkedList or ArrayList are good classes to take a look at. You can then call toArray() to get the list as an array.

jQuery - multiple $(document).ready ...?

It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.

This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.

This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.

New Array from Index Range Swift

subscript

extension Array where Element : Equatable {
  public subscript(safe bounds: Range<Int>) -> ArraySlice<Element> {
    if bounds.lowerBound > count { return [] }
    let lower = Swift.max(0, bounds.lowerBound)
    let upper = Swift.max(0, Swift.min(count, bounds.upperBound))
    return self[lower..<upper]
  }
  
  public subscript(safe lower: Int?, _ upper: Int?) -> ArraySlice<Element> {
    let lower = lower ?? 0
    let upper = upper ?? count
    if lower > upper { return [] }
    return self[safe: lower..<upper]
  }
}

returns a copy of this range clamped to the given limiting range.

var arr = [1, 2, 3]
    
arr[safe: 0..<1]    // returns [1]  assert(arr[safe: 0..<1] == [1])
arr[safe: 2..<100]  // returns [3]  assert(arr[safe: 2..<100] == [3])
arr[safe: -100..<0] // returns []   assert(arr[safe: -100..<0] == [])

arr[safe: 0, 1]     // returns [1]  assert(arr[safe: 0, 1] == [1])
arr[safe: 2, 100]   // returns [3]  assert(arr[safe: 2, 100] == [3])
arr[safe: -100, 0]  // returns []   assert(arr[safe: -100, 0] == [])

Hide HTML element by id

@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS

<style type="text/css">
    #nav-ask{ display:none; }
</style>

or if you already have a "hideMe" CSS Class:

<script type="text/javascript">

    if(document.getElementById && document.createTextNode)
    {
        if(document.getElementById('nav-ask'))
        {
            document.getElementById('nav-ask').className='hideMe';
        }
    }

</script>

How to bind inverse boolean properties in WPF?

Add one more property in your view model, which will return reverse value. And bind that to button. Like;

in view model:

public bool IsNotReadOnly{get{return !IsReadOnly;}}

in xaml:

IsEnabled="{Binding IsNotReadOnly"}

Find all files with name containing string

The -maxdepth option should be before the -name option, like below.,

find . -maxdepth 1 -name "string" -print

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality. In fact, both do this:

return this.Add(new SqlParameter(parameterName, value));

The reason they deprecated the old one in favor of AddWithValue is to add additional clarity, as well as because the second parameter is object, which makes it not immediately obvious to some people which overload of Add was being called, and they resulted in wildly different behavior.

Take a look at this example:

 SqlCommand command = new SqlCommand();
 command.Parameters.Add("@name", 0);

At first glance, it looks like it is calling the Add(string name, object value) overload, but it isn't. It's calling the Add(string name, SqlDbType type) overload! This is because 0 is implicitly convertible to enum types. So these two lines:

 command.Parameters.Add("@name", 0);

and

 command.Parameters.Add("@name", 1);

Actually result in two different methods being called. 1 is not convertible to an enum implicitly, so it chooses the object overload. With 0, it chooses the enum overload.

Understanding repr( ) function in Python

1) The result of repr('foo') is the string 'foo'. In your Python shell, the result of the expression is expressed as a representation too, so you're essentially seeing repr(repr('foo')).

2) eval calculates the result of an expression. The result is always a value (such as a number, a string, or an object). Multiple variables can refer to the same value, as in:

x = 'foo'
y = x

x and y now refer to the same value.

3) I have no idea what you meant here. Can you post an example, and what you'd like to see?

How to Animate Addition or Removal of Android ListView Rows

I haven't tried it but it looks like animateLayoutChanges should do what you're looking for. I see it in the ImageSwitcher class, I assume it's in the ViewSwitcher class as well?

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

Use this script, it is previous version of jquery. Solved my problem.

<script
          src="https://code.jquery.com/jquery-2.2.4.min.js"
          integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
          crossorigin="anonymous"></script>

SQLite select where empty?

It looks like you can simply do:

SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';

Test case:

CREATE TABLE your_table (id int, some_column varchar(10));

INSERT INTO your_table VALUES (1, NULL);
INSERT INTO your_table VALUES (2, '');
INSERT INTO your_table VALUES (3, 'test');
INSERT INTO your_table VALUES (4, 'another test');
INSERT INTO your_table VALUES (5, NULL);

Result:

SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';

id        
----------
1         
2         
5    

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Ubuntu 20.04:

Option 1 - set up a gem installation directory for your user account

For bash (for zsh, we would use .zshrc of course)

echo '# Install Ruby Gems to ~/gems' >> ~/.bashrc
echo 'export GEM_HOME="$HOME/gems"' >> ~/.bashrc
echo 'export PATH="$HOME/gems/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

Option 2 - use snap

Uninstall the apt-version (ruby-full) and reinstall it with snap

sudo apt-get remove ruby
sudo snap install ruby --classic

Set the absolute position of a view

You can use RelativeLayout. Let's say you wanted a 30x40 ImageView at position (50,60) inside your layout. Somewhere in your activity:

// Some existing RelativeLayout from your layout xml
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);

ImageView iv = new ImageView(this);

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);

More examples:

Places two 30x40 ImageViews (one yellow, one red) at (50,60) and (80,90), respectively:

RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;

iv = new ImageView(this);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);

iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;
rl.addView(iv, params);

Places one 30x40 yellow ImageView at (50,60) and another 30x40 red ImageView <80,90> relative to the yellow ImageView:

RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;

int yellow_iv_id = 123; // Some arbitrary ID value.

iv = new ImageView(this);
iv.setId(yellow_iv_id);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);

iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;

// This line defines how params.leftMargin and params.topMargin are interpreted.
// In this case, "<80,90>" means <80,90> to the right of the yellow ImageView.
params.addRule(RelativeLayout.RIGHT_OF, yellow_iv_id);

rl.addView(iv, params);

Creating java date object from year,month,day

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.

Here is a quick example using LocalDate from the Joda Time library:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.

Checking if a variable exists in javascript

I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers. I agree with his answer, but

If you really want to test if a variable is undeclared, you'll need to catch the ReferenceError ...

is not the only way. One can do just:

this.hasOwnProperty("bar")

to check if there is a variable bar declared in the current context. (I'm not sure, but calling the hasOwnProperty could also be more fast/effective than raising an exception) This works only for the current context (not for the whole current scope).

How to get the mobile number of current sim card in real device?

Well, all could be temporary hacks, but there is no way to get mobile number of a user. It is against ethical policy.

For eg, one of the answers above suggests getting all accounts and extracting from there. And it doesn't work anymore! All of these are hacks only.

Only way to get user's mobile number is going through operator. If you have a tie-up with mobile operators like Aitel, Vodafone, etc, you can get user's mobile number in header of request from mobile handset when connected via mobile network internet.

Not sure if any manufacturer tie ups to get specific permissions can help - not explored this area, but nothing documented atleast.

Tar a directory, but don't store full absolute paths in the archive

tar -cjf site1.tar.bz2 -C /var/www/site1 .

In the above example, tar will change to directory /var/www/site1 before doing its thing because the option -C /var/www/site1 was given.

From man tar:

OTHER OPTIONS

  -C, --directory DIR
       change to directory DIR

Return row of Data Frame based on value in a column - R

Based on the syntax provided

 Select * Where Amount = min(Amount)

You could do using:

 library(sqldf)

Using @Kara Woo's example df

  sqldf("select * from df where Amount in (select min(Amount) from df)")
  #Name Amount
 #1    B    120
 #2    E    120

Why does Vim save files with a ~ extension?

Put this line into your vimrc:

set nobk nowb noswf noudf " nobackup nowritebackup noswapfile noundofile


In that would be the:

C:\Program Files (x86)\vim\_vimrc

file for system-wide vim configuration for all users.

Setting the last one noundofile is important in Windows to prevent the creation of *~ tilda files after editing.


I wish Vim had that line included by default. Nobody likes ugly directories.

Let the user choose if and how she wants to enable advanced backup/undo file features first.

This is the most annoying part of Vim.

The next step might be setting up:

set noeb vb t_vb= " errorbells visualbell

to disable beeping in as well :-)

How to view the current heap size that an application is using?

public class CheckHeapSize {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        long heapSize = Runtime.getRuntime().totalMemory(); 

        // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
        long heapMaxSize = Runtime.getRuntime().maxMemory();

         // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
        long heapFreeSize = Runtime.getRuntime().freeMemory(); 

        System.out.println("heapsize"+formatSize(heapSize));
        System.out.println("heapmaxsize"+formatSize(heapMaxSize));
        System.out.println("heapFreesize"+formatSize(heapFreeSize));

    }
    public static String formatSize(long v) {
        if (v < 1024) return v + " B";
        int z = (63 - Long.numberOfLeadingZeros(v)) / 10;
        return String.format("%.1f %sB", (double)v / (1L << (z*10)), " KMGTPE".charAt(z));
    }
}

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

Error: No default engine was specified and no extension was provided

if you've got this error by using the express generator, I've solved it by using

express --view=ejs myapp

instead of

express --view=pug myapp

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

I had the same problem. In the jQuery documentation I found:

For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

So though the server allows cross origin request but does not allow Access-Control-Allow-Headers , it will throw errors. By default angular content type is application/json, which is trying to send a OPTION request. Try to overwrite angular default header or allow Access-Control-Allow-Headers in server end. Here is an angular sample:

$http.post(url, data, {
    headers : {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});

Wamp Server not goes to green color

Quit skype and right click on wamp icon-apache-services-start all services that will work after wamp server is start you can use skype again ;)

How can the default node version be set using NVM?

#Worked for me 100% Follow this for default node version:

nvm install 12.13.1 then, nvm alias default 12.13.1

How to get longitude and latitude of any address?

There is no forumula, as street names and cities are essentially handed out randomly. The address needs to be looked up in a database. Alternatively, you can look up a zip code in a database for the region that the zip code is for.

You didn't mention a country, so I'm going to assume you just want addresses in the USA. There are numerous databases you can use, some free, some not.

You can also use the Google Maps API to have them look up an address in their database for you. That is probably the easiest solution, but requires your application to have a working internet connection at all times.

What is the most efficient string concatenation method in python?

I ran into a situation where I needed to have an appendable string of unknown size. These are the benchmark results (python 2.7.3):

$ python -m timeit -s 's=""' 's+="a"'
10000000 loops, best of 3: 0.176 usec per loop
$ python -m timeit -s 's=[]' 's.append("a")'
10000000 loops, best of 3: 0.196 usec per loop
$ python -m timeit -s 's=""' 's="".join((s,"a"))'
100000 loops, best of 3: 16.9 usec per loop
$ python -m timeit -s 's=""' 's="%s%s"%(s,"a")'
100000 loops, best of 3: 19.4 usec per loop

This seems to show that '+=' is the fastest. The results from the skymind link are a bit out of date.

(I realize that the second example is not complete, the final list would need to be joined. This does show, however, that simply preparing the list takes longer than the string concat.)

How to prevent colliders from passing through each other?

1.) Never use MESH COLLIDER. Use combination of box and capsule collider.

2.) Check constraints in RigidBody. If you tick Freeze Position X than it will pass through the object on the X axis. (Same for y axis).

How to check whether an array is empty using PHP?

In my opinion the simplest way for an indexed array would be simply:

    if ($array) {
      //Array is not empty...  
    }

An 'if' condition on the array would evaluate to true if the array is not empty and false if the array is empty. This is not applicable to associative arrays.

Using CSS for a fade-in effect on page load

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

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

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

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

HTML:

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

CSS:

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

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

Fragments within Fragments

Nested fragments are not currently supported. Trying to put a fragment within the UI of another fragment will result in undefined and likely broken behavior.

Update: Nested fragments are supported as of Android 4.2 (and Android Support Library rev 11) : http://developer.android.com/about/versions/android-4.2.html#NestedFragments

NOTE (as per this docs): "Note: You cannot inflate a layout into a fragment when that layout includes a <fragment>. Nested fragments are only supported when added to a fragment dynamically."

Load image from resources area of project in C#

JDS's answer worked best. C# example loading image:

  • Include the image as Resource (Project tree->Resources, right click to add the desirable file ImageName.png)
  • Embedded Resource (Project tree->Resources->ImageName.png, right click select properties)
  • .png file format (.bmp .jpg should also be OK)

pictureBox1.Image = ProjectName.Properties.Resources.ImageName;

Note the followings:

  • The resource image file is "ImageName.png", file extension should be omitted.
  • ProjectName may perhaps be more adequately understood as "Assembly name", which is to be the respective text entry on the Project->Properties page.

The example code line is run successfully using VisualStudio 2015 Community.

Website screenshots

cutycapt saves webpages to most image formats(jpg,png..) download it from your synaptic, it works much better than wkhtmltopdf

List of standard lengths for database fields

These might be useful to someone;

youtube max channel length = 20
facebook max name length   = 50
twitter max handle length  = 15
email max length           = 255 

http://www.interoadvisory.com/2015/08/6-areas-inside-of-linkedin-with-character-limits/

Disable nginx cache for JavaScript files

The expires and add_header directives have no impact on NGINX caching the files, those are purely about what the browser sees.

What you likely want instead is:

location stuffyoudontwanttocache {
    # don't cache it
    proxy_no_cache 1;
    # even if cached, don't try to use it
    proxy_cache_bypass 1; 
}

Though usually .js etc is the thing you would cache, so perhaps you should just disable caching entirely?

Send email with PHP from html form on submit with the same script

You need a SMPT Server in order for

... mail($to,$subject,$message,$headers);

to work.

You could try light weight SMTP servers like xmailer

java.lang.UnsupportedClassVersionError

This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

Regular Expressions: Is there an AND operator?

The order is always implied in the structure of the regular expression. To accomplish what you want, you'll have to match the input string multiple times against different expressions.

What you want to do is not possible with a single regexp.

Bash scripting, multiple conditions in while loop

The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.

Alternatively:

while [ $stats -gt 300 ] || [ $stats -eq 0 ]

How do I use a regular expression to match any string, but at least 3 characters?

This is python regex, but it probably works in other languages that implement it, too.

I guess it depends on what you consider a character to be. If it's letters, numbers, and underscores:

\w{3,}

if just letters and digits:

[a-zA-Z0-9]{3,}

Python also has a regex method to return all matches from a string.

>>> import re
>>> re.findall(r'\w{3,}', 'This is a long string, yes it is.')
['This', 'long', 'string', 'yes']

count number of characters in nvarchar column

Use

SELECT length(yourfield) FROM table;

TCPDF Save file to folder?

If you still get

TCPDF ERROR: Unable to create output file: myfile.pdf

you can avoid TCPDF's file saving logic by putting PDF data to a variable and saving this string to a file:

$pdf_string = $pdf->Output('pseudo.pdf', 'S');
file_put_contents('./mydir/myfile.pdf', $pdf_string);

npm install private github repositories by dependency in package.json

There's also SSH Key - Still asking for password and passphrase

Using ssh-add ~/.ssh/id_rsa without a local keychain.

This avoids having to mess with tokens.

Why have header files and .cpp files?

Because C, where the concept originated, is 30 years old, and back then, it was the only viable way to link together code from multiple files.

Today, it's an awful hack which totally destroys compilation time in C++, causes countless needless dependencies (because class definitions in a header file expose too much information about the implementation), and so on.

How to create an array of object literals in a loop?

If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:

let john = {
    firstName: "John",
    lastName: "Doe",
};

let people = new Array(10).fill().map((e, i) => {(...john, id: i});

How to trim a string after a specific character in java

Assuming you just want everything before \n (or any other literal string/char), you should use indexOf() with substring():

result = result.substring(0, result.indexOf('\n'));

If you want to extract the portion before a certain regular expression, you can use split():

result = result.split(regex, 2)[0];

String result = "34.1 -118.33\n<!--ABCDEFG-->";

System.out.println(result.substring(0, result.indexOf('\n')));
System.out.println(result.split("\n", 2)[0]);
34.1 -118.33
34.1 -118.33

(Obviously \n isn't a meaningful regular expression, I just used it to demonstrate that the second approach also works.)

Converting java.sql.Date to java.util.Date

Since java.sql.Date extends java.util.Date, you should be able to do

java.util.Date newDate = result.getDate("VALUEDATE");

What is the difference between Collection and List in Java?

First off: a List is a Collection. It is a specialized Collection, however.

A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.

A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.

In a Collection you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.

There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.

What is the difference between a stored procedure and a view?

A view represents a virtual table. You can join multiple tables in a view and use the view to present the data as if the data were coming from a single table.

A stored procedure uses parameters to do a function... whether it is updating and inserting data, or returning single values or data sets.

Creating Views and Stored Procedures - has some information from Microsoft as to when and why to use each.

Say I have two tables:

  • tbl_user, with columns: user_id, user_name, user_pw
  • tbl_profile, with columns: profile_id, user_id, profile_description

So, if I find myself querying from those tables A LOT... instead of doing the join in EVERY piece of SQL, I would define a view like:

CREATE VIEW vw_user_profile
AS
  SELECT A.user_id, B.profile_description
  FROM tbl_user A LEFT JOIN tbl_profile B ON A.user_id = b.user_id
GO

Thus, if I want to query profile_description by user_id in the future, all I have to do is:

SELECT profile_description FROM vw_user_profile WHERE user_id = @ID

That code could be used in a stored procedure like:

CREATE PROCEDURE dbo.getDesc
    @ID int
AS
BEGIN
    SELECT profile_description FROM vw_user_profile WHERE user_id = @ID
END
GO

So, later on, I can call:

dbo.getDesc 25

and I will get the description for user_id 25, where the 25 is your parameter.

There is obviously a lot more detail, this is just the basic idea.

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Conditional Welcome Message

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Nested PHP Shorthand

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

Reading numbers from a text file into an array in C

change to

fscanf(myFile, "%1d", &numberArray[i]);

How to represent a DateTime in Excel

The underlying data type of a datetime in Excel is a 64-bit floating point number where the length of a day equals 1 and 1st Jan 1900 00:00 equals 1. So 11th June 2009 17:30 is about 39975.72917.

If a cell contains a numeric value such as this, it can be converted to a datetime simply by applying a datetime format to the cell.

So, if you can convert your datetimes to numbers using the above formula, output them to the relevant cells and then set the cell formats to the appropriate datetime format, e.g. yyyy-mm-dd hh:mm:ss, then it should be possible to achieve what you want.

Also Stefan de Bruijn has pointed out that there is a bug in Excel in that it incorrectly assumes 1900 is a leap year so you need to take that into account when making your calculations (Wikipedia).

Yahoo Finance All Currencies quote API Documentation

As NT3RP told us that:

... we (Yahoo!) don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service...

So I just thought of sharing this site with you:
http://josscrowcroft.github.com/open-exchange-rates/
[update: site has moved to - http://openexchangerates.org]

This site says:

No access fees, no rate limits, no ugly XML - just free, hourly updated exchange rates in JSON format
[update: Free for personal use, a bargain for your business.]

I hope I've helped and this is of some use to you (and others too). : )

Linux command-line call not returning what it should from os.system?

For your requirement, Popen function of subprocess python module is the answer. For example,

import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout

In laymans terms, what does 'static' mean in Java?

Above points are correct and I want to add some more important points about Static keyword.

Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).

so you will get a doubt that what is the use of this right???

example: static int a=10;(1 program)

just now I told if you use static keyword for variables or for method it will store in permanent memory right.

so I declared same variable with keyword static in other program with different value.

example: static int a=20;(2 program)

the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.

In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.

overall i can say that,if we use static keyword
  1.we can save memory
  2.we can avoid duplicates
  3.No need of creating object in-order to access static variable with the help of class name you can access it.

Import PEM into Java Key Store

I got it from internet. It works pretty good for pem files that contains multiple entries.

#!/bin/bash
pemToJks()
{
        # number of certs in the PEM file
        pemCerts=$1
        certPass=$2
        newCert=$(basename "$pemCerts")
        newCert="${newCert%%.*}"
        newCert="${newCert}"".JKS"
        ##echo $newCert $pemCerts $certPass
        CERTS=$(grep 'END CERTIFICATE' $pemCerts| wc -l)
        echo $CERTS
        # For every cert in the PEM file, extract it and import into the JKS keystore
        # awk command: step 1, if line is in the desired cert, print the line
        #              step 2, increment counter when last line of cert is found
        for N in $(seq 0 $(($CERTS - 1))); do
          ALIAS="${pemCerts%.*}-$N"
          cat $pemCerts |
                awk "n==$N { print }; /END CERTIFICATE/ { n++ }" |
                $KEYTOOLCMD -noprompt -import -trustcacerts \
                                -alias $ALIAS -keystore $newCert -storepass $certPass
        done
}
pemToJks <pem to import> <pass for new jks>

Generate random password string with requirements in javascript

As @RobW notes, restricting the password to a fixed number of characters as proposed in the OP scheme is a bad idea. But worse, answers that propose code based on Math.random are, well, a really bad idea.

Let's start with the bad idea. The OP code is randomly selecting a string of 8 characters from a set of 62. Restricting the random string to 5 letters and 3 numbers means the resulting passwords will have, at best, 28.5 bits of entropy (as opposed to a potential of 47.6 bits if the distribution restriction of 5 letters and 3 numbers were removed). That's not very good. But in reality, the situation is even worse. The at best aspect of the code is destroyed by the use of Math.random as the means of generating entropy for the passwords. Math.random is a pseudo random number generator. Due to the deterministic nature of pseudo random number generators the entropy of the resulting passwords is really bad , rendering any such proposed solution a really bad idea. Assuming these passwords are being doled out to end users (o/w what's the point), an active adversary that receives such a password has very good chance of predicting future passwords doled out to other users, and that's probably not a good thing.

But back to the just bad idea. Assume a cryptographically strong pseudo random number generator is used instead of Math.random. Why would you restrict the passwords to 28.5 bits? As noted, that's not very good. Presumably the 5 letters, 3 numbers scheme is to assist users in managing randomly doled out passwords. But let's face it, you have to balance ease of use against value of use, and 28.5 bits of entropy isn't much value in defense against an active adversary.

But enough of the bad. Let's propose a path forward. I'll use the JavaScript EntropyString library which "efficiently generates cryptographically strong random strings of specified entropy from various character sets". Rather than the OP 62 characters, I'll use a character set with 32 characters chosen to reduce the use of easily confused characters or the formation of English words. And rather than the 5 letter, 3 number scheme (which has too little entropy), I'll proclaim the password will have 60 bits of entropy (this is the balance of ease versus value).

import { Entropy, charSet32 } from 'entropy-string'
const random = new Entropy({ bits: 60, charset: charset32 })
const string = random.string()

"Q7LfR8Jn7RDp"

Note the arguments to Entropy specify the desired bits of entropy as opposed to more commonly seen solutions to random string generation that specify passing in a string length (which is both misguided and typically underspecified, but that's another story).

Remove '\' char from string c#

         while ((line = stringReader.ReadLine()) != null)
         {
             // split the lines
             for (int c = 0; c < line.Length; c++)
             {
                 line = line.Replace("\\", "");
                 lineBreakOne = line.Substring(1, c - 2);
                 lineBreakTwo = line.Substring(c + 2, line.Length - 2);
             }
         }

Store mysql query output into a shell variable

You have the pipe the other way around and you need to echo the query, like this:

myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql db -u $user -p $password)

Another alternative is to use only the mysql client, like this

myvariable=$(mysql db -u $user -p $password -se "SELECT A, B, C FROM table_a")

(-s is required to avoid the ASCII-art)

Now, BASH isn't the most appropriate language to handle this type of scenarios, especially handling strings and splitting SQL results and the like. You have to work a lot to get things that would be very, very simple in Perl, Python or PHP.

For example, how will you get each of A, B and C on their own variable? It's certainly doable, but if you do not understand pipes and echo (very basic shell stuff), it will not be an easy task for you to do, so if at all possible I'd use a better suited language.

Best way to style a TextBox in CSS

You can use:

input[type=text]
{
 /*Styles*/
}

Define your common style attributes inside this. and for extra style you can add a class then.

How to toggle font awesome icon on click?

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

What's the correct way to convert bytes to a hex string in Python 3?

Since Python 3.5 this is finally no longer awkward:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

and reverse:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

works also with the mutable bytearray type.

Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex

Detect whether a Python string is a number or a letter

For a string of length 1 you can simply perform isdigit() or isalpha()

If your string length is greater than 1, you can make a function something like..

def isinteger(a):
    try:
        int(a)
        return True
    except ValueError:
        return False

Java compiler level does not match the version of the installed Java project facet

If using eclipse,

Under.settings click on org.eclipse.wst.common.project.facet.core.xml

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <installed facet="java" version="1.7"/>
</faceted-project>

Change the version to the correct version.

Detect Click into Iframe using JavaScript

This is small solution that works in all browsers even IE8:

var monitor = setInterval(function(){
    var elem = document.activeElement;
    if(elem && elem.tagName == 'IFRAME'){
        clearInterval(monitor);
        alert('clicked!');
    }
}, 100);

You can test it here: http://jsfiddle.net/oqjgzsm0/

Twig ternary operator, Shorthand if-then-else

You can use shorthand syntax as of Twig 1.12.0

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

How do I install the ext-curl extension with PHP 7?

install php70w-common.

It provides php-api, php-bz2, php-calendar, php-ctype, php-curl, php-date, php-exif, php-fileinfo, php-filter, php-ftp, php-gettext, php-gmp, php-hash, php-iconv, php-json, php-libxml, php-openssl, php-pcre, php-pecl-Fileinfo, php-pecl-phar, php-pecl-zip, php-reflection, php-session, php-shmop, php-simplexml, php-sockets, php-spl, php-tokenizer, php-zend-abi, php-zip, php-zlib.

https://webtatic.com/packages/php70/

How to replace text in a column of a Pandas dataframe?

For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column): Pandas has a built in replace method available on a dataframe object.

df.replace(',', '-', regex=True)

Source: Docs

Programmatically shut down Spring Boot application

This works, even done is printed.

  SpringApplication.run(MyApplication.class, args).close();
  System.out.println("done");

So adding .close() after run()

Explanation:

public ConfigurableApplicationContext run(String... args)

Run the Spring application, creating and refreshing a new ApplicationContext. Parameters:

args - the application arguments (usually passed from a Java main method)

Returns: a running ApplicationContext

and:

void close() Close this application context, releasing all resources and locks that the implementation might hold. This includes destroying all cached singleton beans. Note: Does not invoke close on a parent context; parent contexts have their own, independent lifecycle.

This method can be called multiple times without side effects: Subsequent close calls on an already closed context will be ignored.

So basically, it will not close the parent context, that's why the VM doesn't quit.

Is there a Python equivalent of the C# null-coalescing operator?

In addition to Juliano's answer about behavior of "or": it's "fast"

>>> 1 or 5/0
1

So sometimes it's might be a useful shortcut for things like

object = getCachedVersion() or getFromDB()

How to make an android app to always run in background?

On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)

Just go to Settings>PermissionsAutostart

Find a pair of elements from an array whose sum equals a given number

This prints the pairs and avoids duplicates using bitwise manipulation.

public static void findSumHashMap(int[] arr, int key) {
    Map<Integer, Integer> valMap = new HashMap<Integer, Integer>();
    for(int i=0;i<arr.length;i++)
        valMap.put(arr[i], i);

    int indicesVisited = 0; 
    for(int i=0;i<arr.length;i++) {
        if(valMap.containsKey(key - arr[i]) && valMap.get(key - arr[i]) != i) {
            if(!((indicesVisited & ((1<<i) | (1<<valMap.get(key - arr[i])))) > 0)) {
                int diff = key-arr[i];
                System.out.println(arr[i] + " " +diff);
                indicesVisited = indicesVisited | (1<<i) | (1<<valMap.get(key - arr[i]));
            }
        }
    }
}

Socket transport "ssl" in PHP not enabled

Ran into the same problem on Laravel 4 trying to send e-mail using SSL encryption.

Having WAMPServer 2.2 on Windows 7 64bit I only enabled php_openssl in the php.ini, restarted WAMPServer and worked flawlessly.

Did following:

  • Click WampServer -> PHP -> PHP extensions -> php_openssl
  • Restart WampServer

Batch file to delete folders older than 10 days in Windows 7

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.

FOR /d %%K in ("n:\test*") DO (

FOR /d %%J in ("%%K*") DO (

FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"

)

)

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

This works for me nicely:

mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);
mongoose
  .connect(db) //Connection string defined in another file
  .then(() => console.log("Mongo Connected..."))
  .catch(() => console.log(err));

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

Follow followings steps :

  1. Create a file under 'android' folder with name 'local.properties'

  2. Add this line in file 'local.properties' as

    sdk.dir=/Users/bijendrasingh/Library/Android/sdk

Add here your android sdk path.

Subversion ignoring "--password" and "--username" options

Do you actually have the single quotes in your command? I don't think they are necessary. Plus, I think you also need --no-auth-cache and --non-interactive

Here is what I use (no single quotes)

--non-interactive --no-auth-cache --username XXXX --password YYYY

See the Client Credentials Caching documentation in the svnbook for more information.

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Determine project root from a running node.js application

All these "root dirs" mostly need to resolve some virtual path to a real pile path, so may be you should look at path.resolve?

var path= require('path');
var filePath = path.resolve('our/virtual/path.ext');

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.

in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.

name, lastname, email in unpaidMembers.items() so you should refer data or your code might be
lastname, email in unpaidMembers.items() or name, email in unpaidMembers.items()

I want to use CASE statement to update some records in sql server 2005

This is also an alternate use of case-when...

UPDATE [dbo].[JobTemplates]
SET [CycleId] = 
    CASE [Id]
        WHEN 1376 THEN 44   --ACE1 FX1
        WHEN 1385 THEN 44   --ACE1 FX2
        WHEN 1574 THEN 43   --ACE1 ELEM1
        WHEN 1576 THEN 43   --ACE1 ELEM2
        WHEN 1581 THEN 41   --ACE1 FS1
        WHEN 1585 THEN 42   --ACE1 HS1
        WHEN 1588 THEN 43   --ACE1 RS1
        WHEN 1589 THEN 44   --ACE1 RM1
        WHEN 1590 THEN 43   --ACE1 ELEM3
        WHEN 1591 THEN 43   --ACE1 ELEM4
        WHEN 1595 THEN 44   --ACE1 SSTn     
        ELSE 0  
     END
WHERE
    [Id] IN (1376,1385,1574,1576,1581,1585,1588,1589,1590,1591,1595)

I like the use of the temporary tables in cases where duplicate values are not permitted and your update may create them. For example:

SELECT
     [Id]
    ,[QueueId]
    ,[BaseDimensionId]
    ,[ElastomerTypeId]
    ,CASE [CycleId]
        WHEN  29 THEN 44
        WHEN  30 THEN 43
        WHEN  31 THEN 43
        WHEN 101 THEN 41
        WHEN 102 THEN 43
        WHEN 116 THEN 42
        WHEN 120 THEN 44
        WHEN 127 THEN 44
        WHEN 129 THEN 44
        ELSE    0
     END                AS [CycleId]
INTO
    ##ACE1_PQPANominals_1
FROM 
    [dbo].[ProductionQueueProcessAutoclaveNominals]
WHERE
    [QueueId] = 3
ORDER BY 
    [BaseDimensionId], [ElastomerTypeId], [Id];
---- (403 row(s) affected)

UPDATE [dbo].[ProductionQueueProcessAutoclaveNominals]
SET 
    [CycleId] = X.[CycleId]
FROM
    [dbo].[ProductionQueueProcessAutoclaveNominals]
INNER JOIN
(
    SELECT  
        MIN([Id]) AS [Id],[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId] 
    FROM 
        ##ACE1_PQPANominals_1
    GROUP BY    
        [QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId] 
) AS X
ON
    [dbo].[ProductionQueueProcessAutoclaveNominals].[Id] = X.[Id];
----(375 row(s) affected)

Android Color Picker

After some searches in the android references, the newcomer QuadFlask Color Picker seems to be a technically and aesthetically good choice. Also it has Transparency slider and supports HEX coded colors.

Take a look:
QuadFlask Color Picker

recursively use scp but excluding some folders

You can specify GLOBIGNORE and use the pattern *

GLOBIGNORE='ignore1:ignore2' scp -r source/* remoteurl:remoteDir

You may wish to have general rules which you combine or override by using export GLOBIGNORE, but for ad-hoc usage simply the above will do. The : character is used as delimiter for multiple values.

Placing an image to the top right corner - CSS

While looking at the same problem, I found an example

<style type="text/css">
#topright {
    position: absolute;
    right: 0;
    top: 0;
    display: block;
    height: 125px;
    width: 125px;
    background: url(TRbanner.gif) no-repeat;
    text-indent: -999em;
    text-decoration: none;
}
</style>

<a id="topright" href="#" title="TopRight">Top Right Link Text</a>

The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

The best solution for generating an SHA-1 key for Android is from Android Studio.

Click on Gradle on the far right side:

Click on the refresh icon, and you will see the name of the app:

Click on Tasks -> Report -> Signing Report:

Find the SHA-1 key on the bottom part in the console:

NGINX - No input file specified. - php Fast/CGI

I solved it by replacing

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

$document_root with C:\MyWebSite\www\

fastcgi_param SCRIPT_FILENAME C:\MyWebSite\www\$fastcgi_script_name;

How do I update a Mongo document after inserting it?

According to the latest documentation about PyMongo titled Insert a Document (insert is deprecated) and following defensive approach, you should insert and update as follows:

result = mycollection.insert_one(post)
post = mycollection.find_one({'_id': result.inserted_id})

if post is not None:
    post['newfield'] = "abc"
    mycollection.save(post)

Redirect to new Page in AngularJS using $location

If you want to change ng-view you'll have to use the '#'

$window.location.href= "#operation";

Get a list of all the files in a directory (recursive)

The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):

FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
    println "Proguard file located and processed: " + it
}

How to make a programme continue to run after log out from ssh?

You should try using nohup and running it in the background:

nohup sleep 3600 &

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

This is not my answer, but I just copied it from https://gist.github.com/anonymous/2388015 just because the answer is awesome and fixes the problem completely. Credit completely goes to the anonymous author.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        if (/iPhone|iPod|iPad/.test(navigator.userAgent))
            $('iframe').wrap(function(){
                var $this = $(this);
                return $('<div />').css({
                    width: $this.attr('width'),
                    height: $this.attr('height'),
                    overflow: 'auto',
                    '-webkit-overflow-scrolling': 'touch'
                });
            });
    })
</script>

How do I make Visual Studio pause after executing a console application in debug mode?

You say you don't want to use the system("pause") hack. Why not?

If it's because you don't want the program to prompt when it's not being debugged, there's a way around that. This works for me:

void pause () {
    system ("pause");
}

int main (int argc, char ** argv) {
    // If "launched", then don't let the console close at the end until
    // the user has seen the report.
    // (See the MSDN ConGUI sample code)
    //
    do {
        HANDLE hConsoleOutput = ::GetStdHandle (STD_OUTPUT_HANDLE);
        if (INVALID_HANDLE_VALUE == hConsoleOutput)
            break;
        CONSOLE_SCREEN_BUFFER_INFO csbi;
        if (0 == ::GetConsoleScreenBufferInfo (hConsoleOutput, &csbi))
            break;
        if (0 != csbi.dwCursorPosition.X)
            break;
        if (0 != csbi.dwCursorPosition.Y)
            break;
        if (csbi.dwSize.X <= 0)
            break;
        if (csbi.dwSize.Y <= 0)
            break;
        atexit (pause);
    } while (0);

I just paste this code into each new console application I'm writing. If the program is being run from a command window, the cursor position won't be <0,0>, and it won't call atexit(). If it has been launched from you debugger (any debugger) the console cursor position will be <0,0> and the atexit() call will be executed.

I got the idea from a sample program that used to be in the MSDN library, but I think it's been deleted.

NOTE: The Microsoft Visual Studio implementation of the system() routine requires the COMSPEC environment variable to identify the command line interpreter. If this environment variable gets messed up -- for example, if you've got a problem in the Visual Studio project's debugging properties so that the environment variables aren't properly passed down when the program is launched -- then it will just fail silently.

How do I run Selenium in Xvfb?

open a terminal and run this command xhost +. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands

Also make sure in your /etc/environment file there is a line

export DISPLAY=:0.0 

And then, run your tests to see if your issue is resolved.

All please note the comment from sardathrion below before using this.

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

if your intention is send the full array from the html to the controller, can use this:

from the blade.php:

 <input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}"> 

in controller

    public function Get(Request $req) {

    $quotation = array('quotation' => json_decode($req->quotation));

    //or

    return view('quotation')->with('quotation',json_decode($req->quotation))


}

Visual Studio 2012 Web Publish doesn't copy files

This action was successful for me:

Kill Publish Profiles in "Properties>PublishProfiles>xxxx.pubxml" and re-setting again.

What are some alternatives to ReSharper?

I think that CodeRush has a free, limited version, too. I ended up going with ReSharper, and I still recommend it, even though some of the functionality is in Visual Studio 2010. There are just some things that make it worth it.

Keep in mind that you don't need the full ReSharper license if you only code in one language. I have the C# version, and it's cheaper.

Login credentials not working with Gmail SMTP

if you are getting error this(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o60sm2132303pje.21 - gsmtp')

then simply go in you google accountsettings of security section and make a less secure account and turn on the less secure button

Get all validation errors from Angular 2 FormGroup

Based on the @MixerOID response, here is my final solution as a component (maybe I create a library). I also support FormArray's:

import {Component, ElementRef, Input, OnInit} from '@angular/core';
import {FormArray, FormGroup, ValidationErrors} from '@angular/forms';
import {TranslateService} from '@ngx-translate/core';

interface AllValidationErrors {
  controlName: string;
  errorName: string;
  errorValue: any;
}

@Component({
  selector: 'app-form-errors',
  templateUrl: './form-errors.component.html',
  styleUrls: ['./form-errors.component.scss']
})
export class FormErrorsComponent implements OnInit {

  @Input() form: FormGroup;
  @Input() formRef: ElementRef;
  @Input() messages: Array<any>;

  private errors: AllValidationErrors[];

  constructor(
    private translateService: TranslateService
  ) {
    this.errors = [];
    this.messages = [];
  }

  ngOnInit() {
    this.form.valueChanges.subscribe(() => {
      this.errors = [];
      this.calculateErrors(this.form);
    });

    this.calculateErrors(this.form);
  }

  calculateErrors(form: FormGroup | FormArray) {
    Object.keys(form.controls).forEach(field => {
      const control = form.get(field);
      if (control instanceof FormGroup || control instanceof FormArray) {
        this.errors = this.errors.concat(this.calculateErrors(control));
        return;
      }

      const controlErrors: ValidationErrors = control.errors;
      if (controlErrors !== null) {
        Object.keys(controlErrors).forEach(keyError => {
          this.errors.push({
            controlName: field,
            errorName: keyError,
            errorValue: controlErrors[keyError]
          });
        });
      }
    });

    // This removes duplicates
    this.errors = this.errors.filter((error, index, self) => self.findIndex(t => {
      return t.controlName === error.controlName && t.errorName === error.errorName;
    }) === index);
    return this.errors;
  }

  getErrorMessage(error) {
    switch (error.errorName) {
      case 'required':
        return this.translateService.instant('mustFill') + ' ' + this.messages[error.controlName];
      default:
        return 'unknown error ' + error.errorName;
    }
  }
}

And the HTML:

<div *ngIf="formRef.submitted">
  <div *ngFor="let error of errors" class="text-danger">
    {{getErrorMessage(error)}}
  </div>
</div>

Usage:

<app-form-errors [form]="languageForm"
                 [formRef]="formRef"
                 [messages]="{language: 'Language'}">
</app-form-errors>

How to find the sum of an array of numbers

Use reduce

_x000D_
_x000D_
let arr = [1, 2, 3, 4];_x000D_
_x000D_
let sum = arr.reduce((v, i) => (v + i));_x000D_
_x000D_
console.log(sum);
_x000D_
_x000D_
_x000D_

.rar, .zip files MIME Type

You should not trust $_FILES['upfile']['mime'], check MIME type by yourself. For that purpose, you may use fileinfo extension, enabled by default as of PHP 5.3.0.

  $fileInfo = new finfo(FILEINFO_MIME_TYPE);
  $fileMime = $fileInfo->file($_FILES['upfile']['tmp_name']);
  $validMimes = array( 
    'zip' => 'application/zip',
    'rar' => 'application/x-rar',
  );

  $fileExt = array_search($fileMime, $validMimes, true);
  if($fileExt != 'zip' && $fileExt != 'rar')
    throw new RuntimeException('Invalid file format.');

NOTE: Don't forget to enable the extension in your php.ini and restart your server:

extension=php_fileinfo.dll

How to get current local date and time in Kotlin

java.util.Calendar.getInstance() represents the current time using the current locale and timezone.

You could also choose to import and use Joda-Time or one of the forks for Android.

Python NoneType object is not callable (beginner)

You should not pass the call function hi() to the loop() function, This will give the result.

def hi():     
  print('hi')

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)            # Do not use hi() function inside loop() function

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

After doing some research, it seems that this problem may be due to a google bug. For me, I was able to leave this line in my Activities onCreate method:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

AND I changed my targetSdkVersion to 26. Having that line in my onCreate still resulted in a crash while my targetSdkVersion was still set at 27. Since no one else's solution has worked for me thus far, I found that this works as a temporary fix for now.

How to check if a file exists before creating a new file

Looked around a bit, and the only thing I find is using the open system call. It is the only function I found that allows you to create a file in a way that will fail if it already exists

#include <fcntl.h>
#include <errno.h>

int fd=open(filename, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
  /* file exists or otherwise uncreatable
     you might want to check errno*/
}else {
  /* File is open to writing */
}

Note that you have to give permissions since you are creating a file.

This also removes any race conditions there might be

How to clear the canvas for redrawing

there are a ton of good answers here. one further note is that sometimes it's fun to only partially clear the canvas. that is, "fade out" the previous image instead of erasing it entirely. this can give nice trails effects.

it's easy. supposing your background color is white:

// assuming background color = white and "eraseAlpha" is a value from 0 to 1.
myContext.fillStyle = "rgba(255, 255, 255, " + eraseAlpha + ")";
myContext.fillRect(0, 0, w, h);

Vector of Vectors to create matrix

I'm not familiar with c++, but a quick look at the documentation suggests that this should work:

//cin>>CC; cin>>RR; already done
vector<vector<int> > matrix;
for(int i = 0; i<RR; i++)
{
    vector<int> myvector;
    for(int j = 0; j<CC; j++)
    {
        int tempVal = 0;
        cout<<"Enter the number for Matrix 1";
        cin>>tempVal;
        myvector.push_back(tempVal);
    }
    matrix.push_back(myvector);
}

How to echo shell commands as they are executed

set -x or set -o xtrace expands variables and prints a little + sign before the line.

set -v or set -o verbose does not expand the variables before printing.

Use set +x and set +v to turn off the above settings.

On the first line of the script, one can put #!/bin/sh -x (or -v) to have the same effect as set -x (or -v) later in the script.

The above also works with /bin/sh.

See the bash-hackers' wiki on set attributes, and on debugging.

$ cat shl
#!/bin/bash                                                                     

DIR=/tmp/so
ls $DIR

$ bash -x shl 
+ DIR=/tmp/so
+ ls /tmp/so
$

Oracle date format picture ends before converting entire input string

you need to alter session

you can try before insert

 sql : alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

Finding diff between current and last version

If the top commit is pointed to by HEAD then you can do something like this:

commit1 -> HEAD
commit2 -> HEAD~1
commit3 -> HEAD~2

Diff between the first and second commit:

git diff HEAD~1 HEAD

Diff between first and third commit:

git diff HEAD~2 HEAD

Diff between second and third commit:

git diff HEAD~2 HEAD~1

And so on...

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

In order to use API tokens, users will have to obtain their own tokens, each from https://<jenkins-server>/me/configure or https://<jenkins-server>/user/<user-name>/configure. It is up to you, as the author of the script, to determine how users supply the token to the script. For example, in a Bourne Shell script running interactively inside a Git repository, where .gitignore contains /.jenkins_api_token, you might do something like:

api_token_file="$(git rev-parse --show-cdup).jenkins_api_token"
api_token=$(cat "$api_token_file" || true)
if [ -z "$api_token" ]; then
    echo
    echo "Obtain your API token from $JENKINS_URL/user/$user/configure"
    echo "After entering here, it will be saved in $api_token_file; keep it safe!"
    read -p "Enter your Jenkins API token: " api_token
    echo $api_token > "$api_token_file"
fi
curl -u $user:$api_token $JENKINS_URL/someCommand

How to get date in BAT file

Locale-independent one liner to get any date format you like. I use it to generate archive names. Back quote option is needed because PowerShell command line is using single quotes.

:: Get date in yyyyMMdd_HHmm format to use with file name.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Get formatted yesterday date.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).AddDays^(-1^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Show file name with the date.
echo Archive.%DTime%.zip

Beautiful way to remove GET-variables with PHP?

@list($url) = explode("?", $url, 2);

Detecting user leaving page with react-router

You can use this prompt.

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Prompt } from "react-router-dom";

function PreventingTransitionsExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Form</Link>
          </li>
          <li>
            <Link to="/one">One</Link>
          </li>
          <li>
            <Link to="/two">Two</Link>
          </li>
        </ul>
        <Route path="/" exact component={Form} />
        <Route path="/one" render={() => <h3>One</h3>} />
        <Route path="/two" render={() => <h3>Two</h3>} />
      </div>
    </Router>
  );
}

class Form extends Component {
  state = { isBlocking: false };

  render() {
    let { isBlocking } = this.state;

    return (
      <form
        onSubmit={event => {
          event.preventDefault();
          event.target.reset();
          this.setState({
            isBlocking: false
          });
        }}
      >
        <Prompt
          when={isBlocking}
          message={location =>
            `Are you sure you want to go to ${location.pathname}`
          }
        />

        <p>
          Blocking?{" "}
          {isBlocking ? "Yes, click a link or the back button" : "Nope"}
        </p>

        <p>
          <input
            size="50"
            placeholder="type something to block transitions"
            onChange={event => {
              this.setState({
                isBlocking: event.target.value.length > 0
              });
            }}
          />
        </p>

        <p>
          <button>Submit to stop blocking</button>
        </p>
      </form>
    );
  }
}

export default PreventingTransitionsExample;

Bootstrap modal opening on page load

I found the problem. This code was placed in a separate file that was added with a php include() function. And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.

With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.

<script type="text/javascript">
$('#memberModal').modal('show');
</script>

Importing .py files in Google Colab

I face the same problem. After reading numerous posts, I would like to introduce the following solution I finally chose over many other methods (e.g. use urllib, httpimport, clone from GitHub, package the modules for installation, etc). The solution utilizes Google Drive API (official doc) for proper authorization.

Advantages:

  1. Easy and safe (no need for code to handle file operation exceptions and/or additional authorization)
  2. Module files safeguarded by Google account credentials (no one else can view/take/edit them)
  3. You control what to upload/access (you can change/revoke access anytime on a file-by-file basis)
  4. Everything in one place (no need to rely upon or manage another file hosting service)
  5. Freedom to rename/relocate module files (not path-based and won't break your/other's notebook code)

Steps:

  1. Save your .py module file to Google Drive - you should have that since you're already using Colab
  2. Right click on it, "Get shareable link", copy the part after "id=" - the file id assigned by Google Drive
  3. Add and run the following code snippets to your Colab notebook:
!pip install pydrive                             # Package to use Google Drive API - not installed in Colab VM by default
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth                    # Other necessary packages
from oauth2client.client import GoogleCredentials
auth.authenticate_user()                         # Follow prompt in the authorization process
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
your_module = drive.CreateFile({"id": "your_module_file_id"})   # "your_module_file_id" is the part after "id=" in the shareable link
your_module.GetContentFile("your_module_file_name.py")          # Save the .py module file to Colab VM
import your_module_file_name                                    # Ready to import. Don't include".py" part, of course :)

Side note

Last but not least, I should credit the original contributor of this approach. That post might have some typo in the code as it triggered an error when I tried it. After more reading and troubleshooting my code snippets above worked (as of today on Colab VM OS: Linux 4.14.79).

alert a variable value

var input_val=document.getElementById('my_variable');for (i=0; i<input_val.length; i++) {
xx = input_val[i];``
if (xx.name == "ans") {   
    new = xx.value;
    alert(new);    }}

How to set a default Value of a UIPickerView

For example: you populated your UIPickerView with array values, then you wanted 

to select a certain array value in the first load of pickerView like "Arizona". Note that the word "Arizona" is at index 2. This how to do it :) Enjoy coding.

NSArray *countryArray =[NSArray arrayWithObjects:@"Alabama",@"Alaska",@"Arizona",@"Arkansas", nil];
UIPickerView *countryPicker=[[UIPickerView alloc]initWithFrame:self.view.bounds];
countryPicker.delegate=self;
countryPicker.dataSource=self;
[countryPicker selectRow:2 inComponent:0 animated:YES];
[self.view addSubview:countryPicker];

CSS @font-face not working in ie

1) Try putting an absolute link not relative link to your eot font - somehow old IE just don't know in which folder the css file is 2) make 2 extra @font-face declarations so it should look like this:

@font-face { /* for modern browsers and modern IE */
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); 
    src: url("../fonts/Futura_Medium_BT.eot?#iefix") format("embedded-opentype"), 
    url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); 
}
@font-face{ /* for old IE */
  font-family: "Futura_IE"; 
  src: url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot);
}

@font-face{ /* for old IE */
  font-family: "Futura_IE2"; 
  src:url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot?#iefix) 
  format("embedded-opentype");
}

.p{ font-family: "Futura", "Futura_IE", "Futura_IE2", Arial, sans-serif;

This is an example for wordpress template - absolute link should point from where your start index file is.

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

How do you use math.random to generate random ints?

int abc= (Math.random()*100);//  wrong 

you wil get below error message

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int

int abc= (int) (Math.random()*100);// add "(int)" data type

,known as type casting

if the true result is

int abc= (int) (Math.random()*1)=0.027475

Then you will get output as "0" because it is a integer data type.

int abc= (int) (Math.random()*100)=0.02745

output:2 because (100*0.02745=2.7456...etc)

How can I read the contents of an URL with Python?

You can use requests and beautifulsoup libraries to read data on a website. Just install these two libraries and type the following code.

import requests
import bs4
help(requests)
help(bs4)

You will get all the information you need about the library.

Twitter API - Display all tweets with a certain hashtag?

UPDATE for v1.1:

Rather than giving q="search_string" give it q="hashtag" in URL encoded form to return results with HASHTAG ONLY. So your query would become:

    GET https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames

%23 is URL encoded form of #. Try the link out in your browser and it should work.

You can optimize the query by adding since_id and max_id parameters detailed here. Hope this helps !

Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call

Updated

Twitter Search doc link: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html

Converting std::__cxx11::string to std::string

For me -D_GLIBCXX_USE_CXX11_ABI=0 didn't help.

It works after I linked to C++ libs version instead of gnustl.

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

append on an ndarray is ambiguous; to which axis do you want to append the data? Without knowing precisely what your data looks like, I can only provide an example using numpy.concatenate that I hope will help:

import numpy as np

pixels = np.array([[3,3]])
pix = [4,4]
pixels = np.concatenate((pixels,[pix]),axis=0)

# [[3 3]
#  [4 4]]

How to restore PostgreSQL dump file into Postgres databases?

1.open the terminal.

2.backup your database with following command

your postgres bin - /opt/PostgreSQL/9.1/bin/

your source database server - 192.168.1.111

your backup file location and name - /home/dinesh/db/mydb.backup

your source db name - mydatabase

/opt/PostgreSQL/9.1/bin/pg_dump --host '192.168.1.111' --port 5432 --username "postgres" --no-password --format custom --blobs --file "/home/dinesh/db/mydb.backup" "mydatabase"

3.restore mydb.backup file into destination.

your destination server - localhost

your destination database name - mydatabase

create database for restore the backup.

/opt/PostgreSQL/9.1/bin/psql -h 'localhost' -p 5432 -U postgres -c "CREATE DATABASE mydatabase"

restore the backup.

/opt/PostgreSQL/9.1/bin/pg_restore --host 'localhost' --port 5432 --username "postgres" --dbname "mydatabase" --no-password --clean "/home/dinesh/db/mydb.backup"

Reload child component when variables on parent component changes. Angular2

update of @Vladimir Tolstikov's answer

Create a Child Component that use ngOnChanges.

ChildComponent.ts::

import { Component, OnChanges, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'child',
  templateUrl: 'child.component.html',
})

export class ChildComponent implements OnChanges {
  @Input() child_id;

  constructor(private route: ActivatedRoute) { }

  ngOnChanges() {
    // create header using child_id
    console.log(this.child_id);
  }
}

now use it in MasterComponent's template and pass data to ChildComponent like:

<child [child_id]="child_id"></child>

How to make the python interpreter correctly handle non-ASCII characters in string operations?

#!/usr/bin/env python
# -*- coding: utf-8 -*-

s = u"6Â 918Â 417Â 712"
s = s.replace(u"Â", "") 
print s

This will print out 6 918 417 712

Hibernate: best practice to pull all lazy collections

if you using jpa repository, set properties.put("hibernate.enable_lazy_load_no_trans",true); to jpaPropertymap

typesafe select onChange event using reactjs and typescript

The easiest way is to add a type to the variable that is receiving the value, like this:

var value: string = (event.target as any).value;

Or you could cast the value property as well as event.target like this:

var value = ((event.target as any).value as string);

Edit:

Lastly, you can define what EventTarget.value is in a separate .d.ts file. However, the type will have to be compatible where it's used elsewhere, and you'll just end up using any again anyway.

globals.d.ts

interface EventTarget {
    value: any;
}

How to clear all data in a listBox?

If your listbox is connected to a LIST as the data source, listbox.Items.Clear() will not work.

I typically create a file named "DataAccess.cs" containing a separate class for code that uses or changes data pertaining to my form. The following is a code snippet from the DataAccess class that clears or removes all items in the list "exampleItems"

public List<ExampleItem> ClearExampleItems()
       {
           List<ExampleItem> exampleItems = new List<ExampleItem>();
           exampleItems.Clear();
           return examplelistItems;
        }

ExampleItem is also in a separate class named "ExampleItem.cs"

using System;

namespace        // The namespace is automatically added by Visual Studio
{
    public class ExampleItem
    {
        public int ItemId { get; set; }
        public string ItemType { get; set; }
        public int ItemNumber { get; set; }
        public string ItemDescription { get; set; }

        public string FullExampleItem 
        {
            get
            {
                return $"{ItemId} {ItemType} {ItemNumber} {ItemDescription}";
            }
        }
    }
}

In the code for your Window Form, the following code fragments reference your listbox:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;

namespace        // The namespace is automatically added by Visual Studio
{
    
    public partial class YourFormName : Form
    {
        
        List<ExampleItem> exampleItems = new List<ExampleItem>();

        public YourFormName()
        {
            InitializeComponent();

            // Connect listbox to LIST
            UpdateExampleItemsBinding();
        }

        private void UpdateUpdateItemsBinding()
        {
            ExampleItemsListBox.DataSource = exampleItems;
            ExampleItemsListBox.DisplayMember = "FullExampleItem";
        }

        private void buttonClearListBox_Click(object sender, EventArgs e)
        {
            DataAccess db = new DataAccess();
            exampleItems = db.ClearExampleItems();
            
            UpdateExampleItemsBinding();
        }
    }
}

This solution specifically addresses a Windows Form listbox with the datasource connected to a list.

How to display count of notifications in app launcher icon

Android ("vanilla" android without custom launchers and touch interfaces) does not allow changing of the application icon, because it is sealed in the .apk tightly once the program is compiled. There is no way to change it to a 'drawable' programmatically using standard APIs. You may achieve your goal by using a widget instead of an icon. Widgets are customisable. Please read this :http://www.cnet.com/8301-19736_1-10278814-251.html and this http://developer.android.com/guide/topics/appwidgets/index.html. Also look here: https://github.com/jgilfelt/android-viewbadger. It can help you.

As for badge numbers. As I said before - there is no standard way for doing this. But we all know that Android is an open operating system and we can do everything we want with it, so the only way to add a badge number - is either to use some 3-rd party apps or custom launchers, or front-end touch interfaces: Samsung TouchWiz or Sony Xperia's interface. Other answers use this capabilities and you can search for this on stackoverflow, e.g. here. But I will repeat one more time: there is no standard API for this and I want to say it is a bad practice. App's icon notification badge is an iOS pattern and it should not be used in Android apps anyway. In Andrioid there is a status bar notifications for these purposes:http://developer.android.com/guide/topics/ui/notifiers/notifications.html So, if Facebook or someone other use this - it is not a common pattern or trend we should consider. But if you insist anyway and don't want to use home screen widgets then look here, please:

How does Facebook add badge numbers on app icon in Android?

As you see this is not an actual Facebook app it's TouchWiz. In vanilla android this can be achieved with Nova Launcher http://forums.androidcentral.com/android-applications/199709-how-guide-global-badge-notifications.html So if you will see icon badges somewhere, be sure it is either a 3-rd party launcher or touch interface (frontend wrapper). May be sometime Google will add this capability to the standard Android API.

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

How can I format bytes a cell in Excel as KB, MB, GB etc?

You can't really do calculations in the formatting features of Excel. You can use something like the following to do a rough estimation though:

[<500000]#,##0" B";[<500000000]#,##0,," MB";#,##0,,," GB"

How to hide a mobile browser's address bar?

The easiest way to archive browser address bar hiding on page scroll is to add "display": "standalone", to manifest.json file.

Format number as percent in MS SQL Server

And for all SQL Server versions

SELECT CAST(0.973684210526315789 * 100 AS DECIMAL(18, 2))

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

List of installed gems?

use this code (in console mode):

Gem::Specification.all_names

Trigger an event on `click` and `enter`

You call both event listeners using .on() then use a if inside the function:

$(function(){
  $('#searchButton').on('keypress click', function(e){
    var search = $('#usersSearch').val();
    if (e.which === 13 || e.type === 'click') {
      $.post('../searchusers.php', {search: search}, function (response) {
        $('#userSearchResultsTable').html(response);
      });
    }
  });
});

How to create a multi line body in C# System.Net.Mail.MailMessage

In case you dont need the message body in html, turn it off:

message.IsBodyHtml = false;

then use e.g:

message.Body = "First line" + Environment.NewLine + 
               "Second line";

but if you need to have it in html for some reason, use the html-tag:

message.Body = "First line <br /> Second line";

Is there a "goto" statement in bash?

It indeed may be useful for some debug or demonstration needs.

I found that Bob Copeland solution http://bobcopeland.com/blog/2012/10/goto-in-bash/ elegant:

#!/bin/bash
# include this boilerplate
function jumpto
{
    label=$1
    cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
    eval "$cmd"
    exit
}

start=${1:-"start"}

jumpto $start

start:
# your script goes here...
x=100
jumpto foo

mid:
x=101
echo "This is not printed!"

foo:
x=${x:-10}
echo x is $x

results in:

$ ./test.sh
x is 100
$ ./test.sh foo
x is 10
$ ./test.sh mid
This is not printed!
x is 101

"git checkout <commit id>" is changing branch to "no branch"

If you checkout a commit sha directly, it puts you into a "detached head" state, which basically just means that the current sha that your working copy has checked out, doesn't have a branch pointing at it.

If you haven't made any commits yet, you can leave detached head state by simply checking out whichever branch you were on before checking out the commit sha:

git checkout <branch>

If you did make commits while you were in the detached head state, you can save your work by simply attaching a branch before or while you leave detached head state:

# Checkout a new branch at current detached head state:
git checkout -b newBranch

You can read more about detached head state at the official Linux Kernel Git docs for checkout.

Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

public IActionResult AddURLTest()
{
    return ViewComponent("AddURL");
}

You can load it using JQuery load method.

$(document).ready (function(){
    $("#LoadSignIn").click(function(){
        $('#UserControl').load("/Home/AddURLTest");
    });
});

source code link

How to get the CUDA version?

Open a terminal and run these commands:

cd /usr/local/cuda/samples/1_Utilities/deviceQuery
sudo make
./deviceQuery

You can get the information of CUDA Driver version, CUDA Runtime Version, and also detailed information for GPU(s). An image example of the output from my end is as below.

You can find the image here.

How to annotate MYSQL autoincrement field with JPA annotations

same as pascal answered, just if you need to use .AUTO for some reason you just need to add in your application properties:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto = update

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

After installing Postgresql I did the below steps.

  1. open the file pg_hba.conf for Ubuntu it will be in /etc/postgresql/9.x/main and change this line:

    local   all             postgres                                peer

    to

    local   all             postgres                                trust
  2. Restart the server

    $ sudo service postgresql restart
    
  3. Login into psql and set your password

    $ psql -U postgres
    db> ALTER USER postgres with password 'your-pass';
    
  4. Finally change the pg_hba.conf from

    local   all             postgres                                trust

    to

    local   all             postgres                                md5

After restarting the postgresql server, you can access it with your own password

Authentication methods details:

trust - anyone who can connect to the server is authorized to access the database

peer - use client's operating system user name as database user name to access it.

md5 - password-base authentication

for further reference check here

Developing for Android in Eclipse: R.java not regenerating

If your AndroidManifest.xml file is referencing String constants that you have stored in strings.xml, and you rename those Strings in strings.xml, you'll need to change them in the manifest to make everything kosher for a build.

The same would go for any layout .xml files that are referencing those constants you changed. Unfortunately, neither the Markers view nor the Problems view in Eclipse will tell you where you need to go to fix the issues--just that they can't find R.java. As mentioned in other answers, look at the Console to see where you need to fix your constant references, and then clean your project again.

Where to find Java JDK Source Code?

Well, I opened terminal in my Mac and type: "echo $JAVA_HOME" then I got the directory, went there and found src.zip

node and Error: EMFILE, too many open files

This will probably fix your problem if you're struggling to deploy a React solution that was created with the Visual Studio template (and has a web.config). In Azure Release Pipelines, when selecting the template, use:

Azure App Service deployment

Instead of:

Deploy a Node.js app to Azure App Service

It worked for me!

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

Size-limited queue that holds last N elements in Java

Ok I'll share this option. This is a pretty performant option - it uses an array internally - and reuses entries. It's thread safe - and you can retrieve the contents as a List.

static class FixedSizeCircularReference<T> {
    T[] entries

    FixedSizeCircularReference(int size) {
        this.entries = new Object[size] as T[]
        this.size = size
    }
    int cur = 0
    int size

    synchronized void add(T entry) {
        entries[cur++] = entry
        if (cur >= size) {
            cur = 0
        }
    }

    List<T> asList() {
        int c = cur
        int s = size
        T[] e = entries.collect() as T[]
        List<T> list = new ArrayList<>()
        int oldest = (c == s - 1) ? 0 : c
        for (int i = 0; i < e.length; i++) {
            def entry = e[oldest + i < s ? oldest + i : oldest + i - s]
            if (entry) list.add(entry)
        }
        return list
    }
}

Hive query output to file

This will put the results in tab delimited file(s) under a directory:

INSERT OVERWRITE LOCAL DIRECTORY '/home/hadoop/YourTableDir'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
SELECT * FROM table WHERE id > 100;

What are .dex files in Android?

dex file is a file that is executed on the Dalvik VM.

Dalvik VM includes several features for performance optimization, verification, and monitoring, one of which is Dalvik Executable (DEX).

Java source code is compiled by the Java compiler into .class files. Then the dx (dexer) tool, part of the Android SDK processes the .class files into a file format called DEX that contains Dalvik byte code. The dx tool eliminates all the redundant information that is present in the classes. In DEX all the classes of the application are packed into one file. The following table provides comparison between code sizes for JVM jar files and the files processed by the dex tool.

The table compares code sizes for system libraries, web browser applications, and a general purpose application (alarm clock app). In all cases dex tool reduced size of the code by more than 50%.

enter image description here

In standard Java environments each class in Java code results in one .class file. That means, if the Java source code file has one public class and two anonymous classes, let’s say for event handling, then the java compiler will create total three .class files.

The compilation step is same on the Android platform, thus resulting in multiple .class files. But after .class files are generated, the “dx” tool is used to convert all .class files into a single .dex, or Dalvik Executable, file. It is the .dex file that is executed on the Dalvik VM. The .dex file has been optimized for memory usage and the design is primarily driven by sharing of data.

Exporting PDF with jspdf not rendering CSS

As I know jsPDF is not working with CSS and the same issue I was facing.

To solve this issue, I used Html2Canvas. Just Add HTML2Canvas JS and then use pdf.addHTML() instead of pdf.fromHTML().

Here's my code (no other code):

 var pdf = new jsPDF('p', 'pt', 'letter');
 pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
     pdf.save('Test.pdf');
 });

Best of Luck!

Edit: Refer to this line in case you didn't find .addHTML()

Maximum number of threads per process in Linux?

To retrieve it:

cat /proc/sys/kernel/threads-max

To set it:

echo 123456789 | sudo tee -a /proc/sys/kernel/threads-max

123456789 = # of threads

Center content in responsive bootstrap navbar

Seems like all these answers involve custom css on top of bootstrap. The answer I am providing utilizes only bootstrap so I hope it comes to use for those that want to limit customizations.

This was tested with Bootstrap V3.3.7

<footer class="navbar-default navbar-fixed-bottom">
    <div class="container-fluid">
        <div class="row">
            <div class="col-xs-offset-5 col-xs-2 text-center">
                <p>I am centered text<p>
            </div>
            <div class="col-xs-5"></div>
        </div>
    </div>
</footer>

How to get the list of all printers in computer

If you are working with MVC C#, this is the way to deal with printers and serial ports for dropdowns.

using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;

    public class Miclass
    {
        private void AllViews()
        {
            List<PortClass> ports = new List<PortClass>();
            List<Printersclass> Printersfor = new List<Printersclass>();
            string[] portnames = SerialPort.GetPortNames();
            /*PORTS*/
            for (int i = 0; i < portnames.Count(); i++)
            {
                ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
            }
            /*PRINTER*/
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
            }
        }
    }
    public class PortClass
    {
        public string Name { get; set; }
        public string Desc { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Desc);
        }
    }
    public class Printersclass
    {
        public string Name { get; set; }
        public string Desc { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Desc);
        }
    }

Git merge errors

git commit -m "Merged master fixed conflict."

Convert string to decimal number with 2 decimal places in Java

Float.parseFloat() is the problem as it returns a new float.

Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.

You are formatting just for the purpose of display . It doesn't mean the float will be represented by the same format internally .

You can use java.lang.BigDecimal.

I am not sure why are you using parseFloat() twice. If you want to display the float in a certain format then just format it and display it.

Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
System.out.println("liters of petrol before putting in editor"+df.format(litersOfPetrol));

Delete specific values from column with where condition?

You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */

Refresh (reload) a page once using jQuery?

For refreshing page with javascript, you can simply use:

location.reload();

From milliseconds to hour, minutes, seconds and milliseconds

Good question. Yes, one can do this more efficiently. Your CPU can extract both the quotient and the remainder of the ratio of two integers in a single operation. In <stdlib.h>, the function that exposes this CPU operation is called div(). In your psuedocode, you'd use it something like this:

function to_tuple(x):
    qr = div(x, 1000)
    ms = qr.rem
    qr = div(qr.quot, 60)
    s  = qr.rem
    qr = div(qr.quot, 60)
    m  = qr.rem
    h  = qr.quot

A less efficient answer would use the / and % operators separately. However, if you need both quotient and remainder, anyway, then you might as well call the more efficient div().

PostgreSQL: Why psql can't connect to server?

So for me and my pals working on a Node.js app (with Postgres and Sequelize), we had to

  1. brew install postgresql (one of us was missing postgres, one of us was not, and yet we were getting the same error msg as listed above)

  2. brew services start postgresql **** (utilize Homebrew to start postgres)

  3. createdb <name of database in config.json file>

  4. node_modules/.bin/sequelize db:migrate

  5. npm start

log4j logging hierarchy order

Use the force, read the source (excerpt from the Priority and Level class compiled, TRACE level was introduced in version 1.2.12):

public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT  = 30000;
public final static int INFO_INT  = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000; 
public final static int ALL_INT = Integer.MIN_VALUE; 

or the log4j API for the Level class, which makes it quite clear.

When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger object (based on configuration) and compares it with the LogEvent's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent's level is greater or equal to the Logger's level, the LogEvent is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.

Laravel form html with PUT method for PUT routes

If you are using HTML Form element instead Laravel Form Builder, you must place method_field between your form opening tag and closing end. By doing this you may explicitly define form method type.

<form>
{{ method_field('PUT') }}
</form>

How to use JQuery with ReactJS

To install it, just run the command

npm install jquery

or

yarn add jquery

then you can import it in your file like

import $ from 'jquery';

How to disable or enable viewpager swiping in android

I found another solution that worked for me follow this link

https://stackoverflow.com/a/42687397/4559365

It basically overrides the method canScrollHorizontally to disable swiping by finger. Howsoever setCurrentItem still works.

How to create own dynamic type or dynamic object in C#?

 var data = new { studentId = 1, StudentName = "abc" };  

Or value is present

  var data = new { studentId, StudentName };

How can I get a list of all open named pipes in Windows?

I stumbled across a feature in Chrome that will list out all open named pipes by navigating to "file://.//pipe//"

Since I can't seem to find any reference to this and it has been very helpful to me, I thought I might share.

Using cURL with a username and password?

To let the password least not pop up in your .bash_history:

curl -u user:$(cat .password-file) http://example-domain.tld

preventDefault() on an <a> tag

Yet another way of doing this in Javascript using inline onclick, IIFE, event and preventDefault():

<a href='#' onclick="(function(e){e.preventDefault();})(event)">Click Me</a>

Parse large JSON file in Nodejs

To process a file line-by-line, you simply need to decouple the reading of the file and the code that acts upon that input. You can accomplish this by buffering your input until you hit a newline. Assuming we have one JSON object per line (basically, format B):

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var buf = '';

stream.on('data', function(d) {
    buf += d.toString(); // when data is read, stash it in a string buffer
    pump(); // then process the buffer
});

function pump() {
    var pos;

    while ((pos = buf.indexOf('\n')) >= 0) { // keep going while there's a newline somewhere in the buffer
        if (pos == 0) { // if there's more than one newline in a row, the buffer will now start with a newline
            buf = buf.slice(1); // discard it
            continue; // so that the next iteration will start with data
        }
        processLine(buf.slice(0,pos)); // hand off the line
        buf = buf.slice(pos+1); // and slice the processed data off the buffer
    }
}

function processLine(line) { // here's where we do something with a line

    if (line[line.length-1] == '\r') line=line.substr(0,line.length-1); // discard CR (0x0D)

    if (line.length > 0) { // ignore empty lines
        var obj = JSON.parse(line); // parse the JSON
        console.log(obj); // do something with the data here!
    }
}

Each time the file stream receives data from the file system, it's stashed in a buffer, and then pump is called.

If there's no newline in the buffer, pump simply returns without doing anything. More data (and potentially a newline) will be added to the buffer the next time the stream gets data, and then we'll have a complete object.

If there is a newline, pump slices off the buffer from the beginning to the newline and hands it off to process. It then checks again if there's another newline in the buffer (the while loop). In this way, we can process all of the lines that were read in the current chunk.

Finally, process is called once per input line. If present, it strips off the carriage return character (to avoid issues with line endings – LF vs CRLF), and then calls JSON.parse one the line. At this point, you can do whatever you need to with your object.

Note that JSON.parse is strict about what it accepts as input; you must quote your identifiers and string values with double quotes. In other words, {name:'thing1'} will throw an error; you must use {"name":"thing1"}.

Because no more than a chunk of data will ever be in memory at a time, this will be extremely memory efficient. It will also be extremely fast. A quick test showed I processed 10,000 rows in under 15ms.

What is "origin" in Git?

The top answer is great.

I would just add, that it becomes easy to understand if you think about remotes as locations other than your computer that you may want to move your code to.

Some very good examples are:

  • GitHub
  • A server to host your app

So you can certainly have multiple remotes. A very common pattern is to use GitHub to store your code, and a server to host your application (if it's a web application). Then you would have 2 remotes (possibly more if you have other environments).

Try opening your git config by typing git config -e

Note: press escape, then :, then q then enter to quit out

Example

Here's what you might see in your git configs if you had 3 remotes. In this example, 1 remote (called 'origin') is GitHub, another remote (called 'staging') is a staging server, and the third (called 'heroku') is a production server.

[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true
[remote "origin"]
        url = https://github.com/username/reponame.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master
[remote "heroku"]
        url = https://git.heroku.com/appname.git
        fetch = +refs/heads/*:refs/remotes/heroku/*
[remote "staging"]
        url = https://git.heroku.com/warm-bedlands-98000.git
        fetch = +refs/heads/*:refs/remotes/staging/*

The three lines starting with [remote ... show us the remotes we can push to.

Running git push origin will push to the url for '[remote "origin"]', i.e. to GitHub

But similarly, we could push to another remote, say, '[remote "staging"]', with git push staging, then it would push to https://git.heroku.com/warm-bedlands-98000.git.

In the example above, we can see the 3 remotes with git remote:

git remote   
heroku
origin
staging

Summary or origin

Remotes are simply places on the internet that you may have a reason to send your code to. GitHub is an obvious place, as are servers that host your app, and you may have other locations too. git push origin simply means it will push to 'origin', which is the name GitHub chooses to default to.

As for branchname

branchname is simply what you're pushing to the remote. According the git push help docs, the branchname argument is technically a refspec, which, for practical purposes, is the branch you want to push.

  • Read more in the docs for git push by running: git push --help

Connect to network drive with user name and password

The best way to do this is to p/invoke WNetUseConnection.

[StructLayout(LayoutKind.Sequential)] 
private class NETRESOURCE
{ 
        public int dwScope = 0;
        public int dwType = 0;
        public int dwDisplayType = 0;
        public int dwUsage = 0;
        public string lpLocalName = "";
        public string lpRemoteName = "";
        public string lpComment = "";
        public string lpProvider = "";
}


[DllImport("Mpr.dll")] 
private static extern int WNetUseConnection(
            IntPtr hwndOwner,
            NETRESOURCE lpNetResource,
            string lpPassword,
            string lpUserID,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
        );

Example code here.

Re-order columns of table in Oracle

I followed the solution above from Jonas and it worked well until I needed to add a second column. What I found is that when making the columns visible again Oracle does not necessarily set them visible in the order listed in the statement.

To demonstrate this follow Jonas' example above. As he showed, once the steps are complete the table is in the order that you'd expect. Things then break down when you add another column as shown below:

Example (continued from Jonas'):

Add another column which is to be inserted before column C.

ALTER TABLE t ADD (b2 INT);

Use the technique demonstrated above to move the newly added B2 column before column C.

ALTER TABLE t MODIFY (c INVISIBLE, d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY (c VISIBLE, d VISIBLE, e VISIBLE);

DESCRIBE t;

Name
----
A
B
B2
D
E
C

As shown above column C has moved to the end. It seems that the ALTER TABLE statement above processed the columns in the order D, E, C rather than in the order specified in the statement (perhaps in physical table order). To ensure that the column is placed where desired it is necessary to make the columns visible one by one in the desired order.

ALTER TABLE t MODIFY (c INVISIBLE, d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY c VISIBLE;
ALTER TABLE t MODIFY d VISIBLE;
ALTER TABLE t MODIFY e VISIBLE;

DESCRIBE t;

Name
----
A
B
B2
C
D
E

How to determine when Fragment becomes visible in ViewPager

Only this worked for me!! and setUserVisibleHint(...) is now deprecated (I attached docs at end), which means any other answer is deprecated ;-)

public class FragmentFirewall extends Fragment {
    /**
     * Required cause "setMenuVisibility(...)" is not guaranteed to be
     * called after "onResume()" and/or "onCreateView(...)" method.
     */
    protected void didVisibilityChange() {
        Activity activity = getActivity();
        if (isResumed() && isMenuVisible()) {
            // Once resumed and menu is visible, at last
            // our Fragment is really visible to user.
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        didVisibilityChange();
    }

    @Override
    public void setMenuVisibility(boolean visible) {
        super.setMenuVisibility(visible);
        didVisibilityChange();
    }
}

Tested and works with NaviagationDrawer as well, there isMenuVisible() will always return true (and onResume() seems enough, but we want to support ViewPager too).

setUserVisibleHint is deprecated. If overriding this method, behavior implemented when passing in true should be moved to Fragment.onResume(), and behavior implemented when passing in false should be moved to Fragment.onPause().

Using DISTINCT inner join in SQL

I believe your 1:m relationships should already implicitly create DISTINCT JOINs.

But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.

SELECT DISTINCT a.valueA, c.valueC
FROM C
    INNER JOIN B ON B.lookupC = C.id
    INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC

Inconsistent Accessibility: Parameter type is less accessible than method

If sounds like the type ACTInterface is not public, but is using the default accessibility of either internal (if it is top-level) or private (if it is nested in another type).

Giving the type the public modifier would fix it.

Another approach is to make both the type and the method internal, if that is your intent.

The issue is not the accessibility of the field (oActInterface), but rather of the type ACTInterface itself.

Android SDK manager won't open

There are many reasons as to why the SDK Manager won't open. Rather than trying each one of them blindly, I recommend running the android.bat in a command window so you can read the error message and apply the correct fix.

Java program to find the largest & smallest number in n numbers without using arrays

public static void main(String[] args) {
    int smallest = 0;
    int large = 0;
    int num;
    System.out.println("enter the number");//how many number you want to enter
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    num = input.nextInt();
    smallest = num; //assume first entered number as small one
    // i starts from 2 because we already took one num value
    for (int i = 2; i < n; i++) {
        num = input.nextInt();
        //comparing each time entered number with large one
        if (num > large) {
            large = num;
        }
        //comparing each time entered number with smallest one
        if (num < smallest) {
            smallest = num;
        }
    }
    System.out.println("the largest is:" + large);
    System.out.println("Smallest no is : " + smallest);
}

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

Delimiter must not be alphanumeric or backslash and preg_match

You need a delimiter for your pattern. It should be added at the start and end of the pattern like so:

$pattern = "/My name is '(.*)' and im fine/";  // With / as a delimeter 

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Call Class Method From Another Class

update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

class A(object):
    def method1(self, a, b, c):
        # foo

method = A.method1

method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

a = A()
method = a.method1
method(1, 2)

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
  3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

Some examples:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
    def method1(self, a, b):
        return a + b

    @staticmethod
    def method2(a, b):
        return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

t = Test1()  # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2)        # form two (the common one) essentially reduces to form one

Test1.method2(1, 2)  #the static method can be called with just arguments
t.method2(1, 2)      # on an instance or the class

Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
t.method3(1, 2)      # that it's called on (the subclass if called on a subclass) 
                     # but will not have access to the instance it's called on 
                     # (if it is called on an instance)

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

React-Router: No Not Found Route?

According to the documentation, the route was found, even though the resource wasn't.

Note: This is not intended to be used for when a resource is not found. There is a difference between the router not finding a matched path and a valid URL that results in a resource not being found. The url courses/123 is a valid url and results in a matched route, therefore it was "found" as far as routing is concerned. Then, if we fetch some data and discover that the course 123 does not exist, we do not want to transition to a new route. Just like on the server, you go ahead and serve the url but render different UI (and use a different status code). You shouldn't ever try to transition to a NotFoundRoute.

So, you could always add a line in the Router.run() before React.render() to check if the resource is valid. Just pass a prop down to the component or override the Handler component with a custom one to display the NotFound view.

Unix ls command: show full path when using options

simply use find tool.

find absolute_path

displays full paths on my Linux machine, while

find relative_path

will not.

How to list all AWS S3 objects in a bucket using Java

Gray your solution was strange but you seem like a nice guy.

AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials( ....

ObjectListing images = s3Client.listObjects(bucketName); 

List<S3ObjectSummary> list = images.getObjectSummaries();
for(S3ObjectSummary image: list) {
    S3Object obj = s3Client.getObject(bucketName, image.getKey());
    writeToFile(obj.getObjectContent());
}

Firefox 'Cross-Origin Request Blocked' despite headers

In my case CORS error was happening only in POST requests with file attachments other than small files.

After many wasted hours we found out request was blocked for users who were using Kaspersky Total Control.

It's possible that other antivirus or firewall software may cause similar problems. Kaspersky run some security tests for requests, but omits them for websites with SSL EV certificate, so obtaining such certificate should resolve this issue properly.

Disabling protection for your domain is a bit tricky, so here are required steps (as for December 2020): Settings -> Network Settings -> Manage exclusions -> Add -> your domain -> Save

The good thing is you can detect such blocked request. The error is empty – it doesn't have status and response. This way you can assume it was blocked by third party software and show some info.