Programs & Examples On #Startupscript

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

Calling Javascript function from server side

This works for me. Hope it will work for you too.

ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);

I have edited the html page which you have provided. The updated page is as below

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>My Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function Test() {
                alert("Hello Test!!!!");
                $('#ButtonRow').css("display", "block");
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <table>
            <tr>
                <td>
                    <asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
                        BorderStyle="Solid">
                        <asp:ListItem>Merchant</asp:ListItem>
                        <asp:ListItem>Store</asp:ListItem>
                        <asp:ListItem>Terminal</asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr id="ButtonRow" style="display: none">
                <td>
                    <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
                </td>
            </tr>
        </table>
        </form>
    </body>
    </html>

    <script type="text/javascript">

        $("#<%=SearchCategory.ClientID%> input").change(function () {
            alert("hi");
            $("#ButtonRow").show();
        });
    </script>

How to Check byte array empty or not?

.Net V 4.6 OR C # 6.0

Try This

 if (Attachment?.Length > 0)

How to open a page in a new window or tab from code-behind

This code works for me:

Dim script As String = "<script type=""text/javascript"">window.open('" & URL.ToString & "');</script>"
ClientScript.RegisterStartupScript(Me.GetType, "openWindow", script)

How to find Control in TemplateField of GridView?

Try with below code.

Like GridView in LinkButton, Label, HtmlAnchor and HtmlInputControl.

<asp:GridView ID="mainGrid" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-hover tablesorter"
    OnRowDataBound="mainGrid_RowDataBound"  EmptyDataText="No Data Found.">
    <Columns>
        <asp:TemplateField HeaderText="HeaderName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text=' <%# Eval("LabelName") %>'></asp:Label>
                <asp:LinkButton ID="btnLink" runat="server">ButtonName</asp:LinkButton>
                <a href="javascript:void(0);" id="btnAnchor" runat="server">ButtonName</a>
                <input type="hidden" runat="server" id="hdnBtnInput" value='<%#Eval("ID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Handling RowDataBound event,

protected void mainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label lblName = (Label)e.Row.FindControl("lblName");
        LinkButton btnLink = (LinkButton)e.Row.FindControl("btnLink");
        HtmlAnchor btnAnchor = (HtmlAnchor)e.Row.FindControl("btnAnchor");
        HtmlInputControl hdnBtnInput = (HtmlInputControl)e.Row.FindControl("hdnBtnInput");
    }
}

ScriptManager.RegisterStartupScript code not working - why?

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

You can get lat, lng from the place object i.e.

var place = autocomplete.getPlace();

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();

how to add <script>alert('test');</script> inside a text box?

Ok to answer this . I simply converted my < and the > to &lt; and &gt;. What was happening previously is i used to set the text <script>alert('1')</script> but before setting the text in the input text browserconverts &lt; and &gt; as < and the >. So hence converting them again to &lt; and &gt;since browser will understand that as only tags and converts them , than executing the script inside <input type="text" />

Adding Buttons To Google Sheets and Set value to Cells on clicking

Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.

In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.

Why does sudo change the PATH?

Looks like this bug has been around for quite a while! Here are some bug references you may find helpful (and may want to subscribe to / vote up, hint, hint...):


Debian bug #85123 ("sudo: SECURE_PATH still can't be overridden") (from 2001!)

It seems that Bug#20996 is still present in this version of sudo. The changelog says that it can be overridden at runtime but I haven't yet discovered how.

They mention putting something like this in your sudoers file:

Defaults secure_path="/bin:/usr/bin:/usr/local/bin"

but when I do that in Ubuntu 8.10 at least, it gives me this error:

visudo: unknown defaults entry `secure_path' referenced near line 10

Ubuntu bug #50797 ("sudo built with --with-secure-path is problematic")

Worse still, as far as I can tell, it is impossible to respecify secure_path in the sudoers file. So if, for example, you want to offer your users easy access to something under /opt, you must recompile sudo.


Yes. There needs to be a way to override this "feature" without having to recompile. Nothing worse then security bigots telling you what's best for your environment and then not giving you a way to turn it off.


This is really annoying. It might be wise to keep current behavior by default for security reasons, but there should be a way of overriding it other than recompiling from source code! Many people ARE in need of PATH inheritance. I wonder why no maintainers look into it, which seems easy to come up with an acceptable solution.


I worked around it like this:

mv /usr/bin/sudo /usr/bin/sudo.orig

then create a file /usr/bin/sudo containing the following:

#!/bin/bash
/usr/bin/sudo.orig env PATH=$PATH "$@"

then your regular sudo works just like the non secure-path sudo


Ubuntu bug #192651 ("sudo path is always reset")

Given that a duplicate of this bug was originally filed in July 2006, I'm not clear how long an ineffectual env_keep has been in operation. Whatever the merits of forcing users to employ tricks such as that listed above, surely the man pages for sudo and sudoers should reflect the fact that options to modify the PATH are effectively redundant.

Modifying documentation to reflect actual execution is non destabilising and very helpful.


Ubuntu bug #226595 ("impossible to retain/specify PATH")

I need to be able to run sudo with additional non-std binary folders in the PATH. Having already added my requirements to /etc/environment I was surprised when I got errors about missing commands when running them under sudo.....

I tried the following to fix this without sucess:

  1. Using the "sudo -E" option - did not work. My existing PATH was still reset by sudo

  2. Changing "Defaults env_reset" to "Defaults !env_reset" in /etc/sudoers -- also did not work (even when combined with sudo -E)

  3. Uncommenting env_reset (e.g. "#Defaults env_reset") in /etc/sudoers -- also did not work.

  4. Adding 'Defaults env_keep += "PATH"' to /etc/sudoers -- also did not work.

Clearly - despite the man documentation - sudo is completely hardcoded regarding PATH and does not allow any flexibility regarding retaining the users PATH. Very annoying as I can't run non-default software under root permissions using sudo.

Rotate and translate

There is no need for that, as you can use css 'writing-mode' with values 'vertical-lr' or 'vertical-rl' as desired.

.item {
  writing-mode: vertical-rl;
}

CSS:writing-mode

Replace one substring for another string in shell script

To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}:

#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/$secondString}"    
# prints 'I love Sara and Marry'

To replace all occurrences, use ${parameter//pattern/string}:

message='The secret code is 12345'
echo "${message//[0-9]/X}"           
# prints 'The secret code is XXXXX'

(This is documented in the Bash Reference Manual, §3.5.3 "Shell Parameter Expansion".)

Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see The Open Group Technical Standard Base Specifications, Issue 7, the Shell & Utilities volume, §2.6.2 "Parameter Expansion".

How do you launch the JavaScript debugger in Google Chrome?

In Chrome 8.0.552 on a Mac, you can find this under menu View/Developer/JavaScript Console ... or you can use Alt+CMD+J.

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

If you can use javascipt, have the client handle laying out the content using javascript to place elements based on available space.

You could use the jquery columnizer plugin to dynamically lay out your content in fixed size blocks and position your headers and footers as part of the rendering routine. http://welcome.totheinter.net/columnizer-jquery-plugin/

See example 10 http://welcome.totheinter.net/autocolumn/sample10.html

The browser will still add its own headers or footers if enabled in the os. Consistent layout across platforms and browsers will likely require conditional css.

PHP Pass variable to next page

**page 1**
<form action="exapmple.php?variable_name=$value" method="POST"> 
    <button>
        <input  type="hidden" name="x">
    </button>
</form>`

page 2

if(isset($_POST['x'])) {
    $new_value=$_GET['variable_name'];
}

Why use 'git rm' to remove a file instead of 'rm'?

Adding to Andy's answer, there is additional utility to git rm:

  1. Safety: When doing git rm instead of rm, Git will block the removal if there is a discrepancy between the HEAD version of a file and the staging index or working tree version. This block is a safety mechanism to prevent removal of in-progress changes.

  2. Safeguarding: git rm --dry-run. This option is a safeguard that will execute the git rm command but not actually delete the files. Instead it will output which files it would have removed.

How to download all files (but not HTML) from a website using wget?

This downloaded the entire website for me:

wget --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla http://site/path/

CSS scale down image to fit in containing div, without specifing original size

You can use a background image to accomplish this;

From MDN - Background Size: Contain:

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

Demo

CSS:

#im {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url("path/to/img");
    background-repeat: no-repeat;
    background-size: contain;
}

HTML:

<div id="wrapper">
    <div id="im">
    </div>
</div>

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Following are the results when we use both [MaxLength] and [StringLength] attributes, in EF code first. If both are used, [MaxLength] wins the race. See the test result in studentname column in below class

 public class Student
 {
    public Student () {}

    [Key]
    [Column(Order=1)]
    public int StudentKey { get; set; }

    //[MaxLength(50),StringLength(60)]    //studentname column will be nvarchar(50)
    //[StringLength(60)]    //studentname column will be nvarchar(60)
    [MaxLength(50)] //studentname column will be nvarchar(50)
    public string StudentName { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
 }

Facebook login "given URL not allowed by application configuration"

You can set up a developer application and set the url to localhost.com:port Make sure to map localhost.com to localhost on your hosts file

Works for me

JavaFX Application Icon

stage.getIcons().add(new Image("/images/logo_only.png"));

It is good habit to make images folder in your src folder and get images from it.

Validating input using java.util.Scanner

For checking Strings for letters you can use regular expressions for example:

someString.matches("[A-F]");

For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want. Here

    public int readInt(String prompt, int min, int max)
    {
    Scanner scan = new Scanner(System.in);

    int number = 0;

    //Run once and loop until the input is within the specified range.
    do 
    {
        //Print users message.
        System.out.printf("\n%s > ", prompt);

        //Prevent string input crashing the program.
        while (!scan.hasNextInt()) 
        {
            System.out.printf("Input doesn't match specifications. Try again.");
            System.out.printf("\n%s > ", prompt);
            scan.next(); 
        }

        //Set the number.
        number = scan.nextInt();

        //If the number is outside range print an error message.
        if (number < min || number > max)
            System.out.printf("Input doesn't match specifications. Try again.");

    } while (number < min || number > max);

    return number;
}

Should I set max pool size in database connection string? What happens if I don't?

Currently your application support 100 connections in pool. Here is what conn string will look like if you want to increase it to 200:

public static string srConnectionString = 
                "server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;";

You can investigate how many connections with database your application use, by executing sp_who procedure in your database. In most cases default connection pool size will be enough.

How to customize <input type="file">?

You can’t modify much about the input[type=file] control itself.

Since clicking a label element correctly paired with an input will activate/focus it, we can use a label to trigger the OS browse dialog.

Here is how you can do it…

_x000D_
_x000D_
label {_x000D_
   cursor: pointer;_x000D_
   /* Style as you please, it will become the visible UI component. */_x000D_
}_x000D_
_x000D_
#upload-photo {_x000D_
   opacity: 0;_x000D_
   position: absolute;_x000D_
   z-index: -1;_x000D_
}
_x000D_
<label for="upload-photo">Browse...</label>_x000D_
<input type="file" name="photo" id="upload-photo" />
_x000D_
_x000D_
_x000D_

The CSS for the form control will make it appear invisible and not take up space in the document layout, but will still exist so it can be activated via the label.

If you want to display the user’s chosen path after selection, you can listen for the change event with JavaScript and then read the path that the browser makes available to you (for security reasons it can lie to you about the exact path). A way to make it pretty for the end user is to simply use the base name of the path that is returned (so the user simply sees the chosen filename).

There is a great guide by Tympanus for styling this.

Android ADB commands to get the device properties

You should use adb shell getprop command and grep specific info about your current device, For additional information you can read documentation: Android Debug Bridge documentation

I added some examples below:

  1. language - adb shell getprop | grep language

    [persist.sys.language]: [en]

    [ro.product.locale.language]: [en]

  2. boot complete ( device ready after reset) - adb shell getprop | grep boot_completed

    [sys.boot_completed]: [1]

  3. device model - adb shell getprop | grep model

    [ro.product.model]: [Nexus 4]

  4. sdk version - adb shell getprop | grep sdk

    [ro.build.version.sdk]: [22]

  5. time zone - adb shell getprop | grep timezone

    [persist.sys.timezone]: [Asia/China]

  6. serial number - adb shell getprop | grep serialno

    [ro.boot.serialno]: [1234567]

Why is this jQuery click function not working?

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

i.e.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"

Why do we need middleware for async flow in Redux?

When working in an enterprise project, there are many requirements available in middle-ware such as (saga) not available in simple asynchronous flow, below are some:

  • Running request in parallel
  • Pulling future actions without the need to wait
  • Non-blocking calls Race effect, example pickup first
  • response to initiate the process Sequencing your tasks (first in first call)
  • Composing
  • Task cancellation Dynamically forking the task.
  • Support Concurrency Running Saga outside the redux middleware.
  • Using channels

The list is long just review the advanced section in saga documentation

HTML table with horizontal scrolling (first column fixed)

Based on skube's approach, I found the minimal set of CSS I needed was:

_x000D_
_x000D_
.horizontal-scroll-except-first-column {_x000D_
  width: 100%;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table {_x000D_
  margin-left: 8em;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th:first-child,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td:first-child {_x000D_
  position: absolute;_x000D_
  width: 8em;_x000D_
  margin-left: -8em;_x000D_
  background: #ccc;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td {_x000D_
  /* Without this, if a cell wraps onto two lines, the first column_x000D_
   * will look bad, and may need padding. */_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<div class="horizontal-scroll-except-first-column">_x000D_
  <table>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>FIXED</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> <td>66666</td> <td>77777</td> <td>88888</td> <td>99999</td> <td>AAAAA</td> <td>BBBBB</td> <td>CCCCC</td> <td>DDDDD</td> <td>EEEEE</td> <td>FFFFF</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.

Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.

Just my 2 cents worth.

Does Python have a ternary conditional operator?

is_spacial=True if gender = "Female" else (True if age >= 65 else False)

**

it can be nested as your need. best of luck

**

MySql : Grant read only options?

Various permissions that you can grant to a user are

ALL PRIVILEGES- This would allow a MySQL user all access to a designated database (or if no database is selected, across the system)
CREATE- allows them to create new tables or databases
DROP- allows them to them to delete tables or databases
DELETE- allows them to delete rows from tables
INSERT- allows them to insert rows into tables
SELECT- allows them to use the Select command to read through databases
UPDATE- allow them to update table rows
GRANT OPTION- allows them to grant or remove other users' privileges

To provide a specific user with a permission, you can use this framework:

GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;

I found this article very helpful

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Enter the original date into a Date object and then print out the result with a DateFormat. You may have to split up the string into smaller pieces to create the initial Date object, if the automatic parse method does not accept your format.

Pseudocode:

Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);

Read values into a shell variable from a pipe

read won't read from a pipe (or possibly the result is lost because the pipe creates a subshell). You can, however, use a here string in Bash:

$ read a b c <<< $(echo 1 2 3)
$ echo $a $b $c
1 2 3

But see @chepner's answer for information about lastpipe.

Seeding the random number generator in Javascript

I've implemented a number of good, short and fast Pseudorandom number generator (PRNG) functions in plain JavaScript. All of them can be seeded and provide good quality numbers.

First of all, take care to initialize your PRNGs properly. Most of the generators below have no built-in seed generating procedure (for sake of simplicity), but accept one or more 32-bit values as the initial state of the PRNG. Similar seeds (e.g. a simple seed of 1 and 2) can cause correlations in weaker PRNGs, resulting in the output having similar properties (such as randomly generated levels being similar). To avoid this, it is best practice to initialize PRNGs with a well-distributed seed.

Thankfully, hash functions are very good at generating seeds for PRNGs from short strings. A good hash function will generate very different results even when two strings are similar. Here's an example based on MurmurHash3's mixing function:

function xmur3(str) {
    for(var i = 0, h = 1779033703 ^ str.length; i < str.length; i++)
        h = Math.imul(h ^ str.charCodeAt(i), 3432918353),
        h = h << 13 | h >>> 19;
    return function() {
        h = Math.imul(h ^ h >>> 16, 2246822507);
        h = Math.imul(h ^ h >>> 13, 3266489909);
        return (h ^= h >>> 16) >>> 0;
    }
}

Each subsequent call to the return function of xmur3 produces a new "random" 32-bit hash value to be used as a seed in a PRNG. Here's how you might use it:

// Create xmur3 state:
var seed = xmur3("apples");
// Output four 32-bit hashes to provide the seed for sfc32.
var rand = sfc32(seed(), seed(), seed(), seed());

// Output one 32-bit hash to provide the seed for mulberry32.
var rand = mulberry32(seed());

// Obtain sequential random numbers like so:
rand();
rand();

Alternatively, simply choose some dummy data to pad the seed with, and advance the generator a few times (12-20 iterations) to mix the initial state thoroughly. This is often seen in reference implementations of PRNGs, but it does limit the number of initial states.

var seed = 1337 ^ 0xDEADBEEF; // 32-bit seed with optional XOR value
// Pad seed with Phi, Pi and E.
// https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number
var rand = sfc32(0x9E3779B9, 0x243F6A88, 0xB7E15162, seed);
for (var i = 0; i < 15; i++) rand();

The output of these PRNG functions produce a positive 32-bit number (0 to 232-1) which is then converted to a floating-point number between 0-1 (0 inclusive, 1 exclusive) equivalent to Math.random(), if you want random numbers of a specific range, read this article on MDN. If you only want the raw bits, simply remove the final division operation.

Another thing to note are the limitations of JS. Numbers can only represent whole integers up to 53-bit resolution. And when using bitwise operations, this is reduced to 32. This makes it difficult to implement algorithms written in C or C++, that use 64-bit numbers. Porting 64-bit code requires shims that can drastically reduce performance. So for the sake of simplicity and efficiency, I've only considered algorithms that use 32-bit math, as it is directly compatible with JS.

Now, onward to the the generators. (I maintain the full list with references here)


sfc32 (Simple Fast Counter)

sfc32 is part of the PractRand random number testing suite (which it passes of course). sfc32 has a 128-bit state and is very fast in JS.

function sfc32(a, b, c, d) {
    return function() {
      a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0; 
      var t = (a + b) | 0;
      a = b ^ b >>> 9;
      b = c + (c << 3) | 0;
      c = (c << 21 | c >>> 11);
      d = d + 1 | 0;
      t = t + d | 0;
      c = c + t | 0;
      return (t >>> 0) / 4294967296;
    }
}

Mulberry32

Mulberry32 is a simple generator with a 32-bit state, but is extremely fast and has good quality (author states it passes all tests of gjrand testing suite and has a full 232 period, but I haven't verified).

function mulberry32(a) {
    return function() {
      var t = a += 0x6D2B79F5;
      t = Math.imul(t ^ t >>> 15, t | 1);
      t ^= t + Math.imul(t ^ t >>> 7, t | 61);
      return ((t ^ t >>> 14) >>> 0) / 4294967296;
    }
}

I would recommend this if you just need a simple but decent PRNG and don't need billions of random numbers (see Birthday problem).

xoshiro128**

As of May 2018, xoshiro128** is the new member of the Xorshift family, by Vigna & Blackman (professor Vigna was also responsible for the Xorshift128+ algorithm powering most Math.random implementations under the hood). It is the fastest generator that offers a 128-bit state.

function xoshiro128ss(a, b, c, d) {
    return function() {
        var t = b << 9, r = a * 5; r = (r << 7 | r >>> 25) * 9;
        c ^= a; d ^= b;
        b ^= c; a ^= d; c ^= t;
        d = d << 11 | d >>> 21;
        return (r >>> 0) / 4294967296;
    }
}

The authors claim it passes randomness tests well (albeit with caveats). Other researchers have pointed out that fails some tests in TestU01 (particularly LinearComp and BinaryRank). In practice, it should not cause issues when floats are used (such as these implementations), but may cause issues if relying on the raw low bits.

JSF (Jenkins' Small Fast)

This is JSF or 'smallprng' by Bob Jenkins (2007), the guy who made ISAAC and SpookyHash. It passes PractRand tests and should be quite fast, although not as fast as SFC.

function jsf32(a, b, c, d) {
    return function() {
        a |= 0; b |= 0; c |= 0; d |= 0;
        var t = a - (b << 27 | b >>> 5) | 0;
        a = b ^ (c << 17 | c >>> 15);
        b = c + d | 0;
        c = d + t | 0;
        d = a + t | 0;
        return (d >>> 0) / 4294967296;
    }
}

LCG (aka Lehmer/Park-Miller RNG or MCG)

LCG is extremely fast and simple, but the quality of its randomness is so low, that improper use can actually cause bugs in your program! Nonetheless, it is significantly better than some answers suggesting to use Math.sin or Math.PI! It's a one-liner though, which is nice :).

var LCG=s=>()=>(2**31-1&(s=Math.imul(48271,s)))/2**31;

This implementation is called the minimal standard RNG as proposed by Park–Miller in 1988 & 1993 and implemented in C++11 as minstd_rand. Keep in mind that the state is 31-bit (31 bits give 2 billion possible states, 32 bits give double that). This is the very type of PRNG that others are trying to replace!

It will work, but I wouldn't use it unless you really need speed and don't care about randomness quality (what is random anyway?). Great for a game jam or a demo or something. LCGs suffer from seed correlations, so it is best to discard the first result of an LCG. And if you insist on using an LCG, adding an increment value may improve results, but it is probably an exercise in futility when much better options exist.

There seems to be other multipliers offering a 32-bit state (increased state-space):

var LCG=s=>()=>(s=Math.imul(741103597,s)>>>0)/2**32;
var LCG=s=>()=>(s=Math.imul(1597334677,s)>>>0)/2**32;

These LCG values are from: P. L'Ecuyer: A table of Linear Congruential Generators of different sizes and good lattice structure, April 30 1997.

Create array of regex matches

From the Official Regex Java Trails:

        Pattern pattern = 
        Pattern.compile(console.readLine("%nEnter your regex: "));

        Matcher matcher = 
        pattern.matcher(console.readLine("Enter input string to search: "));

        boolean found = false;
        while (matcher.find()) {
            console.format("I found the text \"%s\" starting at " +
               "index %d and ending at index %d.%n",
                matcher.group(), matcher.start(), matcher.end());
            found = true;
        }

Use find and insert the resulting group at your array / List / whatever.

JavaScript REST client Library

For reference I want to add about ExtJS, as explained in Manual: RESTful Web Services. In short, use method to specify GET, POST, PUT, DELETE. Example:

Ext.Ajax.request({
    url: '/articles/restful-web-services',
    method: 'PUT',
    params: {
        author: 'Patrick Donelan',
        subject: 'RESTful Web Services are easy with Ext!'
    }
});

If the Accept header is necessary, it can be set as a default for all requests:

Ext.Ajax.defaultHeaders = {
    'Accept': 'application/json'
};

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

Try wrapping your dates in single quotes, like this:

'15-6-2005'

It should be able to parse the date this way.

JPA OneToMany not deleting child

As explained, it is not possible to do what I want with JPA, so I employed the hibernate.cascade annotation, with this, the relevant code in the Parent class now looks like this:

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, mappedBy = "parent")
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE,
            org.hibernate.annotations.CascadeType.DELETE,
            org.hibernate.annotations.CascadeType.MERGE,
            org.hibernate.annotations.CascadeType.PERSIST,
            org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private Set<Child> childs = new HashSet<Child>();

I could not simple use 'ALL' as this would have deleted the parent as well.

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

How do I prompt a user for confirmation in bash script?

This what I found elsewhere, is there a better possible version?

read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
   exit
fi

jQuery: Performing synchronous AJAX requests

how remote is that url ? is it from the same domain ? the code looks okay

try this

$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;

How to determine whether an object has a given property in JavaScript

You can trim that up a bit like this:

if ( x.y !== undefined ) ...

Cannot drop database because it is currently in use

First check the connected databases

SP_WHO

Second Disconnect your database

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'your_database_name'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

--SELECT @SQL 
EXEC(@SQL)

FINALLY DROP IT

drop database your_database

How does jQuery work when there are multiple elements with the same ID value?

From the id Selector jQuery page:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

Naughty Google. But they don't even close their <html> and <body> tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.

Selecting multiple columns with linq query and lambda expression

You can use:

public YourClass[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts.Where(x => x.Status == 1)
                           .OrderBy(x => x.ID)
                           .Select(x => new YourClass { ID = x.ID, Name = x.Name, Price = x.Price})
                           .ToArray();
        }
    }
    catch
    {
        return null;
    }
}

And here is YourClass implementation:

public class YourClass
{
  public string Name {get; set;}
  public int ID {get; set;}
  public int Price {get; set;}
}

And your AllProducts method's return type must be YourClass[].

Casting variables in Java

Casting a reference will only work if it's an instanceof that type. You can't cast random references. Also, you need to read more on Casting Objects.

e.g.

String string = "String";

Object object = string; // Perfectly fine since String is an Object

String newString = (String)object; // This only works because the `reference` object is pointing to a valid String object.

Generate MD5 hash string with T-SQL

You didn't explicitly say you wanted the string to be hex; if you are open to the more space efficient base 64 string encoding, and you are using SQL Server 2016 or later, here's an alternative:

select SubString(h, 1, 32) from OpenJson(
    (select HashBytes('MD5', '[email protected]') h for json path)
) with (h nvarchar(max));

This produces:

9TvQiSDl0lgJ3yVj75xStg==

Should I use encodeURI or encodeURIComponent for encoding URLs?

Here is a summary.

  1. escape() will not encode @ * _ + - . /

    Do not use it.

  2. encodeURI() will not encode A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    Use it when your input is a complete URL like 'https://searchexample.com/search?q=wiki'

  3. encodeURIComponent() will not encode A-Z a-z 0-9 - _ . ! ~ * ' ( ) Use it when your input is part of a complete URL e.g const queryStr = encodeURIComponent(someString)

Android - default value in editText

Use android android:hint for set default value or android:text

refresh both the External data source and pivot tables together within a time schedule

I used the above answer but made use of the RefreshAll method. I also changed it to allow for multiple connections without having to specify the names. I then linked this to a button on my spreadsheet.

Sub Refresh()

    Dim conn As Variant

    For Each conn In ActiveWorkbook.Connections
        conn.ODBCConnection.BackgroundQuery = False
    Next conn

    ActiveWorkbook.RefreshAll
End Sub

How do I check that a number is float or integer?

Trying some of the answers here I ended up writing this solution. This works also with numbers inside a string.

function isInt(number) {
    if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
    return !(number - parseInt(number));
}

function isFloat(number) {
    if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;
    return number - parseInt(number) ? true : false;
}

_x000D_
_x000D_
    var tests = {_x000D_
        'integer' : 1,_x000D_
        'float' : 1.1,_x000D_
        'integerInString' : '5',_x000D_
        'floatInString' : '5.5',_x000D_
        'negativeInt' : -345,_x000D_
        'negativeFloat' : -34.98,_x000D_
        'negativeIntString' : '-45',_x000D_
        'negativeFloatString' : '-23.09',_x000D_
        'notValidFalse' : false,_x000D_
        'notValidTrue' : true,_x000D_
        'notValidString' : '45lorem',_x000D_
        'notValidStringFloat' : '4.5lorem',_x000D_
        'notValidNan' : NaN,_x000D_
        'notValidObj' : {},_x000D_
        'notValidArr' : [1,2],_x000D_
    };_x000D_
_x000D_
    function isInt(number) {_x000D_
        if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;_x000D_
        return !(number - parseInt(number));_x000D_
    }_x000D_
    _x000D_
    function isFloat(number) {_x000D_
        if(!/^["|']{0,1}[-]{0,1}\d{0,}(\.{0,1}\d+)["|']{0,1}$/.test(number)) return false;_x000D_
        return number - parseInt(number) ? true : false;_x000D_
    }_x000D_
_x000D_
    function testFunctions(obj) {_x000D_
        var keys = Object.keys(obj);_x000D_
        var values = Object.values(obj);_x000D_
_x000D_
        values.forEach(function(element, index){_x000D_
            console.log(`Is ${keys[index]} (${element}) var an integer? ${isInt(element)}`);_x000D_
            console.log(`Is ${keys[index]} (${element}) var a float? ${isFloat(element)}`);_x000D_
        });_x000D_
    }_x000D_
_x000D_
    testFunctions(tests);
_x000D_
_x000D_
_x000D_

number of values in a list greater than a certain number

Different way of counting by using bisect module:

>>> from bisect import bisect
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> j.sort()
>>> b = 5
>>> index = bisect(j,b) #Find that index value
>>> print len(j)-index
3

Format date and time in a Windows batch script

A nice single-line trick to avoid early variable expansion is to use cmd /c echo ^%time^%

cmd /c echo ^%time^% & dir /s somelongcommand & cmd /c echo ^%time^%

How to select the first row of each group?

The solution below does only one groupBy and extract the rows of your dataframe that contain the maxValue in one shot. No need for further Joins, or Windows.

import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.DataFrame

//df is the dataframe with Day, Category, TotalValue

implicit val dfEnc = RowEncoder(df.schema)

val res: DataFrame = df.groupByKey{(r) => r.getInt(0)}.mapGroups[Row]{(day: Int, rows: Iterator[Row]) => i.maxBy{(r) => r.getDouble(2)}}

Java JTable setting Column Width

With JTable.AUTO_RESIZE_OFF, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using the JTable.AUTO_RESIZE_LAST_COLUMN autoResizeMode, but it might be most effective when used with TableColumn.setMaxWidth() instead of TableColumn.setPreferredWidth() for all but the last column.

Once you are satisfied that AUTO_RESIZE_LAST_COLUMN does in fact work, you can experiment with a combination of TableColumn.setMaxWidth() and TableColumn.setMinWidth()

Converting a Date object to a calendar object

it's so easy...converting a date to calendar like this:

Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

What exactly do "u" and "r" string flags do, and what are raw string literals?

There are two types of string in python: the traditional str type and the newer unicode type. If you type a string literal without the u in front you get the old str type which stores 8-bit characters, and with the u in front you get the newer unicode type that can store any Unicode character.

The r doesn't change the type at all, it just changes how the string literal is interpreted. Without the r, backslashes are treated as escape characters. With the r, backslashes are treated as literal. Either way, the type is the same.

ur is of course a Unicode string where backslashes are literal backslashes, not part of escape codes.

You can try to convert a Unicode string to an old string using the str() function, but if there are any unicode characters that cannot be represented in the old string, you will get an exception. You could replace them with question marks first if you wish, but of course this would cause those characters to be unreadable. It is not recommended to use the str type if you want to correctly handle unicode characters.

java: run a function after a specific number of seconds

you could use the Thread.Sleep() function

Thread.sleep(4000);
myfunction();

Your function will execute after 4 seconds. However this might pause the entire program...

How to assign the output of a Bash command to a variable?

Here's your script...

DIR=$(pwd)
echo $DIR
while [ "$DIR" != "/" ]; do
    cd ..
    DIR=$(pwd)
    echo $DIR
done

Note the spaces, use of quotes, and $ signs.

HorizontalScrollView within ScrollView Touch Handling

Thank you Joel for giving me a clue on how to resolve this problem.

I have simplified the code(without need for a GestureDetector) to achieve the same effect:

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                lastX = ev.getX();
                lastY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - lastX);
                yDistance += Math.abs(curY - lastY);
                lastX = curX;
                lastY = curY;
                if(xDistance > yDistance)
                    return false;
        }

        return super.onInterceptTouchEvent(ev);
    }
}

start MySQL server from command line on Mac OS Lion

MySql server startup error 'The server quit without updating PID file '

if you have installed mysql from homebrew

close mysql server from preferences of mac

ps ax | grep mysql

#kill all the mysql process running
sudo kill -9 pid

which mysql
/usr/local/bin/mysql
Admins-MacBook-Pro:bin username$ sudo mysql.server start

Starting MySQL
. SUCCESS! 

Admins-MacBook-Pro:bin username$ which mysql

/usr/local/bin/mysql

Admins-MacBook-Pro:bin username$ ps ax | grep mysql

54916 s005  S      0:00.02 /bin/sh 
/usr/local/Cellar/[email protected]/5.7.27_1/bin/mysqld_safe --datadir=/usr/local/var/mysql --pid-file=/usr/local/var/mysql/Admins-MacBook-Pro.local.pid
55012 s005  S      0:00.40 /usr/local/Cellar/[email protected]/5.7.27_1/bin/mysqld --basedir=/usr/local/Cellar/[email protected]/5.7.27_1 --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/Cellar/[email protected]/5.7.27_1/lib/plugin --user=mysql --log-error=Admins-MacBook-Pro.local.err --pid-file=/usr/local/var/mysql/Admins-MacBook-Pro.local.pid
55081 s005  S+     0:00.00 grep mysql

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

SIMPLE SOLUTION

  1. Create a new blank project and save it
  2. using NOTEPAD open the .VBP of the new project and copy the MSCOMCTL line
  3. using NOTEPAD open the .VBP file of your project
  4. replace the MSCOMCTL line and save it

DONE

good luck

Rerender view on browser resize with React

https://github.com/renatorib/react-sizes is a HOC to do this while still maintaining good performance.

import React from 'react'
import withSizes from 'react-sizes'

@withSizes(({ width }) => ({ isMobile: width < 480 }))
class MyComponent extends Component {
  render() {
    return <div>{this.props.isMobile ? 'Is Mobile' : 'Is Not Mobile'}</div>
  }
}

export default MyComponent

Using Environment Variables with Vue.js

In addition to the previous answers, if you're looking to access VUE_APP_* env variables in your sass (either the sass section of a vue component or a scss file), then you can add the following to your vue.config.js (which you may need to create if you don't have one):

let sav = "";
for (let e in process.env) {
    if (/VUE_APP_/i.test(e)) {
        sav += `$${e}: "${process.env[e]}";`;
    }
}

module.exports = {
    css: {
        loaderOptions: {
            sass: {
                data: sav,
            },
        },
    },
}

The string sav seems to be prepended to every sass file that before processing, which is fine for variables. You could also import mixins at this stage to make them available for the sass section of each vue component.

You can then use these variables in your sass section of a vue file:

<style lang="scss">
.MyDiv {
    margin: 1em 0 0 0;
    background-image: url($VUE_APP_CDN+"/MyImg.png");
}
</style>

or in a .scss file:

.MyDiv {
    margin: 1em 0 0 0;
    background-image: url($VUE_APP_CDN+"/MyImg.png");
}

from https://www.matt-helps.com/post/expose-env-variables-vue-cli-sass/

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Cause: The error occurred since hibernate is not able to connect to the database.
Solution:
1. Please ensure that you have a database present at the server referred to in the configuration file eg. "hibernatedb" in this case.
2. Please see if the username and password for connecting to the db are correct.
3. Check if relevant jars required for the connection are mapped to the project.

Capture keyboardinterrupt in Python without try-except

If all you want is to not show the traceback, make your code like this:

## all your app logic here
def main():
   ## whatever your app does.


if __name__ == "__main__":
   try:
      main()
   except KeyboardInterrupt:
      # do nothing here
      pass

(Yes, I know that this doesn't directly answer the question, but it's not really clear why needing a try/except block is objectionable -- maybe this makes it less annoying to the OP)

How to configure Visual Studio to use Beyond Compare

In Visual Studio 2008 + , go to the

Tools menu -->  select Options 

enter image description here

In Options Window --> expand Source Control --> Select Subversion User Tools --> Select Beyond Compare

and click OK button..

How do I sort a list of dictionaries by a value of the dictionary?

If you do not need the original list of dictionaries, you could modify it in-place with sort() method using a custom key function.

Key function:

def get_name(d):
    """ Return the value of a key in a dictionary. """

    return d["name"]

The list to be sorted:

data_one = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]

Sorting it in-place:

data_one.sort(key=get_name)

If you need the original list, call the sorted() function passing it the list and the key function, then assign the returned sorted list to a new variable:

data_two = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
new_data = sorted(data_two, key=get_name)

Printing data_one and new_data.

>>> print(data_one)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
>>> print(new_data)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

How do I clone a single branch in Git?

There are primarily 2 solutions for this:

  1. You need to specify the branch name with -b command switch. Here is the syntax of the command to clone the specific git branch.

    git clone -b <BRANCH_NAME> <GIT_REMOTE_URL>
    

    Example:

    git clone -b tahir https://github.com/Repository/Project.git
    

    The following command will clone the branch tahir from the git repository.The above command clones only the specific branch but fetches the details of other branches. You can view all branches details with command.

    git branch -a
    
  2. You can use --single-branch flag to prevent fetching details of other branches like below:

    git clone -b <BRANCH_NAME> --single-branch <GIT_REMOTE_URL>
    

    Example:

    git clone -b tahir --single-branch \ 
    https://github.com/Repository/Project.git
    

    Now if you do a git branch -a, it will only show your current single branch that you have cloned and not all the branches. So it depends on you how you want it.

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

Application not picking up .css file (flask/python)

One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py file:

app = Flask(__name__, static_folder="your path to static")

Otherwise flask will not be able to detect static folder.

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

For anyone still experiencing this, I found that images served on Amazon S3 do not work for WhatsApp mobile app (both Android and iOS, but Mac desktop app was fine). It's very possible that our AWS settings cause this, but I noticed the pattern in other sites as well (e.g. this one with an og:image hitting a domain like https://s3.amazonaws.com).

There were no problems on any other platform I tried, just WhatsApp mobile apps. As soon as I pointed my <meta property="og:image" content="https://some-non-aws-location" /> to another public URL like a Google Drive file (shared publicly of course), it worked fine.

I also tried committing the image in our repo, which is hosted and deployed on AWS with a custom domain, and that didn't work either. So AWS still seems to be the culprit. Hope this helps someone!

How can I give the Intellij compiler more heap space?

Since IntelliJ 2016, the location is File | Settings | Build, Execution, Deployment | Compiler | Build process heap size.

enter image description here

How to convert Observable<any> to array[]

This should work:

GetCountries():Observable<CountryData[]>  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json());
}

For this to work you will need to import the following:

import 'rxjs/add/operator/map'

Set a button background image iPhone programmatically

This will work

UIImage *buttonImage = [UIImage imageNamed:@"imageName.png"];
[btn setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:btn];

Unzip All Files In A Directory

for file in 'ls *.zip'; do unzip "${file}" -d "${file:0:-4}"; done

print memory address of Python variable

id is the method you want to use: to convert it to hex:

hex(id(variable_here))

For instance:

x = 4
print hex(id(x))

Gave me:

0x9cf10c

Which is what you want, right?

(Fun fact, binding two variables to the same int may result in the same memory address being used.)
Try:

x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

This gave me identical pairs, even for the large integers.

How store a range from excel into a Range variable?

Declare your dim as a variant, and pull the data as you would from an array. i.e.

Dim y As Variant
y = Range("A1:B2")

Now your excel range is all 1 variable (array), y

To pull the data, call the array position in the range "A1:B2" or whatever you choose. e.g.:

Msgbox y(1, 1)

This will return the top left box in the "A1:B2" range.

How do I add a resources folder to my Java project in Eclipse

Right click on project >> Click on properties >> Java Build Path >> Source >> Add Folder

How can I wrap text in a label using WPF?

Often you cannot replace a Label with a TextBlock as you want to the use the Target property (which sets focus to the targeted control when using the keyboard e.g. ALT+C in the sample code below), as that's all a Label really offers over a TextBlock.

However, a Label uses a TextBlock to render text (if a string is placed in the Content property, which it typically is); therefore, you can add a style for TextBlock inside the Label like so:

<Label              
    Content="_Content Text:"
    Target="{Binding ElementName=MyTargetControl}">
    <Label.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap" />
        </Style>
    </Label.Resources>
 </Label>
 <CheckBox x:Name = "MyTargetControl" />

This way you get to keep the functionality of a Label whilst also being able to wrap the text.

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

How to retrieve data from a SQL Server database in C#?

we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields

class Db
{
    private readonly static string ConnectionString =
            ConfigurationManager.ConnectionStrings
                        ["DbConnectionString"].ConnectionString;
    public static List<string> GetValuesFromDB(string LocationCode)
    {
        List<string> ValuesFromDB = new List<string>();
        string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
            $"from [CustomerLocations] where LocationCode='{LocationCode}';";
        using (SqlConnection Locationconnection =
                                 new SqlConnection(ConnectionString))
        {
            SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
            try
            {
                Locationconnection.Open();
                SqlDataReader Locationreader = command.ExecuteReader();
                while (Locationreader.Read())
                {
                    for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
                    {
                        ValuesFromDB.Add(Locationreader[i].ToString());
                    }
                }
                Locationreader.Close();
                return ValuesFromDB;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

    }

}

hope this might helpful

Note: you guys need connection string (in our case "DbConnectionString")

Extract every nth element of a vector

Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:

foo[ c( rep(FALSE, 5), TRUE ) ]

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

How to sort a List<Object> alphabetically using Object name field

Have a look at Collections.sort() and the Comparator interface.

String comparison can be done with object1.getName().compareTo(object2.getName()) or object2.getName().compareTo(object1.getName()) (depending on the sort direction you desire).

If you want the sort to be case agnostic, do object1.getName().toUpperCase().compareTo(object2.getName().toUpperCase()).

How to handle back button in activity

This is a simple way of doing something.

    @Override
        public void onBackPressed() {
            // do what you want to do when the "back" button is pressed.
            startActivity(new Intent(Activity.this, MainActivity.class));
            finish();
        }

I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.

How do I find all files containing specific text on Linux?

All previous answers suggest grep and find. But there is another way: Use Midnight Commander

It is a free utility (30 years old, proven by time) which is visual without being GUI. It has tons of functions, and finding files is just one of them.

How to convert float to int with Java

As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.

Not dependent on Java Math.round() types

Select from where field not equal to Mysql Php

The key is the sql query, which you will set up as a string:

$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";

Note that there are a lot of ways to specify NOT. Another one that works just as well is:

$sqlquery = "SELECT field1, field2 FROM table WHERE columnA != 'x' AND columbB != 'y'";

Here is a full example of how to use it:

$link = mysql_connect($dbHost,$dbUser,$dbPass) or die("Unable to connect to database");
mysql_select_db("$dbName") or die("Unable to select database $dbName");
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
$result=mysql_query($sqlquery);

while ($row = mysql_fetch_assoc($result) {
//do stuff
}

You can do whatever you would like within the above while loop. Access each field of the table as an element of the $row array which means that $row['field1'] will give you the value for field1 on the current row, and $row['field2'] will give you the value for field2.

Note that if the column(s) could have NULL values, those will not be found using either of the above syntaxes. You will need to add clauses to include NULL values:

$sqlquery = "SELECT field1, field2 FROM table WHERE (NOT columnA = 'x' OR columnA IS NULL) AND (NOT columbB = 'y' OR columnB IS NULL)";

How to generate a random number in C++?

This code produces random numbers from n to m.

int random(int from, int to){
    return rand() % (to - from + 1) + from;
}

example:

int main(){
    srand(time(0));
    cout << random(0, 99) << "\n";
}

SQL Server command line backup statement

Here's an example you can run as a batch script (copy-paste into a .bat file), using the SQLCMD utility in Sql Server client tools:

BACKUP:

echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:

:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%DATE:~-4%.%DATE:~7,2%.%DATE:~4,2%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=your server name here
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause

RESTORE:

echo off
cls
echo -- RESTORE DATABASE --
set /p BACKUPFILENAME=Enter backup file name:%CD%\
set /p DATABASENAME=Enter database name:
set SERVERNAME=your server name here
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"

:: WARNING - delete the database, suits me
:: sqlcmd -E -S %SERVERNAME% -d master -Q "IF EXISTS (SELECT * FROM sysdatabases WHERE name=N'%DATABASENAME%' ) DROP DATABASE [%DATABASENAME%]"
:: sqlcmd -E -S %SERVERNAME% -d master -Q "CREATE DATABASE [%DATABASENAME%]"

:: restore
sqlcmd -E -S %SERVERNAME% -d master -Q "RESTORE DATABASE [%DATABASENAME%] FROM DISK = N'%CD%\%BACKUPFILENAME%' WITH REPLACE"

:: remap user/login (http://msdn.microsoft.com/en-us/library/ms174378.aspx)
sqlcmd -E -S %SERVERNAME% -d %DATABASENAME% -Q "sp_change_users_login 'Update_One', 'login-name', 'user-name'"
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET MULTI_USER"
echo.
pause

SQL Server : fetching records between two dates?

The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <)

select * 
from xxx 
where dates >= '20121026'
  and dates <  '20121028'

If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.

select * 
from xxx 
where CAST(dates as DATE) between '20121026' and '20121027'

This explicitly tells SQL Server that you are only interested in the DATE portion of the dates column for comparison against the BETWEEN range.

Integer ASCII value to character in BASH using printf

One option is to directly input the character you're interested in using hex or octal notation:

printf "\x41\n"
printf "\101\n"

How to change the background color of the options menu?

Just ran into this issue too, on an App that had to be compatible with Gingerbread and still retain as much of the styling from Holo-enabled devices as possible.

I found a relatively clean solution, that worked OK for me.

In the theme I use a 9-patch drawable background to get a custom background color:

<style name="Theme.Styled" parent="Theme.Sherlock">
   ...
   <item name="android:panelFullBackground">@drawable/menu_hardkey_panel</item>
</style>

I gave up trying to style the text color, and just used a Spannable to set the text color for my item in code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   MenuInflater inflater = getSupportMenuInflater();
   inflater.inflate(R.menu.actions_main, menu);

   if (android.os.Build.VERSION.SDK_INT < 
        android.os.Build.VERSION_CODES.HONEYCOMB) {

        SpannableStringBuilder text = new SpannableStringBuilder();
        text.append(getString(R.string.action_text));
        text.setSpan(new ForegroundColorSpan(Color.WHITE), 
                0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        MenuItem item1 = menu.findItem(R.id.action_item1);
        item1.setTitle(text);
   }

   return true;
}

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

FLAG_ACTIVITY_NEW_TASK is the problem here which initiates a new task .Just remove it & you are done.

Well I recommend you to read what every Flag does before working with them

Read this & Intent Flags here

The calling thread cannot access this object because a different thread owns it

This works for me.

new Thread(() =>
        {

        Thread.CurrentThread.IsBackground = false;
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate {

          //Your Code here.

        }, null);
        }).Start();

Is there a difference between `continue` and `pass` in a for loop in python?

In those examples, no. If the statement is not the very last in the loop then they have very different effects.

MongoDB via Mongoose JS - What is findByID?

I'm the maintainer of Mongoose. findById() is a built-in method on Mongoose models. findById(id) is equivalent to findOne({ _id: id }), with one caveat: findById() with 0 params is equivalent to findOne({ _id: null }).

You can read more about findById() on the Mongoose docs and this findById() tutorial.

Check if list<t> contains any of another list

If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

var items = (from x in parameters
                join y in myStrings on x.Source equals y
                select x)
            .ToList();

How to run TypeScript files from command line?

  1. Install ts-node node module globally.
  2. Create node runtime configuration (for IDE) or use node in command line to run below file js file (The path is for windows, but you can do it for linux as well) ~\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js
  3. Give your ts file path as a command line argument.
  4. Run Or Debug as you like.

How can I change or remove HTML5 form validation default error messages?

To set custom error message for HTML 5 validation use,

oninvalid="this.setCustomValidity('Your custom message goes here.')"

and to remove this message when user enters valid data use,

onkeyup="setCustomValidity('')"

Hope this works for you. Enjoy ;)

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

Get text of the selected option with jQuery

Close, you can use

$('#select_2 option:selected').html()

How do I remove all HTML tags from a string without knowing which tags are in it?

You can parse the string using Html Agility pack and get the InnerText.

    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)");
    string result = htmlDoc.DocumentNode.InnerText;

How do I get hour and minutes from NSDate?

Swift 2.0

    let dateNow = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
    let minute = calendar.component(NSCalendarUnit.Minute, fromDate: dateNow)
    print(String(hour))
    print(String(minute))

Please do take note of the cast to String in the print statement, you can easily assign that value to variables, like this:

var hoursString = String(hour)
var minutesString = String(minute)

Then you can concatenate values like this:

var compoundString = "\(hour):\(minute)"
print(compoundString)

How to pass command line argument to gnuplot?

You could even do some shell magic, e.g. like this:

#!/bin/bash
inputfile="${1}" #you could even do some getopt magic here...

################################################################################
## generate a gnuplotscript, strip off bash header
gnuplotscript=$(mktemp /tmp/gnuplot_cmd_$(basename "${0}").XXXXXX.gnuplot)

firstline=$(grep -m 1 -n "^#!/usr/bin/gnuplot" "${0}")
firstline=${firstline%%:*} #remove everything after the colon
sed -e "1,${firstline}d" < "${0}" > "${gnuplotscript}"


################################################################################
## run gnuplot
/usr/bin/gnuplot -e "inputfile=\"${inputfile}\"" "${gnuplotscript}"
status=$?
if [[ ${status} -ne 0 ]] ; then
  echo "ERROR: gnuplot returned with exit status $?"
fi

################################################################################
## cleanup and exit
rm -f "${gnuplotscript}"
exit ${status}

#!/usr/bin/gnuplot
plot inputfile using 1:4 with linespoints
#... or whatever you want

My implementation is a bit more complex (e.g. replacing some magic tokens in the sed call, while I am already at it...), but I simplified this example for better understanding. You could also make it even simpler.... YMMV.

FFmpeg: How to split video efficiently?

Here is a perfect way to split the video. I have done it previously, and it's working well for me.

ffmpeg -i C:\xampp\htdocs\videoCutting\movie.mp4 -ss 00:00:00 -t 00:00:05 -async 1 C:\xampp\htdocs\videoCutting\SampleVideoNew.mp4 (For cmd). shell_exec('ffmpeg -i C:\xampp\htdocs\videoCutting\movie.mp4 -ss 00:00:00 -t 00:00:05 -async 1 C:\xampp\htdocs\videoCutting\SampleVideoNew.mp4') (for php).

Please follow this and I am sure it will work perfectly.

How to fix git error: RPC failed; curl 56 GnuTLS

Reinstalling git will solve the problem.

sudo apt-get remove git
sudo apt-get update
sudo apt-get install git

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

How do I negate a test with regular expressions in a bash script?

You can also put the exclamation mark inside the brackets:

if [[ ! $PATH =~ $temp ]]

but you should anchor your pattern to reduce false positives:

temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]

which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.

Downloading video from YouTube

I've written a library that is up-to-date, since all the other answers are outdated:

https://github.com/flagbug/YoutubeExtractor

How to unset (remove) a collection element after fetching it?

Laravel Collection implements the PHP ArrayAccess interface (which is why using foreach is possible in the first place).

If you have the key already you can just use PHP unset.

I prefer this, because it clearly modifies the collection in place, and is easy to remember.

foreach ($collection as $key => $value) {
    unset($collection[$key]);
}

Argparse: Required arguments listed under "optional arguments"?

Building off of @Karl Rosaen

parser = argparse.ArgumentParser()
optional = parser._action_groups.pop() # Edited this line
required = parser.add_argument_group('required arguments')
# remove this line: optional = parser...
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
parser._action_groups.append(optional) # added this line
return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

Convert bytes to bits in python

Here how to do it using format()

print "bin_signedDate : ", ''.join(format(x, '08b') for x in bytevector)

It is important the 08b . That means it will be a maximum of 8 leading zeros be appended to complete a byte. If you don't specify this then the format will just have a variable bit length for each converted byte.

How do I convert seconds to hours, minutes and seconds?

This is how I got it.

def sec2time(sec, n_msec=3):
    ''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
    if hasattr(sec,'__len__'):
        return [sec2time(s) for s in sec]
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    if n_msec > 0:
        pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
    else:
        pattern = r'%02d:%02d:%02d'
    if d == 0:
        return pattern % (h, m, s)
    return ('%d days, ' + pattern) % (d, h, m, s)

Some examples:

$ sec2time(10, 3)
Out: '00:00:10.000'

$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'

$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'

$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']

Python: print a generator expression?

Or you can always map over an iterator, without the need to build an intermediate list:

>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM

Best practice for using assert?

Is there a performance issue?

  • Please remember to "make it work first before you make it work fast".
    Very few percent of any program are usually relevant for its speed. You can always kick out or simplify an assert if it ever proves to be a performance problem -- and most of them never will.

  • Be pragmatic:
    Assume you have a method that processes a non-empty list of tuples and the program logic will break if those tuples are not immutable. You should write:

    def mymethod(listOfTuples):
        assert(all(type(tp)==tuple for tp in listOfTuples))
    

    This is probably fine if your lists tend to be ten entries long, but it can become a problem if they have a million entries. But rather than discarding this valuable check entirely you could simply downgrade it to

    def mymethod(listOfTuples):
        assert(type(listOfTuples[0])==tuple)  # in fact _all_ must be tuples!
    

    which is cheap but will likely catch most of the actual program errors anyway.

How do I make a list of data frames?

I consider myself a complete newbie, but I think I have an extremely simple answer to one of the original subquestions that has not been stated here: accessing the data frames, or parts of it.

Let's start by creating the list with data frames as was stated above:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))

d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))

my.list <- list(d1, d2)

Then, if you want to access a specific value in one of the data frames, you can do so by using the double brackets sequentially. The first set gets you into the data frame, and the second set gets you to the specific coordinates:

my.list[[1]][[3,2]]

[1] 6

"use database_name" command in PostgreSQL

In pgAdmin you can also use

SET search_path TO your_db_name;

How do I integrate Ajax with Django applications?

Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started, so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking).

Django is server-side. It means, say a client goes to a URL, you have a function inside views that renders what he sees and returns a response in HTML. Let's break it up into examples:

views.py:

def hello(request):
    return HttpResponse('Hello World!')

def home(request):
    return render_to_response('index.html', {'variable': 'world'})

index.html:

<h1>Hello {{ variable }}, welcome to my awesome site</h1>

urls.py:

url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),

That's an example of the simplest of usages. Going to 127.0.0.1:8000/hello means a request to the hello() function, going to 127.0.0.1:8000/home will return the index.html and replace all the variables as asked (you probably know all this by now).

Now let's talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some URL, you get the same data you would get as a user going to that place.

For example, an AJAX call to 127.0.0.1:8000/hello will return the same thing it would as if you visited it. Only this time, you have it inside a JavaScript function and you can deal with it however you'd like. Let's look at a simple use case:

$.ajax({
    url: '127.0.0.1:8000/hello',
    type: 'get', // This is the default though, you don't actually need to always mention it
    success: function(data) {
        alert(data);
    },
    failure: function(data) { 
        alert('Got an error dude');
    }
}); 

The general process is this:

  1. The call goes to the URL 127.0.0.1:8000/hello as if you opened a new tab and did it yourself.
  2. If it succeeds (status code 200), do the function for success, which will alert the data received.
  3. If fails, do a different function.

Now what would happen here? You would get an alert with 'hello world' in it. What happens if you do an AJAX call to home? Same thing, you'll get an alert stating <h1>Hello world, welcome to my awesome site</h1>.

In other words - there's nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:

  1. Learn jQuery. I cannot stress this enough. You're gonna have to understand it a little to know how to handle the data you receive. You'll also need to understand some basic JavaScript syntax (not far from python, you'll get used to it). I strongly recommend Envato's video tutorials for jQuery, they are great and will put you on the right path.
  2. When to use JSON?. You're going to see a lot of examples where the data sent by the Django views is in JSON. I didn't go into detail on that, because it isn't important how to do it (there are plenty of explanations abound) and a lot more important when. And the answer to that is - JSON data is serialized data. That is, data you can manipulate. Like I mentioned, an AJAX call will fetch the response as if the user did it himself. Now say you don't want to mess with all the html, and instead want to send data (a list of objects perhaps). JSON is good for this, because it sends it as an object (JSON data looks like a python dictionary), and then you can iterate over it or do something else that removes the need to sift through useless html.
  3. Add it last. When you build a web app and want to implement AJAX - do yourself a favor. First, build the entire app completely devoid of any AJAX. See that everything is working. Then, and only then, start writing the AJAX calls. That's a good process that helps you learn a lot as well.
  4. Use chrome's developer tools. Since AJAX calls are done in the background it's sometimes very hard to debug them. You should use the chrome developer tools (or similar tools such as firebug) and console.log things to debug. I won't explain in detail, just google around and find out about it. It would be very helpful to you.
  5. CSRF awareness. Finally, remember that post requests in Django require the csrf_token. With AJAX calls, a lot of times you'd like to send data without refreshing the page. You'll probably face some trouble before you'd finally remember that - wait, you forgot to send the csrf_token. This is a known beginner roadblock in AJAX-Django integration, but after you learn how to make it play nice, it's easy as pie.

That's everything that comes to my head. It's a vast subject, but yeah, there's probably not enough examples out there. Just work your way there, slowly, you'll get it eventually.

ReferenceError: describe is not defined NodeJs

OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically

This is what injected describe and it into my tests.

mocha.ui('bdd').run(function (failures) {
    process.on('exit', function () {
      process.exit(failures);
    });
  });

I tried tdd like in the docs, but that didn't work, bdd worked though.

How to use a class from one C# project with another C# project

To provide another much simpler solution:-

  1. Within the project, right click and select "Add -> Existing"
  2. Navigate to the class file in the adjacent project.
  3. The Add button is also a dropdown, click the dropdown and select

"Add as link"

Thats it.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.

Solution

Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.

JSON find in JavaScript

General Solution

We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.

_x000D_
_x000D_
// const objectScan = require('object-scan');

const tool = (() => {
  const scanner = objectScan(['[*]'], {
    abort: true,
    rtn: 'bool',
    filterFn: ({
      value, parent, property, context
    }) => {
      if (value.id === context.id) {
        context.fn({ value, parent, property });
        return true;
      }
      return false;
    }
  });
  return {
    add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
    del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
    mod: (data, id, prop, v = undefined) => scanner(data, {
      id,
      fn: ({ value }) => {
        if (value !== undefined) {
          value[prop] = v;
        } else {
          delete value[prop];
        }
      }
    })
  };
})();

// -------------------------------

const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };

const exec = (fn) => {
  console.log('---------------');
  console.log(fn.toString());
  console.log(fn());
  console.log(data);
};

exec(() => tool.add(data, 'one', toAdd));
exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
exec(() => tool.mod(data, 'one', 'other', 'test'));
exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
exec(() => tool.mod(data, 'one', 'gone'));
exec(() => tool.del(data, 'three'));

// => ---------------
// => () => tool.add(data, 'one', toAdd)
// => true
// => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'pId', 'zzz')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'other', 'test')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone', 'delete me')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.del(data, 'three')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan

Where can I get Google developer key

Go to https://code.google.com/p/google-api-php-client/wiki/OAuth2

Scroll down to where it says 'Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.'

Click on the 'Google API Console' link.

When it pops up and says 'Welcome to the new Google Developers Console! Prefer the old console? Go back | Dismiss' Click on 'GO BACK'

How to enable explicit_defaults_for_timestamp?

For me it worked to add the phrase "explicit_defaults_for_timestamp = ON" without quotes into the config file my.ini.

Make sure you add this phrase right underneath the [mysqld] statement in the config file.

You will find my.ini under C:\ProgramData\MySQL\MySQL Server 5.7 if you had conducted the default installation of MySQL.

maven "cannot find symbol" message unhelpful

SOLUTION: @Before building your component (using mvn clean install). Build the entire project once and build your component again

WHY SO :
I get this error many times. Most of the times I will try to build my component alone (As I have not made changes elsewhere).

Right, But that extra jar which has been downloaded recently might have affected by changes done by a third party(inside their component). Making a full mvn clean install on entire project saved me many times

INFO: No Spring WebApplicationInitializer types detected on classpath

I also had the same problem. My maven had tomcat7 plugin but the JRE environment was 1.6. I changed my tomcat7 to tomcat6 and the error was gone.

What version of javac built my jar?

You can tell the Java binary version by inspecting the first 8 bytes (or using an app that can).

The compiler itself doesn't, to the best of my knowledge, insert any identifying signature. I can't spot such a thing in the file VM spec class format anyway.

DLL and LIB files - what and why?

There are static libraries (LIB) and dynamic libraries (DLL) - but note that .LIB files can be either static libraries (containing object files) or import libraries (containing symbols to allow the linker to link to a DLL).

Libraries are used because you may have code that you want to use in many programs. For example if you write a function that counts the number of characters in a string, that function will be useful in lots of programs. Once you get that function working correctly you don't want to have to recompile the code every time you use it, so you put the executable code for that function in a library, and the linker can extract and insert the compiled code into your program. Static libraries are sometimes called 'archives' for this reason.

Dynamic libraries take this one step further. It seems wasteful to have multiple copies of the library functions taking up space in each of the programs. Why can't they all share one copy of the function? This is what dynamic libraries are for. Rather than building the library code into your program when it is compiled, it can be run by mapping it into your program as it is loaded into memory. Multiple programs running at the same time that use the same functions can all share one copy, saving memory. In fact, you can load dynamic libraries only as needed, depending on the path through your code. No point in having the printer routines taking up memory if you aren't doing any printing. On the other hand, this means you have to have a copy of the dynamic library installed on every machine your program runs on. This creates its own set of problems.

As an example, almost every program written in 'C' will need functions from a library called the 'C runtime library, though few programs will need all of the functions. The C runtime comes in both static and dynamic versions, so you can determine which version your program uses depending on particular needs.

How to update Android Studio automatically?

If you go to help>>check for updates it will tell you if there's an update.

You don't have to change from the stable channel. If you aren't offered an update and restart button, kindly close the window and try again. After about 4 or 5 checks like this, it will eventually show you update and restart button.

Why? because google.

running a command as a super user from a python script

Try giving the full path to apache2ctl.

What, exactly, is needed for "margin: 0 auto;" to work?

It's perhaps interesting that you do not have to specify width for a <button> element to make it work - just make sure it has display:block : http://jsfiddle.net/muhuyttr/

Enable binary mode while restoring a Database from an SQL dump

The file you are trying to import is a zip file. Unzip the file and then try to import again.

Reading a file line by line in Go

Another method is to use the io/ioutil and strings libraries to read the entire file's bytes, convert them into a string and split them using a "\n" (newline) character as the delimiter, for example:

import (
    "io/ioutil"
    "strings"
)

func main() {
    bytesRead, _ := ioutil.ReadFile("something.txt")
    file_content := string(bytesRead)
    lines := strings.Split(file_content, "\n")
}

Technically you're not reading the file line-by-line, however you are able to parse each line using this technique. This method is applicable to smaller files. If you're attempting to parse a massive file use one of the techniques that reads line-by-line.

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

How do you clear Apache Maven's cache?

I've had this same problem, and I wrote a one-liner in shell to do it.

rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
                       -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
                       -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*

I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:

#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
  -Dexpression=settings.localRepository \
  -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
  -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
  --batch-mode \
  | grep -vF '[INFO]')

rm -rf $REPOSITORY/*

Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.

It's a bit wieldy, but it's a decent way of doing business, IMO.

React Native version mismatch

It happens sometimes when you try to run without closing the node server, in which the previous app was running, so try restarting React.To do so, just run the following commands:

1. To kill current processes
killall node -9 

2. To Start React  Native
react-native start 

3. Then Run android
react-native run-android

How to read data From *.CSV file using javascript?

Don't split on commas -- it won't work for most CSV files, and this question has wayyyy too many views for the asker's kind of input data to apply to everyone. Parsing CSV is kind of scary since there's no truly official standard, and lots of delimited text writers don't consider edge cases.

This question is old, but I believe there's a better solution now that Papa Parse is available. It's a library I wrote, with help from contributors, that parses CSV text or files. It's the only JS library I know of that supports files gigabytes in size. It also handles malformed input gracefully.

1 GB file parsed in 1 minute: Parsed 1 GB file in 1 minute

(Update: With Papa Parse 4, the same file took only about 30 seconds in Firefox. Papa Parse 4 is now the fastest known CSV parser for the browser.)

Parsing text is very easy:

var data = Papa.parse(csvString);

Parsing files is also easy:

Papa.parse(file, {
    complete: function(results) {
        console.log(results);
    }
});

Streaming files is similar (here's an example that streams a remote file):

Papa.parse("http://example.com/bigfoo.csv", {
    download: true,
    step: function(row) {
        console.log("Row:", row.data);
    },
    complete: function() {
        console.log("All done!");
    }
});

If your web page locks up during parsing, Papa can use web workers to keep your web site reactive.

Papa can auto-detect delimiters and match values up with header columns, if a header row is present. It can also turn numeric values into actual number types. It appropriately parses line breaks and quotes and other weird situations, and even handles malformed input as robustly as possible. I've drawn on inspiration from existing libraries to make Papa, so props to other JS implementations.

How to get complete month name from DateTime

It should be just DateTime.ToString( "MMMM" )

You don't need all the extra Ms.

fetch in git doesn't get all branches

Had the same problem today setting up my repo from scratch. I tried everything, nothing worked except removing the origin and re-adding it back again.

git remote rm origin
git remote add origin [email protected]:web3coach/the-blockchain-bar-newsletter-edition.git

git fetch --all
// Ta daaa all branches fetched

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

This warning appears because no default script type is specified. Try adding the following directive to your HTML file:

<meta http-equiv="content-script-type" content="text/javascript">

You can read more about default scripting specifications here: http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.2.2.1

Passing arrays as url parameter

Easiest way would be to use the serialize function.

It serializes any variable for storage or transfer. You can read about it in the php manual - serialize

The variable can be restored by using unserialize

So in the passing to the URL you use:

$url = urlencode(serialize($array))

and to restore the variable you use

$var = unserialize(urldecode($_GET['array']))

Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.

Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.

SQL datetime format to date only

After perusing your previous questions I eventually determined you are probably on SQL Server 2005. For US format you would use style 101

select Subject, 
       CONVERT(varchar,DeliveryDate,101) as DeliveryDate
from Email_Administration 
where MerchantId =@MerchantID 

How Can I Override Style Info from a CSS Class in the Body of a Page?

you can test a color by writing the CSS inline like <div style="color:red";>...</div>

Reactjs - setting inline styles correctly

It's not immediately obvious from the documentation why the following does not work:

<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>

But when doing it entirely inline:

  • You need double curly brackets
  • You don't need to put your values in quotes
  • React will add some default if you omit "em"
  • Remember to camelCase style names that have dashes in CSS - e.g. font-size becomes fontSize:
  • class is className

The correct way looks like this:

<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>

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

other = s or "some default value"

Ok, it must be clarified how the or operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.

Note that the or operator does not return only True or False. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.

In this case, the expression x or y returns x if it is True or evaluates to true when converted to boolean. Otherwise, it returns y. For most cases, this will serve for the very same purpose of C?'s null-coalescing operator, but keep in mind:

42    or "something"    # returns 42
0     or "something"    # returns "something"
None  or "something"    # returns "something"
False or "something"    # returns "something"
""    or "something"    # returns "something"

If you use your variable s to hold something that is either a reference to the instance of a class or None (as long as your class does not define members __nonzero__() and __len__()), it is secure to use the same semantics as the null-coalescing operator.

In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None specifically (an error object, for example).

In some languages this behavior is referred to as the Elvis operator.

Change navbar color in Twitter Bootstrap

Just add an id to the HTML navbar, such as:

<nav id="navbar-yellow" class="navbar navbar-default navbar-fixed-top" role="navigation">

With this id you can style the navbar color, but also the links and dropdowns

Examples applied to different types of navbars

Black

Yellow

Darkblue

Red (Cherry)

Darkgreen

Here is the CSS

/*
 * Black navbar style
 */
#navbar-black.navbar-default { /* #3C3C3C - #222222 */
    font-size: 14px;
    background-color: rgba(34, 34, 34, 1);
    background: -webkit-linear-gradient(top, rgba(60, 60, 60, 1) 0%, rgba(34, 34, 34, 1) 100%);
    background: linear-gradient(to bottom, rgba(60, 60, 60, 1) 0%, rgba(34, 34, 34, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-black.navbar-default .navbar-nav>li>a:hover,
#navbar-black.navbar-default .navbar-nav>li>a:focus,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-black.navbar-default .navbar-nav>.active>a,
#navbar-black.navbar-default .navbar-nav>.active>a:hover,
#navbar-black.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(255, 255, 255, 1);
    background-color: rgba(0, 0, 0, 1);
    background: -webkit-linear-gradient(top, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 1) 100%);
}
#sidebar-black, #column-black {
      background-color: #222222;
}
#navbar-black.navbar-default .navbar-toggle {
    border-color: #222222;
}
#navbar-black.navbar-default .navbar-toggle:hover,
#navbar-black.navbar-default .navbar-toggle:focus {
    background-color: #3C3C3C;
}
#navbar-black.navbar-default .navbar-nav>li>a,
#navbar-black.navbar-default .navbar-nav>li>ul>li>a,
#navbar-black.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-black.navbar-default .navbar-toggle .icon-bar,
#navbar-black.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-black.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

/*
 * Red navbar style
 */
#navbar-red.navbar-default { /* #990033 - #cc0033 */
    font-size: 14px;
    background-color: rgba(153, 0, 51, 1);
    background: -webkit-linear-gradient(top, rgba(204, 0, 51, 1) 0%, rgba(153, 0, 51, 1) 100%);
    background: linear-gradient(to bottom, rgba(204, 0, 51, 1) 0%, rgba(153, 0, 51, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-red.navbar-default .navbar-nav>li>a:hover,
#navbar-red.navbar-default .navbar-nav>li>a:focus,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-red.navbar-default .navbar-nav>.active>a,
#navbar-red.navbar-default .navbar-nav>.active>a:hover,
#navbar-red.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
}
#sidebar-red, #column-red {
      background-color: #990033;
}
#navbar-red.navbar-default .navbar-toggle {
    border-color: #990033;
}
#navbar-red.navbar-default .navbar-toggle:hover,
#navbar-red.navbar-default .navbar-toggle:focus {
    background-color: #cc0033;
}
#navbar-red.navbar-default .navbar-nav>li>a,
#navbar-red.navbar-default .navbar-nav>li>ul>li>a,
#navbar-red.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-red.navbar-default .navbar-toggle .icon-bar,
#navbar-red.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-red.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

/*
 * Darkblue navbar style
 */
#navbar-darkblue.navbar-default { /* #003399 - #0033cc */
    font-size: 14px;
    background-color: rgba(51, 51, 153, 1);
    background: -webkit-linear-gradient(top, rgba(51, 51, 204, 1) 0%, rgba(51, 51, 153, 1) 100%);
    background: linear-gradient(to bottom, rgba(51, 51, 204, 1) 0%, rgba(51, 51, 153, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-darkblue.navbar-default .navbar-nav>li>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>li>a:focus,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-darkblue.navbar-default .navbar-nav>.active>a,
#navbar-darkblue.navbar-default .navbar-nav>.active>a:hover,
#navbar-darkblue.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
}
#sidebar-darkblue, #column-darkblue {
    background-color: #333399;
}
#navbar-darkblue.navbar-default .navbar-toggle {
    border-color: #333399;
}
#navbar-darkblue.navbar-default .navbar-toggle:hover,
#navbar-darkblue.navbar-default .navbar-toggle:focus {
    background-color: #3333cc;
}
#navbar-darkblue.navbar-default .navbar-nav>li>a,
#navbar-darkblue.navbar-default .navbar-nav>li>ul>li>a,
#navbar-darkblue.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-darkblue.navbar-default .navbar-toggle .icon-bar,
#navbar-darkblue.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-darkblue.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

/*
 * Darkgreen navbar style
 */
#navbar-darkgreen.navbar-default { /* #006633 - #009933 */
    font-size: 14px;
    background-color: rgba(0, 102, 51, 1);
    background: -webkit-linear-gradient(top, rgba(0, 153, 51, 1) 0%, rgba(0, 102, 51, 1) 100%);
    background: linear-gradient(to bottom, rgba(0, 153, 51, 1) 0%, rgba(0, 102, 51, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-darkgreen.navbar-default .navbar-nav>li>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>li>a:focus,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a:hover,
#navbar-darkgreen.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
}
#sidebar-darkgreen, #column-darkgreen {
    background-color: #006633;
}
#navbar-darkgreen.navbar-default .navbar-toggle {
    border-color: #006633;
}
#navbar-darkgreen.navbar-default .navbar-toggle:hover,
#navbar-darkgreen.navbar-default .navbar-toggle:focus {
    background-color: #009933;
}
#navbar-darkgreen.navbar-default .navbar-nav>li>a,
#navbar-darkgreen.navbar-default .navbar-nav>li>ul>li>a,
#navbar-darkgreen.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-darkgreen.navbar-default .navbar-toggle .icon-bar,
#navbar-darkgreen.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-darkgreen.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

/*
 * Yellow navbar style
 */
#navbar-yellow.navbar-default { /* #99ff00 - #ccff00 */
    font-size: 14px;
    background-color: rgba(153, 255, 0, 1);
    background: -webkit-linear-gradient(top, rgba(204, 255, 0, 1) 0%, rgba(153, 255, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(204, 255, 0, 1) 0%, rgba(153, 255, 0, 1) 100%);
    border: 0px;
    border-radius: 0;
}
#navbar-yellow.navbar-default .navbar-nav>li>a:hover,
#navbar-yellow.navbar-default .navbar-nav>li>a:focus,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a:hover,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a:focus,
#navbar-yellow.navbar-default .navbar-nav>.active>a,
#navbar-yellow.navbar-default .navbar-nav>.active>a:hover,
#navbar-yellow.navbar-default .navbar-nav>.active>a:focus {
    color: rgba(51, 51, 51, 1);
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
    background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 100%);
}
#sidebar-yellow, #column-yellow {
    background-color: #99ff00;
}
#navbar-yellow.navbar-default .navbar-toggle {
    border-color: #99ff00;
}
#navbar-yellow.navbar-default .navbar-toggle:hover,
#navbar-yellow.navbar-default .navbar-toggle:focus {
    background-color: #ccff00;
}
#navbar-yellow.navbar-default .navbar-nav>li>a,
#navbar-yellow.navbar-default .navbar-nav>li>ul>li>a,
#navbar-yellow.navbar-default .navbar-brand {
    color: #999999;
}
#navbar-yellow.navbar-default .navbar-toggle .icon-bar,
#navbar-yellow.navbar-default .navbar-toggle:hover .icon-bar,
#navbar-yellow.navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #ffffff;
}

How to automatically start a service when running a docker container?

First, there is a problem in your Dockerfile:

RUN service mysql restart && /tmp/setup.sh

Docker images do not save running processes. Therefore, your RUN command executes only during docker build phase and stops after the build is completed. Instead, you need to specify the command when the container is started using the CMD or ENTRYPOINT commands like below:

CMD mysql start

Secondly, the docker container needs a process (last command) to keep running, otherwise the container will exit/stop. Therefore, the normal service mysql start command cannot be used directly in the Dockerfile.

Solution

There are three typical ways to keep the process running:

  • Using service command and append non-end command after that like tail -F

    CMD service mysql start && tail -F /var/log/mysql/error.log
    

This is often preferred when you have a single service running as it makes the outputted log accessible to docker.

  • Or use foreground command to do this

    CMD /usr/bin/mysqld_safe
    

This works only if there is a script like mysqld_safe.

  • Or wrap your scripts into start.sh and put this in end

    CMD /start.sh
    

This is best if the command must perform a series of steps, again, /start.sh should stay running.

Note

For the beginner using supervisord is not recommended. Honestly, it is overkill. It is much better to use single service / single command for the container.

BTW: please check https://registry.hub.docker.com for existing mysql docker images for reference

Deleting a pointer in C++

There is a rule in C++, for every new there is a delete.

  1. Why won't the first case work? Seems the most straightforward use to use and delete a pointer? The error says the memory wasn't allocated but 'cout' returned an address.

new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:

myPointer = &myVar;

you say:

myPointer = The address of where the data in myVar is stored

  1. On the second example the error is not being triggered but doing a cout of the value of myPointer still returns a memory address?

It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.

  1. Does #3 really work? Seems to work to me, the pointer is no longer storing an address, is this the proper way to delete a pointer?

NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:

myPointer = NULL;

which equals:

myPointer = 0;

How to have a transparent ImageButton: Android

In your XML set Background attribute to any colour White(#FFFFFF) shade or Black(#000000) shade.if you want transparency just put 80 before the actual hash code.

#80000000   

The listener supports no services

you need to reconfigure your tnsnames.ora so that it can point to your hostname after that listener will be able to pick the new hostname. after which check the status of your listener lsnrctl status and start listener lsnrctl start then register your listener. Alter system register

Background thread with QThread in PyQt

Based on the Worker objects methods mentioned in other answers, I decided to see if I could expand on the solution to invoke more threads - in this case the optimal number the machine can run and spin up multiple workers with indeterminate completion times. To do this I still need to subclass QThread - but only to assign a thread number and to 'reimplement' the signals 'finished' and 'started' to include their thread number.

I've focused quite a bit on the signals between the main gui, the threads, and the workers.

Similarly, others answers have been a pains to point out not parenting the QThread but I don't think this is a real concern. However, my code also is careful to destroy the QThread objects.

However, I wasn't able to parent the worker objects so it seems desirable to send them the deleteLater() signal, either when the thread function is finished or the GUI is destroyed. I've had my own code hang for not doing this.

Another enhancement I felt was necessary was was reimplement the closeEvent of the GUI (QWidget) such that the threads would be instructed to quit and then the GUI would wait until all the threads were finished. When I played with some of the other answers to this question, I got QThread destroyed errors.

Perhaps it will be useful to others. I certainly found it a useful exercise. Perhaps others will know a better way for a thread to announce it identity.

#!/usr/bin/env python3
#coding:utf-8
# Author:   --<>
# Purpose:  To demonstrate creation of multiple threads and identify the receipt of thread results
# Created: 19/12/15

import sys


from PyQt4.QtCore import QThread, pyqtSlot, pyqtSignal
from PyQt4.QtGui import QApplication, QLabel, QWidget, QGridLayout

import sys
import worker

class Thread(QThread):
    #make new signals to be able to return an id for the thread
    startedx = pyqtSignal(int)
    finishedx = pyqtSignal(int)

    def __init__(self,i,parent=None):
        super().__init__(parent)
        self.idd = i

        self.started.connect(self.starttt)
        self.finished.connect(self.finisheddd)

    @pyqtSlot()
    def starttt(self):
        print('started signal from thread emitted')
        self.startedx.emit(self.idd) 

    @pyqtSlot()
    def finisheddd(self):
        print('finished signal from thread emitted')
        self.finishedx.emit(self.idd)

class Form(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

        self.worker={}
        self.threadx={}
        self.i=0
        i=0

        #Establish the maximum number of threads the machine can optimally handle
        #Generally relates to the number of processors

        self.threadtest = QThread(self)
        self.idealthreadcount = self.threadtest.idealThreadCount()

        print("This machine can handle {} threads optimally".format(self.idealthreadcount))

        while i <self.idealthreadcount:
            self.setupThread(i)
            i+=1

        i=0
        while i<self.idealthreadcount:
            self.startThread(i)
            i+=1

        print("Main Gui running in thread {}.".format(self.thread()))


    def setupThread(self,i):

        self.worker[i]= worker.Worker(i)  # no parent!
        #print("Worker object runningt in thread {} prior to movetothread".format(self.worker[i].thread()) )
        self.threadx[i] = Thread(i,parent=self)  #  if parent isn't specified then need to be careful to destroy thread 
        self.threadx[i].setObjectName("python thread{}"+str(i))
        #print("Thread object runningt in thread {} prior to movetothread".format(self.threadx[i].thread()) )
        self.threadx[i].startedx.connect(self.threadStarted)
        self.threadx[i].finishedx.connect(self.threadFinished)

        self.worker[i].finished.connect(self.workerFinished)
        self.worker[i].intReady.connect(self.workerResultReady)

        #The next line is optional, you may want to start the threads again without having to create all the code again.
        self.worker[i].finished.connect(self.threadx[i].quit)

        self.threadx[i].started.connect(self.worker[i].procCounter)

        self.destroyed.connect(self.threadx[i].deleteLater)
        self.destroyed.connect(self.worker[i].deleteLater)

        #This is the key code that actually get the worker code onto another processor or thread.
        self.worker[i].moveToThread(self.threadx[i])

    def startThread(self,i):
        self.threadx[i].start()

    @pyqtSlot(int)
    def threadStarted(self,i):
        print('Thread {}  started'.format(i))
        print("Thread priority is {}".format(self.threadx[i].priority()))        


    @pyqtSlot(int)
    def threadFinished(self,i):
        print('Thread {} finished'.format(i))




    @pyqtSlot(int)
    def threadTerminated(self,i):
        print("Thread {} terminated".format(i))

    @pyqtSlot(int,int)
    def workerResultReady(self,j,i):
        print('Worker {} result returned'.format(i))
        if i ==0:
            self.label1.setText("{}".format(j))
        if i ==1:
            self.label2.setText("{}".format(j))
        if i ==2:
            self.label3.setText("{}".format(j))
        if i ==3:
            self.label4.setText("{}".format(j)) 

        #print('Thread {} has started'.format(self.threadx[i].currentThreadId()))    

    @pyqtSlot(int)
    def workerFinished(self,i):
        print('Worker {} finished'.format(i))

    def initUI(self):
        self.label1 = QLabel("0")
        self.label2= QLabel("0")
        self.label3= QLabel("0")
        self.label4 = QLabel("0")
        grid = QGridLayout(self)
        self.setLayout(grid)
        grid.addWidget(self.label1,0,0)
        grid.addWidget(self.label2,0,1) 
        grid.addWidget(self.label3,0,2) 
        grid.addWidget(self.label4,0,3) #Layout parents the self.labels

        self.move(300, 150)
        self.setGeometry(0,0,300,300)
        #self.size(300,300)
        self.setWindowTitle('thread test')
        self.show()

    def closeEvent(self, event):
        print('Closing')

        #this tells the threads to stop running
        i=0
        while i <self.idealthreadcount:
            self.threadx[i].quit()
            i+=1

         #this ensures window cannot be closed until the threads have finished.
        i=0
        while i <self.idealthreadcount:
            self.threadx[i].wait() 
            i+=1        


        event.accept()


if __name__=='__main__':
    app = QApplication(sys.argv)
    form = Form()
    sys.exit(app.exec_())

And the worker code below

#!/usr/bin/env python3
#coding:utf-8
# Author:   --<>
# Purpose:  Stack Overflow
# Created: 19/12/15

import sys
import unittest


from PyQt4.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time
import random


class Worker(QObject):
    finished = pyqtSignal(int)
    intReady = pyqtSignal(int,int)

    def __init__(self, i=0):
        '''__init__ is called while the worker is still in the Gui thread. Do not put slow or CPU intensive code in the __init__ method'''

        super().__init__()
        self.idd = i



    @pyqtSlot()
    def procCounter(self): # This slot takes no params
        for j in range(1, 10):
            random_time = random.weibullvariate(1,2)
            time.sleep(random_time)
            self.intReady.emit(j,self.idd)
            print('Worker {0} in thread {1}'.format(self.idd, self.thread().idd))

        self.finished.emit(self.idd)


if __name__=='__main__':
    unittest.main()

Hashing a dictionary?

EDIT: If all your keys are strings, then before continuing to read this answer, please see Jack O'Connor's significantly simpler (and faster) solution (which also works for hashing nested dictionaries).

Although an answer has been accepted, the title of the question is "Hashing a python dictionary", and the answer is incomplete as regards that title. (As regards the body of the question, the answer is complete.)

Nested Dictionaries

If one searches Stack Overflow for how to hash a dictionary, one might stumble upon this aptly titled question, and leave unsatisfied if one is attempting to hash multiply nested dictionaries. The answer above won't work in this case, and you'll have to implement some sort of recursive mechanism to retrieve the hash.

Here is one such mechanism:

import copy

def make_hash(o):

  """
  Makes a hash from a dictionary, list, tuple or set to any level, that contains
  only other hashable types (including any lists, tuples, sets, and
  dictionaries).
  """

  if isinstance(o, (set, tuple, list)):

    return tuple([make_hash(e) for e in o])    

  elif not isinstance(o, dict):

    return hash(o)

  new_o = copy.deepcopy(o)
  for k, v in new_o.items():
    new_o[k] = make_hash(v)

  return hash(tuple(frozenset(sorted(new_o.items()))))

Bonus: Hashing Objects and Classes

The hash() function works great when you hash classes or instances. However, here is one issue I found with hash, as regards objects:

class Foo(object): pass
foo = Foo()
print (hash(foo)) # 1209812346789
foo.a = 1
print (hash(foo)) # 1209812346789

The hash is the same, even after I've altered foo. This is because the identity of foo hasn't changed, so the hash is the same. If you want foo to hash differently depending on its current definition, the solution is to hash off whatever is actually changing. In this case, the __dict__ attribute:

class Foo(object): pass
foo = Foo()
print (make_hash(foo.__dict__)) # 1209812346789
foo.a = 1
print (make_hash(foo.__dict__)) # -78956430974785

Alas, when you attempt to do the same thing with the class itself:

print (make_hash(Foo.__dict__)) # TypeError: unhashable type: 'dict_proxy'

The class __dict__ property is not a normal dictionary:

print (type(Foo.__dict__)) # type <'dict_proxy'>

Here is a similar mechanism as previous that will handle classes appropriately:

import copy

DictProxyType = type(object.__dict__)

def make_hash(o):

  """
  Makes a hash from a dictionary, list, tuple or set to any level, that 
  contains only other hashable types (including any lists, tuples, sets, and
  dictionaries). In the case where other kinds of objects (like classes) need 
  to be hashed, pass in a collection of object attributes that are pertinent. 
  For example, a class can be hashed in this fashion:

    make_hash([cls.__dict__, cls.__name__])

  A function can be hashed like so:

    make_hash([fn.__dict__, fn.__code__])
  """

  if type(o) == DictProxyType:
    o2 = {}
    for k, v in o.items():
      if not k.startswith("__"):
        o2[k] = v
    o = o2  

  if isinstance(o, (set, tuple, list)):

    return tuple([make_hash(e) for e in o])    

  elif not isinstance(o, dict):

    return hash(o)

  new_o = copy.deepcopy(o)
  for k, v in new_o.items():
    new_o[k] = make_hash(v)

  return hash(tuple(frozenset(sorted(new_o.items()))))

You can use this to return a hash tuple of however many elements you'd like:

# -7666086133114527897
print (make_hash(func.__code__))

# (-7666086133114527897, 3527539)
print (make_hash([func.__code__, func.__dict__]))

# (-7666086133114527897, 3527539, -509551383349783210)
print (make_hash([func.__code__, func.__dict__, func.__name__]))

NOTE: all of the above code assumes Python 3.x. Did not test in earlier versions, although I assume make_hash() will work in, say, 2.7.2. As far as making the examples work, I do know that

func.__code__ 

should be replaced with

func.func_code

Synchronous request in Node.js

It seems solutions for this problem is never-ending, here's one more :)

// do it once.
sync(fs, 'readFile')

// now use it anywhere in both sync or async ways.
var data = fs.readFile(__filename, 'utf8')

http://alexeypetrushin.github.com/synchronize

How display only years in input Bootstrap Datepicker?

Try this

_x000D_
_x000D_
$("#datepicker").datepicker({_x000D_
    format: "yyyy",_x000D_
    viewMode: "years", _x000D_
    minViewMode: "years"_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<input type="text" id="datepicker" />
_x000D_
_x000D_
_x000D_

$("#datepicker").datepicker( {
    format: " yyyy", // Notice the Extra space at the beginning
    viewMode: "years", 
    minViewMode: "years"
});

Powershell Log Off Remote Session

Log off all users from a machine:

try {
   query user /server:$SERVER 2>&1 | select -skip 1 | foreach {
     logoff ($_ -split "\s+")[-6] /server:$SERVER
   }
}
catch {}

Details:

  • the try/catch is used when there are no users are on the server, and the query returns an error. however, you could drop the 2>&1 part, and remove the try/catch if you don't mind seeing the error string
  • select -skip 1 removes the header line
  • the inner foreach logs off each user
  • ($_ -split "\s+") splits the string to an array with just text items
  • [-6] index gets session ID and is the 6th string counting from the reverse of the array, you need to do this because the query output will have either 8 or 9 elements depending if the users connected or disconnected from the terminal session

Java Class.cast() vs. cast operator

It's always problematic and often misleading to try and translate constructs and concepts between languages. Casting is no exception. Particularly because Java is a dynamic language and C++ is somewhat different.

All casting in Java, no matter how you do it, is done at runtime. Type information is held at runtime. C++ is a bit more of a mix. You can cast a struct in C++ to another and it's merely a reinterpretation of the bytes that represent those structs. Java doesn't work that way.

Also generics in Java and C++ are vastly different. Don't concern yourself overly with how you do C++ things in Java. You need to learn how to do things the Java way.

Text inset for UITextField?

A good approach to add padding to UITextField is to subclass UITextField and add an edgeInsets property. You then set the edgeInsets and the UITextField will be drawn accordingly. This will also function correctly with a custom leftView or rightView set.

OSTextField.h

#import <UIKit/UIKit.h>

@interface OSTextField : UITextField

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end

OSTextField.m

#import "OSTextField.h"

@implementation OSTextField

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if(self){
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

- (CGRect)textRectForBounds:(CGRect)bounds {
    return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}

@end

In Linux, how to tell how much memory processes are using?

Use

  • ps u `pidof $TASKS_LIST` or ps u -C $TASK
  • ps xu --sort %mem
  • ps h -o pmem -C $TASK

Example:

ps-of()
{
 ps u `pidof "$@"`
}

$ ps-of firefox
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
const    18464  5.9  9.4 1190224 372496 ?      Sl   11:28   0:33 /usr/lib/firefox/firefox

$ alias ps-mem="ps xu --sort %mem | sed -e :a -e '1p;\$q;N;6,\$D;ba'"
$ ps-mem 
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
const     3656  0.0  0.4 565728 18648 ?        Sl   Nov21   0:56 /usr/bin/python /usr/lib/ubuntuone-client/ubuntuone-syncdaemon
const    11361  0.3  0.5 1054156 20372 ?       Sl   Nov25  43:50 /usr/bin/python /usr/bin/ubuntuone-control-panel-qt
const     3402  0.0  0.5 1415848 23328 ?       Sl   Nov21   1:16 nautilus -n
const     3577  2.3  2.0 1534020 79844 ?       Sl   Nov21 410:02 konsole
const    18464  6.6 12.7 1317832 501580 ?      Sl   11:28   1:34 /usr/lib/firefox/firefox

$ ps h -o pmem -C firefox
12.7

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

A simple way is set android:usesCleartextTraffic="true" on you AndroidManifest.xml

android:usesCleartextTraffic="true"

Your AndroidManifest.xml look like

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.dww.drmanar">
   <application
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:usesCleartextTraffic="true"
       android:theme="@style/AppTheme"
       tools:targetApi="m">
       <activity
            android:name=".activity.SplashActivity"
            android:theme="@style/FullscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
       </activity>
    </application>
</manifest>

I hope this will help you.

How to change the commit author for one specific commit?

Changing Your Committer Name & Email Globally:

$ git config --global user.name "John Doe"
$ git config --global user.email "[email protected]"

Changing Your Committer Name & Email per Repository:

$ git config user.name "John Doe"
$ git config user.email "[email protected]"

Changing the Author Information Just for the Next Commit:

$ git commit --author="John Doe <[email protected]>"

Hint: For other situation and read more information read the post reference.

Javascript can't find element by id?

Run the code either in onload event, either just before you close body tag. You try to find an element wich is not there at the moment you do it.

How to get CRON to call in the correct PATHs

The simplest workaround I've found looks like this:

* * * * * root su -l -c command

This example invokes su as root user and starts the shell with the user's full environment, including $PATH, set as if they were logged in. It works the same on different distros, is more reliable than sourcing .bashrc (which hasn't worked for me) and avoids hardcoding specific paths which can be a problem if you're providing an example or setup tool and don't know what distro or file layout on the user's system.

You can also specify the username after su if you want a different user than root, but you should probably leave the root parameter before su command since this ensures su has sufficient privileges to switch to any user you specify.

Adding days to a date in Python

This might help:

from datetime import date, timedelta
date1 = date(2011, 10, 10)
date2 = date + timedelta(days=5)
print (date2)

scp or sftp copy multiple files with single command

Copy multiple files from remote to local:

$ scp [email protected]:/some/remote/directory/\{a,b,c\} ./

Copy multiple files from local to remote:

$ scp foo.txt bar.txt [email protected]:~
$ scp {foo,bar}.txt [email protected]:~
$ scp *.txt [email protected]:~

Copy multiple files from remote to remote:

$ scp [email protected]:/some/remote/directory/foobar.txt \
[email protected]:/some/remote/directory/

Source: http://www.hypexr.org/linux_scp_help.php

CSS div element - how to show horizontal scroll bars only?

Use the following

<div style="max-width:980px; overflow-x: scroll; white-space: nowrap;">
<table border="1" style="cellpadding:0; cellspacing:0; border:0; width=:100%;" >

How to convert a selection to lowercase or uppercase in Sublime Text

From the Sublime Text docs for Windows/Linux:

Keypress            Command
Ctrl + K, Ctrl + U  Transform to Uppercase
Ctrl + K, Ctrl + L  Transform to Lowercase

and for Mac:

Keypress    Command
cmd + KU    Transform to Uppercase
cmd + KL    Transform to Lowercase

Also note that Ctrl + Shift + p in Windows (? + Shift + p in a Mac) brings up the Command Palette where you can search for these and other commands. It looks like this:

enter image description here

Import Python Script Into Another?

It depends on how the code in the first file is structured.

If it's just a bunch of functions, like:

# first.py
def foo(): print("foo")
def bar(): print("bar")

Then you could import it and use the functions as follows:

# second.py
import first

first.foo()    # prints "foo"
first.bar()    # prints "bar"

or

# second.py
from first import foo, bar

foo()          # prints "foo"
bar()          # prints "bar"

or, to import all the names defined in first.py:

# second.py
from first import *

foo()          # prints "foo"
bar()          # prints "bar"

Note: This assumes the two files are in the same directory.

It gets a bit more complicated when you want to import names (functions, classes, etc) from modules in other directories or packages.

Python 3.1.1 string to hex

binascii methodes are easier by the way

>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'

Hope it helps. :)

Spring Boot: How can I set the logging level with application.properties?

The proper way to set the root logging level is using the property logging.level.root. See documentation, which has been updated since this question was originally asked.

Example:

logging.level.root=WARN

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

How to subtract a day from a date?

Just to Elaborate an alternate method and a Use case for which it is helpful:

  • Subtract 1 day from current datetime:
from datetime import datetime, timedelta
print datetime.now() + timedelta(days=-1)  # Here, I am adding a negative timedelta
  • Useful in the Case, If you want to add 5 days and subtract 5 hours from current datetime. i.e. What is the Datetime 5 days from now but 5 hours less ?
from datetime import datetime, timedelta
print datetime.now() + timedelta(days=5, hours=-5)

It can similarly be used with other parameters e.g. seconds, weeks etc

How to vertically center content with variable height within a div?

Just add

position: relative;
top: 50%;
transform: translateY(-50%);

to the inner div.

What it does is moving the inner div's top border to the half height of the outer div (top: 50%;) and then the inner div up by half its height (transform: translateY(-50%)). This will work with position: absolute or relative.

Keep in mind that transform and translate have vendor prefixes which are not included for simplicity.

Codepen: http://codepen.io/anon/pen/ZYprdb

How to remove focus around buttons on click

Can't believe nobody has posted this yet.

Use a label instead of a button.

<label type="button" class="btn btn-primary btn-block">
<span class="icon-plus"></span> Add Page
</label>

Fiddle

Visual C++ executable and missing MSVCR100d.dll

I got the same error.

I was refering a VS2010 DLL in a VS2012 project.

Just recompiled the DLL on VS2012 and now everything is fine.

Javascript/jQuery detect if input is focused

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');

Changing fonts in ggplot2

To change the font globally for ggplot2 plots.

theme_set(theme_gray(base_size = 20, base_family = 'Font Name' ))

How do JavaScript closures work?

Let's start from here, As defined on MDN: Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created.

Lexical scoping
Consider the following:

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function    
  }
  displayName();    
}
init();

init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is only available within the body of the init() function. The displayName() function has no local variables of its own. However, because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

function init() {
    var name = "Mozilla"; // name is a local variable created by init
    function displayName() { // displayName() is the inner function, a closure
        alert (name); // displayName() uses variable declared in the parent function    
    }
    displayName();    
}
init();

Run the code and notice that the alert() statement within the displayName() function successfully displays the value of the name variable, which is declared in its parent function. This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.

Closure
Now consider the following example:

function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

Running this code has exactly the same effect as the previous example of the init() function above: this time, the string "Mozilla" will be displayed in a JavaScript alert box. What's different — and interesting — is that the displayName() inner function is returned from the outer function before being executed.

At first glance, it may seem unintuitive that this code still works. In some programming languages, the local variables within a function exist only for the duration of that function's execution. Once makeFunc() has finished executing, you might expect that the name variable would no longer be accessible. However, because the code still works as expected, this is obviously not the case in JavaScript.

The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created. In this case, myFunc is a reference to the instance of the function displayName created when makeFunc is run. The instance of displayName maintains a reference to its lexical environment, within which the variable name exists. For this reason, when myFunc is invoked, the variable name remains available for use and "Mozilla" is passed to alert.

Here's a slightly more interesting example — a makeAdder function:

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

In this example, we have defined a function makeAdder(x), which takes a single argument, x, and returns a new function. The function it returns takes a single argument, y, and returns the sum of x and y.

In essence, makeAdder is a function factory — it creates functions which can add a specific value to their argument. In the above example we use our function factory to create two new functions — one that adds 5 to its argument, and one that adds 10.

add5 and add10 are both closures. They share the same function body definition, but store different lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.

Practical closures

Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.

Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.

For instance, suppose we wish to add some buttons to a page that adjust the text size. One way of doing this is to specify the font-size of the body element in pixels, then set the size of the other elements on the page (such as headers) using the relative em unit:

body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}

h1 {
  font-size: 1.5em;
}

h2 {
  font-size: 1.2em;
}

Our interactive text size buttons can change the font-size property of the body element, and the adjustments will be picked up by other elements on the page thanks to the relative units. Here's the JavaScript:

function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

size12, size14, and size16 are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

<a href="#" id="size-12">12</a>
<a href="#" id="size-14">14</a>
<a href="#" id="size-16">16</a>


function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

for reading more about closures, visit the link on MDN

What are the specific differences between .msi and setup.exe file?

.msi files are windows installer files without the windows installer runtime, setup.exe can be any executable programm (probably one that installs stuff on your computer)

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

Looping through all rows in a table column, Excel-VBA

If this is in fact a ListObject table (Insert Table from the ribbon) then you can use the table's .DataBodyRange object to get the number of rows and columns. This ignores the header row.

Sub TableTest()

Dim tbl As ListObject
Dim tRows As Long
Dim tCols As Long

Set tbl = ActiveSheet.ListObjects("Table1")  '## modify to your table name.

With tbl.DataBodyRange
    tRows = .Rows.Count
    tCols = .Columns.Count
End With

MsgBox tbl.Name & " contains " & tRows & " rows and " & tCols & " columns.", vbInformation

End Sub

If you need to use the header row, instead of using tbl.DataBodyRange just use tbl.Range.

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

open read and close a file in 1 line of code

with open('pagehead.section.htm')as f:contents=f.read()

Raw SQL Query without DbSet - Entity Framework Core

Add Nuget package - Microsoft.EntityFrameworkCore.Relational

using Microsoft.EntityFrameworkCore;
...
await YourContext.Database.ExecuteSqlCommandAsync("... @p0, @p1", param1, param2 ..)

This will return the row numbers as an int

See - https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.executesqlcommand?view=efcore-3.0

How do you connect to multiple MySQL databases on a single webpage?

Instead of mysql_connect use mysqli_connect.

mysqli is provide a functionality for connect multiple database at a time.

$Db1 = new mysqli($hostname,$username,$password,$db_name1); 
// this is connection 1 for DB 1

$Db2 = new mysqli($hostname,$username,$password,$db_name2); 
// this is connection 2 for DB 2

Tomcat won't stop or restart

sudo systemctl stop tomcat

did it for me

How to determine a user's IP address in node

You can use request-ip, to retrieve a user's ip address. It handles quite a few of the different edge cases, some of which are mentioned in the other answers.

Disclosure: I created this module

Install:

npm install request-ip

In your app:

var requestIp = require('request-ip');

// inside middleware handler
var ipMiddleware = function(req, res, next) {
    var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
    next();
};

Hope this helps

When should I write the keyword 'inline' for a function/method?

  • When will the the compiler not know when to make a function/method 'inline'?

This depends on the compiler used. Do not blindly trust that nowadays compilers know better then humans how to inline and you should never use it for performance reasons, because it's linkage directive rather than optimization hint. While I agree that ideologically are these arguments correct encountering reality might be a different thing.

After reading multiple threads around I tried out of curiosity the effects of inline on the code I'm just working and the results were that I got measurable speedup for GCC and no speed up for Intel compiler.

(More detail: math simulations with few critical functions defined outside class, GCC 4.6.3 (g++ -O3), ICC 13.1.0 (icpc -O3); adding inline to critical points caused +6% speedup with GCC code).

So if you qualify GCC 4.6 as a modern compiler the result is that inline directive still matters if you write CPU intensive tasks and know where exactly is the bottleneck.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

What does "request for member '*******' in something not a structure or union" mean?

It may means that you forgot include a header file that define this struct/union. For example:

foo.h file:

typedef union
{
    struct
    {
        uint8_t FIFO_BYTES_AVAILABLE    : 4;
        uint8_t STATE                   : 3;
        uint8_t CHIP_RDY                : 1;
    };
    uint8_t status;
} RF_CHIP_STATUS_t;

RF_CHIP_STATUS_t getStatus();

main.c file:

.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the  #include "foo.h" */
.
.
.

What is the use of static constructors?

1.It can only access the static member(s) of the class.

Reason : Non static member is specific to the object instance. If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical.

2.There should be no parameter(s) in static constructor.

Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it. 3.Only one static constructor is allowed.

Reason: Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor.

4.There should be no access modifier to it.

Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it

HashMap allows duplicates?

m.put(null,null); // here key=null, value=null
m.put(null,a);    // here also key=null, and value=a

Duplicate keys are not allowed in hashmap.
However,value can be duplicated.

What is the default value for enum variable?

It is whatever member of the enumeration represents the value 0. Specifically, from the documentation:

The default value of an enum E is the value produced by the expression (E)0.

As an example, take the following enum:

enum E
{
    Foo, Bar, Baz, Quux
}

Without overriding the default values, printing default(E) returns Foo since it's the first-occurring element.

However, it is not always the case that 0 of an enum is represented by the first member. For example, if you do this:

enum F
{
    // Give each element a custom value
    Foo = 1, Bar = 2, Baz = 3, Quux = 0
}

Printing default(F) will give you Quux, not Foo.

If none of the elements in an enum G correspond to 0:

enum G
{
    Foo = 1, Bar = 2, Baz = 3, Quux = 4
}

default(G) returns literally 0, although its type remains as G (as quoted by the docs above, a cast to the given enum type).

Select query to remove non-numeric characters

To add on to Ken's answer, this handles commas and spaces and parentheses

--Handles parentheses, commas, spaces, hyphens..
declare @table table (c varchar(256))
insert into @table
values
('This is a test 111-222-3344'),
('Some Sample Text (111)-222-3344'),
('Hello there 111222 3344 / How are you?'),
('Hello there 111 222 3344 ? How are you?'),
('Hello there 111 222 3344. How are you?')

select
replace(LEFT(SUBSTRING(replace(replace(replace(replace(replace(c,'(',''),')',''),'-',''),' ',''),',',''), PATINDEX('%[0-9.-]%', replace(replace(replace(replace(replace(c,'(',''),')',''),'-',''),' ',''),',','')), 8000),
           PATINDEX('%[^0-9.-]%', SUBSTRING(replace(replace(replace(replace(replace(c,'(',''),')',''),'-',''),' ',''),',',''), PATINDEX('%[0-9.-]%', replace(replace(replace(replace(replace(c,'(',''),')',''),'-',''),' ',''),',','')), 8000) + 'X') -1),'.','')
from @table

How do I make a transparent canvas in html5?

Paint your two canvases onto a third canvas.

I had this same problem and none of the solutions here solved my problem. I had one opaque canvas with another transparent canvas above it. The opaque canvas was completely invisible but the background of the page body was visible. The drawings from the transparent canvas on top were visible while the opaque canvas below it was not.

Enum String Name from Value

You can convert the int back to an enumeration member with a simple cast, and then call ToString():

int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

Setting Icon for wpf application (VS 08)

Assuming you use VS Express and C#. The icon is set in the project properties page. To open it right click on the project name in the solution explorer. in the page that opens, there is an Application tab, in this tab you can set the icon.

How to get a web page's source code from Java

Try the following code with an added request property:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class SocketConnection
{
    public static String getURLSource(String url) throws IOException
    {
        URL urlObject = new URL(url);
        URLConnection urlConnection = urlObject.openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

        return toString(urlConnection.getInputStream());
    }

    private static String toString(InputStream inputStream) throws IOException
    {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
        {
            String inputLine;
            StringBuilder stringBuilder = new StringBuilder();
            while ((inputLine = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(inputLine);
            }

            return stringBuilder.toString();
        }
    }
}

How do I convert a PDF document to a preview image in PHP?

You can also get the page count using

$im->getNumberImages();

Then you can can create thumbs of all the pages using a loop, eg.

'file.pdf['.$x.']'

Bootstrap center heading

Just use "justify-content-center" in the row's class attribute.

<div class="container">
  <div class="row justify-content-center">
    <h1>This is a header</h1>
  </div>
</div>

Insert data to MySql DB and display if insertion is success or failure

$result = mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')"));
if($result)
{
echo "Success";

}
else
{
echo "Error";

}

How to compile a Perl script to a Windows executable with Strawberry Perl?

There are three packagers, and two compilers:

free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC

http://search.cpan.org/dist/B-C/perlcompile.pod

(Note: perlfaq3 is still wrong)

For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.