Programs & Examples On #Bubble sort

Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. It is little used in industry but useful in teaching.

Simple bubble sort c#

    static bool BubbleSort(ref List<int> myList, int number)
    {
        if (number == 1)
            return true;
        for (int i = 0; i < number; i++)
        {
            if ((i + 1 < number) && (myList[i] > myList[i + 1]))
            {
                int temp = myList[i];
                myList[i] = myList[i + 1];
                myList[i + 1] = temp;
            }
            else
                continue;
        }
        return BubbleSort(ref myList, number - 1);
    }

Bubble Sort Homework

def bubbleSort(alist):
if len(alist) <= 1:
    return alist
for i in range(0,len(alist)):
   print "i is :%d",i
   for j in range(0,i):
      print "j is:%d",j
      print "alist[i] is :%d, alist[j] is :%d"%(alist[i],alist[j])
      if alist[i] > alist[j]:
         alist[i],alist[j] = alist[j],alist[i]
return alist

alist = [54,26,93,17,77,31,44,55,20,-23,-34,16,11,11,11]

print bubbleSort(alist)

github markdown colspan

You can use HTML tables on GitHub (but not on StackOverflow)

<table>
  <tr>
    <td>One</td>
    <td>Two</td>
  </tr>
  <tr>
    <td colspan="2">Three</td>
  </tr>
</table>

Becomes

HTML table output

How do I change the JAVA_HOME for ant?

You will need to change JAVA_HOME path to the Java SDK directory instead of the Java RE directory. In Windows you can do this using the set command in a command prompt.

e.g.

set JAVA_HOME="C:\Program Files\Java\jdk1.6.0_14"

What is an example of the simplest possible Socket.io example?

i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.

every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.

this just returns a string passed from the console UPPERCASED.

app.js

var http = require('http');

var app = http.createServer(function(req, res) {
        console.log('createServer');
});
app.listen(3000);

var io = require('socket.io').listen(app);


io.on('connection', function(socket) {
    io.emit('Server 2 Client Message', 'Welcome!' );

    socket.on('Client 2 Server Message', function(message)      {
        console.log(message);
        io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
    });

});

index.html:

<!doctype html>
<html>
    <head>
        <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script type='text/javascript'>
                var socket = io.connect(':3000');
                 // optionally use io('http://localhost:3000');
                 // but make *SURE* it matches the jScript src
                socket.on ('Server 2 Client Message',
                     function(messageFromServer)       {
                        console.log ('server said: ' + messageFromServer);
                     });

        </script>
    </head>
    <body>
        <h5>Worlds smallest Socket.io example to uppercase strings</h5>
        <p>
        <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                <br />
                socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
        </p>
    </body>
</html>

to run:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &

use something like this port test to ensure your port is open.

now browse to http://localhost/index.html and use your browser console to send messages back to the server.

at best guess, when using http.createServer, it changes the following two lines for you:

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

How to center the content inside a linear layout?

Here's some sample code. This worked for me.

<LinearLayout
    android:gravity="center"
    >
    <TextView
        android:layout_gravity="center"
        />
    <Button
        android:layout_gravity="center"
        />
</LinearLayout>

So you're designing the Linear Layout to place all its contents (TextView and Button) in its center, and then the TextView and Button are placed relative to the center of the Linear Layout.

How to open a file for both reading and writing?

Summarize the I/O behaviors

|          Mode          |  r   |  r+  |  w   |  w+  |  a   |  a+  |
| :--------------------: | :--: | :--: | :--: | :--: | :--: | :--: |
|          Read          |  +   |  +   |      |  +   |      |  +   |
|         Write          |      |  +   |  +   |  +   |  +   |  +   |
|         Create         |      |      |  +   |  +   |  +   |  +   |
|         Cover          |      |      |  +   |  +   |      |      |
| Point in the beginning |  +   |  +   |  +   |  +   |      |      |
|    Point in the end    |      |      |      |      |  +   |  +   |

and the decision branch

enter image description here

Import SQL dump into PostgreSQL database

Just for funsies, if your dump is compressed you can do something like

gunzip -c filename.gz | psql dbname

As Jacob mentioned, the PostgreSQL docs describe all this quite well.

How to get the seconds since epoch from the time + date output of gmtime()?

If you got here because a search engine told you this is how to get the Unix timestamp, stop reading this answer. Scroll down one.

If you want to reverse time.gmtime(), you want calendar.timegm().

>>> calendar.timegm(time.gmtime())
1293581619.0

You can turn your string into a time tuple with time.strptime(), which returns a time tuple that you can pass to calendar.timegm():

>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))
1247169778

More information about calendar module here

Adding Table rows Dynamically in Android

public Boolean addArtist(String artistName){

        SQLiteDatabase db= getWritableDatabase();

        ContentValues data=new ContentValues();
        data.put(ArtistMaster.ArtistDetails.COLUMN_ARTIST_NAME,artistName);
        long id = db.insert(ArtistMaster.ArtistDetails.TABLE_NAME,null,data);

        if(id>0){
            return true;
        }else{
            return false;
        }
    }

Intellij Cannot resolve symbol on import

file-> Project Structure -> Modules, find the module with problems, click it and choose the Dependencies tab in the right side. Click the green plus sign, try to add the jar or libraries that cause the problem. That works for me.

How to change checkbox's border style in CSS?

Here is a pure CSS (no images) cross-browser solution based on Martin's Custom Checkboxes and Radio Buttons with CSS3 LINK: http://martinivanov.net/2012/12/21/imageless-custom-checkboxes-and-radio-buttons-with-css3-revisited/

Here is a jsFiddle: http://jsfiddle.net/DJRavine/od26wL6n/

I have tested this on the following browsers:

  • FireFox (41.0.2) (42)
  • Google Chrome (46.0.2490.80 m)
  • Opera (33.0.1990.43)
  • Internet Explorer (11.0.10240.16431 [Update Versions: 11.0.22])
  • Microsoft Edge (20.10240.16384.0)
  • Safari Mobile iPhone iOS9 (601.1.46)

_x000D_
_x000D_
label,_x000D_
input[type="radio"] + span,_x000D_
input[type="radio"] + span::before,_x000D_
label,_x000D_
input[type="checkbox"] + span,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
 _x000D_
label *,_x000D_
label *_x000D_
{_x000D_
    cursor: pointer;_x000D_
}_x000D_
 _x000D_
input[type="radio"],_x000D_
input[type="checkbox"]_x000D_
{_x000D_
    opacity: 0;_x000D_
    position: absolute;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span,_x000D_
input[type="checkbox"] + span_x000D_
{_x000D_
    font: normal 11px/14px Arial, Sans-serif;_x000D_
    color: #333;_x000D_
}_x000D_
 _x000D_
label:hover span::before,_x000D_
label:hover span::before_x000D_
{_x000D_
    -moz-box-shadow: 0 0 2px #ccc;_x000D_
    -webkit-box-shadow: 0 0 2px #ccc;_x000D_
    box-shadow: 0 0 2px #ccc;_x000D_
}_x000D_
 _x000D_
label:hover span,_x000D_
label:hover span_x000D_
{_x000D_
    color: #000;_x000D_
}_x000D_
 _x000D_
input[type="radio"] + span::before,_x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    content: "";_x000D_
    width: 12px;_x000D_
    height: 12px;_x000D_
    margin: 0 4px 0 0;_x000D_
    border: solid 1px #a8a8a8;_x000D_
    line-height: 14px;_x000D_
    text-align: center;_x000D_
     _x000D_
    -moz-border-radius: 100%;_x000D_
    -webkit-border-radius: 100%;_x000D_
    border-radius: 100%;_x000D_
     _x000D_
    background: #f6f6f6;_x000D_
    background: -moz-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: -o-radial-gradient(#f6f6f6, #dfdfdf);_x000D_
    background: radial-gradient(#f6f6f6, #dfdfdf);_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before,_x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    color: #666;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:disabled + span,_x000D_
input[type="checkbox"]:disabled + span_x000D_
{_x000D_
    cursor: default;_x000D_
     _x000D_
    -moz-opacity: .4;_x000D_
    -webkit-opacity: .4;_x000D_
    opacity: .4;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"] + span::before_x000D_
{_x000D_
    -moz-border-radius: 2px;_x000D_
    -webkit-border-radius: 2px;_x000D_
    border-radius: 2px;_x000D_
}_x000D_
 _x000D_
input[type="radio"]:checked + span::before_x000D_
{_x000D_
    content: "\2022";_x000D_
    font-size: 30px;_x000D_
    margin-top: -1px;_x000D_
}_x000D_
 _x000D_
input[type="checkbox"]:checked + span::before_x000D_
{_x000D_
    content: "\2714";_x000D_
    font-size: 12px;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="blue"] + span::before_x000D_
{_x000D_
    border: solid 1px blue;_x000D_
    background: #B2DBFF;_x000D_
    background: -moz-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: -o-radial-gradient(#B2DBFF, #dfdfdf);_x000D_
    background: radial-gradient(#B2DBFF, #dfdfdf);_x000D_
}_x000D_
input[class="blue"]:checked + span::before_x000D_
{_x000D_
    color: darkblue;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
input[class="red"] + span::before_x000D_
{_x000D_
    border: solid 1px red;_x000D_
    background: #FF9593;_x000D_
    background: -moz-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -webkit-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -ms-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: -o-radial-gradient(#FF9593, #dfdfdf);_x000D_
    background: radial-gradient(#FF9593, #dfdfdf);_x000D_
}_x000D_
input[class="red"]:checked + span::before_x000D_
{_x000D_
    color: darkred;_x000D_
}
_x000D_
 <label><input type="radio" checked="checked" name="radios-01" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-01" disabled="disabled" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-02"  class="blue" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" class="blue" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-02" disabled="disabled" class="blue" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
_x000D_
 <label><input type="radio" checked="checked" name="radios-03"  class="red" /><span>checked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" class="red" /><span>unchecked radio button</span></label>_x000D_
 <label><input type="radio" name="radios-03" disabled="disabled" class="red" /><span>disabled radio button</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="blue" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="blue" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="blue" /><span>disabled checkbox</span></label>_x000D_
_x000D_
<br/>_x000D_
 _x000D_
<label><input type="checkbox" checked="checked" name="checkbox-01" class="red" /><span>selected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-02" class="red" /><span>unselected checkbox</span></label>_x000D_
<label><input type="checkbox" name="checkbox-03" disabled="disabled" class="red" /><span>disabled checkbox</span></label>
_x000D_
_x000D_
_x000D_

How to create Password Field in Model Django

Use widget as PasswordInput

from django import forms
class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = User

java.net.BindException: Address already in use: JVM_Bind <null>:80

I do a goofy mistake and It take me 2 hour to solve It.I mentioned it here for other persons may be help them.The mistake was I enable ssl connector and changed both https and http ports to same number .

require(vendor/autoload.php): failed to open stream

I was able to resolve by removing composer and reinstalling the proper way. Here is what I did:

I was then able to get composer install to work again. Found my answer at the bottom of this issue: https://github.com/composer/composer/issues/5510

How can I set the default timezone in node.js?

Another approach which seemed to work for me at least in Linux environment is to run your Node.js application like this:

env TZ='Europe/Amsterdam' node server.js

This should at least ensure that the timezone is correctly set already from the beginning.

The remote server returned an error: (403) Forbidden

In my case I remembered that a hole in the firewall was created for this address some time ago, so I had to set useDefaultWebProxy="false" on the binding in the config file, as if the default was to use the proxy if useDefaultWebProxy is not specified.

Is it possible to cast a Stream in Java 8?

Late to the party, but I think it is a useful answer.

flatMap would be the shortest way to do it.

Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())

If o is a Client then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>.

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

The problem happens because in same hibernate session you are trying to save two objects with same identifier.There are two solutions:-

  1. This is happening because you have not configured your mapping.xml file correctly for id fields as below:-

    <id name="id">
      <column name="id" sql-type="bigint" not-null="true"/>
      <generator class="hibernateGeneratorClass"</generator>
    </id>
    
  2. Overload the getsession method to accept a Parameter like isSessionClear, and clear the session before returning the current session like below

    public static Session getSession(boolean isSessionClear) {
        if (session.isOpen() && isSessionClear) {
            session.clear();
            return session;
        } else if (session.isOpen()) {
            return session;
        } else {
            return sessionFactory.openSession();
        }
    }
    

This will cause existing session objects to be cleared and even if hibernate doesn't generate a unique identifier ,assuming you have configured your database properly for a primary key using something like Auto_Increment,it should work for you.

Regular expression for letters, numbers and - _

/^[\w-_.]*$/

What is means By:

  • ^ Start of string

  • [......] Match characters inside

  • \w Any word character so 0-9 a-z A-Z

  • -_. Matched by charecter - and _ and .

  • Zero or more of pattern or unlimited $ End of string If you want to limit the amount of characters:

    /^[\w-_.]{0,5}$/
    

    {0,5} Means 0-5 Numbers & characters

Send and receive messages through NSNotificationCenter in Objective-C?

There is also the possibility of using blocks:

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] 
     addObserverForName:@"notificationName" 
     object:nil
     queue:mainQueue
     usingBlock:^(NSNotification *notification)
     {
          NSLog(@"Notification received!");
          NSDictionary *userInfo = notification.userInfo;

          // ...
     }];

Apple's documentation

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

Tieme put a lot of effort into his excellent answer, but I think the core of the OP's question is how these technologies relate to PHP rather than how each technology works.

PHP is the most used language in web development besides the obvious client side HTML, CSS, and Javascript. Yet PHP has 2 major issues when it comes to real-time applications:

  1. PHP started as a very basic CGI. PHP has progressed very far since its early stage, but it happened in small steps. PHP already had many millions of users by the time it became the embed-able and flexible C library that it is today, most of whom were dependent on its earlier model of execution, so it hasn't yet made a solid attempt to escape the CGI model internally. Even the command line interface invokes the PHP library (libphp5.so on Linux, php5ts.dll on Windows, etc) as if it still a CGI processing a GET/POST request. It still executes code as if it just has to build a "page" and then end its life cycle. As a result, it has very little support for multi-thread or event-driven programming (within PHP userspace), making it currently unpractical for real-time, multi-user applications.

Note that PHP does have extensions to provide event loops (such as libevent) and threads (such as pthreads) in PHP userspace, but very, very, few of the applications use these.

  1. PHP still has significant issues with garbage collection. Although these issues have been consistently improving (likely its greatest step to end the life cycle as described above), even the best attempts at creating long-running PHP applications require being restarted on a regular basis. This also makes it unpractical for real-time applications.

PHP 7 will be a great step to fix these issues as well, and seems very promising as a platform for real-time applications.

What is console.log?

Use console.log to add debugging information to your page.

Many people use alert(hasNinjas) for this purpose but console.log(hasNinjas) is easier to work with. Using an alert pop-ups up a modal dialog box that blocks the user interface.

Edit: I agree with Baptiste Pernet and Jan Hancic that it is a very good idea to check if window.console is defined first so that your code doesn't break if there is no console available.

Calculate a Running Total in SQL Server

In SQL Server 2012 you can use SUM() with the OVER() clause.

select id,
       somedate,
       somevalue,
       sum(somevalue) over(order by somedate rows unbounded preceding) as runningtotal
from TestTable

SQL Fiddle

How to make Bootstrap carousel slider use mobile left/right swipe

Checked solution is not accurate, sometimes mouse-right-click triggers right-swipe. after trying different plugins for swipe i found an almost perfect one.

touchSwipe

i said "almost" because this plugin does not support future elements. so we would have to reinitialize the swipe call when the swipe content is changed by ajax or something. this plugin have lots of options to play with touch events like multi-finger-touch,pinch etc.

http://labs.rampinteractive.co.uk/touchSwipe/demos/index.html

solution 1 :

$("#myCarousel").swipe( {
            swipe:function(event, direction, distance, duration, fingerCount, fingerData) {

                if(direction=='left'){
                    $(this).carousel('next');
                }else if(direction=='right'){
                    $(this).carousel('prev');
                }

            }
        });

solution 2:(for future element case)

function addSwipeTo(selector){
            $(selector).swipe("destroy");
            $(selector).swipe( {
                swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
                    if(direction=='left'){
                        $(this).carousel('next');
                    }else if(direction=='right'){
                        $(this).carousel('prev');
                    }
                }
            });
}
addSwipeTo("#myCarousel");

How to clear browsing history using JavaScript?

No,that would be a security issue.


However, it's possible to clear the history in JavaScript within a Google chrome extension. chrome.history.deleteAll().
Use

window.location.replace('pageName.html');

similar behavior as an HTTP redirect

Read How to redirect to another webpage in JavaScript/jQuery?

Difference between MEAN.js and MEAN.io

They're essentially the same... They both use swig for templating, they both use karma and mocha for tests, passport integration, nodemon, etc.

Why so similar? Mean.js is a fork of Mean.io and both initiatives were started by the same guy... Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about the reasons here.

Now... main (or little) differences you can see right now are:


SCAFFOLDING AND BOILERPLATE GENERATION

Mean.io uses a custom cli tool named 'mean'
Mean.js uses Yeoman Generators


MODULARITY

Mean.io uses a more self-contained node packages modularity with client and server files inside the modules.
Mean.js uses modules just in the front-end (for angular), and connects them with Express. Although they were working on vertical modules as well...


BUILD SYSTEM

Mean.io has recently moved to gulp
Mean.js uses grunt


DEPLOYMENT

Both have Dockerfiles in their respective repos, and Mean.io has one-click install on Google Compute Engine, while Mean.js can also be deployed with one-click install on Digital Ocean.


DOCUMENTATION

Mean.io has ok docs
Mean.js has AWESOME docs


COMMUNITY

Mean.io has a bigger community since it was the original boilerplate
Mean.js has less momentum but steady growth


On a personal level, I like more the philosophy and openness of MeanJS and more the traction and modules/packages approach of MeanIO. Both are nice, and you'll end probably modifying them, so you can't really go wrong picking one or the other. Just take them as starting point and as a learning exercise.


ALTERNATIVE “MEAN” SOLUTIONS

MEAN is a generic way (coined by Valeri Karpov) to describe a boilerplate/framework that takes "Mongo + Express + Angular + Node" as the base of the stack. You can find frameworks with this stack that use other denomination, some of them really good for RAD (Rapid Application Development) and building SPAs. Eg:

You also have Hackathon Starter. It doesn't have A of MEAN (it is 'MEN'), but it rocks..

Have fun!

cin and getline skipping input

The structure of your menu code is the issue:

cin >> choice;   // new line character is left in the stream

 switch ( ... ) {
     // We enter the handlers, '\n' still in the stream
 }

cin.ignore();   // Put this right after cin >> choice, before you go on
                // getting input with getline.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

Perhaps your code is behind Sheet1, so when you change the focus to Sheet2 the objects cannot be found? If that's the case, simply specifying your target worksheet might help:

Sheets("Sheet1").Range("C21").Select

I'm not very familiar with how Select works because I try to avoid it as much as possible :-). You can define and manipulate ranges without selecting them. Also it's a good idea to be explicit about everything you reference. That way, you don't lose track if you go from one sheet or workbook to another. Try this:

Option Explicit

Sub CopySheet1_to_PasteSheet2()

    Dim CLastFundRow As Integer
    Dim CFirstBlankRow As Integer
    Dim wksSource As Worksheet, wksDest As Worksheet
    Dim rngStart As Range, rngSource As Range, rngDest As Range

    Set wksSource = ActiveWorkbook.Sheets("Sheet1")
    Set wksDest = ActiveWorkbook.Sheets("Sheet2")

    'Finds last row of content
    CLastFundRow = wksSource.Range("C21").End(xlDown).Row
    'Finds first row without content
    CFirstBlankRow = CLastFundRow + 1

    'Copy Data
    Set rngSource = wksSource.Range("A2:C" & CLastFundRow)

    'Paste Data Values
    Set rngDest = wksDest.Range("A21")
    rngSource.Copy
    rngDest.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    'Bring back to top of sheet for consistancy
    wksDest.Range("A1").Select

End Sub

Save multiple sheets to .pdf

I recommend adding the following line after the export to PDF:

ThisWorkbook.Sheets("Sheet1").Select

(where eg. Sheet1 is the single sheet you want to be active afterwards)

Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

How do I auto size columns through the Excel interop objects?

Have a look at this article, it's not an exact match to your problem, but suits it:

What's the syntax to import a class in a default package in Java?

It is not a compilation error at all! You can import a default package to a default package class only.

If you do so for another package, then it shall be a compilation error.

Send string to stdin

You were close

/my/bash/script <<< 'This string will be sent to stdin.'

For multiline input, here-docs are suited:

/my/bash/script <<STDIN -o other --options
line 1
line 2
STDIN

Edit To the comments:

To achieve binary input, say

xxd -r -p <<BINARY | iconv -f UCS-4BE -t UTF-8 | /my/bash/script
0000 79c1 0000 306f 0000 3061 0000 3093 0000 3077 0000 3093 0000 304b 0000 3093 0000 3077 0000 3093 0000 306a 0000 8a71 0000 306b 0000 30ca 0000 30f3 0000 30bb
0000 30f3 0000 30b9 0000 3092 0000 7ffb 0000 8a33 0000 3059 0000 308b 0000 3053 0000 3068 0000 304c 0000 3067 0000 304d 0000 000a
BINARY

If you substitute cat for /my/bash/script (or indeed drop the last pipe), this prints:

????????????????????????????

Or, if you wanted something a little more geeky:

0000000: 0000 0000 bef9 0e3c 59f8 8e3c 0a71 d63c  .......<Y..<.q.<
0000010: c6f2 0e3d 3eaa 323d 3a5e 563d 090e 7a3d  ...=>.2=:^V=..z=
0000020: 7bdc 8e3d 2aaf a03d b67e b23d c74a c43d  {..=*..=.~.=.J.=
0000030: 0513 d63d 16d7 e73d a296 f93d a8a8 053e  ...=...=...=...>
0000040: 6583 0e3e 5a5b 173e 5b30 203e 3d02 293e  e..>Z[.>[0 >=.)>
0000050: d4d0 313e f39b 3a3e 6f63 433e 1c27 4c3e  ..1>..:>ocC>.'L>
0000060: cde6 543e 59a2 5d3e 9259 663e 4d0c 6f3e  ..T>Y.]>.Yf>M.o>
0000070: 60ba 773e cf31 803e ee83 843e 78d3 883e  `.w>.1.>...>x..>
0000080: 5720 8d3e 766a 913e beb1 953e 1cf6 993e  W .>vj.>...>...>
0000090: 7a37 9e3e c275 a23e dfb0 a63e bce8 aa3e  z7.>.u.>...>...>
00000a0: 441d af3e 624e b33e 017c b73e 0ca6 bb3e  D..>bN.>.|.>...>
00000b0: 6fcc bf3e 15ef c33e e90d c83e d728 cc3e  o..>...>...>.(.>
00000c0: c93f d03e ac52 d43e 6c61 d83e f36b dc3e  .?.>.R.>la.>.k.>
00000d0: 2f72 e03e 0a74 e43e 7171 e83e 506a ec3e  /r.>.t.>qq.>Pj.>
00000e0: 945e f03e 274e f43e f738 f83e f11e fc3e  .^.>'N.>.8.>...>
00000f0: 0000 003f 09ee 013f 89d9 033f 77c2 053f  ...?...?...?w..?
0000100: caa8 073f 788c 093f 776d 0b3f be4b 0d3f  ...?x..?wm.?.K.?
0000110: 4427 0f3f 0000 113f e8d5 123f f3a8 143f  D'.?...?...?...?
0000120: 1879 163f 4e46 183f 8d10 1a3f cad7 1b3f  .y.?NF.?...?...?
0000130: fe9b 1d3f 1f5d 1f3f 241b 213f 06d6 223f  ...?.].?$.!?.."?
0000140: bb8d 243f 3a42 263f 7cf3 273f 78a1 293f  ..$?:B&?|.'?x.)?
0000150: 254c 2b3f 7bf3 2c3f 7297 2e3f 0138 303f  %L+?{.,?r..?.80?
0000160: 22d5 313f ca6e 333f                      ".1?.n3?

Which is the sines of the first 90 degrees in 4byte binary floats

How to use JavaScript to change div backgroundColor

var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
  this.style.backgroundColor = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
  this.style.backgroundColor = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';
};

Extract Data from PDF and Add to Worksheet

You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)

Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)

Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):

Function getTextFromPDF(ByVal strFilename As String) As String
   Dim objAVDoc As New AcroAVDoc
   Dim objPDDoc As New AcroPDDoc
   Dim objPage As AcroPDPage
   Dim objSelection As AcroPDTextSelect
   Dim objHighlight As AcroHiliteList
   Dim pageNum As Long
   Dim strText As String

   strText = ""
   If (objAvDoc.Open(strFilename, "") Then
      Set objPDDoc = objAVDoc.GetPDDoc
      For pageNum = 0 To objPDDoc.GetNumPages() - 1
         Set objPage = objPDDoc.AcquirePage(pageNum)
         Set objHighlight = New AcroHiliteList
         objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
         Set objSelection = objPage.CreatePageHilite(objHighlight)

         If Not objSelection Is Nothing Then
            For tCount = 0 To objSelection.GetNumText - 1
               strText = strText & objSelection.GetText(tCount)
            Next tCount
         End If
      Next pageNum
      objAVDoc.Close 1
   End If

   getTextFromPDF = strText

End Function

What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.

Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.

Hope that helps!

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

You need to CAST your numeric data to strings before you do string concatenation, so for example use CAST(@Actual_Dims_Lenght AS VARCHAR) instead of just @Actual_Dims_Lenght, &c.

inverting image in Python with OpenCV

Alternatively, you could invert the image using the bitwise_not function of OpenCV:

imagem = cv2.bitwise_not(imagem)

I liked this example.

Rails DB Migration - How To Drop a Table?

Alternative to raising exception or attempting to recreate a now empty table - while still enabling migration rollback, redo etc -

def change
  drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end

How do I check if a directory exists? "is_dir", "file_exists" or both?

Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.

How to change credentials for SVN repository in Eclipse?

It's too simple to change username and password in Eclipse.

Just follow the following steps:

In your Eclipse,

Goto Window -> Show View -> Other -> (Type as) SVN Repositories -> click that(SVN Repositories) -> Right Click SVN Repositories -> Location Properties -> General tab change the following details for credentials.,

that's it.

Google map V3 Set Center to specific Marker

If you want to center map onto a marker and you have the cordinate, something like click on a list item and the map should center on that coordinate then the following code will work:

In HTML:

<ul class="locationList" ng-repeat="LocationDetail in coordinateArray| orderBy:'LocationName'">
   <li>
      <div ng-click="focusMarker(LocationDetail)">
          <strong><div ng-bind="locationDetail.LocationName"></div></strong>
          <div ng-bind="locationDetail.AddressLine"></div>
          <div ng-bind="locationDetail.State"></div>
          <div ng-bind="locationDetail.City"></div>
      <div>
   </li>
</ul>

In Controller:

$scope.focusMarker = function (coords) {
    map.setCenter(new google.maps.LatLng(coords.Latitude, coords.Longitude));
    map.setZoom(14);
}

Location Object:

{
    "Name": "Taj Mahal",
    "AddressLine": "Tajganj",
    "City": "Agra",
    "State": "Uttar Pradesh",
    "PhoneNumber": "1234 12344",
    "Latitude": "27.173891",
    "Longitude": "78.042068"
}

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

Your port must be busy in some Other Process. So you can download TCPView on https://technet.microsoft.com/en-us/sysinternals/bb897437 and kill the process for used port.

If you don't know your port, double click on the server that is not starting and click on Open Server Properties Page and click on glassfish from left column. You will find the ports here.

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Date format in dd/MM/yyyy hh:mm:ss

This can be done as follows :

select CONVERT(VARCHAR(10), GETDATE(), 103) + ' '  + convert(VARCHAR(8), GETDATE(), 14)

Hope it helps

MongoDB distinct aggregation

SQL Query: (group by & count of distinct)

select city,count(distinct(emailId)) from TransactionDetails group by city;

Equivalent mongo query would look like this:

db.TransactionDetails.aggregate([ 
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } 
]);

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

I am not about your PHP configuration but until PHP 5.2.6 , PHP does have some problem with SOAP client :

Bug #41983 - Error Fetching http headers

Bug #41983

Find all paths between two graph nodes

Finding all possible paths is a hard problem, since there are exponential number of simple paths. Even finding the kth shortest path [or longest path] are NP-Hard.

One possible solution to find all paths [or all paths up to a certain length] from s to t is BFS, without keeping a visited set, or for the weighted version - you might want to use uniform cost search

Note that also in every graph which has cycles [it is not a DAG] there might be infinite number of paths between s to t.

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

Python Linked List

The following is what I came up with. It's similer to Riccardo C.'s, in this thread, except it prints the numbers in order instead of in reverse. I also made the LinkedList object a Python Iterator in order to print the list out like you would a normal Python list.

class Node:

    def __init__(self, data=None):
        self.data = data
        self.next = None

    def __str__(self):
        return str(self.data)


class LinkedList:

    def __init__(self):
        self.head = None
        self.curr = None
        self.tail = None

    def __iter__(self):
        return self

    def next(self):
        if self.head and not self.curr:
            self.curr = self.head
            return self.curr
        elif self.curr.next:
            self.curr = self.curr.next
            return self.curr
        else:
            raise StopIteration

    def append(self, data):
        n = Node(data)
        if not self.head:
            self.head = n
            self.tail = n
        else:
            self.tail.next = n
            self.tail = self.tail.next


# Add 5 nodes
ll = LinkedList()
for i in range(1, 6):
    ll.append(i)

# print out the list
for n in ll:
    print n

"""
Example output:
$ python linked_list.py
1
2
3
4
5
"""

Change label text using JavaScript

Use .textContent instead.

I was struggling with changing the value of a label as well, until I tried this.

If this doesn't solve try inspecting the object to see what properties you can set by logging it to the console with console.dir as shown on this question: How can I log an HTML element as a JavaScript object?

Using AJAX to pass variable to PHP and retrieve those using AJAX again

In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.

Try this: var_dump($_REQUEST); and check if you're receiving the values.

How to test a variable is null in python

You can do this in a try and catch block:

try:
    if val is None:
        print("null")
except NameError:
    # throw an exception or do something else

Connecting to Oracle Database through C#?

First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

After installation add a reference of the assembly Oracle.DataAccess.dll.

Your are good to go after this.

using System; 
using Oracle.DataAccess.Client; 

class OraTest
{ 
    OracleConnection con; 
    void Connect() 
    { 
        con = new OracleConnection(); 
        con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>"; 
        con.Open(); 
        Console.WriteLine("Connected to Oracle" + con.ServerVersion); 
    }

    void Close() 
    {
        con.Close(); 
        con.Dispose(); 
    } 

    static void Main() 
    { 
        OraTest ot= new OraTest(); 
        ot.Connect(); 
        ot.Close(); 
    } 
}

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

Getting Date or Time only from a DateTime Object

You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

I had the same issues and i had dialogComponent in EntryComponents and it still did not work. this is how I was able to solve the problem. the link is here to a previously answered post:

https://stackoverflow.com/a/64224799/14385758

How to target the href to div

You can put all your #m1...#m9 divs into .target and display them based on fragment identifier (hash) using :target pseudo-class. It doesn't move the contents between divs, but I think the effect is close to what you wanted to achieve.

Fiddle

HTML

<div class="target">
    <div id="m1">
        dasdasdasd m1
    </div>
    <!-- etc... -->
    <div id="m9">
        dasdasdsgaswa m9
    </div>   
</div>

CSS

.target {
    width:50%;
    height:200px;
    border:solid black 1px; 
}
.target > div {
    display:none;
}

.target > div:target{
    display:block;
}

Change navbar text color Bootstrap

Make it the following:

.nav.navbar-nav.navbar-right li a {
    color: blue;
}

The above will target the specific links, which is what you want, versus styling the entire list blue, which is what you were initially doing. Here is a JsFiddle.

The other way would be creating another class and implementing it like so:

HTML

<li><a href="#" class="color-me"><span class="glyphicon glyphicon-list-alt"></span> R&eacute;sum&eacute;</a></li>

CSS

.color-me{
    color:blue;
}

Also demonstrated in this JsFiddle

Get the height and width of the browser viewport without scrollbars using jquery?

Description

The following will give you the size of the browsers viewport.

Sample

$(window).height();   // returns height of browser viewport
$(window).width();   // returns width of browser viewport

More Information

What is DOM Event delegation?

To understand event delegation first we need to know why and when we actually need or want event delegation.

There may be many cases but let's discuss two big use cases for event delegation. 1. The first case is when we have an element with lots of child elements that we are interested in. In this case, instead of adding an event handler to all of these child elements, we simply add it to the parent element and then determine on which child element the event was fired.

2.The second use case for event delegation is when we want an event handler attached to an element that is not yet in the DOM when our page is loaded. That's, of course, because we cannot add an event handler to something that's not on our page, so in a case of deprecation that we're coding.

Suppose you have a list of 0, 10, or 100 items in the DOM when you load your page, and more items are waiting in your hand to add in the list. So there is no way to attach an event handler for the future elements or those elements are not added in the DOM yet, and also there may be a lot of items, so it wouldn't be useful to have one event handler attached to each of them.

Event Delegation

All right, so in order to talk about event delegation, the first concept that we actually need to talk about is event bubbling.

Event bubbling: Event bubbling means that when an event is fired or triggered on some DOM element, for example by clicking on our button here on the bellow image, then the exact same event is also triggered on all of the parent elements.

enter image description here

The event is first fired on the button, but then it will also be fired on all the parent elements one at a time, so it will also fire on the paragraph to the section the main element and actually all the way up in a DOM tree until the HTML element which is the root. So we say that the event bubbles up inside the DOM tree, and that's why it's called bubbling.

1 2 3 4

Target element: The element on which the event was actually first fired called the target element, so the element that caused the event to happen, is called the target element. In our above example here it's, of course, the button that was clicked. The important part is that this target element is stored as a property in the event object, This means that all the parent elements on which the event will also fire will know the target element of the event, so where the event was first fired.

That brings us to event delegation because if the event bubbles up in the DOM tree, and if we know where the event was fired then we can simply attach an event handler to a parent element and wait for the event to bubble up, and we can then do whatever we intended to do with our target element. This technique is called event delegation. In this example here, we could simply add the event handler to the main element.

All right, so again, event delegation is to not set up the event handler on the original element that we're interested in but to attach it to a parent element and, basically, catch the event there because it bubbles up. We can then act on the element that we're interested in using the target element property.

Example: Now lets assume we have two list item in our page, after adding items in those list programmtically we want to delete one or more items from them. Using event delegation tecnique we can achive our ppurpose easily.

<div class="body">
    <div class="top">

    </div>
    <div class="bottom">
        <div class="other">
            <!-- other bottom elements -->
        </div>
        <div class="container clearfix">
            <div class="income">
                <h2 class="icome__title">Income</h2>
                <div class="income__list">
                    <!-- list items -->
                </div>
            </div>
            <div class="expenses">
                <h2 class="expenses__title">Expenses</h2>
                <div class="expenses__list">
                    <!-- list items -->
                </div>
            </div>
        </div>
    </div>
</div>

Adding items in those list:

const DOMstrings={
        type:{
            income:'inc',
            expense:'exp'
        },
        incomeContainer:'.income__list',
        expenseContainer:'.expenses__list',
        container:'.container'
   }


var addListItem = function(obj, type){
        //create html string with the place holder
        var html, element;
        if(type===DOMstrings.type.income){
            element = DOMstrings.incomeContainer
            html = `<div class="item clearfix" id="inc-${obj.id}">
            <div class="item__description">${obj.descripiton}</div>
            <div class="right clearfix">
                <div class="item__value">${obj.value}</div>
                <div class="item__delete">
                    <button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
                </div>
            </div>
        </div>`
        }else if (type ===DOMstrings.type.expense){
            element=DOMstrings.expenseContainer;
            html = ` <div class="item clearfix" id="exp-${obj.id}">
            <div class="item__description">${obj.descripiton}</div>
            <div class="right clearfix">
                <div class="item__value">${obj.value}</div>
                <div class="item__percentage">21%</div>
                <div class="item__delete">
                    <button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
                </div>
            </div>
        </div>`
        }
        var htmlObject = document.createElement('div');
        htmlObject.innerHTML=html;
        document.querySelector(element).insertAdjacentElement('beforeend', htmlObject);
    }

Delete items:

var ctrlDeleteItem = function(event){
       // var itemId = event.target.parentNode.parentNode.parentNode.parentNode.id;
        var parent = event.target.parentNode;
        var splitId, type, ID;
        while(parent.id===""){
            parent = parent.parentNode
        }
        if(parent.id){
            splitId = parent.id.split('-');
            type = splitId[0];
            ID=parseInt(splitId[1]);
        }

        deleteItem(type, ID);
        deleteListItem(parent.id);
 }

 var deleteItem = function(type, id){
        var ids, index;
        ids = data.allItems[type].map(function(current){
            return current.id;
        });
        index = ids.indexOf(id);
        if(index>-1){
            data.allItems[type].splice(index,1);
        }
    }

  var deleteListItem = function(selectorID){
        var element = document.getElementById(selectorID);
        element.parentNode.removeChild(element);
    }

Get installed applications in a system

Might I suggest you take a look at WMI (Windows Management Instrumentation). If you add the System.Management reference to your C# project, you'll gain access to the class `ManagementObjectSearcher', which you will probably find useful.

There are various WMI Classes for Installed Applications, but if it was installed with Windows Installer, then the Win32_Product class is probably best suited to you.

ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Product");

SQL Server PRINT SELECT (Print a select query result)?

You can also use the undocumented sp_MSforeachtable stored procedure as such if you are looking to do this for every table:

sp_MSforeachtable @command1 ="PRINT 'TABLE NAME: ' + '?' DECLARE @RowCount INT SET @RowCount = (SELECT COUNT(*) FROM ?) PRINT @RowCount" 

Import Excel Spreadsheet Data to an EXISTING sql table?

If you would like a software tool to do this, you might like to check out this step-by-step guide:

"How to Validate and Import Excel spreadsheet to SQL Server database"

http://leansoftware.net/forum/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

Check if string has space in between (or anywhere)

This functions should help you...

bool isThereSpace(String s){
    return s.Contains(" ");
}

How can I programmatically get the MAC address of an iphone

I wanted something to return the address regardless of whether or not wifi was enabled, so the chosen solution didn't work for me. I used another call I found on some forum after some tweaking. I ended up with the following (excuse my rusty C ) :

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>


char*  getMacAddress(char* macAddress, char* ifName) {

int  success;
struct ifaddrs * addrs;
struct ifaddrs * cursor;
const struct sockaddr_dl * dlAddr;
const unsigned char* base;
int i;

success = getifaddrs(&addrs) == 0;
if (success) {
    cursor = addrs;
    while (cursor != 0) {
        if ( (cursor->ifa_addr->sa_family == AF_LINK)
            && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp(ifName,  cursor->ifa_name)==0 ) {
            dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
            base = (const unsigned char*) &dlAddr->sdl_data[dlAddr->sdl_nlen];
            strcpy(macAddress, ""); 
            for (i = 0; i < dlAddr->sdl_alen; i++) {
                if (i != 0) {
                    strcat(macAddress, ":");
                }
                char partialAddr[3];
                sprintf(partialAddr, "%02X", base[i]);
                strcat(macAddress, partialAddr);

            }
        }
        cursor = cursor->ifa_next;
    }

    freeifaddrs(addrs);
}    
return macAddress;
}

And then I would call it asking for en0, as follows:

char* macAddressString= (char*)malloc(18);
NSString* macAddress= [[NSString alloc] initWithCString:getMacAddress(macAddressString, "en0")
                                              encoding:NSMacOSRomanStringEncoding];
free(macAddressString);

How to auto import the necessary classes in Android Studio with shortcut?

Go on the missing declaration with cursor and press alt+enter enter image description here

wp_nav_menu change sub-menu class name?

Here's an update to what Richard did that adds a "depth" indicator. The output is level-0, level-1, level-2, etc.

class UL_Class_Walker extends Walker_Nav_Menu {
  function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"level-".$depth."\">\n";
  }
}

DB2 Date format

select to_char(current date, 'yyyymmdd') from sysibm.sysdummy1

result: 20160510

scp copy directory to another server with private key auth

Putty doesn't use openssh key files - there is a utility in putty suite to convert them.

edit: it is called puttygen

BackgroundWorker vs background Thread

If it ain't broke - fix it till it is...just kidding :)

But seriously BackgroundWorker is probably very similar to what you already have, had you started with it from the beginning maybe you would have saved some time - but at this point I don't see the need. Unless something isn't working, or you think your current code is hard to understand, then I would stick with what you have.

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

@Override    
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
}

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.menuitem1:
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      break;
    case R.id.menuitem2:
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
      break;
  }
  return true;
}

Easiest way to ignore blank lines when reading a file in Python

What about LineSentence module, it will ignore such lines:

Bases: object

Simple format: one sentence = one line; words already preprocessed and separated by whitespace.

source can be either a string or a file object. Clip the file to the first limit lines (or not clipped if limit is None, the default).

from gensim.models.word2vec import LineSentence
text = LineSentence('text.txt')

Counting the number of files in a directory using Java

This might not be appropriate for your application, but you could always try a native call (using jni or jna), or exec a platform-specific command and read the output before falling back to list().length. On *nix, you could exec ls -1a | wc -l (note - that's dash-one-a for the first command, and dash-lowercase-L for the second). Not sure what would be right on windows - perhaps just a dir and look for the summary.

Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long. As this blogger suggests, you may not want to sweat this.

I'd probably go with Varkhan's answer myself.

How can I add a space in between two outputs?

Like this?

 System.out.println(Name + " " + Income);

How to check if a stored procedure exists before creating it

I had the same error. I know this thread is pretty much dead already but I want to set another option besides "anonymous procedure".

I solved it like this:

  1. Check if the stored procedure exist:

    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='my_procedure') BEGIN
        print 'exists'  -- or watever you want
    END ELSE BEGIN
        print 'doesn''texists'   -- or watever you want
    END
    
  2. However the "CREATE/ALTER PROCEDURE' must be the first statement in a query batch" is still there. I solved it like this:

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE -- view procedure function or anything you want ...
    
  3. I end up with this code:

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('my_procedure'))
    BEGIN
        DROP PROCEDURE my_procedure
    END
    
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE PROCEDURE [dbo].my_procedure ...
    

ASP.net page without a code behind

You can actually have all the code in the aspx page. As explained here.

Sample from here:

<%@ Language=C# %>
<HTML>
   <script runat="server" language="C#">
   void MyButton_OnClick(Object sender, EventArgs e)
   {
      MyLabel.Text = MyTextbox.Text.ToString();
   }
   </script>
   <body>
      <form id="MyForm" runat="server">
         <asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox>
         <asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button>
         <asp:label id="MyLabel" runat="server"></asp:label>
      </form>
   </body>
</HTML>

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

This helped us, maybe it can help others in the future. @Transaction was not working for us, but this did:

@ConditionalOnMissingClass("org.springframework.orm.jpa.JpaTransactionManager")

Go to particular revision

Using a commit's SHA1 key, you could do the following:

  • First, find the commit you want for a specific file:

    git log -n <# commits> <file-name>

    This, based on your <# commits>, will generate a list of commits for a specific file.

    TIP: if you aren't sure what commit you are looking for, a good way to find out is using the following command: git diff <commit-SHA1>..HEAD <file-name>. This command will show the difference between the current version of a commit, and a previous version of a commit for a specific file.

    NOTE: a commit's SHA1 key is formatted in the git log -n's list as:

commit <SHA1 id>

  • Second, checkout the desired version:

    If you have found the desired commit/version you want, simply use the command: git checkout <desired-SHA1> <file-name>

    This will place the version of the file you specified in the staging area. To take it out of the staging area simply use the command: reset HEAD <file-name>

To revert back to where the remote repository is pointed to, simply use the command: git checkout HEAD <file-name>

How to debug SSL handshake using cURL?

Actually openssl command is a better tool than curl for checking and debugging SSL. Here is an example with openssl:

openssl s_client -showcerts -connect stackoverflow.com:443 < /dev/null

and < /dev/null is for adding EOL to the STDIN otherwise it hangs on the Terminal.


But if you liked, you can wrap some useful openssl commands with curl (as I did with curly) and make it more human readable like so:

# check if SSL is valid
>>> curly --ssl valid -d stackoverflow.com
Verify return code: 0 (ok)
issuer=C = US
O = Let's Encrypt
CN = R3
subject=CN = *.stackexchange.com

option: ssl
action: valid
status: OK

# check how many days it will be valid 
>>> curly --ssl date -d stackoverflow.com
Verify return code: 0 (ok)
from: Tue Feb  9 16:13:16 UTC 2021
till: Mon May 10 16:13:16 UTC 2021
days total:  89
days passed: 8
days left:   81

option: ssl
action: date
status: OK

# check which names it supports
curly --ssl name -d stackoverflow.com
*.askubuntu.com
*.blogoverflow.com
*.mathoverflow.net
*.meta.stackexchange.com
*.meta.stackoverflow.com
*.serverfault.com
*.sstatic.net
*.stackexchange.com
*.stackoverflow.com
*.stackoverflow.email
*.superuser.com
askubuntu.com
blogoverflow.com
mathoverflow.net
openid.stackauth.com
serverfault.com
sstatic.net
stackapps.com
stackauth.com
stackexchange.com
stackoverflow.blog
stackoverflow.com
stackoverflow.email
stacksnippets.net
superuser.com

option: ssl
action: name
status: OK

# check the CERT of the SSL
>>> curly --ssl cert -d stackoverflow.com
-----BEGIN CERTIFICATE-----
MIIG9DCCBdygAwIBAgISBOh5mcfyJFrMPr3vuAuikAYwMA0GCSqGSIb3DQEBCwUA
MDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD
EwJSMzAeFw0yMTAyMDkxNjEzMTZaFw0yMTA1MTAxNjEzMTZaMB4xHDAaBgNVBAMM
Eyouc3RhY2tleGNoYW5nZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQDRDObYpjCvb2smnCP+UUpkKdSr6nVsIN8vkI6YlJfC4xC72bY2v38lE2xB
LCaL9MzKhsINrQZRIUivnEHuDOZyJ3Xwmxq3wY0qUKo2c963U7ZJpsIFsj37L1Ac
Qp4pubyyKPxTeFAzKbpfwhNml633Ao78Cy/l/sYjNFhMPoBN4LYBX7/WJNIfc3UZ
niMfh230NE2dwoXGqA0MnkPQyFKlIwHcmMb+ZI5T8TziYq0WQiYUY3ssOEu1CI5n
wh0+BTAwpx7XBUe5Z+B9SrFp8BUDYWcWuVEIh2btYvo763mrr+lmm8PP23XKkE4f
287Iwlfg/IqxxIxKv9smFoPkyZcFAgMBAAGjggQWMIIEEjAOBgNVHQ8BAf8EBAMC
BaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAw
HQYDVR0OBBYEFMnjX41T+J1bbLgG9TjR/4CvHLv/MB8GA1UdIwQYMBaAFBQusxe3
WFbLrlAJQOYfr52LFMLGMFUGCCsGAQUFBwEBBEkwRzAhBggrBgEFBQcwAYYVaHR0
cDovL3IzLm8ubGVuY3Iub3JnMCIGCCsGAQUFBzAChhZodHRwOi8vcjMuaS5sZW5j
ci5vcmcvMIIB5AYDVR0RBIIB2zCCAdeCDyouYXNrdWJ1bnR1LmNvbYISKi5ibG9n
b3ZlcmZsb3cuY29tghIqLm1hdGhvdmVyZmxvdy5uZXSCGCoubWV0YS5zdGFja2V4
Y2hhbmdlLmNvbYIYKi5tZXRhLnN0YWNrb3ZlcmZsb3cuY29tghEqLnNlcnZlcmZh
dWx0LmNvbYINKi5zc3RhdGljLm5ldIITKi5zdGFja2V4Y2hhbmdlLmNvbYITKi5z
dGFja292ZXJmbG93LmNvbYIVKi5zdGFja292ZXJmbG93LmVtYWlsgg8qLnN1cGVy
dXNlci5jb22CDWFza3VidW50dS5jb22CEGJsb2dvdmVyZmxvdy5jb22CEG1hdGhv
dmVyZmxvdy5uZXSCFG9wZW5pZC5zdGFja2F1dGguY29tgg9zZXJ2ZXJmYXVsdC5j
b22CC3NzdGF0aWMubmV0gg1zdGFja2FwcHMuY29tgg1zdGFja2F1dGguY29tghFz
dGFja2V4Y2hhbmdlLmNvbYISc3RhY2tvdmVyZmxvdy5ibG9nghFzdGFja292ZXJm
bG93LmNvbYITc3RhY2tvdmVyZmxvdy5lbWFpbIIRc3RhY2tzbmlwcGV0cy5uZXSC
DXN1cGVydXNlci5jb20wTAYDVR0gBEUwQzAIBgZngQwBAgEwNwYLKwYBBAGC3xMB
AQEwKDAmBggrBgEFBQcCARYaaHR0cDovL2Nwcy5sZXRzZW5jcnlwdC5vcmcwggEE
BgorBgEEAdZ5AgQCBIH1BIHyAPAAdgBElGUusO7Or8RAB9io/ijA2uaCvtjLMbU/
0zOWtbaBqAAAAXeHyHI8AAAEAwBHMEUCIQDnzDcCrmCPdfgcb/ojY0WJV1rCj+uE
hCiQi0+4fBP9lgIgSI5mwEqBmVcQwRfKikUzhkH0w6K/6wq0e/1zJA0j5a4AdgD2
XJQv0XcwIhRUGAgwlFaO400TGTO/3wwvIAvMTvFk4wAAAXeHyHIoAAAEAwBHMEUC
IHd0ZLB3j0b31Sh/D3RIfF8C31NxIRSG6m/BFSCGlxSWAiEAvYlgPjrPcBZpX4Xm
SdkF39KbVicTGnFOSAqDpRB3IJwwDQYJKoZIhvcNAQELBQADggEBABZ+2WXyP4w/
A+jJtBgKTZQsA5VhUCabAFDEZdnlWWcV3WYrz4iuJjp5v6kL4MNzAvAVzyCTqD1T
m7EUn/usz59m02mZF82+ELLW6Mqix8krYZTpYt7Hu3Znf6HxiK3QrjEIVlwSGkjV
XMCzOHdALreTkB+UJaL6bEs1sB+9h20zSnZAKrPokGL/XwgxUclXIQXr1uDAShJB
Ts0yjoSY9D687W9sjhq+BIjNYIWg1n9NJ7HM48FWBCDmV3NlCR0Zh1Yx15pXCUhb
UqWd6RzoSLmIfdOxgfi9uRSUe0QTZ9o/Fs4YoMi5K50tfRycLKW+BoYDgde37As5
0pCUFwVVH2E=
-----END CERTIFICATE-----

option: ssl
action: cert
status: OK

How do I move a redis database from one server to another?

The simple way I found to export / Backup Redis data (create dump file ) is to start up a server via command line with slaveof flag and create live replica as follow (assuming the source Redis is 1.2.3.4 on port 6379):

/usr/bin/redis-server --port 6399 --dbfilename backup_of_master.rdb --slaveof 1.2.3.4 6379

Visual Studio 2015 is very slow

Update PC Drivers

In my case, and I had bad lag doing the simplest of things, it helped to update my pc drivers. The system drivers are the foundation for everything.

I was fortunate that I have Dell and they have awesome website support to do this. I googled

dell <my model name> update drivers

or go to the drivers home page

I let it update all the drivers it wanted to (Dell driver update is pretty much automatic).

Much of the lag seems to have gone away.

Removing duplicate rows from table in Oracle

I didn't see any answers that use common table expressions and window functions. This is what I find easiest to work with.

DELETE FROM
 YourTable
WHERE
 ROWID IN
    (WITH Duplicates
          AS (SELECT
               ROWID RID, 
               ROW_NUMBER() 
               OVER(
               PARTITION BY First_Name, Last_Name, Birth_Date)
                  AS RN
               SUM(1)
               OVER(
               PARTITION BY First_Name, Last_Name, Birth_Date
               ORDER BY ROWID ROWS BETWEEN UNBOUNDED PRECEDING 
                                       AND UNBOUNDED FOLLOWING)
                   AS CNT
              FROM
               YourTable
              WHERE
               Load_Date IS NULL)
     SELECT
      RID
     FROM
      duplicates
     WHERE
      RN > 1);

Somethings to note:

1) We are only checking for duplication on the fields in the partition clause.

2) If you have some reason to pick one duplicate over others you can use an order by clause to make that row will have row_number() = 1

3) You can change the number duplicate preserved by changing the final where clause to "Where RN > N" with N >= 1 (I was thinking N = 0 would delete all rows that have duplicates, but it would just delete all rows).

4) Added the Sum partition field the CTE query which will tag each row with the number rows in the group. So to select rows with duplicates, including the first item use "WHERE cnt > 1".

pandas dataframe groupby datetime month

Slightly alternative solution to @jpp's but outputting a YearMonth string:

df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))

res = df.groupby('YearMonth')['Values'].sum()

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource

$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection

if(mysqli_num_rows($result) > 0 ){....}

UPDATE

Base in your edit just change:

if(is_resource($query) && mysqli_num_rows($query) > 0 ){
        $query = mysqli_fetch_assoc($query);
        echo $email . " email exists " .  $query["email"] . "\n";

By

if(is_resource($result) && mysqli_num_rows($result) == 1 ){
        $row = mysqli_fetch_assoc($result);
         echo $email . " email exists " .  $row["email"] . "\n";

and you will be fine

UPDATE 2

A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter

SELECT IF( EXISTS (
                  SELECT *
                  FROM `Table`
                  WHERE `email` = @Email)
          , 1, 0) as `Exist`

and retrieve the value in php

Pseudocodigo:

 $query = Call MYSQL_SP($EMAIL);
 $result = mysqli_query($conn,$query);
 $row = mysqli_fetch_array($result)
 $exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';

How to set border on jPanel?

BorderLayout(int Gap, int Gap) or GridLayout(int Gap, int Gap, int Gap, int Gap)

why paint Border() inside paintComponent( ...)

    Border line, raisedbevel, loweredbevel, title, empty;
    line = BorderFactory.createLineBorder(Color.black);
    raisedbevel = BorderFactory.createRaisedBevelBorder();
    loweredbevel = BorderFactory.createLoweredBevelBorder();
    title = BorderFactory.createTitledBorder("");
    empty = BorderFactory.createEmptyBorder(4, 4, 4, 4);
    Border compound = BorderFactory.createCompoundBorder(empty, xxx);
    Color crl = (Color.blue);
    Border compound1 = BorderFactory.createCompoundBorder(empty, xxx);

Oracle : how to subtract two dates and get minutes of the result

When you subtract two dates in Oracle, you get the number of days between the two values. So you just have to multiply to get the result in minutes instead:

SELECT (date2 - date1) * 24 * 60 AS minutesBetween
FROM ...

Force page scroll position to top at page refresh in HTML

The supercalifragilisticexpialidocious answer is:

add this at the top of your js file or script tag

document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera

document.body.scrollTop = 0; // For Safari

How do I set the default locale in the JVM?

You can enforce VM arguments for a JAR file with the following code:

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class JVMArgumentEnforcer
{
    private String argument;

    public JVMArgumentEnforcer(String argument)
    {
        this.argument = argument;
    }

    public static long getTotalPhysicalMemory()
    {
        com.sun.management.OperatingSystemMXBean bean =
                (com.sun.management.OperatingSystemMXBean)
                        java.lang.management.ManagementFactory.getOperatingSystemMXBean();
        return bean.getTotalPhysicalMemorySize();
    }

    public static boolean isUsing64BitJavaInstallation()
    {
        String bitVersion = System.getProperty("sun.arch.data.model");

        return bitVersion.equals("64");
    }

    private boolean hasTargetArgument()
    {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        List<String> inputArguments = runtimeMXBean.getInputArguments();

        return inputArguments.contains(argument);
    }

    public void forceArgument() throws Exception
    {
        if (!hasTargetArgument())
        {
            // This won't work from IDEs
            if (JARUtilities.isRunningFromJARFile())
            {
                // Supply the desired argument
                restartApplication();
            } else
            {
                throw new IllegalStateException("Please supply the VM argument with your IDE: " + argument);
            }
        }
    }

    private void restartApplication() throws Exception
    {
        String javaBinary = getJavaBinaryPath();
        ArrayList<String> command = new ArrayList<>();
        command.add(javaBinary);
        command.add("-jar");
        command.add(argument);
        String currentJARFilePath = JARUtilities.getCurrentJARFilePath();
        command.add(currentJARFilePath);

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.start();

        // Kill the current process
        System.exit(0);
    }

    private String getJavaBinaryPath()
    {
        return System.getProperty("java.home")
                + File.separator + "bin"
                + File.separator + "java";
    }

    public static class JARUtilities
    {
        static boolean isRunningFromJARFile() throws URISyntaxException
        {
            File currentJarFile = getCurrentJARFile();

            return currentJarFile.getName().endsWith(".jar");
        }

        static String getCurrentJARFilePath() throws URISyntaxException
        {
            File currentJarFile = getCurrentJARFile();

            return currentJarFile.getPath();
        }

        private static File getCurrentJARFile() throws URISyntaxException
        {
            return new File(JVMArgumentEnforcer.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        }
    }
}

It is used as follows:

JVMArgumentEnforcer jvmArgumentEnforcer = new JVMArgumentEnforcer("-Duser.language=pt-BR"); // For example
jvmArgumentEnforcer.forceArgument();

Ant error when trying to build file, can't find tools.jar?

I was having the same problem, none of the posted solutions helped. Finally, I figured out what I was doing wrong. When I installed the Java JDK it asked me for a directiy where I wanted to install. I changed the directory to where I wanted the code to go. It then asked for a directory where it could install the Runtime Environment and I selected the SAME DIRECTORY where I installed the JDK. It over wrote my lib folder and erased the tools.jar. Be sure to use different folders during the install. I used my custom folder for the JDK and the default folder for the RE and everything worked fine.

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

How to find the Windows version from the PowerShell command line

I took the scripts above and tweaked them a little to come up with this:

$name=(Get-WmiObject Win32_OperatingSystem).caption
$bit=(Get-WmiObject Win32_OperatingSystem).OSArchitecture

$vert = " Version:"
$ver=(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ReleaseId

$buildt = " Build:"
$build= (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").BuildLabEx -match '^[0-9]+\.[0-9]+' |  % { $matches.Values }

$installd = Get-ComputerInfo -Property WindowsInstallDateFromRegistry

Write-host $installd
Write-Host $name, $bit, $vert, $ver, `enter code here`$buildt, $build, $installd

To get a result like this:

Microsoft Windows 10 Home 64-bit Version: 1709 Build: 16299.431 @{WindowsInstallDateFromRegistry=18-01-01 2:29:11 AM}

Hint: I'd appreciate a hand stripping the prefix text from the install date so I can replace it with a more readable header.

identifier "string" undefined?

<string.h> is the old C header. C++ provides <string>, and then it should be referred to as std::string.

fork() and wait() with two child processes

brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)

#include <sys/types.h>

jQuery - Disable Form Fields

The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true);

And to enable again you could do

$myForm.find(':input:disabled').prop('disabled',false);

How can I parse a string with a comma thousand separator to a number?

const parseLocaleNumber = strNum => {
    const decSep = (1.1).toLocaleString().substring(1, 2);
    const formatted = strNum
        .replace(new RegExp(`([${decSep}])(?=.*\\1)`, 'g'), '')
        .replace(new RegExp(`[^0-9${decSep}]`, 'g'), '');
    return Number(formatted.replace(decSep, '.'));
};

Iif equivalent in C#

the ternary operator

bool a = true;

string b = a ? "if_true" : "if_false";

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

How do I assign a null value to a variable in PowerShell?

Use $dec = $null

From the documentation:

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

Google Maps: How to create a custom InfoWindow?

Styling the infowindow is fairly straightforward with vanilla javascript. I used some of the info from this thread when writing this. I also took into account the possible problems with earlier versions of ie (although I have not tested it with them).

var infowindow = new google.maps.InfoWindow({
  content: '<div id="gm_content">'+contentString+'</div>'
});

google.maps.event.addListener(infowindow,'domready',function(){
  var el = document.getElementById('gm_content').parentNode.parentNode.parentNode;
  el.firstChild.setAttribute('class','closeInfoWindow');
  el.firstChild.setAttribute('title','Close Info Window');
  el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
  el.setAttribute('class','infoWindowContainer');
  for(var i=0; i<11; i++){
    el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
    el.style.display = 'none';
  }
});

The code creates the infowindow as usual (no need for plugins, custom overlays or huge code), using a div with an id to hold the content. This gives a hook in the system that we can use to get the correct elements to manipulate with a simple external stylesheet.

There are a couple of extra pieces (that are not strictly needed) which handle things like giving a hook into the div with the close info window image in it.

The final loop hides all the pieces of the pointer arrow. I needed this myself as I wanted to have transparency on the infowindow and the arrow got in the way. Of course, with the hook, changing the code to replace the arrow image with a png of your choice should be fairly simple too.

If you want to change it to jquery (no idea why you would) then that should be fairly simple.

I'm not usually a javascript developer so any thoughts, comments, criticisms welcome :)

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

function dateToHowManyAgo(stringDate){
    var currDate = new Date();
    var diffMs=currDate.getTime() - new Date(stringDate).getTime();
    var sec=diffMs/1000;
    if(sec<60)
        return parseInt(sec)+' second'+(parseInt(sec)>1?'s':'')+' ago';
    var min=sec/60;
    if(min<60)
        return parseInt(min)+' minute'+(parseInt(min)>1?'s':'')+' ago';
    var h=min/60;
    if(h<24)
        return parseInt(h)+' hour'+(parseInt(h)>1?'s':'')+' ago';
    var d=h/24;
    if(d<30)
        return parseInt(d)+' day'+(parseInt(d)>1?'s':'')+' ago';
    var m=d/30;
    if(m<12)
        return parseInt(m)+' month'+(parseInt(m)>1?'s':'')+' ago';
    var y=m/12;
    return parseInt(y)+' year'+(parseInt(y)>1?'s':'')+' ago';
}
console.log(dateToHowManyAgo('2019-11-07 19:17:06'));

notifyDataSetChanged not working on RecyclerView

Try this method:

List<Business> mBusinesses2 = mBusinesses;
mBusinesses.clear();
mBusinesses.addAll(mBusinesses2);
//and do the notification

a little time consuming, but it should work.

How do I change the language of moment.js?

for momentjs 2.12+, do the following:

moment.updateLocale('de');

Also note that you must use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale.

How to get the id of the element clicked using jQuery

You can get the id of clicked one by this code

$("span").on("click",function(e){
    console.log(e.target.Id);
});

Use .on() event for future compatibility

Simultaneously merge multiple data.frames in a list

I will reuse the data example from @PaulRougieux

x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)

Here's a short and sweet solution using purrr and tidyr

library(tidyverse)

 list(x, y, z) %>% 
  map_df(gather, key=key, value=value, -i) %>% 
  spread(key, value)

How to disable Google Chrome auto update?

This is just a trick to stop auto update of Google Chrome in Mac OS.

  1. Go to Applications Folder in Finder.
  2. Right click Google Chrome and select Show Package Contents.
  3. Go to Contents directory.
  4. Open Info.plist file with XCode or other text editor.
  5. Change the value of the key: KSUpdateURL to an invalid URL. something like https://tools.google.com/service/invalidurl
  6. Overwrite Info.plist file.
  7. Restart Google Chrome.

Finally go to Google Chrome Settings / About. You will see Update always fails because the update url was set to an invalid one.

Update Always Fails

Using Composer's Autoload

Every package should be responsible for autoloading itself, what are you trying to achieve with autoloading classes that are out of the package you define?

One workaround if it's for your application itself is to add a namespace to the loader instance, something like this:

<?php

$loader = require 'vendor/autoload.php';
$loader->add('AppName', __DIR__.'/../src/');

Only allow Numbers in input Tag without Javascript

Though it's probably suggested to get some heavier validation via JS or on the server, HTML5 does support this via the pattern attribute.

<input type= "text" name= "name" pattern= "[0-9]"  title= "Title"/>

How to download an entire directory and subdirectories using wget?

You may use this in shell:

wget -r --no-parent http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r     //recursive Download

and

--no-parent // Don´t download something from the parent directory

If you don't want to download the entire content, you may use:

-l1 just download the directory (tzivi in your case)

-l2 download the directory and all level 1 subfolders ('tzivi/something' but not 'tivizi/somthing/foo')  

And so on. If you insert no -l option, wget will use -l 5 automatically.

If you insert a -l 0 you´ll download the whole Internet, because wget will follow every link it finds.

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

i was trying the same, so i downloaded the .7zip version of XAMPP with php 5.6.33 from https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/5.6.33/

then followed the steps below: 1. rename c:\xampp\php to c:\xampp\php7 2. raname C:\xampp\apache\conf\extra\httpd-xampp.conf to httpd-xampp7.OLD 3. copy php folder from XAMPP_5.6 7zip archive to c:\xampp\ 4. copy file httpd-xampp.conf from XAMPP_5.6 7zip archive to C:\xampp\apache\conf\extra\

open xampp control panel and start Apache and then visit ( i am using port 82 instead of default 80) http://localhost and then click PHPInfo to see if it is working as expected.

Opening localhost shows dashboard

Opening phpinfo shows version 5.6

Read entire file in Scala?

you can also use Path from scala io to read and process files.

import scalax.file.Path

Now you can get file path using this:-

val filePath = Path("path_of_file_to_b_read", '/')
val lines = file.lines(includeTerminator = true)

You can also Include terminators but by default it is set to false..

Exception: There is already an open DataReader associated with this Connection which must be closed first

Add MultipleActiveResultSets=true to the provider part of your connection string example in the file appsettings.json

"ConnectionStrings": {
"EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=YourDatabasename;Trusted_Connection=true;MultipleActiveResultSets=true"}

Efficient way to do batch INSERTS with JDBC

You can use addBatch and executeBatch for batch insert in java See the Example : Batch Insert In Java

Disable automatic sorting on the first column when using jQuery DataTables

Use this simple code for DataTables custom sorting. Its 100% work

<script>
    $(document).ready(function() {
        $('#myTable').DataTable( {
            "order": [[ 0, "desc" ]] // "0" means First column and "desc" is order type; 
        } );
    } );
</script>


See in Datatables website

https://datatables.net/examples/basic_init/table_sorting.html

What is the difference between user and kernel modes in operating systems?

Other answers already explained the difference between user and kernel mode. If you really want to get into detail you should get a copy of Windows Internals, an excellent book written by Mark Russinovich and David Solomon describing the architecture and inside details of the various Windows operating systems.

Bootstrap 4 Change Hamburger Toggler Color

You can create the toggler button with css only in a very easy way, there is no need to use any fonts in SVG or ... foramt.

Your Button:

<button 
     class="navbar-toggler collapsed" 
    data-target="#navbarsExampleDefault" 
    data-toggle="collapse">
        <span class="line"></span> 
        <span class="line"></span> 
        <span class="line"></span>
</button>

Your Button Style:

.navbar-toggler{
width: 47px;
height: 34px;
background-color: #7eb444;

}

Your horizontal line Style:

.navbar-toggler .line{
width: 100%;
float: left;
height: 2px;
background-color: #fff;
margin-bottom: 5px;

}

Demo

_x000D_
_x000D_
.navbar-toggler{_x000D_
    width: 47px;_x000D_
    height: 34px;_x000D_
    background-color: #7eb444;_x000D_
    border:none;_x000D_
}_x000D_
.navbar-toggler .line{_x000D_
    width: 100%;_x000D_
    float: left;_x000D_
    height: 2px;_x000D_
    background-color: #fff;_x000D_
    margin-bottom: 5px;_x000D_
}
_x000D_
<button class="navbar-toggler" data-target="#navbarsExampleDefault" data-toggle="collapse" aria-expanded="true" >_x000D_
        <span class="line"></span> _x000D_
        <span class="line"></span> _x000D_
        <span class="line" style="margin-bottom: 0;"></span>_x000D_
</button>
_x000D_
_x000D_
_x000D_

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

How to secure MongoDB with username and password

This answer is for Mongo 3.2.1 Reference

Terminal 1:

$ mongod --auth

Terminal 2:

db.createUser({user:"admin_name", pwd:"1234",roles:["readWrite","dbAdmin"]})

if you want to add without roles (optional):

db.createUser({user:"admin_name", pwd:"1234", roles:[]})

to check if authenticated or not:

db.auth("admin_name", "1234")

it should give you:

1

else :

Error: Authentication failed.
0

What's is the difference between train, validation and test set, in neural networks?

In simple words define Training set, Test set, Validation set

Training set: Is used for finding Nearest neighbors. Validation set: Is for finding different k which is applying to train set. Test set: Is used for finding the maximum accuracy and unseen data in future.

java.text.ParseException: Unparseable date

Update your format to:

SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd hh:mm:ss Z yyyy");

How to get a product's image in Magento?

First You need to verify the base, small and thumbnail image are selected in Magento admin.

admin->catalog->manage product->product->image

Then select your image roles(base,small,thumbnail)enter image description here

Then you call the image using

echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(163, 100);

Hope this helps you.

Could not obtain information about Windows NT group user

Active Directory is refusing access to your SQL Agent. The Agent should be running under an account that is recognized by STAR domain controller.

Where can I find MySQL logs in phpMyAdmin?

If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here: http://www.apachefriends.org/en/xampp.html

Make a phone call programmatically

'openURL:' is deprecated: first deprecated in iOS 10.0 - Please use openURL:options:completionHandler: instead

in Objective-c iOS 10+ use :

NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber] options:@{} completionHandler:nil];

How to Iterate over a Set/HashSet without an Iterator?

There are at least six additional ways to iterate over a set. The following are known to me:

Method 1

// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {
  System.out.println(e.nextElement());
}

Method 2

for (String movie : movies) {
  System.out.println(movie);
}

Method 3

String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {
  System.out.println(movieArray[i]);
}

Method 4

// Supported in Java 8 and above
movies.stream().forEach((movie) -> {
  System.out.println(movie);
});

Method 5

// Supported in Java 8 and above
movies.stream().forEach(movie -> System.out.println(movie));

Method 6

// Supported in Java 8 and above
movies.stream().forEach(System.out::println);

This is the HashSet which I used for my examples:

Set<String> movies = new HashSet<>();
movies.add("Avatar");
movies.add("The Lord of the Rings");
movies.add("Titanic");

Disable color change of anchor tag when visited

a {
    color: orange !important;
}

!important has the effect that the property in question cannot be overridden unless another !important is used. It is generally considered bad practice to use !important unless absolutely necessary; however, I can't think of any other way of ‘disabling’ :visited using CSS only.

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

Reliable method to get machine's MAC address in C#

Really hate to dig up this old post but I feel the question deserves another answer specific to windows 8-10.

Using NetworkInformation from the Windows.Networking.Connectivity namespace, you can get the Id of the network adapter windows is using. Then you can get the interface MAC Address from the previously mentioned GetAllNetworkInterfaces().

This will not work in Windows Store Apps as NetworkInterface in System.Net.NetworkInformation does not expose GetAllNetworkInterfaces.

string GetMacAddress()
{
    var connectionProfile = NetworkInformation.GetInternetConnectionProfile();
    if (connectionProfile == null) return "";

    var inUseId = connectionProfile.NetworkAdapter.NetworkAdapterId.ToString("B").ToUpperInvariant();
    if(string.IsNullOrWhiteSpace(inUseId)) return "";

    var mac = NetworkInterface.GetAllNetworkInterfaces()
        .Where(n => inUseId == n.Id)
        .Select(n => n.GetPhysicalAddress().GetAddressBytes().Select(b=>b.ToString("X2")))
        .Select(macBytes => string.Join(" ", macBytes))
        .FirstOrDefault();

    return mac;
}

How to get a single value from FormGroup

You can get value like this

this.form.controls['your form control name'].value

DataTable, How to conditionally delete rows

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5");
foreach (var row in rows)
    row.Delete();

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");

public static DataTable Delete(this DataTable table, string filter)
{
    table.Select(filter).Delete();
    return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
    foreach (var row in rows)
        row.Delete();
}

Error: the entity type requires a primary key

Your Id property needs to have a setter. However the setter can be private. The [Key] attribute is not necessary if the property is named "Id" as it will find it through the naming convention where it looks for a key with the name "Id".

public Guid Id { get; }              // Will not work
public Guid Id { get; set; }         // Will work
public Guid Id { get; private set; } // Will also work

Jquery to change form action

$('#button1').click(function(){
$('#myform').prop('action', 'page1.php');
});

open() in Python does not create a file if it doesn't exist

open('myfile.dat', 'a') works for me, just fine.

in py3k your code raises ValueError:

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

in python-2.6 it raises IOError.

Sublime Text 2 - Show file navigation in sidebar

I added the Context Menu item for Folders to open in Sublime Text. In windows, you can right click on any Folder and open the structure in Sublime. You could also create a service (?) for Mac OS - I'm just not familiar with the process.

The following could be saved to a File (OpenFolderWithSublime.reg) to merge to the registry. Be Sure to modify the directory structure to appropriately point to your Sublime installation. Alternatively, you can use REGEDIT and browse to HKCR\Folder\shell and create the values manually.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text]

[HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text\command]
@="C:\\Program Files\\Sublime Text 2\\sublime_text \"%1\""

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

byte[] strToByteArray(string str)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetBytes(str);
}

Error: Segmentation fault (core dumped)

"Segmentation fault (core dumped)" is the string that Linux prints when a program exits with a SIGSEGV signal and you have core creation enabled. This means some program has crashed.

If you're actually getting this error from running Python, this means the Python interpreter has crashed. There are only a few reasons this can happen:

  1. You're using a third-party extension module written in C, and that extension module has crashed.

  2. You're (directly or indirectly) using the built-in module ctypes, and calling external code that crashes.

  3. There's something wrong with your Python installation.

  4. You've discovered a bug in Python that you should report.

The first is by far the most common. If your q is an instance of some object from some third-party extension module, you may want to look at the documentation.

Often, when C modules crash, it's because you're doing something which is invalid, or at least uncommon and untested. But whether it's your "fault" in that sense or not - that doesn't matter. The module should raise a Python exception that you can debug, instead of crashing. So, you should probably report a bug to whoever wrote the extension. But meanwhile, rather than waiting 6 months for the bug to be fixed and a new version to come out, you need to figure out what you did that triggered the crash, and whether there's some different way to do what you want. Or switch to a different library.

On the other hand, since you're reading and printing out data from somewhere else, it's possible that your Python interpreter just read the line "Segmentation fault (core dumped)" and faithfully printed what it read. In that case, some other program upstream presumably crashed. (It's even possible that nobody crashed—if you fetched this page from the web and printed it out, you'd get that same line, right?) In your case, based on your comment, it's probably the Java program that crashed.

If you're not sure which case it is (and don't want to learn how to do process management, core-file inspection, or C-level debugging today), there's an easy way to test: After print line add a line saying print "And I'm OK". If you see that after the Segmentation fault line, then Python didn't crash, someone else did. If you don't see it, then it's probably Python that's crashed.

PDF Editing in PHP?

We use pdflib to create PDF files from our rails apps. It has bindings for PHP, and a ton of other languages.

We use the commmercial version, but they also have a free/open source version which has some limitations.

Unfortunately, this only allows creation of PDF's.

If you want to open and 'edit' existing files, pdflib do provide a product which does this this, but costs a LOT

Oracle Add 1 hour in SQL

select sysdate + 1/24 from dual;

sysdate is a function without arguments which returns DATE type
+ 1/24 adds 1 hour to a date

select to_char(to_date('2014-10-15 03:30:00 pm', 'YYYY-MM-DD HH:MI:SS pm') + 1/24, 'YYYY-MM-DD HH:MI:SS pm') from dual;

Fastest JSON reader/writer for C++

http://lloyd.github.com/yajl/

http://www.digip.org/jansson/

Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower depending on the library/use case)

Appending an id to a list if not already present in a string

A more pythonic way, without using set is as follows:

lst = [1, 2, 3, 4]
lst.append(3) if 3 not in lst else lst

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

We had the same issue, in making a websocket connection to the Load Balancer. The issue is in LB, accepting http connection on port 80 and forwarding the request to node (tomcat app on port 8080). We have changed this to accept tcp (http has been changed as 'tcp') connection on port 80. So the first handshake request is forwarded to Node and a websocket connection is made successfully on some random( as far as i know, may be wrong) port.

below command has been used to test the websocket handshake process.

curl -v -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost" -H "Origin: http://LB URL:80" http://LB URL

  • Rebuilt URL to: http:LB URL/
  • Trying LB URL...
  • TCP_NODELAY set
  • Connected to LB URL (LB URL) port 80 (#0)

    GET / HTTP/1.1 Host: localhost User-Agent: curl/7.60.0 Accept: / Connection: Upgrade Upgrade: websocket Origin: http://LB URL:80

  • Recv failure: Connection reset by peer
  • Closing connection 0 curl: (56) Recv failure: Connection reset by peer

sqlite database default time value 'now'

It may be better to use REAL type, to save storage space.

Quote from 1.2 section of Datatypes In SQLite Version 3

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t REAL DEFAULT (datetime('now', 'localtime'))
);

see column-constraint .

And insert a row without providing any value.

INSERT INTO "test" DEFAULT VALUES;

Difference between innerText, innerHTML and value?

innerText property sets or returns the text content as plain text of the specified node, and all its descendants whereas the innerHTML property gets and sets the plain text or HTML contents in the elements. Unlike innerText, inner HTML lets you work with HTML rich text and doesn’t automatically encode and decode text.

How to float a div over Google Maps?

absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

You can try the expand option in Series.str.split('seperator', expand=True).
By default expand is False.

expand : bool, default False
Expand the splitted strings into separate columns.

  • If True, return DataFrame/MultiIndex expanding dimensionality.
  • If False, return Series/Index, containing lists of strings.

Selecting distinct values from a JSON

This is a great spot for a reduce

var uniqueArray = o.DATA.reduce(function (a, d) {
       if (a.indexOf(d.name) === -1) {
         a.push(d.name);
       }
       return a;
    }, []);

jQuery map vs. each

The each function iterates over an array, calling the supplied function once per element, and setting this to the active element. This:

function countdown() {
    alert(this + "..");
}

$([5, 4, 3, 2, 1]).each(countdown);

will alert 5.. then 4.. then 3.. then 2.. then 1..

Map on the other hand takes an array, and returns a new array with each element changed by the function. This:

function squared() {
    return this * this;
}

var s = $([5, 4, 3, 2, 1]).map(squared);

would result in s being [25, 16, 9, 4, 1].

How to set entire application in portrait mode only?

Add android:screenOrientation="portrait" to the activity in the AndroidManifest.xml. For example:

<activity android:name=".SomeActivity"
    android:label="@string/app_name"
    android:screenOrientation="portrait">

Insert HTML from CSS

No you cannot. The only thing you can do is to insert content. Like so:

p:after {
    content: "yo";
}

Check that a variable is a number in UNIX shell

INTEGER

if echo "$var" | egrep -q '^\-?[0-9]+$'; then 
    echo "$var is an integer"
else 
    echo "$var is not an integer"
fi

tests (with var=2 etc.):

2 is an integer
-2 is an integer
2.5 is not an integer 
2b is not an integer

NUMBER

if echo "$var" | egrep -q '^\-?[0-9]*\.?[0-9]+$'; then 
    echo "$var is a number"
else 
    echo "$var is not a number"
fi

tests (with var=2 etc.):

2 is a number
-2 is a number
-2.6 is a number
-2.c6 is not a number
2. is not a number
2.0 is a number

GridView sorting: SortDirection always Ascending

In vb.net but very simple!

Protected Sub grTicketHistory_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grTicketHistory.Sorting

    Dim dt As DataTable = Session("historytable")
    If Session("SortDirection" & e.SortExpression) = "ASC" Then
        Session("SortDirection" & e.SortExpression) = "DESC"
    Else
        Session("SortDirection" & e.SortExpression) = "ASC"
    End If
    dt.DefaultView.Sort = e.SortExpression & " " & Session("SortDirection" & e.SortExpression)
    grTicketHistory.DataSource = dt
    grTicketHistory.DataBind()

End Sub

SQL : BETWEEN vs <= and >=

In this scenario col BETWEEN ... AND ... and col <= ... and col >= ... are equivalent.


SQL Standard defines also T461 Symmetric BETWEEN predicate:

 <between predicate part 2> ::=
 [ NOT ] BETWEEN [ ASYMMETRIC | SYMMETRIC ]
 <row value predicand> AND <row value predicand>

Transact-SQL does not support this feature.

BETWEEN requires that values are sorted. For instance:

SELECT 1 WHERE 3 BETWEEN 10 AND 1
-- no rows

<=>

SELECT 1 WHERE 3 >= 10 AND 3 <= 1
-- no rows

On the other hand:

SELECT 1 WHERE 3 BETWEEN SYMMETRIC 1 AND 10;
-- 1

SELECT 1 WHERE 3 BETWEEN SYMMETRIC 10 AND 1
-- 1

It works exactly as the normal BETWEEN but after sorting the comparison values.

db<>fiddle demo

internal/modules/cjs/loader.js:582 throw err

I had the same issue when I first tried on node js.
I noticed this issue was happening to me because I had some .js files with same names in different directories, which were in the same main directory.
I created another directory outside the main project folder, and created a .js file.
After that, it ran fine.
ex- app.js

Where are my postgres *.conf files?

Win7, version 10 location:

C:\Program Files\PostgreSQL\10\postgresql.conf

How to "flatten" a multi-dimensional array to simple one in PHP?

If you're okay with loosing array keys, you may flatten a multi-dimensional array using a recursive closure as a callback that utilizes array_values(), making sure that this callback is a parameter for array_walk(), as follows.

<?php  

$array = [1,2,3,[5,6,7]];
$nu_array = null;
$callback = function ( $item ) use(&$callback, &$nu_array) {
    if (!is_array($item)) {
    $nu_array[] = $item;
    }
    else
    if ( is_array( $item ) ) {
     foreach( array_values($item) as $v) {
         if ( !(is_array($v))) {
             $nu_array[] = $v;
         }
         else
         { 
             $callback( $v );
         continue;
         }    
     }
    }
};

array_walk($array, $callback);
print_r($nu_array);

The one drawback of the preceding example is that it involves writing far more code than the following solution which uses array_walk_recursive() along with a simplified callback:

<?php  

$array = [1,2,3,[5,6,7]];

$nu_array = [];
array_walk_recursive($array, function ( $item ) use(&$nu_array )
                     {
                         $nu_array[] = $item;
                     }
);
print_r($nu_array);

See live code

This example seems preferable to the previous one, hiding the details about how values are extracted from a multidimensional array. Surely, iteration occurs, but whether it entails recursion or control structure(s), you'll only know from perusing array.c. Since functional programming focuses on input and output rather than the minutiae of obtaining a result, surely one can remain unconcerned about how behind-the-scenes iteration occurs, that is until a perspective employer poses such a question.

POST data to a URL in PHP

cURL-less you can use in php5

$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

stop service in android

onDestroyed()

is wrong name for

onDestroy()  

Did you make a mistake only in this question or in your code too?

Can you use if/else conditions in CSS?

You can use javascript for this purpose, this way:

  1. first you set the CSS for the 'normal' class and for the 'active' class
  2. then you give to your element the id 'MyElement'
  3. and now you make your condition in JavaScript, something like the example below... (you can run it, change the value of myVar to 5 and you will see how it works)

_x000D_
_x000D_
var myVar = 4;_x000D_
_x000D_
if(myVar == 5){_x000D_
  document.getElementById("MyElement").className = "active";_x000D_
}_x000D_
else{_x000D_
  document.getElementById("MyElement").className = "normal";_x000D_
}
_x000D_
.active{_x000D_
  background-position : 150px 8px;_x000D_
  background-color: black;_x000D_
}_x000D_
.normal{_x000D_
  background-position : 4px 8px; _x000D_
  background-color: green;_x000D_
}_x000D_
div{_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  }
_x000D_
<div id="MyElement">_x000D_
  _x000D_
  </div>
_x000D_
_x000D_
_x000D_

Random row selection in Pandas dataframe

Below line will randomly select n number of rows out of the total existing row numbers from the dataframe df without replacement.

df=df.take(np.random.permutation(len(df))[:n])

Java get last element of a collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement = itr.next();
    }
    return lastElement;
}

Why does my Eclipse keep not responding?

for me, it was because of all the outgoing files, i.e workspace is not in sync with SVN, due to the 'target' folders (maven project, or when building web project), add them to svn:ignore.

How to detect a textbox's content has changed

This Code detects whenever a textbox's content has changed by the user and modified by Javascript code.

var $myText = jQuery("#textbox");

$myText.data("value", $myText.val());

setInterval(function() {
    var data = $myText.data("value"),
    val = $myText.val();

    if (data !== val) {
        console.log("changed");
        $myText.data("value", val);
    }
}, 100);

Clear input fields on form submit

You can clear out their values by just setting value to an empty string:

var1.value = '';
var2.value = '';

Creating a JSON Array in node js

Build up a JavaScript data structure with the required information, then turn it into the json string at the end.

Based on what I think you're doing, try something like this:

var result = [];
for (var name in goals) {
  if (goals.hasOwnProperty(name)) {
    result.push({name: name, goals: goals[name]});
  }
}

res.contentType('application/json');
res.send(JSON.stringify(result));

or something along those lines.

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

JQuery - $ is not defined

Something that I didn't find here, but did happen to me. Make sure you don't have the jQuery slim version included, as that version of the jQuery library doesn't include the Ajax functionality.

The result is that "$" works, but $.get for example returns an error message stating that that function is undefined.

Solution: include the full version of jQuery instead.

Create a folder inside documents folder in iOS apps

Swift 3 Solution:

private func createImagesFolder() {
        // path to documents directory
        let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        if let documentDirectoryPath = documentDirectoryPath {
            // create the custom folder path
            let imagesDirectoryPath = documentDirectoryPath.appending("/images")
            let fileManager = FileManager.default
            if !fileManager.fileExists(atPath: imagesDirectoryPath) {
                do {
                    try fileManager.createDirectory(atPath: imagesDirectoryPath,
                                                    withIntermediateDirectories: false,
                                                    attributes: nil)
                } catch {
                    print("Error creating images folder in documents dir: \(error)")
                }
            }
        }
    }

WebSockets protocol vs HTTP

For the TL;DR, here are 2 cents and a simpler version for your questions:

  1. WebSockets provides these benefits over HTTP:

    • Persistent stateful connection for the duration of the connection
    • Low latency: near-real-time communication between server/client due to no overhead of reestablishing connections for each request as HTTP requires.
    • Full duplex: both server and client can send/receive simultaneously
  2. WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much common ground to combine them into one protocol.

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

How can I convert a DOM element to a jQuery element?

What about constructing the element using jQuery? e.g.

$("<div></div>")

creates a new div element, ready to be added to the page. Can be shortened further to

$("<div>")

then you can chain on commands that you need, set up event handlers and append it to the DOM. For example

$('<div id="myid">Div Content</div>')
    .bind('click', function(e) { /* event handler here */ })
    .appendTo('#myOtherDiv');

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

How to overcome the CORS issue in ReactJS

the simplest way what I found from a tutorial of "TraversyMedia" is that just use https://cors-anywhere.herokuapp.com in 'axios' or 'fetch' api

https://cors-anywhere.herokuapp.com/{type_your_url_here} 

e.g.

axios.get(`https://cors-anywhere.herokuapp.com/https://www.api.com/`)

and in your case edit url as

url: 'https://cors-anywhere.herokuapp.com/https://www.api.com',

libxml/tree.h no such file or directory

Ray Wenderlich has a blog post about using gdata that solves this problem. Basically these simple steps:

In XCode, click Project\Edit Project Settings and make sure “All Configurations” are checked.

Find the Search Paths\Header Search Paths setting and add /usr/include/libxml2 to the list.

Finally, find the Linking\Other Linker Flags section and add -lxml2 to the list.

original post: read and write xml documents with gdataxml

Programmatically Creating UILabel

In Swift -

var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)

Convert timestamp in milliseconds to string formatted time in Java

Try this:

    String sMillis = "10997195233";
    double dMillis = 0;

    int days = 0;
    int hours = 0;
    int minutes = 0;
    int seconds = 0;
    int millis = 0;

    String sTime;

    try {
        dMillis = Double.parseDouble(sMillis);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }


    seconds = (int)(dMillis / 1000) % 60;
    millis = (int)(dMillis % 1000);

    if (seconds > 0) {
        minutes = (int)(dMillis / 1000 / 60) % 60;
        if (minutes > 0) {
            hours = (int)(dMillis / 1000 / 60 / 60) % 24;
            if (hours > 0) {
                days = (int)(dMillis / 1000 / 60 / 60 / 24);
                if (days > 0) {
                    sTime = days + " days " + hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
                } else {
                    sTime = hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
                }
            } else {
                sTime = minutes + " min " + seconds + " sec " + millis + " millisec";
            }
        } else {
            sTime = seconds + " sec " + millis + " millisec";
        }
    } else {
        sTime = dMillis + " millisec";
    }

    System.out.println("time: " + sTime);

Vue.js get selected option on @change

You can also use v-model for the rescue

<template>
    <select name="LeaveType" v-model="leaveType" @change="onChange()" class="form-control">
         <option value="1">Annual Leave/ Off-Day</option>
         <option value="2">On Demand Leave</option>
    </select>
</template>

<script>
export default {
    data() {
        return {
            leaveType: '',
        }
    },

    methods: {
        onChange() {
            console.log('The new value is: ', this.leaveType)
        }
    }
}
</script>

C++ -- expected primary-expression before ' '

You should not be repeating the string part when sending parameters.

int wordLength = wordLengthFunction(word); //you do not put string word here.

Python - Join with newline

You forgot to print the result. What you get is the P in RE(P)L and not the actual printed result.

In Py2.x you should so something like

>>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

and in Py3.X, print is a function, so you should do

print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))

Now that was the short answer. Your Python Interpreter, which is actually a REPL, always displays the representation of the string rather than the actual displayed output. Representation is what you would get with the repr statement

>>> print repr("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'I\nwould\nexpect\nmultiple\nlines'

Align image in center and middle within div

Just set parent div css property "text-align:center;"

 <div style="text-align:center; width:100%">
        <img src="img.png"> 
 </div>

How to Rotate a UIImage 90 degrees?

I like the simple elegance of Peter Sarnowski's answer, but it can cause problems when you can't rely on EXIF metadata and the like. In situations where you need to rotate the actual image data I would recommend something like this:

- (UIImage *)rotateImage:(UIImage *) img
{
    CGSize imgSize = [img size];
    UIGraphicsBeginImageContext(imgSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextRotateCTM(context, M_PI_2);
    CGContextTranslateCTM(context, 0, -640);
    [img drawInRect:CGRectMake(0, 0, imgSize.height, imgSize.width)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

The above code takes an image whose orientation is Landscape (can't remember if it's Landscape Left or Landscape Right) and rotates it into Portrait. It is an example which can be modified for your needs.

The key arguments you would have to play with are CGContextRotateCTM(context, M_PI_2) where you decide how much you want to rotate by, but then you have to make sure the picture still draws on the screen using CGContextTranslateCTM(context, 0, -640). This last part is quite important to make sure you see the image and not a blank screen.

For more info check out the source.

Find all controls in WPF Window by type

And this is how it works upwards

    private T FindParent<T>(DependencyObject item, Type StopAt) where T : class
    {
        if (item is T)
        {
            return item as T;
        }
        else
        {
            DependencyObject _parent = VisualTreeHelper.GetParent(item);
            if (_parent == null)
            {
                return default(T);
            }
            else
            {
                Type _type = _parent.GetType();
                if (StopAt != null)
                {
                    if ((_type.IsSubclassOf(StopAt) == true) || (_type == StopAt))
                    {
                        return null;
                    }
                }

                if ((_type.IsSubclassOf(typeof(T)) == true) || (_type == typeof(T)))
                {
                    return _parent as T;
                }
                else
                {
                    return FindParent<T>(_parent, StopAt);
                }
            }
        }
    }

Redis command to get all available keys?

Updated for Redis 2.8 and above

As noted in the comments of previous answers to this question, KEYS is a potentially dangerous command since your Redis server will be unavailable to do other operations while it serves it. Another risk with KEYS is that it can consume (dependent on the size of your keyspace) a lot of RAM to prepare the response buffer, thus possibly exhausting your server's memory.

Version 2.8 of Redis had introduced the SCAN family of commands that are much more polite and can be used for the same purpose.

The CLI also provides a nice way to work with it:

$ redis-cli --scan --pattern '*'

How do I update a formula with Homebrew?

You will first need to update the local formulas by doing

brew update

and then upgrade the package by doing

brew upgrade formula-name

An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :

brew update && brew upgrade mongodb && brew cleanup mongodb

How to perform a fade animation on Activity transition?

Just re-posting answer by oleynikd because it's simple and neat

Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getContext(),
    android.R.anim.fade_in, android.R.anim.fade_out).toBundle(); 
startActivity(intent, bundle);

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

ASP.NET Core Identity - get current user

Just if any one is interested this worked for me. I have a custom Identity which uses int for a primary key so I overrode the GetUserAsync method

Override GetUserAsync

public override Task<User> GetUserAsync(ClaimsPrincipal principal)
{
    var userId = GetUserId(principal);
    return FindByNameAsync(userId);
}

Get Identity User

var user = await _userManager.GetUserAsync(User);

If you are using a regular Guid primary key you don't need to override GetUserAsync. This is all assuming that you token is configured correctly.

public async Task<string> GenerateTokenAsync(string email)
{
    var user = await _userManager.FindByEmailAsync(email);
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_tokenProviderOptions.SecretKey);

    var userRoles = await _userManager.GetRolesAsync(user);
    var roles = userRoles.Select(o => new Claim(ClaimTypes.Role, o));

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture)),
        new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
        new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
        new Claim(JwtRegisteredClaimNames.Email, user.Email),
    }
    .Union(roles);

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(claims),
        Expires = DateTime.UtcNow.AddHours(_tokenProviderOptions.Expires),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);

    return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token)).Result;
}

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

convert month from name to number

Yes,

$date = 'July 25 2010';
echo date('d/m/Y', strtotime($date));

The m formats the month to its numerical representation there.

Change Title of Javascript Alert

you cant do this. Use a custom popup. Something like with the help of jQuery UI or jQuery BOXY.

for jQuery UI http://jqueryui.com/demos/dialog/

for jQuery BOXY http://onehackoranother.com/projects/jquery/boxy/

Hide header in stack navigator React navigation

I am using header : null instead of header : { visible : true } i am using react-native cli. this is the example :

static navigationOptions = {
   header : null   
};

How to convert a std::string to const char* or char*?

C++17

C++17 (upcoming standard) changes the synopsis of the template basic_string adding a non const overload of data():

charT* data() noexcept;

Returns: A pointer p such that p + i == &operator for each i in [0,size()].


CharT const * from std::basic_string<CharT>

std::string const cstr = { "..." };
char const * p = cstr.data(); // or .c_str()

CharT * from std::basic_string<CharT>

std::string str = { "..." };
char * p = str.data();

C++11

CharT const * from std::basic_string<CharT>

std::string str = { "..." };
str.c_str();

CharT * from std::basic_string<CharT>

From C++11 onwards, the standard says:

  1. The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size().

  1. const_reference operator[](size_type pos) const;
    reference operator[](size_type pos);

    Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type CharT with value CharT(); the referenced value shall not be modified.


  1. const charT* c_str() const noexcept;
    const charT* data() const noexcept;

    Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].

There are severable possible ways to get a non const character pointer.

1. Use the contiguous storage of C++11

std::string foo{"text"};
auto p = &*foo.begin();

Pro

  • Simple and short
  • Fast (only method with no copy involved)

Cons

  • Final '\0' is not to be altered / not necessarily part of the non-const memory.

2. Use std::vector<CharT>

std::string foo{"text"};
std::vector<char> fcv(foo.data(), foo.data()+foo.size()+1u);
auto p = fcv.data();

Pro

  • Simple
  • Automatic memory handling
  • Dynamic

Cons

  • Requires string copy

3. Use std::array<CharT, N> if N is compile time constant (and small enough)

std::string foo{"text"};
std::array<char, 5u> fca;
std::copy(foo.data(), foo.data()+foo.size()+1u, fca.begin());

Pro

  • Simple
  • Stack memory handling

Cons

  • Static
  • Requires string copy

4. Raw memory allocation with automatic storage deletion

std::string foo{ "text" };
auto p = std::make_unique<char[]>(foo.size()+1u);
std::copy(foo.data(), foo.data() + foo.size() + 1u, &p[0]);

Pro

  • Small memory footprint
  • Automatic deletion
  • Simple

Cons

  • Requires string copy
  • Static (dynamic usage requires lots more code)
  • Less features than vector or array

5. Raw memory allocation with manual handling

std::string foo{ "text" };
char * p = nullptr;
try
{
  p = new char[foo.size() + 1u];
  std::copy(foo.data(), foo.data() + foo.size() + 1u, p);
  // handle stuff with p
  delete[] p;
}
catch (...)
{
  if (p) { delete[] p; }
  throw;
}

Pro

  • Maximum 'control'

Con

  • Requires string copy
  • Maximum liability / susceptibility for errors
  • Complex

No Access-Control-Allow-Origin header is present on the requested resource

You are missing 'json' dataType in the $.post() method:

$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
        .done(function(data){
                  alert(data);
         }, "json");
         //-^^^^^^-------here

Updates:

try with this:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

Python: split a list based on a condition?

I'd take a 2-pass approach, separating evaluation of the predicate from filtering the list:

def partition(pred, iterable):
    xs = list(zip(map(pred, iterable), iterable))
    return [x[1] for x in xs if x[0]], [x[1] for x in xs if not x[0]]

What's nice about this, performance-wise (in addition to evaluating pred only once on each member of iterable), is that it moves a lot of logic out of the interpreter and into highly-optimized iteration and mapping code. This can speed up iteration over long iterables, as described in this answer.

Expressivity-wise, it takes advantage of expressive idioms like comprehensions and mapping.

How to Delete node_modules - Deep Nested Folder in Windows

On Windows, using Total Commander all you have to do is select the folder click shift + delete . Don't forget about the shift key.

Vue.js img src concatenate variable and text

just try

_x000D_
_x000D_
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
_x000D_
_x000D_

How to check command line parameter in ".bat" file?

In addition to the other answers, which I subscribe, you may consider using the /I switch of the IF command.

... the /I switch, if specified, says to do case insensitive string compares.

it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.

IF /I "%1"=="-b" GOTO SPECIFIC

Entity Framework vs LINQ to SQL

There are a number of obvious differences outlined in that article @lars posted, but short answer is:

  • L2S is tightly coupled - object property to specific field of database or more correctly object mapping to a specific database schema
  • L2S will only work with SQL Server (as far as I know)
  • EF allows mapping a single class to multiple tables
  • EF will handle M-M relationships
  • EF will have ability to target any ADO.NET data provider

The original premise was L2S is for Rapid Development, and EF for more "enterprisey" n-tier applications, but that is selling L2S a little short.