Programs & Examples On #Perlapp

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); 
  } 
} 

jQuery - selecting elements from inside a element

You can use find option to select an element inside another. For example, to find an element with id txtName in a particular div, you can use like

var name = $('#div1').find('#txtName').val();

How to run a maven created jar file using just the command line

I am not sure in your case. But as I know to run any jar file from cmd we can use following command:

Go up to the directory where your jar file is saved:

java -jar <jarfilename>.jar

But you can check following links. I hope it'll help you:

Run Netbeans maven project from command-line?

http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html

Creating a Shopping Cart using only HTML/JavaScript

I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)

I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.

You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm

You can try following approach:

//create array that will hold all ordered products
    var shoppingCart = [];

    //this function manipulates DOM and displays content of our shopping cart
    function displayShoppingCart(){
        var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
        //ensure we delete all previously added rows from ordered products table
        while(orderedProductsTblBody.rows.length>0) {
            orderedProductsTblBody.deleteRow(0);
        }

        //variable to hold total price of shopping cart
        var cart_total_price=0;
        //iterate over array of objects
        for(var product in shoppingCart){
            //add new row      
            var row=orderedProductsTblBody.insertRow();
            //create three cells for product properties 
            var cellName = row.insertCell(0);
            var cellDescription = row.insertCell(1);
            var cellPrice = row.insertCell(2);
            cellPrice.align="right";
            //fill cells with values from current product object of our array
            cellName.innerHTML = shoppingCart[product].Name;
            cellDescription.innerHTML = shoppingCart[product].Description;
            cellPrice.innerHTML = shoppingCart[product].Price;
            cart_total_price+=shoppingCart[product].Price;
        }
        //fill total cost of our shopping cart 
        document.getElementById("cart_total").innerHTML=cart_total_price;
    }


    function AddtoCart(name,description,price){
       //Below we create JavaScript Object that will hold three properties you have mentioned:    Name,Description and Price
       var singleProduct = {};
       //Fill the product object with data
       singleProduct.Name=name;
       singleProduct.Description=description;
       singleProduct.Price=price;
       //Add newly created product to our shopping cart 
       shoppingCart.push(singleProduct);
       //call display function to show on screen
       displayShoppingCart();

    }  


    //Add some products to our shopping cart via code or you can create a button with onclick event
    //AddtoCart("Table","Big red table",50);
    //AddtoCart("Door","Big yellow door",150);
    //AddtoCart("Car","Ferrari S23",150000);






<table cellpadding="4" cellspacing="4" border="1">
    <tr>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="0">
                <thead>
                    <tr>
                        <td colspan="2">
                            Products for sale
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Table
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Door
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Car
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
                        </td>
                    </tr>
                </tbody>

            </table>
        </td>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
                <thead>
                    <tr>
                        <td>
                            Name
                        </td>
                        <td>
                            Description
                        </td>
                        <td>
                            Price
                        </td>
                    </tr>
                </thead>
                <tbody id="orderedProductsTblBody">

                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" align="right" id="cart_total">

                        </td>
                    </tr>
                </tfoot>
            </table>
        </td>
    </tr>
</table>

Please have a look at following free client-side shopping cart:

SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.

Documentation

http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html

Hope you will find it useful.

How to execute a remote command over ssh with arguments?

I'm using the following to execute commands on the remote from my local computer:

ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2

How to print table using Javascript?

You can also use a jQuery plugin to do that

jQuery PrintPage plugin

Demo

Loaded nib but the 'view' outlet was not set

I had the same problem, but a different solution was called for. The problem in this case was the class of the File Owner was not connected to xib file.

Maximum execution time in phpMyadmin

Well for Wamp User,

Go to: wamp\apps\phpmyadmin3.3.9\libraries

Under line 536, locate $cfg['ExecTimeLimit'] = 0;

and change the value from 0 to 6000. e.g

$cfg['ExecTimeLimit'] = 0;

To

$cfg['ExecTimeLimit'] = 6000;

Restart wamp server and phew.

It works like magic !

Outputting data from unit test in Python

Admitting that I haven't tried it, the testfixtures' logging feature looks quite useful...

How to add a jar in External Libraries in android studio

Step 1: Download any JAR file for your Project.enter image description here

Step 2: Copy .jar file and past in libs folder.

enter image description here enter image description here

Step 3: Click on File > Project Structure >Select app > Dependencies

enter image description here

Step 4:

enter image description here

Step 5:

enter image description here

Step 6: After click Ok button then we can see the Dependencies add like this way:

enter image description here

How to write a Python module/package?

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py

create hello.py then write the following function as its content:

def helloworld():
   print "hello"

Then you can import hello:

>>> import hello
>>> hello.helloworld()
'hello'
>>>

To group many .py files put them in a folder. Any folder with an __init__.py is considered a module by python and you can call them a package

|-HelloModule
  |_ __init__.py
  |_ hellomodule.py

You can go about with the import statement on your module the usual way.

For more information, see 6.4. Packages.

sql delete statement where date is greater than 30 days

To delete records from a table that have a datetime value in Date_column older than 30 days use this query:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < GETDATE() - 30

...or this:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(dd,-30,GETDATE())

To delete records from a table that have a datetime value in Date_column older than 12 hours:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(hh,-12,GETDATE())

To delete records from a table that have a datetime value in Date_column older than 15 minutes:

USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(mi,-15,GETDATE())

From: http://zarez.net/?p=542

CSS border less than 1px

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

Failed to install Python Cryptography package with PIP and setup.py

Apparently on recent versions of OSX this may be caused by Apple shipping their own version of OpenSSL, which doesn't work with the cryptography library.

Recent versions of the cryptography library ship with their own native dependencies, but to get them you'll need to upgrade pip, and possibly also virtual env. So for me, the solution was:

pip install --upgrade --force-reinstall pip virtualenv

Uncaught TypeError: data.push is not a function

you can use push method only if the object is an array:

var data = new Array();
data.push({"country": "IN"}).

OR

data['country'] = "IN"

if it's just an object you can use

data.country = "IN";

How to check for null/empty/whitespace values with a single test?

Every single persons suggestion to run a query in Oracle to find records whose specific field is just blank, (this is not including (null) or any other field just a blank line) did not work. I tried every single suggested code. Guess I will keep searching online.

*****UPDATE*****

I tried this and it worked, not sure why it would not work if < 1 but for some reason < 2 worked and only returned records whose field is just blank

select [columnName] from [tableName] where LENGTH(columnName) < 2 ;

I am guessing whatever script that was used to convert data over has left something in the field even though it shows blank, that is my guess anyways as to why the < 2 works but not < 1

However, if you have any other values in that column field that is less than two characters then you might have to come up with another solution. If there are not a lot of other characters then you can single them out.

Hope my solution helps someone else out there some day.

How to return a table from a Stored Procedure?

In SQL Server 2008 you can use

http://www.sommarskog.se/share_data.html#tableparam

or else simple and same as common execution

CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS

SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
     JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID

SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO

I hopes its help to you

How to count items in JSON object using command line?

Just throwing another solution in the mix...

Try jq, a lightweight and flexible command-line JSON processor:

jq length /tmp/test.json

Prints the length of the array of objects.

Hiding a password in a python script (insecure obfuscation only)

If you are working on a Unix system, take advantage of the netrc module in the standard Python library. It reads passwords from a separate text file (.netrc), which has the format decribed here.

Here is a small usage example:

import netrc

# Define which host in the .netrc file to use
HOST = 'mailcluster.loopia.se'

# Read from the .netrc file in your home directory
secrets = netrc.netrc()
username, account, password = secrets.authenticators( HOST )

print username, password

python dict to numpy structured array

Even more simple if you accept using pandas :

import pandas
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
df = pandas.DataFrame(result, index=[0])
print df

gives :

          0         1         2         3  4         5         6
0  1.118175  0.556608  0.471827  0.487167  1  0.139508  0.209416

VNC viewer with multiple monitors

The free version of TightVnc viewer (I have TightVnc Viewer 1.5.4 8/3/2011) build does not support this. What you need is RealVNC but VNC Enterprise Edition 4.2 or the Personal Edition. Unfortunately this is not free and you have to pay for a license.

From the RealVNC website [releasenote] http://www.realvnc.com/products/enterprise/4.2/release-notes.html

VNC Viewer: Full-screen mode can span monitors on a multi-monitor system.

How to filter WooCommerce products by custom attribute

On one of my sites I had to make a custom search by a lot of data some of it from custom fields here is how my $args look like for one of the options:

$args = array(
    'meta_query' => $meta_query,
    'tax_query' => array(
        $query_tax
    ),
    'posts_per_page' => 10,
    'post_type' => 'ad_listing',
    'orderby' => $orderby,
    'order' => $order,
    'paged' => $paged
);

where "$meta_query" is:

$key = "your_custom_key"; //custom_color for example
$value = "blue";//or red or any color
$query_color = array('key' => $key, 'value' => $value);
$meta_query[] = $query_color;

and after that:

query_posts($args);

so you would probably get more info here: http://codex.wordpress.org/Class_Reference/WP_Query and you can search for "meta_query" in the page to get to the info

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Building on Olie and Algal's answer, here is an updated answer for Swift 3

public func getRGBAs(fromImage image: UIImage, x: Int, y: Int, count: Int) -> [UIColor] {

var result = [UIColor]()

// First get the image into your data buffer
guard let cgImage = image.cgImage else {
    print("CGContext creation failed")
    return []
}

let width = cgImage.width
let height = cgImage.height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let rawdata = calloc(height*width*4, MemoryLayout<CUnsignedChar>.size)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue

guard let context = CGContext(data: rawdata, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
    print("CGContext creation failed")
    return result
}

context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))

// Now your rawData contains the image data in the RGBA8888 pixel format.
var byteIndex = bytesPerRow * y + bytesPerPixel * x

for _ in 0..<count {
    let alpha = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 3, as: UInt8.self)) / 255.0
    let red = CGFloat(rawdata!.load(fromByteOffset: byteIndex, as: UInt8.self)) / alpha
    let green = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 1, as: UInt8.self)) / alpha
    let blue = CGFloat(rawdata!.load(fromByteOffset: byteIndex + 2, as: UInt8.self)) / alpha
    byteIndex += bytesPerPixel

    let aColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)
    result.append(aColor)
}

free(rawdata)

return result
}

Delete the last two characters of the String

You may use the following method to remove last n character -

public String removeLast(String s, int n) {
    if (null != s && !s.isEmpty()) {
        s = s.substring(0, s.length()-n);
    }
    return s;
}

How to reset Jenkins security settings from the command line?

In order to remove the by default security for jenkins in Windows OS,

You can traverse through the file Config.xml created inside /users/{UserName}/.jenkins.

Inside this file you can change the code from

<useSecurity>true</useSecurity>

To,

<useSecurity>false</useSecurity>

Release generating .pdb files, why?

.PDB file is the short name of "Program Database". It contains the information about debug point for debugger and resources which are used or reference. Its generated when we build as debug mode. Its allow to application to debug at runtime.

The size is increase of .PDB file in debug mode. It is used when we are testing our application.

Good article of pdb file.

http://www.codeproject.com/Articles/37456/How-To-Inspect-the-Content-of-a-Program-Database-P

How can I connect to Android with ADB over TCP?

To connect your tablet using TCP port. Make sure your system and device is connected to same network.

  1. Open console cmd.exe
  2. Type adb tcpip 5555
  3. Go to System -> Development option -> USB debugging --> Uncheck it for TCPIP connection
  4. Type adb connect 192.168.1.2 this is your device IP address
  5. Connected to 192.168.1.2

Connected using port forward Try to do port forwarding,

adb forward tcp:<PC port> tcp:<device port>

like:

adb forward tcp:5555 tcp:5555.

C:\Users\abc>adb forward tcp:7612 tcp:7612

C:\Users\abc>adb tcpip 7612 restarting in TCP mode port: 7612

C:\Users\abc>adb connect 10.0.0.1:7612

connected to 10.0.0.1:7612

If you get message error: device not found connect a usb device to system then follow same procedure.
for a rooted device

setprop service.adb.tcp.port 5555
stop adbd
start adbd

SQL SELECT WHERE field contains words

SELECT * FROM MyTable WHERE Column1 Like "*word*"

This will display all the records where column1 has a partial value contains word.

How to have Ellipsis effect on Text

<View 
   style={{
        flexDirection: 'row',
        padding: 10,
    }}
>
  <Text numberOfLines={5} style={{flex:1}}>
       This is a very long text that will overflow on a small device This is a very 
       long text that will overflow on a small deviceThis is a very long text that 
       will overflow on a small deviceThis is a very long text that will overflow 
       on a small device
  </Text>
</View>

How do I change the default library path for R packages

See help(Startup) and help(.libPaths) as you have several possibilities where this may have gotten set. Among them are

  • setting R_LIBS_USER
  • assigning .libPaths() in .Rprofile or Rprofile.site

and more.

In this particular case you need to go backwards and unset whereever \\\\The library/path/I/don't/want is set.

To otherwise ignore it you need to override it use explicitly i.e. via

library("somePackage", lib.loc=.libPaths()[-1])

when loading a package.

Why is it common to put CSRF prevention tokens in cookies?

Besides the session cookie (which is kind of standard), I don't want to use extra cookies.

I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.

My solution without extra cookies is simple:

Client Side

Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.

The main "index" page contains this JavaScript snippet:

// Intialize global variable CSRF_TOKEN to empty sting. 
// This variable is set after a succesful login
window.CSRF_TOKEN = '';

// the supplied callback to .ajaxSend() is called before an Ajax request is sent
$( document ).ajaxSend( function( event, jqXHR ) {
    jqXHR.setRequestHeader('X-CSRF-TOKEN', window.CSRF_TOKEN);
}); 

Server Side

On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.

Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.

@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
if (sessionCSRFToken == null || req.getHeader("X-CSRF-TOKEN") == null || !req.getHeader("X-CSRF-TOKEN").equals(sessionCSRFToken)) {
    resp.sendError(401);
} else
    chain.doFilter(request, response);
}   

How to change the window title of a MATLAB plotting figure?

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

How do I get data from a table?

in this code data is a two dimensional array of table data

let oTable = document.getElementById('datatable-id');
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))

java comparator, how to sort by integer?

Just replace:

return d.age - d1.age;

By:

return ((Integer)d.age).compareTo(d1.age);

Or invert to reverse the list:

return ((Integer)d1.age).compareTo(d.age);

EDIT:

Fixed the "memory problem".
Indeed, the better solution is change the age field in the Dog class to Integer, because there many benefits, like the null possibility...

What is the best way to trigger onchange event in react js

Expanding on the answer from Grin/Dan Abramov, this works across multiple input types. Tested in React >= 15.5

const inputTypes = [
    window.HTMLInputElement,
    window.HTMLSelectElement,
    window.HTMLTextAreaElement,
];

export const triggerInputChange = (node, value = '') => {

    // only process the change on elements we know have a value setter in their constructor
    if ( inputTypes.indexOf(node.__proto__.constructor) >-1 ) {

        const setValue = Object.getOwnPropertyDescriptor(node.__proto__, 'value').set;
        const event = new Event('input', { bubbles: true });

        setValue.call(node, value);
        node.dispatchEvent(event);

    }

};

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

Even without seeing your JSON string you can tell from the error message that it is not the correct structure to be parsed into an instance of your class.

Gson is expecting your JSON string to begin with an object opening brace. e.g.

{

But the string you have passed to it starts with an open quotes

"

Uncaught TypeError: Cannot read property 'value' of null

If in your HTML you have an input element with a name or id with a _ like e.g. first_name or more than one _ like e.g. student_first_name and you also have the Javascript code at the bottom of your Web Page and you are sure you are doing everything else right, then those dashes could be what is messing you up.

Having id or name for your input elements resembling the below

<input type="text" id="first_name" name="first_name">

or

<input type="text" id="student_first_name" name="student_first_name">

Then you try make a call like this below in your JavaScript code

var first_name = document.getElementById("first_name").value;

or

var student_first_name = document.getElementById("student_first_name").value;

You are certainly going to have an error like Uncaught TypeError: Cannot read property 'value' of null in Google Chrome and on Internet Explorer too. I did not get to test that with Firefox.

In my case I removed the dashes, in first_name and renamed it to firstname and from student_first_name to studentfirstname

At the end, I was able to resolve that error with my code now looking as follows for HTML and JavaScript.

HTML

<input type="text" id="firstname" name="firstname">

or

<input type="text" id="studentfirstname" name="studentfirstname">

Javascript

var firstname = document.getElementById("firstname").value;

or

var studentfirstname = document.getElementById("studentfirstname").value;

So if it is within your means to rename the HTML and JavaScript code with those dashes, it may help if that is what is ailing your piece of code. In my case that was what was bugging me.

Hope this helps someone stop pulling their hair like I was.

How do I mock an autowired @Value field in Spring with Mockito?

You can also mock your property configuration into your test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class MyTest 
{ 
   @Configuration
   public static class MockConfig{
       @Bean
       public Properties myProps(){
             Properties properties = new Properties();
             properties.setProperty("default.url", "myUrl");
             properties.setProperty("property.value2", "value2");
             return properties;
        }
   }
   @Value("#{myProps['default.url']}")
   private String defaultUrl;

   @Test
   public void testValue(){
       Assert.assertEquals("myUrl", defaultUrl);
   }
}

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

If you compile the files and the value of the "targetFramework" is set as being a particular version i.e. 4.0,

Make sure the host is running .net framework as the same version stated.

If not, download the .net framework.

After downloading, if it is not automatic being set in the IIS manager to be using the extension of the newly downloaded version of .net framework,

add the extension manually by going to the folder of the recently downloaded .net framework THROUGH IIS manager:

1.right-click website folder

2.go to "Properties"

3.under "virtual directory" , click "configuration"

4.edit the executable path of extension ".aspx" (of which the path being pointed to version other than the version of the recently downloaded .net framework) to the correct path which is the folder of the NEWLY downloaded version of .net framework and then select the "aspnet_isapi.dll" file.

5.click ok!

How can I check the system version of Android?

Be aware that Build.VERSION.SDK_INT isn't reliable, it's mentioned by @Falcon165o and recently I ran into that one too.

So to get the String data (based on Android version list) of currently installed android, I made a code like this:

Java

//Current Android version data
public static String currentVersion(){
    double release=Double.parseDouble(Build.VERSION.RELEASE.replaceAll("(\\d+[.]\\d+)(.*)","$1"));
    String codeName="Unsupported";//below Jelly bean OR above Oreo
    if(release>=4.1 && release<4.4)codeName="Jelly Bean";
    else if(release<5)codeName="Kit Kat";
    else if(release<6)codeName="Lollipop";
    else if(release<7)codeName="Marshmallow";
    else if(release<8)codeName="Nougat";
    else if(release<9)codeName="Oreo";
    return codeName+" v"+release+", API Level: "+Build.VERSION.SDK_INT;
}

Kotlin

fun currentVersion(): String {
    val release = java.lang.Double.parseDouble(java.lang.String(Build.VERSION.RELEASE).replaceAll("(\\d+[.]\\d+)(.*)", "$1"))
    var codeName = "Unsupported"//below Jelly bean OR above Oreo
    if (release >= 4.1 && release < 4.4)  codeName = "Jelly Bean"
    else if (release < 5) codeName = "Kit Kat"
    else if (release < 6) codeName = "Lollipop"
    else if (release < 7) codeName = "Marshmallow"
    else if (release < 8) codeName = "Nougat"
    else if (release < 9) codeName = "Oreo"
    return codeName + " v" + release + ", API Level: " + Build.VERSION.SDK_INT
}

Example of an output it produce:

Marshmallow v6.0, API Level: 23

Git: How to find a deleted file in the project commit history?

Suppose you want to recover a file called MyFile, but are uncertain of its path (or its extension, for that matter):

Preliminary: Avoid confusion by stepping to the git root

A nontrivial project may have multiple directories with similar or identical filenames.

> cd <project-root>
  1. Find the full path

    git log --diff-filter=D --summary | grep delete | grep MyFile

    delete mode 100644 full/path/to/MyFile.js

full/path/to/MyFile.js is the path & file you're seeking.

  1. Determine all the commits that affected that file

    git log --oneline --follow -- full/path/to/MyFile.js

    bd8374c Some helpful commit message

    ba8d20e Another prior commit message affecting that file

    cfea812 The first message for a commit in which that file appeared.

  2. Checkout the file

If you choose the first-listed commit (the last chronologically, here bd8374c), the file will not be found, since it was deleted in that commit.

> git checkout bd8374c -- full/path/to/MyFile.js

`error: pathspec 'full/path/to/MyFile.js' did not match any file(s) known to git.`

Just select the preceding (append a caret) commit:

> git checkout bd8374c^ -- full/path/to/MyFile.js

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

If you want to do this often, you can create a keybindings file in your Library to map it to a key combination.

In ~/Library create a directory named KeyBindings. Create a file named DefaultKeyBinding.dict inside the directory. You can add key bindings in this format:

{
    "x" = (insertText:, "\U23CF");
    "y" = (insertText:, "hi"); /* warning: this will change 'y' to 'hi'! */
}

The LHS is the key combination you'll hit to enter the character. You can use the following characters to indicate command keys:

@ - Command

~ - Option

^ - Control

You'll need to look up the unicode for your character (in this case, ? is \U2234). So to type this character whenever you typed Control-M, you'd use

"^m" = (insertText:, "\U2234");

You can find more information here: http://www.hcs.harvard.edu/~jrus/site/cocoa-text.html

Select Top and Last rows in a table (SQL server)

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

Create a temporary table in a SELECT statement without a separate CREATE TABLE

Engine must be before select:

CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY 
as (select * from table1)

How to set HTML5 required attribute in Javascript?

required is a reflected property (like id, name, type, and such), so:

element.required = true;

...where element is the actual input DOM element, e.g.:

document.getElementById("edName").required = true;

(Just for completeness.)

Re:

Then the attribute's value is not the empty string, nor the canonical name of the attribute:

edName.attributes.required = [object Attr]

That's because required in that code is an attribute object, not a string; attributes is a NamedNodeMap whose values are Attr objects. To get the value of one of them, you'd look at its value property. But for a boolean attribute, the value isn't relevant; the attribute is either present in the map (true) or not present (false).

So if required weren't reflected, you'd set it by adding the attribute:

element.setAttribute("required", "");

...which is the equivalent of element.required = true. You'd clear it by removing it entirely:

element.removeAttribute("required");

...which is the equivalent of element.required = false.

But we don't have to do that with required, since it's reflected.

How do I line up 3 divs on the same row?

This is easier and gives purpose to the never used unordered/ordered list tags.

In your CSS add:

    li{float: left;}  //Sets float left property globally for all li tags.

Then add in your HTML:

    <ul>
         <li>1</li>
         <li>2</li>
         <li>3</li>        
    </ul>

Now watch it all line up perfectly! No more arguing over tables vs divs!

Remove all subviews?

Use the Following code to remove all subviews.

for (UIView *view in [self.view subviews]) 
{
 [view removeFromSuperview];
}

How do I run Java .class files?

This can mean a lot of things, but the most common one is that the class contained in the file doesn't have the same name as the file itself. So, check if your class is also called HelloWorld2.

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

When should I use curly braces for ES6 import?

Usually when you export a function you need to use the {}.

If you have

export const x

you use

import {x} from ''

If you use

export default const x

you need to use

import x from ''

Here you can change X to whatever variable you want.

css to make bootstrap navbar transparent

This works for 4.0.

<nav class="navbar navbar-expand-sm fixed-top navbar-light">
or
<nav class="navbar navbar-expand-lg fixed-top navbar-dark">

key item is fixed-top, otherwise, white or default page background is displayed even if there is a image top. navbar-light gives dark letters, navbar-dark shows light text.

How can I return the difference between two lists?

Here is a generic solution for this problem.

public <T> List<T> difference(List<T> first, List<T> second) {
    List<T> toReturn = new ArrayList<>(first);
    toReturn.removeAll(second);
    return toReturn;
}

How to run crontab job every week on Sunday

I think you would like this interactive website, which often helps me build complex Crontab directives: https://crontab.guru/

What is the best regular expression to check if a string is a valid URL?

Interestingly, none of the answers above worked for what I needed, so I figured I would offer my solution. I needed to be able to do the following:

  • Match http(s)://www.google.com, http://google.com, www.google.com, and google.com
  • Match Github markdown style links like [Google](http://www.google.com)
  • Match all possible domain extensions, like .com, or .io, or .guru, etc. Basically anything between 2-6 characters in length
  • Split everything into proper groupings so that I could access each part as needed.

Here was the solution:

/^(\[[A-z0-9 _]*\]\()?((?:(http|https):\/\/)?(?:[\w-]+\.)+[a-z]{2,6})(\))?$

This gives me all of the above requirements. You could optionally add the ability for ftp and file if necessary:

/^(\[[A-z0-9 _]*\]\()?((?:(http|https|ftp|file):\/\/)?(?:[\w-]+\.)+[a-z]{2,6})(\))?$

How to trigger event in JavaScript?

The most efficient way is to call the very same function that has been registered with addEventListener directly.

You can also trigger a fake event with CustomEvent and co.

Finally some elements such as <input type="file"> support a .click() method.

Assign multiple values to array in C

You can use:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).

The other two ways that spring to mind are to blat the contents if they're fixed:

GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));

or provide a function that looks like your initialisation code anyway:

void setCoords (float *p0, float p1, ..., float p8) {
    p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
    p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);

keeping in mind those ellipses (...) are placeholders, not things to literally insert in the code.

An efficient way to transpose a file in Bash

Here's a Haskell solution. When compiled with -O2, it runs slightly faster than ghostdog's awk and slightly slower than Stephan's thinly wrapped c python on my machine for repeated "Hello world" input lines. Unfortunately GHC's support for passing command line code is non-existent as far as I can tell, so you will have to write it to a file yourself. It will truncate the rows to the length of the shortest row.

transpose :: [[a]] -> [[a]]
transpose = foldr (zipWith (:)) (repeat [])

main :: IO ()
main = interact $ unlines . map unwords . transpose . map words . lines

htaccess redirect all pages to single page

Add this for pages not currently on your site...

ErrorDocument 404 http://example.com/

Along with your Redirect 301 / http://www.thenewdomain.com/ that should cover all the bases...

Good luck!

Plot a legend outside of the plotting area in base graphics?

Maybe what you need is par(xpd=TRUE) to enable things to be drawn outside the plot region. So if you do the main plot with bty='L' you'll have some space on the right for a legend. Normally this would get clipped to the plot region, but do par(xpd=TRUE) and with a bit of adjustment you can get a legend as far right as it can go:

 set.seed(1) # just to get the same random numbers
 par(xpd=FALSE) # this is usually the default

 plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2), bty='L')
 # this legend gets clipped:
 legend(2.8,0,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

 # so turn off clipping:
 par(xpd=TRUE)
 legend(2.8,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

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

way of getting home directory of current user is

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

and to append path separator

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

File.separator

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

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

What are the most common naming conventions in C?

The most important thing here is consistency. That said, I follow the GTK+ coding convention, which can be summarized as follows:

  1. All macros and constants in caps: MAX_BUFFER_SIZE, TRACKING_ID_PREFIX.
  2. Struct names and typedef's in camelcase: GtkWidget, TrackingOrder.
  3. Functions that operate on structs: classic C style: gtk_widget_show(), tracking_order_process().
  4. Pointers: nothing fancy here: GtkWidget *foo, TrackingOrder *bar.
  5. Global variables: just don't use global variables. They are evil.
  6. Functions that are there, but shouldn't be called directly, or have obscure uses, or whatever: one or more underscores at the beginning: _refrobnicate_data_tables(), _destroy_cache().

How to calculate a Mod b in Casio fx-991ES calculator

It all falls back to the definition of modulus: It is the remainder, for example, 7 mod 3 = 1. This because 7 = 3(2) + 1, in which 1 is the remainder.

To do this process on a simple calculator do the following: Take the dividend (7) and divide by the divisor (3), note the answer and discard all the decimals -> example 7/3 = 2.3333333, only worry about the 2. Now multiply this number by the divisor (3) and subtract the resulting number from the original dividend.

so 2*3 = 6, and 7 - 6 = 1, thus 1 is 7mod3

MVC3 EditorFor readOnly

The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:

<div class="editor-field">
    @Html.TextBoxFor(model => model.userName, new 
        { disabled = "disabled", @readonly = "readonly" })
</div>

You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:

public class MyModel
{
    [UIHint("userName")]
    public string userName { ;get; set; }
}

Then, in your Views/Shared/EditorTemplates folder, create a file userName.cshtml. In that file, put this:

@model string
@Html.TextBoxFor(m => m, new { disabled = "disabled", @readonly = "readonly" })

What is the 'new' keyword in JavaScript?

Suppose you have this function:

var Foo = function(){
  this.A = 1;
  this.B = 2;
};

If you call this as a standalone function like so:

Foo();

Executing this function will add two properties to the window object (A and B). It adds it to the window because window is the object that called the function when you execute it like that, and this in a function is the object that called the function. In Javascript at least.

Now, call it like this with new:

var bar = new Foo();

What happens when you add new to a function call is that a new object is created (just var bar = new Object()) and that the this within the function points to the new Object you just created, instead of to the object that called the function. So bar is now an object with the properties A and B. Any function can be a constructor, it just doesn't always make sense.

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

ArrayList initialization equivalent to array initialization

Arrays.asList("Ryan", "Julie", "Bob");

nodejs mysql Error: Connection lost The server closed the connection

Try to use this code to handle server disconnect:

var db_config = {
  host: 'localhost',
    user: 'root',
    password: '',
    database: 'example'
};

var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connection.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      handleDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

handleDisconnect();

In your code i am missing the parts after connection = mysql.createConnection(db_config);

Using 24 hour time in bootstrap timepicker

The below code is correct answer for me.

 $('#datetimepicker6').datetimepicker({
                    format : 'YYYY-MM-DD HH:mm'
                });

Django model "doesn't declare an explicit app_label"

I had this error today trying to run Django tests because I was using the shorthand from .models import * syntax in one of my files. The issue was that I had a file structure like so:

    apps/
      myapp/
        models/
          __init__.py
          foo.py
          bar.py

and in models/__init__.py I was importing my models using the shorthand syntax:

    from .foo import *
    from .bar import *

In my application I was importing models like so:

    from myapp.models import Foo, Bar

This caused the Django model doesn't declare an explicit app_label when running ./manage.py test.

To fix the problem, I had to explicitly import from the full path in models/__init__.py:

    from myapp.models.foo import *
    from myapp.models.bar import *

That took care of the error.

H/t https://medium.com/@michal.bock/fix-weird-exceptions-when-running-django-tests-f58def71b59a

UPDATE and REPLACE part of a string

To make the query run faster in big tables where not every line needs to be updated, you can also choose to only update rows that will be modified:

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <= 4
AND Value LIKE '%123%'

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

How can I embed a YouTube video on GitHub wiki pages?

Center align Video with Thumbnail and Link:

<div align="center">
      <a href="https://www.youtube.com/watch?v=StTqXEQ2l-Y">
     <img 
      src="https://img.youtube.com/vi/StTqXEQ2l-Y/0.jpg" 
      alt="Everything Is AWESOME" 
      style="width:100%;">
      </a>
    </div>

Result:

enter image description here

How do I add a new class to an element dynamically?

CSS really doesn't have the ability to modify an object in the same manner as JavaScript, so in short - no.

How to initialize a vector in C++

You can also do like this:

template <typename T>
class make_vector {
public:
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    data_.push_back(val);
    return *this;
  }
  operator std::vector<T>() const {
    return data_;
  }
private:
  std::vector<T> data_;
};

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;

@selector() in Swift?

It may be useful to note where you setup the control that triggers the action matters.

For example, I have found that when setting up a UIBarButtonItem, I had to create the button within viewDidLoad or else I would get an unrecognized selector exception.

override func viewDidLoad() {
    super.viewDidLoad() 

    // add button
    let addButton = UIBarButtonItem(image: UIImage(named: "746-plus-circle.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("addAction:"))
    self.navigationItem.rightBarButtonItem = addButton
}

func addAction(send: AnyObject?) {     
    NSLog("addAction")
}

How to take input in an array + PYTHON?

arr = []
elem = int(raw_input("insert how many elements you want:"))
for i in range(0, elem):
    arr.append(int(raw_input("Enter next no :")))
print arr

Number of elements in a javascript object

if you are already using jQuery in your build just do this:

$(yourObject).length

It works nicely for me on objects, and I already had jQuery as a dependancy.

Rails 3.1 and Image Assets

For what it's worth, when I did this I found that no folder should be include in the path in the css file. For instance if I have app/assets/images/example.png, and I put this in my css file...

div.example { background: url('example.png'); }

... then somehow it magically works. I figured this out by running the rake assets:precompile task, which just sucks everything out of all your load paths and dumps it in a junk drawer folder: public/assets. That's ironic, IMO...

In any case this means you don't need to put any folder paths, everything in your assets folders will all end up living in one huge directory. How this system resolves file name conflicts is unclear, you may need to be careful about that.

Kind of frustrating there aren't better docs out there for this big of a change.

Bootstrap 3 Collapse show state with Chevron icon

You could use this kind of code :

function toggleChevron(e) {
    $(e.target)
        .prev('.panel-heading')
        .find('i.indicator')
        .toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
}
$('#accordion').on('hidden.bs.collapse', toggleChevron);
$('#accordion').on('shown.bs.collapse', toggleChevron);

=> Working JsFiddle

What are NR and FNR and what does "NR==FNR" imply?

Look for keys (first word of line) in file2 that are also in file1.
Step 1: fill array a with the first words of file 1:

awk '{a[$1];}' file1

Step 2: Fill array a and ignore file 2 in the same command. For this check the total number of records until now with the number of the current input file.

awk 'NR==FNR{a[$1]}' file1 file2

Step 3: Ignore actions that might come after } when parsing file 1

awk 'NR==FNR{a[$1];next}' file1 file2 

Step 4: print key of file2 when found in the array a

awk 'NR==FNR{a[$1];next} $1 in a{print $1}' file1 file2

jQuery: Adding two attributes via the .attr(); method

Something like this:

$(myObj).attr({"data-test-1": num1, "data-test-2": num2});

Regex empty string or email

This regex pattern will match an empty string:

^$

And this will match (crudely) an email or an empty string:

(^$|^.*@.*\..*$)

Padding between ActionBar's home icon and title

For my case, it was with Toolbar i resolved it like this:

ic_toolbar_drawble.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:drawable="@drawable/ic_toolbar"
    android:right="-16dp"
    android:left="-16dp"/>
</layer-list>

In my Fragment, i check the api :

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      toolbar.setLogo(R.drawable.ic_toolbar);
else
      toolbar.setLogo(R.drawable.ic_toolbar_draweble);

Good luck!

How do you set the title color for the new Toolbar?

With the Material Components Library you can use the app:titleTextColor attribute.

In the layout you can use something like:

<com.google.android.material.appbar.MaterialToolbar
    app:titleTextColor="@color/...."
    .../>

You can also use a custom style:

<com.google.android.material.appbar.MaterialToolbar
     style="@style/MyToolbarStyle"
    .../>

with (extending the Widget.MaterialComponents.Toolbar.Primary style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar.Primary">
       <item name="titleTextColor">@color/....</item>
  </style>

or (extending the Widget.MaterialComponents.Toolbar style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
       <item name="titleTextColor">@color/....</item>
  </style>

enter image description here

You can also override the color defined by the style using the android:theme attribute (using the Widget.MaterialComponents.Toolbar.Primary style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        />

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is also used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>

enter image description here

or (using the Widget.MaterialComponents.Toolbar style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar"
        android:theme="@style/MyThemeOverlay_Toolbar2"

with:

  <style name="MyThemeOverlay_Toolbar3" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>

How to convert a string with Unicode encoding to a string of letters

one easy way i know using JsonObject:

try {
    JSONObject json = new JSONObject();
    json.put("string", myString);
    String converted = json.getString("string");

} catch (JSONException e) {
    e.printStackTrace();
}

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

How can I force gradle to redownload dependencies?

For those who are wondering where to run gradle commands:

  1. Open Android Studio
  2. Click on Terminal(You will find it in the base of Android Studio)
  3. The command tool will open
  4. Type your command gradlew build --refresh-dependencies

How to split a data frame?

Splitting the data frame seems counter-productive. Instead, use the split-apply-combine paradigm, e.g., generate some data

df = data.frame(grp=sample(letters, 100, TRUE), x=rnorm(100))

then split only the relevant columns and apply the scale() function to x in each group, and combine the results (using split<- or ave)

df$z = 0
split(df$z, df$grp) = lapply(split(df$x, df$grp), scale)
## alternative: df$z = ave(df$x, df$grp, FUN=scale)

This will be very fast compared to splitting data.frames, and the result remains usable in downstream analysis without iteration. I think the dplyr syntax is

library(dplyr)
df %>% group_by(grp) %>% mutate(z=scale(x))

In general this dplyr solution is faster than splitting data frames but not as fast as split-apply-combine.

How to parse the AndroidManifest.xml file inside an .apk package

With the latest SDK-Tools, you can now use a tool called the apkanalyzer to print out the AndroidManifest.xml of an APK (as well as other parts, such as resources).

[android sdk]/tools/bin/apkanalyzer manifest print [app.apk]

apkanalyzer

Handling back button in Android Navigation Component

My Opinion requireActivity().onBackPressed()

requireActivity().onBackPressed()

What's the difference between & and && in MATLAB?

A good rule of thumb when constructing arguments for use in conditional statements (IF, WHILE, etc.) is to always use the &&/|| forms, unless there's a very good reason not to. There are two reasons...

  1. As others have mentioned, the short-circuiting behavior of &&/|| is similar to most C-like languages. That similarity / familiarity is generally considered a point in its favor.
  2. Using the && or || forms forces you to write the full code for deciding your intent for vector arguments. When a = [1 0 0 1] and b = [0 1 0 1], is a&b true or false? I can't remember the rules for MATLAB's &, can you? Most people can't. On the other hand, if you use && or ||, you're FORCED to write the code "in full" to resolve the condition.

Doing this, rather than relying on MATLAB's resolution of vectors in & and |, leads to code that's a little bit more verbose, but a LOT safer and easier to maintain.

Call a Class From another class

If your class2 looks like this having static members

public class2
{
    static int var = 1;

    public static void myMethod()
    {
      // some code

    }
}

Then you can simply call them like

class2.myMethod();
class2.var = 1;

If you want to access non-static members then you would have to instantiate an object.

class2 object = new class2();
object.myMethod();  // non static method
object.var = 1;     // non static variable

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

PHP, display image with Header()

if you know the file name, but don't know the file extention you can use this function:

public function showImage($name)
    {

         $types = [
             'gif'=> 'image/gif',
             'png'=> 'image/png',
             'jpeg'=> 'image/jpeg',
             'jpg'=> 'image/jpeg',
         ];
         $root_path  = '/var/www/my_app'; //use your framework to get this properly ..
         foreach($types as $type=>$meta){
             if(file_exists($root_path .'/uploads/'.$name  .'.'. $type)){
                 header('Content-type: ' . $meta);
                 readfile($root_path .'/uploads/'.$name .'.'. $type);
                 return;
             }
         }
    }

Note: the correct content-type for JPG files is image/jpeg.

Use .corr to get the correlation between two columns

changing 'Citable docs per Capita' to numeric before correlation will solve the problem.

    Top15['Citable docs per Capita'] = pd.to_numeric(Top15['Citable docs per Capita'])
    data = Top15[['Citable docs per Capita','Energy Supply per Capita']]
    correlation = data.corr(method='pearson')

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

Try this in a Thread (not the UI-Thread):

final CountDownLatch latch = new CountDownLatch(1);
handler.post(new Runnable() {
  @Override
  public void run() {
    OnClickListener okListener = new OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
      dialog.dismiss();
      latch.countDown();
    }
  };

  AlertDialog dialog = new AlertDialog.Builder(context).setTitle(title)
    .setMessage(msg).setPositiveButton("OK", okListener).create();
  dialog.show();
}
});
try {
  latch.await();
} catch (InterruptedException e) {
  e.printStackTrace();
}

Generate a random point within a circle (uniformly)

How to generate a random point within a circle of radius R:

r = R * sqrt(random())
theta = random() * 2 * PI

(Assuming random() gives a value between 0 and 1 uniformly)

If you want to convert this to Cartesian coordinates, you can do

x = centerX + r * cos(theta)
y = centerY + r * sin(theta)


Why sqrt(random())?

Let's look at the math that leads up to sqrt(random()). Assume for simplicity that we're working with the unit circle, i.e. R = 1.

The average distance between points should be the same regardless of how far from the center we look. This means for example, that looking on the perimeter of a circle with circumference 2 we should find twice as many points as the number of points on the perimeter of a circle with circumference 1.


                

Since the circumference of a circle (2πr) grows linearly with r, it follows that the number of random points should grow linearly with r. In other words, the desired probability density function (PDF) grows linearly. Since a PDF should have an area equal to 1 and the maximum radius is 1, we have


                

So we know how the desired density of our random values should look like. Now: How do we generate such a random value when all we have is a uniform random value between 0 and 1?

We use a trick called inverse transform sampling

  1. From the PDF, create the cumulative distribution function (CDF)
  2. Mirror this along y = x
  3. Apply the resulting function to a uniform value between 0 and 1.

Sounds complicated? Let me insert a blockquote with a little side track that conveys the intuition:

Suppose we want to generate a random point with the following distribution:

                

That is

  • 1/5 of the points uniformly between 1 and 2, and
  • 4/5 of the points uniformly between 2 and 3.

The CDF is, as the name suggests, the cumulative version of the PDF. Intuitively: While PDF(x) describes the number of random values at x, CDF(x) describes the number of random values less than x.

In this case the CDF would look like:

                

To see how this is useful, imagine that we shoot bullets from left to right at uniformly distributed heights. As the bullets hit the line, they drop down to the ground:

                

See how the density of the bullets on the ground correspond to our desired distribution! We're almost there!

The problem is that for this function, the y axis is the output and the x axis is the input. We can only "shoot bullets from the ground straight up"! We need the inverse function!

This is why we mirror the whole thing; x becomes y and y becomes x:

                

We call this CDF-1. To get values according to the desired distribution, we use CDF-1(random()).

…so, back to generating random radius values where our PDF equals 2x.

Step 1: Create the CDF:

Since we're working with reals, the CDF is expressed as the integral of the PDF.

CDF(x) = ? 2x = x2

Step 2: Mirror the CDF along y = x:

Mathematically this boils down to swapping x and y and solving for y:

CDF:     y = x2
Swap:   x = y2
Solve:   y = √x
CDF-1:  y = √x

Step 3: Apply the resulting function to a uniform value between 0 and 1

CDF-1(random()) = √random()

Which is what we set out to derive :-)

Implementing multiple interfaces with Java - is there a way to delegate?

As said, there's no way. However, a bit decent IDE can autogenerate delegate methods. For example Eclipse can do. First setup a template:

public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
    private InterFaceOne if1;
    private InterFaceTwo if2;
}

then rightclick, choose Source > Generate Delegate Methods and tick the both if1 and if2 fields and click OK.

See also the following screens:

alt text


alt text


alt text

Match all elements having class name starting with a specific string

It's not a direct answer to the question, however I would suggest in most cases to simply set multiple classes to each element:

<div class="myclass one"></div>
<div class="myclass two></div>
<div class="myclass three"></div>

In this way you can set rules for all myclass elements and then more specific rules for one, two and three.

.myclass { color: #f00; }

.two { font-weight: bold; }

etc.

Generating a PDF file from React Components

npm install jspdf --save

//code on react

import jsPDF from 'jspdf';


var doc = new jsPDF()


 doc.fromHTML("<div>JOmin</div>", 1, 1)


onclick //

 doc.save("name.pdf")

Add Auto-Increment ID to existing table?

ALTER TABLE users CHANGE id int( 30 ) NOT NULL AUTO_INCREMENT

the integer parameter is based on my default sql setting have a nice day

Difference between static STATIC_URL and STATIC_ROOT on Django

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix: picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

TCPDF Save file to folder?

For who is having difficulties storing the file, the path has to be all the way through root. For example, mine was:

$pdf->Output('/home/username/public_html/app/admin/pdfs/filename.pdf', 'F');

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Getting value from appsettings.json in .net core

In my case it was simple as using the Bind() method on the Configuration object. And then add the object as singleton in the DI.

var instructionSettings = new InstructionSettings();
Configuration.Bind("InstructionSettings", instructionSettings);
services.AddSingleton(typeof(IInstructionSettings), (serviceProvider) => instructionSettings);

The Instruction object can be as complex as you want.

{  
 "InstructionSettings": {
    "Header": "uat_TEST",
    "SVSCode": "FICA",
    "CallBackUrl": "https://UATEnviro.companyName.co.za/suite/webapi/receiveCallback",
    "Username": "s_integrat",
    "Password": "X@nkmail6",
    "Defaults": {
    "Language": "ENG",
    "ContactDetails":{
       "StreetNumber": "9",
       "StreetName": "Nano Drive",
       "City": "Johannesburg",
       "Suburb": "Sandton",
       "Province": "Gauteng",
       "PostCode": "2196",
       "Email": "[email protected]",
       "CellNumber": "0833 468 378",
       "HomeNumber": "0833 468 378",
      }
      "CountryOfBirth": "710"
    }
  }

How do I read the contents of a Node.js stream into a string variable?

What do you think about this ?

// lets have a ReadableStream as a stream variable

const chunks = [];

for await (let chunk of stream) {
    chunks.push(chunk)
}

const buffer  = Buffer.concat(chunks);
const str = buffer.toString("utf-8")

Regex any ASCII character

Accepts / Matches only ASCII characters

/^[\x00-\x7F]*$/

How can I select random files from a directory in bash?

How about a Perl solution slightly doctored from Mr. Kang over here:
How can I shuffle the lines of a text file on the Unix command line or in a shell script?

$ ls | perl -MList::Util=shuffle -e '@lines = shuffle(<>); print @lines[0..4]'

Why doesn't JavaScript have a last method?

It's easy to define one yourself. That's the power of JavaScript.

if(!Array.prototype.last) {
    Array.prototype.last = function() {
        return this[this.length - 1];
    }
}

var arr = [1, 2, 5];
arr.last(); // 5

However, this may cause problems with 3rd-party code which (incorrectly) uses for..in loops to iterate over arrays.

However, if you are not bound with browser support problems, then using the new ES5 syntax to define properties can solve that issue, by making the function non-enumerable, like so:

Object.defineProperty(Array.prototype, 'last', {
    enumerable: false,
    configurable: true,
    get: function() {
        return this[this.length - 1];
    },
    set: undefined
});

var arr = [1, 2, 5];
arr.last; // 5

How can I clone a JavaScript object except for one key?

If you use Ramda you can use its omit and clone functions to make a deep clone of your object and omit the unnecessary fields.

var object = {a: 1, b: 2, c: 3, y:25, z:26};
R.clone(R.omit(["z", "y"], object));

Double precision floating values in Python?

For some applications you can use Fraction instead of floating-point numbers.

>>> from fractions import Fraction
>>> Fraction(1, 3**54)
Fraction(1, 58149737003040059690390169)

(For other applications, there's decimal, as suggested out by the other responses.)

Query to get all rows from previous month

WHERE created_date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) 
  AND created_date <= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)), INTERVAL 0 DAY) 

This worked for me (Selects all records created from last month, regardless of the day you run the query this month)

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

you can make a function like this

function translateTo($language, $word) {  
   define('defaultLang','english');  
   if (isset($lang[$language][$word]) == FALSE)  
      return $lang[$language][$word];  
   else  
      return $lang[defaultLang][$word];  
}

Try catch statements in C

In C99, you can use setjmp/longjmp for non-local control flow.

Within a single scope, the generic, structured coding pattern for C in the presence of multiple resource allocations and multiple exits uses goto, like in this example. This is similar to how C++ implements destructor calls of automatic objects under the hood, and if you stick to this diligently, it should allow you for a certain degree of cleanness even in complex functions.

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

If this class is only a utility class, you should make the class final and define a private constructor:

public final class FilePathHelper {

   private FilePathHelper() {
      //not called
   }
}

This prevents the default parameter-less constructor from being used elsewhere in your code. Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.

Parallel.ForEach vs Task.Factory.StartNew

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

Removing All Items From A ComboBox?

I could not get clear to work. (Mac Excel) but this does.

ActiveSheet.DropDowns("CollectionComboBox").RemoveAllItems

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

ISO C90 forbids mixed declarations and code in C

Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99.

How to import jquery using ES6 syntax?

My project stack is: ParcelJS + WordPress

WordPress got jQuery v1.12.4 itself and I have also import jQuery v3^ as module for other depending modules as well as bootstrap/js/dist/collapse, for example... Unfortunately, I can’t leave only one jQuery version due to other WordPress modular dependencies. And ofcourse there is conflict arises between two jquery version. Also keep in mind we got two modes for this project running Wordpress(Apache) / ParcelJS (NodeJS), witch make everything little bit difficulty. So at solution for this conflict was searching, sometimes the project broke on the left, sometimes on the right side. SO... My finall solution (I hope it so...) is:

    import $ from 'jquery'
    import 'popper.js'
    import 'bootstrap/js/dist/collapse'
    import 'bootstrap/js/dist/dropdown'
    import 'signalr'

    if (typeof window.$ === 'undefined') {
        window.$ = window.jQ = $.noConflict(true);
    }

    if (process) {
        if (typeof window.jQuery === 'undefined') {
            window.$ = window.jQuery = $.noConflict(true);
        }
    }

    jQ('#some-id').do('something...')    

    /* Other app code continuous below.......... */

I still didn’t understand how myself, but this method works. Errors and conflicts of two jQuery version no longer arise

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

library not found for -lPods

I did open the workspace, but got the same error.

Build Active Architecture Only set to YES

solve my problem.

How to apply style classes to td classes?

Simply create a Class Name and define your style there like this :

table.tdfont td {
  font-size: 0.9em;
}

Interesting 'takes exactly 1 argument (2 given)' Python error

try using:

def extractAll(self,tag):

attention to self

Get the POST request body from HttpServletRequest

If all you want is the POST request body, you could use a method like this:

static String extractPostRequestBody(HttpServletRequest request) throws IOException {
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
    return "";
}

Credit to: https://stackoverflow.com/a/5445161/1389219

How to count how many values per level in a given factor?

Using data.table

 library(data.table)
 setDT(dat)[, .N, keyby=ID] #(Using @Paul Hiemstra's `dat`)

Or using dplyr 0.3

 res <- count(dat, ID)
 head(res)
 #Source: local data frame [6 x 2]

 #  ID n
 #1  a 2
 #2  b 3
 #3  c 3
 #4  d 3
 #5  e 2
 #6  f 4

Or

  dat %>% 
      group_by(ID) %>% 
      tally()

Or

  dat %>% 
      group_by(ID) %>%
      summarise(n=n())

removeEventListener on anonymous functions in JavaScript

window.document.onkeydown = function(){};

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

Try to set the property when starting JVM, for example, add -Djava.net.preferIPv4Stack=true.

You can't set it when code running, as the java.net just read it when jvm starting.

And about the root cause, this article give some hint: Why do I need java.net.preferIPv4Stack=true only on some windows 7 systems?.

Jenkins returned status code 128 with github

I changed the permission of my .ssh/id_rsa (private key) to 604. chmod 700 id_rsa

SQL: set existing column as Primary Key in MySQL

alter table table_name
add constraint myprimarykey primary key(column);

reference : http://www.w3schools.com/sql/sql_primarykey.asp

PostgreSQL Autoincrement

Starting with Postgres 10, identity columns as defined by the SQL standard are also supported:

create table foo 
(
  id integer generated always as identity
);

creates an identity column that can't be overridden unless explicitly asked for. The following insert will fail with a column defined as generated always:

insert into foo (id) 
values (1);

This can however be overruled:

insert into foo (id) overriding system value 
values (1);

When using the option generated by default this is essentially the same behaviour as the existing serial implementation:

create table foo 
(
  id integer generated by default as identity
);

When a value is supplied manually, the underlying sequence needs to be adjusted manually as well - the same as with a serial column.


An identity column is not a primary key by default (just like a serial column). If it should be one, a primary key constraint needs to be defined manually.

What methods of ‘clearfix’ can I use?

Assuming you're using this HTML structure:

<div id="container">
  <div id="content">
  </div>
  <div id="sidebar">
  </div>
</div>

Here's the CSS that I would use:

div#container {
    overflow: hidden;    /* makes element contain floated child elements */
}

div#content, div#sidebar {
    float: left;
    display: inline;    /* preemptively fixes IE6 dobule-margin bug */
}

I use this set all the time and it works fine for me, even in IE6.

Add single element to array in numpy

Try this:

np.concatenate((a, np.array([a[0]])))

http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

concatenate needs both elements to be numpy arrays; however, a[0] is not an array. That is why it does not work.

How to equalize the scales of x-axis and y-axis in Python matplotlib?

See the documentation on plt.axis(). This:

plt.axis('equal')

doesn't work because it changes the limits of the axis to make circles appear circular. What you want is:

plt.axis('square')

This creates a square plot with equal axes.

How to get enum value by string or int

You could use following method to do that:

public static Output GetEnumItem<Output, Input>(Input input)
    {
        //Output type checking...
        if (typeof(Output).BaseType != typeof(Enum))
            throw new Exception("Exception message...");

        //Input type checking: string type
        if (typeof(Input) == typeof(string))
            return (Output)Enum.Parse(typeof(Output), (dynamic)input);

        //Input type checking: Integer type
        if (typeof(Input) == typeof(Int16) ||
            typeof(Input) == typeof(Int32) ||
            typeof(Input) == typeof(Int64))

            return (Output)(dynamic)input;

        throw new Exception("Exception message...");
    }

Note:this method only is a sample and you can improve it.

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

How to get unique device hardware id in Android?

Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html

Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices

.

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

jQuery Dialog Box

If you need to use multiple dialog boxes on one page and open, close and reopen them the following works well:

 JS CODE:
    $(".sectionHelp").click(function(){
        $("#dialog_"+$(this).attr('id')).dialog({autoOpen: false});
        $("#dialog_"+$(this).attr('id')).dialog("open");
    });

 HTML: 
    <div class="dialog" id="dialog_help1" title="Dialog Title 1">
        <p>Dialog 1</p>
    </div>
    <div class="dialog" id="dialog_help2" title="Dialog Title 2">
        <p>Dialog 2 </p>
    </div>

    <a href="#" id="help1" class="sectionHelp"></a>
    <a href="#" id="help2" class="sectionHelp"></a>

 CSS:
    div.dialog{
      display:none;
    }

How do you clear the focus in javascript?

With jQuery its just: $(this).blur();

Changing .gitconfig location on Windows

  1. Change to folder %PROGRAMFILES%\Git\etc
  2. Edit file profile
  3. Add to first line HOME="c:\location_were_you_want_gitconfig"
  4. Done

Note: The file permissions are usually restricted, so change them accordingly or you won't be able to save your changes.

Any way to replace characters on Swift String?

you can test this:

let newString = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)

SQL Server procedure declare a list

If you want input comma separated string as input & apply in in query in that then you can make Function like:

create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))       
    returns @temptable TABLE (items varchar(MAX))       
    as       
    begin      
        declare @idx int       
        declare @slice varchar(8000)       

        select @idx = 1       
            if len(@String)<1 or @String is null  return       

        while @idx!= 0       
        begin       
            set @idx = charindex(@Delimiter,@String)       
            if @idx!=0       
                set @slice = left(@String,@idx - 1)       
            else       
                set @slice = @String       

            if(len(@slice)>0)  
                insert into @temptable(Items) values(@slice)       

            set @String = right(@String,len(@String) - @idx)       
            if len(@String) = 0 break       
        end   
    return 
    end;

You can use it like :

Declare @Values VARCHAR(MAX);

set @Values ='1,2,5,7,10';
Select * from DBTable
    Where id  in (select items from [dbo].[Split] (@Values, ',') )

Alternatively if you don't have comma-separated string as input, You can try Table variable OR TableType Or Temp table like: INSERT using LIST into Stored Procedure

How can I start PostgreSQL on Windows?

If you are getting an error "psql.exe' is not recognized as an internal or external command,... "

There can be : Causes

  • System is unable to find the psql.exe tool, because the path to this tool is not specified in the system environment variable PATH

or - PostgreSQL Database client not installed on your PC

Since you have already installed PostgreSQL the latter can not be the issue(assuming everything is installed as expected)

In order to fix the first one "please specify the full path to the bin directory in the PostgreSQL installation folder, where this tool resides."

For example

Path: "C:\Program Files\PostgreSQL\10\bin"

How do you do a ‘Pause’ with PowerShell 2.0?

cmd /c pause | out-null

(It is not the PowerShell way, but it's so much more elegant.)

Save trees. Use one-liners.

nvm is not compatible with the npm config "prefix" option:

This error can occur when your NVM installation folder path has a Symbolic Link.

Explanation

The default installation path of NVM is: $HOME/.nvm but your home folder could be a symbolic link for another drive, like my case.

Example, my home folder is a Symbolic Link to aother drive:

/home/myuser -> /bigdrive/myuser

This cause the prefix problem.

Solution

On your startup script (.bashrc or .zshrc or other), change the NVM folder to the direct path.

Ex: NVM_DIR="/bigdrive/myuser/.nvm".

.bashrc

export NVM_DIR="/bigdrive/myuser/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

Using an index to get an item, Python

You can use pop():

x=[2,3,4,5,6,7]
print(x.pop(2))

output is 4

Is there a good JavaScript minifier?

Active

Deprecated


Google Closure Compiler generally achieves smaller files than YUI Compressor, particularly if you use the advanced mode, which looks worryingly meddlesome to me but has worked well on the one project I've used it on:

Several big projects use UglifyJS, and I've been very impressed with it since switching.

Force a screen update in Excel VBA

Put a call to DoEvents in the loop.

This will affect performance, so you might want to only call it on each, say, 10th iteration.
However, if you only have 30, that's hardly an issue.

Why does Eclipse Java Package Explorer show question mark on some classes?

those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:

image describing Eclipse icons for Egit

  • dirty (folder) - At least one file below the folder is dirty; that means that it has changes in the working tree that are neither in the index nor in the repository.
  • tracked - The resource is known to the Git repository. untracked - The resource is not known to the Git repository.
  • ignored - The resource is ignored by the Git team provider. Here only the preference settings under Team -> Ignored Resources and the "derived" flag are relevant. The .gitignore file is not taken into account.
  • dirty - The resource has changes in the working tree that are neither in the index nor in the repository.
  • staged - The resource has changes which are added to the index. Not that adding to the index is possible at the moment only on the commit dialog on the context menu of a resource.
  • partially-staged - The resource has changes which are added to the index and additionally changes in the working tree that are neither in the index nor in the repository.
  • added - The resource is not yet tracked by but added to the Git repository.
  • removed - The resource is staged for removal from the Git repository.
  • conflict - A merge conflict exists for the file.
  • assume-valid - The resource has the "assume unchanged" flag. This means that Git stops checking the working tree files for possible modifications, so you need to manually unset the bit to tell Git when you change the working tree file. This setting can be switched on with the menu action Team->Assume unchanged (or on the command line with git update-index--assume-unchanged).

What is the difference between :focus and :active?

:active       Adds a style to an element that is activated
:focus        Adds a style to an element that has keyboard input focus
:hover        Adds a style to an element when you mouse over it
:lang         Adds a style to an element with a specific lang attribute
:link         Adds a style to an unvisited link
:visited      Adds a style to a visited link

Source: CSS Pseudo-classes

Negation in Python

Combining the input from everyone else (use not, no parens, use os.mkdir) you'd get...

special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
    os.mkdir(special_path_for_john)

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I've solved this problem by configuring MySQL.

SET GLOBAL time_zone = '+3:00';

How would you do a "not in" query with LINQ?

One could also use All()

var notInList = list1.Where(p => list2.All(p2 => p2.Email != p.Email));

Why javascript getTime() is not a function?

For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.

I was facing this error because I tried to compare two dates using the following Method

var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator

However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.

Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime() method was simply not added to the prototype.

Solution

In this case, recreating a date-Object based on your dates will fix the issue.

var res = new Date(dat1).getTime() > new Date(dat2).getTime()

Edit:

I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.

The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.

class Details {
    description: string;
    date: Date;
    score: number;
    approved: boolean;

    constructor(data: any) {
      Object.assign(this, data);
    }
}

and to perform the mapping:

public getDetails(id: number): Promise<Details> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details/${id}`)
               .map(response => new Details(response.json()))
               .toPromise();
}

for arrays use:

public getDetails(): Promise<Details[]> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details`)
               .map(response => {
                   const array = JSON.parse(response.json()) as any[];
                   const details = array.map(data => new Details(data));
                   return details;
               })
               .toPromise();
}

For credits and further information about this topic follow the link.

How to modify JsonNode in Java?

Just for the sake of understanding of others who may not get the whole picture clear following code works for me to find a field and then update it

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(JsonString);    
JsonPointer valueNodePointer = JsonPointer.compile("/GrandObj/Obj/field");
JsonPointer containerPointer = valueNodePointer.head();
JsonNode parentJsonNode = rootNode.at(containerPointer);

if (!parentJsonNode.isMissingNode() && parentJsonNode.isObject()) {
    ObjectNode parentObjectNode = (ObjectNode) parentJsonNode;
    //following will give you just the field name. 
    //e.g. if pointer is /grandObject/Object/field
    //JsonPoint.last() will give you /field 
    //remember to take out the / character 
    String fieldName = valueNodePointer.last().toString();
    fieldName = fieldName.replace(Character.toString(JsonPointer.SEPARATOR), StringUtils.EMPTY);
    JsonNode fieldValueNode = parentObjectNode.get(fieldName);

    if(fieldValueNode != null) {
        parentObjectNode.put(fieldName, "NewValue");
    }
}

Reading serial data in realtime in Python

A very good solution to this can be found here:

Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs, self.s.read(i) returns an empty string and you might want to throw an exception to indicate the timeout.

It is also supposed to be fast according to the author:

The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.

class ReadLine:
    def __init__(self, s):
        self.buf = bytearray()
        self.s = s

    def readline(self):
        i = self.buf.find(b"\n")
        if i >= 0:
            r = self.buf[:i+1]
            self.buf = self.buf[i+1:]
            return r
        while True:
            i = max(1, min(2048, self.s.in_waiting))
            data = self.s.read(i)
            i = data.find(b"\n")
            if i >= 0:
                r = self.buf + data[:i+1]
                self.buf[0:] = data[i+1:]
                return r
            else:
                self.buf.extend(data)

ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)

while True:

    print(rl.readline())

CSS Div stretch 100% page height

I ran into the same problem as you. I wanted to make a DIV as background, why, because its easy to manipulate div through javascript. Anyways three things I did in the css for that div.

CSS:

{    
position:absolute; 
display:block; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
z-index:-1;    
}

Materialize CSS - Select Doesn't Seem to Render

For me none of the other answers worked because I am using the latest version of MaterializeCSS and Meteor and there is incompatability between the jquery versions, Meteor 1.1.10 uses jquery 1.11 (overriding this dependancy is not easy and will probably break Meteor/Blaze) and testing Materialise with jquery 2.2 works fine. See https://stackoverflow.com/a/34809976/2882279 for more info.

This is a known issue with dropdowns and selects in materialize 0.97.2 and 0.97.3; for more info see https://github.com/Dogfalo/materialize/issues/2265 and https://github.com/Dogfalo/materialize/commit/45feae64410252fe51e56816e664c09d83dc8931.

I'm using the Sass version of MaterializeCSS in Meteor and worked around the problem by using poetic:[email protected] in my meteor packages file to force the old version. The dropdowns now work, old jquery and all!

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

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

Ruby String to Date Conversion

What is wrong with Date.parse method?

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
date = Date.parse str
=> #<Date: 4910837/2,0,2299161>
puts date
2010-08-10

It seems to work.

The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time object, suppose we have string:

str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10
puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

I couldn't find simpler method to convert Time to Date.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Setting up SSL on a local xampp/apache server

It turns out that OpenSSL is compiled and enabled in php 5.3 of XAMPP 1.7.2 and so no longer requires a separate extension dll.

However, you STILL need to enable it in your PHP.ini file the line extension=php_openssl.dll

What is the Windows version of cron?

Check out the excellent Cronical program at https://github.com/mgefvert/Cronical

It is a .NET program that reads a text file with unix-like cron lines. Very convenient to use. It will send emails if stdout just like unix cron. It even supports acting as the service runner.

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

file_put_contents(meta/services.json): failed to open stream: Permission denied

Try again with chmod -R 755 /var/www/html/test/app/storage. Use with sudo for Operation not permitted in chmod. Use Check owner permission if still having the error.

Swift Alamofire: How to get the HTTP response status code

Best way to get the status code using alamofire.

 Alamofire.request(URL).responseJSON {
  response in

  let status = response.response?.statusCode
  print("STATUS \(status)")

}

Java Class.cast() vs. cast operator

In addition to remove ugly cast warnings as most mentioned ,Class.cast is run-time cast mostly used with generic casting ,due to generic info will be erased at run time and some how each generic will be considered Object , this leads to not to throw an early ClassCastException.

for example serviceLoder use this trick when creating the objects,check S p = service.cast(c.newInstance()); this will throw a class cast exception when S P =(S) c.newInstance(); won't and may show a warning 'Type safety: Unchecked cast from Object to S'.(same as Object P =(Object) c.newInstance();)

-simply it checks that the casted object is instance of casting class then it will use the cast operator to cast and hide the warning by suppressing it.

java implementation for dynamic cast:

@SuppressWarnings("unchecked")
public T cast(Object obj) {
    if (obj != null && !isInstance(obj))
        throw new ClassCastException(cannotCastMsg(obj));
    return (T) obj;
}




    private S nextService() {
        if (!hasNextService())
            throw new NoSuchElementException();
        String cn = nextName;
        nextName = null;
        Class<?> c = null;
        try {
            c = Class.forName(cn, false, loader);
        } catch (ClassNotFoundException x) {
            fail(service,
                 "Provider " + cn + " not found");
        }
        if (!service.isAssignableFrom(c)) {
            fail(service,
                 "Provider " + cn  + " not a subtype");
        }
        try {
            S p = service.cast(c.newInstance());
            providers.put(cn, p);
            return p;
        } catch (Throwable x) {
            fail(service,
                 "Provider " + cn + " could not be instantiated",
                 x);
        }
        throw new Error();          // This cannot happen
    }

How to pass all arguments passed to my bash script to a function of mine?

abc "$@"

$@ represents all the parameters given to your bash script.

Jenkins could not run git

I had similar problem, the solution for Windows looks the same (my Jenkins is installed on a Windows machine):

Global settings:

Go to Manage jenkins -> Configure System -> Git installations add there the git exe path (for example: C:\Program Files\Git\bin\git.exe), or you can use environment variable.

For Jenkins version 2.121.3, Go to Manage jenkins -> Global tool configuration -> Git installations -> Path to Git executable: C:\Program Files\Git\bin\git.exe

Jenkins job side:

Go to Source code Management -> select git, add your repository, choose connection to repository (http/ssh) and add credentials and it should work.

How do I use extern to share variables between source files?

Using extern is only of relevance when the program you're building consists of multiple source files linked together, where some of the variables defined, for example, in source file file1.c need to be referenced in other source files, such as file2.c.

It is important to understand the difference between defining a variable and declaring a variable:

  • A variable is declared when the compiler is informed that a variable exists (and this is its type); it does not allocate the storage for the variable at that point.

  • A variable is defined when the compiler allocates the storage for the variable.

You may declare a variable multiple times (though once is sufficient); you may only define it once within a given scope. A variable definition is also a declaration, but not all variable declarations are definitions.

Best way to declare and define global variables

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable.

The header is included by the one source file that defines the variable and by all the source files that reference the variable. For each program, one source file (and only one source file) defines the variable. Similarly, one header file (and only one header file) should declare the variable. The header file is crucial; it enables cross-checking between independent TUs (translation units — think source files) and ensures consistency.

Although there are other ways of doing it, this method is simple and reliable. It is demonstrated by file3.h, file1.c and file2.c:

file3.h

extern int global_variable;  /* Declaration of the variable */

file1.c

#include "file3.h"  /* Declaration made available here */
#include "prog1.h"  /* Function declarations */

/* Variable defined here */
int global_variable = 37;    /* Definition checked against declaration */

int increment(void) { return global_variable++; }

file2.c

#include "file3.h"
#include "prog1.h"
#include <stdio.h>

void use_it(void)
{
    printf("Global variable: %d\n", global_variable++);
}

That's the best way to declare and define global variables.


The next two files complete the source for prog1:

The complete programs shown use functions, so function declarations have crept in. Both C99 and C11 require functions to be declared or defined before they are used (whereas C90 did not, for good reasons). I use the keyword extern in front of function declarations in headers for consistency — to match the extern in front of variable declarations in headers. Many people prefer not to use extern in front of function declarations; the compiler doesn't care — and ultimately, neither do I as long as you're consistent, at least within a source file.

prog1.h

extern void use_it(void);
extern int increment(void);

prog1.c

#include "file3.h"
#include "prog1.h"
#include <stdio.h>

int main(void)
{
    use_it();
    global_variable += 19;
    use_it();
    printf("Increment: %d\n", increment());
    return 0;
}
  • prog1 uses prog1.c, file1.c, file2.c, file3.h and prog1.h.

The file prog1.mk is a makefile for prog1 only. It will work with most versions of make produced since about the turn of the millennium. It is not tied specifically to GNU Make.

prog1.mk

# Minimal makefile for prog1

PROGRAM = prog1
FILES.c = prog1.c file1.c file2.c
FILES.h = prog1.h file3.h
FILES.o = ${FILES.c:.c=.o}

CC      = gcc
SFLAGS  = -std=c11
GFLAGS  = -g
OFLAGS  = -O3
WFLAG1  = -Wall
WFLAG2  = -Wextra
WFLAG3  = -Werror
WFLAG4  = -Wstrict-prototypes
WFLAG5  = -Wmissing-prototypes
WFLAGS  = ${WFLAG1} ${WFLAG2} ${WFLAG3} ${WFLAG4} ${WFLAG5}
UFLAGS  = # Set on command line only

CFLAGS  = ${SFLAGS} ${GFLAGS} ${OFLAGS} ${WFLAGS} ${UFLAGS}
LDFLAGS =
LDLIBS  =

all:    ${PROGRAM}

${PROGRAM}: ${FILES.o}
    ${CC} -o $@ ${CFLAGS} ${FILES.o} ${LDFLAGS} ${LDLIBS}

prog1.o: ${FILES.h}
file1.o: ${FILES.h}
file2.o: ${FILES.h}

# If it exists, prog1.dSYM is a directory on macOS
DEBRIS = a.out core *~ *.dSYM
RM_FR  = rm -fr

clean:
    ${RM_FR} ${FILES.o} ${PROGRAM} ${DEBRIS}


Guidelines

Rules to be broken by experts only, and only with good reason:

  • A header file only contains extern declarations of variables — never static or unqualified variable definitions.

  • For any given variable, only one header file declares it (SPOT — Single Point of Truth).

  • A source file never contains extern declarations of variables — source files always include the (sole) header that declares them.

  • For any given variable, exactly one source file defines the variable, preferably initializing it too. (Although there is no need to initialize explicitly to zero, it does no harm and can do some good, because there can be only one initialized definition of a particular global variable in a program).

  • The source file that defines the variable also includes the header to ensure that the definition and the declaration are consistent.

  • A function should never need to declare a variable using extern.

  • Avoid global variables whenever possible — use functions instead.

The source code and text of this answer are available in my SOQ (Stack Overflow Questions) repository on GitHub in the src/so-0143-3204 sub-directory.

If you're not an experienced C programmer, you could (and perhaps should) stop reading here.

Not so good way to define global variables

With some (indeed, many) C compilers, you can get away with what's called a 'common' definition of a variable too. 'Common', here, refers to a technique used in Fortran for sharing variables between source files, using a (possibly named) COMMON block. What happens here is that each of a number of files provides a tentative definition of the variable. As long as no more than one file provides an initialized definition, then the various files end up sharing a common single definition of the variable:

file10.c

#include "prog2.h"

long l;   /* Do not do this in portable code */

void inc(void) { l++; }

file11.c

#include "prog2.h"

long l;   /* Do not do this in portable code */

void dec(void) { l--; }

file12.c

#include "prog2.h"
#include <stdio.h>

long l = 9;   /* Do not do this in portable code */

void put(void) { printf("l = %ld\n", l); }

This technique does not conform to the letter of the C standard and the 'one definition rule' — it is officially undefined behaviour:

J.2 Undefined behavior

An identifier with external linkage is used, but in the program there does not exist exactly one external definition for the identifier, or the identifier is not used and there exist multiple external definitions for the identifier (6.9).

§6.9 External definitions ¶5

An external definition is an external declaration that is also a definition of a function (other than an inline definition) or an object. If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof or _Alignof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one.161)

161) Thus, if an identifier declared with external linkage is not used in an expression, there need be no external definition for it.

However, the C standard also lists it in informative Annex J as one of the Common extensions.

J.5.11 Multiple external definitions

There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).

Because this technique is not always supported, it is best to avoid using it, especially if your code needs to be portable. Using this technique, you can also end up with unintentional type punning.

If one of the files above declared l as a double instead of as a long, C's type-unsafe linkers probably would not spot the mismatch. If you're on a machine with 64-bit long and double, you'd not even get a warning; on a machine with 32-bit long and 64-bit double, you'd probably get a warning about the different sizes — the linker would use the largest size, exactly as a Fortran program would take the largest size of any common blocks.

Note that GCC 10.1.0, which was released on 2020-05-07, changes the default compilation options to use -fno-common, which means that by default, the code above no longer links unless you override the default with -fcommon (or use attributes, etc — see the link).


The next two files complete the source for prog2:

prog2.h

extern void dec(void);
extern void put(void);
extern void inc(void);

prog2.c

#include "prog2.h"
#include <stdio.h>

int main(void)
{
    inc();
    put();
    dec();
    put();
    dec();
    put();
}
  • prog2 uses prog2.c, file10.c, file11.c, file12.c, prog2.h.

Warning

As noted in comments here, and as stated in my answer to a similar question, using multiple definitions for a global variable leads to undefined behaviour (J.2; §6.9), which is the standard's way of saying "anything could happen". One of the things that can happen is that the program behaves as you expect; and J.5.11 says, approximately, "you might be lucky more often than you deserve". But a program that relies on multiple definitions of an extern variable — with or without the explicit 'extern' keyword — is not a strictly conforming program and not guaranteed to work everywhere. Equivalently: it contains a bug which may or may not show itself.

Violating the guidelines

There are, of course, many ways in which these guidelines can be broken. Occasionally, there may be a good reason to break the guidelines, but such occasions are extremely unusual.

faulty_header.h

int some_var;    /* Do not do this in a header!!! */

Note 1: if the header defines the variable without the extern keyword, then each file that includes the header creates a tentative definition of the variable. As noted previously, this will often work, but the C standard does not guarantee that it will work.

broken_header.h

int some_var = 13;    /* Only one source file in a program can use this */

Note 2: if the header defines and initializes the variable, then only one source file in a given program can use the header. Since headers are primarily for sharing information, it is a bit silly to create one that can only be used once.

seldom_correct.h

static int hidden_global = 3;   /* Each source file gets its own copy  */

Note 3: if the header defines a static variable (with or without initialization), then each source file ends up with its own private version of the 'global' variable.

If the variable is actually a complex array, for example, this can lead to extreme duplication of code. It can, very occasionally, be a sensible way to achieve some effect, but that is very unusual.


Summary

Use the header technique I showed first. It works reliably and everywhere. Note, in particular, that the header declaring the global_variable is included in every file that uses it — including the one that defines it. This ensures that everything is self-consistent.

Similar concerns arise with declaring and defining functions — analogous rules apply. But the question was about variables specifically, so I've kept the answer to variables only.

End of Original Answer

If you're not an experienced C programmer, you probably should stop reading here.


Late Major Addition

Avoiding Code Duplication

One concern that is sometimes (and legitimately) raised about the 'declarations in headers, definitions in source' mechanism described here is that there are two files to be kept synchronized — the header and the source. This is usually followed up with an observation that a macro can be used so that the header serves double duty — normally declaring the variables, but when a specific macro is set before the header is included, it defines the variables instead.

Another concern can be that the variables need to be defined in each of a number of 'main programs'. This is normally a spurious concern; you can simply introduce a C source file to define the variables and link the object file produced with each of the programs.

A typical scheme works like this, using the original global variable illustrated in file3.h:

file3a.h

#ifdef DEFINE_VARIABLES
#define EXTERN /* nothing */
#else
#define EXTERN extern
#endif /* DEFINE_VARIABLES */

EXTERN int global_variable;

file1a.c

#define DEFINE_VARIABLES
#include "file3a.h"  /* Variable defined - but not initialized */
#include "prog3.h"

int increment(void) { return global_variable++; }

file2a.c

#include "file3a.h"
#include "prog3.h"
#include <stdio.h>

void use_it(void)
{
    printf("Global variable: %d\n", global_variable++);
}

The next two files complete the source for prog3:

prog3.h

extern void use_it(void);
extern int increment(void);

prog3.c

#include "file3a.h"
#include "prog3.h"
#include <stdio.h>

int main(void)
{
    use_it();
    global_variable += 19;
    use_it();
    printf("Increment: %d\n", increment());
    return 0;
}
  • prog3 uses prog3.c, file1a.c, file2a.c, file3a.h, prog3.h.

Variable initialization

The problem with this scheme as shown is that it does not provide for initialization of the global variable. With C99 or C11 and variable argument lists for macros, you could define a macro to support initialization too. (With C89 and no support for variable argument lists in macros, there is no easy way to handle arbitrarily long initializers.)

file3b.h

#ifdef DEFINE_VARIABLES
#define EXTERN                  /* nothing */
#define INITIALIZER(...)        = __VA_ARGS__
#else
#define EXTERN                  extern
#define INITIALIZER(...)        /* nothing */
#endif /* DEFINE_VARIABLES */

EXTERN int global_variable INITIALIZER(37);
EXTERN struct { int a; int b; } oddball_struct INITIALIZER({ 41, 43 });

Reverse contents of #if and #else blocks, fixing bug identified by Denis Kniazhev

file1b.c

#define DEFINE_VARIABLES
#include "file3b.h"  /* Variables now defined and initialized */
#include "prog4.h"

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }

file2b.c

#include "file3b.h"
#include "prog4.h"
#include <stdio.h>

void use_them(void)
{
    printf("Global variable: %d\n", global_variable++);
    oddball_struct.a += global_variable;
    oddball_struct.b -= global_variable / 2;
}

Clearly, the code for the oddball structure is not what you'd normally write, but it illustrates the point. The first argument to the second invocation of INITIALIZER is { 41 and the remaining argument (singular in this example) is 43 }. Without C99 or similar support for variable argument lists for macros, initializers that need to contain commas are very problematic.

Correct header file3b.h included (instead of fileba.h) per Denis Kniazhev


The next two files complete the source for prog4:

prog4.h

extern int increment(void);
extern int oddball_value(void);
extern void use_them(void);

prog4.c

#include "file3b.h"
#include "prog4.h"
#include <stdio.h>

int main(void)
{
    use_them();
    global_variable += 19;
    use_them();
    printf("Increment: %d\n", increment());
    printf("Oddball:   %d\n", oddball_value());
    return 0;
}
  • prog4 uses prog4.c, file1b.c, file2b.c, prog4.h, file3b.h.

Header Guards

Any header should be protected against reinclusion, so that type definitions (enum, struct or union types, or typedefs generally) do not cause problems. The standard technique is to wrap the body of the header in a header guard such as:

#ifndef FILE3B_H_INCLUDED
#define FILE3B_H_INCLUDED

...contents of header...

#endif /* FILE3B_H_INCLUDED */

The header might be included twice indirectly. For example, if file4b.h includes file3b.h for a type definition that isn't shown, and file1b.c needs to use both header file4b.h and file3b.h, then you have some more tricky issues to resolve. Clearly, you might revise the header list to include just file4b.h. However, you might not be aware of the internal dependencies — and the code should, ideally, continue to work.

Further, it starts to get tricky because you might include file4b.h before including file3b.h to generate the definitions, but the normal header guards on file3b.h would prevent the header being reincluded.

So, you need to include the body of file3b.h at most once for declarations, and at most once for definitions, but you might need both in a single translation unit (TU — a combination of a source file and the headers it uses).

Multiple inclusion with variable definitions

However, it can be done subject to a not too unreasonable constraint. Let's introduce a new set of file names:

  • external.h for the EXTERN macro definitions, etc.

  • file1c.h to define types (notably, struct oddball, the type of oddball_struct).

  • file2c.h to define or declare the global variables.

  • file3c.c which defines the global variables.

  • file4c.c which simply uses the global variables.

  • file5c.c which shows that you can declare and then define the global variables.

  • file6c.c which shows that you can define and then (attempt to) declare the global variables.

In these examples, file5c.c and file6c.c directly include the header file2c.h several times, but that is the simplest way to show that the mechanism works. It means that if the header was indirectly included twice, it would also be safe.

The restrictions for this to work are:

  1. The header defining or declaring the global variables may not itself define any types.

  2. Immediately before you include a header that should define variables, you define the macro DEFINE_VARIABLES.

  3. The header defining or declaring the variables has stylized contents.

external.h

/*
** This header must not contain header guards (like <assert.h> must not).
** Each time it is invoked, it redefines the macros EXTERN, INITIALIZE
** based on whether macro DEFINE_VARIABLES is currently defined.
*/
#undef EXTERN
#undef INITIALIZE

#ifdef DEFINE_VARIABLES
#define EXTERN              /* nothing */
#define INITIALIZE(...)     = __VA_ARGS__
#else
#define EXTERN              extern
#define INITIALIZE(...)     /* nothing */
#endif /* DEFINE_VARIABLES */

file1c.h

#ifndef FILE1C_H_INCLUDED
#define FILE1C_H_INCLUDED

struct oddball
{
    int a;
    int b;
};

extern void use_them(void);
extern int increment(void);
extern int oddball_value(void);

#endif /* FILE1C_H_INCLUDED */

file2c.h


/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE2C_H_DEFINITIONS)
#undef FILE2C_H_INCLUDED
#endif

#ifndef FILE2C_H_INCLUDED
#define FILE2C_H_INCLUDED

#include "external.h"   /* Support macros EXTERN, INITIALIZE */
#include "file1c.h"     /* Type definition for struct oddball */

#if !defined(DEFINE_VARIABLES) || !defined(FILE2C_H_DEFINITIONS)

/* Global variable declarations / definitions */
EXTERN int global_variable INITIALIZE(37);
EXTERN struct oddball oddball_struct INITIALIZE({ 41, 43 });

#endif /* !DEFINE_VARIABLES || !FILE2C_H_DEFINITIONS */

/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE2C_H_DEFINITIONS
#endif /* DEFINE_VARIABLES */

#endif /* FILE2C_H_INCLUDED */

file3c.c

#define DEFINE_VARIABLES
#include "file2c.h"  /* Variables now defined and initialized */

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }

file4c.c

#include "file2c.h"
#include <stdio.h>

void use_them(void)
{
    printf("Global variable: %d\n", global_variable++);
    oddball_struct.a += global_variable;
    oddball_struct.b -= global_variable / 2;
}

file5c.c


#include "file2c.h"     /* Declare variables */

#define DEFINE_VARIABLES
#include "file2c.h"  /* Variables now defined and initialized */

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }

file6c.c


#define DEFINE_VARIABLES
#include "file2c.h"     /* Variables now defined and initialized */

#include "file2c.h"     /* Declare variables */

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }


The next source file completes the source (provides a main program) for prog5, prog6 and prog7:

prog5.c

#include "file2c.h"
#include <stdio.h>

int main(void)
{
    use_them();
    global_variable += 19;
    use_them();
    printf("Increment: %d\n", increment());
    printf("Oddball:   %d\n", oddball_value());
    return 0;
}
  • prog5 uses prog5.c, file3c.c, file4c.c, file1c.h, file2c.h, external.h.

  • prog6 uses prog5.c, file5c.c, file4c.c, file1c.h, file2c.h, external.h.

  • prog7 uses prog5.c, file6c.c, file4c.c, file1c.h, file2c.h, external.h.


This scheme avoids most problems. You only run into a problem if a header that defines variables (such as file2c.h) is included by another header (say file7c.h) that defines variables. There isn't an easy way around that other than "don't do it".

You can partially work around the problem by revising file2c.h into file2d.h:

file2d.h

/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE2D_H_DEFINITIONS)
#undef FILE2D_H_INCLUDED
#endif

#ifndef FILE2D_H_INCLUDED
#define FILE2D_H_INCLUDED

#include "external.h"   /* Support macros EXTERN, INITIALIZE */
#include "file1c.h"     /* Type definition for struct oddball */

#if !defined(DEFINE_VARIABLES) || !defined(FILE2D_H_DEFINITIONS)

/* Global variable declarations / definitions */
EXTERN int global_variable INITIALIZE(37);
EXTERN struct oddball oddball_struct INITIALIZE({ 41, 43 });

#endif /* !DEFINE_VARIABLES || !FILE2D_H_DEFINITIONS */

/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE2D_H_DEFINITIONS
#undef DEFINE_VARIABLES
#endif /* DEFINE_VARIABLES */

#endif /* FILE2D_H_INCLUDED */

The issue becomes 'should the header include #undef DEFINE_VARIABLES?' If you omit that from the header and wrap any defining invocation with #define and #undef:

#define DEFINE_VARIABLES
#include "file2c.h"
#undef DEFINE_VARIABLES

in the source code (so the headers never alter the value of DEFINE_VARIABLES), then you should be clean. It is just a nuisance to have to remember to write the the extra line. An alternative might be:

#define HEADER_DEFINING_VARIABLES "file2c.h"
#include "externdef.h"

externdef.h

/*
** This header must not contain header guards (like <assert.h> must not).
** Each time it is included, the macro HEADER_DEFINING_VARIABLES should
** be defined with the name (in quotes - or possibly angle brackets) of
** the header to be included that defines variables when the macro
** DEFINE_VARIABLES is defined.  See also: external.h (which uses
** DEFINE_VARIABLES and defines macros EXTERN and INITIALIZE
** appropriately).
**
** #define HEADER_DEFINING_VARIABLES "file2c.h"
** #include "externdef.h"
*/

#if defined(HEADER_DEFINING_VARIABLES)
#define DEFINE_VARIABLES
#include HEADER_DEFINING_VARIABLES
#undef DEFINE_VARIABLES
#undef HEADER_DEFINING_VARIABLES
#endif /* HEADER_DEFINING_VARIABLES */

This is getting a tad convoluted, but seems to be secure (using the file2d.h, with no #undef DEFINE_VARIABLES in the file2d.h).

file7c.c

/* Declare variables */
#include "file2d.h"

/* Define variables */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"

/* Declare variables - again */
#include "file2d.h"

/* Define variables - again */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }

file8c.h

/* Standard prologue */
#if defined(DEFINE_VARIABLES) && !defined(FILE8C_H_DEFINITIONS)
#undef FILE8C_H_INCLUDED
#endif

#ifndef FILE8C_H_INCLUDED
#define FILE8C_H_INCLUDED

#include "external.h"   /* Support macros EXTERN, INITIALIZE */
#include "file2d.h"     /* struct oddball */

#if !defined(DEFINE_VARIABLES) || !defined(FILE8C_H_DEFINITIONS)

/* Global variable declarations / definitions */
EXTERN struct oddball another INITIALIZE({ 14, 34 });

#endif /* !DEFINE_VARIABLES || !FILE8C_H_DEFINITIONS */

/* Standard epilogue */
#ifdef DEFINE_VARIABLES
#define FILE8C_H_DEFINITIONS
#endif /* DEFINE_VARIABLES */

#endif /* FILE8C_H_INCLUDED */

file8c.c

/* Define variables */
#define HEADER_DEFINING_VARIABLES "file2d.h"
#include "externdef.h"

/* Define variables */
#define HEADER_DEFINING_VARIABLES "file8c.h"
#include "externdef.h"

int increment(void) { return global_variable++; }
int oddball_value(void) { return oddball_struct.a + oddball_struct.b; }


The next two files complete the source for prog8 and prog9:

prog8.c

#include "file2d.h"
#include <stdio.h>

int main(void)
{
    use_them();
    global_variable += 19;
    use_them();
    printf("Increment: %d\n", increment());
    printf("Oddball:   %d\n", oddball_value());
    return 0;
}

file9c.c

#include "file2d.h"
#include <stdio.h>

void use_them(void)
{
    printf("Global variable: %d\n", global_variable++);
    oddball_struct.a += global_variable;
    oddball_struct.b -= global_variable / 2;
}

  • prog8 uses prog8.c, file7c.c, file9c.c.

  • prog9 uses prog8.c, file8c.c, file9c.c.


However, the problems are relatively unlikely to occur in practice, especially if you take the standard advice to

A

Show/hide image with JavaScript

HTML

<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>

JavaScript:

document.getElementById("showImage").onclick = function() {
    document.getElementById("theImage").style.display = "block";
}

CSS:

#theImage { display:none; }

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

If you want to add magic comments on all the source files of a project easily, you can use the magic_encoding gem

sudo gem install magic_encoding

then just call magic_encoding in the terminal from the root of your app.

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

Hopefully it helps someone: I ran into this error and the cause was wrong permission on the log folder for phpfpm, after changing it so phpfpm could write to it, everything was fine.

ERROR 1049 (42000): Unknown database 'mydatabasename'

Open the sql file and comment out the line that tries to create the existing database and remove USE mydatabasename and try again.

How to send a JSON object using html form data

You can try something like:

<html>
<head>
    <title>test</title>
</head>

<body>
    <form id="formElem">
        <input type="text" name="firstname" value="Karam">
        <input type="text" name="lastname" value="Yousef">
        <input type="submit">
    </form>
    <div id="decoded"></div>
    <button id="encode">Encode</button>
    <div id="encoded"></div>
</body>
<script>
    encode.onclick = async (e) => {
        let response = await fetch('http://localhost:8482/encode', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
        })

        let text = await response.text(); // read response body as text
        data = JSON.parse(text);
        document.querySelector("#encoded").innerHTML = text;
      //  document.querySelector("#encoded").innerHTML = `First name = ${data.firstname} <br/> 
      //                                                  Last name = ${data.lastname} <br/>
      //                                                  Age    = ${data.age}`
    };

    formElem.onsubmit = async (e) => {
      e.preventDefault();
      var form = document.querySelector("#formElem");
     // var form = document.forms[0];

        data = {
          firstname : form.querySelector('input[name="firstname"]').value,
          lastname : form.querySelector('input[name="lastname"]').value,
          age : 5
        }

        let response = await fetch('http://localhost:8482/decode', {
                method: 'POST', // or 'PUT'
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
        })

        let text = await response.text(); // read response body as text
        document.querySelector("#decoded").innerHTML = text;
    };
</script>
</html>

Calling startActivity() from outside of an Activity context

Instead of using (getApplicationContext) use YourActivity.this

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

Cross Browser Flash Detection in Javascript

I agree with Max Stewart. SWFObject is the way to go. I'd like to supplement his answer with a code example. This ought to to get you started:

Make sure you have included the swfobject.js file (get it here):

<script type="text/javascript" src="swfobject.js"></script>

Then use it like so:

if(swfobject.hasFlashPlayerVersion("9.0.115"))
{
    alert("You have the minimum required flash version (or newer)");
}
else
{
    alert("You do not have the minimum required flash version");
}

Replace "9.0.115" with whatever minimum flash version you need. I chose 9.0.115 as an example because that's the version that added h.264 support.

If the visitor does not have flash, it will report a flash version of "0.0.0", so if you just want to know if they have flash at all, use:

if(swfobject.hasFlashPlayerVersion("1"))
{
    alert("You have flash!");
}
else
{
    alert("You do not flash :-(");
}

Java Program to test if a character is uppercase/lowercase/number/vowel

This may not be what you are looking for but I thought you oughta know the real way to do this. You can use the java.lang.Character class's isUpperCase() to find aout about the case of the character. You can use isDigit() to differentiate between the numbers and letters(This is just FYI :) ). You can then do a toUpperCase() and then do the switch for vowels. This will improve your code quality.

In php, is 0 treated as empty?

To accept 0 as a value in variable use isset

Check if variable is empty

$var = 0;

if ($var == '') {
    echo "empty";
} else {
    echo "not empty"; 
}
//output is empty

Check if variable is set

$var = 0;

if (isset($var)) {
    echo "not empty";
} else {    
    echo "empty";
}
//output is not empty

Illegal Escape Character "\"

Use "\\" to escape the \ character.

Comparing date part only without comparing time in JavaScript

I'm still learning JavaScript, and the only way that I've found which works for me to compare two dates without the time is to use the setHours method of the Date object and set the hours, minutes, seconds and milliseconds to zero. Then compare the two dates.

For example,

date1 = new Date()
date2 = new Date(2011,8,20)

date2 will be set with hours, minutes, seconds and milliseconds to zero, but date1 will have them set to the time that date1 was created. To get rid of the hours, minutes, seconds and milliseconds on date1 do the following:

date1.setHours(0,0,0,0)

Now you can compare the two dates as DATES only without worrying about time elements.

Trim specific character from a string

"|Howdy".replace(new RegExp("^\\|"),"");

(note the double escaping. \\ needed, to have an actually single slash in the string, that then leads to escaping of | in the regExp).

Only few characters need regExp-Escaping., among them the pipe operator.

Remove gutter space for a specific div only

Simplest way to remove padding and margin is with simple css.

<div class="header" style="margin:0px;padding:0px;">
.....
.....
.....
</div>

Random strings in Python

In python3.6+ you can use the secrets module:

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

In testing generation of 768bit security tokens I found:

  • random.choices() - 0.000246 secs
  • secrets.choice() - 0.003529 secs

The secrets modules is slower but outside of testing it is what you should be using for cryptographic purposes:

import string, secrets

def random_string(size):        
        letters = string.ascii_lowercase+string.ascii_uppercase+string.digits            
        return ''.join(secrets.choice(letters) for i in range(size))

print(random_string(768))

Reading from memory stream to string

string result = System.Text.Encoding.UTF8.GetString(fs.ToArray());

Regex to extract substring, returning 2 results for some reason

I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.

What does servletcontext.getRealPath("/") mean and when should I use it

My Method:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        String path = request.getRealPath("/WEB-INF/conf.properties");
        Properties p = new Properties();
        p.load(new FileInputStream(path));

        String StringConexion=p.getProperty("StringConexion");
        String User=p.getProperty("User");
        String Password=p.getProperty("Password");
    }
    catch(Exception e){
        String msg = "Excepcion " + e;
    }
}

Pandas get topmost n records within each group

Did you try df.groupby('id').head(2)

Ouput generated:

>>> df.groupby('id').head(2)
       id  value
id             
1  0   1      1
   1   1      2 
2  3   2      1
   4   2      2
3  7   3      1
4  8   4      1

(Keep in mind that you might need to order/sort before, depending on your data)

EDIT: As mentioned by the questioner, use df.groupby('id').head(2).reset_index(drop=True) to remove the multindex and flatten the results.

>>> df.groupby('id').head(2).reset_index(drop=True)
    id  value
0   1      1
1   1      2
2   2      1
3   2      2
4   3      1
5   4      1

How to send list of file in a folder to a txt file in Linux

If only names of regular files immediately contained within a directory (assume it's ~/dirs) are needed, you can do

find ~/docs -type f -maxdepth 1 > filenames.txt

How to sort a list of objects based on an attribute of the objects?

Add rich comparison operators to the object class, then use sort() method of the list.
See rich comparison in python.


Update: Although this method would work, I think solution from Triptych is better suited to your case because way simpler.

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

Crystal Reports 13 And Asp.Net 3.5

I had faced the same issue because of some dll files were missing from References of VS13. I went to the location http://scn.sap.com/docs/DOC-7824 and installed the newest pack. It resolved the issue.