Programs & Examples On #Cgns

CGNS stands for CFD General Notation System. It is a general, portable, and extensible standard for the storage and retrieval of CFD (Computational Fluid Dynamics) analysis data.

Are HTTP headers case-sensitive?

The RFC for HTTP (as cited above) dictates that the headers are case-insensitive, however you will find that with certain browsers (I'm looking at you, IE) that capitalizing each of the words tends to be best:

Location: http://stackoverflow.com

Content-Type: text/plain

vs

location: http://stackoverflow.com

content-type: text/plain

This isn't "HTTP" standard, but just another one of the browser quirks, we as developers, have to think about.

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).

Make sure all your referenced fields have the same type AND the same collation!

ETag vs Header Expires

One additional thing I would like to mention that some of the answers may have missed is the downside to having both ETags and Expires/Cache-control in your headers.

Depending on your needs it may just add extra bytes in your headers which may increase packets which means more TCP overhead. Again, you should see if the overhead of having both things in your headers is necessary or will it just add extra weight in your requests which reduces performance.

You can read more about it on this excellent blog post by Kyle Simpson: http://calendar.perfplanet.com/2010/bloated-request-response-headers/

Python: Making a beep noise

Using pygame on any platform

The advantage of using pygame is that it can be made to work on any OS platform. Below example code is for GNU/Linux though.

First install the pygame module for python3 as explained in detail here.

$ sudo pip3 install pygame

The pygame module can play .wav and .ogg files from any file location. Here is an example:

#!/usr/bin/env python3
import pygame
pygame.mixer.init()
sound = pygame.mixer.Sound('/usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga')
sound.play()

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

Just for other's reference, I just received this and found it was due to AngularJS. It's for backwards compatibility:

if (!event.preventDefault) {
    event.preventDefault = function() {
        event.returnValue = false; //ie
    };
}

is the + operator less performant than StringBuffer.append()

Agreed with Michael Haren.

Also consider the use of arrays and join if performance is indeed an issue.

var buffer = ["<a href='", url, "'>click here</a>"];
buffer.push("More stuff");
alert(buffer.join(""));

Change Spinner dropdown icon

dummy.xml(remember image size should be less)

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <layer-list android:opacity="transparent">
                <item android:width="60dp" android:gravity="left" android:start="20dp">
                    <bitmap  android:src="@drawable/down_button_dummy_dummy" android:gravity="left"/>
                </item>
            </layer-list>
        </item>
    </selector>

layout file snippet be like

<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardUseCompatPadding="true"
        app:cardElevation="5dp"
        >
     <Spinner
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/dummy">

     </Spinner>
    </android.support.v7.widget.CardView>

click to see result layout image

angularjs ng-style: background-image isn't working

For those who are struggling to get this working with IE11

HTML

<div ng-style="getBackgroundStyle(imagepath)"></div>

JS

$scope.getBackgroundStyle = function(imagepath){
    return {
        'background-image':'url(' + imagepath + ')'
    }
}

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

Python, add items from txt file into a list

This should be a good case for map and lambda

with open ('names.txt','r') as f :
   Names = map (lambda x : x.strip(),f_in.readlines())

I stand corrected (or at least improved). List comprehensions is even more elegant

with open ('names.txt','r') as f :
    Names = [name.rstrip() for name in f]

Codeigniter how to create PDF

Create new pdf helper file in application\helpers folder and name it pdf_helper.php. Add below code in pdf_helper.php file:

        function tcpdf()
      {
        require_once('tcpdf/config/lang/eng.php');
        require_once('tcpdf/tcpdf.php');
      }
     ?>

For more Please follow the below link:

 http://www.ccode4u.com/how-to-generate-pdf-file-in-codeigniter.html

Python Matplotlib Y-Axis ticks on Right Side of Plot

For right labels use ax.yaxis.set_label_position("right"), i.e.:

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()

Java - using System.getProperty("user.dir") to get the home directory

way of getting home directory of current user is

String currentUsersHomeDir = System.getProperty("user.home");

and to append path separator

String otherFolder = currentUsersHomeDir + File.separator + "other";

File.separator

The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.

What is the difference between Collection and List in Java?

Collection is the main interface of Java Collections hierarchy and List(Sequence) is one of the sub interfaces that defines an ordered collection.

How do I get the coordinates of a mouse click on a canvas element?

I was creating an application having a canvas over a pdf, that involved a lot of resizes of canvas like Zooming the pdf-in and out, and in turn on every zoom-in/out of PDF I had to resize the canvas to adapt the size of the pdf, I went through lot of answers in stackOverflow, and didn't found a perfect solution that will eventually solve the problem.

I was using rxjs and angular 6, and didn't found any answer specific to the newest version.

Here is the entire code snippet that would be helpful, to anyone leveraging rxjs to draw on top of canvas.

  private captureEvents(canvasEl: HTMLCanvasElement) {

    this.drawingSubscription = fromEvent(canvasEl, 'mousedown')
      .pipe(
        switchMap((e: any) => {

          return fromEvent(canvasEl, 'mousemove')
            .pipe(
              takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {
                const prevPos = {
                  x: null,
                  y: null
                };
              })),

              takeUntil(fromEvent(canvasEl, 'mouseleave')),
              pairwise()
            )
        })
      )
      .subscribe((res: [MouseEvent, MouseEvent]) => {
        const rect = this.cx.canvas.getBoundingClientRect();
        const prevPos = {
          x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
          y:  Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
        };
        const currentPos = {
          x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
          y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
        };

        this.coordinatesArray[this.file.current_slide - 1].push(prevPos);
        this.drawOnCanvas(prevPos, currentPos);
      });
  }

And here is the snippet that fixes, mouse coordinates relative to size of the canvas, irrespective of how you zoom-in/out the canvas.

const prevPos = {
  x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
  y:  Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};
const currentPos = {
  x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),
  y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )
};

Java: Insert multiple rows into MySQL with PreparedStatement

You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch().

Here's a kickoff example:

public void save(List<Entity> entities) throws SQLException {
    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setString(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length.

See also:

How do I pass JavaScript values to Scriptlet in JSP?

If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.

Other wise you can't do it.

How to change the font on the TextView?

Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.

Check below link to check roboto fonts:

How to use Roboto in xml layout

Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ......
    <item name="android:buttonStyle">@style/MyButton</item>
    <item name="android:textViewStyle">@style/MyTextView</item>
</style>

<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

And don't forget to use 'AppTheme' in your AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ......
</application>

Find (and kill) process locking port 3000 on Mac

These two commands will help you find and kill server process

  1. lsof -wni tcp:3000
  2. kill -9 pid

super() raises "TypeError: must be type, not classobj" for new-style class

The problem is that super needs an object as an ancestor:

>>> class oldstyle:
...     def __init__(self): self.os = True

>>> class myclass(oldstyle):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass()
TypeError: must be type, not classobj

On closer examination one finds:

>>> type(myclass)
classobj

But:

>>> class newstyle(object): pass

>>> type(newstyle)
type    

So the solution to your problem would be to inherit from object as well as from HTMLParser. But make sure object comes last in the classes MRO:

>>> class myclass(oldstyle, object):
...     def __init__(self): super(myclass, self).__init__()

>>> myclass().os
True

How to format strings in Java

I wrote this function it does just the right thing. Interpolate a word starting with $ with the value of the variable of the same name.

private static String interpol1(String x){
    Field[] ffield =  Main.class.getDeclaredFields();
    String[] test = x.split(" ") ;
    for (String v : test ) {
        for ( Field n: ffield ) {
            if(v.startsWith("$") && ( n.getName().equals(v.substring(1))  )){
                try {
                    x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
                }catch (Exception e){
                    System.out.println("");
                }
            }
        }
    }
    return x;
}

TSQL select into Temp table from dynamic sql

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)


SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
       ap.AccountNumber
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'


EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

How to find Current open Cursors in Oracle

1)your id should have sys dba access 2)

select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur, 
 s.username, s.machine
 from v$sesstat a, v$statname b, v$session s 
 where a.statistic# = b.statistic# and s.sid=a.sid
 and b.name = 'opened cursors current' 
 group by s.username, s.machine
 order by 1 desc;

IntelliJ Organize Imports

Simple & short solution worked for me.

Go to File -> Settings -> Editor -> Auto Import -> Java (left panel) and make the below things: Select check box for "Add unambigious imports on the fly" and "Optimize imports on the fly"

Refer this.

enter image description here

What is thread safe or non-thread safe in PHP?

As per PHP Documentation,

What does thread safety mean when downloading PHP?

Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.

So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.

Following Libraries are not thread safe. They are not recommended for use in a multi-threaded environment.

  • SNMP (Unix)
  • mSQL (Unix)
  • IMAP (Win/Unix)
  • Sybase-CT (Linux, libc5)

Calling remove in foreach loop in Java

To safely remove from a collection while iterating over it you should use an Iterator.

For example:

List<String> names = ....
Iterator<String> i = names.iterator();
while (i.hasNext()) {
   String s = i.next(); // must be called before you can call i.remove()
   // Do something
   i.remove();
}

From the Java Documentation :

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Perhaps what is unclear to many novices is the fact that iterating over a list using the for/foreach constructs implicitly creates an iterator which is necessarily inaccessible. This info can be found here

jQuery rotate/transform

t = setTimeout(function() { rotate(++degree); },65);

and clearTimeout to stop

clearTimeout(t);

I use this with AJAX

success:function(){ clearTimeout(t); }

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

1:Go to: Tools > Options > Projects and Solutions > Web Projects > Use the 64 bit version of IIS Express 2: change below setting for web service project. enter image description here

HTML5 Canvas vs. SVG vs. div

I agree with Simon Sarris's conclusions:

I have compared some visualization in Protovis (SVG) to Processingjs (Canvas) which display > 2000 points and processingjs is much faster than protovis.

Handling events with SVG is of course much easer because you can attach them to the objects. In Canvas you have to do it manually (check mouse position, etc) but for simple interaction it shouldn't be hard.

There is also the dojo.gfx library of the dojo toolkit. It provides an abstraction layer and you can specify the renderer (SVG, Canvas, Silverlight). That might be also an viable choice although I don't know how much overhead the additional abstraction layer adds but it makes it easy to code interactions and animations and is renderer-agnostic.

Here are some interesting benchmarks:

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

How to get commit history for just one branch?

Note: if you limit that log to the last n commit (last 3 commits for instance, git log -3), make sure to put a space between 'n' and your branch:

git log -3 master..

Before Git 2.1 (August 2014), this mistake: git log -3master.. would actually show you the last 3 commits of the current branch (here my_experiment), ignoring the master limit (meaning if my_experiment contains only one commit, 3 would still be listed, 2 of them from master)

See commit e3fa568 by Junio C Hamano (gitster):

revision: parse "git log -<count>" more carefully

This mistyped command line simply ignores "master" and ends up showing two commits from the current HEAD:

$ git log -2master

because we feed "2master" to atoi() without making sure that the whole string is parsed as an integer.

Use the strtol_i() helper function instead.

make: *** [ ] Error 1 error

Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!

Find which rows have different values for a given column in Teradata SQL

This works for PL/SQL:

select count(*), id,address from table group by id,address having count(*)<2

IIS_IUSRS and IUSR permissions in IIS8

IIS_IUSRS group has prominence only if you are using ApplicationPool Identity. Even though you have this group looks empty at run time IIS adds to this group to run a worker process according to microsoft literature.

Entity Framework The underlying provider failed on Open

I saw this error when a colleague was trying to connect to a database that was protected behind a VPN. The user had unknownling switched to a wireless network that did not have VPN access. One way to test this scenario is to see if you can establish a connection in another means, such as SSMS, and see if that fails as well.

How to change root logging level programmatically for logback

I assume you are using logback (from the configuration file).

From logback manual, I see

Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

Perhaps this can help you change the value?

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

Refresh Part of Page (div)

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

Is Eclipse the best IDE for Java?

This is subjective... I find it to be a good tool.

It depends what kind of development you're doing - for EJB stuff, many folk would favour Netbeans. It also depends how much you want to spend - I assume you're talking about free IDEs?

Get HTML code using JavaScript with a URL

There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp

This is an example code taken from that tutorial:

<html>

<head>
    <script type="text/javascript">
        function loadXMLDoc()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {
              // Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
              xmlhttp = new XMLHttpRequest();
            }
            else
            {
                // Code for Internet Explorer 6 and Internet Explorer 5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "ajax_info.txt", true);
            xmlhttp.send();
        }
    </script>
</head>

<body>
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>

</html>

RegEx to exclude a specific string constant

This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:

$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:

$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".

How to run a single test with Mocha?

Try using mocha's --grep option:

    -g, --grep <pattern>            only run tests matching <pattern>

You can use any valid JavaScript regex as <pattern>. For instance, if we have test/mytest.js:

it('logs a', function(done) {
  console.log('a');
  done();
});

it('logs b', function(done) {
  console.log('b');
  done();
});

Then:

$ mocha -g 'logs a'

To run a single test. Note that this greps across the names of all describe(name, fn) and it(name, fn) invocations.

Consider using nested describe() calls for namespacing in order to make it easy to locate and select particular sets.

how do I make a single legend for many subplots with matplotlib?

There is also a nice function get_legend_handles_labels() you can call on the last axis (if you iterate over them) that would collect everything you need from label= arguments:

handles, labels = ax.get_legend_handles_labels()
fig.legend(handles, labels, loc='upper center')

How to round a floating point number up to a certain decimal place?

Just for the record. You could do it this way:

def roundno(no):
    return int(no//1 + ((no%1)/0.5)//1)

There, no need for includes/imports

Increment variable value by 1 ( shell programming)

The way to use expr:

i=0
i=`expr $i + 1`

the way to use i++

((i++)); echo $i;

Tested in gnu bash

What is FCM token in Firebase?

They deprecated getToken() method in the below release notes. Instead, we have to use getInstanceId.

https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId

Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
      @Override
      public void onSuccess(InstanceIdResult authResult) {
          // Task completed successfully
          // ...
          String fcmToken = authResult.getToken();
      }
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
    // Task failed with an exception
    // ...
}
});

To handle success and failure in the same listener, attach an OnCompleteListener:

task.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
    if (task.isSuccessful()) {
        // Task completed successfully
        InstanceIdResult authResult = task.getResult();
        String fcmToken = authResult.getToken();
    } else {
        // Task failed with an exception
        Exception exception = task.getException();
    }
}
});

Also, the FirebaseInstanceIdService Class is deprecated and they came up with onNewToken method in FireBaseMessagingService as replacement for onTokenRefresh,

you can refer to the release notes here, https://firebase.google.com/support/release-notes/android

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Use this code logic to send the info to your server.
    //sendRegistrationToServer(s);
}

jQuery table sort

If you want to avoid all the bells and whistles then may I suggest this simple sortElements plugin. Usage:

var table = $('table');

$('.sortable th')
    .wrapInner('<span title="sort this column"/>')
    .each(function(){

        var th = $(this),
            thIndex = th.index(),
            inverse = false;

        th.click(function(){

            table.find('td').filter(function(){

                return $(this).index() === thIndex;

            }).sortElements(function(a, b){

                if( $.text([a]) == $.text([b]) )
                    return 0;

                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;

            }, function(){

                // parentNode is the element we want to move
                return this.parentNode; 

            });

            inverse = !inverse;

        });

    });

And a demo. (click the "city" and "facility" column-headers to sort)

Does Python's time.time() return the local or UTC timestamp?

To get a local timestamp using datetime library, Python 3.x

#wanted format: year-month-day hour:minute:seconds

from datetime import datetime

# get time now
dt = datetime.now()
# format it to a string
timeStamp = dt.strftime('%Y-%m-%d %H:%M:%S')

# print it to screen
print(timeStamp)

Palindrome check in Javascript

One more solution with ES6

isPalin = str => [...str].every((c, i) => c === str[str.length-1-i]);

Two inline-block, width 50% elements wrap to second line

inline and inline-block elements are affected by whitespace in the HTML.

The simplest way to fix your problem is to remove the whitespace between </div> and <div id="col2">, see: http://jsfiddle.net/XCDsu/15/

There are other possible solutions, see: bikeshedding CSS3 property alternative?

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

Java - How to convert type collection into ArrayList?

As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:

http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29

So you need to do:

ArrayList<MyNode> myNodeList = new ArrayList<MyNode>(this.getVertices());

However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.

I think your code should look like this:

public V getNode(int nodeId){
        ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());
        return myNodeList(nodeId);
}

But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.

How to generate .json file with PHP?

If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.

my_json.php

$array = array(
    'title' => $title,
    'url' => $url
);

echo stripslashes(json_encode($array)); 

Then in your script set the path to the file my_json.php

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Below pattern perfectly works in case of leap year and as well as with normal dates. The date format is : YYYY-MM-DD

<input type="text"  placeholder="YYYY-MM-DD" pattern="(?:19|20)(?:(?:[13579][26]|[02468][048])-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))|(?:[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:29|30))|(?:(?:0[13578]|1[02])-31)))" class="form-control "  name="eventDate" id="" required autofocus autocomplete="nope">

I got this solution from http://html5pattern.com/Dates. Hope it may help someone.

Using $_POST to get select option value from HTML

Use this way:

$selectOption = $_POST['taskOption'];

But it is always better to give values to your <option> tags.

<select name="taskOption">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
</select>

How to use sed to extract substring

You want awk.

This would be a quick and dirty hack:

awk -F "\"" '{print $2}' /tmp/file.txt

PortMappingEnabled
PortMappingLeaseDuration
RemoteHost
ExternalPort
ExternalPortEndRange
InternalPort
PortMappingProtocol
InternalClient
PortMappingDescription

How does the Java 'for each' loop work?

As many of other answers correctly state, the for each loop is just syntactic sugar over the same old for loop and the compiler translates it to the same old for loop.

javac (open jdk) has a switch -XD-printflat, which generates a java file with all the syntactic sugar removed. the complete command looks like this

javac -XD-printflat -d src/ MyFile.java

//-d is used to specify the directory for output java file

So Lets remove the syntactical sugar

To answer this question, I created a file and wrote two version of for each, one with array and another with a list. my java file looked like this.

import java.util.*;
public class Temp{

    private static void forEachArray(){
        int[] arr = new int[]{1,2,3,4,5};
        for(int i: arr){
            System.out.print(i);
        }
    }

    private static void forEachList(){
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        for(Integer i: list){
            System.out.print(i);
        }
    }
}

When I compiled this file with above switch, I got the following output.

import java.util.*;

public class Temp {

    public Temp() {
        super();
    }

    private static void forEachArray() {
        int[] arr = new int[]{1, 2, 3, 4, 5};
        for (/*synthetic*/ int[] arr$ = arr, len$ = arr$.length, i$ = 0; i$ < len$; ++i$) {
            int i = arr$[i$];
            {
                System.out.print(i);
            }
        }
    }

    private static void forEachList() {
        List list = Arrays.asList(new Integer[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5)});
        for (/*synthetic*/ Iterator i$ = list.iterator(); i$.hasNext(); ) {
            Integer i = (Integer)i$.next();
            {
                System.out.print(i);
            }
        }
    }
}

You can see that along with the other syntactic sugar (Autoboxing) for each loops got changed to simple loops.

Rails Active Record find(:all, :order => ) issue

Make sure to check the schema at the database level directly. I've gotten burned by this before, where, for example, a migration was initially written to create a :datetime column, and I ran it locally, then tweaked the migration to a :date before actually deploying. Thus everyone's database looks good except for mine, and the bugs are subtle.

How does DISTINCT work when using JPA and Hibernate

You are close.

select DISTINCT(c.name) from Customer c

How can I install Apache Ant on Mac OS X?

To get Ant running on your Mac in 5 minutes, follow these steps.

Open up your terminal.

Perform these commands in order:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

brew install ant

If you don't have Java installed yet, you will get the following error: "Error: An unsatisfied requirement failed this build." Run this command next: brew cask install java to fix this.

The installation will resume.

Check your version of by running this command:

ant -version

And you're ready to go!

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

If you get this error while running the site in IIS 7+ on 64bit servers, you may have assemblies that are 32bit and your application pool will have the option "Enable 32-Bit Applications" set to False; Set this to true and restart the site to get it working.

Making the Android emulator run faster

Thank you @zest! Worked like a charm. Some things of note: Need to apply Intel's hotfix for the HAXM to deal with kernel panic issue: http://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager Also, note, if you have more than one abi, you need to uninstall one due to a bug in the latest version of the Android API (r19): https://code.google.com/p/android/issues/detail?id=66740 (remove armeabi-v7a in this case, since you want the x86 abi). Other than the 45-minutes it took me to resolve these, it was an very rewarding exercise in terms of the increased performance of the emulator.

Correctly determine if date string is a valid date in that format

Accordling with cl-sah's answer, but this sound better, shorter...

function checkmydate($date) {
  $tempDate = explode('-', $date);
  return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}

Test

checkmydate('2015-12-01');//true
checkmydate('2015-14-04');//false

Oracle Insert via Select from multiple tables where one table may not have a row

insert into account_type_standard (account_type_Standard_id, tax_status_id, recipient_id)
select account_type_standard_seq.nextval,
   ts.tax_status_id, 
   ( select r.recipient_id
     from recipient r
     where r.recipient_code = ?
   )
from tax_status ts
where ts.tax_status_code = ?

Get the week start date and week end date from week number

I have a way other, It is select day Start and day End of Week Current:

DATEADD(d, -(DATEPART(dw, GETDATE()-2)), GETDATE()) is date time Start

and

DATEADD(day,7-(DATEPART(dw,GETDATE()-1)),GETDATE()) is date time End

ImageMagick security policy 'PDF' blocking conversion

This is due to a security vulnerability that has been addressed in Ghostscript 9.24 (source). If you have a newer version, you don't need this workaround anymore. On Ubuntu 19.10 with Ghostscript 6, this means:

  1. Make sure you have Ghostscript =9.24:

    gs --version
    
  2. If yes, just remove this whole following section from /etc/ImageMagick-6/policy.xml:

    <!-- disable ghostscript format types -->
    <policy domain="coder" rights="none" pattern="PS" />
    <policy domain="coder" rights="none" pattern="PS2" />
    <policy domain="coder" rights="none" pattern="PS3" />
    <policy domain="coder" rights="none" pattern="EPS" />
    <policy domain="coder" rights="none" pattern="PDF" />
    <policy domain="coder" rights="none" pattern="XPS" />
    

Why do we use web.xml?

Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

How to get a complete list of object's methods and attributes?

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.

URL to load resources from the classpath in Java

Solution with registering URLStreamHandlers is most correct, of course, but sometimes the simplest solution is needed. So, I use the following method for that:

/**
 * Opens a local file or remote resource represented by given path.
 * Supports protocols:
 * <ul>
 * <li>"file": file:///path/to/file/in/filesystem</li>
 * <li>"http" or "https": http://host/path/to/resource - gzipped resources are supported also</li>
 * <li>"classpath": classpath:path/to/resource</li>
 * </ul>
 *
 * @param path An URI-formatted path that points to resource to be loaded
 * @return Appropriate implementation of {@link InputStream}
 * @throws IOException in any case is stream cannot be opened
 */
public static InputStream getInputStreamFromPath(String path) throws IOException {
    InputStream is;
    String protocol = path.replaceFirst("^(\\w+):.+$", "$1").toLowerCase();
    switch (protocol) {
        case "http":
        case "https":
            HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
            int code = connection.getResponseCode();
            if (code >= 400) throw new IOException("Server returned error code #" + code);
            is = connection.getInputStream();
            String contentEncoding = connection.getContentEncoding();
            if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"))
                is = new GZIPInputStream(is);
            break;
        case "file":
            is = new URL(path).openStream();
            break;
        case "classpath":
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path.replaceFirst("^\\w+:", ""));
            break;
        default:
            throw new IOException("Missed or unsupported protocol in path '" + path + "'");
    }
    return is;
}

CORS with POSTMAN

Use the browser/chrome postman plugin to check the CORS/SOP like a website. Use desktop application instead to avoid these controls.

Domain Account keeping locking out with correct password every few minutes

Try this solution from http://social.technet.microsoft.com/Forums/en/w7itprosecurity/thread/e1ef04fa-6aea-47fe-9392-45929239bd68

Microsoft Support found the problem for us. Our domain accounts were locking when a Windows 7 computer was started. The Windows 7 computer had a hidden old password from that domain account. There are passwords that can be stored in the SYSTEM context that can't be seen in the normal Credential Manager view.

Download PsExec.exe from http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx and copy it to C:\Windows\System32.

From a command prompt run: psexec -i -s -d cmd.exe

From the new DOS window run: rundll32 keymgr.dll,KRShowKeyMgr

Remove any items that appear in the list of Stored User Names and Passwords. Restart the computer.

Should I use Python 32bit or Python 64bit

I had trouble running python app (running large dataframes) in 32 - got MemoryError message, while on 64 it worked fine.

How to do something before on submit?

If you have a form as such:

<form id="myform">
...
</form>

You can use the following jQuery code to do something before the form is submitted:

$('#myform').submit(function() {
    // DO STUFF...
    return true; // return false to cancel form action
});

Python using enumerate inside list comprehension

Just to be really clear, this has nothing to do with enumerate and everything to do with list comprehension syntax.

This list comprehension returns a list of tuples:

[(i,j) for i in range(3) for j in 'abc']

this a list of dicts:

[{i:j} for i in range(3) for j in 'abc']

a list of lists:

[[i,j] for i in range(3) for j in 'abc']

a syntax error:

[i,j for i in range(3) for j in 'abc']

Which is inconsistent (IMHO) and confusing with dictionary comprehensions syntax:

>>> {i:j for i,j in enumerate('abcdef')}
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

And a set of tuples:

>>> {(i,j) for i,j in enumerate('abcdef')}
set([(0, 'a'), (4, 'e'), (1, 'b'), (2, 'c'), (5, 'f'), (3, 'd')])

As Óscar López stated, you can just pass the enumerate tuple directly:

>>> [t for t in enumerate('abcdef') ] 
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')]

Extracting an attribute value with beautifulsoup

Here is an example for how to extract the href attrbiutes of all a tags:

import requests as rq 
from bs4 import BeautifulSoup as bs

url = "http://www.cde.ca.gov/ds/sp/ai/"
page = rq.get(url)
html = bs(page.text, 'lxml')

hrefs = html.find_all("a")
all_hrefs = []
for href in hrefs:
    # print(href.get("href"))
    links = href.get("href")
    all_hrefs.append(links)

print(all_hrefs)

Usage of sys.stdout.flush() method

As per my understanding, When ever we execute print statements output will be written to buffer. And we will see the output on screen when buffer get flushed(cleared). By default buffer will be flushed when program exits. BUT WE CAN ALSO FLUSH THE BUFFER MANUALLY by using "sys.stdout.flush()" statement in the program. In the below code buffer will be flushed when value of i reaches 5.

You can understand by executing the below code.

chiru@online:~$ cat flush.py
import time
import sys

for i in range(10):
    print i
    if i == 5:
        print "Flushing buffer"
        sys.stdout.flush()
    time.sleep(1)

for i in range(10):
    print i,
    if i == 5:
        print "Flushing buffer"
        sys.stdout.flush()
chiru@online:~$ python flush.py 
0 1 2 3 4 5 Flushing buffer
6 7 8 9 0 1 2 3 4 5 Flushing buffer
6 7 8 9

Convert date to day name e.g. Mon, Tue, Wed

Your code works for me

$date = '15-12-2016';
$nameOfDay = date('D', strtotime($date));
echo $nameOfDay;

Use l instead of D, if you prefer the full textual representation of the name

How to pass parameters to ThreadStart method in Thread?

here is the perfect way...

private void func_trd(String sender)
{

    try
    {
        imgh.LoadImages_R_Randomiz(this, "01", groupBox, randomizerB.Value); // normal code

        ThreadStart ts = delegate
        {
            ExecuteInForeground(sender);
        };

        Thread nt = new Thread(ts);
        nt.IsBackground = true;

        nt.Start();

    }
    catch (Exception)
    {

    }
}

private void ExecuteInForeground(string name)
{
     //whatever ur function
    MessageBox.Show(name);
}

SQL update from one Table to another based on a ID match

Seems you are using MSSQL, then, if I remember correctly, it is done like this:

UPDATE [Sales_Lead].[dbo].[Sales_Import] SET [AccountNumber] = 
RetrieveAccountNumber.AccountNumber 
FROM RetrieveAccountNumber 
WHERE [Sales_Lead].[dbo].[Sales_Import].LeadID = RetrieveAccountNumber.LeadID

How to print to stderr in Python?

If you want to exit a program because of a fatal error, use:

sys.exit("Your program caused a fatal error. ... description ...")

and import sys in the header.

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Current user in Magento?

Found under "app/code/core/Mage/Page/Block/Html/Header.php":

public function getWelcome()
{
    if (empty($this->_data['welcome'])) {
        if (Mage::app()->isInstalled() && Mage::getSingleton('customer/session')->isLoggedIn()) {
            $this->_data['welcome'] = $this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getName());
        } else {
            $this->_data['welcome'] = Mage::getStoreConfig('design/header/welcome');
        }
    }

    return $this->_data['welcome'];
}

So it looks like Mage::getSingleton('customer/session')->getCustomer() will get your current logged in customer ;)

To get the currently logged in admin:

Mage::getSingleton('admin/session')->getUser();

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

in my case (project create in another system):

  1. clean project(right click on project in solution explorer and click clean item).
  2. then build project(right click on project in solution explorer and click build item).

I can run this project.

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

On Windows 10,

I just solved this issue by doing the following.

  1. Goto my.ini and add these 2 lines under [mysqld]

    skip-log-bin
    log_bin_trust_function_creators = 1
    
  2. restart MySQL service

Spring Boot application can't resolve the org.springframework.boot package

I had the same problem when I was trying to work with a basic spring boot app. I tried to use the latest spring-boot version from the official spring-boot site.

As on today, the latest version is 1.5.4.RELEASE. But I keep getting compilation issues on my eclipse IDE irrespective of multiple cleanups to the project. I lowered the version of spring-boot to 1.5.3.RELEASE and it simply worked !! Some of my earlier projects were using the old version which drove me to try this option.

Resolve absolute path from relative path and/or file name

This is to help fill in the gaps in Adrien Plisson's answer (which should be upvoted as soon as he edits it ;-):

you can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current path, which is obviously not what you want.

unfortunately, i don't know how to mix the 2 together...

One can handle %0 and %1 likewise:

  • %~dpnx0 for fully qualified drive+path+name+extension of the batchfile itself,
    %~f0 also suffices;
  • %~dpnx1 for fully qualified drive+path+name+extension of its first argument [if that's a filename at all],
    %~f1 also suffices;

%~f1 will work independent of how you did specify your first argument: with relative paths or with absolute paths (if you don't specify the file's extension when naming %1, it will not be added, even if you use %~dpnx1 -- however.

But how on earth would you name a file on a different drive anyway if you wouldn't give that full path info on the commandline in the first place?

However, %~p0, %~n0, %~nx0 and %~x0 may come in handy, should you be interested in path (without driveletter), filename (without extension), full filename with extension or filename's extension only. But note, while %~p1 and %~n1 will work to find out the path or name of the first argument, %~nx1 and %~x1 will not add+show the extension, unless you used it on the commandline already.

How do I add a simple onClick event handler to a canvas element?

As an alternative to alex's answer:

You could use a SVG drawing instead of a Canvas drawing. There you can add events directly to the drawn DOM objects.

see for example:

Making an svg image object clickable with onclick, avoiding absolute positioning

variable is not declared it may be inaccessible due to its protection level

I have found that you have to comment out the namespace wrapping the the class at time when moving between version of Visual Studio:

'Namespace FormsAuth

'End Namespace

and at other times, I have to uncomment the namespace.

This happened to me several times when other developers edited the same solution using a different version of VS and/or I moved (copied) the solution to another location

Get generic type of java.util.List

If you need to get the generic type of a returned type, I used this approach when I needed to find methods in a class which returned a Collection and then access their generic types:

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

public class Test {

    public List<String> test() {
        return null;
    }

    public static void main(String[] args) throws Exception {

        for (Method method : Test.class.getMethods()) {
            Class returnClass = method.getReturnType();
            if (Collection.class.isAssignableFrom(returnClass)) {
                Type returnType = method.getGenericReturnType();
                if (returnType instanceof ParameterizedType) {
                    ParameterizedType paramType = (ParameterizedType) returnType;
                    Type[] argTypes = paramType.getActualTypeArguments();
                    if (argTypes.length > 0) {
                        System.out.println("Generic type is " + argTypes[0]);
                    }
                }
            }
        }

    }

}

This outputs:

Generic type is class java.lang.String

Apache Proxy: No protocol handler was valid

For me all above-mentioned answers was enabled on xampp still not working. Enabling below module made virtual host work again

LoadModule slotmem_shm_module modules/mod_slotmem_shm.so

How to add Options Menu to Fragment in Android

Menu file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/play"
        android:titleCondensed="Speak"
        android:showAsAction="always"
        android:title="Speak"
        android:icon="@drawable/ic_play">
    </item>
    <item
        android:id="@+id/pause"
        android:titleCondensed="Stop"
        android:title="Stop"
        android:showAsAction="always"
        android:icon="@drawable/ic_pause">
    </item>
</menu>

Activity code:

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.play:
            Toast.makeText(getApplicationContext(), "speaking....", Toast.LENGTH_LONG).show();
            return false;

        case R.id.pause:
            Toast.makeText(getApplicationContext(), "stopping....", Toast.LENGTH_LONG).show();
            return false;

        default:
            break;
    }

    return false;
}

Fragment code:

@Override

public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.play:
            text = page.getText().toString();
            speakOut(text);

            // Do Activity menu item stuff here
            return true;

        case R.id.pause:
            speakOf();

            // Not implemented here
            return true;

        default:
            break;
    }
    return false;
}

How to use subList()

Using subList(30, 38); will fail because max index 38 is not available in list, so its not possible.

Only way may be before asking for the sublist, you explicitly determine the max index using list size() method.

for example, check size, which returns 35, so call sublist(30, size());

OR

COPIED FROM pb2q comment

dataList = dataList.subList(30, 38 > dataList.size() ? dataList.size() : 38);

How to calculate an age based on a birthday?

I don't really understand why you would make this an HTML Helper. I would make it part of the ViewData dictionary in an action method of the controller. Something like this:

ViewData["Age"] = DateTime.Now.Year - birthday.Year;

Given that birthday is passed into an action method and is a DateTime object.

How to add extension methods to Enums

You can also add an extension method to the Enum type rather than an instance of the Enum:

/// <summary> Enum Extension Methods </summary>
/// <typeparam name="T"> type of Enum </typeparam>
public class Enum<T> where T : struct, IConvertible
{
    public static int Count
    {
        get
        {
            if (!typeof(T).IsEnum)
                throw new ArgumentException("T must be an enumerated type");

            return Enum.GetNames(typeof(T)).Length;
        }
    }
}

You can invoke the extension method above by doing:

var result = Enum<Duration>.Count;

It's not a true extension method. It only works because Enum<> is a different type than System.Enum.

What is git tag, How to create tags & How to checkout git remote tag(s)

To get the specific tag code try to create a new branch add get the tag code in it. I have done it by command : $git checkout -b newBranchName tagName

How to pass a value from Vue data to href?

Or you can do that with ES6 template literal:

<a :href="`/job/${r.id}`"

What is the size limit of a post request?

For developers who cannot change php configuration because of the webhosting. (My settings 256MB max size, 1000 max variables)

I got the same issue that just 2 out of 5 big data objects (associative arrays) with substructures were received on the server side.

I find out that the whole substructure is being "flattened" in the post request. So, one object becomes a hundreds of literal variables. At the end, instead of 5 Object variables it is in reality sending dozens of hundreds elementar variables.

Solution in this case is to serialize each of the substructures into String. Then it is received on the server as 5 String variables. Example: {variable1:JSON.stringify(myDataObject1),variable2:JSON.stringify(myDataObject2)...}

How to cast the size_t to double or int C++

A cast, as Blaz Bratanic suggested:

size_t data = 99999999;
int convertdata = static_cast<int>(data);

is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).

But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t to int really could overflow.

If at all possible, design your program so you don't need to convert a size_t value to int. Just store it in a size_t variable (as you've already done) and use that.

Converting to double will not cause an overflow, but it could result in a loss of precision for a very large size_t value. Again, it doesn't make a lot of sense to convert a size_t to a double; you're still better off keeping the value in a size_t variable.

(R Sahu's answer has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)

How to change href of <a> tag on button click through javascript

remove href attribute:

<a id="" onclick="f1()">jhhghj</a>

if link styles are important then:

<a href="javascript:void(f1())">jhhghj</a>

no module named urllib.parse (How should I install it?)

You want urlparse using python2:

from urlparse import urlparse

#1071 - Specified key was too long; max key length is 767 bytes

change your collation. You can use utf8_general_ci that supports almost all

How to use double or single brackets, parentheses, curly braces

Truncate the contents of a variable

$ var="abcde"; echo ${var%d*}
abc

Make substitutions similar to sed

$ var="abcde"; echo ${var/de/12}
abc12

Use a default value

$ default="hello"; unset var; echo ${var:-$default}
hello

Search for string and get count in vi editor

I suggest doing:

  1. Search either with * to do a "bounded search" for what's under the cursor, or do a standard /pattern search.
  2. Use :%s///gn to get the number of occurrences. Or you can use :%s///n to get the number of lines with occurrences.

** I really with I could find a plug-in that would giving messaging of "match N of N1 on N2 lines" with every search, but alas.

Note: Don't be confused by the tricky wording of the output. The former command might give you something like 4 matches on 3 lines where the latter might give you 3 matches on 3 lines. While technically accurate, the latter is misleading and should say '3 lines match'. So, as you can see, there really is never any need to use the latter ('n' only) form. You get the same info, more clearly, and more by using the 'gn' form.

C# 4.0 optional out/ref arguments

Use an overloaded method without the out parameter to call the one with the out parameter for C# 6.0 and lower. I'm not sure why a C# 7.0 for .NET Core is even the correct answer for this thread when it was specifically asked if C# 4.0 can have an optional out parameter. The answer is NO!

RSA: Get exponent and modulus given a public key

It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it's a one-off (always the same key) or whether you need to script it.

Command-line / OpenSSL

If you want to use something like OpenSSL on a unix command line, you can do something as follows. I'm assuming you public.key file contains something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmBAjFv+29CaiQqYZIw4P
J0q5Qz2gS7kbGleS3ai8Xbhu5n8PLomldxbRz0RpdCuxqd1yvaicqpDKe/TT09sR
mL1h8Sx3Qa3EQmqI0TcEEqk27Ak0DTFxuVrq7c5hHB5fbJ4o7iEq5MYfdSl4pZax
UxdNv4jRElymdap8/iOo3SU1RsaK6y7kox1/tm2cfWZZhMlRFYJnpoXpyNYrp+Yo
CNKxmZJnMsS698kaFjDlyznLlihwMroY0mQvdD7dCeBoVlfPUGPAlamwWyqtIU+9
5xVkSp3kxcNcNb/mePSKQIPafQ1sAmBKPwycA/1I5nLzDVuQa95ZWMn0JkphtFIh
HQIDAQAB
-----END PUBLIC KEY-----

Then, the commands would be:

PUBKEY=`grep -v -- ----- public.key | tr -d '\n'`

Then, you can look into the ASN.1 structure:

echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i

This should give you something like this:

    0:d=0  hl=4 l= 290 cons: SEQUENCE          
    4:d=1  hl=2 l=  13 cons:  SEQUENCE          
    6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
   17:d=2  hl=2 l=   0 prim:   NULL              
   19:d=1  hl=4 l= 271 prim:  BIT STRING 

The modulus and public exponent are in the last BIT STRING, offset 19, so use -strparse:

 echo $PUBKEY | base64 -d | openssl asn1parse -inform DER -i -strparse 19

This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim:  INTEGER           :98102316FFB6F426A242A619230E0F274AB9433DA04BB91B1A5792DDA8BC5DB86EE67F0F2E89A57716D1CF4469742BB1A9DD72BDA89CAA90CA7BF4D3D3DB1198BD61F12C7741ADC4426A88D1370412A936EC09340D3171B95AEAEDCE611C1E5F6C9E28EE212AE4C61F752978A596B153174DBF88D1125CA675AA7CFE23A8DD253546C68AEB2EE4A31D7FB66D9C7D665984C951158267A685E9C8D62BA7E62808D2B199926732C4BAF7C91A1630E5CB39CB96287032BA18D2642F743EDD09E0685657CF5063C095A9B05B2AAD214FBDE715644A9DE4C5C35C35BFE678F48A4083DA7D0D6C02604A3F0C9C03FD48E672F30D5B906BDE5958C9F4264A61B452211D
  265:d=1  hl=2 l=   3 prim:  INTEGER           :010001

That's probably fine if it's always the same key, but this is probably not very convenient to put in a script.

Alternatively (and this might be easier to put into a script),

openssl rsa -pubin -inform PEM -text -noout < public.key

will return this:

Modulus (2048 bit):
    00:98:10:23:16:ff:b6:f4:26:a2:42:a6:19:23:0e:
    0f:27:4a:b9:43:3d:a0:4b:b9:1b:1a:57:92:dd:a8:
    bc:5d:b8:6e:e6:7f:0f:2e:89:a5:77:16:d1:cf:44:
    69:74:2b:b1:a9:dd:72:bd:a8:9c:aa:90:ca:7b:f4:
    d3:d3:db:11:98:bd:61:f1:2c:77:41:ad:c4:42:6a:
    88:d1:37:04:12:a9:36:ec:09:34:0d:31:71:b9:5a:
    ea:ed:ce:61:1c:1e:5f:6c:9e:28:ee:21:2a:e4:c6:
    1f:75:29:78:a5:96:b1:53:17:4d:bf:88:d1:12:5c:
    a6:75:aa:7c:fe:23:a8:dd:25:35:46:c6:8a:eb:2e:
    e4:a3:1d:7f:b6:6d:9c:7d:66:59:84:c9:51:15:82:
    67:a6:85:e9:c8:d6:2b:a7:e6:28:08:d2:b1:99:92:
    67:32:c4:ba:f7:c9:1a:16:30:e5:cb:39:cb:96:28:
    70:32:ba:18:d2:64:2f:74:3e:dd:09:e0:68:56:57:
    cf:50:63:c0:95:a9:b0:5b:2a:ad:21:4f:bd:e7:15:
    64:4a:9d:e4:c5:c3:5c:35:bf:e6:78:f4:8a:40:83:
    da:7d:0d:6c:02:60:4a:3f:0c:9c:03:fd:48:e6:72:
    f3:0d:5b:90:6b:de:59:58:c9:f4:26:4a:61:b4:52:
    21:1d
Exponent: 65537 (0x10001)

Java

It depends on the input format. If it's an X.509 certificate in a keystore, use (RSAPublicKey)cert.getPublicKey(): this object has two getters for the modulus and the exponent.

If it's in the format as above, you might want to use BouncyCastle and its PEMReader to read it. I haven't tried the following code, but this would look more or less like this:

PEMReader pemReader = new PEMReader(new FileReader("file.pem"));
Object obj = pemReader.readObject();
pemReader.close();
if (obj instanceof X509Certificate) {
   // Just in case your file contains in fact an X.509 certificate,
   // useless otherwise.
   obj = ((X509Certificate)obj).getPublicKey();
}
if (obj instanceof RSAPublicKey) {
   // ... use the getters to get the BigIntegers.
}

(You can use BouncyCastle similarly in C# too.)

VBA Excel - Insert row below with same format including borders and frames

well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)

lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents

(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )

How do I use the built in password reset/change views with my own templates

Another, perhaps simpler, solution is to add your override template directory to the DIRS entry of the TEMPLATES setting in settings.py. (I think this setting is new in Django 1.8. It may have been called TEMPLATE_DIRS in previous Django versions.)

Like so:

TEMPLATES = [
   {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # allow overriding templates from other installed apps                                                                                                
        'DIRS': ['my_app/templates'],
        'APP_DIRS': True,
}]

Then put your override template files under my_app/templates. So the overridden password reset template would be my_app/templates/registration/password_reset_form.html

UUID max character length

Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).

Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.

Convert int to a bit array in .NET

Use Convert.ToString (value, 2)

so in your case

string binValue = Convert.ToString (3, 2);

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

I'm not sure how this example works for older Web browsers but I use this for IE, Firefox and Chrome without an issue:

var iFrameDetection = (window === window.parent) ? false : true;

Could not find or load main class

First, put your file *.class (e.g Hello.class) into 1 folder (e.g C:\java). Then you try command and type cd /d C:\java. Now you can type "java Hello" !

How to replace (or strip) an extension from a filename in Python?

As @jethro said, splitext is the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension must be the part of the filename coming after the final period:

filename = '/home/user/somefile.txt'
print( filename.rsplit( ".", 1 )[ 0 ] )
# '/home/user/somefile'

The rsplit tells Python to perform the string splits starting from the right of the string, and the 1 says to perform at most one split (so that e.g. 'foo.bar.baz' -> [ 'foo.bar', 'baz' ]). Since rsplit will always return a non-empty array, we may safely index 0 into it to get the filename minus the extension.

Android WebView Cookie Problem

the solution is to give the Android enough time to proccess cookies. You can find more information here: http://code.walletapp.net/post/46414301269/passing-cookie-to-webview

AWS S3: how do I see how much disk space is using

I use Cloud Turtle to get the size of individual buckets. If the bucket size exceeds >100 Gb, then it would take some time to display the size. Cloud turtle is freeware.

How to suppress warnings globally in an R Script

Have a look at ?options and use warn:

options( warn = -1 )

Preventing form resubmission

I really like @Angelin's answer. But if you're dealing with some legacy code where this is not practical, this technique might work for you.

At the top of the file

// Protect against resubmits
if (empty($_POST))  {
   $_POST['last_pos_sub'] = time();
} else {
     if (isset($_POST['last_pos_sub'])){
        if ($_POST['last_pos_sub'] == $_SESSION['curr_pos_sub']) {
           redirect back to the file so POST data is not preserved
        }
        $_SESSION['curr_pos_sub'] = $_POST['last_pos_sub'];
     }
}

Then at the end of the form, stick in last_pos_sub as follows:

<input type="hidden" name="last_pos_sub" value=<?php echo $_POST['last_pos_sub']; ?>>

Angular 2 @ViewChild annotation returns undefined

For me using ngAfterViewInit instead of ngOnInit fixed the issue :

export class AppComponent implements OnInit {
  @ViewChild('video') video;
  ngOnInit(){
    // <-- in here video is undefined
  }
  public ngAfterViewInit()
  {
    console.log(this.video.nativeElement) // <-- you can access it here
  }
}

PHP Session timeout

    session_cache_expire( 20 );
    session_start(); // NEVER FORGET TO START THE SESSION!!!
    $inactive = 1200; //20 minutes *60
    if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
    header("Location: user_logout.php");
}
    }
    $_SESSION['start'] = time();

    if($_SESSION['valid_user'] != true){
    header('Location: ../....php');
    }else{  

source: http://www.daniweb.com/web-development/php/threads/124500

Which comes first in a 2D array, rows or columns?

In TStringGrid cells property Col come first.

Property Cells[ACol, ARow: Integer]: string read GetCells write SetCells;

So the assignment StringGrid1.cells[2, 1] := 'abcde'; the value is displayed in the third column second row.

How can I use Timer (formerly NSTimer) in Swift?

Check with:

Swift 2

var timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true)

Swift 3, 4, 5

var timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)

Add single element to array in numpy

append() creates a new array which can be the old array with the appended element.

I think it's more normal to use the proper method for adding an element:

a = numpy.append(a, a[0])

C++ Get name of type in template

Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:

template<typename T>
struct TypeParseTraits;

#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
    { static const char* name; } ; const char* TypeParseTraits<X>::name = #X


REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...

And then use it like

throw ParseError(TypeParseTraits<T>::name);

EDIT:

You could also combine the two, change name to be a function that by default calls typeid(T).name() and then only specialize for those cases where that's not acceptable.

Formatting "yesterday's" date in python

Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')

How to switch between hide and view password

Use the below code

    val hidePasswordMethod = PasswordTransformationMethod()
    showOrHidePasswordButton.setOnClickListener {
        passwordEditText.apply {
            transformationMethod =
                if (transformationMethod is PasswordTransformationMethod) 
                   null //shows password
               else 
                   hidePasswordMethod //hides password
        }
    }

and make sure you add this to your password edittext in layout

    android:inputType="textPassword"

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

The @RequestParam String action suggests there is a parameter present within the request with the name action which is absent in your form. You must either:

  1. Submit a parameter named value e.g. <input name="action" />
  2. Set the required parameter to false within the @RequestParam e.g. @RequestParam(required=false)

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Implement a simple factory pattern with Spring 3 annotations

Based on solution by Pavel Cerný here we can make an universal typed implementation of this pattern. To to it, we need to introduce NamedService interface:

    public interface NamedService {
       String name();
    }

and add abstract class:

public abstract class AbstractFactory<T extends NamedService> {

    private final Map<String, T> map;

    protected AbstractFactory(List<T> list) {
        this.map = list
                .stream()
                .collect(Collectors.toMap(NamedService::name, Function.identity()));
    }

    /**
     * Factory method for getting an appropriate implementation of a service
     * @param name name of service impl.
     * @return concrete service impl.

     */
    public T getInstance(@NonNull final String name) {
        T t = map.get(name);
        if(t == null)
            throw new RuntimeException("Unknown service name: " + name);
        return t;
    }
}

Then we create a concrete factory of specific objects like MyService:

 public interface MyService extends NamedService {
           String name();
           void doJob();
 }

@Component
public class MyServiceFactory extends AbstractFactory<MyService> {

    @Autowired
    protected MyServiceFactory(List<MyService> list) {
        super(list);
    }
}

where List the list of implementations of MyService interface at compile time.

This approach works fine if you have multiple similar factories across app that produce objects by name (if producing objects by a name suffice you business logic of course). Here map works good with String as a key, and holds all the existing implementations of your services.

if you have different logic for producing objects, this additional logic can be moved to some another place and work in combination with these factories (that get objects by name).

phpmyadmin.pma_table_uiprefs doesn't exist

I just located the create_tables.sql, saved to my desktop, opened phpMyAdmin, selected the import tab, selected the create_tables.sql, clicked ok

Updates were rejected because the tip of your current branch is behind its remote counterpart

Set current branch name like master

git pull --rebase origin master git push origin master

Or branch name develop

git pull --rebase origin develop git push origin develop

Why do I get a SyntaxError for a Unicode escape in my file path?

All the three syntax work very well.

Another way is to first write

path = r'C:\user\...................' (whatever is the path for you)

and then passing it to os.chdir(path)

Use of Application.DoEvents()

I've seen many commercial applications, using the "DoEvents-Hack". Especially when rendering comes into play, I often see this:

while(running)
{
    Render();
    Application.DoEvents();
}

They all know about the evil of that method. However, they use the hack, because they don't know any other solution. Here are some approaches taken from a blog post by Tom Miller:

  • Set your form to have all drawing occur in WmPaint, and do your rendering there. Before the end of the OnPaint method, make sure you do a this.Invalidate(); This will cause the OnPaint method to be fired again immediately.
  • P/Invoke into the Win32 API and call PeekMessage/TranslateMessage/DispatchMessage. (Doevents actually does something similar, but you can do this without the extra allocations).
  • Write your own forms class that is a small wrapper around CreateWindowEx, and give yourself complete control over the message loop. -Decide that the DoEvents method works fine for you and stick with it.

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is available only on IE browser. So every other useragent will throw an error

On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

How to pass a value to razor variable from javascript variable?

I see that this problem was discussed some time ago, but if anyone 'll meet with this again, here is my solution:

In your *.cshtml View file:

<script>
var data = JsFunction("@Html.Raw(Model.Path)");
$(function () {
    $("#btn").click(function () {
        var model = { Id: '@Html.Raw(Model.Id)', Data: data }
        $.ajax({
            type: "POST",
            url: "/Controller/Action",
            data: model,
            datatype: "html",
            success: function() {
                console.log('Success');
            }
        });
    });
});
</script>

JavaScript variable model is something that I need to pass to Razor ViewModel. It can be done with ajax request. You just need to have proper argument/s in your action, that matches Json object created in JavaScript.

Hope it'll help someone!

Spring Boot: Cannot access REST Controller on localhost (404)

Try adding the following to your InventoryApp class

@SpringBootApplication
@ComponentScan(basePackageClasses = ItemInventoryController.class)
public class InventoryApp {
...

spring-boot will scan for components in packages below com.nice.application, so if your controller is in com.nice.controller you need to scan for it explicitly.

Remove a marker from a GoogleMap

Make a global variable to keep track of marker

private Marker currentLocationMarker;

//Remove old marker

            if (null != currentLocationMarker) {
                currentLocationMarker.remove();
            }

// Add updated marker in and move the camera

            currentLocationMarker = mMap.addMarker(new MarkerOptions().position(
                    new LatLng(getLatitude(), getLongitude()))
                    .title("You are now Here").visible(true)
                    .icon(Utils.getMarkerBitmapFromView(getActivity(), R.drawable.auto_front))
                    .snippet("Updated Location"));

            currentLocationMarker.showInfoWindow();

HTML anchor tag with Javascript onclick event

Use following code to show menu instead go to href addres

_x000D_
_x000D_
function show_more_menu(e) {_x000D_
  if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
_x000D_
_x000D_

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

I just want to thank @Heapify for providing a practical answer and update his answer because the attached links are not up-to-date.

Step 1: Check the existing kernel of your Ubuntu Linux:

uname -a

Step 2:

Ubuntu maintains a website for all the versions of kernel that have been released. At the time of this writing, the latest stable release of Ubuntu kernel is 4.15. If you go to this link: http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/, you will see several links for download.

Step 3:

Download the appropriate files based on the type of OS you have. For 64 bit, I would download the following deb files:

// UP-TO-DATE 2019-03-18
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-headers-4.15.0-041500_4.15.0-041500.201802011154_all.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-headers-4.15.0-041500-generic_4.15.0-041500.201802011154_amd64.deb
wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-image-4.15.0-041500-generic_4.15.0-041500.201802011154_amd64.deb

Step 4:

Install all the downloaded deb files:

sudo dpkg -i *.deb

Step 5:

Reboot your machine and check if the kernel has been updated by:

uname -aenter code here

How do I get a UTC Timestamp in JavaScript?

I am amazed at how complex this question has become.

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

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

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

Parsing json and searching through it

Functions to search through and print dicts, like JSON. *made in python 3

Search:

def pretty_search(dict_or_list, key_to_search, search_for_first_only=False):
    """
    Give it a dict or a list of dicts and a dict key (to get values of),
    it will search through it and all containing dicts and arrays
    for all values of dict key you gave, and will return you set of them
    unless you wont specify search_for_first_only=True

    :param dict_or_list: 
    :param key_to_search: 
    :param search_for_first_only: 
    :return: 
    """
    search_result = set()
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if key == key_to_search:
                if search_for_first_only:
                    return key_value
                else:
                    search_result.add(key_value)
            if isinstance(key_value, dict) or isinstance(key_value, list) or isinstance(key_value, set):
                _search_result = pretty_search(key_value, key_to_search, search_for_first_only)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, list) or isinstance(element, set) or isinstance(element, dict):
                _search_result = pretty_search(element, key_to_search, search_result)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
                        search_result.add(result)
    return search_result if search_result else None

Print:

def pretty_print(dict_or_list, print_spaces=0):
    """
    Give it a dict key (to get values of),
    it will return you a pretty for print version
    of a dict or a list of dicts you gave.

    :param dict_or_list: 
    :param print_spaces: 
    :return: 
    """
    pretty_text = ""
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if isinstance(key_value, dict):
                key_value = pretty_print(key_value, print_spaces + 1)
                pretty_text += "\t" * print_spaces + "{}:\n{}\n".format(key, key_value)
            elif isinstance(key_value, list) or isinstance(key_value, set):
                pretty_text += "\t" * print_spaces + "{}:\n".format(key)
                for element in key_value:
                    if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                        pretty_text += pretty_print(element, print_spaces + 1)
                    else:
                        pretty_text += "\t" * (print_spaces + 1) + "{}\n".format(element)
            else:
                pretty_text += "\t" * print_spaces + "{}: {}\n".format(key, key_value)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                pretty_text += pretty_print(element, print_spaces + 1)
            else:
                pretty_text += "\t" * print_spaces + "{}\n".format(element)
    else:
        pretty_text += str(dict_or_list)
    if print_spaces == 0:
        print(pretty_text)
    return pretty_text

Python, Unicode, and the Windows console

Despite the other plausible-sounding answers that suggest changing the code page to 65001, that does not work. (Also, changing the default encoding using sys.setdefaultencoding is not a good idea.)

See this question for details and code that does work.

What is the difference between Normalize.css and Reset CSS?

This question has been answered already several times, I'll short summary for each of them, an example and insights as of September 2019:

  • Normalize.css - as the name suggests, it normalizes styles in the browsers for their user agents, i.e. makes them the same across all browsers due to the reason by default they're slightly different.

Example: <h1> tag inside <section> by default Google Chrome will make smaller than the "expected" size of <h1> tag. Microsoft Edge on the other hand is making the "expected" size of <h1> tag. Normalize.css will make it consistent.

Current status: the npm repository shows that normalize.css package has currently more than 500k downloads per week. GitHub stars in the project of the repository are more than 36k.

  • Reset CSS - as the name suggests, it resets all styles, i.e. it removes all browser's user agent styles.

Example: it would do something like that below:

html, body, div, span, ..., audio, video {  
   margin: 0;  
   padding: 0;  
   border: 0;  
   font-size: 100%;  
   font: inherit;  
   vertical-align: baseline; 
}

Current status: it's much less popular than Normalize.css, the reset-css package shows it's something around 26k downloads per week. GitHub stars are only 200, as it can be noticed from the project's repository.

Is there a way to make mv create the directory to be moved to if it doesn't exist?

This will move foo.c to the new directory baz with the parent directory bar.

mv foo.c `mkdir -p ~/bar/baz/ && echo $_`

The -p option to mkdir will create intermediate directories as required.
Without -p all directories in the path prefix must already exist.

Everything inside backticks `` is executed and the output is returned in-line as part of your command.
Since mkdir doesn't return anything, only the output of echo $_ will be added to the command.

$_ references the last argument to the previously executed command.
In this case, it will return the path to your new directory (~/bar/baz/) passed to the mkdir command.


I unzipped an archive without giving a destination and wanted to move all the files except demo-app.zip from my current directory to a new directory called demo-app.
The following line does the trick:

mv `ls -A | grep -v demo-app.zip` `mkdir -p demo-app && echo $_`

ls -A returns all file names including hidden files (except for the implicit . and ..).

The pipe symbol | is used to pipe the output of the ls command to grep (a command-line, plain-text search utility).
The -v flag directs grep to find and return all file names excluding demo-app.zip.
That list of files is added to our command-line as source arguments to the move command mv. The target argument is the path to the new directory passed to mkdir referenced using $_ and output using echo.

How to gracefully handle the SIGKILL signal in Java

You can use Runtime.getRuntime().addShutdownHook(...), but you cannot be guaranteed that it will be called in any case.

Pseudo-terminal will not be allocated because stdin is not a terminal

After reading a lot of these answers I thought I would share my resulting solution. All I added is /bin/bash before the heredoc and it doesn't give the error anymore.

Use this:

ssh user@machine /bin/bash <<'ENDSSH'
   hostname
ENDSSH

Instead of this (gives error):

ssh user@machine <<'ENDSSH'
   hostname
ENDSSH

Or use this:

ssh user@machine /bin/bash < run-command.sh

Instead of this (gives error):

ssh user@machine < run-command.sh

EXTRA:

If you still want a remote interactive prompt e.g. if the script you're running remotely prompts you for a password or other information, because the previous solutions won't allow you to type into the prompts.

ssh -t user@machine "$(<run-command.sh)"

And if you also want to log the entire session in a file logfile.log:

ssh -t user@machine "$(<run-command.sh)" | tee -a logfile.log

Android - Get value from HashMap

This with no warnings!

    HashMap<String, String> meMap=new HashMap<String, String>();
    meMap.put("Color1","Red");
    meMap.put("Color2","Blue");
    meMap.put("Color3","Green");
    meMap.put("Color4","White");

    for (Object o : meMap.keySet()) {
        Toast.makeText(getBaseContext(), meMap.get(o.toString()),
                Toast.LENGTH_SHORT).show();
    }

Why is datetime.strptime not working in this simple example?

You should use strftime static method from datetime class from datetime module. Try:

import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")

Concat a string to SELECT * MySql

You simply can't do that in SQL. You have to explicitly list the fields and concat each one:

SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1

If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?

Bad Request - Invalid Hostname IIS7

This page by Microsoft describes how to set up access to IIS Server Express from other computers on the local network.

In a nutshell:

1) from a command prompt with admin privileges:

netsh http add urlacl url=http://[your ip address]:8181/ user=everyone

2) In Windows Firewall with Advanced Security, create a new inbound rule for port 8181 to allow external connections

3) In applicationhost.config, in the node for your project, add:

<binding protocol="http" bindingInformation="*:8181:[your ip address]" />

Do NOT add (as was suggested in another answer):

<binding protocol="http" bindingInformation="*:8181:*" />

The above wildcard binding broke my access from http://192.168.1.6:8181/

Python: "TypeError: __str__ returned non-string" but still prints to output?

You can also surround the output with str(). I had this same problem because my model had the following (as a simplified example):

def __str__(self):
    return self.pressid

Where pressid was an IntegerField type object. Django (and python in general) expects a string for a str function, so returning an integer causes this error to be thrown.

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

That solved the problems I was encountering on the Django management side of the house. Hope it helps with yours.

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

enter image description here

Considering the particular column Amount in the above table is of integer type. The following would be a solution :

df['Amount'] = df.Amount.fillna(0).astype(int)

Similarly, you can fill it with various data types like float, str and so on.

In particular, I would consider datatype to compare various values of the same column.

hide/show a image in jquery

Use the .css() jQuery manipulators, or better yet just call .show()/.hide() on the image once you've obtained a handle to it (e.g. $('#img' + id)).

BTW, you should not write javascript handlers with the "javascript:" prefix.

Open file by its full path in C++

You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream ifs( "c:/demo.txt" );       // note no mode needed
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      cout <<"Opened OK" << endl;
   }
}

What does this code produce on your system?

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

This error occurs because you are using a normal string as a path. You can use one of the three following solutions to fix your problem:

1: Just put r before your normal string it converts normal string to raw string:

pandas.read_csv(r"C:\Users\DeePak\Desktop\myac.csv")

2:

pandas.read_csv("C:/Users/DeePak/Desktop/myac.csv")

3:

pandas.read_csv("C:\\Users\\DeePak\\Desktop\\myac.csv")

How to migrate GIT repository from one server to a new one

I'm just reposting what others have said, in a simple to follow list of instructions.

  1. Move the repository: Simply login to the new server, cd to the parent directory where you now want to hold the repository, and use rsync to copy from the old server:

    new.server> rsync -a -v -e ssh [email protected]:path/to/repository.git .
    
  2. Make clients point to the new repository: Now on each client using the repository, just remove the pointer to the old origin, and add one to the new one.

    client> git remote rm origin
    client> git remote add origin [email protected]:path/to/repository.git
    

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

How to position absolute inside a div?

One of #a or #b needs to be not position:absolute, so that #box will grow to accommodate it.

So you can stop #a from being position:absolute, and still position #b over the top of it, like this:

_x000D_
_x000D_
 #box {_x000D_
        background-color: #000;_x000D_
        position: relative;     _x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }_x000D_
    _x000D_
    .a {_x000D_
        width: 210px;_x000D_
        background-color: #fff;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    .b {_x000D_
        width: 100px; /* So you can see the other one */_x000D_
        position: absolute;_x000D_
        top: 10px; left: 10px;_x000D_
        background-color: red;_x000D_
        padding: 5px;_x000D_
    }_x000D_
    _x000D_
    #after {_x000D_
        background-color: yellow;_x000D_
        padding: 10px;_x000D_
        width: 220px;_x000D_
    }
_x000D_
    <div id="box">_x000D_
        <div class="a">Lorem</div>_x000D_
        <div class="b">Lorem</div>_x000D_
    </div>_x000D_
    <div id="after">Hello world</div>
_x000D_
_x000D_
_x000D_

(Note that I've made the widths different, so you can see one behind the other.)

Edit after Justine's comment: Then your only option is to specify the height of #box. This:

#box {
    /* ... */
    height: 30px;
}

works perfectly, assuming the heights of a and b are fixed. Note that you'll need to put IE into standards mode by adding a doctype at the top of your HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
          "http://www.w3.org/TR/html4/strict.dtd">

before that works properly.

adding onclick event to dynamically added button?

but.onclick = function() { yourjavascriptfunction();};

or

but.onclick = function() { functionwithparam(param);};

CSS word-wrapping in div

I'm a little surprised it doesn't just do that. Could there another element inside the div that has a width set to something greater than 250?

How to use Console.WriteLine in ASP.NET (C#) during debug?

Console.Write will not work in ASP.NET as it is called using the browser. Use Response.Write instead.

See Stack Overflow question Where does Console.WriteLine go in ASP.NET?.

If you want to write something to Output window during debugging, you can use

System.Diagnostics.Debug.WriteLine("SomeText");

but this will work only during debug.

See Stack Overflow question Debug.WriteLine not working.

if-else statement inside jsx: ReactJS

                        <Card style={{ backgroundColor: '#ffffff', height: 150, width: 250, paddingTop: 10 }}>
                            
                            <Text style={styles.title}>     {item.lastName}, {item.firstName} ({item.title})</Text> 
                            <Text >     Email: {item.email}</Text>
                            {item.lastLoginTime != null ? <Text >     Last Login: {item.lastLoginTime}</Text> : <Text >     Last Login: None</Text>}
                            {item.lastLoginTime != null ? <Text >     Status: Active</Text> : <Text >     Status: Inactive</Text>}
                           
                        </Card>

Getting "project" nuget configuration is invalid error

NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.

Updating Visual Studio to 'Update 2' got it working again.

Tools -> Extensions and Updates ->Visual Studio Update 2

As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.

Is there a concise way to iterate over a stream with indices in Java 8?

Here is code by AbacusUtil

Stream.of(names).indexed()
      .filter(e -> e.value().length() <= e.index())
      .map(Indexed::value).toList();

Disclosure: I'm the developer of AbacusUtil.

how to convert java string to Date object

"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".

So, try to change the code to:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate = df.parse(startDateString);

Edit: A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting. When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class DateTest {

        public static void main(String[] args) throws Exception {
            String startDateString = "06/27/2007";

            // This object can interpret strings representing dates in the format MM/dd/yyyy
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 

            // Convert from String to Date
            Date startDate = df.parse(startDateString);

            // Print the date, with the default formatting. 
            // Here, the important thing to note is that the parts of the date 
            // were correctly interpreted, such as day, month, year etc.
            System.out.println("Date, with the default formatting: " + startDate);

            // Once converted to a Date object, you can convert 
            // back to a String using any desired format.
            String startDateString1 = df.format(startDate);
            System.out.println("Date in format MM/dd/yyyy: " + startDateString1);

            // Converting to String again, using an alternative format
            DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy"); 
            String startDateString2 = df2.format(startDate);
            System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
        }
    }

Output:

Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007

How do I left align these Bootstrap form items?

Just my two cents. If you are using Bootstrap 3 then I would just add an extra style into your own site's stylesheet which controls the text-left style of the control-label.

If you were to add text-left to the label, by default there is another style which overrides this .form-horizontal .control-label. So if you add:

.form-horizontal .control-label.text-left{
    text-align: left;
}

Then the built in text-left style is applied to the label correctly.

Writing a list to a file with Python

Another way of iterating and adding newline:

for item in items:
    filewriter.write(f"{item}" + "\n")

What's the difference between HEAD^ and HEAD~ in Git?

Rules of thumb

  • Use ~ most of the time — to go back a number of generations, usually what you want
  • Use ^ on merge commits — because they have two or more (immediate) parents

Mnemonics:

  • Tilde ~ is almost linear in appearance and wants to go backward in a straight line
  • Caret ^ suggests an interesting segment of a tree or a fork in the road

Tilde

The “Specifying Revisions” section of the git rev-parse documentation defines ~ as

<rev>~<n>, e.g. master~3
A suffix ~<n> to a revision parameter means the commit object that is the nth generation ancestor of the named commit object, following only the first parents. For example, <rev>~3 is equivalent to <rev>^^^ which is equivalent to <rev>^1^1^1

You can get to parents of any commit, not just HEAD. You can also move back through generations: for example, master~2 means the grandparent of the tip of the master branch, favoring the first parent on merge commits.

Caret

Git history is nonlinear: a directed acyclic graph (DAG) or tree. For a commit with only one parent, rev~ and rev^ mean the same thing. The caret selector becomes useful with merge commits because each one is the child of two or more parents — and strains language borrowed from biology.

HEAD^ means the first immediate parent of the tip of the current branch. HEAD^ is short for HEAD^1, and you can also address HEAD^2 and so on as appropriate. The same section of the git rev-parse documentation defines it as

<rev>^, e.g. HEAD^, v1.5.1^0
A suffix ^ to a revision parameter means the first parent of that commit object. ^<n> means the nth parent ([e.g.] <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when <rev> is the object name of a tag object that refers to a commit object.

Examples

These specifiers or selectors can be chained arbitrarily, e.g., topic~3^2 in English is the second parent of the merge commit that is the great-grandparent (three generations back) of the current tip of the branch topic.

The aforementioned section of the git rev-parse documentation traces many paths through a notional git history. Time flows generally downward. Commits D, F, B, and A are merge commits.

Here is an illustration, by Jon Loeliger. Both commit nodes B and C are parents of commit node A. Parent commits are ordered left-to-right. (N.B. The git log --graph command displays history in the opposite order.)

G   H   I   J
 \ /     \ /
  D   E   F
   \  |  / \
    \ | /   |
     \|/    |
      B     C
       \   /
        \ /
         A

A =      = A^0
B = A^   = A^1     = A~1
C = A^2
D = A^^  = A^1^1   = A~2
E = B^2  = A^^2
F = B^3  = A^^3
G = A^^^ = A^1^1^1 = A~3
H = D^2  = B^^2    = A^^^2  = A~2^2
I = F^   = B^3^    = A^^3^
J = F^2  = B^3^2   = A^^3^2

Run the code below to create a git repository whose history matches the quoted illustration.

#! /usr/bin/env perl

use strict;
use warnings;
use subs qw/ postorder /;
use File::Temp qw/ mkdtemp /;

my %sha1;
my %parents = (
  A => [ qw/ B C /               ],
  B => [ qw/     D E F /         ],
  C => [ qw/         F /         ],
  D => [ qw/           G H /     ],
  F => [ qw/               I J / ],
);

sub postorder {
  my($root,$hash) = @_;
  my @parents = @{ $parents{$root} || [] };
  postorder($_, $hash) for @parents;
  return if $sha1{$root};
  @parents = map "-p $sha1{$_}", @parents;
  chomp($sha1{$root} = `git commit-tree @parents -m "$root" $hash`);
  die "$0: git commit-tree failed" if $?;
  system("git tag -a -m '$sha1{$root}' '$root' '$sha1{$root}'") == 0 or die "$0: git tag failed";
}

$0 =~ s!^.*/!!;  # / fix Stack Overflow highlighting
my $repo = mkdtemp "repoXXXXXXXX";
chdir $repo or die "$0: chdir: $!";
system("git init") == 0               or die "$0: git init failed";
chomp(my $tree = `git write-tree`);      die "$0: git write-tree failed" if $?;

postorder 'A', $tree;
system "git update-ref HEAD   $sha1{A}"; die "$0: git update-ref failed" if $?;
system "git update-ref master $sha1{A}"; die "$0: git update-ref failed" if $?;

# for browsing history - http://blog.kfish.org/2010/04/git-lola.html
system "git config alias.lol  'log --graph --decorate --pretty=oneline --abbrev-commit'";
system "git config alias.lola 'log --graph --decorate --pretty=oneline --abbrev-commit --all'";

It adds aliases in the new throwaway repo only for git lol and git lola so you can view history as in

$ git lol
*   29392c8 (HEAD -> master, tag: A) A
|\
| * a1ef6fd (tag: C) C
| |
|  \
*-. \   8ae20e9 (tag: B) B
|\ \ \
| | |/
| | *   03160db (tag: F) F
| | |\
| | | * 9df28cb (tag: J) J
| | * 2afd329 (tag: I) I
| * a77cb1f (tag: E) E
*   cd75703 (tag: D) D
|\
| * 3043d25 (tag: H) H
* 4ab0473 (tag: G) G

Note that on your machine the SHA-1 object names will differ from those above, but the tags allow you to address commits by name and check your understanding.

$ git log -1 --format=%f $(git rev-parse A^)
B
$ git log -1 --format=%f $(git rev-parse A~^3~)
I
$ git log -1 --format=%f $(git rev-parse A^2~)
F

The “Specifying Revisions” in the git rev-parse documentation is full of great information and is worth an in-depth read. See also Git Tools - Revision Selection from the book Pro Git.

Order of Parent Commits

The commit 89e4fcb0dd from git’s own history is a merge commit, as git show 89e4fcb0dd indicates with the Merge header line that displays the immediate ancestors’ object names.

commit 89e4fcb0dd01b42e82b8f27f9a575111a26844df
Merge: c670b1f876 649bf3a42f b67d40adbb
Author: Junio C Hamano <[email protected]>
Date:   Mon Oct 29 10:15:31 2018 +0900

    Merge branches 'bp/reset-quiet' and 'js/mingw-http-ssl' into nd/config-split […]

We can confirm the ordering by asking git rev-parse to show 89e4fcb0dd’s immediate parents in sequence.

$ git rev-parse 89e4fcb0dd^1 89e4fcb0dd^2 89e4fcb0dd^3
c670b1f876521c9f7cd40184bf7ed05aad843433
649bf3a42f344e71b1b5a7f562576f911a1f7423
b67d40adbbaf4f5c4898001bf062a9fd67e43368

Querying the non-existent fourth parent results in an error.

$ git rev-parse 89e4fcb0dd^4
89e4fcb0dd^4
fatal: ambiguous argument '89e4fcb0dd^4': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

If you want to extract the parents only, use pretty format %P for the full hashes

$ git log -1 --pretty=%P 89e4fcb0dd
c670b1f876521c9f7cd40184bf7ed05aad843433 649bf3a42f344e71b1b5a7f562576f911a1f7423 b67d40adbbaf4f5c4898001bf062a9fd67e43368

or %p for abbreviated parents.

$ git log -1 --pretty=%p 89e4fcb0dd
c670b1f876 649bf3a42f b67d40adbb

Linq Query Group By and Selecting First Items

var result = list.GroupBy(x => x.Category).Select(x => x.First())

How to recover a dropped stash in Git?

Windows PowerShell equivalent using gitk:

gitk --all $(git fsck --no-reflog | Select-String "(dangling commit )(.*)" | %{ $_.Line.Split(' ')[2] })

There is probably a more efficient way to do this in one pipe, but this does the job.

How to start jenkins on different port rather than 8080 using command prompt in Windows?

Open Command Prompt as Administrator in Windows . Go to the directory where Jenkins is installed. and stop the Jenkins service first, using jenkins.exe stop

type the command to change the port using, java -jar jenkins.war --httpPort=9090 (enter the port number you want to use).

and at-last, restart the Jenkins services, using jenkins.exe restart

How to pass 2D array (matrix) in a function in C?

C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:

1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:

#define ROWS 4
#define COLS 5

void func(int array[ROWS][COLS])
{
  int i, j;

  for (i=0; i<ROWS; i++)
  {
    for (j=0; j<COLS; j++)
    {
      array[i][j] = i*j;
    }
  }
}

void func_vla(int rows, int cols, int array[rows][cols])
{
  int i, j;

  for (i=0; i<rows; i++)
  {
    for (j=0; j<cols; j++)
    {
      array[i][j] = i*j;
    }
  }
}

int main()
{
  int x[ROWS][COLS];

  func(x);
  func_vla(ROWS, COLS, x);
}

2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.

void func(int** array, int rows, int cols)
{
  int i, j;

  for (i=0; i<rows; i++)
  {
    for (j=0; j<cols; j++)
    {
      array[i][j] = i*j;
    }
  }
}

int main()
{
  int rows, cols, i;
  int **x;

  /* obtain values for rows & cols */

  /* allocate the array */
  x = malloc(rows * sizeof *x);
  for (i=0; i<rows; i++)
  {
    x[i] = malloc(cols * sizeof *x[i]);
  }

  /* use the array */
  func(x, rows, cols);

  /* deallocate the array */
  for (i=0; i<rows; i++)
  {
    free(x[i]);
  }
  free(x);
}

3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:

void func(int* array, int rows, int cols)
{
  int i, j;

  for (i=0; i<rows; i++)
  {
    for (j=0; j<cols; j++)
    {
      array[i*cols+j]=i*j;
    }
  }
}

int main()
{
  int rows, cols;
  int *x;

  /* obtain values for rows & cols */

  /* allocate the array */
  x = malloc(rows * cols * sizeof *x);

  /* use the array */
  func(x, rows, cols);

  /* deallocate the array */
  free(x);
}

4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

extern void func_vla(int rows, int cols, int array[rows][cols]);
extern void get_rows_cols(int *rows, int *cols);
extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);

void func_vla(int rows, int cols, int array[rows][cols])
{
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            array[i][j] = (i + 1) * (j + 1);
        }
    }
}

int main(void)
{
    int rows, cols;

    get_rows_cols(&rows, &cols);

    int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
    /* error check omitted */

    func_vla(rows, cols, array);
    dump_array("After initialization", rows, cols, array);

    free(array);
    return 0;
}

void dump_array(const char *tag, int rows, int cols, int array[rows][cols])
{
    printf("%s (%dx%d):\n", tag, rows, cols);
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
            printf("%4d", array[i][j]);
        putchar('\n');
    }
}

void get_rows_cols(int *rows, int *cols)
{
    srand(time(0));           // Only acceptable because it is called once
    *rows = 5 + rand() % 10;
    *cols = 3 + rand() % 12;
}

(See srand() — why call it only once?.)

How to merge 2 JSON objects from 2 files using jq?

Since 1.4 this is now possible with the * operator. When given two objects, it will merge them recursively. For example,

jq -s '.[0] * .[1]' file1 file2

Important: Note the -s (--slurp) flag, which puts files in the same array.

Would get you:

{
  "value1": 200,
  "timestamp": 1382461861,
  "value": {
    "aaa": {
      "value1": "v1",
      "value2": "v2",
      "value3": "v3",
      "value4": 4
    },
    "bbb": {
      "value1": "v1",
      "value2": "v2",
      "value3": "v3"
    },
    "ccc": {
      "value1": "v1",
      "value2": "v2"
    },
    "ddd": {
      "value3": "v3",
      "value4": 4
    }
  },
  "status": 200
}

If you also want to get rid of the other keys (like your expected result), one way to do it is this:

jq -s '.[0] * .[1] | {value: .value}' file1 file2

Or the presumably somewhat more efficient (because it doesn't merge any other values):

jq -s '.[0].value * .[1].value | {value: .}' file1 file2

Easiest way to compare arrays in C#

You could use Enumerable.SequenceEqual. This works for any IEnumerable<T>, not just arrays.

How to define servlet filter order of execution using annotations in WAR

  1. Make the servlet filter implement the spring Ordered interface.
  2. Declare the servlet filter bean manually in configuration class.
    import org.springframework.core.Ordered;
    
    public class MyFilter implements Filter, Ordered {

        @Override
        public void init(FilterConfig filterConfig) {
            // do something
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            // do something
        }

        @Override
        public void destroy() {
            // do something
        }

        @Override
        public int getOrder() {
            return -100;
        }
    }


    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ComponentScan
    public class MyAutoConfiguration {

        @Bean
        public MyFilter myFilter() {
            return new MyFilter();
        }
    }

How to create an Array with AngularJS's ng-model

You can do a variety of things. What I would do is this.

Create an array on scope that will be your data structure for the phone numbers.

$scope.telephone = '';
$scope.numbers = [];

Then in your html I would have this

<input type="text" ng-model="telephone">
<button ng-click="submitNumber()">Submit</button>

Then when your user clicks submit, run submitNumber(), which pushes the new telephone number into the numbers array.

$scope.submitNumber = function(){
  $scope.numbers.push($scope.telephone);
}

Jquery $.ajax fails in IE on cross domain calls

Jquery does this for you, only thing is to set $.support.cors = true; Then cross domain request works fine in all browsers for jquery users.

What is a magic number, and why is it bad?

A Magic Number is a hard-coded value that may change at a later stage, but that can be therefore hard to update.

For example, let's say you have a Page that displays the last 50 Orders in a "Your Orders" Overview Page. 50 is the Magic Number here, because it's not set through standard or convention, it's a number that you made up for reasons outlined in the spec.

Now, what you do is you have the 50 in different places - your SQL script (SELECT TOP 50 * FROM orders), your Website (Your Last 50 Orders), your order login (for (i = 0; i < 50; i++)) and possibly many other places.

Now, what happens when someone decides to change 50 to 25? or 75? or 153? You now have to replace the 50 in all the places, and you are very likely to miss it. Find/Replace may not work, because 50 may be used for other things, and blindly replacing 50 with 25 can have some other bad side effects (i.e. your Session.Timeout = 50 call, which is also set to 25 and users start reporting too frequent timeouts).

Also, the code can be hard to understand, i.e. "if a < 50 then bla" - if you encounter that in the middle of a complicated function, other developers who are not familiar with the code may ask themselves "WTF is 50???"

That's why it's best to have such ambiguous and arbitrary numbers in exactly 1 place - "const int NumOrdersToDisplay = 50", because that makes the code more readable ("if a < NumOrdersToDisplay", it also means you only need to change it in 1 well defined place.

Places where Magic Numbers are appropriate is everything that is defined through a standard, i.e. SmtpClient.DefaultPort = 25 or TCPPacketSize = whatever (not sure if that is standardized). Also, everything only defined within 1 function might be acceptable, but that depends on Context.

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

How to use: while not in

If I understand the question correctly you are looking for something like this:

>>> s = "a1 c2 OR c3 AND"
>>> boolops = ["AND", "OR", "NOT"]
>>> if not any(boolop in s for boolop in boolops):
...     print "no boolean operator"
... 
>>> s = "test"
>>> if not any(boolop in s for boolop in boolops):
...     print "no boolean operator"
... 
no boolean operator
>>> 

How are Anonymous inner classes used in Java?

You can use anonymous class this way

TreeSet treeSetObj = new TreeSet(new Comparator()
{
    public int compare(String i1,String i2)
    {
        return i2.compareTo(i1);
    }
});

how to install tensorflow on anaconda python 3.6

This is what I did for Installing Anaconda Python 3.6 version and Tensorflow on Window 10 64bit.And It was success!

  1. Download Anaconda Python 3.6 version for Window 64bit.

  2. Create a conda environment named tensorflow by invoking the following command:

    C:> conda create -n tensorflow 
    
  3. Activate the conda environment by issuing the following command:

    C:> activate tensorflow
    (tensorflow)C:>  # Your prompt should change 
    
  4. Download “tensorflow-1.0.1-cp36-cp36m-win_amd64.whl” from here. (For my case, the file will be located in “C:\Users\Joshua\Downloads” once after downloaded).

  5. Install the Tensorflow by using following command:

    (tensorflow)C:>pip install C:\Users\Joshua\Downloads\ tensorflow-1.0.1-cp36-cp36m-win_amd64.whl
    

This is what I got after the installing: enter image description here

  1. Validate installation by entering following command in your Python environment:

    import tensorflow as tf
    hello = tf.constant('Hello, TensorFlow!')
    sess = tf.Session()
    print(sess.run(hello))
    

If the output you got is 'Hello, TensorFlow!',that means you have successfully install your Tensorflow.

How can I generate an apk that can run without server with react-native?

for React Native 0.49 and over

you should go to project directory on terminal and run that command

1 - mkdir android/app/src/main/assets
2 - react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

if under 0.49

  1 - mkdir android/app/src/main/assets
  2 - react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Then Use android studio to open the 'android' folder in you react native app directory, it will ask to upgrade gradle and some other stuff. go to build-> Generate signed APK and follow the instructions from there. That okey.

Splitting a string into chunks of a certain size

It's not pretty and it's not fast, but it works, it's a one-liner and it's LINQy:

List<string> a = text.Select((c, i) => new { Char = c, Index = i }).GroupBy(o => o.Index / 4).Select(g => new String(g.Select(o => o.Char).ToArray())).ToList();

http://localhost:50070 does not work HADOOP

  • step 1 : bin/stop-all.sh
  • step 2 : bin/hadoop namenode -format
  • step 3 : bin/start-all.sh

Create an enum with string values

In latest version (1.0RC) of TypeScript, you can use enums like this:

enum States {
    New,
    Active,
    Disabled
} 

// this will show message '0' which is number representation of enum member
alert(States.Active); 

// this will show message 'Disabled' as string representation of enum member
alert(States[States.Disabled]);

Update 1

To get number value of enum member from string value, you can use this:

var str = "Active";
// this will show message '1'
alert(States[str]);

Update 2

In latest TypeScript 2.4, there was introduced string enums, like this:

enum ActionType {
    AddUser = "ADD_USER",
    DeleteUser = "DELETE_USER",
    RenameUser = "RENAME_USER",

    // Aliases
    RemoveUser = DeleteUser,
}

For more info about TypeScript 2.4, read blog on MSDN.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!

(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)

You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View-> Edit in Visual Studio.... It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

How can I return two values from a function in Python?

You can return more than one value using list also. Check the code below

def newFn():    #your function
  result = []    #defining blank list which is to be return
  r1 = 'return1'    #first value
  r2 = 'return2'    #second value
  result.append(r1)    #adding first value in list
  result.append(r2)    #adding second value in list
  return result    #returning your list

ret_val1 = newFn()[1]    #you can get any desired result from it
print ret_val1    #print/manipulate your your result

How to load data to hive from HDFS without removing the source file?

I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').

When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.

If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).

Circle button css

Add display: block;. That's the difference between a <div> tag and an <a> tag

.btn {
      display: block;
      height: 300px;
      width: 300px;
      border-radius: 50%;
      border: 1px solid red;
    }

Google MAP API v3: Center & Zoom on displayed markers

I've also find this fix that zooms to fit all markers

LatLngList: an array of instances of latLng, for example:

// "map" is an instance of GMap3

var LatLngList = [
                     new google.maps.LatLng (52.537,-2.061), 
                     new google.maps.LatLng (52.564,-2.017)
                 ],
    latlngbounds = new google.maps.LatLngBounds();

LatLngList.forEach(function(latLng){
   latlngbounds.extend(latLng);
});

// or with ES6:
// for( var latLng of LatLngList)
//    latlngbounds.extend(latLng);

map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds); 

How to reposition Chrome Developer Tools

Chrome 46 or newer

Click the vertical ellipsis button ( ? ) then choose the desired docking option.

Chrome 45 or older

Long-hold the dock icon in the top right. It pops up an option to change the docking

To change the split between the HTML and CSS panels, go in DevTools to Settings (F1) > General > Appearance > Panel Layout.

Modulo operator in Python

In addition to the other answers, the fmod documentation has some interesting things to say on the subject:

math.fmod(x, y)

Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

How does true/false work in PHP?

Zero is false, nonzero is true.

In php you can test more explicitly using the === operator.

if (0==false) 
    echo "works"; // will echo works

if (0===false) 
    echo "works"; // will not echo anything

How to instantiate, initialize and populate an array in TypeScript?

If you really want to have named parameters plus have your objects be instances of your class, you can do the following:

class bar {
    constructor (options?: {length: number; height: number;}) {
        if (options) {
            this.length = options.length;
            this.height = options.height;
        }
    }
    length: number;
    height: number;
}

class foo {
    bars: bar[] = new Array();
}

var ham = new foo();
ham.bars = [
    new bar({length: 4, height: 2}),
    new bar({length: 1, height: 3})
];

Also here's the related item on typescript issue tracker.