Programs & Examples On #Header

This tag is deprecated because it lacks discriminating power. Please use a more specific tag instead, e.g.: html-heading, email-header etc.

Emulate a 403 error page

Seen a lot of the answers, but the correct one is to provide the full options for the header function call as per the php manual

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

If you invoke with

header('HTTP/1.0 403 Forbidden', true, 403);

the normal behavior of HTTP 403 as configured with Apache or any other server would follow.

Where does gcc look for C and C++ header files?

One could view the (additional) include path for a C program from bash by checking out the following:

echo $C_INCLUDE_PATH

If this is empty, it could be modified to add default include locations, by:

export C_INCLUDE_PATH=$C_INCLUDE_PATH:/usr/include

Cannot set some HTTP headers when using System.Net.WebRequest

WebRequest being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?

ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.

Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See this post for instance.

Variable declaration in a header file

What about this solution?

#ifndef VERSION_H
#define VERSION_H

static const char SVER[] = "14.2.1";
static const char AVER[] = "1.1.0.0";

#else

extern static const char SVER[];
extern static const char AVER[];

#endif /*VERSION_H */

The only draw back I see is that the include guard doesn't save you if you include it twice in the same file.

How to fix "Headers already sent" error in PHP

This error message gets triggered when anything is sent before you send HTTP headers (with setcookie or header). Common reasons for outputting something before the HTTP headers are:

  • Accidental whitespace, often at the beginning or end of files, like this:

     <?php
    // Note the space before "<?php"
    ?>
    

       To avoid this, simply leave out the closing ?> - it's not required anyways.

  • Byte order marks at the beginning of a php file. Examine your php files with a hex editor to find out whether that's the case. They should start with the bytes 3F 3C. You can safely remove the BOM EF BB BF from the start of files.
  • Explicit output, such as calls to echo, printf, readfile, passthru, code before <? etc.
  • A warning outputted by php, if the display_errors php.ini property is set. Instead of crashing on a programmer mistake, php silently fixes the error and emits a warning. While you can modify the display_errors or error_reporting configurations, you should rather fix the problem.
    Common reasons are accesses to undefined elements of an array (such as $_POST['input'] without using empty or isset to test whether the input is set), or using an undefined constant instead of a string literal (as in $_POST[input], note the missing quotes).

Turning on output buffering should make the problem go away; all output after the call to ob_start is buffered in memory until you release the buffer, e.g. with ob_end_flush.

However, while output buffering avoids the issues, you should really determine why your application outputs an HTTP body before the HTTP header. That'd be like taking a phone call and discussing your day and the weather before telling the caller that he's got the wrong number.

Auto generate function documentation in Visual Studio

Visual Assist has a nice solution too, and is highly costumizable.

After tweaking it to generate doxygen-style comments, these two clicks would produce -

/**
* Method:    FindTheFoo
* FullName:  FindTheFoo
* Access:    private 
* Qualifier:
* @param    int numberOfFoos
* @return   bool
*/
private bool FindTheFoo(int numberOfFoos)
{

}

(Under default settings, its a bit different.)


Edit: The way to customize the 'document method' text is under VassistX->Visual Assist Options->Suggestions, select 'Edit VA Snippets', Language: C++, Type: Refactoring, then go to 'Document Method' and customize. The above example is generated by:

va_doxy

HTTP Range header

For folks who are stumbling across Victor Stoddard's answer above in 2019, and become hopeful and doe eyed, note that:

a) Support for X-Content-Duration was removed in Firefox 41: https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/41#HTTP

b) I think it was only supported in Firefox for .ogg audio and .ogv video, not for any other types.

c) I can't see that it was ever supported at all in Chrome, but that may just be a lack of research on my part. But its presence or absence seems to have no effect one way or another for webm or ogv videos as of today in Chrome 71.

d) I can't find anywhere where 'Content-Duration' replaced 'X-Content-Duration' for anything, I don't think 'X-Content-Duration' lived long enough for there to be a successor header name.

I think this means that, as of today if you want to serve webm or ogv containers that contain streams that don't know their duration (e.g. the output of an ffpeg pipe) to Chrome or FF, and you want them to be scrubbable in an HTML 5 video element, you are probably out of luck. Firefox 64.0 makes a half hearted attempt to make these scrubbable whether or not you serve via range requests, but it gets confused and throws up a spinning wheel until the stream is completely downloaded if you seek a few times more than it thinks is appropriate. Chrome doesn't even try, it just nopes out and won't let you scrub at all until the entire stream is finished playing.

How to use HTML to print header and footer on every printed page of a document?

Use page breaks to define the styles in CSS:

@media all
  {
  #page-one, .footer, .page-break { display:none; }
  }

@media print
  {
  #page-one, .footer, .page-break   
    { 
    display: block;
    color:red; 
    font-family:Arial; 
    font-size: 16px; 
    text-transform: uppercase; 
    }
  .page-break
    {
    page-break-before:always;
    } 
}

Then add the markup in the document at the appropriate places:

<h2 id="page-one">unclassified</h2>
<!-- content block -->
<h2 class="footer">unclassified</h2>
<h2 class="page-break">unclassified</h2>
<!-- content block -->
<h2 class="footer">unclassified</h2>
<h2 class="page-break">unclassified</h2>
<!-- content block -->
<h2 class="footer">unclassified</h2>
<h2 class="page-break">unclassified</h2>
<!-- content block -->
<h2 class="footer">unclassified</h2>
<h2 class="page-break">unclassified</h2>

References

header location not working in my php code

That is because you have an output:

?>
<?php

results in blank line output.

header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Combine all your PHP codes and make sure you don't have any spaces at the beginning of the file.

also after header('location: index.php'); add exit(); if you have any other scripts bellow.

Also move your redirect header after the last if.

If there is content, then you can also redirect by injecting javascript:

<?php
    echo "<script>window.location.href='target.php';</script>";
    exit;
?>

I have Python on my Ubuntu system, but gcc can't find Python.h

You have to use #include "python2.7/Python.h" instead of #include "Python.h".

Adding header to all request with Retrofit 2

RetrofitHelper library written in kotlin, will let you make API calls, using a few lines of code.

Add headers in your application class like this :

class Application : Application() {

    override fun onCreate() {
    super.onCreate()

        retrofitClient = RetrofitClient.instance
                    //api url
                .setBaseUrl("https://reqres.in/")
                    //you can set multiple urls
        //                .setUrl("example","http://ngrok.io/api/")
                    //set timeouts
                .setConnectionTimeout(4)
                .setReadingTimeout(15)
                    //enable cache
                .enableCaching(this)
                    //add Headers
                .addHeader("Content-Type", "application/json")
                .addHeader("client", "android")
                .addHeader("language", Locale.getDefault().language)
                .addHeader("os", android.os.Build.VERSION.RELEASE)
            }

        companion object {
        lateinit var retrofitClient: RetrofitClient

        }
    }  

And then make your call:

retrofitClient.Get<GetResponseModel>()
            //set path
            .setPath("api/users/2")
            //set url params Key-Value or HashMap
            .setUrlParams("KEY","Value")
            // you can add header here
            .addHeaders("key","value")
            .setResponseHandler(GetResponseModel::class.java,
                object : ResponseHandler<GetResponseModel>() {
                    override fun onSuccess(response: Response<GetResponseModel>) {
                        super.onSuccess(response)
                        //handle response
                    }
                }).run(this)

For more information see the documentation

Using G++ to compile multiple .cpp and .h files

You can use several g++ commands and then link, but the easiest is to use a traditional Makefile or some other build system: like Scons (which are often easier to set up than Makefiles).

How to add an Access-Control-Allow-Origin header

For Java based Application add this to your web.xml file:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.ttf</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.otf</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.eot</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.woff</url-pattern>
</servlet-mapping>

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

Define constant variables in C++ header

Rather than making a bunch of global variables, you might consider creating a class that has a bunch of public static constants. It's still global, but this way it's wrapped in a class so you know where the constant is coming from and that it's supposed to be a constant.

Constants.h

#ifndef CONSTANTS_H
#define CONSTANTS_H

class GlobalConstants {
  public:
    static const int myConstant;
    static const int myOtherConstant;
};

#endif

Constants.cpp

#include "Constants.h"

const int GlobalConstants::myConstant = 1;
const int GlobalConstants::myOtherConstant = 3;

Then you can use this like so:

#include "Constants.h"

void foo() {
  int foo = GlobalConstants::myConstant;
}

Why has it failed to load main-class manifest attribute from a JAR file?

If your class path is fully specified in manifest, maybe you need the last version of java runtime environment. My problem fixed when i reinstalled the jre 8.

Warning: Cannot modify header information - headers already sent by ERROR

Check something with echo, print() or printr() in the include file, header.php.

It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>. This could also make a problem.

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

Where does Visual Studio look for C++ header files?

Visual Studio looks for headers in this order:

  • In the current source directory.
  • In the Additional Include Directories in the project properties (Project -> [project name] Properties, under C/C++ | General).
  • In the Visual Studio C++ Include directories under Tools ? Options ? Projects and Solutions ? VC++ Directories.
  • In new versions of Visual Studio (2015+) the above option is deprecated and a list of default include directories is available at Project Properties ? Configuration ? VC++ Directories

In your case, add the directory that the header is to the project properties (Project Properties ? Configuration ? C/C++ ? General ? Additional Include Directories).

What is the difference between a .cpp file and a .h file?

By convention, .h files are included by other files, and never compiled directly by themselves. .cpp files are - again, by convention - the roots of the compilation process; they include .h files directly or indirectly, but generally not .cpp files.

How do you POST to a page using the PHP header() function?

There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/

Concatenate multiple files but include filename as section headers

First I created each file: echo 'information' > file1.txt for each file[123].txt.

Then I printed each file to makes sure information was correct: tail file?.txt

Then I did this: tail file?.txt >> Mainfile.txt. This created the Mainfile.txt to store the information in each file into a main file.

cat Mainfile.txt confirmed it was okay.

==> file1.txt <== bluemoongoodbeer

==> file2.txt <== awesomepossum

==> file3.txt <== hownowbrowncow

jQuery and AJAX response header

The underlying XMLHttpRequest object used by jQuery will always silently follow redirects rather than return a 302 status code. Therefore, you can't use jQuery's AJAX request functionality to get the returned URL. Instead, you need to put all the data into a form and submit the form with the target attribute set to the value of the name attribute of the iframe:

$('#myIframe').attr('name', 'myIframe');

var form = $('<form method="POST" action="url.do"></form>').attr('target', 'myIframe');
$('<input type="hidden" />').attr({name: 'search', value: 'test'}).appendTo(form);

form.appendTo(document.body);
form.submit();

The server's url.do page will be loaded in the iframe, but when its 302 status arrives, the iframe will be redirected to the final destination.

How to add header row to a pandas DataFrame

Alternatively you could read you csv with header=None and then add it with df.columns:

Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]

PHP header redirect 301 - what are the implications?

Search engines like 301 redirects better than a 404 or some other type of client side redirect, no worries there.

CPU usage will be minimal, if you want to save even more cycles you could try and handle the redirect in apache using htaccess, then php won't even have to get involved. If you want to load test a server, you can use ab which comes with apache, or httperf if you are looking for a more robust testing tool.

Javascript : Send JSON Object with Ajax?

I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.

Wrap up content like below,

var params = {
            "IDs": IDs,
            "ID2s": IDs2,
            "id": 1
        };

In my case I had already json'd the arrays and passed the result to the function

var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());

Then call the XMLHttpRequest POST and stringify the object

var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");           
ajax.onreadystatechange = function () {
    if (this.readyState == 4) {
       var blob = new Blob([this.response], { type: "application/octet-stream" });
       saveAs(blob, "filename.zip");
    }
};

ajax.send(JSON.stringify(params));

Then have a model like this

public class MyModel
{
    public int[] IDs { get; set; }
    public int[] ID2s { get; set; }
    public int id { get; set; }
}

Then pass in Action like

public async Task<IActionResult> MyAction([FromBody] MyModel model)

Use this add-on if your returning a file

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>

X-Frame-Options Allow-From multiple domains

Strictly speaking no, you cant.

You can however specify X-Frame-Options: mysite.com and therefore allow subdomain1.mysite.com and subdomain2.mysite.com. But yes, that's still one domain. There happens to be some workaround for this, but I think it's easiest to read that directly at the RFC specs: https://tools.ietf.org/html/rfc7034

It's also worth to point out that the Content-Security-Policy (CSP) header's frame-ancestor directive obsoletes X-Frame-Options. Read more here.

Redirecting a request using servlets and the "setHeader" method not working

Alternatively, you could try the following,

resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");

Fixed header table with horizontal scrollbar and vertical scrollbar on

Here's a solution which again is not a CSS only solution. It is similar to avrahamcool's solution in that it uses a few lines of jQuery, but instead of changing heights and moving the header along, all it does is changing the width of tbody based on how far its parent table is scrolled along to the right.

An added bonus with this solution is that it works with a semantically valid HTML table.

It works great on all recent browser versions (IE10, Chrome, FF) and that's it, the scrolling functionality breaks on older versions.

But then the fact that you are using a semantically valid HTML table will save the day and ensure the table is still displayed properly, it's only the scrolling functionality that won't work on older browsers.

Here's a jsFiddle for demonstration purposes.

CSS

table {
    width: 300px;
    overflow-x: scroll;
    display: block;
}
thead, tbody {
    display: block;
}
tbody {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 140px;
}
td, th {
    min-width: 100px;
}

JS

$("table").on("scroll", function () {
    $("table > *").width($("table").width() + $("table").scrollLeft());
});

I needed a version which degrades nicely in IE9 (no scrolling, just a normal table). Posting the fiddle here as it is an improved version. All you need to do is set a height on the tr.

Additional CSS to make this solution degrade nicely in IE9

tr {
    height: 25px; /* This could be any value, it just needs to be set. */ 
}

Here's a jsFiddle demonstrating the nicely degrading in IE9 version of this solution.

Edit: Updated fiddle links to link to a version of the fiddle which contains fixes for issues mentioned in the comments. Just adding a snippet with the latest and greatest version while I'm at it:

_x000D_
_x000D_
$('table').on('scroll', function() {_x000D_
  $("table > *").width($("table").width() + $("table").scrollLeft());_x000D_
});
_x000D_
html {_x000D_
  font-family: verdana;_x000D_
  font-size: 10pt;_x000D_
  line-height: 25px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
  width: 300px;_x000D_
  overflow-x: scroll;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
thead {_x000D_
  background-color: #EFEFEF;_x000D_
}_x000D_
_x000D_
thead,_x000D_
tbody {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
tbody {_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  height: 140px;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  min-width: 100px;_x000D_
  height: 25px;_x000D_
  border: dashed 1px lightblue;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  max-width: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column 1</th>_x000D_
      <th>Column 2</th>_x000D_
      <th>Column 3</th>_x000D_
      <th>Column 4</th>_x000D_
      <th>Column 5</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>AAAAAAAAAAAAAAAAAAAAAAAAAA</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

PHP header(Location: ...): Force URL change in address bar

use

header("Location: index.php"); //this work in my site

read more on header() at php documentation.

How to fix a header on scroll

Hopefully this one piece of an alternate solution will be as valuable to someone else as it was for me.

Situation:
In an HTML5 page I had a menu that was a nav element inside a header (not THE header but a header in another element).
I wanted the navigation to stick to the top once a user scrolled to it, but previous to this the header was absolute positioned (so I could have it overlay something else slightly).
The solutions above never triggered a change because .offsetTop was not going to change as this was an absolute positioned element. Additionally the .scrollTop property was simply the top of the top most element... that is to say 0 and always would be 0.
Any tests I performed utilizing these two (and same with getBoundingClientRect results) would not tell me if the top of the navigation bar ever scrolled to the top of the viewable page (again, as reported in console, they simply stayed the same numbers while scrolling occurred).

Solution
The solution for me was utilizing

window.visualViewport.pageTop

The value of the pageTop property reflects the viewable section of the screen, therefore allowing me to track where an element is in reference to the boundaries of the viewable area.
This allowed a simple function assigned to the scroll event of the window to detect when the top of the navigation bar intersected with the top of the viewable area and apply the styling to make it stick to the top.

Probably unnecessary to say, anytime I am dealing with scrolling I expect to use this solution to programatically respond to movement of elements being scrolled.
Hope it helps someone else.

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Found the flex magic.

Here's an example of how to do a fixed header and a scrollable content. Code:

<!DOCTYPE html>
<html style="height: 100%">
  <head>
    <meta charset=utf-8 />
    <title>Holy Grail</title>
    <!-- Reset browser defaults -->
    <link rel="stylesheet" href="reset.css">
  </head>
  <body style="display: flex; height: 100%; flex-direction: column">
    <div>HEADER<br/>------------
    </div>
    <div style="flex: 1; overflow: auto">
        CONTENT - START<br/>
        <script>
        for (var i=0 ; i<1000 ; ++i) {
          document.write(" Very long content!");
        }
        </script>
        <br/>CONTENT - END
    </div>
  </body>
</html>

* The advantage of the flex solution is that the content is independent of other parts of the layout. For example, the content doesn't need to know height of the header.

For a full Holy Grail implementation (header, footer, nav, side, and content), using flex display, go to here.

PHP header() redirect with POST variables

It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.

You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.

C++ Redefinition Header Files (winsock2.h)

You should use header guard.

put those line at the top of the header file

#ifndef PATH_FILENAME_H
#define PATH_FILENAME_H

and at the bottom

#endif

How can I make sticky headers in RecyclerView? (Without external lib)

Yo,

This is how you do it if you want just one type of holder stick when it starts getting out of the screen (we are not caring about any sections). There is only one way without breaking the internal RecyclerView logic of recycling items and that is to inflate additional view on top of the recyclerView's header item and pass data into it. I'll let the code speak.

import android.graphics.Canvas
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView

class StickyHeaderItemDecoration(@LayoutRes private val headerId: Int, private val HEADER_TYPE: Int) : RecyclerView.ItemDecoration() {

private lateinit var stickyHeaderView: View
private lateinit var headerView: View

private var sticked = false

// executes on each bind and sets the stickyHeaderView
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
    super.getItemOffsets(outRect, view, parent, state)

    val position = parent.getChildAdapterPosition(view)

    val adapter = parent.adapter ?: return
    val viewType = adapter.getItemViewType(position)

    if (viewType == HEADER_TYPE) {
        headerView = view
    }
}

override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDrawOver(c, parent, state)
    if (::headerView.isInitialized) {

        if (headerView.y <= 0 && !sticked) {
            stickyHeaderView = createHeaderView(parent)
            fixLayoutSize(parent, stickyHeaderView)
            sticked = true
        }

        if (headerView.y > 0 && sticked) {
            sticked = false
        }

        if (sticked) {
            drawStickedHeader(c)
        }
    }
}

private fun createHeaderView(parent: RecyclerView) = LayoutInflater.from(parent.context).inflate(headerId, parent, false)

private fun drawStickedHeader(c: Canvas) {
    c.save()
    c.translate(0f, Math.max(0f, stickyHeaderView.top.toFloat() - stickyHeaderView.height.toFloat()))
    headerView.draw(c)
    c.restore()
}

private fun fixLayoutSize(parent: ViewGroup, view: View) {

    // Specs for parent (RecyclerView)
    val widthSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY)
    val heightSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.UNSPECIFIED)

    // Specs for children (headers)
    val childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, parent.paddingLeft + parent.paddingRight, view.getLayoutParams().width)
    val childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, parent.paddingTop + parent.paddingBottom, view.getLayoutParams().height)

    view.measure(childWidthSpec, childHeightSpec)

    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
}

}

And then you just do this in your adapter:

override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
    super.onAttachedToRecyclerView(recyclerView)
    recyclerView.addItemDecoration(StickyHeaderItemDecoration(R.layout.item_time_filter, YOUR_STICKY_VIEW_HOLDER_TYPE))
}

Where YOUR_STICKY_VIEW_HOLDER_TYPE is viewType of your what is supposed to be sticky holder.

Creating your own header file in C

myfile.h

#ifndef _myfile_h
#define _myfile_h

void function();

#endif

myfile.c

#include "myfile.h"

void function() {

}

Parsing CSV files in C#, with header

Here is my KISS implementation...

using System;
using System.Collections.Generic;
using System.Text;

class CsvParser
{
    public static List<string> Parse(string line)
    {
        const char escapeChar = '"';
        const char splitChar = ',';
        bool inEscape = false;
        bool priorEscape = false;

        List<string> result = new List<string>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < line.Length; i++)
        {
            char c = line[i];
            switch (c)
            {
                case escapeChar:
                    if (!inEscape)
                        inEscape = true;
                    else
                    {
                        if (!priorEscape)
                        {
                            if (i + 1 < line.Length && line[i + 1] == escapeChar)
                                priorEscape = true;
                            else
                                inEscape = false;
                        }
                        else
                        {
                            sb.Append(c);
                            priorEscape = false;
                        }
                    }
                    break;
                case splitChar:
                    if (inEscape) //if in escape
                        sb.Append(c);
                    else
                    {
                        result.Add(sb.ToString());
                        sb.Length = 0;
                    }
                    break;
                default:
                    sb.Append(c);
                    break;
            }
        }

        if (sb.Length > 0)
            result.Add(sb.ToString());

        return result;
    }

}

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

I was trying to figure how to do this recently and while I like the most popular solution at the top, it simply would not work for me as I needed the names to be the alias's that I entered in the script so I used some batch files (with some help from a colleague) to accomplish custom table names.

The batch file that initiates the bcp has a line at the bottom of the script that executes another script that merges a template file with the header names and the file that was just exported with bcp using the code below. Hope this helps someone else that was in my situation.

echo Add headers from template file to exported sql files....
Echo School 0031
copy e:\genin\templates\TEMPLATE_Courses.csv + e:\genin\0031\courses0031.csv e:\genin\finished\courses0031.csv /b

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

C++, how to declare a struct in a header file

You should not place an using directive in an header file, it creates unnecessary headaches.

Also you need an include guard in your header.

EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

In Node.js, how do I "include" functions from my other files?

app.js

let { func_name } = require('path_to_tools.js');
func_name();    //function calling

tools.js

let func_name = function() {
    ...
    //function body
    ...
};

module.exports = { func_name };

PHP, display image with Header()

Browsers can often tell the image type by sniffing out the meta information of the image. Also, there should be a space in that header:

header('Content-type: image/png');

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

The place where you might want to do this is when you create a library and header combination, and hide the implementation to the user. Therefore, the suggested approach is to use explicit instantiation, because you know what your software is expected to deliver, and you can hide the implementations.

Some useful information is here: https://docs.microsoft.com/en-us/cpp/cpp/explicit-instantiation?view=vs-2019

For your same example: Stack.hpp

template <class T>
class Stack {

public:
    Stack();
    ~Stack();
    void Push(T val);
    T Pop();
private:
    T val;
};


template class Stack<int>;

stack.cpp

#include <iostream>
#include "Stack.hpp"
using namespace std;

template<class T>
void Stack<T>::Push(T val) {
    cout << "Pushing Value " << endl;
    this->val = val;
}

template<class T>
T Stack<T>::Pop() {
    cout << "Popping Value " << endl;
    return this->val;
}

template <class T> Stack<T>::Stack() {
    cout << "Construct Stack " << this << endl;
}

template <class T> Stack<T>::~Stack() {
    cout << "Destruct Stack " << this << endl;
}

main.cpp

#include <iostream>
using namespace std;

#include "Stack.hpp"

int main() {
    Stack<int> s;
    s.Push(10);
    cout << s.Pop() << endl;
    return 0;
}

Output:

> Construct Stack 000000AAC012F8B4
> Pushing Value
> Popping Value
> 10
> Destruct Stack 000000AAC012F8B4

I however don't entirely like this approach, because this allows the application to shoot itself in the foot, by passing incorrect datatypes to the templated class. For instance, in the main function, you can pass other types that can be implicitly converted to int like s.Push(1.2); and that is just bad in my opinion.

In LaTeX, how can one add a header/footer in the document class Letter?

With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.

header('HTTP/1.0 404 Not Found'); not doing anything

You could try specifying an HTTP response code using an optional parameter:

header('HTTP/1.0 404 Not Found', true, 404);

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

PHP page redirect

The header() function in PHP does this, but make sure that you call it before any other file contents are sent to the browser or else you will receive an error.

JavaScript is an alternative if you have already sent the file contents.

Display PNG image as response to jQuery AJAX request

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this:

$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');

Insert variable into Header Location PHP

You can add it like this

header('Location: http://linkhere.com/'.$url_endpoint);

Show Curl POST Request Headers? Is there a way to do this?

I had exactly the same problem lately, and I installed Wireshark (it is a network monitoring tool). You can see everything with this, except encrypted traffic (HTTPS).

How to declare a structure in a header that is to be used by multiple files in c?

a.h:

#ifndef A_H
#define A_H

struct a { 
    int i;
    struct b {
        int j;
    }
};

#endif

there you go, now you just need to include a.h to the files where you want to use this structure.

WPF TabItem Header Styling

While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.

The Code:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MealNinja"
        mc:Ignorable="d"
        Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
    <Window.Effect>
        <DropShadowEffect Opacity="0.5"/>
    </Window.Effect>
    <Grid Background="#FF423C3C">
        <TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
            <TabControl.Resources>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
                                        <ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                    <Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="FontWeight" Value="Bold" />
                                        <Setter TargetName="ContentSite" Property="Width" Value="30" />
                                        <Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="FontWeight" Value="Bold" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <ContentPresenter Content="{TemplateBinding Content}">
                                    <ContentPresenter.LayoutTransform>
                                        <RotateTransform Angle="270" />
                                    </ContentPresenter.LayoutTransform>
                                </ContentPresenter>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Background" Value="#FF6E6C67" />
                    <Setter Property="Height" Value="90" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="FontFamily" Value="DokChampa" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="VerticalAlignment" Value="Top" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="UseLayoutRounding" Value="False" />
                </Style>
                <Style x:Key="tabGrids">
                    <Setter Property="Grid.Background" Value="#FFE5E5E5" />
                    <Setter Property="Grid.Margin" Value="6,10,10,10" />
                </Style>
            </TabControl.Resources>
            <TabItem Header="Planner">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 2">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section III">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 04">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Tools">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Screenshot:

enter image description here

Adding author name in Eclipse automatically to existing files

Actually in Eclipse Indigo thru Oxygen, you have to go to the Types template Window -> Preferences -> Java -> Code Style -> Code templates -> (in right-hand pane) Comments -> double-click Types and make sure it has the following, which it should have by default:

/**
 * @author ${user}
 *
 * ${tags}
 */

and as far as I can tell, there is nothing in Eclipse to add the javadoc automatically to existing files in one batch. You could easily do it from the command line with sed & awk but that's another question.

If you are prepared to open each file individually, then selected the class / interface declaration line, e.g. public class AdamsClass { and then hit the key combo Shift + Alt + J and that will insert a new javadoc comment above, along with the author tag for your user. To experiment with other settings, go to Windows->Preferences->Java->Editor->Templates.

How to set response header in JAX-RS so that user sees download popup for Excel?

You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:

return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()

If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:

@Path("/resource")
class MyResource {

  // one way to get HttpServletResponse
  @Context
  private HttpServletResponse anotherServletResponse;

  // another way
  Response myMethod(@Context HttpServletResponse servletResponse) {
      // ... code
  }
}

Node.js: How to send headers with form data using request module?

This should work.

var url = 'http://<your_url_here>';
var headers = { 
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
    'Content-Type' : 'application/x-www-form-urlencoded' 
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};

request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
    // your callback body
});

HTTP headers in Websockets client API

You can not send custom header when you want to establish WebSockets connection using JavaScript WebSockets API. You can use Subprotocols headers by using the second WebSocket class constructor:

var ws = new WebSocket("ws://example.com/service", "soap");

and then you can get the Subprotocols headers using Sec-WebSocket-Protocol key on the server.

There is also a limitation, your Subprotocols headers values can not contain a comma (,) !

GridView - Show headers on empty data source

Use an EmptyDataTemplate like below. When your DataSource has no records, you will see your grid with headers, and the literal text or HTML that is inside the EmptyDataTemplate tags.

<asp:GridView ID="gvResults" AutoGenerateColumns="False" HeaderStyle-CssClass="tableheader" runat="server">
    <EmptyDataTemplate>
        <asp:Label ID="lblEmptySearch" runat="server">No Results Found</asp:Label>
    </EmptyDataTemplate>
    <Columns>
        <asp:BoundField DataField="ItemId" HeaderText="ID" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        ...
    </Columns>
</asp:GridView>

Python Pandas Replacing Header with Top Row

@ostrokach answer is best. Most likely you would want to keep that throughout any references to the dataframe, thus would benefit from inplace = True.
df.rename(columns=df.iloc[0], inplace = True) df.drop([0], inplace = True)

How to include header files in GCC search path?

Using environment variable is sometimes more convenient when you do not control the build scripts / process.

For C includes use C_INCLUDE_PATH.

For C++ includes use CPLUS_INCLUDE_PATH.

See this link for other gcc environment variables.

Example usage in MacOS / Linux

# `pip install` will automatically run `gcc` using parameters
# specified in the `asyncpg` package (that I do not control)

C_INCLUDE_PATH=/home/scott/.pyenv/versions/3.7.9/include/python3.7m pip install asyncpg

Example usage in Windows

set C_INCLUDE_PATH="C:\Users\Scott\.pyenv\versions\3.7.9\include\python3.7m"

pip install asyncpg

# clear the environment variable so it doesn't affect other builds
set C_INCLUDE_PATH=

No 'Access-Control-Allow-Origin' header in Angular 2 app

This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

that code was an answer of @jvandemo to a very similar question.

Sticky Header after scrolling down

I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.

    $('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
    if (e.currentTarget.scrollTop >= 130) {
        $('.results-label').addClass('fixedSimilarLabel');
    }
    else {      
        $('.results-label').removeClass('fixedSimilarLabel');
    }
});

http://codepen.io/franklynroth/pen/pjEzeK

Returning JSON from a PHP Script

In case you're doing this in WordPress, then there is a simple solution:

add_action( 'parse_request', function ($wp) {
    $data = /* Your data to serialise. */
    wp_send_json_success($data); /* Returns the data with a success flag. */
    exit(); /* Prevents more response from the server. */
})

Note that this is not in the wp_head hook, which will always return most of the head even if you exit immediately. The parse_request comes a lot earlier in the sequence.

php refresh current page?

header('Location: '.$_SERVER['PHP_SELF']);  

will also work

correct PHP headers for pdf file download

There are some things to be considered in your code.

First, write those headers correctly. You will never see any server sending Content-type:application/pdf, the header is Content-Type: application/pdf, spaced, with capitalized first letters etc.

The file name in Content-Disposition is the file name only, not the full path to it, and altrough I don't know if its mandatory or not, this name comes wrapped in " not '. Also, your last ' is missing.

Content-Disposition: inline implies the file should be displayed, not downloaded. Use attachment instead.

In addition, make the file extension in upper case to make it compatible with some mobile devices. (Update: Pretty sure only Blackberries had this problem, but the world moved on from those so this may be no longer a concern)

All that being said, your code should look more like this:

<?php

    $filename = './pdf/jobs/pdffile.pdf';

    $fileinfo = pathinfo($filename);
    $sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);

    header('Content-Type: application/pdf');
    header("Content-Disposition: attachment; filename=\"$sendname\"");
    header('Content-Length: ' . filesize($filename));
    readfile($filename);

Content-Length is optional but is also important if you want the user to be able to keep track of the download progress and detect if the download was interrupted. But when using it you have to make sure you won't be send anything along with the file data. Make sure there is absolutely nothing before <?php or after ?>, not even an empty line.

Custom HTTP Authorization Header

No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string ) (see section 1.2), and your example doesn't use "=" that way.

HTML5 best practices; section/header/aside/article elements

EDIT: Unfortunately I have to correct myself.

Refer below https://stackoverflow.com/a/17935666/2488942 for a link to the w3 specs which include an example (unlike the ones I looked at earlier on).

But then.... Here is a nice article about it thanks to @Fez.

My original response was:

The way the w3 specs are structured:

4.3.4 Sections

4.3.4.1 The body element

4.3.4.2 The section element

4.3.4.3 The nav element

4.3.4.4 The article element

....

suggests to me that section is higher level than article. As mentioned in this answer section groups thematically related content. Content within an article is in my opinion thematically related anyway, hence this, to me at least, then also suggests that section groups at a higher level compared to article.

I think it's meant to be used like this:

section: Chapter 1
    nav: Ch. 1.1
         Ch. 1.2

    article: Ch. 1.1
             some insightful text

    article: Ch. 1.2
             related to 1.1 but different topic

or for a news website:

section: News
    article: This happened today
    article: this happened in England

section: Sports
    article: England - Ukraine 0:0
    article: Italy books tickets to Brazil 2014

Android ListView headers

You probably are looking for an ExpandableListView which has headers (groups) to separate items (childs).

Nice tutorial on the subject: here.

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

If that helps anyone, (even if this is kind of poor as we must only allow this for dev purpose) here is a Java solution as I encountered the same issue. [Edit] Do not use the wild card * as it is a bad solution, use localhost if you really need to have something working locally.

public class SimpleCORSFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "my-authorized-proxy-or-domain");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}

public void destroy() {}

}

*.h or *.hpp for your class definitions

The extension of the source file may have meaning to your build system, for example, you might have a rule in your makefile for .cpp or .c files, or your compiler (e.g. Microsoft cl.exe) might compile the file as C or C++ depending on the extension.

Because you have to provide the whole filename to the #include directive, the header file extension is irrelevant. You can include a .c file in another source file if you like, because it's just a textual include. Your compiler might have an option to dump the preprocessed output which will make this clear (Microsoft: /P to preprocess to file, /E to preprocess to stdout, /EP to omit #line directives, /C to retain comments)

You might choose to use .hpp for files that are only relevant to the C++ environment, i.e. they use features that won't compile in C.

Remove Server Response Header IIS7

IIS 7.5 and possibly newer versions have the header text stored in iiscore.dll

Using a hex editor, find the string and the word "Server" 53 65 72 76 65 72 after it and replace those with null bytes. In IIS 7.5 it looks like this:

4D 69 63 72 6F 73 6F 66 74 2D 49 49 53 2F 37 2E 35 00 00 00 53 65 72 76 65 72 

Unlike some other methods this does not result in a performance penalty. The header is also removed from all requests, even internal errors.

What is the common header format of Python files?

Also see PEP 263 if you are using a non-ascii characterset

Abstract

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

Problem

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.

Proposed Solution

I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.

To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given.

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

      # coding=<encoding name>

or (using formats recognized by popular editors)

      #!/usr/bin/python
      # -*- coding: <encoding name> -*-

or

      #!/usr/bin/python
      # vim: set fileencoding=<encoding name> :

...

Creating a PHP header/footer

You can use this for header: Important: Put the following on your PHP pages that you want to include the content.

<?php
//at top:
require('header.php'); 
 ?>
 <?php
// at bottom:
require('footer.php');
?>

You can also include a navbar globaly just use this instead:

 <?php
 // At top:
require('header.php'); 
 ?>
  <?php
// At bottom:
require('footer.php');
 ?>
 <?php
 //Wherever navbar goes:
require('navbar.php'); 
?>

In header.php:

 <!DOCTYPE html>
 <html lang="en">
 <head>
    <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 </head>
 <body> 

Do Not close Body or Html tags!
Include html here:

 <?php
 //Or more global php here:

 ?>

Footer.php:

Code here:

<?php
//code

?>

Navbar.php:

<p> Include html code here</p>
<?php
 //Include Navbar PHP code here
 
?>

Benifits:

  • Cleaner main php file (index.php) script.
  • Change the header or footer. etc to change it on all pages with the include— Good for alerts on all pages etc...
  • Time Saving!
  • Faster page loads!
  • you can have as many files to include as needed!
  • server sided!

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

How do I set headers using python's urllib?

Use urllib2 and create a Request object which you then hand to urlopen. http://docs.python.org/library/urllib2.html

I dont really use the "old" urllib anymore.

req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()

untested....

Why won't my PHP app send a 404 error?

A little bit shorter version. Suppress odd echo.

if (strstr($_SERVER['REQUEST_URI'],'index.php')){
  header('HTTP/1.0 404 Not Found');
  exit("<h1>404 Not Found</h1>\nThe page that you have requested could not be found.");
}

Add custom header in HttpWebRequest

You use the Headers property with a string index:

request.Headers["X-My-Custom-Header"] = "the-value";

According to MSDN, this has been available since:

  • Universal Windows Platform 4.5
  • .NET Framework 1.1
  • Portable Class Library
  • Silverlight 2.0
  • Windows Phone Silverlight 7.0
  • Windows Phone 8.1

https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx

How to add Headers on RESTful call using Jersey Client API

I think you're looking for header(name,value) method. See WebResource.header(String, Object)

Note it returns a Builder though, so you need to save the output in your webResource var.

Authentication issues with WWW-Authenticate: Negotiate

The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.

This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):

  • either NTLM
  • or Kerberos.

See:

C++: Rounding up to the nearest multiple of a number

This is a generalization of the problem of "how do I find out how many bytes n bits will take? (A: (n bits + 7) / 8).

int RoundUp(int n, int roundTo)
{
    // fails on negative?  What does that mean?
    if (roundTo == 0) return 0;
    return ((n + roundTo - 1) / roundTo) * roundTo; // edit - fixed error
}

Where are Magento's log files located?

You can find them in /var/log within your root Magento installation

There will usually be two files by default, exception.log and system.log.

If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes

Setting up foreign keys in phpMyAdmin?

InnoDB allows you to add a new foreign key constraint to a table by using ALTER TABLE:

ALTER TABLE tbl_name
    ADD [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

On the other hand, if MyISAM has advantages over InnoDB in your context, why would you want to create foreign key constraints at all. You can handle this on the model level of your application. Just make sure the columns which you want to use as foreign keys are indexed!

How to change Angular CLI favicon

Please follow below steps to change app icon:

  1. Add your .ico file in the project.
  2. Go to angular.json and in that "projects" -> "architect" -> "build" -> "options" -> "assets" and here make an entry for your icon file. Refer to the existing entry of favicon.ico to know how to do it.
  3. Go to index.html and update the path of the icon file. For example,

  4. Restart the server.

  5. Hard refresh browser and you are good to go.

Is there a TRY CATCH command in Bash

There are so many similar solutions which probably work. Below is a simple and working way to accomplish try/catch, with explanation in the comments.

#!/bin/bash

function a() {
  # do some stuff here
}
function b() {
  # do more stuff here
}

# this subshell is a scope of try
# try
(
  # this flag will make to exit from current subshell on any error
  # inside it (all functions run inside will also break on any error)
  set -e
  a
  b
  # do more stuff here
)
# and here we catch errors
# catch
errorCode=$?
if [ $errorCode -ne 0 ]; then
  echo "We have an error"
  # We exit the all script with the same error, if you don't want to
  # exit it and continue, just delete this line.
  exit $errorCode
fi

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

What are the benefits of using C# vs F# or F# vs C#?

You're asking for a comparison between a procedural language and a functional language so I feel your question can be answered here: What is the difference between procedural programming and functional programming?

As to why MS created F# the answer is simply: Creating a functional language with access to the .Net library simply expanded their market base. And seeing how the syntax is nearly identical to OCaml, it really didn't require much effort on their part.

Is it possible to import a whole directory in sass using @import?

If you are using Sass in a Rails project, the sass-rails gem, https://github.com/rails/sass-rails, features glob importing.

@import "foo/*"     // import all the files in the foo folder
@import "bar/**/*"  // import all the files in the bar tree

To answer the concern in another answer "If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity."

Some would argue that organizing your files into directories can REDUCE complexity.

My organization's project is a rather complex app. There are 119 Sass files in 17 directories. These correspond roughly to our views and are mainly used for adjustments, with the heavy lifting being handled by our custom framework. To me, a few lines of imported directories is a tad less complex than 119 lines of imported filenames.

To address load order, we place files that need to load first – mixins, variables, etc. — in an early-loading directory. Otherwise, load order is and should be irrelevant... if we are doing things properly.

How to get the indices list of all NaN value in numpy array?

np.isnan combined with np.argwhere

x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
np.argwhere(np.isnan(x))

output:

array([[1, 2],
       [2, 0]])

Display a view from another controller in ASP.NET MVC

You can also call any controller from JavaScript/jQuery. Say you have a controller returning 404 or some other usercontrol/page. Then, on some action, from your client code, you can call some address that will fire your controller and return the result in HTML format your client code can take this returned result and put it wherever you want in you your page...

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I had the same problem. After spending hours, I came across the solution that I already added dependency for "spring-webmvc" but missed for "spring-web". So just add the below dependency to resolve this issue. If you already have, just update both to the latest version. It will work for sure.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.6.RELEASE</version>
</dependency>

You could update the version to "5.1.2" or latest. I used V4.1.6 therefore the build was failing, because this is an old version (one might face compatibility issues).

Joining pairs of elements of a list

Well I would do it this way as I am no good with Regs..

CODE

t = '1. eat, food\n\
7am\n\
2. brush, teeth\n\
8am\n\
3. crack, eggs\n\
1pm'.splitlines()

print [i+j for i,j in zip(t[::2],t[1::2])]

output:

['1. eat, food   7am', '2. brush, teeth   8am', '3. crack, eggs   1pm']  

Hope this helps :)

Laravel Eloquent compare date from datetime field

You can get the all record of the date '2016-07-14' by using it

 whereDate('date','=','2016-07-14')

Or use the another code for dynamic date

whereDate('date',$date)

DateTime.TryParseExact() rejecting valid formats

Try C# 7.0

var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
 ? dt : DateTime.Parse("1800-01-01");

Count all duplicates of each value

If you want to check repetition more than 1 in descending order then implement below query.

SELECT   duplicate_data,COUNT(duplicate_data) AS duplicate_data
FROM     duplicate_data_table_name 
GROUP BY duplicate_data
HAVING   COUNT(duplicate_data) > 1
ORDER BY COUNT(duplicate_data) DESC

If want simple count query.

SELECT   COUNT(duplicate_data) AS duplicate_data
FROM     duplicate_data_table_name 
GROUP BY duplicate_data
ORDER BY COUNT(duplicate_data) DESC

How to use zIndex in react-native

I believe there are different ways to do this based on what you need exactly, but one way would be to just put both Elements A and B inside Parent A.

    <View style={{ position: 'absolute' }}>    // parent of A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 0, position: 'absolute' }} />  // element B
    </View>

Java: recommended solution for deep cloning/copying an instance

Depends.

For speed, use DIY. For bulletproof, use reflection.

BTW, serialization is not the same as refl, as some objects may provide overridden serialization methods (readObject/writeObject) and they can be buggy

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

If the problem is that you don't have access to SQL Server and now you are using mixed mode to enable sa or grant an account admin privileges, then it is far easier just to uninstall SQL Server and reinstall.

Unable to establish SSL connection, how do I fix my SSL cert?

Just a quick note (and possible cause).

You can have a perfectly correct VirtualHost setup with _default_:443 etc. in your Apache .conf file.

But... If there is even one .conf file enabled with incorrect settings that also listens to port 443, then it will bring the whole SSL system down.

Therefore, if you are sure your .conf file is correct, try disabling the other site .conf files in sites-enabled.

laravel Eloquent ORM delete() method

At first,

You should know that destroy() is correct method for removing an entity directly via object or model and delete() can only be called in query builder.

In your case, You have not checked if record exists in database or not. Record can only be deleted if exists.

So, You can do it like follows.

$user = User::find($id);
    if($user){
        $destroy = User::destroy(2);
    }

The value or $destroy above will be 0 or 1 on fail or success respectively. So, you can alter the $data array like:

if ($destroy){

    $data=[
        'status'=>'1',
        'msg'=>'success'
    ];

}else{

    $data=[
        'status'=>'0',
        'msg'=>'fail'
    ];

}

Hope, you understand.

Replace and overwrite instead of appending

You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:

import re

myfile = "path/test.xml"

with open(myfile, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
    f.truncate()

The other way is to read the file then open it again with open(myfile, 'w'):

with open(myfile, "r") as f:
    data = f.read()

with open(myfile, "w") as f:
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))

Neither truncate nor open(..., 'w') will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4).

By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See http://man7.org/linux/man-pages/man2/truncate.2.html

How to move or copy files listed by 'find' command in unix?

find /PATH/TO/YOUR/FILES -name NAME.EXT -exec cp -rfp {} /DST_DIR \;

What Language is Used To Develop Using Unity

When you build for iPhone in Unity it does Ahead of Time (AOT) compilation of your mono assembly (written in C# or JavaScript) to native ARM code.

The authoring tool also creates a stub xcode project and references that compiled lib. You can add objective C code to this xcode project if there is native stuff you want to do that isn't exposed in Unity's environment yet (e.g. accessing the compass and/or gyroscope).

merge one local branch into another local branch

  1. git checkout [branchYouWantToReceiveBranch] - checkout branch you want to receive branch
  2. git merge [branchYouWantToMergeIntoBranch]

How to convert interface{} to string?

You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:

host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)

Latest version of Docopt returns Opts object that has methods for conversion:

host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port

Trying to mock datetime.date.today(), but not working

To add to Daniel G's solution:

from datetime import date

class FakeDate(date):
    "A manipulable date replacement"
    def __new__(cls, *args, **kwargs):
        return date.__new__(date, *args, **kwargs)

This creates a class which, when instantiated, will return a normal datetime.date object, but which is also able to be changed.

@mock.patch('datetime.date', FakeDate)
def test():
    from datetime import date
    FakeDate.today = classmethod(lambda cls: date(2010, 1, 1))
    return date.today()

test() # datetime.date(2010, 1, 1)

EditText, clear focus on touch outside

As @pcans suggested you can do this overriding dispatchTouchEvent(MotionEvent event) in your activity.

Here we get the touch coordinates and comparing them to view bounds. If touch is performed outside of a view then do something.

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View yourView = (View) findViewById(R.id.view_id);
        if (yourView != null && yourView.getVisibility() == View.VISIBLE) {
            // touch coordinates
            int touchX = (int) event.getX();
            int touchY = (int) event.getY();
            // get your view coordinates
            final int[] viewLocation = new int[2];
            yourView.getLocationOnScreen(viewLocation);

            // The left coordinate of the view
            int viewX1 = viewLocation[0];
            // The right coordinate of the view
            int viewX2 = viewLocation[0] + yourView.getWidth();
            // The top coordinate of the view
            int viewY1 = viewLocation[1];
            // The bottom coordinate of the view
            int viewY2 = viewLocation[1] + yourView.getHeight();

            if (!((touchX >= viewX1 && touchX <= viewX2) && (touchY >= viewY1 && touchY <= viewY2))) {

                Do what you want...

                // If you don't want allow touch outside (for example, only hide keyboard or dismiss popup) 
                return false;
            }
        }
    }
    return super.dispatchTouchEvent(event);
}

Also it's not necessary to check view existance and visibility if your activity's layout doesn't change during runtime (e.g. you don't add fragments or replace/remove views from the layout). But if you want to close (or do something similiar) custom context menu (like in the Google Play Store when using overflow menu of the item) it's necessary to check view existance. Otherwise you will get a NullPointerException.

How can I use nohup to run process as a background process in linux?

You can write a script and then use nohup ./yourscript & to execute

For example:

vi yourscript

put

#!/bin/bash
script here

you may also need to change permission to run script on server

chmod u+rwx yourscript

finally

nohup ./yourscript &

RVM is not a function, selecting rubies with 'rvm use ...' will not work

Same principle as other answers, just thought it was quicker than re-opening terminals :)

bash -l -c "rvm use 2.0.0"

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

I think programmers should be competent in the language they are using; use it clearly; and use it well. I don't think they should artificially cripple the language they are using. I speak from experience. I once worked literally next door to a Cobol shop where they didn't use ELSE 'because it was too complicated'. Reductio ad absurdam.

What's a clean way to stop mongod on Mac OS X?

Check out these docs:

http://www.mongodb.org/display/DOCS/Starting+and+Stopping+Mongo#StartingandStoppingMongo-SendingaUnixINTorTERMsignal

If you started it in a terminal you should be ok with a ctrl + 'c' -- this will do a clean shutdown.

However, if you are using launchctl there are specific instructions for that which will vary depending on how it was installed.

If you are using Homebrew it would be launchctl stop homebrew.mxcl.mongodb

Add carriage return to a string

string s2 = s1.Replace(",", ",\n");

How to merge multiple dicts with same key or different key?

Python 3.x Update

From Eli Bendersky answer:

Python 3 removed dict.iteritems use dict.items instead. See Python wiki: https://wiki.python.org/moin/Python3.0

from collections import defaultdict

dd = defaultdict(list)

for d in (d1, d2):
    for key, value in d.items():
        dd[key].append(value)

SQL SELECT multi-columns INTO multi-variable

SELECT @variable1 = col1, @variable2 = col2
FROM table1

Subset data to contain only columns whose names match a condition

Just in case for data.table users, the following works for me:

df[, grep("ABC", names(df)), with = FALSE]

How to redirect the output of a PowerShell to a file during its execution

You might want to take a look at the cmdlet Tee-Object. You can pipe output to Tee and it will write to the pipeline and also to a file

clearing a char array c

I usually just do like this:

memset(bufferar, '\0', sizeof(bufferar));

How can I make a CSS table fit the screen width?

If the table content is too wide (as in this example), there's nothing you can do other than alter the content to make it possible for the browser to show it in a more narrow format. Contrary to the earlier answers, setting width to 100% will have absolutely no effect if the content is too wide (as that link, and this one, demonstrate). Browsers already try to keep tables within the left and right margins if they can, and only resort to a horizontal scrollbar if they can't.

Some ways you can alter content to make a table more narrow:

  • Reduce the number of columns (perhaps breaking one megalithic table into multiple independent tables).
  • If you're using CSS white-space: nowrap on any of the content (or the old nowrap attribute, &nbsp;, a nobr element, etc.), see if you can live without them so the browser has the option of wrapping that content to keep the width down.
  • If you're using really wide margins, padding, borders, etc., try reducing their size (but I'm sure you thought of that).

If the table is too wide but you don't see a good reason for it (the content isn't that wide, etc.), you'll have to provide more information about how you're styling the table, the surrounding elements, etc. Again, by default the browser will avoid the scrollbar if it can.

Create JSON object dynamically via JavaScript (Without concate strings)

This topic, especially the answer of Xotic750 was very helpful to me. I wanted to generate a json variable to pass it to a php script using ajax. My values were stored into two arrays, and i wanted them in json format. This is a generic example:

valArray1 = [121, 324, 42, 31];
valArray2 = [232, 131, 443];
myJson = {objArray1: {}, objArray2: {}};
for (var k = 1; k < valArray1.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray1[k];
    myJson.objArray1[objName] = objValue;
}
for (var k = 1; k < valArray2.length; k++) {
    var objName = 'obj' + k;
    var objValue = valArray2[k];
    myJson.objArray2[objName] = objValue;
}
console.log(JSON.stringify(myJson));

The result in the console Log should be something like this:

{
   "objArray1": {
        "obj1": 121,
        "obj2": 324,
        "obj3": 42,
        "obj4": 31
   },
   "objArray2": {
        "obj1": 232,
        "obj2": 131,
        "obj3": 443
  }
}

CSS list item width/height does not work

Declare the a element as display: inline-block and drop the width and height from the li element.

Alternatively, apply a float: left to the li element and use display: block on the a element. This is a bit more cross browser compatible, as display: inline-block is not supported in Firefox <= 2 for example.

The first method allows you to have a dynamically centered list if you give the ul element a width of 100% (so that it spans from left to right edge) and then apply text-align: center.

Use line-height to control the text's Y-position inside the element.

Disable back button in react navigation

For the latest version React Navigation 5 with Typescript:

<Stack.Screen
    name={Routes.Consultations}
    component={Consultations}
    options={{headerLeft: () => null}}
  />

jquery how to empty input field

if you hit the "back" button it usually tends to stick, what you can do is when the form is submitted clear the element then before it goes to the next page but after doing with the element what you need to.

    $('#shares').keyup(function(){
                payment = 0;
                calcTotal();
                gtotal = ($('#shares').val() * 1) + payment;
                gtotal = gtotal.toFixed(2);
                $('#shares').val('');
                $("p.total").html("Total Payment: <strong>" + gtotal + "</strong>");
            });

Setting maxlength of textbox with JavaScript or jQuery

without jQuery you can use

document.getElementById('text_input').setAttribute('maxlength',200);

Add two numbers and display result in textbox with Javascript

<script>

function sum()
{
    var value1= parseInt(document.getElementById("txtfirst").value);
    var value2=parseInt(document.getElementById("txtsecond").value);
    var sum=value1+value2;
    document.getElementById("result").value=sum;

}
 </script>

What is Vim recording and how can it be disabled?

You start recording by q<letter> and you can end it by typing q again.

Recording is a really useful feature of Vim.

It records everything you type. You can then replay it simply by typing @<letter>. Record search, movement, replacement...

One of the best feature of Vim IMHO.

JQuery How to extract value from href tag?

I see two options here

var link = $('a').attr('href');
var equalPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(equalPosition + 1); //Split the string and get the number.

I dont know if you're gonna use it for paging and have the text in the <a>-tag as you have it, but if you should you can also do

var number = $('a').text();

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

How to send a JSON object over Request with Android?

Now since the HttpClient is deprecated the current working code is to use the HttpUrlConnection to create the connection and write the and read from the connection. But I preferred to use the Volley. This library is from android AOSP. I found very easy to use to make JsonObjectRequest or JsonArrayRequest

if block inside echo statement?

You will want to use the a ternary operator which acts as a shortened IF/Else statement:

echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';

Sorting a Dictionary in place with respect to keys

By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.

Centering the image in Bootstrap

Use This as the solution

This worked for me perfectly..

<div align="center">
   <img src="">
</div>

c++ array - expression must have a constant value

When you declare a variable as here

int a[10][10];

you are telling the C++ compiler that you want 100 consecutive integers allocated in the program's memory at runtime. The compiler will then provide for your program to have that much memory available and all is well with the world.

If however you tell the compiler

int x = 9001;
int y = 5;
int a[x][y];

the compiler has no way of knowing how much memory you are actually going to need at run time without doing a lot of very complex analysis to track down every last place where the values of x and y changed [if any]. Rather than support such variable size arrays, C++ and C strongly suggest if not outright demand that you use malloc() to manually allocate the space you want.

TL;DR

int x = 5;
int y = 5;
int **a = malloc(x*sizeof(int*));
for(int i = 0; i < y; i++) {
    a[i] = malloc(sizeof(int*)*y);
}

a is now a 2D array of size 5x5 and will behave the same as int a[5][5]. Because you have manually allocated memory, C++ and C demand that you delete it by hand too...

for(int i = 0; i < x; i++) {
    free(a[i]); // delete the 2nd dimension array
}
free(a); // delete a itself

php execute a background process

Well i found a bit faster and easier version to use

shell_exec('screen -dmS $name_of_screen $command'); 

and it works.

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

The best and the safest way to show a 'ProgressDialog' in an AsyncTask, avoiding memory leak problem is to use a 'Handler' with Looper.main().

    private ProgressDialog tProgressDialog;

then in the 'onCreate'

    tProgressDialog = new ProgressDialog(this);
    tProgressDialog.setMessage(getString(R.string.loading));
    tProgressDialog.setIndeterminate(true);

Now you r done with the setup part. Now call 'showProgress()' and 'hideProgress()' in AsyncTask.

    private void showProgress(){
        new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                tProgressDialog.show();
            }
        }.sendEmptyMessage(1);
    }

    private void hideProgress(){
        new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                tProgressDialog.dismiss();
            }
        }.sendEmptyMessage(1);
    }

Split a large pandas dataframe

Caution:

np.array_split doesn't work with numpy-1.9.0. I checked out: It works with 1.8.1.

Error:

Dataframe has no 'size' attribute

How do you get the path to the Laravel Storage folder?

In Laravel 3, call path('storage').

In Laravel 4, use the storage_path() helper function.

What's the difference between ASCII and Unicode?

ASCII and Unicode are two character encodings. Basically, they are standards on how to represent difference characters in binary so that they can be written, stored, transmitted, and read in digital media. The main difference between the two is in the way they encode the character and the number of bits that they use for each. ASCII originally used seven bits to encode each character. This was later increased to eight with Extended ASCII to address the apparent inadequacy of the original. In contrast, Unicode uses a variable bit encoding program where you can choose between 32, 16, and 8-bit encodings. Using more bits lets you use more characters at the expense of larger files while fewer bits give you a limited choice but you save a lot of space. Using fewer bits (i.e. UTF-8 or ASCII) would probably be best if you are encoding a large document in English.

One of the main reasons why Unicode was the problem arose from the many non-standard extended ASCII programs. Unless you are using the prevalent page, which is used by Microsoft and most other software companies, then you are likely to encounter problems with your characters appearing as boxes. Unicode virtually eliminates this problem as all the character code points were standardized.

Another major advantage of Unicode is that at its maximum it can accommodate a huge number of characters. Because of this, Unicode currently contains most written languages and still has room for even more. This includes typical left-to-right scripts like English and even right-to-left scripts like Arabic. Chinese, Japanese, and the many other variants are also represented within Unicode. So Unicode won’t be replaced anytime soon.

In order to maintain compatibility with the older ASCII, which was already in widespread use at the time, Unicode was designed in such a way that the first eight bits matched that of the most popular ASCII page. So if you open an ASCII encoded file with Unicode, you still get the correct characters encoded in the file. This facilitated the adoption of Unicode as it lessened the impact of adopting a new encoding standard for those who were already using ASCII.

Summary:

1.ASCII uses an 8-bit encoding while Unicode uses a variable bit encoding.
2.Unicode is standardized while ASCII isn’t.
3.Unicode represents most written languages in the world while ASCII does not.
4.ASCII has its equivalent within Unicode.

Taken From: http://www.differencebetween.net/technology/software-technology/difference-between-unicode-and-ascii/#ixzz4zEjnxPhs

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here: https://docs.python.org/tutorial/errors.html

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

So when you want to pass on certain exceptions, use suppress.

PHP function to make slug (URL string)

There's a good solution here that deals with special characters as well.

Texto Fantástico => texto-fantastico

function slugify( $string, $separator = '-' ) {
    $accents_regex = '~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i';
    $special_cases = array( '&' => 'and', "'" => '');
    $string = mb_strtolower( trim( $string ), 'UTF-8' );
    $string = str_replace( array_keys($special_cases), array_values( $special_cases), $string );
    $string = preg_replace( $accents_regex, '$1', htmlentities( $string, ENT_QUOTES, 'UTF-8' ) );
    $string = preg_replace("/[^a-z0-9]/u", "$separator", $string);
    $string = preg_replace("/[$separator]+/u", "$separator", $string);
    return $string;
}

Author: Natxet

Custom ImageView with drop shadow

Here you are. Set source of ImageView statically in xml or dynamically in code.

Shadow is here white.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content">

    <View android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:background="@android:color/white" android:layout_alignLeft="@+id/image"
        android:layout_alignRight="@id/image" android:layout_alignTop="@id/image"
        android:layout_alignBottom="@id/image" android:layout_marginLeft="10dp"
        android:layout_marginBottom="10dp" />

    <ImageView android:id="@id/image" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:src="..."
        android:padding="5dp" />

</RelativeLayout>

How can I use Oracle SQL developer to run stored procedures?

Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).

I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number).

I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:

DECLARE
  DNO NUMBER;
  MAXSAL NUMBER;
BEGIN
  DNO := NULL;

  GET_MAXSAL_BY_DEPT(
    DNO => DNO,
    MAXSAL => MAXSAL
  );
  DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;

I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:

Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc. 

To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor.

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;

However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
  v_rec emp%rowtype;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );

  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
  end loop;
END;

The output from the same location:

Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc. 

Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:

var rc refcursor 
exec :rc := get_emps_by_dept(30) 
print rc

In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).

The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.


"When I type just var rc refcursor; and select it and run it, I get this error (GUI):"

There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor and click Execute Statement (or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script (or F5 ), even for a single line of SQL*Plus.


"I am so close ... please help."

You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:

exec :rc := get_account(1)

What you need is something like the following. I have used the named notation for clarity.

var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor

exec :tran_cnt := 0
exec :msg_cnt := 123

exec get_account (Vret_val => :ret1, 
                  Vtran_count => :tran_cnt, 
                  Vmessage_count => :msg_cnt, 
                  Vaccount_id   => 1,
                  rc1 => :rc )

print tran_count 
print rc

That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.

How to check whether a file is empty or not?

if you have the file object, then

>>> import os
>>> with open('new_file.txt') as my_file:
...     my_file.seek(0, os.SEEK_END) # go to end of file
...     if my_file.tell(): # if current position is truish (i.e != 0)
...         my_file.seek(0) # rewind the file for later use 
...     else:
...         print "file is empty"
... 
file is empty

How to position text over an image in css

Why not set sample.png as background image of text or h2 css class? This will give effect as you have written over an image.

How do I invert BooleanToVisibilityConverter?

There's also the WPF Converters project on Codeplex. In their documentation they say you can use their MapConverter to convert from Visibility enumeration to bool

<Label>
    <Label.Visible>
        <Binding Path="IsVisible">
            <Binding.Converter>
                <con:MapConverter>
                    <con:Mapping From="True" To="{x:Static Visibility.Visible}"/>
                    <con:Mapping From="False" To="{x:Static Visibility.Hidden}"/>
                </con:MapConverter>
            </Binding.Converter>
        </Binding>
    </Label.Visible>
</Label>

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

SELECT Convert(varchar(10),CONVERT(date,'columnname',105),105) as "end";

OR

SELECT CONVERT(VARCHAR(10), CAST(event_enddate AS DATE), 105) AS [end];

will return the particular date in the format of 'dd-mm-yyyy'

The result would be like this..

04-07-2016

Loading/Downloading image from URL on Swift

When using SwiftUI, SDWebImageSwiftUI is the best option.

Add the dependancy via XCode's Swift Package Manager: https://github.com/SDWebImage/SDWebImageSwiftUI.git

Then just use WebImage() instead of Image()

WebImage(url: URL(string: "https://nokiatech.github.io/heif/content/images/ski_jump_1440x960.heic"))

CSS border less than 1px

try giving border in % for exapmle 0.1% according to your need.

How to solve maven 2.6 resource plugin dependency?

Step 1 : Check the proxy configured in eclipse is correct or not ? (Window->Preferences->General->Network Connections).

Step 2 : Right Click on Project-> Go to Maven -> Update the project

Step 3: Run as Maven Install.

==== By Following these steps, i am able to solve this error.

How to export table data in MySql Workbench to csv?

MySQL Workbench 6.3.6

Export the SELECT result

  • After you run a SELECT: Query > Export Results...

    Query Export Results

Export table data

  • In the Navigator, right click on the table > Table Data Export Wizard

    Table Data Export

  • All columns and rows are included by default, so click on Next.

  • Select File Path, type, Field Separator (by default it is ;, not ,!!!) and click on Next.

    CSV

  • Click Next > Next > Finish and the file is created in the specified location

How to compile and run a C/C++ program on the Android system

You can compile your C programs with an ARM cross-compiler:

arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test

Then you can push your compiled binary file to somewhere (don't push it in to the SD card):

adb push test /data/local/tmp/test

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

I had a struggle getting this to work i've tested it and it's working on lamp server mysql version 5.12

So, steps to success:

  1. sudo vim /etc/mysql/conf.d/mysql.cnf
  2. Scroll to the bottom of file Copy and paste

    [mysqld] sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

to the bottom of the file

  1. save and exit input mode
  2. sudo service mysql restart to restart MySQL.

Done!

Changing minDate and maxDate on the fly using jQuery DatePicker

For from / to date, here is how I implemented restricting the dates based on the date entered in the other datepicker. Works pretty good:

function activateDatePickers() {
    $("#aDateFrom").datepicker({
        onClose: function() {
            $("#aDateTo").datepicker(
                    "change",
                    { minDate: new Date($('#aDateFrom').val()) }
            );
        }
    });
    $("#aDateTo").datepicker({
        onClose: function() {
            $("#aDateFrom").datepicker(
                    "change",
                    { maxDate: new Date($('#aDateTo').val()) }
            );
        }
    });
}

Moment.js get day name from date

code

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');
console.log(weekDayName);

mydate is the input date. The variable weekDayName get the name of the day. Here the output is

Output

Wednesday

_x000D_
_x000D_
var mydate = "2017-08-30T00:00:00";_x000D_
console.log(moment(mydate).format('dddd'));_x000D_
console.log(moment(mydate).format('ddd'));_x000D_
console.log('Day in number[0,1,2,3,4,5,6]: '+moment(mydate).format('d'));_x000D_
console.log(moment(mydate).format('MMM'));_x000D_
console.log(moment(mydate).format('MMMM'));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

Depend on a branch or tag using a git URL in a package.json?

per @dantheta's comment:

As of npm 1.1.65, Github URL can be more concise user/project. npmjs.org/doc/files/package.json.html You can attach the branch like user/project#branch

So

"babel-eslint": "babel/babel-eslint",

Or for tag v1.12.0 on jscs:

"jscs": "jscs-dev/node-jscs#v1.12.0",

Note, if you use npm --save, you'll get the longer git

From https://docs.npmjs.com/cli/v6/configuring-npm/package-json#git-urls-as-dependencies

Git URLs as Dependencies

Git urls are of the form:

git+ssh://[email protected]:npm/cli.git#v1.0.27 git+ssh://[email protected]:npm/cli#semver:^5.0 git+https://[email protected]/npm/cli.git
git://github.com/npm/cli.git#v1.0.27

If #<commit-ish> is provided, it will be used to clone exactly that commit. If > the commit-ish has the format #semver:<semver>, <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then master is used.

GitHub URLs

As of version 1.1.65, you can refer to GitHub urls as just "foo": "user/foo-project". Just as with git URLs, a commit-ish suffix can be included. For example:

{
 "name": "foo",
 "version": "0.0.0",
 "dependencies": {
   "express": "expressjs/express",
   "mocha": "mochajs/mocha#4727d357ea",
   "module": "user/repo#feature\/branch"
 }
}```

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

Wheel file installation

you can follow the below command to install using the wheel file at your local

pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

From the community documentation:

hibernate.hbm2ddl.auto Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.

e.g. validate | update | create | create-drop

So the list of possible options are,

  • validate: validate the schema, makes no changes to the database.
  • update: update the schema.
  • create: creates the schema, destroying previous data.
  • create-drop: drop the schema when the SessionFactory is closed explicitly, typically when the application is stopped.
  • none: does nothing with the schema, makes no changes to the database

These options seem intended to be developers tools and not to facilitate any production level databases, you may want to have a look at the following question; Hibernate: hbm2ddl.auto=update in production?

MySQL Error 1093 - Can't specify target table for update in FROM clause

The simplest way to do this is use a table alias when you are referring parent query table inside the sub query.

Example :

insert into xxx_tab (trans_id) values ((select max(trans_id)+1 from xxx_tab));

Change it to:

insert into xxx_tab (trans_id) values ((select max(P.trans_id)+1 from xxx_tab P));

convert an enum to another type of enum

I wrote this answer because I believe there are fundamental issues with the majority of answers already provided, and the ones that are acceptable are incomplete.

Mapping by enum integer value

This approach is bad simply because it assumes that the integer values of both MyGender and TheirGender will always remain comparable. In practice, it is very rare that you can guarantee this even within a single project, let alone a separate service.

The approach we take should be something that can be used for other enum-mapping cases. We should never assume that one enum identically relates to another - especially when we may not have control over one or another.

Mapping by enum string value

This is a little better, as MyGender.Male will still convert to TheirGender.Male even if the integer representation is changed, but still not ideal.

I would discourage this approach as it assumes the name values will not change, and will always remain identical. Considering future enhancements, you cannot guarantee that this will be the case; consider if MyGender.NotKnown was added. It is likely that you would want this to map to TheirGender.Unknown, but this would not be supported.

Also, it is generally bad to assume that one enum equates to another by name, as this might not be the case in some contexts. As mentioned earlier, an ideal approach would work for other enum-mapping requirements.

Explicitly mapping enums

This approach explictly maps MyGender to TheirGender using a switch statement.

This is better as:

  • Covers the case where the underlying integer value changes.
  • Covers the case where the enum names changes (i.e. no assumptions - the developer will need to update the code to handle the scenario - good).
  • Handles cases where enum values cannot be mapped.
  • Handles cases where new enum values are added and cannot be mapped by default (again, no assumptions made - good).
  • Can easily be updated to support new enum values for either MyGender or TheirGender.
  • The same approach can be taken for all enum mapping requirements.

Assuming we have the following enums:

public enum MyGender
{
    Male = 0,
    Female = 1,
}

public enum TheirGender
{
    Male = 0,
    Female = 1,
    Unknown = 2,
}

We can create the following function to "convert from their enum to mine":

public MyGender GetMyGender(TheirGender theirGender)
{
    switch (theirGender)
    {
        case TheirGender.Male:
            return MyGender.Male;

        case TheirGender.Female:
            return MyGender.Female;

        default:
            throw new InvalidEnumArgumentException(nameof(theirGender), (int)theirGender, typeof(TheirGender));
    }
}

A previous answer suggested returning a nullable enum (TheirGender?) and returning null for any unmatched input. This is bad; null is not the same as an unknown mapping. If the input cannot be mapped, an exception should be thrown, else the method should be named more explictly to the behaviour:

public TheirGender? GetTheirGenderOrDefault(MyGender myGender)
{
    switch (myGender)
    {
        case MyGender.Male:
            return TheirGender.Male;
            
        case MyGender.Female:
            return TheirGender.Female;
            
        default:
            return default(TheirGender?);
    }
}

Additional considerations

If it is likely that this method will be required more than once in various parts of the solution, you could consider creating an extension method for this:

public static class TheirGenderExtensions
{
    public static MyGender GetMyGender(this TheirGender theirGender)
    {
        switch (theirGender)
        {
            case TheirGender.Male:
                return MyGender.Male;

            case TheirGender.Female:
                return MyGender.Female;

            default:
                throw new InvalidEnumArgumentException(nameof(theirGender), (int)theirGender, typeof(TheirGender));
        }
    }
}

If you are using C#8, you can use the syntax for switch expressions and expression bodies to neaten up the code:

public static class TheirGenderExtensions
{
    public static MyGender GetMyGender(this TheirGender theirGender)
        => theirGender switch
        {
            TheirGender.Male => MyGender.Male,
            TheirGender.Female => MyGender.Female,
            _ => throw new InvalidEnumArgumentException(nameof(theirGender), (int)theirGender, typeof(TheirGender))
        };
}

If you will only ever be mapping the enums within a single class, then an extension method may be overkill. In this case, the method can be declared within the class itself.

Furthermore, if the mapping will only ever take place within a single method, then you can declare this as a local function:

public static void Main()
{
    Console.WriteLine(GetMyGender(TheirGender.Male));
    Console.WriteLine(GetMyGender(TheirGender.Female));
    Console.WriteLine(GetMyGender(TheirGender.Unknown));
    
    static MyGender GetMyGender(TheirGender theirGender)
        => theirGender switch
        {
            TheirGender.Male => MyGender.Male,
            TheirGender.Female => MyGender.Female,
            _ => throw new InvalidEnumArgumentException(nameof(theirGender), (int)theirGender, typeof(TheirGender))
        };
}

Here's a dotnet fiddle link with the above example.

tl;dr:

Do not:

  • Map enums by integer value
  • Map enums by name

Do:

  • Map enums explicitly using a switch statement
  • Throw an exception when a value cannot be mapped rather than returning null
  • Consider using extension methods

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

Well considering there's no overhead difference between a varchar(30) and a varchar(100) if you're only storing 20 characters in each, err on the side of caution and just make it 50.

jQuery ajax upload file in asp.net mvc

AJAX file uploads are now possible by passing a FormData object to the data property of the $.ajax request.

As the OP specifically asked for a jQuery implementation, here you go:

<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST">
    <input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
    <button>Upload!</button>
</form>
$('#upload').submit(function(e) {
    e.preventDefault(); // stop the standard form submission

    $.ajax({
        url: this.action,
        type: this.method,
        data: new FormData(this),
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
        },
        error: function(xhr, error, status) {
            console.log(error, status);
        }
    });
});
public JsonResult Survey()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        // save file as required here...
    }
    return Json(new { UploadedFileCount = Request.Files.Count });
}

More information on FormData at MDN

HTML select form with option to enter custom value

jQuery Solution!

Demo: http://jsfiddle.net/69wP6/2/

Another Demo Below(updated!)

I needed something similar in a case when i had some fixed Options and i wanted one other option to be editable! In this case i made a hidden input that would overlap the select option and would be editable and used jQuery to make it all work seamlessly.

I am sharing the fiddle with all of you!

HTML

<div id="billdesc">
    <select id="test">
      <option class="non" value="option1">Option1</option>
      <option class="non" value="option2">Option2</option>
      <option class="editable" value="other">Other</option>
    </select>
    <input class="editOption" style="display:none;"></input>
</div>

CSS

body{
    background: blue;
}
#billdesc{
    padding-top: 50px;
}
#test{
    width: 100%;
    height: 30px;
}
option {
    height: 30px;
    line-height: 30px;
}

.editOption{
    width: 90%;
    height: 24px;
    position: relative;
    top: -30px

}

jQuery

var initialText = $('.editable').val();
$('.editOption').val(initialText);

$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();

if(selected == "editable"){
  $('.editOption').show();


  $('.editOption').keyup(function(){
      var editText = $('.editOption').val();
      $('.editable').val(editText);
      $('.editable').html(editText);
  });

}else{
  $('.editOption').hide();
}
});

Edit : Added some simple touches design wise, so people can clearly see where the input ends!

JS Fiddle : http://jsfiddle.net/69wP6/4/

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

Download this Sqlite manager its the easiest one to use Sqlite manager

and drag and drop your fetched file on its running instance

only drawback of this Sqlite Manager it stop responding if you run some SQL statement that has Syntax Error in it.

So i Use Firefox Plugin Side by side also which you can find at FireFox addons

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

How to make an HTTP request + basic auth in Swift

I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.

I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.

// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?

if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
    keys = NSDictionary(contentsOfFile: path)
}

if let dict = keys {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = dict["mailgunAPIPath"] as? String
    let emailRecipient = "[email protected]"
    let emailMessage = "Testing%20email%20sender%20variables"

    // Create a session and fill it with our request
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)

    // POST and report back with any errors and response codes
    request.HTTPMethod = "POST"
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let response = response {
            print("url = \(response.URL!)")
            print("response = \(response)")
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:

https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?

Hope this helps offers a solution to someone trying to avoid using 3rd party code for their POST requests!

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

Android Studio - How to increase Allocated Heap Size

_x000D_
_x000D_
-Xms256m _x000D_
-Xmx2048m _x000D_
-XX:MaxPermSize=512m _x000D_
-XX:ReservedCodeCacheSize=128m _x000D_
-XX:+UseCompressedOops 
_x000D_
_x000D_
_x000D_

Is there a command for formatting HTML in the Atom editor?

Not Just HTML, Using atom-beautify - Package for Atom, you can format code for HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more) in Atom within a matter of seconds.

To Install the atom-beautify package :

  • Open Atom Editor.
  • Press Ctrl+Shift+P (Cmd+Shift+P on mac), this will open the atom Command Palette.
  • Search and click on Install Packages & Themes. A Install Package window comes up.
  • Search for Beautify package, you will see a lot of beautify packages. Install any. I will recommend for atom-beautify.
  • Now Restart atom and TADA! now you are ready for quick formatting.

To Format text Using atom-beautify :

  • Go to the file you want to format.
  • Hit Ctrl+Alt+B (Ctrl+Option+B on mac).
  • Your file is formatted in seconds.

Will using 'var' affect performance?

As nobody has mentioned reflector yet...

If you compile the following C# code:

static void Main(string[] args)
{
    var x = "hello";
    string y = "hello again!";
    Console.WriteLine(x);
    Console.WriteLine(y);
}

Then use reflector on it, you get:

// Methods
private static void Main(string[] args)
{
    string x = "hello";
    string y = "hello again!";
    Console.WriteLine(x);
    Console.WriteLine(y);
}

So the answer is clearly no runtime performance hit!

How to delete a folder with files using Java

One more choice is to use Spring's org.springframework.util.FileSystemUtils relevant method which will recursively delete all content of the directory.

File directoryToDelete = new File(<your_directory_path_to_delete>);
FileSystemUtils.deleteRecursively(directoryToDelete);

That will do the job!

Adding a new line/break tag in XML

You probably need to put it in a CDATA block to preserve whitespace

<?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type="text/xsl" href="dummy.xsl"?>   
   <item>      
      <summary>
         <![CDATA[Tootsie roll tiramisu macaroon wafer carrot cake.                       
            Danish topping sugar plum tart bonbon caramels cake.]]>
      </summary>   
   </item> 

How to Resize image in Swift?

Swift 4, extension version, NO WHITE LINE ON EDGES.

Nobody seems to be mentioning that if image.draw() is called with non-integer values, resulting image could show a white line artifact at the right or bottom edge.

extension UIImage {

    func scaled(with scale: CGFloat) -> UIImage? {
        // size has to be integer, otherwise it could get white lines
        let size = CGSize(width: floor(self.size.width * scale), height: floor(self.size.height * scale))
        UIGraphicsBeginImageContext(size)
        draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

Possible to make labels appear when hovering over a point in matplotlib?

From http://matplotlib.sourceforge.net/examples/event_handling/pick_event_demo.html :

from matplotlib.pyplot import figure, show
import numpy as npy
from numpy.random import rand


if 1: # picking on a scatter plot (matplotlib.collections.RegularPolyCollection)

    x, y, c, s = rand(4, 100)
    def onpick3(event):
        ind = event.ind
        print('onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind))

    fig = figure()
    ax1 = fig.add_subplot(111)
    col = ax1.scatter(x, y, 100*s, c, picker=True)
    #fig.savefig('pscoll.eps')
    fig.canvas.mpl_connect('pick_event', onpick3)

show()

How to Validate a DateTime in C#?

A problem with using DateTime.TryParse is that it doesn't support the very common data-entry use case of dates entered without separators, e.g. 011508.

Here's an example of how to support this. (This is from a framework I'm building, so its signature is a little weird, but the core logic should be usable):

    private static readonly Regex ShortDate = new Regex(@"^\d{6}$");
    private static readonly Regex LongDate = new Regex(@"^\d{8}$");

    public object Parse(object value, out string message)
    {
        msg = null;
        string s = value.ToString().Trim();
        if (s.Trim() == "")
        {
            return null;
        }
        else
        {
            if (ShortDate.Match(s).Success)
            {
                s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 2);
            }
            if (LongDate.Match(s).Success)
            {
                s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 4);
            }
            DateTime d = DateTime.MinValue;
            if (DateTime.TryParse(s, out d))
            {
                return d;
            }
            else
            {
                message = String.Format("\"{0}\" is not a valid date.", s);
                return null;
            }
        }

    }

Copy Paste in Bash on Ubuntu on Windows

That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.

Twitter Bootstrap modal on mobile devices

you can add this property globally in javascript:

if( navigator.userAgent.match(/iPhone|iPad|iPod/i) ) {
    var styleEl = document.createElement('style'), styleSheet;
    document.head.appendChild(styleEl);
    styleSheet = styleEl.sheet;
    styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
 }

ITextSharp insert text to an existing pdf

In addition to the excellent answers above, the following shows how to add text to each page of a multi-page document:

 using (var reader = new PdfReader(@"C:\Input.pdf"))
 {
    using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write))
    {
       var document = new Document(reader.GetPageSizeWithRotation(1));
       var writer = PdfWriter.GetInstance(document, fileStream);

       document.Open();

       for (var i = 1; i <= reader.NumberOfPages; i++)
       {
          document.NewPage();

          var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
          var importedPage = writer.GetImportedPage(reader, i);

          var contentByte = writer.DirectContent;
          contentByte.BeginText();
          contentByte.SetFontAndSize(baseFont, 12);

          var multiLineString = "Hello,\r\nWorld!".Split('\n');

          foreach (var line in multiLineString)
          {
             contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
          }

          contentByte.EndText();
          contentByte.AddTemplate(importedPage, 0, 0);
       }

       document.Close();
       writer.Close();
    }
 }

How to fix Python indentation

On most UNIX-like systems, you can also run:

expand -t4 oldfilename.py > newfilename.py

from the command line, changing the number if you want to replace tabs with a number of spaces other than 4. You can easily write a shell script to do this with a bunch of files at once, retaining the original file names.

Hide div after a few seconds

Probably the easiest way is to use the timers plugin. http://plugins.jquery.com/project/timers and then call something like

$(this).oneTime(1000, function() {
    $("#something").hide();
  });

How do I use DateTime.TryParse with a Nullable<DateTime>?

Here is a slightly concised edition of what Jason suggested:

DateTime? d; DateTime dt;
d = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;

How to update a claim in ASP.NET Identity?

You can create a new ClaimsIdentity and then do the claims update with such.

set {
    // get context of the authentication manager
    var authenticationManager = HttpContext.GetOwinContext().Authentication;

    // create a new identity from the old one
    var identity = new ClaimsIdentity(User.Identity);

    // update claim value
    identity.RemoveClaim(identity.FindFirst("AccountNo"));
    identity.AddClaim(new Claim("AccountNo", value));

    // tell the authentication manager to use this new identity
    authenticationManager.AuthenticationResponseGrant = 
        new AuthenticationResponseGrant(
            new ClaimsPrincipal(identity),
            new AuthenticationProperties { IsPersistent = true }
        );
}

How to make a promise from setTimeout

Update (2017)

Here in 2017, Promises are built into JavaScript, they were added by the ES2015 spec (polyfills are available for outdated environments like IE8-IE11). The syntax they went with uses a callback you pass into the Promise constructor (the Promise executor) which receives the functions for resolving/rejecting the promise as arguments.

First, since async now has a meaning in JavaScript (even though it's only a keyword in certain contexts), I'm going to use later as the name of the function to avoid confusion.

Basic Delay

Using native promises (or a faithful polyfill) it would look like this:

function later(delay) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay);
    });
}

Note that that assumes a version of setTimeout that's compliant with the definition for browsers where setTimeout doesn't pass any arguments to the callback unless you give them after the interval (this may not be true in non-browser environments, and didn't used to be true on Firefox, but is now; it's true on Chrome and even back on IE8).

Basic Delay with Value

If you want your function to optionally pass a resolution value, on any vaguely-modern browser that allows you to give extra arguments to setTimeout after the delay and then passes those to the callback when called, you can do this (current Firefox and Chrome; IE11+, presumably Edge; not IE8 or IE9, no idea about IE10):

function later(delay, value) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
        /* Or for outdated browsers that don't support doing that:
        setTimeout(function() {
            resolve(value);
        }, delay);
        Or alternately:
        setTimeout(resolve.bind(null, value), delay);
        */
    });
}

If you're using ES2015+ arrow functions, that can be more concise:

function later(delay, value) {
    return new Promise(resolve => setTimeout(resolve, delay, value));
}

or even

const later = (delay, value) =>
    new Promise(resolve => setTimeout(resolve, delay, value));

Cancellable Delay with Value

If you want to make it possible to cancel the timeout, you can't just return a promise from later, because promises can't be cancelled.

But we can easily return an object with a cancel method and an accessor for the promise, and reject the promise on cancel:

const later = (delay, value) => {
    let timer = 0;
    let reject = null;
    const promise = new Promise((resolve, _reject) => {
        reject = _reject;
        timer = setTimeout(resolve, delay, value);
    });
    return {
        get promise() { return promise; },
        cancel() {
            if (timer) {
                clearTimeout(timer);
                timer = 0;
                reject();
                reject = null;
            }
        }
    };
};

Live Example:

_x000D_
_x000D_
const later = (delay, value) => {_x000D_
    let timer = 0;_x000D_
    let reject = null;_x000D_
    const promise = new Promise((resolve, _reject) => {_x000D_
        reject = _reject;_x000D_
        timer = setTimeout(resolve, delay, value);_x000D_
    });_x000D_
    return {_x000D_
        get promise() { return promise; },_x000D_
        cancel() {_x000D_
            if (timer) {_x000D_
                clearTimeout(timer);_x000D_
                timer = 0;_x000D_
                reject();_x000D_
                reject = null;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
};_x000D_
_x000D_
const l1 = later(100, "l1");_x000D_
l1.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l1 cancelled"); });_x000D_
_x000D_
const l2 = later(200, "l2");_x000D_
l2.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l2 cancelled"); });_x000D_
setTimeout(() => {_x000D_
  l2.cancel();_x000D_
}, 150);
_x000D_
_x000D_
_x000D_


Original Answer from 2014

Usually you'll have a promise library (one you write yourself, or one of the several out there). That library will usually have an object that you can create and later "resolve," and that object will have a "promise" you can get from it.

Then later would tend to look something like this:

function later() {
    var p = new PromiseThingy();
    setTimeout(function() {
        p.resolve();
    }, 2000);

    return p.promise(); // Note we're not returning `p` directly
}

In a comment on the question, I asked:

Are you trying to create your own promise library?

and you said

I wasn't but I guess now that's actually what I was trying to understand. That how a library would do it

To aid that understanding, here's a very very basic example, which isn't remotely Promises-A compliant: Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
  <script>
    (function() {

      // ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
      var PromiseThingy = (function() {

        // Internal - trigger a callback
        function triggerCallback(callback, promise) {
          try {
            callback(promise.resolvedValue);
          }
          catch (e) {
          }
        }

        // The internal promise constructor, we don't share this
        function Promise() {
          this.callbacks = [];
        }

        // Register a 'then' callback
        Promise.prototype.then = function(callback) {
          var thispromise = this;

          if (!this.resolved) {
            // Not resolved yet, remember the callback
            this.callbacks.push(callback);
          }
          else {
            // Resolved; trigger callback right away, but always async
            setTimeout(function() {
              triggerCallback(callback, thispromise);
            }, 0);
          }
          return this;
        };

        // Our public constructor for PromiseThingys
        function PromiseThingy() {
          this.p = new Promise();
        }

        // Resolve our underlying promise
        PromiseThingy.prototype.resolve = function(value) {
          var n;

          if (!this.p.resolved) {
            this.p.resolved = true;
            this.p.resolvedValue = value;
            for (n = 0; n < this.p.callbacks.length; ++n) {
              triggerCallback(this.p.callbacks[n], this.p);
            }
          }
        };

        // Get our underlying promise
        PromiseThingy.prototype.promise = function() {
          return this.p;
        };

        // Export public
        return PromiseThingy;
      })();

      // ==== Using it

      function later() {
        var p = new PromiseThingy();
        setTimeout(function() {
          p.resolve();
        }, 2000);

        return p.promise(); // Note we're not returning `p` directly
      }

      display("Start " + Date.now());
      later().then(function() {
        display("Done1 " + Date.now());
      }).then(function() {
        display("Done2 " + Date.now());
      });

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

Creating a constant Dictionary in C#

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
{
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;
}

This is exactly what you want. And yes, I know, it's ugly.

Formatting Decimal places in R

The function formatC() can be used to format a number to two decimal places. Two decimal places are given by this function even when the resulting values include trailing zeros.

Sum rows in data.frame or matrix

you can use rowSums

rowSums(data) should give you what you want.

What's the difference between an Angular component and module

enter image description here

Simplest Explanation:

Module is like a big container containing one or many small containers called Component, Service, Pipe

A Component contains :

  • HTML template or HTML code

  • Code(TypeScript)

  • Service: It is a reusable code that is shared by the Components so that rewriting of code is not required

  • Pipe: It takes in data as input and transforms it to the desired output

Reference: https://scrimba.com/

Changing the text on a label

Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar

If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.

There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.

text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
                                                                    ^^^^^^^^^^^^^^^^^
  def depositCallBack(self,event):
      text.set('change the value')

Allow only numbers to be typed in a textbox

You could subscribe for the onkeypress event:

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

and then define the isNumber function:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

You can see it in action here.

Redefine tab as 4 spaces

Add line
set ts=4
in
~/.vimrc file for per user
or
/etc/vimrc file for system wide

mysql_config not found when installing mysqldb python interface

On python 3.5.2

sudo apt-get install libmysqlclient-dev python-dev

How to create a GUID/UUID using iOS

Reviewing the Apple Developer documentation I found the CFUUID object is available on the iPhone OS 2.0 and later.

Should you commit .gitignore into the Git repos?

It is a good practice to .gitignore at least your build products (programs, *.o, etc.).

What is the best way to left align and right align two div tags?

You can do it with few lines of CSS code. You can align all div's which you want to appear next to each other to right.

<div class="div_r">First Element</div>
<div class="div_r">Second Element</div>

<style>
.div_r{
float:right;
color:red;
}
</style>

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

How do I use Apache tomcat 7 built in Host Manager gui?

Host Manager is a web application inside of Tomcat that creates/removes Virtual Hosts within Tomcat.

A Virtual Host allows you to define multiple hostnames on a single server, so you can use the same server to handles requests to, for example, ren.myserver.com and stimpy.myserver.com.

Unfortunately documentation on the GUI side of the Host Manager doesn't appear to exist, but documentation on configuring the virtual hosts manually in context.xml is here:

http://tomcat.apache.org/tomcat-7.0-doc/virtual-hosting-howto.html.

The full explanation of the Host parameters you can find here:

http://tomcat.apache.org/tomcat-7.0-doc/config/host.html.

Adding a virtual host

Once you have access to the host-manager (see other answers on setting up the permissions, the GUI will let you add a (temporary - see edit at the end of this post) virtual host.

Tomcat Host Manager - Add Virtual Host Panel

At a minimum you need the Name and App Base fields defined. Tomcat will then create the following directories:

{CATALINA_HOME}\conf\Catalina\{Name}
{CATALINA_HOME}\{App Base}
  • App Base will be where web applications will be deployed to the virtual host. Can be relative or absolute.
  • Name is usually the fully-qualified domain name (e.g. ren.myserver.com)
  • Alias can be used to extend the Name also where two addresses should resolve to the same host (e.g. www.ren.myserver.com). Note that this needs to be reflected in DNS records.

The checkboxes are as follows:

  • Auto Deploy: Automatically redeploy applications placed into App Base. Dangerous for Production environments!
  • Deploy On Startup: Automatically boot up applications under App Base when Tomcat starts
  • Deploy XML: Determines whether to parse the application's /META-INF/context.xml
  • Unpack WARs: Unpack WAR files placed or uploaded to the App Base, as opposed to running them directly from the WAR.
  • Tomcat 8 Copy XML: Copy an application's META-INF/context.xml to the App Base/XML Base on deployment, and use that exclusively, regardless of whether the application is updated. Irrelevant if Deploy XML is false.
  • Manager App: Add the manager application to the Virtual Host (Useful for controlling the applications you might have underneath ren.myserver.com)

Update: After playing around with this same process on Tomcat8, the behaviour I'm seeing is that adding a virtual host via the GUI isn't persistent - it doesn't get written to server.xml, even on shutdown. Therefore (unless I'm doing something terribly wrong), you can create it in the GUI, but you'll need to edit server.xml anyway, as per the first link above, to make it stick.

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop constraint):

SELECT
    CONCAT(table_name, '.', column_name) AS 'foreign key',
    CONCAT(referenced_table_name, '.', referenced_column_name) AS 'references',
    constraint_name AS 'constraint name'
FROM
    information_schema.key_column_usage
WHERE
    referenced_table_name IS NOT NULL;

If you want to check tables in a specific database, add the following:

AND table_schema = 'database_name';

A CSS selector to get last visible div

You could select and style this with JavaScript or jQuery, but CSS alone can't do this.

For example, if you have jQuery implemented on the site, you could just do:

var last_visible_element = $('div:visible:last');

Although hopefully you'll have a class/ID wrapped around the divs you're selecting, in which case your code would look like:

var last_visible_element = $('#some-wrapper div:visible:last');

How to apply bold text style for an entire row using Apache POI?

This work for me

I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0); 
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);

Which is faster: Stack allocation or Heap allocation

Stack allocation is a couple instructions whereas the fastest rtos heap allocator known to me (TLSF) uses on average on the order of 150 instructions. Also stack allocations don't require a lock because they use thread local storage which is another huge performance win. So stack allocations can be 2-3 orders of magnitude faster depending on how heavily multithreaded your environment is.

In general heap allocation is your last resort if you care about performance. A viable in-between option can be a fixed pool allocator which is also only a couple instructions and has very little per-allocation overhead so it's great for small fixed size objects. On the downside it only works with fixed size objects, is not inherently thread safe and has block fragmentation problems.

How to parse data in JSON format?

Very simple:

import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']

How to define constants in Visual C# like #define in C?

Check How to: Define Constants in C# on MSDN:

In C# the #define preprocessor directive cannot be used to define constants in the way that is typically used in C and C++.

Array Length in Java

Java arrays are actually fixed in size, and the other answers explain how .length isn't really doing what you'd expect. I'd just like to add that given your question what you might want to be using is an ArrayList, that is an array that can grow and shrink:

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

Here the .size() method will show you the number of elements in your list, and you can grow this as you add things.

"Full screen" <iframe>

You can use this piece of code:

  <iframe src="http://example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0%;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>

JavaScript seconds to time string with format hh:mm:ss

Non-prototype version of toHHMMSS:

    function toHHMMSS(seconds) {
        var sec_num = parseInt(seconds);
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);        
        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        var time    = hours+':'+minutes+':'+seconds;
        return time;
    }   

Git: Create a branch from unstaged/uncommitted changes on master

In the latest GitHub client for Windows, if you have uncommitted changes, and choose to create a new branch.
It prompts you how to handle this exact scenario:

enter image description here

The same applies if you simply switch the branch too.

Build unsigned APK file with Android Studio

You can click the dropdown near the run button on toolbar,

  1. Select "Edit Configurations"
  2. Click the "+"
  3. Select "Gradle"
  4. Choose your module as Gradle project
  5. In Tasks: enter assemble

Now press ok,

all you need to do is now select your configuration from the dropdown and press run button. It will take some time. Your unsigned apk is now located in

Project\app\build\outputs\apk

What are the integrity and crossorigin attributes?

Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.

Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference

Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin

More detail on Bootstrap CDNs implementation

Skip certain tables with mysqldump

For sake of completeness, here is a script which actually could be a one-liner to get a backup from a database, excluding (ignoring) all the views. The db name is assumed to be employees:

ignore=$(mysql --login-path=root1 INFORMATION_SCHEMA \
    --skip-column-names --batch \
    -e "select 
          group_concat(
            concat('--ignore-table=', table_schema, '.', table_name) SEPARATOR ' '
          ) 
        from tables 
        where table_type = 'VIEW' and table_schema = 'employees'")

mysqldump --login-path=root1 --column-statistics=0 --no-data employees $ignore > "./backups/som_file.sql"   

You can update the logic of the query. In general using group_concat and concat you can generate almost any desired string or shell command.

What is the maximum size of a web browser's cookie's key?

A cookie key(used to identify a session) and a cookie are the same thing being used in different ways. So the limit would be the same. According to Microsoft its 4096 bytes.

MSDN

cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.

Change hash without reload in jQuery

You can simply assign it a new value as follows,

window.location.hash

How to modify a specified commit?

Well, this solution might sound very silly, but can save you in certain conditions.

A friend of mine just ran into accidentally committing very some huge files (four auto-generated files ranging between 3GB to 5GB each) and then made some additional code commits on top of that before realizing the problem that git push wasn't working any longer!

The files had been listed in .gitignore but after renaming the container folder, they got exposed and committed! And now there were a few more commits of the code on top of that, but push was running forever (trying to upload GB of data!) and finally would fail due to Github's file size limits.

The problem with interactive rebase or anything similar was that they would deal with poking around these huge files and would take forever to do anything. Nevertheless, after spending almost an hour in the CLI, we weren't sure if the files (and deltas) are actually removed from the history or simply not included in the current commits. The push wasn't working either and my friend was really stuck.

So, the solution I came up with was:

  1. Rename current git folder to ~/Project-old.
  2. Clone the git folder again from github (to ~/Project).
  3. Checkout to the same branch.
  4. Manually cp -r the files from ~/Project-old folder to ~/Project.
  5. Make sure the massive files, that are not needed to be checked in are mved, and included in .gitignore properly.
  6. Also make sure you don't overwrite .git folder in the recently-cloned ~/Project by the old one. That's where the logs of the problematic history lives!
  7. Now review the changes. It should be the union of all the recent commits, excluding the problematic files.
  8. Finally commit the changes, and it's good to be push'ed.

The biggest problem with this solution is, it deals with manual copying some files, and also it merges all the recent commits into one (obviously with a new commit-hash.) B

The big benefits are that, it is very clear in every step, it works great for huge files (as well as sensitive ones), and it doesn't leave any trace in history behind!

In Node.js, how do I "include" functions from my other files?

Another way to do this in my opinion, is to execute everything in the lib file when you call require() function using (function(/* things here */){})(); doing this will make all these functions global scope, exactly like the eval() solution

src/lib.js

(function () {
    funcOne = function() {
            console.log('mlt funcOne here');
    }

    funcThree = function(firstName) {
            console.log(firstName, 'calls funcThree here');
    }

    name = "Mulatinho";
    myobject = {
            title: 'Node.JS is cool',
            funcFour: function() {
                    return console.log('internal funcFour() called here');
            }
    }
})();

And then in your main code you can call your functions by name like:

main.js

require('./src/lib')
funcOne();
funcThree('Alex');
console.log(name);
console.log(myobject);
console.log(myobject.funcFour());

Will make this output

bash-3.2$ node -v
v7.2.1
bash-3.2$ node main.js 
mlt funcOne here
Alex calls funcThree here
Mulatinho
{ title: 'Node.JS is cool', funcFour: [Function: funcFour] }
internal funcFour() called here
undefined

Pay atention to the undefined when you call my object.funcFour(), it will be the same if you load with eval(). Hope it helps :)

What are Maven goals and phases and what is their difference?

Credit to Sandeep Jindal and Premraj. Their explanation help me to understand after confused about this for a while.

I created some full code examples & some simple explanations here https://www.surasint.com/maven-life-cycle-phase-and-goal-easy-explained/ . I think it may help others to understand.

In short from the link, You should not try to understand all three at once, first you should understand the relationship in these groups:

  • Life Cycle vs Phase
  • Plugin vs Goal

1. Life Cycle vs Phase

Life Cycle is a collection of phase in sequence see here Life Cycle References. When you call a phase, it will also call all phase before it.

For example, the clean life cycle has 3 phases (pre-clean, clean, post-clean).

mvn clean

It will call pre-clean and clean.

2. Plugin vs Goal

Goal is like an action in Plugin. So if plugin is a class, goal is a method.

you can call a goal like this:

mvn clean:clean

This means "call the clean goal, in the clean plugin" (Nothing relates to the clean phase here. Don't let the word"clean" confusing you, they are not the same!)

3. Now the relation between Phase & Goal:

Phase can (pre)links to Goal(s).For example, normally, the clean phase links to the clean goal. So, when you call this command:

mvn clean

It will call the pre-clean phase and the clean phase which links to the clean:clean goal.

It is almost the same as:

mvn pre-clean clean:clean

More detail and full examples are in https://www.surasint.com/maven-life-cycle-phase-and-goal-easy-explained/

Reset select2 value and show placeholder

Use this code into your js file

$('#id').val('1');
$('#id').trigger('change');

Gridview get Checkbox.Checked value

You want an independent for loop for all the rows in grid view, then refer the below link

http://nikhilsreeni.wordpress.com/asp-net/checkbox/

Select all checkbox in Gridview

CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
    cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);

    cb.Checked = ((CheckBox)sender).Checked;
}

Select checked rows to a dataset; For gridview multiple edit

CheckBox cb = default(CheckBox);

foreach (GridViewRow row in grdforumcomments.Rows)
{
    cb = (CheckBox)row.FindControl("cbsel");
    if (cb.Checked)
    {
        drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
        drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
        drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
    }
}

How to display an IFRAME inside a jQuery UI dialog

Although this is a old post, I have spent 3 hours to fix my issue and I think this might help someone in future.

Here is my jquery-dialog hack to show html content inside an <iframe> :

let modalProperties = {autoOpen: true, width: 900, height: 600, modal: true, title: 'Modal Title'};
let modalHtmlContent = '<div>My Content First div</div><div>My Content Second div</div>';

// create wrapper iframe
let wrapperIframe = $('<iframe src="" frameborder="0" style="width:100%; height:100%;"></iframe>');

// create jquery dialog by a 'div' with 'iframe' appended
$("<div></div>").append(wrapperIframe).dialog(modalProperties);

// insert html content to iframe 'body'
let wrapperIframeDocument = wrapperIframe[0].contentDocument;
let wrapperIframeBody = $('body', wrapperIframeDocument);
wrapperIframeBody.html(modalHtmlContent);

jsfiddle demo

PHP array delete by value (not key)

A one-liner using the or operator:

($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);

Find object by id in an array of JavaScript objects

I think the easiest way would be the following, but it won't work on Internet Explorer 8 (or earlier):

var result = myArray.filter(function(v) {
    return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property

Execution order of events when pressing PrimeFaces p:commandButton

I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:

        <p:pickList id="formPickList" 
                    value="#{mediaDetail.availableMedia}" 
                    converter="MediaPicklistConverter" 
                    widgetVar="formsPicklistWidget" 
                    var="mediaFiles" 
                    itemLabel="#{mediaFiles.mediaTitle}" 
                    itemValue="#{mediaFiles}" >
            <f:facet name="sourceCaption">Available Media</f:facet>
            <f:facet name="targetCaption">Chosen Media</f:facet>
        </p:pickList>

        <p:commandButton id="viewStream_btn" 
                         value="Stream chosen media" 
                         icon="fa fa-download"
                         ajax="true"
                         action="#{mediaDetail.prepareStreams}"                                              
                         update=":streamDialogPanel"
                         oncomplete="PF('streamingDialog').show()"
                         styleClass="ui-priority-primary"
                         style="margin-top:5px" >
            <p:ajax process="formPickList"  />
        </p:commandButton>

The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.

As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.

The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.

Happy coding!

cleanup php session files

Use cron with find to delete files older than given threshold. For example to delete files that haven't been accessed for at least a week.

find .session/ -atime +7  -exec rm {} \;

Null check in VB

Your code is way more cluttered than necessary.

Replace (Not (X Is Nothing)) with X IsNot Nothing and omit the outer parentheses:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For i As Integer = 0 To comp.Container.Components.Count() - 1
        fixUIIn(comp.Container.Components(i), style)
    Next
End If

Much more readable. … Also notice that I’ve removed the redundant Step 1 and the probably redundant .Item.

But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each instead:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For Each component In comp.Container.Components
        fixUIIn(component, style)
    Next
End If

JSON find in JavaScript

(You're not searching through "JSON", you're searching through an array -- the JSON string has already been deserialized into an object graph, in this case an array.)

Some options:

Use an Object Instead of an Array

If you're in control of the generation of this thing, does it have to be an array? Because if not, there's a much simpler way.

Say this is your original data:

[
    {"id": "one",   "pId": "foo1", "cId": "bar1"},
    {"id": "two",   "pId": "foo2", "cId": "bar2"},
    {"id": "three", "pId": "foo3", "cId": "bar3"}
]

Could you do the following instead?

{
    "one":   {"pId": "foo1", "cId": "bar1"},
    "two":   {"pId": "foo2", "cId": "bar2"},
    "three": {"pId": "foo3", "cId": "bar3"}
}

Then finding the relevant entry by ID is trivial:

id = "one"; // Or whatever
var entry = objJsonResp[id];

...as is updating it:

objJsonResp[id] = /* New value */;

...and removing it:

delete objJsonResp[id];

This takes advantage of the fact that in JavaScript, you can index into an object using a property name as a string -- and that string can be a literal, or it can come from a variable as with id above.

Putting in an ID-to-Index Map

(Dumb idea, predates the above. Kept for historical reasons.)

It looks like you need this to be an array, in which case there isn't really a better way than searching through the array unless you want to put a map on it, which you could do if you have control of the generation of the object. E.g., say you have this originally:

[
    {"id": "one",   "pId": "foo1", "cId": "bar1"},
    {"id": "two",   "pId": "foo2", "cId": "bar2"},
    {"id": "three", "pId": "foo3", "cId": "bar3"}
]

The generating code could provide an id-to-index map:

{
    "index": {
        "one": 0, "two": 1, "three": 2
    },
    "data": [
        {"id": "one",   "pId": "foo1", "cId": "bar1"},
        {"id": "two",   "pId": "foo2", "cId": "bar2"},
        {"id": "three", "pId": "foo3", "cId": "bar3"}
    ]
}

Then getting an entry for the id in the variable id is trivial:

var index = objJsonResp.index[id];
var obj = objJsonResp.data[index];

This takes advantage of the fact you can index into objects using property names.

Of course, if you do that, you have to update the map when you modify the array, which could become a maintenance problem.

But if you're not in control of the generation of the object, or updating the map of ids-to-indexes is too much code and/ora maintenance issue, then you'll have to do a brute force search.

Brute Force Search (corrected)

Somewhat OT (although you did ask if there was a better way :-) ), but your code for looping through an array is incorrect. Details here, but you can't use for..in to loop through array indexes (or rather, if you do, you have to take special pains to do so); for..in loops through the properties of an object, not the indexes of an array. Your best bet with a non-sparse array (and yours is non-sparse) is a standard old-fashioned loop:

var k;
for (k = 0; k < someArray.length; ++k) { /* ... */ }

or

var k;
for (k = someArray.length - 1; k >= 0; --k) { /* ... */ }

Whichever you prefer (the latter is not always faster in all implementations, which is counter-intuitive to me, but there we are). (With a sparse array, you might use for..in but again taking special pains to avoid pitfalls; more in the article linked above.)

Using for..in on an array seems to work in simple cases because arrays have properties for each of their indexes, and their only other default properties (length and their methods) are marked as non-enumerable. But it breaks as soon as you set (or a framework sets) any other properties on the array object (which is perfectly valid; arrays are just objects with a bit of special handling around the length property).

Git Cherry-Pick and Conflicts

Also, to complete what @claudio said, when cherry-picking you can also use a merging strategy.

So you could something like this git cherry-pick --strategy=recursive -X theirs commit or git cherry-pick --strategy=recursive -X ours commit

NGinx Default public www location?

You can find it in /var/www/ that is default directory for nginx and apache but you can change it. step 1 go to the following folder /etc/nginx/sites-available

step 2 edit default file in that you can find a server block under that there will be line named as root that is what defines the location.

'Field required a bean of type that could not be found.' error spring restful API using mongodb

Using this solved my issue.

@SpringBootApplication(scanBasePackages={"com.example.something", "com.example.application"})

Definition of int64_t

My 2 cents, from a current implementation Point of View and for SWIG users on k8 (x86_64) architecture.

Linux

First long long and long int are different types but sizeof(long long) == sizeof(long int) == sizeof(int64_t)

Gcc

First try to find where and how the compiler define int64_t and uint64_t

grepc -rn "typedef.*INT64_TYPE" /lib/gcc
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:43:typedef __INT64_TYPE__ int64_t;
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:55:typedef __UINT64_TYPE__ uint64_t;

So we need to find this compiler macro definition

gcc -dM -E -x c /dev/null | grep __INT64                 
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int

gcc -dM -E -x c++ /dev/null | grep __INT64
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int

Clang

clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long int
#define __UINT64_TYPE__ long unsigned int

Clang, GNU compilers:
-dM dumps a list of macros.
-E prints results to stdout instead of a file.
-x c and -x c++ select the programming language when using a file without a filename extension, such as /dev/null

Ref: https://web.archive.org/web/20190803041507/http://nadeausoftware.com/articles/2011/12/c_c_tip_how_list_compiler_predefined_macros

note: for swig user, on Linux x86_64 use -DSWIGWORDSIZE64

MacOS

On Catalina 10.15 IIRC

Clang

clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long long int
#define __UINT64_TYPE__ long long unsigned int

Clang:
-dM dumps a list of macros.
-E prints results to stdout instead of a file.
-x c and -x c++ select the programming language when using a file without a filename extension, such as /dev/null

Ref: https://web.archive.org/web/20190803041507/http://nadeausoftware.com/articles/2011/12/c_c_tip_how_list_compiler_predefined_macros

note: for swig user, on macOS x86_64 don't use -DSWIGWORDSIZE64

Visual Studio 2019

First sizeof(long int) == 4 and sizeof(long long) == 8

in stdint.h we have:

#if _VCRT_COMPILER_PREPROCESSOR

typedef signed char        int8_t;
typedef short              int16_t;
typedef int                int32_t;
typedef long long          int64_t;
typedef unsigned char      uint8_t;
typedef unsigned short     uint16_t;
typedef unsigned int       uint32_t;
typedef unsigned long long uint64_t;

note: for swig user, on windows x86_64 don't use -DSWIGWORDSIZE64

SWIG Stuff

First see https://github.com/swig/swig/blob/3a329566f8ae6210a610012ecd60f6455229fe77/Lib/stdint.i#L20-L24 so you can control the typedef using SWIGWORDSIZE64 but...

now the bad: SWIG Java and SWIG CSHARP do not take it into account

So you may want to use

#if defined(SWIGJAVA)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGJAVA)

and

#if defined(SWIGCSHARP)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, unsigned long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGCSHARP)

So int64_t aka long int will be bind to Java/C# long on Linux...

How do I break a string in YAML over multiple lines?

None of the above solutions worked for me, in a YAML file within a Jekyll project. After trying many options, I realized that an HTML injection with <br> might do as well, since in the end everything is rendered to HTML:

name: | In a village of La Mancha <br> whose name I don't <br> want to remember.

At least it works for me. No idea on the problems associated to this approach.

text-overflow: ellipsis not working

Without Fixed Width

For those of us that do not want to use fixed-width, it also works using display: inline-grid. So along with required properties, you just add display

span {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-grid;
}

What is a stack trace, and how can I use it to debug my application errors?

Just to add to the other examples, there are inner(nested) classes that appear with the $ sign. For example:

public class Test {

    private static void privateMethod() {
        throw new RuntimeException();
    }

    public static void main(String[] args) throws Exception {
        Runnable runnable = new Runnable() {
            @Override public void run() {
                privateMethod();
            }
        };
        runnable.run();
    }
}

Will result in this stack trace:

Exception in thread "main" java.lang.RuntimeException
        at Test.privateMethod(Test.java:4)
        at Test.access$000(Test.java:1)
        at Test$1.run(Test.java:10)
        at Test.main(Test.java:13)

Maven command to determine which settings.xml file Maven is using

This is the configuration file for Maven. It can be specified at two levels:

  1. User Level. This settings.xml file provides configuration for a single user, and is normally provided in ${user.home}/.m2/settings.xml.

              NOTE: This location can be overridden with the CLI option:
    
              -s /path/to/user/settings.xml
    
  2. Global Level. This settings.xml file provides configuration for all Maven users on a machine (assuming they're all using the same Maven installation). It's normally provided in ${maven.home}/conf/settings.xml.

              NOTE: This location can be overridden with the CLI option:
    
              -gs /path/to/global/settings.xml
    

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

To avoid disabling ssl verification entirely or duplicating / hacking the bundled CA certificate file used by git, you can export the host's certificate chain into a file, and make git use it:

git config --global http.https://the.host.com/.sslCAInfo c:/users/me/the.host.com.cer

If that does not work, you can disable ssl verification only for the host:

git config --global http.https://the.host.com/.sslVerify false

Note : Subjected to possible man in the middle attacks when ssl verification is turned off.

How to load my app from Eclipse to my Android phone instead of AVD

First you need to set your device to debugging mode. On Android 4.X that means as described in another answer in another question:

Open up your device’s “Settings”. This can be done by pressing the Menu button while on your home screen and tapping “System settings”

Now scroll to the bottom and tap “About phone” or “About tablet”.

At the “About” screen, scroll to the bottom and tap on “Build number” seven times. [Note this is no joke]

Make sure you tap seven times. If you see a “Not need, you are already a developer!” message pop up, then you know you have done it correctly.

Done! By tapping on “Build number” seven times, you have unlocked USB debugging mode on Android 4.2 and higher. You can now enable/disable it whenever you desire by going to “Settings” -> “Developer Options” -> “Debugging” ->” USB debugging”.

The next step is to connect your device to your computer via the USB cable.

The next step is to install a USB driver for it. On the official website you find a list with sources for drivers for phones from various different companies.

Eclipse now should give you the phone as a choice when you click on Run and it presents you possible device to launch.

In some case Eclpise will tell you Target Unknown which prevents you from using the device. If that's the case you might have to restart the phone. You might also have to check and recheckUSB debugging, till the phone asks you to allow your particular computer to do usb debugging.

How to post data to specific URL using WebClient in C#

Using simple client.UploadString(adress, content); normally works fine but I think it should be remembered that a WebException will be thrown if not a HTTP successful status code is returned. I usually handle it like this to print any exception message the remote server is returning:

try
{
    postResult = client.UploadString(address, content);
}
catch (WebException ex)
{
    String responseFromServer = ex.Message.ToString() + " ";
    if (ex.Response != null)
    {
        using (WebResponse response = ex.Response)
        {
            Stream dataRs = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(dataRs))
            {
                responseFromServer += reader.ReadToEnd();
                _log.Error("Server Response: " + responseFromServer);
            }
        }
    }
    throw;
}

Alternative to file_get_contents?

If you're trying to read XML generated from a URL without file_get_contents() then you'll probably want to have a look at cURL

INSERT ... ON DUPLICATE KEY (do nothing)

Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id (it won't trigger row update even though id is assigned to itself).

If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE.

Quickest way to compare two generic lists for differences

Not for this Problem, but here's some code to compare lists for equal and not! identical objects:

public class EquatableList<T> : List<T>, IEquatable<EquatableList<T>> where    T : IEquatable<T>

/// <summary>
/// True, if this contains element with equal property-values
/// </summary>
/// <param name="element">element of Type T</param>
/// <returns>True, if this contains element</returns>
public new Boolean Contains(T element)
{
    return this.Any(t => t.Equals(element));
}

/// <summary>
/// True, if list is equal to this
/// </summary>
/// <param name="list">list</param>
/// <returns>True, if instance equals list</returns>
public Boolean Equals(EquatableList<T> list)
{
    if (list == null) return false;
    return this.All(list.Contains) && list.All(this.Contains);
}

Eclipse returns error message "Java was started but returned exit code = 1"

None of the above answers helped for me. I discovered that, in general, an error like that could mean that your eclipse.ini has an invalid entry. So, all the above answers could be correct, depending on your particular case. In my case, it turned out I added a locale argument with a typo in it.

Should I use Python 32bit or Python 64bit

In my experience, using the 32-bit version is more trouble-free. Unless you are working on applications that make heavy use of memory (mostly scientific computing, that uses more than 2GB memory), you're better off with 32-bit versions because:

  1. You generally use less memory.
  2. You have less problems using COM (since you are on Windows).
  3. If you have to load DLLs, they most probably are also 32-bit. Python 64-bit can't load 32-bit libraries without some heavy hacks running another Python, this time in 32-bit, and using IPC.
  4. If you have to load DLLs that you compile yourself, you'll have to compile them to 64-bit, which is usually harder to do (specially if using MinGW on Windows).
  5. If you ever use PyInstaller or py2exe, those tools will generate executables with the same bitness of your Python interpreter.

How to include (source) R script in other scripts

I solved my problem using entire address where my code is: Before:

if(!exists("foo", mode="function")) source("utils.r")

After:

if(!exists("foo", mode="function")) source("C:/tests/utils.r")

ASP.NET Web Site or ASP.NET Web Application?

Definitely web application, single DLL file and easy to maintain. But a website is more flexible; you can edit the aspx file on the go.

How to find the location of the Scheduled Tasks folder

Tasks are saved in filesystem AND registry

Tasks are stored in 3 locations: 1 file system location and 2 registry locations.

File system:

C:\Windows\System32\Tasks

Registry:

HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree

So, you need to delete a corrupted task in these 3 locations.

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

The ":PATH" part in the accepted answer can be omitted. This syntax may be more memorable:

cmake -DCMAKE_INSTALL_PREFIX=/usr . && make all install

...as used in the answers here.

java.util.zip.ZipException: error in opening zip file

In my case SL4j-api.jar with multiple versions are conflicting in the maven repo. Than I deleted the entire SL4j-api folder in m2 maven repo and updated maven project, build maven project than ran the project in JBOSS server. issue got resolved.

How to abort a Task like aborting a Thread (Thread.Abort method)?

  1. You shouldn't use Thread.Abort()
  2. Tasks can be Cancelled but not aborted.

The Thread.Abort() method is (severely) deprecated.

Both Threads and Tasks should cooperate when being stopped, otherwise you run the risk of leaving the system in a unstable/undefined state.

If you do need to run a Process and kill it from the outside, the only safe option is to run it in a separate AppDomain.


This answer is about .net 3.5 and earlier.

Thread-abort handling has been improved since then, a.o. by changing the way finally blocks work.

But Thread.Abort is still a suspect solution that you should always try to avoid.

git error: failed to push some refs to remote

git push -f origin master.

this one is write

How do you overcome the svn 'out of date' error?

Upgrade your server and client to Subversion 1.9.

If the out of date error randomly occurs when it normally should not, when you run commit, it may indicate that you are using an outdated and unsupported Subversion 1.7 or older client or server.

You should upgrade the server and clients in order to solve the problem. See the relevant Subversion 1.9 Release Notes entry: "Out of date" errors when committing over HTTPv1.

UIButton: set image for selected-highlighted state

In Swift 3.x, you can set highlighted image when button is selected in the following way:

// Normal state
button.setImage(UIImage(named: "normalImage"), for: .normal) 

// Highlighted state (before button is selected)
button.setImage(UIImage(named: "pressedImage"), for: .highlighted)

// Selected state
button.setImage(UIImage(named: "selectedImage"), for:  .selected)

// Highlighted state (after button is selected)
button.setImage(UIImage(named: "pressedAfterBeingSelectedImage"), 
                for:  UIControlState.selected.union(.highlighted))

How do I convert a float number to a whole number in JavaScript?

In your case, when you want a string in the end (in order to insert commas), you can also just use the Number.toFixed() function, however, this will perform rounding.

Favicon: .ico or .png / correct tags?

For compatibility with all browsers stick with .ico.

.png is getting more and more support though as it is easier to create using multiple programs.

for .ico

<link rel="shortcut icon" href="http://example.com/myicon.ico" />

for .png, you need to specify the type

<link rel="icon" type="image/png" href="http://example.com/image.png" />

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

This happened to me when I was trying to build an App-store ipa exported file on my device, I had to export ad-hoc instead.

c# datagridview doubleclick on row with FullRowSelect

you can do this by : CellDoubleClick Event this is code.

private void datagridview1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(e.RowIndex.ToString());
    }

Can dplyr package be used for conditional mutating?

Since you ask for other better ways to handle the problem, here's another way using data.table:

require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]

Note the order of conditional statements is reversed to get g correctly. There's no copy of g made, even during the second assignment - it's replaced in-place.

On larger data this would have better performance than using nested if-else, as it can evaluate both 'yes' and 'no' cases, and nesting can get harder to read/maintain IMHO.


Here's a benchmark on relatively bigger data:

# R version 3.1.0
require(data.table) ## 1.9.2
require(dplyr)
DT <- setDT(lapply(1:6, function(x) sample(7, 1e7, TRUE)))
setnames(DT, letters[1:6])
# > dim(DT) 
# [1] 10000000        6
DF <- as.data.frame(DT)

DT_fun <- function(DT) {
    DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
    DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
    mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

BASE_fun <- function(DF) { # R v3.1.0
    transform(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

system.time(ans1 <- DT_fun(DT))
#   user  system elapsed 
#  2.659   0.420   3.107 

system.time(ans2 <- DPLYR_fun(DF))
#   user  system elapsed 
# 11.822   1.075  12.976 

system.time(ans3 <- BASE_fun(DF))
#   user  system elapsed 
# 11.676   1.530  13.319 

identical(as.data.frame(ans1), as.data.frame(ans2))
# [1] TRUE

identical(as.data.frame(ans1), as.data.frame(ans3))
# [1] TRUE

Not sure if this is an alternative you'd asked for, but I hope it helps.

Custom sort function in ng-repeat

The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.

e.g. Given the following assignment:

$scope.cards = {
  "card2": {
    values: {
      opt1: 9,
      opt2: 12
    }
  },
  "card1": {
    values: {
      opt1: 9,
      opt2: 11
    }
  }
};

and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.

To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.

myApp.filter('orderByValue', function () {
  // custom value function for sorting
  function myValueFunction(card) {
    return card.values.opt1 + card.values.opt2;
  }

  return function (obj) {
    var array = [];
    Object.keys(obj).forEach(function (key) {
      // inject key into each object so we can refer to it from the template
      obj[key].name = key;
      array.push(obj[key]);
    });
    // apply a custom sorting function
    array.sort(function (a, b) {
      return myValueFunction(b) - myValueFunction(a);
    });
    return array;
  };
});

We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.

<ul ng-repeat="card in cards | orderByValue">
    <li>{{card.name}} {{value(card)}}</li>
</ul>

Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/

Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332

jQuery function to get all unique elements from an array?

You can use a jQuery plugin called Array Utilities to get an array of unique items. It can be done like this:

var distinctArray = $.distinct([1, 2, 2, 3])

distinctArray = [1,2,3]

OSError - Errno 13 Permission denied

Another option is to ensure the file is not open anywhere else on your machine.

Create line after text with css

You could achieve this with an extra <span>:

HTML

<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>

CSS

h2 {
    position: relative;
}

h2 span {
    background-color: white;
    padding-right: 10px;
}

h2:after {
    content:"";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 0.5em;
    border-top: 1px solid black;
    z-index: -1;
}

http://jsfiddle.net/myajouri/pkm5r/

Another solution without the extra <span> but requires an overflow: hidden on the <h2>:

h2 {
    overflow: hidden;
}

h2:after {
    content:"";
    display: inline-block;
    height: 0.5em;
    vertical-align: bottom;
    width: 100%;
    margin-right: -100%;
    margin-left: 10px;
    border-top: 1px solid black;
}

http://jsfiddle.net/myajouri/h2JRj/

Is 'bool' a basic datatype in C++?

Yes, bool is a built-in type.

WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.

Editor does not contain a main type

Try 'Update Project'. Once I did this, The Run as Java Application option appeared.

Commit history on remote repository

Here's a bash function that makes it easy to view the logs on a remote. It takes two optional arguments. The first one is the branch, it defaults to master. The second one is the remote, it defaults to staging.

git_log_remote() {
  branch=${1:-master}
  remote=${2:-staging}
  
  git fetch $remote
  git checkout $remote/$branch
  git log
  git checkout -
}

examples:

 $ git_log_remote
 $ git_log_remote development origin

How to get Bitmap from an Uri?

you can do this structure:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                    Uri selectedImage = imageReturnedIntent.getData();
                    Bundle extras = imageReturnedIntent.getExtras();
                    bitmap = extras.getParcelable("data");
            }
            break;
   }

by this you can easily convert a uri to bitmap. hope help u.

What to put in a python module docstring?

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

Eclipse Java Missing required source folder: 'src'

One of the build path issue is it cannot find the correct /src/conf source folder. Right click on each project, Build Path > Configure Build Path. Under the Source tab, remove the folder with a red cross icon on the bottom right. It will work for the situation that there is a small red exclamation mark “!“ bedore your project name!

Instantiating a generic class in Java

And this is the Factory implementation, as Jon Skeet suggested:

interface Factory<T> {
    T factory();
}

class Araba {
    //static inner class for Factory<T> implementation
    public static class ArabaFactory implements Factory<Araba> {
        public Araba factory() {
            return new Araba();
        }
    }
    public String toString() { return "Abubeee"; }
}

class Generic<T> {
    private T var;

    Generic(Factory<T> fact) {
        System.out.println("Constructor with Factory<T> parameter");
        var = fact.factory();
    }
    Generic(T var) {
        System.out.println("Constructor with T parameter");
        this.var = var;
    }
    T get() { return var; }
}

public class Main {
    public static void main(String[] string) {
        Generic<Araba> gen = new Generic<Araba>(new Araba.ArabaFactory());
        System.out.print(gen.get());
    }
}

Output:

Constructor with Factory<T> parameter
Abubeee

SQL Server: converting UniqueIdentifier to string in a case statement

Instead of Str(RequestID), try convert(varchar(38), RequestID)

Finding Number of Cores in Java

If you want to dubbel check the amount of cores you have on your machine to the number your java program is giving you.

In Linux terminal: lscpu

In Windows terminal (cmd): echo %NUMBER_OF_PROCESSORS%

In Mac terminal: sysctl -n hw.ncpu

A better way to check if a path exists or not in PowerShell

The alias solution you posted is clever, but I would argue against its use in scripts, for the same reason I don't like using any aliases in scripts; it tends to harm readability.

If this is something you want to add to your profile so you can type out quick commands or use it as a shell, then I could see that making sense.

You might consider piping instead:

if ($path | Test-Path) { ... }
if (-not ($path | Test-Path)) { ... }
if (!($path | Test-Path)) { ... }

Alternatively, for the negative approach, if appropriate for your code, you can make it a positive check then use else for the negative:

if (Test-Path $path) {
    throw "File already exists."
} else {
   # The thing you really wanted to do.
}

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

Convert UTC datetime string to local datetime

Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone

from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
   assert isinstance(timestampValue, int)

   # get the UTC time from the timestamp integer value.
   d = datetime.utcfromtimestamp( timestampValue )

   # calculate time difference from utcnow and the local system time reported by OS
   offset = datetime.now() - datetime.utcnow()

   # Add offset to UTC time and return it
   return d + offset

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can customize the JsonSerializerSettings by using the Formatters.JsonFormatter.SerializerSettings property in the HttpConfiguration object.

For example, you could do that in the Application_Start() method:

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.Formatting =
        Newtonsoft.Json.Formatting.Indented;
}

CSS float right not working correctly

Verry Easy, change order of element:

Origin

<div style="">

    My Text

    <button type="button" style="float: right; margin:5px;">
       My Button
    </button>

</div>

Change to:

<div style=""> 

    <button type="button" style="float: right; margin:5px;">
       My Button
     </button>

   My Text

</div>

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I used the following on Mac OSX.

currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")

How to make the Facebook Like Box responsive?

As of August 4 2015, the native facebook like box have a responsive code snippet available at Facebook Developers page.

You can generate your responsive Facebook likebox here

https://developers.facebook.com/docs/plugins/page-plugin

This is the best solution ever rather than hacking CSS.

Rename multiple files in cmd

I found the following in a small comment in Supperuser.com:

@JacksOnF1re - New information/technique added to my answer. You can actually delete your Copy of prefix using an obscure forward slash technique: ren "Copy of .txt" "////////"

Of How does the Windows RENAME command interpret wildcards? See in this thread, the answer of dbenham.

My problem was slightly different, I wanted to add a Prefix to the file and remove from the beginning what I don't need. In my case I had several hundred of enumerated files such as:

SKMBT_C36019101512510_001.jpg
SKMBT_C36019101512510_002.jpg
SKMBT_C36019101512510_003.jpg
SKMBT_C36019101512510_004.jpg
:
:

Now I wanted to respectively rename them all to (Album 07 picture #):

A07_P001.jpg
A07_P002.jpg
A07_P003.jpg
A07_P004.jpg
:
:

I did it with a single command line and it worked like charm:

ren "SKMBT_C36019101512510_*.*" "/////////////////A06_P*.*"

Note:

  1. Quoting (") the "<Name Scheme>" is not an option, it does not work otherwise, in our example: "SKMBT_C36019101512510_*.*" and "/////////////////A06_P*.*" were quoted.
  2. I had to exactly count the number of characters I want to remove and leave space for my new characters: The A06_P actually replaced 2510_ and the SKMBT_C3601910151 was removed, by using exactly the number of slashes ///////////////// (17 characters).
  3. I recommend copying your files (making a backup), before applying the above.