Programs & Examples On #Rjava

rJava is an interface between R and Java.

Using the rJava package on Win7 64 bit with R

I need to have a 32 bit JRE available for my browser, but 64 bit JRE for R and rJava. The 32 bit JRE is installed in the default location. After some experimentation, I found that I only needed one of misterbee's suggestions to get rJava (version 0.9-6) working for me. All I did was add the path to my 64 bit java installation:

C:\apps\Java\jre\bin\server\jvm.dll

to the top of my path environment variable (your path will likely be different) and remove my JAVA_HOME as user2161065 suggested. I put this just ahead of the entry

C:\ProgramData\Oracle\Java\javapath

which the Oracle installer inserts at the top of the path and points to some symlinks to the 32 bit JRE. By adding the entry to 64 bit jvm.dll, looks like rJava could find what it needs.

R: rJava package install failing

Turns out my problem was an issue with my JAVA_HOME environment variable. Yes, shocking I know. My initial setting for PATH and JAVA_HOME looked like this:

export JAVA_HOME=/usr/lib/jvm/java-6-sun
export PATH=$PATH:$JAVA_HOME/bin

And I added /jre so it now looks like this:

export JAVA_HOME=/usr/lib/jvm/java-6-sun/jre
export PATH=$PATH:$JAVA_HOME/bin

Everything in Java seemed to work fine without the /jre but rJava would not. Odd.

Problems when trying to load a package in R due to rJava

I had a similar problem what worked for me was to set JAVA_HOME. I tired it first in R:

Sys.setenv(JAVA_HOME = "C:/Program Files/Java/jdk1.8.0_101/")

And when it actually worked I set it in

System Properties -> Advanced -> Environment Variables

by adding a new System variable. I then restarted R/RStudio and everything worked.

java - iterating a linked list

Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)

ValueError: could not convert string to float: id

I solved the similar situation with basic technique using pandas. First load the csv or text file using pandas.It's pretty simple

data=pd.read_excel('link to the file')

Then set the index of data to the respected column that needs to be changed. For example, if your data has ID as one attribute or column, then set index to ID.

 data = data.set_index("ID")

Then delete all the rows with "id" as the value instead of number using following command.

  data = data.drop("id", axis=0). 

Hope, this will help you.

Radio buttons not checked in jQuery

If my firebug profiler work fine (and i know how to use it well), this:

$('#communitymode').attr('checked')

is faster than

$('#communitymode').is('checked')

You can try on this page :)

And then you can use it like

if($('#communitymode').attr('checked')===true) { 
// do something
}

Read input numbers separated by spaces

int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
    cin >> i;
    sum += i;
    //cout << i << endl;
    if (cin.peek() == '\n') {
        break;
    }
    
}

cout << "result: " << sum << endl;
return 0;
}

I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints

Prevent Sequelize from outputting SQL to the console on execution of query?

I solved a lot of issues by using the following code. Issues were : -

  1. Not connecting with database
  2. Database connection Rejection issues
  3. Getting rid of logs in console (specific for this).
const sequelize = new Sequelize("test", "root", "root", {
  host: "127.0.0.1",
  dialect: "mysql",
  port: "8889",
  connectionLimit: 10,
  socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock",
  // It will disable logging
  logging: false
});

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Nothing worked for me for these errors EXCEPT

... was not expected, 
... there is an error in XML document (1,2)
... System.FormatException Input String was not in correct format ...

Except this way

1- You need to inspect the xml response as string (the response that you are trying to de-serialize to an object)

2- Use online tools for string unescape and xml prettify/formatter

3- MAKE SURE that the C# Class (main class) you are trying to map/deserialize the xml string to HAS AN XmlRootAttribute that matches the root element of the response.

Exmaple:

My XML Response was staring like :

<ShipmentCreationResponse xmlns="http://ws.aramex.net/ShippingAPI/v1/">
       <Transaction i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>
           ....

And the C# class definition + attributes was like :

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="ShipmentCreationResponse", WrapperNamespace="http://ws.aramex.net/ShippingAPI/v1/", IsWrapped=true)]
public partial class ShipmentCreationResponse {
  .........
}

Note that the class definition does not have "XmlRootAttribute"

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]

And when i try to de serialize using a generic method :

public static T Deserialize<T>(string input) where T : class
{
    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using (System.IO.StringReader sr = new System.IO.StringReader(input))
    {
        return (T)ser.Deserialize(sr);
    }
}





var _Response = GeneralHelper.XMLSerializer.Deserialize<ASRv2.ShipmentCreationResponse>(xml);

I was getting the errors above

... was not expected, ... there is an error in XML document (1,2) ...

Now by just adding the "XmlRootAttribute" that fixed the issue for ever and for every other requests/responses i had a similar issue with:

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]

..

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ws.aramex.net/ShippingAPI/v1/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]
public partial class ShipmentCreationResponse
{
    ........
}

SQL Row_Number() function in Where Clause

In response to comments on rexem's answer, with respect to whether a an inline view or CTE would be faster I recast the queries to use a table I, and everyone, had available: sys.objects.

WITH object_rows AS (
    SELECT object_id, 
        ROW_NUMBER() OVER ( ORDER BY object_id) RN
    FROM sys.objects)
SELECT object_id
FROM object_rows
WHERE RN > 1

SELECT object_id
FROM (SELECT object_id, 
        ROW_NUMBER() OVER ( ORDER BY object_id) RN
    FROM sys.objects) T
WHERE RN > 1

The query plans produced were exactly the same. I would expect in all cases, the query optimizer would come up with the same plan, at least in simple replacement of CTE with inline view or vice versa.

Of course, try your own queries on your own system to see if there is a difference.

Also, row_number() in the where clause is a common error in answers given on Stack Overflow. Logicaly row_number() is not available until the select clause is processed. People forget that and when they answer without testing the answer, the answer is sometimes wrong. (A charge I have myself been guilty of.)

Prevent direct access to a php include file

You can use phpMyAdmin Style:

/**
 * block attempts to directly run this script
 */
if (getcwd() == dirname(__FILE__)) {
    die('Attack stopped');
}

How to make 'submit' button disabled?

.html

<form [formGroup]="contactForm">

<button [disabled]="contactForm.invalid"  (click)="onSubmit()">SEND</button>

.ts

contactForm: FormGroup;

Update and left outer join statements

The Left join in this query is pointless:

UPDATE md SET md.status = '3' 
FROM pd_mounting_details AS md 
LEFT OUTER JOIN pd_order_ecolid AS oe ON md.order_data = oe.id

It would update all rows of pd_mounting_details, whether or not a matching row exists in pd_order_ecolid. If you wanted to only update matching rows, it should be an inner join.

If you want to apply some condition based on the join occurring or not, you need to add a WHERE clause and/or a CASE expression in your SET clause.

Pass multiple parameters to rest API - Spring

Yes its possible to pass JSON object in URL

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

"for loop" with two variables?

There's two possible questions here: how can you iterate over those variables simultaneously, or how can you loop over their combination.

Fortunately, there's simple answers to both. First case, you want to use zip.

x = [1, 2, 3]
y = [4, 5, 6]

for i, j in zip(x, y):
   print(str(i) + " / " + str(j))

will output

1 / 4
2 / 5
3 / 6

Remember that you can put any iterable in zip, so you could just as easily write your exmple like:

for i, j in zip(range(x), range(y)):
    # do work here.

Actually, just realised that won't work. It would only iterate until the smaller range ran out. In which case, it sounds like you want to iterate over the combination of loops.

In the other case, you just want a nested loop.

for i in x:
    for j in y:
        print(str(i) + " / " + str(j))

gives you

1 / 4
1 / 5
1 / 6
2 / 4
2 / 5
...

You can also do this as a list comprehension.

[str(i) + " / " + str(j) for i in range(x) for j in range(y)]

Hope that helps.

Check if string begins with something?

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

Run multiple python scripts concurrently

I am working in Windows 7 with Python IDLE. I have two programs,

# progA
while True:
    m = input('progA is running ')
    print (m)

and

# progB
while True:
    m = input('progB is running ')
    print (m)

I open up IDLE and then open file progA.py. I run the program, and when prompted for input I enter "b" + <Enter> and then "c" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progA.py =
progA is running b
b
progA is running c
c
progA is running 

Next, I go back to Windows Start and open up IDLE again, this time opening file progB.py. I run the program, and when prompted for input I enter "x" + <Enter> and then "y" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progB.py =
progB is running x
x
progB is running y
y
progB is running 

Now two IDLE Python 3.6.3 Shell programs are running at the same time, one shell running progA while the other one is running progB.

How to ssh from within a bash script?

If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:

#!/usr/bin/expect -f
spawn ssh user@hostname
expect "password:"
sleep 1
send "<your password>\r"
command1
command2
commandN

"While .. End While" doesn't work in VBA?

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1
Wend

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

Expected initializer before function name

Try adding a semi colon to the end of your structure:

 struct sotrudnik {
    string name;
    string speciality;
    string razread;
    int zarplata;
} //Semi colon here

What's the fastest way to read a text file line-by-line?

There's a good topic about this in Stack Overflow question Is 'yield return' slower than "old school" return?.

It says:

ReadAllLines loads all of the lines into memory and returns a string[]. All well and good if the file is small. If the file is larger than will fit in memory, you'll run out of memory.

ReadLines, on the other hand, uses yield return to return one line at a time. With it, you can read any size file. It doesn't load the whole file into memory.

Say you wanted to find the first line that contains the word "foo", and then exit. Using ReadAllLines, you'd have to read the entire file into memory, even if "foo" occurs on the first line. With ReadLines, you only read one line. Which one would be faster?

Python NoneType object is not callable (beginner)

You should not pass the call function hi() to the loop() function, This will give the result.

def hi():     
  print('hi')

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)            # Do not use hi() function inside loop() function

How to calculate the sum of the datatable column in asp.net?

  public decimal Total()
    {
      decimal decTotal=(datagridview1.DataSource as DataTable).Compute("Sum(FieldName)","");
      return decTotal;
    }

proper hibernate annotation for byte[]

Thanks Justin, Pascal for guiding me to the right direction. I was also facing the same issue with Hibernate 3.5.3. Your research and pointers to the right classes had helped me identify the issue and do a fix.

For the benefit for those who are still stuck with Hibernate 3.5 and using oid + byte[] + @LoB combination, following is what I have done to fix the issue.

  1. I created a custom BlobType extending MaterializedBlobType and overriding the set and the get methods with the oid style access.

    public class CustomBlobType extends MaterializedBlobType {
    
    private static final String POSTGRESQL_DIALECT = PostgreSQLDialect.class.getName();
    
    /**
     * Currently set dialect.
     */
    private String dialect = hibernateConfiguration.getProperty(Environment.DIALECT);
    
    /*
     * (non-Javadoc)
     * @see org.hibernate.type.AbstractBynaryType#set(java.sql.PreparedStatement, java.lang.Object, int)
     */
    @Override
    public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        byte[] internalValue = toInternalFormat(value);
    
        if (POSTGRESQL_DIALECT.equals(dialect)) {
            try {
    
    //I had access to sessionFactory through a custom sessionFactory wrapper.
    st.setBlob(index, Hibernate.createBlob(internalValue, sessionFactory.getCurrentSession()));
                } catch (SystemException e) {
                    throw new HibernateException(e);
                }
            } else {
                st.setBytes(index, internalValue);
            }
        }
    
    /*
     * (non-Javadoc)
     * @see org.hibernate.type.AbstractBynaryType#get(java.sql.ResultSet, java.lang.String)
     */
    @Override
    public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
        Blob blob = rs.getBlob(name);
        if (rs.wasNull()) {
            return null;
        }
        int length = (int) blob.length();
        return toExternalFormat(blob.getBytes(1, length));
      }
    }
    
    1. Register the CustomBlobType with Hibernate. Following is what i did to achieve that.

      hibernateConfiguration= new AnnotationConfiguration();
      Mappings mappings = hibernateConfiguration.createMappings();
      mappings.addTypeDef("materialized_blob", "x.y.z.BlobType", null);
      

psql: FATAL: role "postgres" does not exist

For MAC:

  1. Install Homebrew
  2. brew install postgres
  3. initdb /usr/local/var/postgres
  4. /usr/local/Cellar/postgresql/<version>/bin/createuser -s postgres or /usr/local/opt/postgres/bin/createuser -s postgres which will just use the latest version.
  5. start postgres server manually: pg_ctl -D /usr/local/var/postgres start

To start server at startup

  • mkdir -p ~/Library/LaunchAgents
  • ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
  • launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

Now, it is set up, login using psql -U postgres -h localhost or use PgAdmin for GUI.

By default user postgres will not have any login password.

Check this site for more articles like this: https://medium.com/@Nithanaroy/installing-postgres-on-mac-18f017c5d3f7

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

Download xcode 10.2 from below link https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2/Xcode_10.2.xip

Edit: Minimum System Version* to 10.13.6 in Info.plist at below paths

  1. Xcode.app/Contents/Info.plist
  2. Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/Info.plist

Replace: Xcode.app/Contents/Developer/usr/bin/xcodebuild from Xcode 10

****OR*****

you can install disk image of 12.2 in your existing xcode to run on 12.2 devices Download disk image from here https://github.com/xushuduo/Xcode-iOS-Developer-Disk-Image/releases/download/12.2/12.2.16E5191d.zip

And paste at Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

Note: Restart the Xcode

Is there any "font smoothing" in Google Chrome?

I will say before all that this will not always works, i have tested this with sans-serif font and external fonts like open sans

Sometimes, when you use huge fonts, try to approximate to font-size:49px and upper

font-size:48px

This is a header text with a size of 48px (font-size:48px; in the element that contains the text).

But, if you up the 48px to font-size:49px; (and 50px, 60px, 80px, etc...), something interesting happens

font-size:49px

The text automatically get smooth, and seems really good

For another side...

If you are looking for small fonts, you can try this, but isn't very effective.

To the parent of the text, just apply the next css property: -webkit-backface-visibility: hidden;

You can transform something like this:

-webkit-backface-visibility: visible;

To this:

-webkit-backface-visibility: hidden;

(the font is Kreon)

Consider that when you are not putting that property, -webkit-backface-visibility: visible; is inherit

But be careful, that practice will not give always good results, if you see carefully, Chrome just make the text look a little bit blurry.

Another interesting fact:

-webkit-backface-visibility: hidden; will works too when you transform a text in Chrome (with the -webkit-transform property, that includes rotations, skews, etc)

Without

Without -webkit-backface-visibility: hidden;

With

With -webkit-backface-visibility: hidden;

Well, I don't know why that practices works, but it does for me. Sorry for my weird english.

Does Enter key trigger a click event?

Use (keyup.enter).

Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter pseudo-event.

Visual Studio Code Search and Replace with Regular Expressions

So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:

Visual studio code's search & replace tab If you mean to disable the code, you just have to put <h1> in search, and replace to ####.

But if you want to use this regex instead, you may enable it in the icon: .* and use the regex: <h1>(.+?)<\/h1> and replace to: #### $1.

And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:

C#: How to access an Excel cell?

Try:

Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;

oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));

oSheet = (Excel._Worksheet)oWB.Worksheets;
oSheet.Activate();

oSheet.Cells[3, 9] = "Some Text"

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

Force page scroll position to top at page refresh in HTML

You can use location.replace instead of location.reload:

location.replace(location.href);

This way page will reload with scroll on top.

Remove/ truncate leading zeros by javascript/jquery

Since you said "any string", I'm assuming this is a string you want to handle, too.

"00012  34 0000432    0035"

So, regex is the way to go:

var trimmed = s.replace(/\b0+/g, "");

And this will prevent loss of a "000000" value.

var trimmed = s.replace(/\b(0(?!\b))+/g, "")

You can see a working example here

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

Relative paths based on file location instead of current working directory

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

Setting href attribute at runtime

<style>
a:hover {
    cursor:pointer;
}
</style>

<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $(".link").click(function(){
        var href = $(this).attr("href").split("#");
        $(".results").text(href[1]);
    })
})
</script>



<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>


<br /><br />
<div class="results"></div>

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

You can used Lambda as "Lambda Proxy Integration" ,ref this [https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-proxy-integration-lambda-function-python] , options avalible to this lambda are

For Nodejs Lambda 'event.headers', 'event.pathParameters', 'event.body', 'event.stageVariables', and 'event.requestContext'

For Python Lambda event['headers']['parametername'] and so on

Spring @Transactional read-only propagation

First of all, since Spring doesn't do persistence itself, it cannot specify what readOnly should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.

If you specify readOnly as true, the flush mode will be set as FlushMode.NEVER in the current Hibernate Session preventing the session from committing the transaction.

Furthermore, setReadOnly(true) will be called on the JDBC Connection, which is also a hint to the underlying database. If your database supports it (most likely it does), this has basically the same effect as FlushMode.NEVER, but it's stronger since you cannot even flush manually.

Now let's see how transaction propagation works.

If you don't explicitly set readOnly to true, you will have read/write transactions. Depending on the transaction attributes (like REQUIRES_NEW), sometimes your transaction is suspended at some point, a new one is started and eventually committed, and after that the first transaction is resumed.

OK, we're almost there. Let's see what brings readOnly into this scenario.

If a method in a read/write transaction calls a method that requires a readOnly transaction, the first one should be suspended, because otherwise a flush/commit would happen at the end of the second method.

Conversely, if you call a method from within a readOnly transaction that requires read/write, again, the first one will be suspended, since it cannot be flushed/committed, and the second method needs that.

In the readOnly-to-readOnly, and the read/write-to-read/write cases the outer transaction doesn't need to be suspended (unless you specify propagation otherwise, obviously).

Return Bit Value as 1/0 and NOT True/False in SQL Server

This can be changed to 0/1 through using CASE WHEN like this example:

SELECT 
 CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value' 
 FROM SchemaName.TableName

SQL Query for Student mark functionality

I like the simple solution using windows functions:

select t.*
from (select student.*, su.subname, max(mark) over (partition by subid) as maxmark
      from marks m join
           students st
           on m.stid = st.stid join
           subject su
           on m.subid = su.subid
     ) t
where t.mark = maxmark

Or, alternatively:

select t.*
from (select student.*, su.subname, rank(mark) over (partition by subid order by mark desc) as markseqnum
      from marks m join
           students st
           on m.stid = st.stid join
           subject su
           on m.subid = su.subid
     ) t
where markseqnum = 1

Cannot ping AWS EC2 instance

1.Go to EC2 Dashboard and click "Running Instances" on "Security Groups"
2.select the group of your instance which you need to add security.  
3.click on the "Inbound" tab
4.Click "Edit" Button (It will open an popup window)
5.click "Add Rule"
6.Select the "Custom ICMP rule - IPv4" as Type
7.Enter the "0.0.0.0/0" as Source or your public IP

7.Click "Save"

What does <![CDATA[]]> in XML mean?

CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be.

The key differences between CDATA and comments are:

This means given these four snippets of XML from one well-formed document:

<!ENTITY MyParamEntity "Has been expanded">

<!--
Within this comment I can use ]]>
and other reserved characters like <
&, ', and ", but %MyParamEntity; will not be expanded
(if I retrieve the text of this node it will contain
%MyParamEntity; and not "Has been expanded")
and I can't place two dashes next to each other.
-->

<![CDATA[
Within this Character Data block I can
use double dashes as much as I want (along with <, &, ', and ")
*and* %MyParamEntity; will be expanded to the text
"Has been expanded" ... however, I can't use
the CEND sequence. If I need to use CEND I must escape one of the
brackets or the greater-than sign using concatenated CDATA sections.
]]>

<description>An example of escaped CENDs</description>
<!-- This text contains a CEND ]]> -->
<!-- In this first case we put the ]] at the end of the first CDATA block
     and the > in the second CDATA block -->
<data><![CDATA[This text contains a CEND ]]]]><![CDATA[>]]></data>
<!-- In this second case we put a ] at the end of the first CDATA block
     and the ]> in the second CDATA block -->
<alternative><![CDATA[This text contains a CEND ]]]><![CDATA[]>]]></alternative>

Python Anaconda - How to Safely Uninstall

I always try to follow the developers advice, since they are usually the ones that now how it would affect your system. Theoretically this should be the safest way:

Install the Anaconda-Clean package from Anaconda Prompt (terminal on Linux or macOS):

conda install anaconda-clean

In the same window, run one of these commands:

  1. Remove all Anaconda-related files and directories with a confirmation prompt before deleting each one:

anaconda-clean

  1. Remove all Anaconda-related files and directories without being prompted to delete each one:

anaconda-clean --yes

Anaconda-Clean creates a backup of all files and directories that might be removed in a folder named .anaconda_backup in your home directory. Also note that Anaconda-Clean leaves your data files in the AnacondaProjects directory untouched.

https://docs.anaconda.com/anaconda/install/uninstall/

How to preview selected image in input type="file" in popup using jQuery?

Demo

HTML:

 <form id="form1" runat="server">
   <input type='file' id="imgInp" />
   <img id="blah" src="#" alt="your image" />
</form>

jQuery

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

Reference

Passing in class names to react components

In React, when you want to pass an interpreted expression, you have to open a pair of curly braces. Try:

render () {
  return (
    <button className={`pill ${ this.props.styleName }`}>
      {this.props.children}
    </button>
  );
}

Using the classnames npm package

import classnames from 'classnames';

render() {
  return (
    <button className={classnames('pill', this.props.styleName)}>
      {this.props.children}
    </button>
  );
}

Reading column names alone in a csv file

Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-

An implementation could be as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    #get fieldnames from DictReader object and store in list
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...

>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']

If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    #you can eat the first line before creating DictReader.
    #if no "fieldnames" param is passed into
    #DictReader object upon creation, DictReader
    #will read the upper-most line as the headers
    f.readline()

    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

There was a relevant answer from Ask Tom published in April 2016.

If you have sufficient server power, you can do

select /*+ parallel */ count(*) from sometable

If you are just after an approximation, you can do :

select 5 * count(*) from sometable sample block (10);

Also, if there is

  1. a column that contains no nulls, but is not defined as NOT NULL, and
  2. there is an index on that column

you could try:

select /*+ index_ffs(t) */ count(*) from sometable  t where indexed_col is not null

How do I get a computer's name and IP address using VB.NET?

Use the My Class :)

My.Computer.Name

as for the IP address quick google search

Private Sub GetIPAddress()

Dim strHostName As String

Dim strIPAddress As String



strHostName = System.Net.Dns.GetHostName()

strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()


MessageBox.Show("Host Name: " & strHostName & "; IP Address: " & strIPAddress)

End Sub

How to download a branch with git?

Thanks to a related question, I found out that I need to "checkout" the remote branch as a new local branch, and specify a new local branch name.

git checkout -b newlocalbranchname origin/branch-name

Or you can do:

git checkout -t origin/branch-name

The latter will create a branch that is also set to track the remote branch.


Update: It's been 5 years since I originally posted this question. I've learned a lot and git has improved since then. My usual workflow is a little different now.

If I want to fetch the remote branches, I simply run:

git pull

This will fetch all of the remote branches and merge the current branch. It will display an output that looks something like this:

From github.com:andrewhavens/example-project
   dbd07ad..4316d29  master     -> origin/master
 * [new branch]      production -> origin/production
 * [new branch]      my-bugfix-branch -> origin/my-bugfix-branch
First, rewinding head to replay your work on top of it...
Fast-forwarded master to 4316d296c55ac2e13992a22161fc327944bcf5b8.

Now git knows about my new my-bugfix-branch. To switch to this branch, I can simply run:

git checkout my-bugfix-branch

Normally, I would need to create the branch before I could check it out, but in newer versions of git, it's smart enough to know that you want to checkout a local copy of this remote branch.

Calling a function on bootstrap modal open

You can use the shown event/show event based on what you need:

$( "#code" ).on('shown', function(){
    alert("I want this to appear after the modal has opened!");
});

Demo: Plunker

Update for Bootstrap 3.0

For Bootstrap 3.0 you can still use the shown event but you would use it like this:

$('#code').on('shown.bs.modal', function (e) {
  // do something...
})

See the Bootstrap 3.0 docs here under "Events".

Simplest way to do grouped barplot

with ggplot2:

library(ggplot2)
Animals <- read.table(
  header=TRUE, text='Category        Reason Species
1   Decline       Genuine      24
2  Improved       Genuine      16
3  Improved Misclassified      85
4   Decline Misclassified      41
5   Decline     Taxonomic       2
6  Improved     Taxonomic       7
7   Decline       Unclear      41
8  Improved       Unclear     117')

ggplot(Animals, aes(factor(Reason), Species, fill = Category)) + 
  geom_bar(stat="identity", position = "dodge") + 
  scale_fill_brewer(palette = "Set1")

Bar Chart

How to check SQL Server version

Simply use

SELECT @@VERSION

Sample output

Microsoft SQL Server 2012 - 11.0.2100.60 (X64) 
Feb 10 2012 19:39:15 
Copyright (c) Microsoft Corporation
Express Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )

Source: How to check sql server version? (Various ways explained)

How to develop a soft keyboard for Android?

A good place to start is the sample application provided on the developer docs.

  • Guidelines would be to just make it as usable as possible. Take a look at the others available on the market to see what you should be aiming for
  • Yes, services can do most things, including internet; provided you have asked for those permissions
  • You can open activities and do anything you like n those if you run into a problem with doing some things in the keyboard. For example HTC's keyboard has a button to open the settings activity, and another to open a dialog to change languages.

Take a look at other IME's to see what you should be aiming for. Some (like the official one) are open source.

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

Where can I download Eclipse Android bundle?

You don't actually need the bundle as the ADT can be used with just any latest Eclipse IDE.


1. Make sure you have JDK installed.

  1. Download latest eclipse.

  2. Download latest ADT plugin ADT-XX.X.X.zip. As of this answer the current version is ADT-23.0.7.zip (More versions at http://developer.android.com/tools/sdk/eclipse-adt.html)

  3. Open Eclipse and follow the following steps:

    • Open Help > Install New Software > Add > Archive
    • Navigate to where you downloaded your ADT plugin and select it.
    • Check Developer Tools, click Next, accept any licenses and Finish
  4. After restarting Eclipse, if you are not able to open a layout file go to step 4 but instead of selecting archive add https://dl-ssl.google.com/android/eclipse/ in the Location: textbox. Press Ok, update the ADT and restart Eclipse. Close and reopen the layout files and you'll be good to go.

  5. Run the Android SDK Manager to update its components.


EDIT: The ADT plugin has long since been deprecated. For more information visit this link:

https://developer.android.com/studio/tools/sdk/eclipse-adt.html

jQuery Screen Resolution Height Adjustment

To get screen resolution in JS use screen object

screen.height;
screen.width;

Based on that values you can calculate your margin to whatever suits you.

How to stop a setTimeout loop?

setTimeout returns a timer handle, which you can use to stop the timeout with clearTimeout.

So for instance:

function setBgPosition() {
    var c = 0,
        timer = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c >= numbers.length) {
            c = 0;
        }
        timer = setTimeout(run, 200);
    }
    timer = setTimeout(run, 200);

    return stop;

    function stop() {
        if (timer) {
            clearTimeout(timer);
            timer = 0;
        }
}

So you'd use that as:

var stop = setBgPosition();
// ...later, when you're ready to stop...
stop();

Note that rather than having setBgPosition call itself again, I've just had it set c back to 0. Otherwise, this wouldn't work. Also note that I've used 0 as a handle value for when the timeout isn't pending; 0 isn't a valid return value from setTimeout so it makes a handy flag.

This is also one of the (few) places I think you'd be better off with setInterval rather than setTimeout. setInterval repeats. So:

function setBgPosition() {
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c >= numbers.length) {
            c = 0;
        }
    }
    return setInterval(run, 200);
}

Used like this:

var timer = setBgPosition();
// ...later, when you're ready to stop...
clearInterval(timer);

All of the above notwithstanding, I'd want to find a way to make setBgPosition stop things itself, by detecting that some completion condition has been satisfied.

How to run a function when the page is loaded?

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

I'd recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);

PHP Header redirect not working

Look at /Applications/MAMP/htdocs/testygubbins/OO/test/header.php line 15.

At that position, it makes some output. Fix it. :)

Maven Modules + Building a Single Specific Module

If you have previously run mvn install on project B it will have been installed to your local repository, so when you build package A Maven can resolve the dependency. So as long as you install project B each time you change it your builds for project A will be up to date.

You can define a multi-module project with an aggregator pom to build a set of projects.

It's also worthwhile mentioning m2eclipse, it integrates Maven into Eclipse and allows you to (optionally) resolve dependencies from the workspace. So if you are hacking away on multiple projects, the workspace content will be used for compilation. Once you are happy with your changes, run mvn install (on each project in turn, or using an aggregator) to put them in your local repository.

Multiple submit buttons in the same form calling different Servlets

You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.

function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

How do I Convert DateTime.now to UTC in Ruby?

Unfortunately, the DateTime class doesn't have the convenience methods available in the Time class to do this. You can convert any DateTime object into UTC like this:

d = DateTime.now
d.new_offset(Rational(0, 24))

You can switch back from UTC to localtime using:

d.new_offset(DateTime.now.offset)

where d is a DateTime object in UTC time. If you'd like these as convenience methods, then you can create them like this:

class DateTime
  def localtime
    new_offset(DateTime.now.offset)
  end

  def utc
    new_offset(Rational(0, 24))
  end
end

You can see this in action in the following irb session:

d = DateTime.now.new_offset(Rational(-4, 24))
 => #<DateTime: 106105391484260677/43200000000,-1/6,2299161> 
1.8.7 :185 > d.to_s
 => "2012-08-03T15:42:48-04:00" 
1.8.7 :186 > d.localtime.to_s
 => "2012-08-03T12:42:48-07:00" 
1.8.7 :187 > d.utc.to_s
 => "2012-08-03T19:42:48+00:00" 

As you can see above, the initial DateTime object has a -04:00 offset (Eastern Time). I'm in Pacific Time with a -07:00 offset. Calling localtime as described previously properly converts the DateTime object into local time. Calling utc on the object properly converts it to a UTC offset.

How do you make an anchor link non-clickable or disabled?

The cleanest method would be to add a class with pointer-events:none when you want to disable a click. It would function like a normal label.

.disableClick{
    pointer-events: none;
}

PHP Function with Optional Parameters

I know this is an old post, but i was having a problem like the OP and this is what i came up with.

Example of array you could pass. You could re order this if a particular order was required, but for this question this will do what is asked.

$argument_set = array (8 => 'lots', 5 => 'of', 1 => 'data', 2 => 'here');

This is manageable, easy to read and the data extraction points can be added and removed at a moments notice anywhere in coding and still avoid a massive rewrite. I used integer keys to tally with the OP original question but string keys could be used just as easily. In fact for readability I would advise it.

Stick this in an external file for ease

function unknown_number_arguments($argument_set) {

    foreach ($argument_set as $key => $value) {

        # create a switch with all the cases you need. as you loop the array 
        # keys only your submitted $keys values will be found with the switch. 
        switch ($key) {
            case 1:
                # do stuff with $value
                break;
            case 2:
                # do stuff with $value;
                break;
            case 3:
                # key 3 omitted, this wont execute 
                break;
            case 5:
                # do stuff with $value;
                break;
            case 8:
                # do stuff with $value;
                break;
            default:
                # no match from the array, do error logging?
                break;
        }
    }
return;
}

put this at the start if the file.

$argument_set = array(); 

Just use these to assign the next piece of data use numbering/naming according to where the data is coming from.

$argument_set[1][] = $some_variable; 

And finally pass the array

unknown_number_arguments($argument_set);

Plotting two variables as lines using ggplot2 on the same graph

For a small number of variables, you can build the plot manually yourself:

ggplot(test_data, aes(date)) + 
  geom_line(aes(y = var0, colour = "var0")) + 
  geom_line(aes(y = var1, colour = "var1"))

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

IntelliJ - Convert a Java project/module into a Maven project/module

Right-click on the module, select "Add framework support...", and check the "Maven" technology.

(This also creates a pom.xml for you to modify.)

If you mean adding source repository elements, I think you need to do that manually–not sure.

Pre-IntelliJ 13 this won't convert the project to the Maven Standard Directory Layout, 13+ it will.

Convert varchar into datetime in SQL Server

SQL Server can implicitly cast strings in the form of 'YYYYMMDD' to a datetime - all other strings must be explicitly cast. here are two quick code blocks which will do the conversion from the form you are talking about:

version 1 uses unit variables:

BEGIN 
DECLARE @input VARCHAR(8), @mon CHAR(2), 
@day char(2), @year char(4), @output DATETIME

SET @input = '10022009'   --today's date


SELECT @mon = LEFT(@input, 2), @day = SUBSTRING(@input, 3,2), @year = RIGHT(@input,4)

SELECT @output = @year+@mon+@day 
SELECT @output 
END

version 2 does not use unit variables:

BEGIN 
DECLARE @input CHAR(8), @output DATETIME
SET @input = '10022009' --today's date 

SELECT @output = RIGHT(@input,4) + SUBSTRING(@input, 3,2) + LEFT(@input, 2)

SELECT @output
END

Both cases rely on sql server's ability to do that implicit conversion.

CodeIgniter: How to get Controller, Action, URL information

Last segment of URL will always be the action. Please get like this:

$this->uri->segment('last_segment');

How can I create a copy of an object in Python?

To get a fully independent copy of an object you can use the copy.deepcopy() function.

For more details about shallow and deep copying please refer to the other answers to this question and the nice explanation in this answer to a related question.

print call stack in C or C++

You can use the GNU profiler. It shows the call-graph as well! the command is gprof and you need to compile your code with some option.

a tag as a submit button?

Supposing the form is the direct parent you can do:

<a href='#' onclick='this.parentNode.submit(); return false;'>submit</a>

If not you can access through the forms name attribute like this:

<a href='#' onclick='document.forms["myform"].submit(); return false;'>submit</a>

See both examples here: http://jsfiddle.net/WEZDC/1/

How to delete shared preferences data from App in Android

You can use the adb shell to do this even without a rooted phone. The only catch is that the app must be debuggable.

run-as <your package name> <command>

For example:

run-as com.asdf.blah rm /data/data/com.asdf.blah/databases/myDB.db

Alternatively, you can just do the above but without the command which will direct you to the app package root and allow you to execute more commands in the app's context.

Sum all the elements java arraylist

Using Java 8 streams:

double sum = m.stream()
    .mapToDouble(a -> a)
    .sum();

System.out.println(sum); 

How do Python's any and all functions work?

You can roughly think of any and all as series of logical or and and operators, respectively.

any

any will return True when at least one of the elements is Truthy. Read about Truth Value Testing.

all

all will return True only when all the elements are Truthy.

Truth table

+-----------------------------------------+---------+---------+
|                                         |   any   |   all   |
+-----------------------------------------+---------+---------+
| All Truthy values                       |  True   |  True   |
+-----------------------------------------+---------+---------+
| All Falsy values                        |  False  |  False  |
+-----------------------------------------+---------+---------+
| One Truthy value (all others are Falsy) |  True   |  False  |
+-----------------------------------------+---------+---------+
| One Falsy value (all others are Truthy) |  True   |  False  |
+-----------------------------------------+---------+---------+
| Empty Iterable                          |  False  |  True   |
+-----------------------------------------+---------+---------+

Note 1: The empty iterable case is explained in the official documentation, like this

any

Return True if any element of the iterable is true. If the iterable is empty, return False

Since none of the elements are true, it returns False in this case.

all

Return True if all elements of the iterable are true (or if the iterable is empty).

Since none of the elements are false, it returns True in this case.


Note 2:

Another important thing to know about any and all is, it will short-circuit the execution, the moment they know the result. The advantage is, entire iterable need not be consumed. For example,

>>> multiples_of_6 = (not (i % 6) for i in range(1, 10))
>>> any(multiples_of_6)
True
>>> list(multiples_of_6)
[False, False, False]

Here, (not (i % 6) for i in range(1, 10)) is a generator expression which returns True if the current number within 1 and 9 is a multiple of 6. any iterates the multiples_of_6 and when it meets 6, it finds a Truthy value, so it immediately returns True, and rest of the multiples_of_6 is not iterated. That is what we see when we print list(multiples_of_6), the result of 7, 8 and 9.

This excellent thing is used very cleverly in this answer.


With this basic understanding, if we look at your code, you do

any(x) and not all(x)

which makes sure that, atleast one of the values is Truthy but not all of them. That is why it is returning [False, False, False]. If you really wanted to check if both the numbers are not the same,

print [x[0] != x[1] for x in zip(*d['Drd2'])]

"The page has expired due to inactivity" - Laravel 5.5

Try all of them.

composer dump-autoload
php artisan optimize
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

Using the "With Clause" SQL Server 2008

There are two types of WITH clauses:

Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).

;WITH mil AS (
 SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
 FROM master.sys.all_columns as c
 CROSS JOIN master.sys.all_columns as c2
)                
 SELECT CASE WHEN n  % 3 = 0 THEN
             CASE WHEN n  % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
        WHEN n % 5 = 0 THEN 'Buzz'
        ELSE CAST(n AS char(6))
     END + CHAR(13)
 FROM mil

Here is a select statement also using a WITH clause

SELECT * FROM orders WITH (NOLOCK) where order_id = 123

Change onclick action with a Javascript function

var Foo = function(){
    document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}

var Boo = function(){
    alert("test");
}

2D character array initialization in C

C strings are enclosed in double quotes:

const char *options[2][100];

options[0][0] = "test1";
options[1][0] = "test2";

Re-reading your question and comments though I'm guessing that what you really want to do is this:

const char *options[2] = { "test1", "test2" };

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

Disabling vertical scrolling in UIScrollView

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
    [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x,0)];

}

you must have confirmed to UIScrollViewDelegate

aScrollView.delegate = self;

Is there an embeddable Webkit component for Windows / C# development?

Haven't tried yet but found WebKit.NET on SourceForge. It was moved to GitHub.

Warning: Not maintained anymore, last commits are from early 2013

How do you strip a character out of a column in SQL Server?

This is done using the REPLACE function

To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:

SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn]  FROM [SomeTable]

To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"

UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        cards.id_card,
        cards.hash_card,
        cards.`table`,
        users.name,
        0 as total,
        cards.card_status,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
    UNION
    SELECT
        cards.id_card,
        orders.hash_card,
        cards.`table`,
        users.name,
        sum(orders.quantity*orders.product_price) as total, 
        cards.card_status, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

How can I pull from remote Git repository and override the changes in my local repository?

As an addendum, if you want to reapply your changes on top of the remote, you can also try:

git pull --rebase origin master

If you then want to undo some of your changes (but perhaps not all of them) you can use:

git reset SHA_HASH

Then do some adjustment and recommit.

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

I faced the same problem in eclipse with tomcat7 with the error javax.servlet cannot be resolved. If I select the server in targeted runtime mode and build project again, the error get's resolved.

What is the Swift equivalent of isEqualToString in Objective-C?

One important point is that Swift's == on strings might not be equivalent to Objective-C's -isEqualToString:. The peculiarity lies in differences in how strings are represented between Swift and Objective-C.

Just look on this example:

let composed = "Ö" // U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS
let decomposed = composed.decomposedStringWithCanonicalMapping // (U+004F LATIN CAPITAL LETTER O) + (U+0308 COMBINING DIAERESIS)

composed.utf16.count // 1
decomposed.utf16.count // 2

let composedNSString = composed as NSString
let decomposedNSString = decomposed as NSString

decomposed == composed // true, Strings are equal
decomposedNSString == composedNSString // false, NSStrings are not

NSString's are represented as a sequence of UTF–16 code units (roughly read as an array of UTF-16 (fixed-width) code units). Whereas Swift Strings are conceptually sequences of "Characters", where "Character" is something that abstracts extended grapheme cluster (read Character = any amount of Unicode code points, usually something that the user sees as a character and text input cursor jumps around).

The next thing to mention is Unicode. There is a lot to write about it, but here we are interested in something called "canonical equivalence". Using Unicode code points, visually the same "character" can be encoded in more than one way. For example, "Á" can be represented as a precomposed "Á" or as decomposed A + ?´ (that's why in example composed.utf16 and decomposed.utf16 had different lengths). A good thing to read on that is this great article.

-[NSString isEqualToString:], according to the documentation, compares NSStrings code unit by code unit, so:

[Á] != [A, ?´]

Swift's String == compares characters by canonical equivalence.

[ [Á] ] == [ [A, ?´] ]

In swift the above example will return true for Strings. That's why -[NSString isEqualToString:] is not equivalent to Swift's String ==. Equivalent pure Swift comparison could be done by comparing String's UTF-16 Views:

decomposed.utf16.elementsEqual(composed.utf16) // false, UTF-16 code units are not the same
decomposedNSString == composedNSString // false, UTF-16 code units are not the same
decomposedNSString.isEqual(to: composedNSString as String) // false, UTF-16 code units are not the same

Also, there is a difference between NSString == NSString and String == String in Swift. The NSString == will cause isEqual and UTF-16 code unit by code unit comparison, where as String == will use canonical equivalence:

decomposed == composed // true, Strings are equal
decomposed as NSString == composed as NSString // false, UTF-16 code units are not the same

And the whole example:

let composed = "Ö" // U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS
let decomposed = composed.decomposedStringWithCanonicalMapping // (U+004F LATIN CAPITAL LETTER O) + (U+0308 COMBINING DIAERESIS)

composed.utf16.count // 1
decomposed.utf16.count // 2

let composedNSString = composed as NSString
let decomposedNSString = decomposed as NSString

decomposed == composed // true, Strings are equal
decomposedNSString == composedNSString // false, NSStrings are not

decomposed.utf16.elementsEqual(composed.utf16) // false, UTF-16 code units are not the same
decomposedNSString == composedNSString // false, UTF-16 code units are not the same
decomposedNSString.isEqual(to: composedNSString as String) // false, UTF-16 code units are not the same

How to set a cell to NaN in a pandas dataframe

You can try these snippets.

In [16]:mydata = {'x' : [10, 50, 18, 32, 47, 20], 'y' : ['12', '11', 'N/A', '13', '15', 'N/A']}
In [17]:df=pd.DataFrame(mydata)

In [18]:df.y[df.y=="N/A"]=np.nan

Out[19]:df 
    x    y
0  10   12
1  50   11
2  18  NaN
3  32   13
4  47   15
5  20  NaN

How to read input from console in a batch file?

If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough

set /p asd="Hit enter to continue"

at the end of your script and it'll keep the window open.

Note that this'll set asd as an environment variable, and can be replaced with anything else.

get the data of uploaded file in javascript

The example below is based on the html5rocks solution. It uses the browser's FileReader() function. Newer browsers only.

See http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files

In this example, the user selects an HTML file. It uploaded into the <textarea>.

<form enctype="multipart/form-data">
<input id="upload" type=file   accept="text/html" name="files[]" size=30>
</form>

<textarea class="form-control" rows=35 cols=120 id="ms_word_filtered_html"></textarea>

<script>
function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // use the 1st file from the list
    f = files[0];

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
        return function(e) {

          jQuery( '#ms_word_filtered_html' ).val( e.target.result );
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsText(f);
  }

  document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>

How to close jQuery Dialog within the dialog?

$(this).parents(".ui-dialog-content").dialog('close')

Simple, I like to make sure I don't:

  1. hardcode dialog #id values.
  2. Close all dialogs.

Is there a good Valgrind substitute for Windows?

Check out this question: Is there a good Valgrind substitute for Windows? . Though general substitute for valgrind is asked, it mainly discusses memory leak detectors and not race conditions detections.

Simple Deadlock Examples

Here's a simple deadlock in C#.

void UpdateLabel(string text) {
   lock(this) {
      if(MyLabel.InvokeNeeded) {
        IAsyncResult res =  MyLable.BeginInvoke(delegate() {
             MyLable.Text = text;
            });
         MyLabel.EndInvoke(res);
        } else {
             MyLable.Text = text;
        }
    }
}

If, one day, you call this from the GUI thread, and another thread calls it as well - you might deadlock. The other thread gets to EndInvoke, waits for the GUI thread to execute the delegate while holding the lock. The GUI thread blocks on the same lock waiting for the other thread to release it - which it will not because the GUI thread will never be available to execute the delegate the other thread is waiting for. (ofcourse the lock here isn't strictly needed - nor is perhaps the EndInvoke, but in a slightly more complex scenario, a lock might be acquired by the caller for other reasons, resulting in the same deadlock.)

HTML: Changing colors of specific words in a string of text

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
  Enter the competition by 
  <span style="color: #ff0000">January 30, 2011</span>
  and you could win up to $$$$ — including amazing 
  <span style="color: #0000a0">summer</span> 
  trips!
</p>

Or you may want to use CSS classes instead:

<html>
  <head>
    <style type="text/css">
      p { 
        font-size:14px; 
        color:#538b01; 
        font-weight:bold; 
        font-style:italic;
      }
      .date {
        color: #ff0000;
      }
      .season { /* OK, a bit contrived... */
        color: #0000a0;
      }
    </style>
  </head>
  <body>
    <p>
      Enter the competition by 
      <span class="date">January 30, 2011</span>
      and you could win up to $$$$ — including amazing 
      <span class="season">summer</span> 
      trips!
    </p>
  </body>
</html>

Pretty Printing a pandas dataframe

You can use prettytable to render the table as text. The trick is to convert the data_frame to an in-memory csv file and have prettytable read it. Here's the code:

from StringIO import StringIO
import prettytable    

output = StringIO()
data_frame.to_csv(output)
output.seek(0)
pt = prettytable.from_csv(output)
print pt

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

ListenForClients is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main. When two instances of the TcpListener try to listen on the same port, you get that error.

How do I find out if a column exists in a VB.Net DataRow

DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.

    If DataRow.Table.Columns.Contains("column") Then
        MsgBox("YAY")
    End If

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Excel doesn't update value unless I hit Enter

Executive summary / TL;DR:
Try doing a find & replace of "=" with "=". Yes, replace the equals sign with itself. For my scenario, it forced everything to update.

Background:
I frequently make formulas across multiple columns then concatenate them together. After doing such, I'll copy & paste them as values to extract my created formula. After this process, they're typically stuck displaying a formula, and not displaying a value, unless I enter the cell and press Enter. Pressing F2 & Enter repeatedly is not fun.

Return from a promise then()

When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails).

Source: https://web.dev/promises/#queuing-asynchronous-actions

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I am using the following construct, although you might want to avoid shell=True. This gives you the output and error message for any command, and the error code as well:

process = subprocess.Popen(cmd, shell=True,
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.PIPE)

# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode

Sending HTTP Post request with SOAP action using org.apache.http

... using org.apache.http api. ...

You need to include SOAPAction as a header in the request. As you have httpPost and requestWrapper handles, there are three ways adding the header.

 1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
 2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
 3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );

Only difference is that addHeader allows multiple values with same header name and setHeader allows unique header names only. setHeader(... over writes first header with the same name.

You can go with any of these on your requirement.

jquery loop on Json data using $.each

getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

Understanding unique keys for array children in React.js

I fixed this using Guid for each key like this: Generating Guid:

guid() {
    return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
        this.s4() + '-' + this.s4() + this.s4() + this.s4();
}

s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
}

And then assigning this value to markers:

{this.state.markers.map(marker => (
              <MapView.Marker
                  key={this.guid()}
                  coordinate={marker.coordinates}
                  title={marker.title}
              />
          ))}

Method to Add new or update existing item in Dictionary

Functionally, they are equivalent.

Performance-wise map[key] = value would be quicker, as you are only making single lookup instead of two.

Style-wise, the shorter the better :)

The code will in most cases seem to work fine in multi-threaded context. It however is not thread-safe without extra synchronization.

How to catch all exceptions in c# using try and catch?

Both are fine, but only the first one will allow you to inspect the Exception itself.

Both swallow the Exception, and you should only catch exceptions to do something meaningfull. Hiding a problem is not meaningful!

Get elements by attribute when querySelectorAll is not available without using libraries?

Try this it works

document.querySelector('[attribute="value"]')

example :

document.querySelector('[role="button"]')

What arguments are passed into AsyncTask<arg1, arg2, arg3>?

Google's Android Documentation Says that :

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

AsyncTask's generic types :

The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }

You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html

Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog

Well The structure of a typical AsyncTask class goes like :

private class MyTask extends AsyncTask<X, Y, Z>

    protected void onPreExecute(){

    }

This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.

    protected Z doInBackground(X...x){

    }

The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.

   protected void onProgressUpdate(Y y){

   }

This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.

  protected void onPostExecute(Z z){

  }

This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.

What about the X, Y and Z types?

As you can deduce from the above structure:

 X – The type of the input variables value you want to set to the background process. This can be an array of objects.

 Y – The type of the objects you are going to enter in the onProgressUpdate method.

 Z – The type of the result from the operations you have done in the background process.

How do we call this task from an outside class? Just with the following two lines:

MyTask myTask = new MyTask();

myTask.execute(x);

Where x is the input parameter of the type X.

Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.

 myTask.getStatus();

and we can receive the following status:

RUNNING - Indicates that the task is running.

PENDING - Indicates that the task has not been executed yet.

FINISHED - Indicates that onPostExecute(Z) has finished.

Hints about using AsyncTask

  1. Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.

  2. You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.

  3. The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).

  4. The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.

ctypes - Beginner

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

Javascript validation: Block special characters

I think checking keypress events is not completely adequate, as I believe users can copy/paste into input boxes without triggering a keypress.

So onblur is probably somewhat more reliable (but is less immediate).

To truly make sure characters you don't want are not entered into input boxes (or textareas, etc.), I think you will need to

  1. check keypress (if you want to give immediate feedback) and
  2. also check onblur,
  3. as well as validating inputs on the server (which is the only real way to make sure nothing unwanted gets into your data).

The code samples in the other answers will work fine for doing the client-side checks (just don't rely only on checking keypress events), but as was pointed out in the accepted answer, a server-side check is really required.

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

I'm using this:

var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);

C/C++ Struct vs Class

C++ uses structs primarily for 1) backwards compatibility with C and 2) POD types. C structs do not have methods, inheritance or visibility.

Formatting struct timespec

One way to format it is:

printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec);

Automated testing for REST Api

One of the problems of doing automated testing for APIs is that many of the tools require you to have the API server up and running before you run your test suite. It can be a real advantage to have a unit testing framework that is capable of running and querying the APIs in a fully automated test environment.

An option that's good for APIs implemented with Node.JS / Express is to use mocha for automated testing. In addition to unit tests, its easy to write functional tests against the APIs, separated into different test suites. You can start up the API server automatically in the local test environment and set up a local test database. Using make, npm, and a build server, you can create a "make test" target and an incremental build that will run the entire test suite every time a piece of code is submitted to your repository. For the truly fastidious developer, it will even generate a nice HTML code-coverage report showing you which parts of your code base are covered by tests or not. If this sounds interesting, here's a blog post that provides all the technical details.

If you're not using node, then whatever the defacto unit testing framework for the language is (jUnit, cucumber/capybara, etc) - look at its support for spinning up servers in the local test environment and running the HTTP queries. If it's a large project, the effort to get automated API testing and continual integration working will pay off pretty quickly.

Hope that helps.

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You need to encode your parameter's values before concatenating them to URL.
Backslash \ is special character which have to be escaped as %5C

Escaping example:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is properly formatted url string.

Fastest way to count number of occurrences in a Python list

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

It's probably optimized heavily at the C level.

Edit: I randomly generated a large list.

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

Edit edit: This could be done with collections.Counter

a = Counter(your_list)
print a['1']

Using the same list in my last timing example

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.

Here is some profiling

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

How to insert a blob into a database using sql server management studio

There are two ways to SELECT a BLOB with TSQL:

SELECT * FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

As well as:

SELECT BulkColumn FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

Note the correlation name after the FROM clause, which is mandatory.

You can then this to INSERT by doing an INSERT SELECT.

You can also use the second version to do an UPDATE as I described in How To Update A BLOB In SQL SERVER Using TSQL .

Difference between fprintf, printf and sprintf?

printf

  1. printf is used to perform output on the screen.
  2. syntax = printf("control string ", argument );
  3. It is not associated with File input/output

fprintf

  1. The fprintf it used to perform write operation in the file pointed to by FILE handle.
  2. The syntax is fprintf (filename, "control string ", argument );
  3. It is associated with file input/output

Handling file renames in git

Just ran into this issue - if you updated a bunch of files and don't want to do git mv all of them this also works:

  1. Rename parent directory from /dir/RenamedFile.js to /whatever/RenamedFile.js.
  2. git add -A to stage that change
  3. Rename parent directory back to /dir/RenamedFile.js.
  4. git add -A again, will re-stage vs that change, forcing git to pick up the filename change.

How to update a value in a json file and save it through node.js

I would strongly recommend not to use synchronous (blocking) functions, as they hold other concurrent operations. Instead, use asynchronous fs.promises:

const fs = require('fs').promises

const setValue = (fn, value) => 
  fs.readFile(fn)
    .then(body => JSON.parse(body))
    .then(json => {
      // manipulate your data here
      json.value = value
      return json
    })
    .then(json => JSON.stringify(json))
    .then(body => fs.writeFile(fn, body))
    .catch(error => console.warn(error))

Remeber that setValue returns a pending promise, you'll need to use .then function or, within async functions, the await operator.

// await operator
await setValue('temp.json', 1)           // save "value": 1
await setValue('temp.json', 2)           // then "value": 2
await setValue('temp.json', 3)           // then "value": 3

// then-sequence
setValue('temp.json', 1)                 // save "value": 1
  .then(() => setValue('temp.json', 2))  // then save "value": 2
  .then(() => setValue('temp.json', 3))  // then save "value": 3

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

You can find and kill the running processes: ps aux | grep puma Then you can kill it with kill PID

IIS7 Permissions Overview - ApplicationPoolIdentity

On Windows Server 2008(r2) you can't assign an application pool identity to a folder through Properties->Security. You can do it through an admin command prompt using the following though:

icacls "c:\yourdirectory" /t /grant "IIS AppPool\DefaultAppPool":(R)

CSS: Position text in the middle of the page

Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.

HTML:

<h1>Hello world!</h1>

Javascript (jQuery):

$(document).ready(function(){
  $('h1').css({ 'width':'100%', 'text-align':'center' });
  var h1 = $('h1').height();
  var h = h1/2;
  var w1 = $(window).height();
  var w = w1/2;
  var m = w - h
  $('h1').css("margin-top",m + "px")
});

This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top of the h1. The beauty of this method is that it works on multiple-line h1s.

EDIT: I modified it so that it centered it every time the window is resized.

How to right align widget in horizontal linear layout Android?

Try to add empty View inside horizontal LinearLayout before element that you want to see right, e.g.:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1" />                

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

Flask example with POST

Here is the example in which you can easily find the way to use Post,GET method and use the same way to add other curd operations as well..

#libraries to include

import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')<br>
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
    def question():
    # request.args is to get urls arguments 


    if request.method == 'GET':
        start = request.args.get('start', default=0, type=int)
        limit_url = request.args.get('limit', default=20, type=int)
        questions = mongo.db.questions.find().limit(limit_url).skip(start);
        data = [doc for doc in questions]
        return jsonify(isError= False,
                    message= "Success",
                    statusCode= 200,
                    data= data), 200

# request.form to get form parameter

    if request.method == 'POST':
        average_time = request.form.get('average_time')
        choices = request.form.get('choices')
        created_by = request.form.get('created_by')
        difficulty_level = request.form.get('difficulty_level')
        question = request.form.get('question')
        topics = request.form.get('topics')

    ##Do something like insert in DB or Render somewhere etc. it's up to you....... :)

How to make GREP select only numeric values?

Don't use more commands than necessary, leave away tail, grep and cut. You can do this with only (a simple) awk

PS: giving a block-size en print only de persentage is a bit silly ;-) So leave also away the "-B MB"

df . |awk -F'[multiple field seperators]' '$NF=="Last field must be exactly --> mounted patition" {print $(NF-number from last field)}'

in your case, use:

df . |awk -F'[ %]' '$NF=="/" {print $(NF-2)}'

output: 81

If you want to show the percent symbol, you can leave the -F'[ %]' away and your print field will move 1 field further back

df . |awk '$NF=="/" {print $(NF-1)}'

output: 81%

Eclipse: How to build an executable jar with external jar?

Try the fat-jar extension. It will include all external jars inside the jar.

React.js inline style best practices

I prefer to use styled-components. It provide better solution for design.

import React, { Component, Fragment } from 'react'
import styled from 'styled-components';

const StyledDiv = styled.div`
    display: block;
    margin-left: auto;
    margin-right: auto;
    font-size:200; // here we can set static
    color: ${props => props.color} // set dynamic color by props
`;

export default class RenderHtml extends Component {
    render() {
        return (
            <Fragment>
                <StyledDiv color={'white'}>
                    Have a good and productive day!
                </StyledDiv>
            </Fragment>
        )
    }
}

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

matrix multiplication algorithm time complexity

Using linear algebra, there exist algorithms that achieve better complexity than the naive O(n3). Solvay Strassen algorithm achieves a complexity of O(n2.807) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7.

The fastest known matrix multiplication algorithm is Coppersmith-Winograd algorithm with a complexity of O(n2.3737). Unless the matrix is huge, these algorithms do not result in a vast difference in computation time. In practice, it is easier and faster to use parallel algorithms for matrix multiplication.

How to refresh or show immediately in datagridview after inserting?

Try refreshing the datagrid after each insert

datagridview1.update();
datagridview1.refresh();  

Hope this helps you!

MySQL default datetime through phpmyadmin

You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.

The only field you can use current_time on is a timestamp.

'this' vs $scope in AngularJS controllers

$scope has a different 'this' then the controller 'this'.Thus if you put a console.log(this) inside controller it gives you a object(controller) and this.addPane() adds addPane Method to the controller Object. But the $scope has different scope and all method in its scope need to be accesed by $scope.methodName(). this.methodName() inside controller means to add methos inside controller object.$scope.functionName() is in HTML and inside

$scope.functionName(){
    this.name="Name";
    //or
    $scope.myname="myname"//are same}

Paste this code in your editor and open console to see...

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>this $sope vs controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
    <script>
        var app=angular.module("myApp",[]);
app.controller("ctrlExample",function($scope){
          console.log("ctrl 'this'",this);
          //this(object) of controller different then $scope
          $scope.firstName="Andy";
          $scope.lastName="Bot";
          this.nickName="ABot";
          this.controllerMethod=function(){

            console.log("controllerMethod ",this);
          }
          $scope.show=function(){
              console.log("$scope 'this",this);
              //this of $scope
              $scope.message="Welcome User";
          }

        });
</script>
</head>
<body ng-app="myApp" >
<div ng-controller="ctrlExample">
       Comming From $SCOPE :{{firstName}}
       <br><br>
       Comming from $SCOPE:{{lastName}}
       <br><br>
       Should Come From Controller:{{nickName}}
       <p>
            Blank nickName is because nickName is attached to 
           'this' of controller.
       </p>

       <br><br>
       <button ng-click="controllerMethod()">Controller Method</button>

       <br><br>
       <button ng-click="show()">Show</button>
       <p>{{message}}</p>

   </div>

</body>
</html>

Jquery click not working with ipad

Thanks to the previous commenters I found all the following worked for me:

Either adding an onclick stub to the element

onclick="void(0);" 

or user a cursor pointer style

style="cursor:pointer;"

or as in my existing code my jquery code needed tap added

$(document).on('click tap','.ciAddLike',function(event)
{
    alert('like added!'); // stopped working in ios safari until tap added
});

I am adding a cross-reference back to the Apple Docs for those interested. See Apple Docs:Making Events Clickable

(I'm not sure exactly when my hybrid app stopped processing clicks but I seem to remember they worked iOS 7 and earlier.)

ASP.NET Core 1.0 on IIS error 502.5

I had this problem aswell (The error occurred both on VS 15 and 17). However on VS15 it returned a CONNECTION_REFUSED error and on VS17 it returned ASP.NET Core 1.0 on IIS error 502.5.

FIX

  1. Navigate to your project directory and locate the hidden folder .vs (it's located in the projects folder dir). (Remember to show hidden files/folders)

  2. Close VS

  3. Delete .vs-folder
  4. Start VS as admin (.vs-folder will be recreated by VS)

JavaScript: Get image dimensions

if you have image file from your input form. you can use like this

let images = new Image();
images.onload = () => {
 console.log("Image Size", images.width, images.height)
}
images.onerror = () => result(true);

let fileReader = new FileReader();
fileReader.onload = () => images.src = fileReader.result;
fileReader.onerror = () => result(false);
if (fileTarget) {
   fileReader.readAsDataURL(fileTarget);
}

git: patch does not apply

WARNING: This command can remove old lost commits PERMANENTLY. Make a copy of your entire repository before attempting this.

I have found this link

I have no idea why this works but I tried many work arounds and this is the only one that worked for me. In short, run the three commands below:

git fsck --full
git reflog expire --expire=now --all
git gc --prune=now

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Use for in

var obj = { "10":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0,
            "8":0, "9":0, "10":0, "11":0, "12":0 };

var objectToArray = function(obj) {
    var _arr = [];

    for (var key in obj) {
        _arr.push([key, obj[key]]);
    }
    return _arr;
}

console.log(objectToArray(obj));

How to do this in Laravel, subquery where in

Have a look at the advanced wheres documentation for Fluent: http://laravel.com/docs/queries#advanced-wheres

Here's an example of what you're trying to achieve:

DB::table('users')
    ->whereIn('id', function($query)
    {
        $query->select(DB::raw(1))
              ->from('orders')
              ->whereRaw('orders.user_id = users.id');
    })
    ->get();

This will produce:

select * from users where id in (
    select 1 from orders where orders.user_id = users.id
)

Get the (last part of) current directory name in C#

Try this:

String newString = "";
Sting oldString = "/Users/smcho/filegen_from_directory/AIRPassthrough";

int indexOfLastSlash = oldString.LastIndexOf('/', 0, oldString.length());

newString = oldString.subString(indexOfLastSlash, oldString.length());

Code may be off (I haven't tested it) but the idea should work

Sum values in a column based on date

Following up on Niketya's answer, there's a good explanation of Pivot Tables here: http://peltiertech.com/WordPress/grouping-by-date-in-a-pivot-table/

For Excel 2007 you'd create the Pivot Table, make your Date column a Row Label, your Amount column a value. You'd then right click on one of the row labels (ie a date), right click and select Group. You'd then get the option to group by day, month, etc.

Personally that's the way I'd go.

If you prefer formulae, Smandoli's answer would get you most of the way there. To be able to use Sumif by day, you'd add a column with a formula like:

=DATE(YEAR(C1), MONTH(C1), DAY(C1))

where column C contains your datetimes.

You can then use this in your sumif.

What's the best mock framework for Java?

The best solution to mocking is to have the machine do all the work with automated specification-based testing. For Java, see ScalaCheck and the Reductio framework included in the Functional Java library. With automated specification-based testing frameworks, you supply a specification of the method under test (a property about it that should be true) and the framework generates tests as well as mock objects, automatically.

For example, the following property tests the Math.sqrt method to see if the square root of any positive number n squared is equal to n.

val propSqrt = forAll { (n: Int) => (n >= 0) ==> scala.Math.sqrt(n*n) == n }

When you call propSqrt.check(), ScalaCheck generates hundreds of integers and checks your property for each, also automatically making sure that the edge cases are covered well.

Even though ScalaCheck is written in Scala, and requires the Scala Compiler, it's easy to test Java code with it. The Reductio framework in Functional Java is a pure Java implementation of the same concepts.

What is the effect of extern "C" in C++?

A function void f() compiled by a C compiler and a function with the same name void f() compiled by a C++ compiler are not the same function. If you wrote that function in C, and then you tried to call it from C++, then the linker would look for the C++ function and not find the C function.

extern "C" tells the C++ compiler that you have a function which was compiled by the C compiler. Once you tell it that it was compiled by the C compiler, the C++ compiler will know how to call it correctly.

It also allows the C++ compiler to compile a C++ function in such a way that the C compiler can call it. That function would officially be a C function, but since it is compiled by the C++ compiler, it can use all the C++ features and has all the C++ keywords.

Insert data to MySql DB and display if insertion is success or failure

if (mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error())) {
  echo 'Success';
} else {
  echo 'Fail';
} 

Although since you have or die(mysql_error()) it will show the mysql_error() on the screen when it fails. You should probably remove that if it isnt the desired result

How do I get the current location of an iframe?

HTA works like a normal windows application.
You write HTML code, and save it as an .hta file.

However, there are, at least, one drawback: The browser can't open an .hta file; it's handled as a normal .exe program. So, if you place a link to an .hta onto your web page, it will open a download dialog, asking of you want to open or save the HTA file. If its not a problem for you, you can click "Open" and it will open a new window (that have no toolbars, so no Back button, neither address bar, neither menubar).

I needed to do something very similar to what you want, but instead of iframes, I used a real frameset.
The main page need to be a .hta file; the other should be a normal .htm page (or .php or whatever).

Here's an example of a HTA page with 2 frames, where the top one have a button and a text field, that contains the second frame URL; the button updates the field:

frameset.hta

<html>
    <head>
        <title>HTA Example</title>
        <HTA:APPLICATION id="frames" border="thin" caption="yes" icon="http://www.google.com/favicon.ico" showintaskbar="yes" singleinstance="no" sysmenu="yes" navigable="yes" contextmenu="no" innerborder="no" scroll="auto" scrollflat="yes" selection="yes" windowstate="normal"></HTA:APPLICATION>
    </head>
    <frameset rows="60px, *">
        <frame src="topo.htm" name="topo" id="topo" application="yes" />
        <frame src="http://www.google.com" name="conteudo" id="conteudo" application="yes" />
    </frameset>
</html>
  • There's an HTA:APPLICATION tag that sets some properties to the file; it's good to have, but it isn't a must.
  • You NEED to place an application="yes" at the frames' tags. It says they belongs to the program too and should have access to all data (if you don't, the frames will still show the error you had before).

topo.htm

<html>
    <head>
        <title>Topo</title>
        <script type="text/javascript">
            function copia_url() {
                campo.value = parent.conteudo.location;
            }
        </script>
    </head>
    <body style="background: lightBlue;" onload="copia_url()">
        <input type="button" value="Copiar URL" onclick="copia_url()" />
        <input type="text" size="120" id="campo" />
    </body>
</html>
  • You should notice that I didn't used any getElement function to fetch the field; on HTA file, all elements that have an ID becomes instantly an object

I hope this help you, and others that get to this question. It solved my problem, that looks like to be the same as you have.

You can found more information here: http://www.irt.org/articles/js191/index.htm

Enjoy =]

How to use color picker (eye dropper)?

It is just called the eyedropper tool. There is no shortcut key for it that I'm aware of. The only way you can use it now is by clicking on the color picker box in styles sidebar and then clicking on the page as you have already been doing.

MySQL Stored procedure variables from SELECT statements

You simply need to enclose your SELECT statements in parentheses to indicate that they are subqueries:

SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);

Alternatively, you can use MySQL's SELECT ... INTO syntax. One advantage of this approach is that both cityLat and cityLng can be assigned from a single table-access:

SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;

However, the entire procedure can be replaced with a single self-joined SELECT statement:

SELECT   b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM     cities AS a, cities AS b
WHERE    a.id = cityID
ORDER BY dist
LIMIT    10;

Converting int to string in C

If you really want to use itoa, you need to include the standard library header.

#include <stdlib.h>

I also believe that if you're on Windows (using MSVC), then itoa is actually _itoa.

See http://msdn.microsoft.com/en-us/library/yakksftt(v=VS.100).aspx

Then again, since you're getting a message from collect2, you're likely running GCC on *nix.

How to define static property in TypeScript interface

Another option not mentioned here is defining variable with a type representing static interface and assigning to it class expression:

interface MyType {
    instanceMethod(): void;
}

interface MyTypeStatic {
    new(): MyType;
    staticMethod(): void;
}

// ok
const MyTypeClass: MyTypeStatic = class MyTypeClass {
    public static staticMethod() { }
    instanceMethod() { }
}

// error: 'instanceMethod' is missing
const MyTypeClass1: MyTypeStatic = class MyTypeClass {
    public static staticMethod() { }
}

// error: 'staticMethod' is missing
const MyTypeClass2: MyTypeStatic = class MyTypeClass {
    instanceMethod() { }
}

The effect is same as in answer with decorators, but without overhead of decorators

Playground

Relevant suggestion/discussion on GitHub

MySQL - SELECT * INTO OUTFILE LOCAL ?

Try setting path to /var/lib/mysql-files/filename.csv (MySQL 8). Determine what files directory is yours by typping SHOW VARIABLES LIKE "secure_file_priv"; in mysql client command line.

See answer about here: (...) --secure-file-priv in MySQL answered in 2015 by vhu user

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

jQuery .each() with input elements

You can use:

$(formId).serializeArray();

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

There are two things I learned from this:

  1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

  2. To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

I hope this helps someone else!

How to Use Order By for Multiple Columns in Laravel 4?

Use order by like this:

return User::orderBy('name', 'DESC')
    ->orderBy('surname', 'DESC')
    ->orderBy('email', 'DESC')
    ...
    ->get();

String representation of an Enum

I use a combination of several of the suggestions above, combined with some caching. Now, I got the idea from some code that I found somewhere on the net, but I can neither remember where I got it or find it. So if anyone ever finds something that looks similar please comment with the attribution.

Anyway, the usage involves the type converters, so if you are binding to the UI it 'just works'. You can extended with Jakub's pattern for quick code lookup by initializing from the type converter into the static methods.

The base usage would look like this

[TypeConverter(typeof(CustomEnumTypeConverter<MyEnum>))]
public enum MyEnum
{
    // The custom type converter will use the description attribute
    [Description("A custom description")]
    ValueWithCustomDescription,

   // This will be exposed exactly.
   Exact
}

The code for the custom enum type converter follows:

public class CustomEnumTypeConverter<T> : EnumConverter
    where T : struct
{
    private static readonly Dictionary<T,string> s_toString = 
      new Dictionary<T, string>();

    private static readonly Dictionary<string, T> s_toValue = 
      new Dictionary<string, T>();

    private static bool s_isInitialized;

    static CustomEnumTypeConverter()
    {
        System.Diagnostics.Debug.Assert(typeof(T).IsEnum,
          "The custom enum class must be used with an enum type.");
    }

    public CustomEnumTypeConverter() : base(typeof(T))
    {
        if (!s_isInitialized)
        {
            Initialize();
            s_isInitialized = true;
        }
    }

    protected void Initialize()
    {
        foreach (T item in Enum.GetValues(typeof(T)))
        {
            string description = GetDescription(item);
            s_toString[item] = description;
            s_toValue[description] = item;
        }
    }

    private static string GetDescription(T optionValue)
    {
        var optionDescription = optionValue.ToString();
        var optionInfo = typeof(T).GetField(optionDescription);
        if (Attribute.IsDefined(optionInfo, typeof(DescriptionAttribute)))
        {
            var attribute = 
              (DescriptionAttribute)Attribute.
                 GetCustomAttribute(optionInfo, typeof(DescriptionAttribute));
            return attribute.Description;
        }
        return optionDescription;
    }

    public override object ConvertTo(ITypeDescriptorContext context, 
       System.Globalization.CultureInfo culture, 
       object value, Type destinationType)
    {
        var optionValue = (T)value;

        if (destinationType == typeof(string) && 
            s_toString.ContainsKey(optionValue))
        {
            return s_toString[optionValue];
        }

        return base.ConvertTo(context, culture, value, destinationType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, 
       System.Globalization.CultureInfo culture, object value)
    {
        var stringValue = value as string;

        if (!string.IsNullOrEmpty(stringValue) && s_toValue.ContainsKey(stringValue))
        {
            return s_toValue[stringValue];
        }

        return base.ConvertFrom(context, culture, value);
    }
}

}

How to insert &nbsp; in XSLT

I was trying to display borders on an empty cell in an HTML table. My old trick of using non-breaking space in empty cells was not working from xslt. I used line break with the same effect. I mention this just in case the reason you were trying to use the non-breaking space was to give some content to an 'empty' table cell in order to turn on the cell borders.

<br/>

Modulo operation with negative numbers

I don't think there isn't any need to check if the number is negative.

A simple function to find the positive modulo would be this -

Edit: Assuming N > 0 and N + N - 1 <= INT_MAX

int modulo(int x,int N){
    return (x % N + N) %N;
}

This will work for both positive and negative values of x.

Original P.S: also as pointed out by @chux, If your x and N may reach something like INT_MAX-1 and INT_MAX respectively, just replace int with long long int.

And If they are crossing limits of long long as well (i.e. near LLONG_MAX), then you shall handle positive and negative cases separately as described in other answers here.

How can I access the MySQL command line with XAMPP for Windows?

You can access the MySQL command line with XAMPP for Windows

enter image description here

  1. click XAMPP icon to launch its cPanel

  2. click on Shell button

  3. Type this mysql -h localhost -u root and click enter

You should see all the command lines and what they do

Setting environment for using XAMPP for Windows.
Your PC c:\xampp

# mysql -h localhost - root

mysql  Ver 15.1 Distrib 10.1.19-MariaDB, for Win32 (AMD64)
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Usage: mysql [OPTIONS] [database]

Default options are read from the following files in the given order:
C:\WINDOWS\my.ini C:\WINDOWS\my.cnf C:\my.ini C:\my.cnf C:\xampp\mysql\my.ini C:\xampp\mysql\my.cnf C:\xampp\mysql\bin\my.ini C:\xampp\mysql\bin\my.cnf
The following groups are read: mysql client client-server client-mariadb
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.

  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --abort-source-on-error
Abort 'source filename' operations in case of errors
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash
                      No automatic rehashing. One has to use 'rehash' to get
                      table and field completion. This gives a quicker start of
                      mysql and disables rehashing on reconnect.
  --auto-vertical-output
                      Automatically switch to vertical output mode if the
                      result is wider than the terminal width.
  -B, --batch         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  --character-sets-dir=name
                      Directory for character set files.
  --column-type-info  Display column type information.
  -c, --comments      Preserve comments. Send comments to the server. The
                      default is --skip-comments (discard comments), enable
                      with --comments.
  -C, --compress      Use compression in server/client protocol.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       Check memory and open file usage at exit.
  -T, --debug-info    Print some debug info at exit.
  -D, --database=name Database to use.
  --default-character-set=name
                      Set the default character set.
  --delimiter=name    Delimiter to be used.
  -e, --execute=name  Execute command and quit. (Disables --force and history
                      file.)
  -E, --vertical      Print the output of a query (rows) vertically.
  -f, --force         Continue even if we get an SQL error. Sets
                      abort-source-on-error to 0
  -G, --named-commands
                      Enable named commands. Named commands mean this program's
                      internal commands; see mysql> help . When enabled, the
                      named commands can be used from any line of the query,
                      otherwise only from the first line, before an enter.
                      Disable with --disable-named-commands. This option is
                      disabled by default.
  -i, --ignore-spaces Ignore space after function names.
  --init-command=name SQL Command to execute when connecting to MySQL server.
                      Will automatically be re-executed when reconnecting.
  --local-infile      Enable/disable LOAD DATA LOCAL INFILE.
  -b, --no-beep       Turn off beep on error.
  -h, --host=name     Connect to host.
  -H, --html          Produce HTML output.
  -X, --xml           Produce XML output.
  --line-numbers      Write line numbers for errors.
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers
                      Don't write line number for errors.
  -n, --unbuffered    Flush buffer after each query.
  --column-names      Write column names in results.
                      (Defaults to on; use --skip-column-names to disable.)
  -N, --skip-column-names
                      Don't write column names in results.
  --sigint-ignore     Ignore SIGINT (CTRL-C).
  -o, --one-database  Ignore statements except those that occur while the
                      default database is the one named at the command line.
  -p, --password[=name]
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -W, --pipe          Use named pipes to connect to server.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --progress-reports  Get progress reports for long running commands (like
                      ALTER TABLE)
                      (Defaults to on; use --skip-progress-reports to disable.)
  --prompt=name       Set the mysql prompt to this value.
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -q, --quick         Don't cache result, print it row by row. This may slow
                      down the server if the output is suspended. Doesn't use
                      history file.
  -r, --raw           Write fields without conversion. Used with --batch.
  --reconnect         Reconnect if the connection is lost. Disable with
                      --disable-reconnect. This option is enabled by default.
                      (Defaults to on; use --skip-reconnect to disable.)
  -s, --silent        Be more silent. Print results with a tab as separator,
                      each row on new line.
  --shared-memory-base-name=name
                      Base name of shared memory.
  -S, --socket=name   The socket file to use for connection.
  --ssl               Enable SSL for connection (automatically enabled with
                      other flags).
  --ssl-ca=name       CA file in PEM format (check OpenSSL docs, implies
                      --ssl).
  --ssl-capath=name   CA directory (check OpenSSL docs, implies --ssl).
  --ssl-cert=name     X509 cert in PEM format (implies --ssl).
  --ssl-cipher=name   SSL cipher to use (implies --ssl).
  --ssl-key=name      X509 key in PEM format (implies --ssl).
  --ssl-crl=name      Certificate revocation list (implies --ssl).
  --ssl-crlpath=name  Certificate revocation list path (implies --ssl).
  --ssl-verify-server-cert
                      Verify server's "Common Name" in its cert against
                      hostname used when connecting. This option is disabled by
                      default.
  -t, --table         Output in table format.
  --tee=name          Append everything into outfile. See interactive help (\h)
                      also. Does not work in batch mode. Disable with
                      --disable-tee. This option is disabled by default.
  -u, --user=name     User for login if not current user.
  -U, --safe-updates  Only allow UPDATE and DELETE that uses keys.
  -U, --i-am-a-dummy  Synonym for option --safe-updates, -U.
  -v, --verbose       Write more. (-v -v -v gives the table output format).
  -V, --version       Output version information and exit.
  -w, --wait          Wait and retry if connection is down.
  --connect-timeout=# Number of seconds before connection timeout.
  --max-allowed-packet=#
                      The maximum packet length to send to or receive from
                      server.
  --net-buffer-length=#
                      The buffer size for TCP/IP and socket communication.
  --select-limit=#    Automatic limit for SELECT when using --safe-updates.
  --max-join-size=#   Automatic limit for rows in a join when using
                      --safe-updates.
  --secure-auth       Refuse client connecting to server if it uses old
                      (pre-4.1.1) protocol.
  --server-arg=name   Send embedded server this as a parameter.
  --show-warnings     Show warnings after every statement.
  --plugin-dir=name   Directory for client-side plugins.
  --default-auth=name Default authentication client-side plugin to use.
  --binary-mode       By default, ASCII '\0' is disallowed and '\r\n' is
                      translated to '\n'. This switch turns off both features,
                      and also turns off parsing of all clientcommands except
                      \C and DELIMITER, in non-interactive mode (for input
                      piped to mysql or loaded using the 'source' command).
                      This is necessary when processing output from mysqlbinlog
                      that may contain blobs.

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- ----------------------------------------
abort-source-on-error             FALSE
auto-rehash                       FALSE
auto-vertical-output              FALSE
character-sets-dir                (No default value)
column-type-info                  FALSE
comments                          FALSE
compress                          FALSE
debug-check                       FALSE
debug-info                        FALSE
database                          (No default value)
default-character-set             auto
delimiter                         ;
vertical                          FALSE
force                             FALSE
named-commands                    FALSE
ignore-spaces                     FALSE
init-command                      (No default value)
local-infile                      FALSE
no-beep                           FALSE
host                              localhost
html                              FALSE
xml                               FALSE
line-numbers                      TRUE
unbuffered                        FALSE
column-names                      TRUE
sigint-ignore                     FALSE
port                              3306
progress-reports                  TRUE
prompt                            \N [\d]>
quick                             FALSE
raw                               FALSE
reconnect                         TRUE
shared-memory-base-name           (No default value)
socket                            C:/xampp/mysql/mysql.sock
ssl                               FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
ssl-verify-server-cert            FALSE
table                             FALSE
user                              (No default value)
safe-updates                      FALSE
i-am-a-dummy                      FALSE
connect-timeout                   0
max-allowed-packet                16777216
net-buffer-length                 16384
select-limit                      1000
max-join-size                     1000000
secure-auth                       FALSE
show-warnings                     FALSE
plugin-dir                        (No default value)
default-auth                      (No default value)
binary-mode                       FALSE

What does the symbol \0 mean in a string-literal?

char str[]= "Hello\0";

That would be 7 bytes.

In memory it'd be:

48 65 6C 6C 6F 00 00
H  e  l  l  o  \0 \0

Edit:

  • What does the \0 symbol mean in a C string?
    It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

  • What is the length of str array? (Answered before the edit part)
    7

  • and with how much 0s it is ending?
    You array has two "spaces" with zero; str[5]=str[6]='\0'=0

Extra example:
Let's assume you have a function that prints the content of that text array. You could define it as:

char str[40];

Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

So you print that char array. And then you want a new message. Let's say just "Hello"

48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

scp with port number specified

Unlike ssh, scp uses the uppercase P switch to set the port instead of the lowercase p:

scp -P 80 ... # Use port 80 to bypass the firewall, instead of the scp default

The lowercase p switch is used with scp for the preservation of times and modes.

Here is an excerpt from scp's man page with all of the details concerning the two switches, as well as an explanation of why uppercase P was chosen for scp:

-P port   Specifies the port to connect to on the remote host. Note that this option is written with a capital 'P', because -p is already reserved for preserving the times and modes of the file in rcp(1).

-p           Preserves modification times, access times, and modes from the original file.

Update and aside to address one of the (heavily upvoted) comments:

With regard to Abdull's comment about scp option order, what he suggests:

scp -P80 -r some_directory -P 80 ...

..., intersperses options and parameters. getopt(1) clearly defines that parameters must come after options and not be interspersed with them:

The parameters getopt is called with can be divided into two parts: options which modify the way getopt will do the parsing (the options and the optstring in the SYNOPSIS), and the parameters which are to be parsed (parameters in the SYNOPSIS). The second part will start at the first non-option parameter that is not an option argument, or after the first occurrence of '--'. If no '-o' or '--options' option is found in the first part, the first parameter of the second part is used as the short options string.

Since the -r command line option takes no further arguments, some_directory is "the first non-option parameter that is not an option argument." Therefore, as clearly spelled out in the getopt(1) man page, all succeeding command line arguments that follow it (i.e., -P 80 ...) are assumed to be non-options (and non-option arguments).

So, in effect, this is how getopt(1) sees the example presented with the end of the options and the beginning of the parameters demarcated by succeeding text bing in gray:

scp -P80 -r some_directory -P 80 ...

This has nothing to do with scp behavior and everything to do with how POSIX standard applications parse command line options using the getopt(3) set of C functions.

For more details with regard to command line ordering and processing, please read the getopt(1) manpage using:

man 1 getopt

Rename all files in directory from $filename_h to $filename_half?

Another approach can be manually using batch rename option

Right click on the file -> File Custom Commands -> Batch Rename and you can replace h. with half.

This will work for linux based gui using WinSCP etc

Android replace the current fragment with another fragment

it's very simple how to replace with Fragment.

DataFromDb changeActivity = new DataFromDb();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.changeFrg, changeActivity);
    transaction.commit();

How to clear browsing history using JavaScript?

No,that would be a security issue.


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

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

similar behavior as an HTTP redirect

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

Are the shift operators (<<, >>) arithmetic or logical in C?

According to K&R 2nd edition the results are implementation-dependent for right shifts of signed values.

Wikipedia says that C/C++ 'usually' implements an arithmetic shift on signed values.

Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift.

php: Get html source code with cURL

Try the following:

$ch = curl_init("http://www.example-webpage.com/file.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);

I would only recommend this for small files. Big files are read as a whole and are likely to produce a memory error.


EDIT: after some discussion in the comments we found out that the problem was that the server couldn't resolve the host name and the page was in addition a HTTPS resource so here comes your temporary solution (until your server admin fixes the name resolving).

what i did is just pinging graph.facebook.com to see the IP address, replace the host name with the IP address and instead specify the header manually. This however renders the SSL certificate invalid so we have to suppress peer verification.

//$url = "https://graph.facebook.com/19165649929?fields=name";
$url = "https://66.220.146.224/19165649929?fields=name";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com'));
$output = curl_exec($ch);
curl_close($ch); 

Keep in mind that the IP address might change and this is an error source. you should also do some error handling using curl_error();.

SQL use CASE statement in WHERE IN clause

 select  * from Tran_LibraryBooksTrans LBT  left join
 Tran_LibraryIssuedBooks LIB ON   case WHEN LBT.IssuedTo='SN' AND
 LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when LBT.IssuedTo='SM'
 AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 WHEN
 LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
 ELSE 0 END`enter code here`select  * from Tran_LibraryBooksTrans LBT 
 left join Tran_LibraryIssuedBooks LIB ON   case WHEN LBT.IssuedTo='SN'
 AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1 when
 LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
 WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN
 1 ELSE 0 END

How do I allow HTTPS for Apache on localhost?

Running Apache on Windows 10 here. I couldn't get Chrome to trust the certificate made in the top answer by Simon. What I ended up doing was using PowerShell to generate a self signed certificate.

Step 1 - Generate Self-Signed certificate

In PowerShell
New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" 1

Step 2 - Configure and Export Certificate

Type Certificate into the Windows search bar, click the Manage Computer Certificates control panel item that is suggested.

From the Certificate Management program that comes up (certlm), you should now see a localhost key under Personal >> Certificates.

I copied this certificate into Trusted Root Certification Authorities. I'll be honest in that I'm not sure if that's necessary.

Selecting the newly copied certificate, double click on it (the localhost certificate). From the Certificate modal, click the Details tab, then the Copy to File... button.

This will bring up and Export Wizard, I chose to export the private key, click next. I also chose to Export all extended properties (again, I'm not certain if that was necessary). I chose to use a simple password (pass) and the default encryption. Choose a folder to export to and name the file. You can always move and rename the file if necessary. For simplicity's sake let's copy it to your conf folder under your Apache installation (In my case: C:\apache\conf) and name the file myCert (the resulting file will be a .pfx file)

Step 3 - Convert .pfx file for use with Apache

From here I basically followed the tutorial here, but I'll add instructions here (tweaked for our settings) in case that site goes down.

Open your Command Prompt in the /apache/conf/ folder
Run the following commands: Note: This assumes you have openssl.exe in the bin folder in the apache root folder (this should be standard/default)

..\bin\openssl pkcs12 -in myCert.pfx -nocerts -out privateKey.pem

This will prompt you for a password, enter what you input for Step 2 when you exported the .pfx file. In my case, this is pass. I entered the same password for the PEM phrase and again to verify. This will create a new file called privateKey.pem in your conf folder.

Then, run

..\bin\openssl rsa -in privateKey.pem -out private.pem

Again you will be prompted for a password (Enter pass phrase for privateKey.pem:), use the password you set for privateKey.pem. (In my case, pass)
You should see a message that says writing RSA key and a new file called private.pem in your conf/ folder. This will be your SSLCertificateKeyFile.

Now to generate the corresponding Server Certificate. Run:

..\bin\openssl pkcs12 -in myCert.pfx -clcerts -nokeys -out EntrustCert.pem

This will prompt you for a password, enter what you input for Step 2 when you exported the .pfx file. Enter it and you will now have a file called EntrustCert.pem in your conf folder. This is your SSLCertificateFile

Step 4 - Configure httpd.conf

Use the new files created as you server's key and certificate. Be sure to change your document root to where your files are!

ServerName localhost:80
Protocols h2 h2c http/1.1
<Directory />
    Options FollowSymLinks
    AllowOverride All
</Directory>

<VirtualHost _default_:443>
  ServerName localhost:443
  DocumentRoot ${SRVROOT}/htdocs/MYSITE
  SSLEngine on
  SSLCertificateFile "${SRVROOT}/conf/EntrustCert.pem"
  SSLCertificateKeyFile "${SRVROOT}/conf/private.pem"
</VirtualHost>

Also in httpd.conf:

  • Make sure LoadModule ssl_module modules/mod_ssl.so is uncommented (no # in front)
  • Uncomment LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
  • Uncomment LoadModule http2_module modules/mod_http2.so
  • Uncomment Include conf/extra/httpd-ssl.conf (NOTE: Ensure that's where the file is!)

I also have curl and open ssl libraries included:

# load curl and open ssl libraries
LoadFile "C:\php\libeay32.dll"
LoadFile "C:\php\ssleay32.dll"
LoadFile "C:\php\libssh2.dll"

These modules shouldn't be necessary, but I'll note that I have them enabled:
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule filter_module modules/mod_filter.so
LoadModule deflate_module modules/mod_deflate.so

Step 5 - Config httpd-ssl.conf

In the extra/ folder in the conf/ folder you should see a file called httpd-ssl.conf.

5a. Change the DocumentRoot - Change the DocumentRoot from the default to the directory where your files are.

5b. Change the ServerName - Change the ServerName from the default (something like www.example.com:443) to localhost:443

5c. Change the SSLCertificateFile
Change the SSLCertificateFile from the default (${SRVROOT}/conf/server.crt) to ${SRVROOT}/conf/EntrustCert.pem

5c. Change the SSLCertificateKeyFile
Change the SSLCertificateKeyFile from the default (${SRVROOT}/conf/server.key) to ${SRVROOT}/conf/private.pem

All together, in the <VirtualHost _default_:443> tag.

#   General setup for the virtual host
DocumentRoot "${SRVROOT}/htdocs/MYSITE"
ServerName localhost:443
ServerAdmin [email protected]
ErrorLog "${SRVROOT}/logs/error.log"
TransferLog "${SRVROOT}/logs/access.log"

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
SSLEngine on

#   Server Certificate:
#   Point SSLCertificateFile at a PEM encoded certificate.  If
#   the certificate is encrypted, then you will be prompted for a
#   pass phrase.  Note that a kill -HUP will prompt again.  Keep
#   in mind that if you have both an RSA and a DSA certificate you
#   can configure both in parallel (to also allow the use of DSA
#   ciphers, etc.)
#   Some ECC cipher suites (http://www.ietf.org/rfc/rfc4492.txt)
#   require an ECC certificate which can also be configured in
#   parallel.
SSLCertificateFile "${SRVROOT}/conf/EntrustCert.pem"
#SSLCertificateFile "${SRVROOT}/conf/server-dsa.crt"
#SSLCertificateFile "${SRVROOT}/conf/server-ecc.crt"

#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)
#   ECC keys, when in use, can also be configured in parallel
SSLCertificateKeyFile "${SRVROOT}/conf/private.pem"
#SSLCertificateKeyFile "${SRVROOT}/conf/server-dsa.key"
#SSLCertificateKeyFile "${SRVROOT}/conf/server-ecc.key"

Restart Apache

After making these changes you should be able to restart Apache and navigate to https://localhost without a security warning and a little padlock!

Secured localhost

I hope this helps someone!

Sources:
1.) Auri Rahimzadeh's answer on creating a self-signed certificate
2.) Entrust Datacard - How do I convert a .pfx to be used with an Apache server?

Flutter: how to make a TextField with HintText but no Underline?

I found no other answer gives a border radius, you can simply do it like this, no nested Container

  TextField(
    decoration: InputDecoration(
      border: OutlineInputBorder(
        borderSide: BorderSide.none,
        borderRadius: BorderRadius.circular(20),
      ),
    ),
  );

How to find out the MySQL root password

Unless the package manager requests you to type the root password during installation, the default root password is the empty string. To connect to freshly installed server, type:

shell> mysql -u root --password=
mysql>

To change the password, get back the unix shell and type:

shell> mysqladmin -u root --password= password root

The new password is 'root'. Now connect to the server:

shell> mysql -u root --password=
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Oops, the password has changed. Use the new one, root:

shell> mysql -u root --password=root
...
blah, blah, blah : mysql welcome banner
...
mysql> 

Bingo! New do something interesting

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

Maurycy

How to change shape color dynamically?

The simplest way to fill the shape with the Radius is:

XML:

<TextView
    android:id="@+id/textView"
    android:background="@drawable/test"
    android:layout_height="45dp"
    android:layout_width="100dp"
    android:text="Moderate"/>

Java:

(textView.getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN);

How can I remove the first line of a text file using bash/sed script?

No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).

But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.

For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.

Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.

You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.

Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.

It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.

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

How to save local data in a Swift app?

Using NSCoding and NSKeyedArchiver is another great option for data that's too complex for NSUserDefaults, but for which CoreData would be overkill. It also gives you the opportunity to manage the file structure more explicitly, which is great if you want to use encryption.

Limit number of characters allowed in form input text field

<input type="text" maxlength="5">

the maximum amount of letters that can be in the input is 5.

How to prune local tracking branches that do not exist on remote anymore

The Powershell Version of git branch --merged master | grep -v '^[ *]*master$' | xargs git branch -d

git branch --merged master | %{ if($_ -notmatch '\*.*master'){ git branch -d "$($_.Trim())" }}

This will remove any local branches that have been merged into master, while you are on the master branch.

git checkout master to switch.

Stop Excel from automatically converting certain text values to dates

While creating the string to be written to my CSV file in C# I had to format it this way:

"=\"" + myVariable + "\""

Add one day to date in javascript

If you don't mind using a library, DateJS (https://github.com/abritinthebay/datejs/) would make this fairly easy. You would probably be better off with one of the answers using vanilla JavaScript however, unless you're going to take advantage of some other DateJS features like parsing of unusually-formatted dates.

If you're using DateJS a line like this should do the trick:

Date.parse(startdate).add(1).days();

You could also use MomentJS which has similar features (http://momentjs.com/), however I'm not as familiar with it.

How to create an android app using HTML 5

When people talk about HTML5 applications they're most likely talking about writing just a simple web page or embedding a web page into their app (which will essentially provide the user interface). For the later there are different frameworks available, e.g. PhoneGap. These are used to provide more than the default browser features (e.g. multi touch) as well as allowing the app to run seamingly "standalone" and without the browser's navigation bars etc.

How do I get JSON data from RESTful service using Python?

Something like this should work unless I'm missing the point:

import json
import urllib2
json.load(urllib2.urlopen("url"))

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

Can't you just change working directory within the python script using os.chdir(target)? I agree, I can't see any way of doing it from the jar command itself.

If you don't want to permanently change directory, then store the current directory (using os.getcwd())in a variable and change back afterwards.

Java: Reading integers from a file into an array

You must have an empty line in your file.

You may want to wrap your parseInt calls in a "try" block:

try {
  tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
  continue;
}

Or simply check for empty strings before parsing:

if (s.length() == 0) 
  continue;

Note that by initializing your index variable i inside the loop, it is always 0. You should move the declaration before the while loop. (Or make it part of a for loop.)

How can I close a browser window without receiving the "Do you want to close this window" prompt?

Because of the security enhancements in IE, you can't close a window unless it is opened by a script. So the way around this will be to let the browser think that this page is opened using a script, and then to close the window. Below is the implementation.

Try this, it works like a charm!
javascript close current window without prompt IE

<script type="text/javascript">
function closeWP() {
 var Browser = navigator.appName;
 var indexB = Browser.indexOf('Explorer');

 if (indexB > 0) {
    var indexV = navigator.userAgent.indexOf('MSIE') + 5;
    var Version = navigator.userAgent.substring(indexV, indexV + 1);

    if (Version >= 7) {
        window.open('', '_self', '');
        window.close();
    }
    else if (Version == 6) {
        window.opener = null;
        window.close();
    }
    else {
        window.opener = '';
        window.close();
    }

 }
else {
    window.close();
 }
}
</script>

javascript close current window without prompt IE

How to show an alert box in PHP?

use this code

echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';

The problem was:

  1. you missed "
  2. It should be alert not alery

Simple Popup by using Angular JS

Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.

Created an angular directive called modal and used in html. Explanation:-

HTML

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>

On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.

JS

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

UPDATE

<!doctype html>
<html ng-app="mymodal">


<body>

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <!-- Scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <!-- App -->
    <script>
        var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
          scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

    </script>
</body>
</html>

UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is

<modal>

Other values are 'A' for attribute

<div modal>

'C' for class (not preferable in our case because modal is already a class in bootstrap.css)

<div class="modal">

How to read keyboard-input?

It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct:

nb = input('Choose a number: ')

The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input:

nb = raw_input('Choose a number: ')

If you want to convert that to a number, then you should try:

number = int(nb)

... though you need to take into account that this can raise an exception:

try:
    number = int(nb)
except ValueError:
    print("Invalid number")

And if you want to print the number using formatting, in Python 3 str.format() is recommended:

print("Number: {0}\n".format(number))

Instead of:

print('Number %s \n' % (nb))

But both options (str.format() and %) do work in both Python 2.7 and Python 3.

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

Delete empty lines using sed

I believe this is the easiest and fastest one:

cat file.txt | grep .

If you need to ignore all white-space lines as well then try this:

cat file.txt | grep '\S'

Example:

s="\
\
a\
 b\
\
Below is TAB:\
    \
Below is space:\
 \
c\
\
"; echo "$s" | grep . | wc -l; echo "$s" | grep '\S' | wc -l

outputs

7
5

Remove .php extension with .htaccess

To remove the .php extension from a PHP file for example yoursite.com/about.php to yoursite.com/about Follow these step . Open .htaccess(create new one if not exists) file from root of your website, and add the following code.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

To remove the .html extension from a html file for example yoursite.com/about.html to yoursite.com/about Follow these step .

Open .htaccess(create new one if not exists) file from root of your website, and add the following code.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Reference: How to Remove php Extention from URL

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

fig.add_subplot(ROW,COLUMN,POSITION)

  • ROW=number of rows
  • COLUMN=number of columns
  • POSITION= position of the graph you are plotting

Examples

`fig.add_subplot(111)` #There is only one subplot or graph  
`fig.add_subplot(211)`  *and*  `fig.add_subplot(212)` 

There are total 2 rows,1 column therefore 2 subgraphs can be plotted. Its location is 1st. There are total 2 rows,1 column therefore 2 subgraphs can be plotted.Its location is 2nd

How to define an enumerated type (enum) in C?

It's worth pointing out that you don't need a typedef. You can just do it like the following

enum strategy { RANDOM, IMMEDIATE, SEARCH };
enum strategy my_strategy = IMMEDIATE;

It's a style question whether you prefer typedef. Without it, if you want to refer to the enumeration type, you need to use enum strategy. With it, you can just say strategy.

Both ways have their pro and cons. The one is more wordy, but keeps type identifiers into the tag-namespace where they won't conflict with ordinary identifiers (think of struct stat and the stat function: these don't conflict either), and where you immediately see that it's a type. The other is shorter, but brings type identifiers into the ordinary namespace.

What is a regular expression which will match a valid domain name without a subdomain?

The following regex extracts the sub, root and tld of a given domain:

^(?<domain>(?<domain_sub>(?:[^\/\"\]:\.\s\|\-][^\/\"\]:\.\s\|]*?\.)*?)(?<domain_root>[^\/\"\]:\s\.\|\n]+\.(?<domain_tld>(?:xn--)?[\w-]{2,7}(?:\.[a-zA-Z-]{2,3})*)))$

Tested for the following domains:

* stack.com
* sta-ck.com
* sta---ck.com
* 9sta--ck.com
* sta--ck9.com
* stack99.com
* 99stack.com
* sta99ck.com
* google.com.uk
* google.co.in

* google.com
* maselkowski.pl
* maselkowski.pl
* m.maselkowski.pl
* www.maselkowski.pl.com
* xn--masekowski-d0b.pl
* xn--fiqa61au8b7zsevnm8ak20mc4a87e.xn--fiqs8s

* xn--stackoverflow.com
* stackoverflow.xn--com
* stackoverflow.co.uk

How do I minimize the command prompt from my bat file

One way to 'minimise' the cmd window is to reduce the size of the console using something like...

echo DO NOT CLOSE THIS WINDOW
MODE CON COLS=30 LINES=2

You can reduce the COLS to about 18 and the LINES to 1 if you wish. The advantage is that it works under WinPE, 32-bit or 64-bit, and does not require any 3rd party utility.

How to create a directive with a dynamic template in AngularJS?

Had a similar need. $compile does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)

http://jsbin.com/ebuhuv/7/edit - my exploration test.

One thing to note (per my example), one of my requirements was that the template would change based on a type attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.

Date Difference in php on days?

I would recommend to use date->diff function, as in example below:

   $dStart = new DateTime('2012-07-26');
   $dEnd  = new DateTime('2012-08-26');
   $dDiff = $dStart->diff($dEnd);
   echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater

see http://www.php.net/manual/en/datetime.diff.php

ggplot2 legend to bottom and horizontal

Here is how to create the desired outcome:

library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() + 
  geom_tile(aes(X1, X2, fill = value)) + 
  scale_fill_continuous(guide = guide_legend()) +
  theme(legend.position="bottom",
        legend.spacing.x = unit(0, 'cm'))+
  guides(fill = guide_legend(label.position = "bottom"))

Created on 2019-12-07 by the reprex package (v0.3.0)


Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.

Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

Created on 2019-02-28 by the reprex package (v0.2.1)

How to pass params with history.push/Link/Redirect in react-router v4?

First of all, you need not do var r = this; as this in if statement refers to the context of the callback itself which since you are using arrow function refers to the React component context.

According to the docs:

history objects typically have the following properties and methods:

  • length - (number) The number of entries in the history stack
  • action - (string) The current action (PUSH, REPLACE, or POP)
  • location - (object) The current location. May have the following properties:

    • pathname - (string) The path of the URL
    • search - (string) The URL query string
    • hash - (string) The URL hash fragment
    • state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation

So while navigating you can pass props to the history object like

this.props.history.push({
  pathname: '/template',
  search: '?query=abc',
  state: { detail: response.data }
})

or similarly for the Link component or the Redirect component

<Link to={{
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    }}> My Link </Link>

and then in the component which is rendered with /template route, you can access the props passed like

this.props.location.state.detail

Also keep in mind that, when using history or location objects from props you need to connect the component with withRouter.

As per the Docs:

withRouter

You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.